//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap (full, compile) |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.0"
#property strict
#include <Trade\Trade.mqh>
input double inpLot = 0.05;
input bool useRiskPercent = false;
input double riskPercent = 1.0; // Position risk % per trade
input int sl_atr_mult = 3;
input double r2r_ratio = 2.0;
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5;
input int atrPeriod = 14;
input int swingLookback = 20;
input ENUM_TIMEFRAMES swingTF = PERIOD_M1;
input int maPeriod = 50;
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15;
input int tradeStartHour = 7;
input int tradeEndHour = 22;
input int maxPositions = 1;
input uint inpMagicNumber = 123456;
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 for a Break of Structure strategy with a floating risk cap looks well structured and mostly complete. Here's a summary with some comments, improvements, and things to watch out for:
Overview
Uses ATR for ATR-based stops and trailing.
Uses EMA on a higher TF for trend filtering.
Detects Swing High/Low for breakouts (swingLookback + swingTF).
Implements several trailing stop modes including a hybrid one.
Applies a daily max loss limit and floating risk per trade (floating loss cap).
Supports reverse entries if enabled.
Limits max open positions.
Uses OrderSend with MqlTradeRequest for order placing and SL/TP updating.
Potential Improvements / Notes:
Check for Indicator Update Errors
In OnTick(), you call CopyBuffer for ma_handle and atr_handle. If CopyBuffer returns 0, you just return silently.
It would be helpful to add logs if one of these fails repeatedly, as that would indicate an initialization issue or an indicator problem.
mql5
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
Print("Failed to copy MA buffer");
return;
}
Magic Number Casting
You cast your input magic number inpMagicNumber to (long) before comparing with position magic:
Since Magic Number is usually a uint, make sure this casting is safe and keeps the number unchanged.
TrailingStopUpdate Frequency
You have a TrailUpdateIntervalSec to prevent excessive trailing SL updates. This is good for performance and broker compliance.
Trailing SL Conditions
In UpdateTrailingStopByMarketStructure, the logic to compare new SL with current SL and entry price looks robust.
Similarly, the ATR-based trailing SL uses the ATR multipliers and prevents too tight SL.
The hybrid stops effectively combine these.
User
i want to optimeze for best
Assistant
Optimizing your EA for best performance and profitability involves a combination of improving the algorithm logic, adding parameters for comprehensive strategy testing, and making sure the code runs efficiently without skipped or delayed signals. Here are detailed suggestions and actionable steps to optimize your Break of Structure EA:
1. Add More Inputs for Optimization
To fully optimize the strategy in the Strategy Tester, you want to expose key parameters like:
input int sl_atr_mult_min = 1;
input int sl_atr_mult_max = 5;
input double r2r_ratio_min = 1.0;
input double r2r_ratio_max = 4.0;
input int atrPeriod_min = 7;
input int atrPeriod_max = 21;
input int swingLookback_min = 5;
input int swingLookback_max = 40;
input int maPeriod_min = 20;
input int maPeriod_max = 200;
input int tradeStartHour_min = 0;
input int tradeStartHour_max = 12;
input int tradeEndHour_min = 12;
input int tradeEndHour_max = 24;
// And the rest similarly
Then in optimization runs, test these parameter ranges.
2. Use More Precise Entry Logic / Confirmation
Break of Structure (BoS) strategy can be enhanced by:
Waiting for candle close confirmation above/below swing high/low.
Using volume or momentum indicators (like RSI or MACD) as filter.
Confirm with additional conditions, like price closing above/below EMA on the current TF, not just HTF.
User
Trailing Stop inputs that are working together, best result optimizing together than one by one
Assistant
Great question! When optimizing trailing stop inputs, it’s crucial to optimize related parameters together instead of independently, because trailing logic parameters interact significantly and adjusting one in isolation often misrepresents the true optimal setting.
In your EA, the main trailing-related parameters are:
Parameter
Description
atr_trail_mult
ATR multiple distance for trailing stop
MinSLBufferATRMult
Min SL buffer multiplier based on ATR
TrailingProfitTriggerPerc
Profit % threshold (relative to SL distance) to start trailing
TrailUpdateIntervalSec
Minimum seconds between trailing updates
ms_swingLookback
Swing lookback bars for market structure trailing
Why Optimize These Together?
atr_trail_mult and MinSLBufferATRMult: Modify how far SL trails behind price, balancing early stop outs vs. maximizing profit capture.
TrailingProfitTriggerPerc: Determines how soon trailing begins after profit reaches some fraction of initial SL range.
ms_swingLookback: Defines how far back the trailing logic looks for market structure levels to adjust the SL.
TrailUpdateIntervalSec: Controls update frequency; too low may cause excessive order modifications, too high may cause lagging stops.
Changing any of these can affect whether your trailing SL tightens quickly or lags behind, and the interaction defines how profitable and stable the strategy behaves.
Recommended Approach for Joint Optimization
Define rational ranges for each parameter that avoid nonsense values:
Param
Min
Max
Step
Notes
atr_trail_mult
1.0
5.0
0.25
Lower → Tighter trailing SL
MinSLBufferATRMult
0.5
2.0
0.1
Buffer to prevent too-tight stops
User
Trailing Stop inputs that are working together, best result optimizing together than one by one, and for what mode marjetstructure, atr, hybrid
Assistant
Great question! Since your EA supports three different trailing stop modes — Market Structure (MS), ATR, and Hybrid — your trailing stop input parameters will have slightly different importance and interaction in each mode.
Trailing Stop Inputs in Your EA
Parameter
Applies to Mode(s)
Description
atr_trail_mult
ATR, Hybrid
ATR multiplier for trailing SL distance
MinSLBufferATRMult
ATR, Hybrid
Min buffer distance (ATR-based)
TrailingProfitTriggerPerc
ATR, Hybrid
How much profit % before trailing kicks in
ms_swingLookback
MS, Hybrid
Swing lookback bars for market structure trailing
TrailUpdateIntervalSec
All
Minimal seconds between trailing SL updates
How to Optimize Trailing Stop Inputs Together per Mode
1. Market Structure (MS) Mode
Key Parameters:
ms_swingLookback: controls how far back the trailing SL “pivot” (swing high/low) is calculated.
TrailingProfitTriggerPerc: trailing only activates after sufficient profit.
TrailUpdateIntervalSec: update frequency of trailing SL.
What matters most:
Proper swing lookback balances SL tightness and avoids frequent stop-outs.
Trailing trigger percent ensures trailing starts only after meaningful profit.
Update interval balances broker execution limits and SL responsiveness.
Optimization focus:
Optimize ms_swingLookback and TrailingProfitTriggerPerctogether to find the sweet spot between stop sensitivity and staying behind volatile market noise.
2. ATR Mode
Key Parameters:
atr_trail_mult: the core controlling the ATR multiplier distance for trailing SL.
MinSLBufferATRMult: minimum SL distance buffer based on ATR (avoids overly tight trailing).
User
if i activate hybrid trailing stop only bed results
Assistant
Thanks for sharing your experience! It’s not uncommon that the Hybrid trailing stop mode yields worse performance than using either pure Market Structure or pure ATR trailing independently — this often happens because:
Why Hybrid Trailing Can Underperform
1. Conflicting SL Adjustments
Hybrid mode picks the “best” (in your code, tighter) SL suggested by either:
Market Structure trailing SL (pivot-based), or
ATR-based trailing SL
When those two produce very different SL levels simultaneously, SL may jump back and forth or trail ineffectively.
This can cause trailing SL to move prematurely away from price or stay too loose, hurting profit capture or causing early stops.
2. Parameter Mismatch
Hybrid uses all parameters together: atr_trail_mult, MinSLBufferATRMult, ms_swingLookback, TrailingProfitTriggerPerc
If parameters suited for one mode (say, large ms_swingLookback for MS) conflict with different ATR trailing parameters, the hybrid’s “best SL” calculation may not be meaningful.
Mixed parameters create an ambiguous trailing zone.
3. Trailing Trigger Threshold
If TrailingProfitTriggerPerc is too high or too low, trailing might start prematurely (wrong side), or too late (missed locking in profits).
Hybrid mode’s logic can amplify this problem, as one trailing condition may activate sooner than the other.
4. Update Interval / Frequency
Hybrid SL updates often run more frequently as it tries to combine two SL logic sources.
This can hit broker limits or cause rejections, leading to stale trailing SL.
How to Fix / Improve Hybrid Trailing Results
Step 1: Parameter Harmonization
Find compatible parameter sets for MS and ATR parts before hybrid.
For example:
ms_swingLookback = 10-20 (instead of 30-50)
atr_trail_mult = 2.0-3.0
MinSLBufferATRMult = 1.0-1.3
User
let's say i backtest from january 1st 2023 to december 31th 2023, on a 10000 dollars prop firm account ( 4% daily loss, 8% overall los limits). result are 2000 dollars, 3% drawdown, that's not gona give a 5-10% monthly income
Assistant
You're raising a realistic concern about backtesting results and expected income, especially when trading under strict prop firm limits like a 4% daily loss and 8% overall loss limit. Let me break this down and offer some insights and practical paths forward.
Your Scenario Recap:
Account size: $10,000
Prop firm limits:
4% daily max loss (~$400)
8% overall max loss (~$800)
Backtest timeframe: Full year (Jan 1 2023 - Dec 31 2023)
Backtest result: $2,000 profit (~20%) with max drawdown of 3%
Your concern: 20% yearly profit (~1.6% per month) is less than desired 5-10% monthly income.
Key Points to Understand
1. Risk Limits Reduce Potential Return
Prop firm loss limits severely constraint how much you can risk per day and overall.
To avoid blowing the account or violating rules, you must trade conservatively.
Therefore, compounding rapidly (5-10% monthly) often isn’t realistic without significantly increasing risk tolerance.
2. Drawdown and Profit Relationship
Your max drawdown is 3% across the year, which indicates a very low-risk, consistent strategy.
Low drawdown strategies tend to give smoother but lower returns.
Trying to push monthly returns to 5-10% would typically require accepting higher drawdowns and larger risk per trade.
3. Backtest vs Real Market
Backtest assumes idealized fills, no slippage, may omit commissions, fatigue, spikes, news events.
Real trading usually results in lower net returns or higher drawdowns due to these factors.
Achieving this legally under strict prop firm risk rules is nearly impossible without elevating risk, which ends up breaching daily loss rules.
Such high returns normally require aggressive risk-taking or high-reward/potentially low-winrate approaches.
What Are Your Practical Options?
1. Accept Realistic Returns & Manage Growth
A 20%+ annual realistic return with low drawdown is solid for prop firm conditions.
User
Scenario Recap:
Account size: 10,000Propfirmlimits:4400)
8% overall max loss (~800)Backtesttimeframe:Fullyear(Jan12023−Dec312023)Backtestresult:2,000 profit (~20%) with max drawdown of 3%
Your concern: 20% yearly profit (~1.6% per month) is less than desired 5-10% monthly income.
how to know profit per month?
Assistant
To estimate monthly profit from your backtest results, there are a few straightforward methods depending on how detailed your backtest data is. Let me explain how to calculate or approximate monthly profits from your annual results, plus some tips on getting per month profit breakdowns from strategy testing.
1. Basic Method: Average Monthly Profit from Annual Profit
If you have only the total profit over the entire backtest period (1 year), and the total drawdown, the simplest way is:
So average monthly profit ≈ 20% / 12 ≈ 1.67% per month
This matches your statement and is a rough estimate.
2. More Accurate Method: Use Monthly Balance/Equity Values
If your backtesting platform (e.g. MT5 Strategy Tester) provides equity curve or balance curve data for the entire period, you can extract monthly balances and compute monthly profits more precisely:
For each month ( M ):
Get the starting balance/equity at the beginning of month ( M ) — call it ( B_{start,M} )
Get the ending balance/equity at the end of month ( M ) — call it ( B_{end,M} )
You use MqlTradeRequest for order sending and stop modifying. This is best practice in MQL5 assuming your broker supports it.
Risk Calculation
Your CalculateLotSize() looks good:
Uses SymbolInfoDouble to get contract size, tick value, tick size.
Falls back to fixed lot if any data missing.
Floors lot size to allowed steps.
Floating Loss Cap
You close positions immediately when floating loss is above the max risk percent of balance.
This is checked every tick.
Daily Max Loss Limit
By resetting daily equity and checking drawdown since reset, you limit total loss per day.
Nice way to implement a daily lose cap.
Lines and Object Cleanup
Swing High/Low lines are created in OnInit and deleted in OnDeinit.
Ensures no leftover objects clutter chart.
Suggestions for Further Enhancements
Logging & Debugging
Consider adding #define _DEBUG or an input bool for debug logging to toggle detailed prints only when needed.
Error Handling
If OrderSend or trade.PositionClose() fails, consider retry logic or more elaborate error diagnostics.
Use CTrade Object for Opening Trades as Well
You use trade.PositionClose(), but opening trades is via OrderSend request. For consistency, using trade.Buy() and trade.Sell() might be easier and less error-prone, but current approach is fine if you need precise control.
Improvement: Get Current Highest/Lowest Bars on Higher TF
Currently, UpdateTrailingStopByMarketStructure uses PERIOD_CURRENT (chart TF) for swing bars — consider matching swingTF parameter for consistency.
Check PositionSelect Performance
Since PositionSelectByTicket() usually changes global position context, ensure you minimize calls or cache selection state if reading multiple times.
Summary
Your EA code is solid and feature-rich. It respects MQL5 conventions and good trading practice like risk controls and trailing stops. It should compile and function well on live data.
If you want feedback on any specific part or help with testing/debugging, please ask!
If you want me to help with:
Adding specific features,
Fixing bugs,
Explaining some blocks,
Porting it to a different style,
Or optimizing execution,
let me know!
This reduces random or false signals.
3. Improve the Batched Indicator Access
Currently, CopyBuffer is called every tick for EMA and ATR with only 1 bar.
Optimization:
Cache indicator buffers outside OnTick, update once per bar or every X seconds.
Keep track of Time[0] (new bar) on the swingTF or maTimeframe, only update indicator buffers when a new bar appears.
This avoids unnecessary indicator calls every tick and reduces CPU usage.
4. Use CTrade Object for Entry & Exit
You already use CTrade trade; for closing positions but rely on low-level OrderSend for entries.
Switch to using trade.Buy(), trade.Sell() and trade.PositionClose() for consistent API usage and improved error handling.
Longer lookback → trailing SL more reactive to older pivots
TrailUpdateIntervalSec
Faster/slower SL update frequency affects effective trailing responsiveness
Bonus: Add Interaction Checks in Code
If desired, during OnInit or OnTick, you can apply constraints or sanity checks to prevent dangerous parameter combos, like:
mql5
if (atr_trail_mult < MinSLBufferATRMult)
{
Print("Warning: atr_trail_mult should be >= MinSLBufferATRMult. Adjusting...");
atr_trail_mult = MinSLBufferATRMult;
}
If you want, I can provide you a sample MQL5 optimization configuration script (.set equivalent) or code snippet showing how to log or restrict ranges dynamically for better optimizer experience.
Bottom line: Optimize all trailing stop related parameters together as a group in MT5 Strategy Tester for reliable, stable, and profitable trailing stop behavior.
If you want help building this joint optimization setup or need sample input setups for your EA, just ask!
TrailingProfitTriggerPerc
TrailUpdateIntervalSec
What matters most:
A small atr_trail_mult (e.g. 1.0 to 2.5) means tight trailing stops, which lock profit but risk premature stops.
Larger values reduce risk of stop-hunting but reduce potential profit capture.
MinSLBufferATRMult controls the minimal buffer floor — protects from SL being set too close.
Optimization focus:
Optimize atr_trail_mult, MinSLBufferATRMult, and TrailingProfitTriggerPercsimultaneously, as these directly affect SL tightening timing and distance.
3. Hybrid Mode
Hybrid uses BOTH MS and ATR trailing logic and chooses the "best" stop.
Uses all parameters:
atr_trail_mult
MinSLBufferATRMult
ms_swingLookback
TrailingProfitTriggerPerc
TrailUpdateIntervalSec
Why optimize all together:
Because hybrid mode chooses SL based on whichever is tighter/better (between MS and ATR logic), the parameters controlling both must be optimized together to:
Find the best swing lookback
Find the best ATR multiplier + buffer
Harmonize trailing activation threshold
Manage update frequency to avoid redundant orders and missed improvements
TrailUpdateIntervalSec is often overlooked.
A very small value in optimization results in excessive order requests and broker rejections. Keep it above 5 seconds, but no more than 30-60 seconds to keep trails responsive.
TrailingProfitTriggerPerc should never be 0, typically at least 0.1 (10% of SL distance profit) to avoid moving SL prematurely.
When optimizing Hybrid, consider narrowing the parameter ranges first in MS and ATR modes separately to get reasonable ranges, then do a combined optimization on Hybrid.
Combines MS & ATR parameters as both interact and select best SL
If you want, I can help you prepare MT5 input arrays or .set files for these grouped optimizations or assist building a helper routine to set sane input combinations for testing.
Just ask!
TrailingProfitTriggerPerc = 0.3 - 0.6
Having these ranges helps hybrid logic pick matching SL levels instead of conflicting.
Step 2: Adjust Trailing Start Threshold
Make sure TrailingProfitTriggerPerc is set to a reasonable value.
If too low (close to 0), SL moves too early — can cause whipsaws.
Usually between 30% and 60% of initial SL distance yields better trailing tradeoffs.
Step 3: Add Logging Specifically for Hybrid SL Decisions
Print/log the two trailing SL values (MS SL and ATR SL) and which one was picked each update.
Check for abnormal or frequent oscillations in trailing SL.
Example debug you can add inside UpdateTrailingStopHybrid():
Increase to 20 or 30 seconds to prevent noisy rapid trailing updates that can cause execution problems.
Step 5: Evaluate Separately — MS and ATR Mode Results
Run optimizations for MS and ATR modes individually, identify best parameters for each mode.
Then start hybrid testing with those subset values as start, don’t span full parameter ranges.
Step 6 (optional): Add Mode-Specific Disabled Flags or Logic
For example, if MS trailing SL differs by > X points vs ATR SL, choose only the one with bigger trailing distance or use other smoothing.
Summary
Issue
Solution
Conflicting SL levels from MS and ATR
Tune parameters for MS and ATR to harmonize ranges
Trailing SL moves too early or late
Adjust TrailingProfitTriggerPerc to 30-60%
Too frequent SL updates
Increase TrailUpdateIntervalSec to 20-30s
SL oscillations causing losses
Add logging to see SL choice; consider smoothing or thresholds
Poor parameter synergy
Optimize MS and ATR parameters separately first
Final Note:
Hybrid trailing stops are powerful if parameters and logic are carefully tuned for your symbol, timeframe, and market conditions. They often require more careful multi-parameter joint optimization than single-mode trailing stops.
If you want, I can generate:
A revised hybrid trailing function with smoothing/guardrails to avoid switching SL up and down erratically,
Sample sets of optimized parameters from test data,
A debug-enabled version with log printouts specific to hybrid mode.
Just ask!
Focus on consistent growth and avoiding catastrophic drawdowns that would disqualify your account.
Compound gains conservatively over long periods.
2. Increase Risk Per Trade Slightly
Test if you can safely push riskPercent or maxRiskPerTradePercent up to a level approaching your daily limit but without triggering loss limits.
This can increase returns but beware: curve-fitting past data can cause losses in live trading.
3. Improve Strategy with More Filters / Higher Probability Setups
Try to improve trade quality to increase win rate, reward-to-risk ratio, or reduce SL, squeeze more profit without increasing risk.
Use composite indicators, price action rules, and multi-timeframe confirmation.
4. Use Multiple Instruments or Strategies
Diversify: trading multiple uncorrelated symbols or strategies can increase overall return while keeping drawdown manageable.
But account for commission and margin.
5. Focus on Trailing Stops & Partial Profit Taking
Improve trailing stop logic to lock in profits earlier.
Consider exiting partial position size at TP and trailing rest.
Reduce drawdown and improve return-to-risk ratio.
Example Calculation:
If you risk 1% per trade with a 2 R:R and ~50% win rate
Expect average trade gain ~ 0.5% (win rate * reward - loss rate * risk).
If you take 1 trade per day → ~0.5% daily gross.
Realistically only a few trades per week → ~1-2% weekly → ~4-8% monthly possible with prudent risk.
Daily max loss 4% allows scaling risk but must avoid reaching loss limit repeatedly.
Final Thoughts
Return
Max Drawdown
Feasible Under Prop Rules?
1-3% monthly
2-5%
Moderate risk, consistent
5-10% monthly
10-20%
High risk, unlikely with daily loss limits
20%+ annual
~3%
Good risk-adjusted performance
Recommendations for Your EA & Trading Plan
Optimize to maximize return for a given max drawdown < 4% (prop firm daily limit).
Set risk sizing dynamically to never breach 4% daily loss cap.
Use your EA’s floating loss cap and daily max loss logic stringently.
Prioritize consistency over high monthly returns.
Slowly increase position sizing if equity grows and drawdown stays controlled.
Use realistic backtest slippage & commission models.
If possible, run walk-forward optimization and forward testing to avoid curve fitting.
Summary
Your backtest shows a well-controlled strategy. Trying to push for 5-10% monthly without surpassing prop firm limits will be challenging and likely require sacrifice in drawdown or risk controls.
Focus on gradual account growth, risk management, and strategy improvements—this will pay off steadily and prevent account termination by the prop firm.
If you want, I can help:
Suggest settings or strategy improvements to carefully nudge returns higher.
Help implement more advanced risk management within your EA.
Provide realistic expectations for growth curves based on your backtest.
Just let me know!
Open the CSV in Excel or any spreadsheet.
Filter or group equity by months (using the “Date” column).
Calculate monthly returns as above.
3. Using MQL5 Code to Log Monthly Profit
If you want to add monthly profit logging inside your EA during backtest (or live), you can do:
Track equity at the start of each month.
On the first tick of a new month, compute profit % from previous month and log/store it.