// 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 provided EA script named Advanced_BoS_EA_MT5.mq5 appears quite comprehensive and well-structured. Here’s a summary of what it does and also some suggestions and considerations you might want to keep in mind:
Summary of the EA features:
Break of Structure (BoS) entries:
Buys on a break above the most recent swing high if price is above EMA (trend filter)
Sells on a break below the most recent swing low if price is below EMA
Optional reverse entry logic (enableReverseEntries): sell on swing high break, buy on swing low break.
Dynamic lot sizing:
Fixed lots or risk-percent-based lots based on stop loss distance
Capped by max risk per trade percent (maxRiskPerTradePercent)
Stop Loss/Take Profit:
Initial SL based on ATR multiplier (sl_atr_mult)
TP based on fixed risk-reward ratio (r2r_ratio)
Multiple Trailing Stop Modes:
None, Market Structure based, ATR based, or Hybrid (combination)
Trailing stop updates are throttled (TrailUpdateIntervalSec) and will only update after some time interval
Minimum SL buffer and trailing activation after some profit percent
Daily loss protection:
Tracks closed losses for the current day and stops trading when losses exceed a daily loss limit (maxDailyLossPercent)
Trade management:
Limits max simultaneous open positions (maxPositions)
Trade only allowed in a specified time window (tradeStartHour and tradeEndHour)
Handles multiple symbols and trade contexts via inpMagicNumber.
Your code looks mostly complete, but here are some notes, validations, and potential improvements:
__DATE__ is a compile-time macro, not the version string. Consider printing both version string and date.
swingTF is an enum - printing its integer value is okay, but consider adding a helper function to get string names for enums, for clearer logs.
2. Swing detection based on iHighest / iLowest
Your call for swing detection uses iHighest and iLowest with a lookback of swingLookback and swingTF timeframe. You then check the high or low of that bar.
Make sure the bars at index are valid and not out-of-range.
You fetch highestBar and lowestBar with:
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
Note: The last param start is 1, meaning from 1 bar ago (the last closed bar). This is probably correct to avoid fake signals from the current forming bar.
3. Tick time and synchronization
You use TimeCurrent() for daily loss resets and updates. This is good, but you might want to check if TimeTradeServer() or TimeLocal() is better for your broker context, especially if you want synchronization to broker’s day start.
4. Reverse entries logic — Check bid/ask usage
Within the reverse entries block, you have:
if(ask > lastSwingHigh && is_uptrend)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
... // open sell at bid price
}
}
else if(bid < lastSwingLow && is_downtrend)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
... // open buy at ask price
}
}
Note that you use the correct order prices for buys (ask) and sells (bid), which is good.
5. OrderSend with refilled MqlTradeRequest structure
But if new_sl already < (current_price - min_sl_dist), you increase it to current_price - min_sl_dist. This might never happen given how new_sl was computed. Just be sure this logic is consistent and tested in live data.
10. Performance considerations
Avoid continuous frequent ObjectSetDouble() calls for swing lines — only update when lines change.
Use optimized caching for swing highs and lows to avoid recalculating repeatedly.
11. OnInit returns no value — If critical initializations fail, consider return(INIT_FAILED);
Your current OnInit() just returns void. MQL5 expects int OnInit(), returning INIT_SUCCEEDED or INIT_FAILED.
Same with OnDeinit().
12. Safety buffers on SL/TP
You may want to ensure SL/TP distance respects minimum contract/comission/spread and isn’t too tight.
13. An example missing:
You do not show any code for modifying nested positions with the same symbol/magic number — currently code seems OK to handle single max position.
Conclusion:
Your EA is very advanced and appears highly functional as-is. If you want I can help you:
Write specific helper functions
Implement additional features
Optimize or refactor
Add detailed comments
Just ask!
If you have any question, want code adjustments, or face specific errors, please share your question.
Certainly! Here is a professional, detailed, and comprehensive description suitable for publishing your Advanced_BoS_EA_MT5 on the MQL5 Market. It highlights the features, settings, trading logic, risk management, and unique advantages of your EA to help users understand its capabilities and usage.
Advanced_BoS_EA_MT5 — Break Of Structure Expert Advisor with Dynamic Risk Management and Trailing Stops
The Advanced_BoS_EA_MT5 is a powerful, fully automated Expert Advisor designed for MetaTrader 5 that trades breakouts of key market structure levels (swing highs and lows) with built-in dynamic lot sizing, multiple trailing stop modes, advanced risk management, and safety buffers to maximize profitability while protecting your capital.
This EA applies professional-grade concepts such as trend filtering via EMA, volatility-based stops via ATR, and flexible trailing stops based on market structure, ATR, or their combination. It is intended for medium-term swing trading on multiple symbols and timeframes.
Key Features
Break of Structure (BoS) Entry Logic
Swing High/Low Break Detection: Detects breakout of recent swing highs and lows based on user-configurable lookback periods and timeframe.
Trend Filter: Trades are only opened in the direction of the trend, filtered by EMA on a higher timeframe to improve trade quality.
Reverse Entry Mode: Optional reverse trading mode where buy/sell logic flips, allowing contrarian or mean-reversion strategies.
Dynamic Lot Sizing & Risk Management
Fixed Lot or Risk Percent: Choose between fixed lot size or dynamic fractional position sizing based on risk percentage of account balance.
Max Risk Per Trade: Caps lot size automatically to ensure risk per trade does not exceed user-defined maximum (percentage-based).
Daily Loss Limit: Prevents further trading if daily losses exceed a configurable percentage of the account balance to protect capital.
Stop Loss and Take Profit Management
ATR-based Stop Loss: Stop Loss is automatically calculated based on user-configurable ATR multiplier providing volatility-adjusted placement.
Risk-to-Reward Ratio: Take Profit is set dynamically relative to Stop Loss distance, adjustable using a risk-to-reward multiplier.
Safety Buffers: Ensures minimum stop distances and trailing buffers to avoid premature stop-outs caused by market noise.
Advanced Trailing Stops
Multiple Trailing Modes:
None: No trailing stop applied.
Market Structure: Trail SL based on dynamic swing highs and lows, adapting stops to recent price action.
ATR: Trail SL based on ATR volatility distance to lock profits while allowing normal market fluctuations.
Hybrid: Combines the above two methods for optimal stop placement.
Throttling Mechanism: Limits trailing SL updates to fixed intervals (default 15 seconds) to prevent excessive order modifications.
Trailing Activation: Trailing starts only after trades reach a configurable fraction of profit to avoid unnecessary early SL moves.
Additional Professional Features
Trading Time Window: Set specific trading hours to avoid low-liquidity periods or high-risk news events.
Maximum Open Positions: Limit concurrent trades per symbol or globally to reduce overexposure.
Magic Number Support: Allows running multiple instances independently on different symbols or strategies.
Visual Swing Lines: Draws and updates swing high/low levels on the chart for better market context visualization.
Robust Error Handling: Logs order sending errors, trade rejections, and internal alerts for easier debugging and monitoring.
Input Parameters
Parameter
Description
Default
Entry Settings
inpLot
Fixed lot size per trade
0.05
useRiskPercent
Use risk % for calculating lot size
false
riskPercent
Risk % per trade if enabled
1.0
sl_atr_mult
Stop Loss multiplier applied to ATR at trade entry
Bars lookback for trailing stop based on market structure
20
atr_trail_mult
ATR multiplier for trailing stop calculation
How It Works
Trend Check: The EA first checks if the current trend is bullish or bearish by comparing the closing price on a higher timeframe to the EMA.
Swing Detection: It scans swing highs and lows within the configured lookback period on your chosen swing timeframe.
Trade Entry:
In normal mode, it buys at a break above the last swing high if the trend is up, or sells at a break below the last swing low if the trend is down.
In reverse mode (optional), the logic is inverted.
Risk & Size Calculation: The stop loss is placed at a multiple of ATR away from entry price. Lot size is dynamically calculated to keep risk within user limits.
Take Profit Setting: TP is set according to your risk-reward ratio.
Trade Management: Positions are managed with trailing stops that adapt dynamically to price and volatility conditions, protecting accumulated profits.
Daily Loss Limit: If losses exceed the daily threshold, the EA suspends opening new trades until the next trading day.
Recommended Usage
Symbols: Major and minor currency pairs, indices, metals with good liquidity.
Timeframes: Ideal for M1, M5, M15 swing detection; EMA filtering on M15 or higher.
Broker Settings: Ensure adequate margin for dynamic lot sizing and spread/time filtering.
Adjust Parameters: Use the inputs to tune risk, trade timing, and trailing modes to your strategy preference.
Backtest First: Always validate on historical data before running live to find optimal settings.
Why Choose Advanced_BoS_EA_MT5?
Combines price action market structure with technical trend filters.
Implements adaptive and robust trailing stops preventing profit erosion.
Presents flexible risk management tools vital for prolonged trading survival.
Designed for hands-off swing trading with minimal parameter tuning.
Visualizes key levels for better trade transparency.
Includes safety features like max daily loss limits and throttled trailing stop calls.
Inputs and Parameter Summary
You can customize everything from trading hours, risk levels, trailing types, and entry logic to fit your preferences.
Installation
Copy the Advanced_BoS_EA_MT5.mq5 file into your MQL5/Experts folder.
Compile using MetaEditor.
Attach to any chart and configure input settings as needed.
Enable AutoTrading for live operation.
Support & Updates
For questions, feature requests or support, contact the author LucienWP via the MQL5 community messages or the provided support channels.
Disclaimer
Trading Forex and CFDs involves significant risk. Past performance is not indicative of future results. Use this EA responsibly with proper risk management.
License
This EA is provided under the terms specified by the MQL5 Market. Redistribution or resale without permission is prohibited.
This detailed description should offer your users a clear, professional understanding of your EA, helping build confidence and encouraging downloads or purchases.
If you want, I can help draft a shorter description, marketing bullet points, or even a tutorial article for your EA. Just ask!
means that the broker rejected your attempt to modify the stop loss for position #2 because the new stop loss is considered invalid.
Why "Invalid stops" error occurs in MT5?
For sell positions (short trades), the stop loss must be placed above the current price (and TP below the current price). For buy positions, the SL must be below the current price (and TP above).
Also, the SL and TP orders must respect the broker's minimum stop level distance from the current price. This minimal distance is usually defined by:
SYMBOL_TRADE_STOPS_LEVEL — minimal stop level in points
The minimal distance depends on broker’s symbol settings and spread.
If the SL or TP are set inside these minimal allowed distances, the modification fails with "Invalid stops".
Diagnosing your case (EURUSD sell):
Current SL: 1.21330
Trying to move to new SL values around 1.21240–1.21263
TP unchanged at 1.21165
If your current price (bid/ask) is approx near or above 1.21250-1.21300 region, then your attempted SL is likely too close below the price or not respecting broker's minimum stop level, or the stop loss is set incorrectly relative to the position.
Common causes & fixes:
1. Check correct SL placement for sell order
For a sell position:
SL must be above the entry price and current price
TP must be below the entry price and current price
If you try to set SL below current price for sell, the broker will reject it.
In your log:
New SL attempts like 1.21242, 1.21244, 1.21253, etc.
Compare it to current price — if current ask or bid is lower than new SL, stop loss is valid.
If new SL is below current bid price (for sell position), it is invalid.
Confirm the price comparisons in the EA code before sending requests.
2. Check minimum stop level
You must ensure SL/TP distances respect the broker’s minimum stop level. Fetch this using:
Make sure SL and TP are not too close or crossing over each other.
For a Sell:
SL > entry price
TP < entry price
SL > TP (not crossing over)
5. Verify trailing SL logic
Your trailing stop update code may sometimes calculate an invalid SL, e.g., moving SL below current price for sell. Strengthen your code logical tests.
For example, in UpdateTrailingStopByMarketStructure() or the ATR trailing functions for sell:
Confirm your SL for sell is above current price and TP below.
Ensure SL and TP respect minimal allowed distance (SYMBOL_TRADE_STOPS_LEVEL).
Normalize SL/TP prices correctly.
Add validation checks in trailing stop updates.
Avoid setting SL too close to price or inside spread limits.
If you want, I can help you modify your trailing stop functions or your SL/TP placement logic to include these validations and ensure compatibility with hedging mode and broker rules.
Feel free to share your trailing update related snippets if you'd like me to patch them!