// --- 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];
// 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;
}
Your EA code looks quite comprehensive and well-structured. Here is a high-level review plus some suggestions and points to verify or improve:
Summary
Multi-timeframe EMAs (3) and ATR are used to gauge trend and volatility.
ADX filters entries below defined strength.
Losing streak and daily loss money limits prevent overtrading or excessive losses.
Floating risk cap closes positions if unrealized loss exceeds a percentage of balance.
Trailing stop logic supports Market Structure, ATR-based, or Hybrid trailing.
Fair Value Gap (FVG) detection is implemented and used as a filter.
Cooldown rules prevent multiple trades on the same candle or too soon after previous trade.
Reverse entry mode can open counter-trend trades.
Detailed logging and throttled repeated print output on cooldown/debug events.
Specific Notes and Suggestions
1. Indicator Handles Management
Indicator handles are created in OnInit() and released in OnDeinit(). This is correct.
However, ensure that when handle is released, the corresponding int is set back to INVALID_HANDLE to prevent accidental use after release. You do this well.
2. Fair Value Gap Detection
You detect bullish FVG when candle1 high < candle3 low and bearish FVG vice versa. This is a straightforward interpretation.
You might want to validate that candle2's body is wide enough or verify partial gaps to reduce noise. Currently, any such gap triggers signal.
The function assumes bars are fully formed (shift=1).
3. Floating Risk Close Logic (Floating Loss Cap)
You iterate over all positions and close if unrealized loss exceeds limit in account currency.
You close immediately by trade.PositionClose(). This is fine but watch for partial fills, slippage, or disabling trading.
Consider protecting against recursion or multiple position closes in a single OnTick() if positions are many.
4. Losing Streak Tracking
You scan closed deals in the last 24h every tick.
This can be slow or redundant, use a timer or minimum interval between calls.
You reset losing streak at midnight.
Consider adding a max scan count or some performance optimization.
5. Cooldown Rules
User
tell me about entry only on reverse mode and fvg filter on
Assistant
Certainly! Let me explain how entry logic works when enableReverseEntries is set to true and the Fair Value Gap (FVG) filter is enabled in your EA.
Context Recap
Your EA normally enters trades aligned with the trend defined by 3 EMAs (short, medium, long), and breaks of swing highs/lows.
The Fair Value Gap filter verifies the presence of a particular price gap pattern (bullish or bearish FVG) before allowing an entry.
The Reverse Entries mode swaps the usual trade direction on swing break signals.
How Entry Logic Works with Reverse Entries = true and FVG Filter = enabled
1. Normal Entry Logic (when enableReverseEntries == false)
Buy entry criteria:
Price (ask) breaks above last swing high.
Market is in uptrend (EMA1 > EMA2 > EMA3, ask > EMA2).
Fair Value Gap bullish FVG signal detected (fvgSignal == 1).
No existing open buy position.
Sell entry criteria:
Price (bid) breaks below last swing low.
Market is in downtrend (EMA1 < EMA2 < EMA3, ask < EMA2).
Fair Value Gap bearish FVG signal detected (fvgSignal == -1).
Swap the entry direction according to trend and level break:
Condition
Trade Type Opened
FVG Signal Condition
Ask price breaks above swing high AND downtrend detected
Open a Sell position (reverse)
fvgSignal == -1 (bearish FVG)
Bid price breaks below swing low AND uptrend detected
Open a Buy position (reverse)
fvgSignal == 1 (bullish FVG)
3. Fair Value Gap Filter (when useFairValueGapFilter == true)
Before opening any new position, the EA checks the FVG condition on the selected timeframe and recent bars.
User
The logic ensures that you only enter when there’s evidence of a recent Fair Value Gap (gap between candle 1 and candle 3 on swing timeframe) after the break or befor or at the time of break?
Assistant
Great question!
When is the Fair Value Gap (FVG) detected relative to the entry trigger (break)?
In your EA, the FVG detection is done on recently closed candles before the current tick, i.e., before the actual break candle is formed or confirmed.
Explanation based on your code (key lines):
mql5
// Detect FVG using shift=1: means bars[0] = candle with shift 1, i.e., last fully closed candle before current forming candle
fvgSignal = DetectFairValueGap(swingTF, 1);
What does shift=1 mean?
shift=0 points to the current forming candle—not fully closed.
shift=1 points to the last fully closed candle.
So your EA detects the FVG on the last completed candle plus the two before it:
Candle1 = bar with shift=1
Candle2 = bar with shift=2
Candle3 = bar with shift=3
(Since your function grabs three bars starting from startShift=1 onward.)
Therefore:
The FVG pattern must already exist on recently closed candles before the break or at least not on the current forming candle.
The entry trigger (break above swing high / below swing low) is typically detected on the current tick's price action or in-progress candle.
The EA relies on an existing fair value gap pattern formed before the breakout bar to validate the trade.
In other words:
Step
Detail
1. FVG exists on candles:
Bars closed 1+ candles ago on swing timeframe, prior to the breakout.
2. Price breaks swing high/low level:
On current bar/tick after the FVG is formed.
3. EA detects FVG on last closed candle(s) (shift=1)
FVG confirmed before break or right at start of break candle.
4. EA places trade if FVG aligns with trade direction + other conditions.
Entry happens after the FVG signal is present.
Why this approach?
User
i want trade open when fvg apear after break
Assistant
Got it — you want the EA to open trades only when a Fair Value Gap (FVG) appears after the swing high/low breakout**,* i.e., the FVG forms as a consequence of the breakout, not before.
What that means:
In your current EA, the FVG check is done on bars before the breakout bar (by checking candles shifted 1 or more bars back).
You want instead to detect that the FVG appears on or after the breakout candle, so the FVG forms as a reaction to the break, not before.
How to implement "trade open when FVG appears after break" logic:
1) Understanding your existing FVG detection:
mql5
// Current usage: DetectFairValueGap(swingTF, 1);
// Checks 3 bars starting from shift=1 (last fully closed candle)
shift=1 means you're checking candles entirely before the breakout candle.
2) What you want is to detect FVG emerging on candles coming after the breakout:
This means you need to:
Detect when price breaks swing high/low (that defines breakout bar, say bar N).
Then wait for FVG formation on bars with shift <= N or on bars formed after the breakout candle.
Practically, this implies you do NOT open the trade immediately on breakout, but instead:
Detect the breakout.
Then monitor next few candles for FVG to form.
When FVG is confirmed on bars formed after breakout, open the trade.
Coding conceptual approach
You can’t detect FVG on a candle that hasn't formed yet. So you must:
On breakout candle/bar:
Record the breakout event time or candle index.
Delay trade entry until next candle(s) confirm FVG.
On every new candle after breakout, check for FVG appearing on recent candles (including newly closed ones).
When FVG forms matching breakout direction, open trade.
How to do this practically in your EA
Add state variables to track breakout:
mql5
User
update and send complete ea code just to compile
Assistant
Certainly! I've updated your EA code to implement this logic:
When a breakout (swing high/low break) is detected, the EA does NOT open a trade immediately.
Instead, it records the breakout event (direction and candle time).
On subsequent candles, it checks for a Fair Value Gap (FVG) that occurs after the breakout and matching breakout direction.
When such FVG is confirmed, the EA opens the trade.
The breakout state resets after successful trade or after a timeout of specified bars without FVG confirmation.
Added a timeout: maxBreakoutWaitBars = 3 (number of candles to wait for FVG after breakout before reset).
Modified OnTick() to detect breakouts but delay entries until FVG appears post-breakout.
Here's the complete updated EA code, just to compile (I kept almost all your original code intact, just added & changed relevant parts). You can replace your current .mq5 file with this and compile.
mql5
User
how ea works with this update?
Assistant
Certainly! Here’s a detailed explanation of how your updated EA works with this new logic, focusing on the trade entry flow and the Fair Value Gap (FVG) detection after breakouts.
1. General Context
Your EA is a Break of Structure (BOS) strategy that enters trades when price breaks above swing highs or below swing lows filtered by:
Multi-timeframe EMA trend filters
ATR-based stop losses and take profits
ADX strength filter to avoid low volatility
Losing streak and daily loss caps
Cooldowns to prevent overtrading
Fair Value Gap (FVG) filter for better entry timing
Optional "Reverse Entries" mode to trade counter-trend breakouts
2. Updated Key Entry Logic
Previous behavior:
EA tested for FVG presence before or on the breakout candle (on already closed candles).
If FVG existed before breakout, trade could open immediately.
New behavior with this update:
When price breaks a swing high or low (breakout):
The EA records the breakout event but does NOT open a trade immediately.
Stores the breakout candle time (when break happened)
Stores breakout direction:
1 for bullish breakout (break above swing high)
-1 for bearish breakout (break below swing low)
Resets waiting counter to start counting bars after breakout.
After breakout, the EA waits for a Fair Value Gap (FVG) to appear after the breakout bar, up to a configurable number of bars (maxBreakoutWaitBars, default 3).
On each new candle after breakout, the EA:
Checks for the presence of a Fair Value Gap on the recent closed candles on the swing timeframe.
If a matching FVG is detected (bullish for bullish breakout, bearish for bearish breakout), the EA proceeds to place the trade.
Once trade is opened, the breakout state is cleared (ready for next breakout).
If FVG does not appear within the timeout candle limit, the EA resets breakout state and cancels that entry attempt.
User
i backtested with different maxbreakoutwaitbars for 1 to 10 , same result
Assistant
Thanks for testing and sharing your observation.
If changing maxBreakoutWaitBars from 1 to 10 produces the same result with no variation, it suggests the EA might not be properly waiting for multiple bars, or the breakout tracking/reset logic might be causing immediate reset or premature clearing of the breakout flag.
What could cause identical behavior regardless of wait bar count?
The breakout detection and FVG check happen within the same tick or bar, so the wait counter increments and resets immediately.
The breakout state (breakoutDetected) is reset prematurely after first failed attempt or immediately after first bar.
The EA might be unable to detect new bars properly (e.g., currentCandleTime not changing, or signal logic run multiple times within same bar).
FVG detection code might be consistently returning no gap or conflicting gap, so EA never actually waits beyond first bar.
How to troubleshoot & fix
1) Verify breakoutWaitCounter incrementation and reset logic
Make sure the increment and resets are done only once per closed candle, otherwise it will fire many times per tick.
This often requires running logic on new candle only, for example using a static variable that stores last candle time processed:
2) Ensure breakoutDetected remains true while waiting
If you reset breakoutDetected too early—e.g., right after failing first FVG check—the wait logic effectively stops and is restarted on next breakout. This makes wait bar count meaningless.
Combining candle cooldown and minimum time interval cooldown before new trades is a good approach.
You use last closed candle time lastTradeCandleTime and last trade open time lastTradeOpenTime.
This ensures no duplicate trade in same candle or trades spaced by defined seconds.
6. Trailing Stop Logic
Three modes are supported with ATR & Market Structure.
You throttle updates using TrailUpdateIntervalSec so no too frequent modifications.
Good handling of sl adjustment conditions.
7. Lot Sizing
Supports fixed lot or risk percent-based.
Calculation looks correct with consideration of tick_value, contract_size.
Floor lot to step size and clamp between min/max limits.
Potential Issues or Improvements
A. Error Handling in OrderSend
You use OrderSend(request,result) and check for retcode.
Consider adding retries or logging result.comment for more info.
Possibly add PrintLastError() or log errors more verbosely.
B. Market Conditions Check
ADX filter disables entries if ADX below threshold.
Maybe also confirm spread is low and liquidity is sufficient.
Could add check for news or trading sessions.
C. Reverse Entries Logic
Reverse entries trigger on opposite trend breaking swing levels.
Good option, but be cautious it can increase drawdown.
Consider adding a toggle for reverse entries or limiting frequency.
D. HistorySelect Usage
HistorySelect can fail due to no history or server load; you catch failure but maybe retry after delay.
Also, HistorySelect can be slow if called every tick, consider caching or calling less often.
E. Protection Against Multiple Trades on Same Swing Break
It seems checks use IsPositionOpen() and cooldowns to prevent multiple orders.
Verify multiple orders don’t slip in when maxPositions allows >1.
Code Readability and Maintenance
Consider splitting big OnTick() into smaller functions for clarity, e.g. CheckFloatingRiskClose(), TryOpenTrade(), UpdateTrailingStops().
Add comments above complex calculations.
Declare and initialize variables close to their use to enhance reading.
Quick Error Fix Suggestion (if you want)
Your OnTick() uses OrderSend(request,result), but better to wrap with trade class as you use it elsewhere, or at least check for result.retcode in more detail.
Add a helper function to send trade requests and log consistently.
Overall, this EA source looks solid, feature-rich, and ready to run (subject to your broker and symbol conditions).
If you want me to check or add specific improvements or error fixes, just ask!
If no appropriate FVG is detected matching the trade direction, the trade entry is skipped.
The logic ensures that you only enter when there’s evidence of a recent Fair Value Gap (gap between candle 1 and candle 3 on swing timeframe) confirming kind of price inefficiency or space for price to fill.
4. Summary of Combined Logic
plaintext
If reverse entries enabled:
If price breakout AND trend opposite usual direction THEN
If FVG filter ON and appropriate FVG signal detected (bullish for BUY reverse, bearish for SELL reverse)
Place reverse position (SELL on swing high break in downtrend; BUY on swing low break in uptrend)
ELSE
Skip trade (no FVG)
Else (normal trading):
If price breakout AND trend aligned normally THEN
If FVG filter ON and appropriate FVG signal detected (bullish for BUY, bearish for SELL )
Place normal position (BUY on swing high break in uptrend; SELL on swing low break in downtrend)
ELSE
Skip trade (no FVG)
Practical Example
Suppose:
enableReverseEntries = true
useFairValueGapFilter = true
Trend is downtrend (MA1 < MA2 < MA3)
Price breaks above the swing high (which usually signals bullish breakout)
The EA checks for bearish FVG on swing timeframe (FVG == -1)
Since reverse trading is enabled and bearish FVG is confirmed, a SELL position is opened (reverse to the breakout).
Similarly, for opposite scenario in uptrend with breakdown of swing low.
Why use Reverse Entry mode with FVG filter?
This is intended to catch potential fakeouts or traps:
Price breaks a critical swing level, but underlying momentum conditions (via EMA trend and FVG) suggest reversal likely or continuation of original trend.
The FVG filter adds context, requiring that recent price gaps align with expected directional pressure.
By using reverse entries + FVG, the EA only trades counter-trend on confirmed supply/demand imbalances.
Important Notes
Reverse entry mode can be riskier since you trade against primary trend breaks.
FVG filter acts as a strong condition to reduce false signals.
Ensure you test this mode thoroughly on demo to confirm it behaves as intended.
Adjust your trailing stops and risk management because counter-trend trades may need more precise exits.
If you want, I can also help provide a simplified snippet or flow diagram of this part of the logic, just ask!
Using closed candles for FVG detection avoids relying on incomplete (still forming) bars, which can be noisy or uncertain.
It reduces false signals by confirming fair value gaps are already established in recent price data, not just suspected intra-bar.
Summary:
The EA requires the Fair Value Gap to have formed on the most recent fully closed candles before the breakout or entry candle, and uses this as confirmation to allow trade entry at/after the break, not projecting FVG on the current or future bars.
If you want to check or modify this behavior to detect gaps on the current forming candle or introduce more realtime FVG detection, it would require changing the startShift parameter or logic to include shift=0 and handle partial candles carefully.
Let me know if you want help adapting the FVG detection logic for other timing or conditions!
With useFairValueGapFilter=true and enableReverseEntries=true (or false), the EA first detects breakout and then waits up to maxBreakoutWaitBars bars for FVG confirmation before opening the trade.
Check logs to see printed messages about breakout detection, waiting for FVG, FVG detection, and trade placement.
If you want me to help further improve or explain any part, just say!
3. How FVG Filter and Reverse Entries Fit In
If useFairValueGapFilter == true (default true), only trades confirmed by the post-breakout FVG pattern are entered.
If the filter is disabled, fallback logic can be added (currently not specified - EA waits).
If enableReverseEntries == true, then:
Breakouts against trend open reverse trades, e.g., a bullish break in a downtrend → open Sell (reverse).
FVG detection matches the reversed trade direction accordingly.
4. Walkthrough Example
Suppose:
You have a downtrend (EMA1 < EMA2 < EMA3).
Price breaks above the last swing high on the swing timeframe (this is a bullish breakout technically, but against trend).
Since reverse entries are enabled:
EA records the breakout event with direction = -1 (reverse bearish).
The EA does not open a trade now; instead, it waits.
On subsequent candles after breakout:
EA looks for a bearish Fair Value Gap (FVG == -1).
If such FVG appears on closed candles, EA opens a Sell position.
If no bearish FVG appears in 3 bars after breakout, EA cancels the breakout signal watch.
5. Why This Behavior?
The update enforces a confirmation step after the breakout rather than immediate entry.
This reduces false breakouts and increases probability of catching momentum continuation or retracement setups validated by price inefficiencies (FVG).
Waiting some bars after breakout to see an FVG gives the market time to "show its hand" — giving more reliable signal.
The wait timeout avoids indefinite waiting to prevent stale breakout signals.
6. Trade Execution Notes
When conditions are met (breakout + matching FVG in allowed wait period + cooldowns + position limits etc.), the EA opens a trade with:
Calculated lot size (fixed or risk % based on SL distance)
SL and TP based on ATR multiples and R:R ratio
Magic number and market price request
Proper volume and deviation
After trade open, cooldowns reset to prevent trades in same candle or too soon.
7. Other Existing Features Remain
ADX filter prevents new entries under weak trend strength.
Losing streak and max daily loss limits still cancel new trades.
Floating risk cap closes losing trades exceeding set % loss dynamically.
Cooldowns per candle and intervals prevent overtrading.
All indicator handling and memory release as before.
8. Summary
Step
Description
1) Price breaks swing high/low
EA detects breakout, records breakout time and direction, but does NOT open trade yet.
2) EA waits for next bars (up to maxBreakoutWaitBars)
Monitors incoming closed candles for FVG matching the breakout direction.
3) FVG appears and matches breakout
EA opens the trade with proper risk and SL/TP.
4) No FVG after max wait bars
EA cancels breakout watch, no trade opened for that breakout.
5) Trade cooldowns and position limits enforced
prevents overtrading or breaching defined limits.
Overall:
Your EA has become more conservative with post-breakout confirmation via FVG before entries. This helps filter out fakeouts and potentially improves the quality of entries by trading on confirmed price inefficiencies appearing after the breakout rather than before.
If you would like, I can help you further tune parameters or explain any other parts of the EA.
Make sure breakoutDetected is only reset if timeout reached or trade placed.
3) Confirm how DetectFairValueGap() behaves
Log the FVG detection results carefully — add debug prints showing:
What bars you are fetching (their times)
What values of highs/lows
What signal (fvgSignal) is returned on every wait candle
If no FVG is detected at all (always zero), wait timer is wasted.
4) Be aware of your backtesting environment
In some strategy testers, OnTick() runs multiple times per bar.
The candle timing and bar shifts might behave unexpectedly.
Consider adapting your code to run wait logic only once per newly closed candle (by tracking lastProcessedCandle) as above.
Minimal sample snippet to track breakout wait count properly per closed candle
Add near start of OnTick():
mql5
static datetime lastProcessedCandle = 0;
// Get current last closed candle time on swing timeframe (or your cooldown timeframe)
MqlRates lastClosedCandle[];
if(CopyRates(_Symbol, swingTF, 1, 1, lastClosedCandle) != 1)
{
Print("Failed to get last closed candle");
return;
}
datetime lastClosedCandleTime = lastClosedCandle[0].time;
if(lastClosedCandleTime != lastProcessedCandle)
{
lastProcessedCandle = lastClosedCandleTime;
if(breakoutDetected)
{
breakoutWaitCounter++;
if(breakoutWaitCounter > maxBreakoutWaitBars)
{
PrintFormat("Timeout reached at %s, resetting breakout", TimeToString(lastClosedCandleTime));
breakoutDetected = false;
breakoutDirection = 0;
breakoutWaitCounter = 0;
}
else
{
int fvgSignal = DetectFairValueGap(swingTF, 1);
PrintFormat("FVG signal %d at candle %s while waiting for breakout confirmation",
fvgSignal, TimeToString(lastClosedCandleTime));
// Your FVG check and trade entry logic here
}
}
}
else
{
// No new closed candle since last call, wait...
return;
}
Summary of recommendations
Add logic to run breakout wait and FVG checks only once per new closed candle.
Make sure wait counter only increments once per candle.
Make sure state reset only on timeout or successful entry, not prematurely.
Add debug prints logging the FVG detection results each wait candle.
Verify backtester or real-time context supports expected bar timings.
If you want…
I can help you add this candle-tick separation logic to your EA or provide a focused debug snippet.