// --- 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
// *** 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 provided MQL5 expert advisor code appears to be a fairly advanced Break of Structure (BoS) strategy EA that includes:
Multiple EMA trend filters on different timeframes.
ATR-based stop loss and take profit calculation.
ADX filter to trade only in trending markets.
Losing streak filter to pause trading after X consecutive losing trades.
Post-close cooldown on opening new trades.
Additional cooldowns to space trades by candle and by time interval.
Floating risk cap: closes existing positions if floating loss exceeds a set % of balance.
Trailing stop loss implemented with several modes (Market Structure, ATR, Hybrid).
Optional reversed entries (counter-trend trades).
Your question is not explicitly stated, so I'll assume you either want:
Code review or explanation.
Suggestions or improvements.
Validation of correctness or potential bugs.
Help integrating/fixing something.
How to compile or run.
Summary & review notes:
Initialization and indicators:
The code initializes 3 EMAs on M15, ATR on M5, and ADX on M15 with proper handle checks, releasing on error.
Cooldown logic:
postCloseCooldownSeconds disables opening new trades if recent closed positions within cooldown seconds.
Candle cooldown (lastTradeCandleTime vs last closed candle time).
Time interval cooldown (lastTradeOpenTime vs now).
Loss streak logic:
It tracks recent closed deals, checks their profit, increments g_currentLosingStreak on losses, resets on wins.
Is reset daily via ResetLosingStreakIfNewDay().
Floating risk cap:
Loops open positions, closes if loss exceeds max risk % of balance.
Trailing stops:
Three modes implemented, with timers to avoid over-updating.
Trade conditions:
Uptrend: MA1 > MA2 > MA3 && ask > MA2
Downtrend: MA1 < MA2 < MA3 && ask < MA2
Buys when price breaks last swing high in uptrend.
User
tell me more about Reverse mode
Assistant
Certainly! The Reverse mode in your EA is essentially designed to open trades against the prevailing trend conditions and Break of Structure signals that the EA normally uses. It’s a kind of contrarian or counter-trend mode which can be useful in certain market conditions (e.g., reversals, choppy markets) or as part of your strategy preferences.
How Reverse Mode works in your EA code
In your EA, enableReverseEntries is a boolean input:
mql5
input bool enableReverseEntries = true;
When enableReverseEntries == false, the EA enters trades conforming to the standard trend/direction and Break of Structure:
Buy if price breaks above last swing high AND trend is up.
Sell if price breaks below last swing low AND trend is down.
When enableReverseEntries == true, the logic flips:
Sell if price breaks above last swing high AND trend is down.
Buy if price breaks below last swing low AND trend is up.
Relevant code snippet from OnTick():
mql5
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
// Place a BUY order...
}
else if(bid < lastSwingLow && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
// Place a SELL order...
}
}
else
{
if(ask > lastSwingHigh && is_downtrend && !IsPositionOpen(POSITION_TYPE_SELL))
{
// Reverse mode SELL on break of swing high but trend DOWN
}
else if(bid < lastSwingLow && is_uptrend && !IsPositionOpen(POSITION_TYPE_BUY))
{
// Reverse mode BUY on break of swing low but trend UP
}
}
Interpretations of this reverse logic:
Normal mode:
User
(contrary to trend being down???
Assistant
Good catch! Let me clarify this because that phrasing could easily confuse.
What I meant by "contrary to trend being down" in the reverse mode context:
Suppose the trend is down (i.e., your MA conditions indicate a downtrend):
In normal mode, you only sell on breaks below swing lows (which aligns with the downtrend), and you don't buy at all.
In reverse mode, when price breaks above the last swing high, but the trend is down:
Instead of ignoring this or waiting for trend continuation, your EA sells (opens a SELL order) at that breakout above swing high, even though the trend is down and price broke higher.
Let's visualize it with an example:
Trend = down (MAs aligned downward).
Price manages to break above last swing high (which often suggests bullish strength).
Normal mode:
This breakout "above swing high" in a downtrend is usually ignored—no position opened here.
Reverse mode:
Your EA interprets this break above swing high in a downtrend as an opportunity to enter a SELL position. In other words, it bets on price reversing back down after the breakout, thus entering against the breakout and trend continuation.
In simpler words:
When trend is down but price breaks above swing high, reverse mode says:
"This might be a false breakout or a retracement—let's SELL here expecting price to resume the downtrend."
Why it looked confusing to say "contrary to trend being down"?
Because the normal expectation is to buy when price moves above resistance, but trend is down—so this is a counter-trend entry.
Reverse mode uses breakouts that go against the trend to signal entry against price action breakout direction (hence "contrary").
Full picture for reverse mode:
Market Trend
Price Break
Action (Reverse mode)
Explanation
Downtrend
Breaks above swing high
SELL
Enter expecting rejection of breakout
User
let say trend = down (MAs aligned downward).
Price manages to break above last swing high, what means to me, overall trend (m15) is down (bearish) and if Price manages to break above last swing high, this is sweep of liquidity for me,
Assistant
Exactly! Your interpretation is correct and aligns well with a common institutional order flow concept called "liquidity sweep" or "stop hunt" before continuation of the main trend.
Let's break it down carefully:
Trend (on M15) is down → means the bigger bias is bearish.
Price breaks above the last swing high → this "breakout above resistance" looks like a temporary move against the main downtrend.
This breakout is often a liquidity sweep — it triggers stops of shorts above the swing high, potential buy stops, and traps retail traders into thinking the trend reversed.
Institutions or Smart Money may push price above swing high momentarily to gather liquidity before resuming the downtrend.
How Reverse Mode relates to this:
In your EA's reverse mode, this break above swing high in a downtrend is interpreted as an entry point for a SELL!
The EA expects price to complete the liquidity sweep (stop hunt).
Price will likely fail to sustain above that level, leading to a reversal back down continuing the downtrend.
Why is this useful?
Your EA tries to enter short positions right after liquidity sweeps, catching the move back down.
Example:
On chart (bearish trend):
code
|
Swing High ----- Price breaks above this (liquidity sweep)
|
|___ <-- after the sweep, price reverses downward again
Your EA reverse mode would open a SELL right after that break above swing high (when ask > lastSwingHigh and is_downtrend == true), assuming the move up was a liquidity grab.
This matches your description:
"... overall trend (M15) is down (bearish)... Price manages to break above last swing high, this is sweep of liquidity for me..."
The Reverse mode captures exactly this logic — entering against the breakout as a short entry anticipating continuation of the primary downtrend once the sweep ends.
Important notes / considerations:
Timing is key: the EA enters only after of break (ask price broke last swing high) within the defined cooldown and filters.
User
how to improve this entry mode?
Assistant
Great question! Improving reverse mode entries based on liquidity sweeps (breaks of swing highs/lows against trend) involves adding additional filters and conditions that:
Confirm the strength/validity of the sweep,
Reduce false signals/fake breakouts,
Optimize entry timing,
And manage risk tightly.
Here are practical improvements you can incorporate into your EA to make reverse mode entries (like shorting a liquidity sweep in a downtrend) more effective:
1. Confirmation with Momentum / Volume Indicators
Volume confirmation:
Check if volume spikes during the breakout candle or immediately after. Large volume on the breakout followed by exhaustion (decreasing volume) can signal a liquidity grab.
Momentum indicators:
Use RSI, Stochastic, or even an oscillator divergence to detect weakening momentum at the breakout.
Example: Only enter reverse when the RSI/Stochastic indicates overbought (for a liquidity sweep above swing high when trend is down).
Use ADX trend filtering more dynamically:
For reverse mode, perhaps enter only when ADX is moderate (not too strong trend), indicating possible retracement or setup for reversal after sweep.
2. Price Action Patterns & Candle Analysis
Rejection candle at breakout:
Wait for a strong wick (shadow) above the swing high candle (a pin bar or shooting star) that indicates rejection after the sweep.
Multiple attempts & failed closes:
Price breaks the swing high intrabar / temporarily, but closes back below the swing high level. This rejection is stronger signal.
Implement a "confirmation candle" logic: wait for a candle close back below the swing high after the breakout candle before entering short.
3. Use Multiple Timeframe Confluence
Confirm the liquidity sweep is visible or meaningful on multiple timeframes, e.g., M15 (trend) + M5 or M1 (entry).
For example:
M15 trend is down and break above last swing high occurs.
Check on M5 or M1 for reversal bars, bearish engulfing, or pin bars near the level.
This helps filter noise and find better timed entries.
4. Refined Entry Placement: Limit / Stop Orders near the Swing High
User
im thinking something about candle close?
Assistant
Great! Using candle close confirmation is an excellent way to improve the reliability of your reverse mode entries, especially for trading liquidity sweeps or breakouts against the trend.
Why confirm with candle close?
Price can spike above/below levels intrabar but close on the other side, which is often a fake breakout.
Waiting for a candle close confirms that the breakout level was indeed broken and price accepted at that level.
For reverse mode entries (betting on rejection of the breakout), waiting for the next candle’s close back below (for longs) or above (for shorts) the breakout level helps reduce false signals and triggers entries on confirmed rejection.
How to apply candle close confirmation in your reverse mode logic?
Given your example scenario:
Trend = down (MAs aligned downward)
Price breaks above last swing high (liquidity sweep)
Instead of entering immediately when ask > lastSwingHigh, add this confirmation step:
Detect breakout candle: a candle closes with high above last swing high (breakout occurs).
Wait for a confirmation candle that closes back below last swing high.
Only enter a SELL when the confirmation candle has closed.
Why this helps:
You avoid entering immediately on a weak or spurious breakout.
You catch the actual rejection of breakout level by price failing to hold above it.
Certainly! Below is a demonstration of how you can incorporate candle close confirmation logic for your reverse mode entries into your existing OnTick() function.
Key points in this implementation:
Detect breakout candle close above last swing high (downtrend + reverse sell).
Wait for a confirmation candle to close back below last swing high.
Only after confirmation candle close, submit the SELL order.
Similar logic can be applied for reverse BUY entries (uptrend + break below last swing low + confirmation candle closing above swing low).
The state is stored per symbol and reset after trade or timeout.
Step 1: Add global state variables at the top of your .mq5 file
Step 2: Implement confirmation logic inside your OnTick() just before placing reverse entries
Here I wrap the reverse entry in wait-for-confirmation logic:
mql5
User
can you create complete code?
Assistant
Certainly! Below is a complete, minimal example EA code based on your original EA’s key parts plus the reverse mode with candle close confirmation logic integrated** as requested.**
This example includes:
Initialization of indicators (EMAs, ATR)
OnTick() with your filters, cooldowns, and trade logic
Reverse Mode enhanced with candle close confirmation before entry
Simplified for clarity, but you can blend this logic back into your full original EA.
mql5
User
2025.05.09 17:58:18 Reverse Sell opened @ 20060.80000 lot 0.20 SL 20109.28000 TP 19963.84000
2025.05.12 01:00:38 Closing position 4 as floating loss reached 610.10 (cap is 98.98)
2025.05.12 01:00:39 failed market buy 0.2 USTEC.p, close #4 sell 0.2 USTEC.p 20060.80 [Market closed]
2025.05.12 01:00:39 CTrade::OrderSend: market buy 0.20 position #4 USTEC.p [market closed]
Assistant
The logs show your EA opened a reverse sell position successfully:
code
2025.05.09 17:58:18 Reverse Sell opened @ 20060.80000 lot 0.20 SL 20109.28000 TP 19963.84000
But then later, your EA attempted to close that position due to floating loss exceeding the risk cap:
code
2025.05.12 01:00:38 Closing position 4 as floating loss reached 610.10 (cap is 98.98)
Immediately after this, the EA tried to open a reversing buy to close/offset the sell:
datetime session_start, session_end;
if(!SymbolInfoSessionTrade(_Symbol, DAY_OF_WEEK(now), 0, session_start, session_end))
{
// unable to get session - safest to prevent trading
return false;
}
if(now < session_start || now > session_end)
return false;
return true;
User
even if i had a stop loss, price exploded, and didnt close trade at my stop loss
Assistant
What you describe—your trade not closing at the stop loss despite having an SL set—can occur due to several reasons, especially during sharp, explosive price movements (commonly called slippage or gap moves). Here’s a detailed explanation and suggestions:
Why Stop Loss Might Not Close the Trade Exactly When Price Hits SL
Market Gaps / Fast price moves (Slippage)
If the market price moves very sharply (e.g., during news, after-hours, or low liquidity) it can "gap" over your stop loss price. Since MT5 does not guarantee execution at the exact SL price but at the next available market price, your position might close at a worse price or even remain open temporarily if no liquidity is available at or better than your SL price.
Broker Execution Model
Some brokers use market execution and slips or requotes are possible, especially during high volatility or news events. Delays may cause your SL order to be rejected or executed at a worse level.
Trading hours and instrument restrictions
If price hits your SL outside of trading hours or during illiquid periods, the stop may only get triggered when the market reopens, possibly at a worse price.
Partial fills or insufficient liquidity
If the volume at the stop level isn't available, it can cause slippage or partial fills.
Server or connection delays
Latency or server issues can cause delayed SL triggers.
How to Better Handle / Minimize This Risk
1. Use Stop Orders Instead of Guaranteed SL
Your EA uses SL via MqlTradeRequest.sl, which sends stop loss as part of position (soft SL). These SLs are typically stop loss market orders managed by broker, not guaranteed stop loss orders.
Solution:
If broker supports guaranteed stop loss orders (GSLO), use those — some brokers offer guaranteed SL at a set premium.
Otherwise, implement a protective logic to detect adverse move on price and manually close positions (see below).
2. Implement Manual Stop Loss via OnTick Protection
Example:
Continuously monitor open orders.
If price moves beyond your SL price by a certain buffer, send manual close request.
This can help catch cases where SL didn't execute.
mql5
User
why market structure trail stop not working?
Assistant
When your Market Structure trailing stop (MS trailing stop) is not working, it usually means the conditions or the logic that trigger the update and send the modification request are not met, or the order to update SL is failing silently or with errors. Let’s systematically check common causes and how your code's MS trailing stop logic works.
Quick Recap: How Your Market Structure Trailing Stop Works
It finds a recent swing low (for buy) or swing high (for sell) over a lookback (ms_swingLookback).
It calculates a new SL slightly below (buy) or above (sell) that swing point with a buffer (2 * point).
It checks if the new SL is an improvement over the existing SL (new_sl > current_sl && new_sl < entry_price for buy).
If conditions are met, it sends a TRADE_ACTION_SLTP request to modify SL.
It throttles updates with CanUpdateTrailing() using TrailUpdateIntervalSec.
Common reasons MS trailing stop doesn't work and how to debug:
1. Trailing update frequency blocked by cooldown (TrailUpdateIntervalSec)
Your code prevents updates if the last update was within TrailUpdateIntervalSec seconds to avoid hammering the broker.
Check:
Is your EA skipping the update due to this?
Add a Print() inside CanUpdateTrailing() when it blocks an update to verify:
mql5
if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec)
{
PrintFormat("Trailing SL update skipped for position %I64d due to interval cooldown", ticket);
return false;
}
2. No valid recent swing low/high found (iLowest or iHighest returns -1)
iLowest or iHighest call might return -1 indicating no data.
Confirm your ms_swingLookback is appropriate and there is enough history.
Sells when price breaks last swing low in downtrend.
Reverse mode optionally reverses entry rules.
Order sending uses MqlTradeRequest/Result with rejections handled.
Potential suggestions:
UpdateLosingStreak() behavior:
g_currentLosingStreak increments each time a loss is found, but it never resets during the loop for multiple trades. It resets on wins.
This means if a lost trade happened 3 closed trades ago, and then last 2 were wins, the losing streak still counts the old losses cumulatively.
Usually losing streak means consecutive losses. You could enhance this by:
mql5
void UpdateLosingStreak()
{
datetime now = TimeCurrent();
if(!HistorySelect(now - 86400, now))
{
Print("HistorySelect failed");
return;
}
// Reverse iterate deals newest to oldest for consecutive loss calculation
int total = HistoryDealsTotal();
int streak = 0;
for (int i = total - 1; i >= 0; i--)
{
ulong ticket = HistoryDealGetTicket(i);
datetime closeTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(closeTime <= g_lastHistoryTickTime)
break; // Older deals processed
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
if(symbol != _Symbol || magic != inpMagicNumber)
continue;
long entryType = HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(entryType != DEAL_ENTRY_OUT)
continue;
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
streak++;
else
break; // winning trade breaks streak
}
g_currentLosingStreak = streak;
g_lastHistoryTickTime = (ulong)now;
PrintFormat("Updated losing streak to %d", g_currentLosingStreak);
}
Trailing Stop updates timing:
This is very well handled with your g_trailingUpdateInfo[] and cooldown per position updates.
Risk calculation in CalculateLotSize():
Using tick_value, tick_size is OK but be mindful these depend on broker symbol definition, might want to validate their values carefully.
Use of CopyRates() with 1,1 means get one candle starting at shift=1 - a closed candle.
OrderSend() dev=10 might be too tight, consider adjustable or larger for volatile pairs.
**You use HistorySelect() with now - seconds — remember on live charts that history might not be fully available; you could implement fallback or error handling.
If you want me to add something or fix a bug, or improve performance or provide suggestions on trading logic or place missing feature let me know.
What is missing or could be added?
More checks for open positions per type or aggregated volume instead of count?
Partial closes on floating risk?
More granular trailing stop options?
Break-even stop method?
Error-retry trade execution?
Final notes:
This is a fairly solid base expert advisor with many practical considerations for live trading safety.
If you want compilation instructions:
Save as .mq5 file, compile in MetaEditor for MetaTrader 5.
Attach to chart of desired symbol.
Ensure history data is downloaded for all used timeframes (M1, M5, M15).
If you want me to write or modify specific function(s) or explain a part more deeply, just ask!
If price breaks the last swing high → you look to buy (trend is up).
If price breaks the last swing low → you sell (trend is down).
Reverse mode:
If price breaks the last swing high → you sell (contrary to trend being down).
If price breaks the last swing low → you buy (contrary to trend being up).
This means the EA anticipates the break of structure to be a false breakout or a reversal point, entering trades which expect the price to reverse again after the breakout.
Why use Reverse mode?
It can perform better in ranging or low-volatility markets where trend-following signals produce frequent false breakouts.
It aims to catch pullbacks or reversals rather than trend continuation.
When combined with filters like ADX, it might avoid trading in strong trend and only apply reverse entries when ADX is low (since your EA only allows trading based on ADX threshold).
Things to consider with Reverse Mode:
Confirm with other filters: Reverse trades have higher risk without strong confirmation; ADX filter still applies (your EA disables trading if ADX < threshold, which should limit bad signals).
Trailing Stops and exit logic: Since reverse entries are counter-trend, the risk of stop out may be higher — trailing stops in your EA might help reduce losses on these trades.
Position sizing and risk management: Particularly important in reverse mode; be mindful of drawdown.
Backtesting: Always backtest both modes under various market conditions.
How to toggle Reverse Mode:
Via Inputs tab in the EA attached to the chart, set enableReverseEntries to true or false.
When false → normal trend-following logic.
When true → reverse entry logic as above.
Summary:
Condition
Normal Mode Entry
Reverse Mode Entry
Price > swingHigh & Uptrend
Buy
(No trade / Sell if Downtrend)
Price > swingHigh & Downtrend
(No trade)
Sell (Reverse)
Price < swingLow & Downtrend
Sell
(No trade / Buy if Uptrend)
Price < swingLow & Uptrend
(No trade)
Buy (Reverse)
If you want me to help you improve or add more logic for reverse mode, like better filters, partial close, or different SL/TP approach, feel free to ask!
Downtrend
Breaks below swing low
(no trade)
No signal
Uptrend
Breaks below swing low
BUY
Enter expecting rejection of breakout
Uptrend
Breaks above swing high
(no trade)
No signal
Summary:
Reverse mode trades against the breakout direction relative to the trend.
It tries to catch reversals or false breakouts by opening positions contrary to the breakout move.
This can be useful in ranging or choppy markets but carries risk if breakouts are genuine trend continuation.
If this still seems unclear or if you want, I can illustrate with a chart example or add precise comments in your code snippet. Would that help?
confirmation
Risk management: Because you enter against a temporary breakout, SL placement is critical (usually just above the swing high or a factor of ATR).
Filtering with ADX and losing streak limits helps reduce getting stopped by fake reversals or choppy action.
Summary
Scenario
EA Action (Reverse Mode)
M15 downtrend + price breaks above last swing high (liquidity sweep)
Enter SELL expecting reversal and trend continuation down
If you want, I can help you customize your EA further to refine stop loss, entry timing, or add additional confirmation (volume, price action patterns) around these liquidity sweeps to improve accuracy!
Instead of market orders immediately on breakout, place sell limit orders slightly below the swing high or the high of the breakout candle to catch retracement down.
Alternatively, use stop orders just below a confirmation candle low, or break of low after sweep.
This can avoid entering too early before the reversal starts.
5. Tighten Stop Loss and Adjust Take Profit
Place stop loss just above the swing high or the high of the sweep candle with a small buffer (1-2 ATR points or spread).
TP can be at recent support or based on risk-reward ratio (e.g., TP = 1.5x or 2x SL).
Consider implementing break-even stops or partial profit taking when reversal move starts.
6. Candlestick Volume & Delta Volume
If available in your broker/wrapper, use volume delta (buy vs sell volume) to confirm exhaustion after breakout.
7. Optional: Add Order Flow or Tape Reading Data (more advanced)
This is more complex and requires special data access, but detecting large aggressive orders or stops hitting at swing highs adds confidence.
8. Time / Session Filters
Higher success of liquidity sweeps often occurs near session opens or news events:
Add time filters to focus on:
Market open periods (London open, NY open)
After significant volatility spikes or news
Practical Code-level improvements for your EA
Example: Adding confirmation candle close below swing high
mql5
// After detecting price broke above last swing high in downtrend
static bool breakout_detected = false;
static datetime breakout_time = 0;
double lastClose = iClose(_Symbol, swingTF, 0);
double lastHigh = lastSwingHigh;
// 1. Detect breakout candle (price breaks above swing high)
if(ask > lastHigh && is_downtrend)
{
breakout_detected = true;
breakout_time = TimeCurrent();
}
// 2. Wait for confirmation candle close back below swing high, within max wait time
if(breakout_detected)
{
if(lastClose < lastHigh)
{
// Confirmation candle detected: close below swing high after breakout
// Trade entry condition here
// Place sell order now
breakout_detected = false; // reset for next setup
}
else if(TimeCurrent() - breakout_time > 300) // e.g., max 5 min wait to confirm
{
// Timeout, no confirmation candle, reset
breakout_detected = false;
}
}
Example: Use RSI to filter entry (short only if RSI is overbought)
Reverse mode entries are inherently more challenging due to going against breakout momentum, so always backtest extensively on historic data and demo accounts.
If you want, I can help code or incorporate any of these into your existing EA!
Would you like me to help you implement a specific improvement?
// globals (or static in function)
static bool breakoutOccurred = false;
static datetime breakoutTime = 0;
// inside OnTick or OnTimer:
double lastSwingHigh = ...; // from your swing logic
double lastClose = iClose(_Symbol, swingTF, 0);
double prevClose = iClose(_Symbol, swingTF, 1);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
datetime now = TimeCurrent();
// 1) Detect breakout candle (candle close above last swing high)
if(!breakoutOccurred && prevClose <= lastSwingHigh && lastClose > lastSwingHigh)
{
breakoutOccurred = true;
breakoutTime = now;
Print("Breakout candle detected above swing high");
}
// 2) Wait for confirmation candle close below last swing high
// Assuming your timeframe candles close every e.g. 1 min, adapt as needed
if(breakoutOccurred)
{
// After breakout candle detected,
// wait for a candle that closes below last swing high
// Current candle close <= lastSwingHigh is confirmation of rejection
if(lastClose < lastSwingHigh)
{
// Confirmation candle closed below swing high
// Now enter SELL order (reverse mode entry)
Print("Confirmation candle closed below swing high. Enter SELL.");
// Place your order here...
breakoutOccurred = false; // reset flag for next setup
}
else
{
// Optional: add timeout so you don't wait forever
int maxWaitSeconds = 300; // 5 minutes
if(now - breakoutTime > maxWaitSeconds)
{
Print("Timeout waiting for confirmation candle, reset");
breakoutOccurred = false;
}
}
}
Important notes for integration:
You must properly detect closed candles — for M15 candle timeframe (swingTF), candle closes every 15 minutes.
Use CopyRates() or CopyOpen/High/Low/Close() as needed to access closed candle data (i.e., shift=1 is the last fully closed candle).
Modify accordingly if your tick timeframe is smaller.
Be careful to not use the current candle close as it’s still forming. Instead, use the last fully closed candle (shift=1).
Example to get shifted closed candle prices:
mql5
MqlRates rates[];
if(CopyRates(_Symbol, swingTF, 1, 2, rates) == 2)
{
double prevClose = rates[1].close; // fully closed candle before last
double lastClose = rates[0].close; // last closed candle (shift=1)
}
Applying to your EA:
In your existing OnTick(), integrate this logic before placing reverse entry:
Detect breakout candles closing above swing high (for downtrend).
Wait for confirmation candle closing back below swing high.
Only then send SELL order.
Similarly, handle the reverse for upside (uptrend + break below swing low → confirm close above swing low → BUY).
Copy this code into a new .mq5 file in MetaEditor.
Compile and attach it to a chart with sufficient history on the input Swing timeframe (default M1).
Watch the Logs for print messages about breakout detection and trade entries.
Adjust inputs and risk parameters as needed.
Explanation
This EA identifies trend by three EMA lines (your existing trend logic).
It detects liquidity sweeps via candle close above swing high (downtrend) or below swing low (uptrend).
Reverse entries wait for a confirmation candle closing back inside the previous price structure (below swing high or above swing low).
It enters trades only once confirmed, with SL/TP set by ATR multiple.
Position sizing uses your risk % or fixed lot input.
Positions opened if none exist of that type to keep max 1 open (you can extend to multi-positions logic).
State of breakout detection resets after entry / timeout.
Let me know if you want me to add normal trend-following entries, trailing stops, risk caps or other features from your original full EA integrated with this. Happy to help!
Then only send orders if CanTradeNow() returns true.
Implement retry logic
If the market is closed, you can either:
Skip the order and try again on next tick / OnTimer.
Buffer the order and execute once market is open.
Modify closing logic
When closing position, check if market is open before calling PositionClose() or OrderSend(). If market closed, skip and wait.
Log and alert
Keep logs so you can track attempts to trade off-hours, potentially alert you.
Example snippet to check trading time before order:
mql5
datetime now = TimeCurrent();
int day = DayOfWeek(now);
datetime session_start, session_end;
if(!SymbolInfoSessionTrade(_Symbol, day, 0, session_start, session_end))
{
Print("Failed to get session time, skip trading");
return;
}
if(now < session_start || now > session_end)
{
Print("Market closed, skipping trade");
return;
}
// Proceed to trade
Summary
Your EA is working correctly, but it tried to send a trade outside trading hours.
Add trading hours checks before closing or opening trades.
Optionally add retry or delay logic.
This will stop order send errors on "market closed."
If you want, I can help you write the exact snippet to integrate into your EA — just ask!
Call this function in every OnTick() after variable updates.
3. Avoid Trading Outside Main Market Hours
Gaps and explosions happen often outside active market hours or during news.
Your EA already has trading time filters; ensure they're strict to avoid trading near close.
Reduce/maximize your SL/TP to avoid close to market close.
4. Use Proper Slippage and Deviation Parameters in OrderSend
Your EA uses deviation=10 which is okay, but:
For fast volatile instruments, you might want to increase deviation slightly.
Or dynamically adjust depending on ATR or volatility.
5. Use Guaranteed Stop Loss Orders if Broker Supports
Check with your broker about guaranteed SL options.
Summary and Recommendations
Cause
Remedy / Check
Price gaps/skips SL level
Implement manual SL monitoring and close logic.
Broker market execution latency
Increase deviation, check broker execution type.
Trading off-hours or illiquid
Restrict trading time, avoid entries near close.
No guaranteed SL available
Use manual SL as a safety net
Final advice
Your EA already has solid SL logic and floating loss cap. Adding manual SL monitoring as shown will help catch missed stops during explosive price action.
Would you like me to generate a full snippet or integrate manual SL monitoring directly into your current EA code?
int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
PrintFormat("Lowest bar at shift %d", lowestBar);
if(lowestBar < 0)
return;
3. New SL validity check fails
For buys, new stop loss must be > current SL and < entry price.
For sells, new stop loss must be < current SL and > entry price.
If your swing low/high is not between these values, no update happens.
This condition may fail often if current SL is already tight or far from swing point.
4. Broker rejects SL update request
If OrderSend() fails or returns non-success retcode, trailing stop is not updated.
Check your error handling and print error codes.
You have:
mql5
if(!OrderSend(req, res))
PrintFormat("Failed to update trailing SL for position %I64d, error %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 moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
Verify you get any errors in logs.
5. Price and SL calculations related errors
Your buffer 2 * point might be insufficient or too large, causing new SL to be invalid.
NormalizeDouble() uses digits for precision — double check number of decimals corresponds to your symbol properly.
If point size or digits detection is wrong, SL values might be incorrect.
6. Current SL is zero or not set
Your code only updates SL if new_sl is better than current SL.
If current SL is zero/invalid or already close to swing low/high, no update occurs.
Sometimes initial SL is 0 if order was sent without SL or broker adjusted.
7. Position selection failure or symbol mismatch
Make sure your code calls PositionSelectByTicket() correctly before accessing position details.
Confirm position symbol and magic number filter passed.
Steps to diagnose and fix
Add debug prints everywhere possible in your trailing function, for example: