// New input for reverse entry logic
input bool enableReverseEntries = false; // Reverse trade entry logic (Sell on swing high break, Buy on swing low break)
// New inputs for max risk and daily loss limits
input double maxRiskPerTradePercent = 1.0; // Max risk per trade as % of account balance
input double maxDailyLossPercent = 2.0; // Max daily loss as % of account balance
CTrade trade;
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
//+------------------------------------------------------------------+
// Resets daily loss tracking at start of each new day
void ResetDailyLossIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm {};
TimeToStruct(now, tm);
//+------------------------------------------------------------------+
// Update daily loss as sum of closed negative trades for current day & symbol
void UpdateDailyLoss()
{
datetime dayStart = dailyLossResetTime;
datetime dayEnd = dayStart + 86400; // Next day
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 EA code looks quite comprehensive and well-structured for a Break Of Structure strategy with dynamic position sizing, trailing stops, and risk controls. Here are some general comments, suggestions, and considerations for improvement, correctness, and maintainability:
1. Initialization: OnInit()
You're using shifting indices correctly (highestBar and lowestBar have +1 in OnTick to avoid using the current forming bar).
You correctly handle indicator handle creation and release.
Swing high/low horizontal lines as visual aids are a nice touch.
2. Daily Loss Tracking
You reset daily loss on new daily bars using ResetDailyLossIfNewDay().
UpdateDailyLoss() sums negative closed deals with your Magic number and symbol during the day.
You then use IsDailyLossExceeded() to block new trades if the loss exceeds limit.
Potential Improvement:
Make sure your platform runs the EA continuously, or reset triggers might be missed if the EA is started mid-day.
Instead of relying purely on TimeCurrent(), consider synchronizing with the server day boundary carefully. Currently, you initialize dailyLossResetTime=0 in OnInit(). If the EA is restarted later than midnight, daily loss starts from 0 regardless (could be desired behavior).
3. Lot Size Calculation
Good use of symbol properties including SYMBOL_VOLUME_STEP, SYMBOL_VOLUME_MIN/MAX.
The calculation for risk percent takes proper account of tick value, tick size, contract size.
You cap lot sizes by maxRiskPerTradePercent * balance to respect risk limits.
Potential Issue:
You use riskPercent input separately from maxRiskPerTradePercent, but your CalculateLotSize() code only uses maxRiskPerTradePercent for capping, while riskPercent controls the risk calculation if useRiskPercent is enabled.
Make sure users understand the difference between these two inputs (riskPercent for the formula, maxRiskPerTradePercent as hard cap).
4. Position Management
You handle max positions open correctly.
You ensure only positions with your magic and symbol are considered.
Checking if position of a given type is open uses a proper loop.
5. Swing High/Low Detection and Entry
Swing detection uses highest high and lowest low for given lookback on your chosen swing timeframe.
Entry check: Price breaking last SwingHigh/Low on the swing timeframe + EMA trend filter on a higher timeframe to ensure trades with trend.
Correct bid/ask usage for buy/sell entries.
Potential Bug:
For reversed entries, you send order at bid price for BUY and ask price for SELL. While mostly fine, usually BUY orders are placed at ask, SELL at bid. In your enableReverseEntries == true section:
mql5
if(ask > lastSwingHigh && is_uptrend)
{
// Reverse sells - but sends order at bid price for sell: Correct for SELL.
}
else if(bid < lastSwingLow && is_downtrend)
{
// Reverse buys - sends order with ask price for buy: Correct for BUY.
}
So this seems consistent.
6. Trailing Stop Logic
You have 3 modes: MarketStructure, ATR, Hybrid trailing.
Throttling trailing stop update frequency through TrailUpdateIntervalSec to reduce unnecessary request spam.
Combining ATR and market structure trailing in hybrid mode is smart.
Small notes:
In hybrid trailing, initial_sl_dist calculation uses (entry_price - sl) for buy positions, which could be negative if SL not set properly. You handle fallback, but add checks if SL == 0?
TrailingProfitTriggerPerc is a good safeguard to prevent trailing before a minimum profit is reached.
Consider additional logging for when trailing is skipped due to throttling — could help debugging.
7. Chart Objects
Use of horizontal lines to mark swing high/low looks good.
However, in OnDeinit you delete the lines safely.
One suggestion: update the objects only on new swing detected, not every tick — minor optimization.
8. Error Handling & Logging
You check important returns and print error codes frequently which is excellent.
Consider adding a #define DEBUG macro or input parameter to control verbosity.
9. Miscellaneous suggestions
Timeframe Consistency:
Trailing stop calculation uses PERIOD_CURRENT for swing lookback in market structure trailing (e.g. iLowest(symbol, PERIOD_CURRENT, ...)), but you use swingTF for swing detection in entries. You might want to keep them consistent or link via inputs.
Fix the OrderSend usage: OrderSend() returns bool, but actual error can be GetLastError() or MqlTradeResult.retcode. You do that well, but you might want to log or handle specific retcodes explicitly (e.g., requotes, trade context busy).
Multiple Positions Handling:
Currently supports maxPositions > 0 but does not differentiate on trade types/hedging. If you plan to support multiple positions, consider tracking positions differently.
Code Efficiency:
Consider caching arrays of positions per tick once (e.g., save position tickets matching your magic and symbol), then loop over trailing updates from this cached array to minimize calls.
10. A small Possible bug in Market Structure trailing SL update:
In UpdateTrailingStopByMarketStructure() for SELL positions:
half_tp_level will be between entry price and TP (lower for a sell).
If ask > half_tp_level you do not update trailing. Is that correct logic?
Logic says: only update trailing stop when price moved at least halfway towards TP.
This matches the trailingProfitTriggerPerc concept, but note it's hardcoded as 0.5 here and separately as an input elsewhere.
You might want to unify trailing activation thresholds to avoid inconsistent behavior.
Summary
Your EA is very solid and feature rich! The key points:
Keep careful synchronization for daily loss reset, ensure EA runs or is restarted daily.
Check risk parameters usage and clarify distinction between riskPercent and maxRiskPerTradePercent.
Confirm trailing stop update activation logic and harmonize thresholds.
Optimize repetitive tasks and clarify timeframe usage for swing and trailing.
Consider additional debug logs and possibly resilience against order send errors.
If you want help with specific parts (e.g., adding features, fixing bugs, optimizing performance), just ask! Great job building this advanced BoS EA!
Great question! The EMA trend filter in your EA code is used as a direction filter to decide if the market is in an uptrend or downtrend before placing trades. It helps the EA avoid trading against the trend, increasing the chance to take trades in the direction of the prevailing market momentum.
The iMA (moving average) function creates a handle for the EMA indicator on your specified symbol and maTimeframe (e.g., M15), with period maPeriod (e.g., 50), using the close price.
This handle is reused to obtain EMA values anytime during the EA operation.
CopyBuffer copies the latest EMA value (buffer 0) from the EMA indicator handle.
ma_buf[0] now contains the latest EMA value shifted back by 1 bar (or maybe the current bar depending on your indexing, in your case it seems you want bar 1).
Determining Market Trend Using EMA and Price on Higher Timeframe
The price_htf is the close price of the previous candle (index 1) on the EMA timeframe (maTimeframe), for the same symbol.
If the close price > EMA → uptrend.
If the close price < EMA → downtrend.
Using the Trend Filter for Trade Entries
mql5
// Regular (non-reverse) entry logic example:
if(ask > lastSwingHigh && is_uptrend)
{
// Place buy order
}
else if(bid < lastSwingLow && is_downtrend)
{
// Place sell order
}
EA takes buy trades only when the price broke above recent swing high and trend is up according to EMA.
EA takes sell trades only when the price broke below recent swing low and trend is down according to EMA.
This ensures trades go with the trend defined by price vs EMA.
Summary
Step
Explanation
Create EMA handle
Set up EMA indicator on chosen timeframe.
Copy EMA value on tick
Get latest EMA value at each tick.
Fetch price at same HTF close
Get recent close price at the EMA timeframe.
Compare price with EMA
Price above EMA → uptrend, price below → downtrend.
Filter trades by trend
Only enter buy if trending up, sell if trending down.
Why EMA Trend Filter Helps
Avoids counter-trend trades i.e. trades against momentum.
Filters out false breakouts when the trend does not support the trade direction.
Can improve performance by catching moves with higher probability.
Important Notes:
maTimeframe (default PERIOD_M15) typically higher than your swing detection timeframe (PERIOD_M1) — i.e., trend filter is from a higher timeframe.
You look at bar 1 on maTimeframe (previous closed bar), not bar 0 (current forming bar) to avoid signals on incomplete data.
EMA period maPeriod=50 is a common mid-length filter to define medium-term trend.
If you want, I can provide a concise code snippet or explanation on how to change/filter the timeframe or EMA period to adjust trend sensitivity. Just ask!