//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap (full, compile) |
//| Added ADX filter and Losing Streak filter |
//| Added cooldown per candle & minimum time interval cooldown |
//| Improved cooldown after close - scanning recent closed deals |
//| Added Fair Value Gap (FVG) filter for entry signals |
//| Updated reverse mode to wait FVG post break before entry |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.7"
#property strict
#include <Trade\Trade.mqh>
// --- 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.
// --- Fair Value Gap filter input ---
input bool useFairValueGapFilter = true; // Enable Fair Value Gap filter for entries
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
// *** 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);
//-- Fair Value Gap detection function --
// Returns:
// 1 if bullish FVG detected (Candle1 High < Candle3 Low)
// -1 if bearish FVG detected (Candle1 Low > Candle3 High)
// 0 if no gap or error
int DetectFairValueGap(ENUM_TIMEFRAMES timeframe, int startShift)
{
MqlRates bars[3];
if(CopyRates(_Symbol, timeframe, startShift, 3, bars) != 3)
{
Print("DetectFairValueGap: failed to copy 3 bars");
return 0;
}
Your EA code looks quite comprehensive and well-structured, combining lots of useful features:
Break of Structure entries with multi-timeframe MAs.
ATR-based SL/TP sizing and trailing stop modes.
ADX filter for confirming trend strength.
Losing streak limits and daily loss caps.
Post-close cooldown and minimum interval between trades.
Fair Value Gap (FVG) filter with logic to wait for FVG before entering reverse trades.
A clear, robust trailing stop system with market structure and ATR based trailing, including a hybrid option.
Reverse mode trading by waiting for price breaks beyond swing levels and then FVG confirmations before entering.
Overall Feedback and Possible Improvements:
Trade Timing Logic:
You have multiple cooldown checks (time interval + per candle cooldown + post-close cooldown). These combined ensure a minimal frequency and reduce overtrading. They are properly implemented and include throttled print statements, which is good.
Risk Management:
The floating loss cap (maxRiskPerTradePercent) closes trades whose floating losses exceed a % of account balance. This is an advanced money management feature.
You also have daily maximum loss checks and losing streak filters, which is excellent.
Trailing Stops:
You support 3 trailing stop modes plus none. The hybrid mode combines MS swing levels and ATR trailing, which is good.
You throttle trailing stop update calls via CanUpdateTrailing() to reduce frequent SL moves, which is smart.
Fair Value Gap (FVG) Logic:
You detect bullish/bearish FVG with DetectFairValueGap(), comparing candles 1 and 3.
The reverse logic waits for a break beyond swings plus a matching FVG before entering; this sequencing reduces false signals.
Reverse Entry Flags and Reset Logic:
You correctly set/reset reverse break flags and only enter after confirming the FVG.
You might consider adding a timeout to reset these flags if FVG fails to appear within some time, to avoid waiting indefinitely.
Position Limit Enforced (maxPositions):
Works as expected, counting only EA's positions for the symbol and magic.
Indicator Handles and OnInit:
Proper creation and cleanup on OnInit() and OnDeinit().
User
ill send another version and tell me the diferences
Assistant
Absolutely, just send your other version of the EA code, and I will analyze and highlight the differences compared to this version you posted.
User
//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap (full, compile) |
//| Added ADX filter and Losing Streak filter |
//| Added cooldown per candle & minimum time interval cooldown |
//| Improved cooldown after close - scanning recent closed deals |
//| Added Fair Value Gap (FVG) filter for entry signals |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.6"
#property strict
#include <Trade\Trade.mqh>
// --- 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.
// --- Fair Value Gap filter input ---
input bool useFairValueGapFilter = true; // Enable Fair Value Gap filter for entries
CTrade trade;
Assistant
Here is a detailed comparison and summary of differences between the second EA version (v1.6) you just posted and the first EA version (v1.7) you posted earlier:
1. Version and Header Comments:
First version: #property version "1.7" and a more detailed header with reverse mode waiting FVG logic, added cooldown improvements, more comments.
Second version: #property version "1.6" with a simpler header; it lacks some newer comments about reverse mode and cooldown improvements.
2. Reverse Entry Logic:
First (v1.7) version:
Uses reverse break flagsreverseSellBreakOccurred and reverseBuyBreakOccurred plus timestamps to wait for Fair Value Gap (FVG) confirmation after break before placing reverse trades.
Second (v1.6) version:
Simpler reverse entries logic without flags. It directly checks if:
enableReverseEntries is true:
If price breaks above swing high in downtrend, then open SELL immediately if FVG signal bearish or no FVG filter.
If price breaks below swing low in uptrend, open BUY immediately if bullish FVG/no filter.
No waiting state or flags, trades placed instantly on signal if conditions met.
Reverse mode does not short-circuit processing, all logic contained inside if/else blocks.
Summary:
Version 1.7 introduces a more sophisticated flag-based waiting system for reverse trades that waits for FVG confirmation after break, whereas version 1.6 opens reverse trades immediately upon break + FVG signal without waiting state flags.
3. Fair Value Gap (FVG) filter usage:
User
why both give same backtest results?
Assistant
Great question! If both versions give the same backtest results despite the clear differences in the reverse entry logic (flag-based waiting in v1.7 vs immediate entries in v1.6), here are the most likely explanations:
1. Market Conditions During Backtest
The conditions triggering reverse entries (price breaks beyond swing + required FVG confirmation) may rarely trigger differently between the two methods in your backtest data.
For example:
The FVG may often appear immediately after the break or even before, meaning waiting flags in v1.7 do not delay entries much compared to immediate entries in v1.6.
Or the price might not break conditions often at all, limiting the difference impact.
2. Backtest Settings & Data Granularity
Backtests often run on closed candle data or minute-level ticks.
If FVG, break levels, and reverse break conditions are evaluated on completed bars, you may get very similar signals in both versions.
The "waiting" mechanism in v1.7 mostly helps on live or tick-by-tick data, adding delay between break detection and entry until FVG appears.
3. Reverse Mode May Not Be Heavily Used / Disabled or Rarely Triggered
If you often run with enableReverseEntries=false or your trade setups rarely go into reverse conditions, the main difference (reverse entry waiting) won’t show impact.
In your v1.6 code, the reverse logic is simpler, but if reverse conditions are very rare, both versions effectively behave the same.
4. Reverse Flags Are Reset Quickly
In your live or backtest runs, the state flags reverseSellBreakOccurred and reverseBuyBreakOccurred could be set and reset in the same tick or next tick because the break and FVG happen quickly.
So with no real "waiting" delay, entries happen at approximately the same bar/candle ticks in both.
5. Backtest Model Limitations
Some platforms in backtest mode do not perfectly emulate the difference between immediate tick-based logic vs flag-waiting with real-time ticks.
Since both scripts place trades only at bar closes or on ticks evaluated at once, the differences in timing rarely manifest.
User
2025.05.01 07:32:56 Reverse BUY break below swing low detected at 2025.05.01 07:32. Waiting for bullish FVG to open BUY.
2025.05.01 07:33:00 No Fair Value Gap detected, skipping new entries per FVG filter.
2025.05.01 07:33:00 Reverse BUY break invalidated, resetting flag.
2025.05.01 07:35:00 Bullish Fair Value Gap detected between candle1 high 19839.70000 and candle3 low 19843.70000 (Gap 4.00000)
detected Bullish Fair Value Gap but didnt buy, why?
Assistant
Your logs clearly show these events:
07:32:56: Reverse BUY break detected below swing low → flag set, waiting for bullish FVG.
07:33:00: No FVG detected → skip entry.
07:33:00: Reverse BUY break invalidated → flag reset.
07:35:00: Bullish FVG detected.
Why no buy was opened at 07:35 despite Bullish FVG detected?
The crucial part is that the reverse buy break flag was reset at 07:33:00, before the FVG appeared at 07:35.
Here's the likely cause:
Your code logic (from OnTick() in version 1.7) managing reverse buy breaks does this:
mql
// Detecting reverse BUY break
if(is_uptrend && bid < lastSwingLow && !reverseBuyBreakOccurred)
{
reverseBuyBreakOccurred = true;
reverseBuyBreakTime = TimeCurrent();
PrintFormat("Reverse BUY break below swing low detected at %s. Waiting for bullish FVG to open BUY.", TimeToString(reverseBuyBreakTime));
}
// Reset buy flag if invalidated
if(reverseBuyBreakOccurred)
{
if(!is_uptrend || bid >= lastSwingLow)
{
Print("Reverse BUY break invalidated, resetting flag.");
reverseBuyBreakOccurred = false;
reverseBuyBreakTime = 0;
}
}
// Open BUY only after bullish FVG appears post-break
if(reverseBuyBreakOccurred && fvgSignal == 1 && bid < lastSwingLow)
{
// Place buy order ...
}
What happened in your case?
At 07:32:56, the break was detected, flag set.
At 07:33:00:
Condition is_uptrend && bid < lastSwingLow no longer held true (bid price probably went back above or equal to lastSwingLow).
So flag reset by the invalidation condition.
Since flag was reset, even if FVG is detected later, the condition is now , so the buy entry .
User
tell me more about Add a small "waiting window" or timeout for reverse break flag and remove strict "price still below swing low" condition at entry moment
Assistant
Certainly! Let me explain both approaches in detail and how you can implement them for your reverse break flag logic to improve your EA’s entry decisions after a break.
1. Adding a Small "Waiting Window" or Timeout for Reverse Break Flag
Problem this solves:
Currently your EA immediately resets the reverse break flag when price no longer satisfies the strict break condition (e.g., bid is back above swing low for reverse buy break).
If the Fair Value Gap (FVG) doesn’t appear instantly, the flag is reset too soon → no entry even if a valid FVG appears shortly afterward.
Concept:
When the reverse break first happens, you set a timestamp (reverseBuyBreakTime).
Instead of resetting the reverse break flag immediately when price conditions fail, you allow a grace period ("waiting window") during which the flag remains set, so the EA waits for the FVG signal.
The flag only resets if BOTH:
The price condition invalidates the break (e.g., price recovers above swing low)
AND a reasonable timeout period elapsed WITHOUT FVG appearing
Example implementation:
mql
// Timeout in seconds you want to wait after a break before discarding it
int reverseBreakTimeoutSecs = 300; // e.g., 5 minutes
// Detect reverse break for BUY (your existing code)
if(is_uptrend && bid < lastSwingLow && !reverseBuyBreakOccurred)
{
reverseBuyBreakOccurred = true;
reverseBuyBreakTime = TimeCurrent();
PrintFormat("Reverse BUY break below swing low detected at %s. Waiting for bullish FVG to open BUY.", TimeToString(reverseBuyBreakTime));
}
// Instead of resetting the flag immediately on invalid price, wait for timeout
if(reverseBuyBreakOccurred)
{
datetime now = TimeCurrent();
// Only reset if price invalid AND timeout exceeded
if((!is_uptrend || bid >= lastSwingLow) && (now - reverseBuyBreakTime > reverseBreakTimeoutSecs))
{
Print("Reverse BUY break invalidated by price & timeout, resetting flag.");
reverseBuyBreakOccurred = false;
reverseBuyBreakTime = 0;
}
}
Timeout for Reverse Flags:
To avoid lingering reverseSellBreakOccurred or reverseBuyBreakOccurred, add a maximum time window after which the flag resets if trigger conditions do not occur.
Fair Value Gap Logic More Flexible:
The current FVG detection compares exactly 3 consecutive bars. You may want to extend this to allow "open gaps" that occur on any recent bars within a certain lookback, or check price's relation to FVG zones for better filtering.
Trailing Stop Mode Selection:
If trailingStopMode is TrailingHybrid, in UpdateTrailingStopHybrid() you might check which trailing SL (MS or ATR) is tighter or more protective and use it accordingly.
Logging Levels / Debug Mode:
To prevent print spam during live trading, add a debug flag to control verbosity of print statements (especially internal indicator failures, FVG detection prints, etc).
Re-Check Indicator Buffers more Safely:
The CopyBuffer() calls do not always handle the return error beyond <=0, currently you just return. Consider handling partial extracts or retries.
Asynchronous OrderSend() and Error Handling:
You print error codes when OrderSend() fails. Consider adding error recovery or retry logic for transient errors.
Position Selection by Symbol and Magic:
You test PositionGetString(POSITION_SYMBOL)==_Symbol. This is correct but you might cache _Symbol once or make this const string.
Summary / Key Points you might want to add or test:
Add a time expiration on reverseBreak flags, e.g., reset them if no trade occurred after X minutes.
Consider adding debug verbosity levels to reduce log noise.
Test behavior when no FVG appears indefinitely, ensure EA eventually resets waiting flags.
Optionally improve FVG detection granularity or tolerance.
Consider adding relevant comments describing tricky logic sections for maintainability.
If you want me to help add e.g. reverse-break timeout logic or add a debug flag, or make improvements/fixes, just ask!
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
// *** 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);
//-- Fair Value Gap detection function --
// Returns:
// 1 if bullish FVG detected (Candle1 High < Candle3 Low)
// -1 if bearish FVG detected (Candle1 Low > Candle3 High)
// 0 if no gap or error
int DetectFairValueGap(ENUM_TIMEFRAMES timeframe, int startShift)
{
MqlRates bars[3];
// Copy 3 bars starting from startShift, i.e. bars[0] = bar at startShift
if(CopyRates(_Symbol, timeframe, startShift, 3, bars) != 3)
{
Print("DetectFairValueGap: failed to copy 3 bars");
return 0;
}
Version 1.7:
In normal mode (non-reverse), skips entries if no FVG detected but does not fully skip in reverse mode (as waiting flag logic handles that). Prints log "No FVG, skipping new entries" throttled once per candle.
Version 1.6:
In both normal and reverse modes, if no FVG is detected and filter enabled, it returns early (skips trading). No special handling for reverse waiting flags here.
4. Trailing Stop Updates:
Both versions have identical trailing stop functions: UpdateTrailingStopByMarketStructure(), UpdateTrailingStopByATR(), and UpdateTrailingStopHybrid(). No difference detected here.
5. Cooldown / Delay Management:
Both versions check:
Post-close cooldown (IsRecentPositionClose()) with throttled logging.
Minimum time interval cooldown (lastTradeOpenTime and tradeIntervalSeconds).
Per candle cooldown (lastTradeCandleTime).
No major code differences in this aspect between versions.
6. ADX Filter Behavior:
Both versions apply the ADX filter strictly same way:
Skip trade if ADX below threshold.
Print message throttled once per candle.
7. Position Opening / Closing Conditions:
Version 1.7:
More advanced position checks, including floating risk close (positions closed if losing beyond maxRiskPerTradePercent)—same for v1.6.
Order sending difference in reverse mode:
In v1.7, reverse orders sent only after waiting for FVG post break (with flags).
In v1.6, reverse orders sent immediately if conditions met.
8. Globals / Flags:
Version 1.7:
Defines two global flags and timestamps:
The key functional difference is the reverse entry logic implementation.
Version 1.7 is more robust and sophisticated, avoiding premature reverse trades by waiting for FVG confirmation with persistent flags.
Version 1.6 is simpler and might enter reverse trades immediately on price and FVG signal without confirmation waiting.
If you want me to help you merge these features or modify one version to include the other’s behavior, just ask!
6. Same Trade Filters and Other Features
Both versions share identical or nearly identical:
Time filters
Risk and position filters
ADX filter
Lot sizing
Trailing stop logic
These common features dominate performance, making the minor entry timing differences marginal in backtests.
How to check if difference is real?
Run live or tick-by-tick simulated test with detailed logging enabled, and watch the internal printouts of reverseSellBreakOccurred and entry times for reverse trades.
Temporarily force longer waiting time for flags in v1.7, e.g. add a delay or expiration timeout (e.g. wait 1-3 candles after break to place entry). This would create more pronounced difference.
Compare equity curves and order timestamps precisely between versions.
Summary
The versions differ mainly in how reverse trades are timed (waiting flags vs immediate), but in backtest mode with the available data and market conditions, they effectively end up opening trades very close in time — resulting in near identical backtest results.
If you want, I can help you add artificial delays or expand the reverse flag logic to make differences more visible in tests. Just ask!
reverseBuyBreakOccurred
false
will not be triggered
At 07:35:00 when FVG detected, the EA was no longer "waiting" because the break was invalidated too early.
In other words:
For reverse entry to trigger, the "reverse break" condition must persist continuously from the break through the FVG detection. If price recovers above the swing low (for buy side) before FVG appears, reverse break flag resets and no trade opens.
How to fix / improve this:
1. Add a small "waiting window" or timeout for reverse break flag
Allow the reverse break flag to persist for some seconds/minutes even if interim price conditions fail, giving time for FVG to occur — for example:
mql
int reverseBreakTimeoutSecs = 300; // 5 minutes
if(reverseBuyBreakOccurred)
{
datetime now = TimeCurrent();
// Reset only if price invalid AND timeout elapsed
if((!is_uptrend || bid >= lastSwingLow) && (now - reverseBuyBreakTime > reverseBreakTimeoutSecs))
{
Print("Reverse BUY break invalidated by price & timeout, resetting flag.");
reverseBuyBreakOccurred = false;
reverseBuyBreakTime = 0;
}
}
This way, even if price bounces back briefly, the EA will still wait a bit for FVG.
2. Or, remove strict "price still below swing low" condition at entry moment
Instead, check if reverse break occurred previously (flag true) and FVG now is valid, place the order even if price slightly recovered (maybe with a looser check).
3. Add logging to see exact bid and lastSwingLow during invalidation
The bid < lastSwingLow part is strict and may prevent entries if price briefly moves back above the swing low but FVG confirms the setup and entry would still be logical.
Concept:
Once the reverse break flag is set, you could open the trade as soon as FVG appears, without always requiring the price still to be below swing low at that moment.
Where priceTolerance is a small buffer (e.g., a few points or pips).
Example implementation:
mql
double priceTolerance = SymbolInfoDouble(_Symbol, SYMBOL_POINT) * 5; // e.g. 5 points
if(reverseBuyBreakOccurred && fvgSignal == 1 && (bid <= lastSwingLow + priceTolerance))
{
// Place buy order
// ...
// Reset flags as usual
}
Or even remove the price condition entirely:
mql
if(reverseBuyBreakOccurred && fvgSignal == 1)
{
// Place buy order unconditionally once FVG appears
}
Implications:
This gives more flexibility for entry after the break — the EA trusts the combination of the initial break flag plus FVG confirmation, regardless of minor price retracement.
Can increase trade frequency but may increase risk slightly if price moved back decisively.
It's good to combine this with the waiting window so the flag doesn’t stay forever active.
Combining Both Approaches (Recommended)
Maintain the waiting window (timeout) mechanism to avoid waiting indefinitely.
Relax or remove the strict price condition at entry, allowing slightly more tolerant or unconditional entry once the FVG forms.
This balance ensures you react appropriately to setup without prematurely dismissing valid breaks or missing entries due to minor price pullbacks.
Summary
Approach
Advantages
Possible Risks
Waiting Window / Timeout
Waits for FVG, more trades executed when valid
Potential slight delay entering
Remove Strict Price Condition
More flexible entries after break
Might enter after minor retrace; less strict price confirmation