// --- ADX filter inputs ---
input int adxPeriod = 14; // ADX period
input double adxThreshold = 25.0; // ADX minimum threshold to allow trading
input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15; // ADX timeframe to use for filtering
// --- Losing streak inputs ---
input int maxLosingStreak = 3; // Max consecutive losing trades allowed
// --- POST-CLOSE COOLDOWN ---
input int postCloseCooldownSeconds = 180; // Cooldown seconds after a position closes before new trades allowed.
CTrade trade;
int ma_handle = INVALID_HANDLE;
int ma_handle2 = INVALID_HANDLE; // Medium-term MA handle
int ma_handle3 = INVALID_HANDLE; // Long-term MA handle
int atr_handle = INVALID_HANDLE;
int adx_handle = INVALID_HANDLE; // ADX handle
Assistant
User
what are enter trade conditions in normal and reverse mode?
Assistant
User
reverse mode, ask > lastSwingHigh Downtrend (is_downtrend) No sell positions open and down fair value gap then sell
bid < lastSwingLow Uptrend (is_uptrend) No buy positions open and up fair value gap then buy
Assistant
User
fvg are created from 3 candles
Assistant
User
FVGs are typically identified within a three-candle pattern on a price chart. The middle candle's price range (especially the wick) doesn't overlap with the wicks of the first and third candles, creating a noticeable gap. In a bullish FVG, the first candle's high and the third candle's low do not overlap, creating a gap above the first candle and below the third candle. Conversely, in a bearish FVG, the first candle's low and the third candle's high do not overlap, creating a gap below the first candle and above the third candle.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// *** Cooldown globals ***
datetime lastTradeCandleTime = 0; // last candle time when trade opened
ENUM_TIMEFRAMES cooldownTimeframe = swingTF; // timeframe for candle cooldown
datetime lastTradeOpenTime = 0; // last trade open timestamp
int tradeIntervalSeconds = 180; // min seconds between trades
if(!OrderSend(req,res))
PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
else if(res.retcode != TRADE_RETCODE_DONE)
PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
else
PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
Your code looks solid and well-structured. It includes various advanced features — multi-timeframe moving averages, ADX filtering, losing streak logic, cooldowns, floating risk cap, and trailing stops with multiple modes.
What you have:
Proper initialization and cleanup of indicator handles
Managing daily equity reset and losing streak reset at midnight
Checking ADX filter and max losing streak before opening trades
Cooldown logic with both candle-based and minimum time intervals
Floating risk cap: closes positions losing more than allowed % of balance
You are using HistorySelect followed by scanning HistoryDealsTotal to find closed deals.
Make sure your terminal’s history depth is sufficient to cover these periods.
Keep HistorySelect calls light, ideally only once per tick or fewer.
2. OnTick heavy logic
Your OnTick method is doing quite a bit — indicator buffer copying, deal history scanning, managing trailing stops — on every tick.
For efficiency, consider running some parts (e.g., losing streak update) only once per candle or at intervals (use datetime check).
You might also run trailing stop updates on timer events or at longer intervals.
3. Trailing Stop - OrderSend error handling
Most OrderSend calls print error on failure, which is good.
Check for GetLastError() == ERR_NO_ERROR (0) after every trade call to confirm reason for failure.
Some errors require retry or alternative approach (e.g., retcode retests).
4. ADX Indicator buffer index
You copy buffer 0 assuming it's ADX value. For ADX you get 3 lines:
Buffer 0 = ADX line
Buffer 1 = +DI
Buffer 2 = -DI
Double-check if buffer 0 really corresponds to ADX; it usually does.
5. Trailing Stop Hybrid logic
The hybrid combines MS and ATR trailing stop levels logically.
The logic to pick max/min of MS and ATR levels (for buy/sell) is correct for tightening stops.
Minor code style suggestions:
Use const or static correctly for constant variables or those that persist state.
Use ENUM_POSITION_TYPE instead of casting long — already done and good.
Consider separating some logic into functions to improve readability.
Summary
Your Break of Structure EA is advanced and seems complete:
Proper risk management with fixed and floating limits
Trend filtering by MAs and ADX filter
Trade cooldowns and max concurrent trades
Smart trailing stop variations
Losing streak avoidance
If you want, I can help you add features or optimize parts of it further. Otherwise, it looks ready to test and run. Just verify it on demo accounts first.
If you want me to review or adjust any specific part, just ask!
Certainly! Let me explain the trade entry conditions for both normal mode (when enableReverseEntries == false) and reverse mode (when enableReverseEntries == true) as implemented in your EA's OnTick() function.
Variables involved in entry decision:
lastSwingHigh: last swing high price on swingTF
lastSwingLow: last swing low price on swingTF
MA1, MA2, MA3: three EMAs with different periods and timeframes
ask and bid: current ask and bid prices of symbol
is_uptrend: defined as (MA1 > MA2) && (MA2 > MA3) && (ask > MA2)
is_downtrend: defined as (MA1 < MA2) && (MA2 < MA3) && (ask < MA2)
1. Normal mode (enableReverseEntries == false) trades:
Buy entry:
Condition:
ask > lastSwingHigh → Price breaks above last swing high
is_uptrend is true → the trend is up (EMA 50 > EMA 100 > EMA 200 and price is above EMA100)
No open buy position exists already (!IsPositionOpen(POSITION_TYPE_BUY))
Action: Place a Buy order with:
SL = ask - sl_dist
TP = ask + tp_dist
Sell entry:
Condition:
bid < lastSwingLow → Price breaks below last swing low
is_downtrend is true → the trend is down (EMA 50 < EMA 100 < EMA 200 and price below EMA100)
No open sell position exists already (!IsPositionOpen(POSITION_TYPE_SELL))
This is a contrarian or counter-trend mode that deliberately enters opposite trades relative to the trend direction.
Sell entry (reverse):
Condition:
ask > lastSwingHigh → Price breaks above last swing high (bullish breakout) but
is_downtrend is true → the trend direction is down (indicating possible false breakout or reversal)
No open sell position exists (!IsPositionOpen(POSITION_TYPE_SELL))
Action: Place a Sell order with:
SL = bid + sl_dist
TP = bid - tp_dist
Buy entry (reverse):
Condition:
bid < lastSwingLow → Price breaks below last swing low (bearish breakout) but
is_uptrend is true → the trend direction is up (indicating possible false breakdown or reversal)
No open buy position exists (!IsPositionOpen(POSITION_TYPE_BUY))
Action: Place a Buy order with:
SL = ask - sl_dist
TP = ask + tp_dist
Summary Table:
Mode
Price condition
Trend Condition
Position Check
Action
Normal (False)
ask > lastSwingHigh
Uptrend (is_uptrend)
No buy positions open
Open Buy
Normal (False)
bid < lastSwingLow
Downtrend (is_downtrend)
No sell positions open
Open Sell
Reverse (True)
ask > lastSwingHigh
Downtrend (is_downtrend)
No sell positions open
Open Sell
Reverse (True)
bid < lastSwingLow
Uptrend (is_uptrend)
No buy positions open
Open Buy
Intuition:
Normal mode: Enter in the direction of the trend when price breaks above (for buys) or below (for sells) the relevant swing high/low. Trend is confirmed by EMAs.
Reverse mode: Enter counter-trend on price breaks but in opposite direction of trend (e.g., price breaks up to lastSwingHigh but trend is down → open sell), expecting reversal or false breakout.
If you'd like more detail or explanation on any part, or want help on tuning these conditions, just ask!
Got it! You want to extend the reverse mode entry conditions by adding a check for Fair Value Gaps (FVG) in the relevant direction before entering trades. So:
For a reverse sell in downtrend with price breaking above lastSwingHigh and no sell position open, the EA should also confirm that a down Fair Value Gap exists before selling.
For a reverse buy in uptrend with price breaking below lastSwingLow and no buy position open, the EA should confirm an up Fair Value Gap exists before buying.
How to implement this?
You’d need to add a function to detect whether an up or down Fair Value Gap currently exists on the chart (or within recent bars), and use its return in the entry condition.
Concept of Fair Value Gap (FVG)
Fair Value Gap is a price imbalance area where a gap or inefficiency in the order flow exists, often identified by three consecutive bars with specific open/high/low/close conditions, e.g.:
Up Fair Value Gap:
The low of bar 2 is above the high of bar 0 → gap between these bars.
Down Fair Value Gap:
The high of bar 2 is below the low of bar 0 → gap below price.
You can define FVG on a user-specified timeframe and lookback.
Sketch of FVG detection functions (for swingTF example):
// Checks for a down FVG in last few bars on timeframe tf, returns true if exists
bool HasDownFairValueGap(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
int copied = CopyRates(symbol, tf, 0, 5, bars); // get last 5 bars
if(copied < 3)
return false;
// Example: Check last 3 bars for down FVG
// Bar indexing: bars[0] = current bar, bars[1], bars[2]
// Down FVG (gap below) if High of bar[2] < Low of bar[0] (gap between bars 2 and 0)
if(bars[2].high < bars[0].low)
return true;
return false;
}
// Checks for an up FVG in last few bars
bool HasUpFairValueGap(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
int copied = CopyRates(symbol, tf, 0, 5, bars);
if(copied < 3)
return false;
// Up FVG if Low of bar[2] > High of bar[0] (gap above)
if(bars[2].low > bars[0].high)
return true;
return false;
}
Modify your reverse mode entry in OnTick() like this:
The FVG check is a simple example. Depending on your exact definition, you may want to scan more bars or make rules more complex (e.g., buffer zones, wick vs body).
Confirm on the swingTF timeframe or adjust accordingly to your strategy.
You may consider caching or optimizing CopyRates calls (avoid excessive calls per tick).
If you want, I can help you write a robust FVG detection function or help integrate it in your EA fully with proper checks. Just let me know!
Correct, Fair Value Gaps (FVGs) are typically identified using 3 consecutive candles (bars). The common logic is:
Fair Value Gap Up (bullish gap): The low of candle 2 is greater than the high of candle 0 — meaning there is a gap or imbalance between these candles on the upside.
Fair Value Gap Down (bearish gap): The high of candle 2 is lower than the low of candle 0 — meaning there is a gap or imbalance between these candles on the downside.
Here, candle numbering is like this:
candle 0: the most recent completed candle
candle 1: the candle before that
candle 2: two candles ago
Example implementation of 3-candle Fair Value Gap detection in MQL5
// Checks for a Down Fair Value Gap using 3 candles on timeframe tf
bool HasDownFairValueGap(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
// get last 3 closed candles (from latest completed candle 0 backward)
if(CopyRates(symbol, tf, 1, 3, bars) != 3) // start from shift=1 to exclude incomplete current candle
return false;
// bars[0]: candle #1 (most recent completed candle)
// bars[1]: candle #2
// bars[2]: candle #3 (earliest of the 3)
// Down FVG test: High of candle #3 < Low of candle #1
if(bars[2].high < bars[0].low)
return true;
return false;
}
// Checks for an Up Fair Value Gap using 3 candles on timeframe tf
bool HasUpFairValueGap(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
if(CopyRates(symbol, tf, 1, 3, bars) != 3) // exclude current forming candle
return false;
// bars[0]: candle #1
// bars[2]: candle #3
// Up FVG test: Low of candle #3 > High of candle #1
if(bars[2].low > bars[0].high)
return true;
return false;
}
How to incorporate into your reverse mode entries (reminder):
if(enableReverseEntries)
{
// Reverse Sell: breakout above lastSwingHigh + downtrend + no sell position + down FVG
if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
if(HasDownFairValueGap(_Symbol, swingTF))
{
// Place sell order logic here...
}
else
{
Print("Reverse Sell skipped: no down fair value gap");
}
}
// Reverse Buy: breakout below lastSwingLow + uptrend + no buy position + up FVG
else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
if(HasUpFairValueGap(_Symbol, swingTF))
{
// Place buy order logic here...
}
else
{
Print("Reverse Buy skipped: no up fair value gap");
}
}
}
Important notes:
CopyRates(symbol, tf, 1, 3, bars) reads 3 closed candles excluding the current forming candle.
The candle indexes (bars[0], bars[1], bars[2]) correspond to shift 1, 2, 3 respectively.
This definition fits the "3 consecutive candle" FVG concept.
You may want to confirm ticks or timeframe precision (some brokers have irregular timeframes).
Optionally, you can extend to scans multiple bars back or add more filters to qualify gaps.
If you want, I can help you build a full example that integrates these FVG checks into your trading function properly, including plotting or debugging messages. Just ask!
Exactly! Your explanation captures a more precise and commonly used definition of Fair Value Gaps (FVG) based on the middle candle’s price range relative to the first and third candles:
Recap of FVG concept (3 candles):
Let's label:
Candle 1 (first candle, earlier)
Candle 2 (middle candle)
Candle 3 (third candle, later)
The middle candle's full price range (wicks included) does not overlap with the wicks of candles 1 and 3, creating an imbalance/gap.
Bullish (Up) Fair Value Gap:
The low of Candle 2 is greater than the highs of Candle 1 and Candle 3.
This means Candle 2’s entire range sits above the other two candles with a gap downward.
Specifically:
Candle 1 high < Candle 2 low
Candle 3 low < Candle 2 low (or ideally Candle 3 high < Candle 2 low to confirm no overlap)
Visual representation:
Candle 1 High < Candle 2 Low (middle candle wick completely higher)
Candle 3 Low < Candle 2 Low
=> Gap below middle candle to either side.
Bearish (Down) Fair Value Gap:
The high of Candle 2 is less than the lows of Candle 1 and Candle 3.
Meaning Candle 2’s entire range sits below the other two candles with a gap upward.
Specifically:
Candle 1 low > Candle 2 high
Candle 3 high > Candle 2 high (or ideally Candle 3 low > Candle 2 high to confirm no overlap)
Visual representation:
Candle 1 Low > Candle 2 High (middle candle wick completely lower)
Candle 3 High > Candle 2 High
=> Gap above middle candle to either side.
How to implement this in code?
You must check both sides of the gap relative to Candle 2's wicks (high and low), comparing to Candle 1 and Candle 3.
Example MQL5 FVG detection functions:
// Returns true if Bullish (Up) Fair Value Gap detected over 3 candles on 'tf'
bool HasBullishFVG(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
if(CopyRates(symbol, tf, 1, 3, bars) != 3)
return false;
// bars[0]: candle 1 (earliest)
// bars[1]: candle 2 (middle)
// bars[2]: candle 3 (latest of 3)
double candle2_low = bars[1].low;
double candle2_high = bars[1].high;
// Bullish FVG: Candle 2 low > Candle 1 high and Candle 3 low
bool bullish_gap = (candle2_low > bars[0].high) && (candle2_low > bars[2].low);
// Optional: confirm candle2 high is above candle1 high and candle3 low to confirm no overlap
// Could also add additional checks if desired
return bullish_gap;
}
// Returns true if Bearish (Down) Fair Value Gap detected over 3 candles on 'tf'
bool HasBearishFVG(string symbol, ENUM_TIMEFRAMES tf)
{
MqlRates bars[];
if(CopyRates(symbol, tf, 1, 3, bars) != 3)
return false;
// bars[0]: candle 1
// bars[1]: candle 2
// bars[2]: candle 3
double candle2_low = bars[1].low;
double candle2_high = bars[1].high;
// Bearish FVG: Candle 2 high < Candle 1 low and Candle 3 high
bool bearish_gap = (candle2_high < bars[0].low) && (candle2_high < bars[2].high);
return bearish_gap;
}
How to interpret:
HasBullishFVG(): detects a gap with the middle candle’s low greater than the neighbouring candles’ highs/lows — signifying a bullish demand gap.
HasBearishFVG(): detects a gap with the middle candle’s high lower than the neighbouring candles’ lows/highs — signifying a bearish supply gap.
Integrate into your reverse trades condition:
if(enableReverseEntries)
{
// Reverse Sell: breakout above lastSwingHigh + downtrend + no sell position + bearish FVG (down FVG)
if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
if(HasBearishFVG(_Symbol, swingTF)) // check bearish FVG before selling
{
// Place sell order ...
}
else
{
Print("Reverse Sell skipped: Bearish FVG not present");
}
}
// Reverse Buy: breakout below lastSwingLow + uptrend + no buy position + bullish FVG (up FVG)
else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
if(HasBullishFVG(_Symbol, swingTF)) // check bullish FVG before buying
{
// Place buy order ...
}
else
{
Print("Reverse Buy skipped: Bullish FVG not present");
}
}
}
Additional considerations:
Some traders use wicks only, some the full candle range to define gaps.
You can adjust logic if you want to detect partial gaps or gaps including candle bodies only.
May add buffer pixels/points to allow small overlaps.
Check latency and data consistency for large CopyRates calls when running on tick.
If you'd like, I can help you add code to visualize these Fair Value Gaps on the chart as horizontal rectangles or lines for debugging and confirmation.
Feel free to ask if you want me to prepare a fully integrated example for you!