// New inputs for trailing settings (separate from entry/trade)
input int ms_swingLookback = 20; // Swing trailing lookback bars (separate from trade entry)
input double atr_trail_mult = 2.5; // ATR trailing multiplier (can differ from SL multiplier)
// Trailing enhancements
input uint TrailUpdateIntervalSec = 15; // Minimum seconds between trailing stop updates per position
input double MinSLBufferATRMult = 1.0; // Minimum SL distance buffer in ATR multiples
input double TrailingProfitTriggerPerc = 0.5; // Trailing activates once price moves this fraction of SL distance in profit
// 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 MT5 Expert Advisor code "Advanced_BoS_EA_MT5.mq5" looks quite comprehensive and well-structured, implementing a Break of Structure trading logic with dynamic lot sizing, multiple trailing stop methods, risk management, and configurable trading hours.
Below are some notes, confirmations, and suggestions that might help you ensure your EA works as intended or improve it further:
1. Initialization (OnInit)
Creation of ATR and EMA indicator handles is correct.
Horizontal lines are created for swing high/low visualization.
You reset daily loss tracking on init.
2. Daily Loss Tracking & Max Risk
ResetDailyLossIfNewDay() resets daily loss counters at the start of each server day (midnight).
UpdateDailyLoss() sums negative closed trades with your magic number and current symbol within the current day.
IsDailyLossExceeded() compares accumulated daily loss with user max daily loss percent.
CalculateLotSize() uses either fixed lot or risk % per trade capped by max risk per trade.
The signature and logic look solid.
It uses riskPercent for calculation only if useRiskPercent is true.
Uses Symbol info to calculate lot size precisely.
3. Position Checks & Management
IsPositionOpen() correctly loops through positions with your magic number and symbol.
It restricts to one position per type (buy or sell).
maxPositions controls max simultaneous positions; defaults to 1.
Positions selected by ticket for updates/trailing.
4. Trailing Stop Updates
Supports three modes: Market Structure, ATR, and Hybrid.
Market Structure Trailing: updates SL based on swing lows (buy) or swing highs (sell), with a small buffer.
ATR Trailing: uses ATR * multiplier to set trailing SL.
Hybrid: picks between MS and ATR trailing stop, comparing both and using the more conservative SL.
Throttling via TrailUpdateIntervalSec prevents frequent SL updates.
TrailingProfitTriggerPerc prevents trailing stops from adjusting before profit moves past a fraction of initial SL distance.
Buffer parameters and thresholds seem configurable and logical.
5. Trading / Entry Logic (OnTick)
Checks time against user-defined trading hours.
User
i want to use this ea on an prop firm account with Max Daily Loss -500,MaxLoss−1,000, Profit Target $500. if i want to have opened two chart in the same time , us100 and ger30. what are recommended settings?
Assistant
Using this EA for a prop firm account with strict risk limits and two instruments (US100 and GER30) simultaneously requires careful parameter configuration to ensure you respect your max loss limits and profit targets while maintaining proper risk management and avoiding overtrading.
Your Prop Firm Constraints Recap
Max Daily Loss: -500(youwanttheEAtostoptradingif500)
User
Max Loss -$1,000 ,This value represents the lowest recorded equity of your account from the time it is traded
Assistant
Thanks for the clarification!
If Max Loss = -1,000∗1,000, this is essentially a maximum drawdown limit.
User
so how to set ea on each symbol?
Assistant
Great question! To run the Advanced_BoS_EA_MT5 EA on two symbols simultaneously (e.g., US100 and GER30) with your prop firm risk limits, here’s a step-by-step on how to set up and configure the EA on each symbol/chart:
How to Set Up the EA on Each Symbol (US100 and GER30)
1. Open a Chart for Each Symbol
Open two charts in your MT5 terminal: one for US100, one for GER30.
2. Attach the EA to Each Chart Individually
Attach a separate instance of your EA to the US100 chart.
Attach a separate instance of your EA to the GER30 chart.
3. Set Unique Magic Numbers
To keep EA trades, trailing stops, and position management separate per symbol, you must assign a unique magic number per instance.
This prevents the EA from confusing trades on US100 with GER30 and vice versa.
Example settings:
Symbol
inpMagicNumber Value
US100
123456
GER30
654321
Change this in the Inputs tab for each EA instance accordingly.
4. Configure Inputs for Each Instance
Below is an example configuration for each symbol. Adjust your balance assumptions accordingly.
For US100 Chart (EA instance #1):
Input Name
Value
Notes
inpMagicNumber
123456
Unique ID for US100 trades
useRiskPercent
true
Enable % risk per trade
riskPercent
1.0
1% risk per trade
maxRiskPerTradePercent
10.0
Caps maximum risk per trade
maxDailyLossPercent
5.0
Max daily loss = 5% of balance
User
if US100 lost 350 $ , does ger30 know? maxim daily los is 500
Assistant
Good question! In your current EA design, the daily loss tracking (dailyLossMoney) is done per EA instance and symbol, filtered by symbol and magic number in the UpdateDailyLoss() function:
The US100 EA instance tracks only US100 closed trade losses
The GER30 EA instance tracks only GER30 closed trade losses
So:
If US100 loses $350 today
And GER30 loses $200 today
Then individually, neither EA exceeds the $500 daily loss limit
But combined your account is down 550,exceedingyourinte500 daily loss
User
yes please, and send me full ea updated code.
Assistant
Certainly!
Below is your full EA code updated to include combined equity drawdown tracking for the daily max loss limit (e.g., $500) across all symbols and EA instances running on the same account.
What I added:
Global static variable g_initialEquity stores the equity on first tick.
On each OnTick(), the EA compares current equity with initial equity.
If equity has dropped by maxDailyLossAmount dollars (a new input parameter), it prevents opening new trades.
The existing percent-based daily loss tracking is kept as-is but you can now control combined max loss in absolute dollars too.
Updated EA code snippet (full code with additions highlighted)
mql5
User
what are all updates of ea?
Assistant
Here is a summary of all updates made to your original EA code based on your request for implementing combined max daily loss tracking via equity drawdown and related clarifications:
Summary of EA Updates from version 1.4 to 1.5 (as provided)
1. Added new input parameter:
mql5
input double maxDailyLossAmount = 500.0; // Max combined daily loss $ amount (equity drawdown)
This allows you to set an absolute dollar amount limit for the combined daily loss (i.e., equity drawdown) across all symbols/EAs running on the same account.
2. Introduced a global static variable:
mql5
static double g_initialEquity = 0.0;
To store the initial account equity snapshot on the very first tick after EA starts.
Persistently used to compare current equity against initial equity.
3. In OnTick() added early check for combined equity drawdown:
mql5
if(g_initialEquity == 0.0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return; // stop trading if combined drawdown hit
}
This condition prevents opening new trades once the combined equity drawdown exceeds the specified dollar limit, regardless of symbol.
Effectively enforces a global max daily loss limit applicable to multiple EA instances running on different symbols on the same account.
4. Kept existing per-symbol per-magic-number daily loss % tracking
The existing with closed trade loss summation per symbol is unchanged.
User
you can delete old maxim daily loss
Assistant
Certainly! I will remove the old daily loss percent-based tracking (maxDailyLossPercent) and related code, so the EA will rely only on the new combined max daily loss specified as an absolute dollar amount (maxDailyLossAmount) based on equity drawdown.
Here is a summary of what will be removed and what remains:
Remove:
Input maxDailyLossPercent
Function UpdateDailyLoss()
Function ResetDailyLossIfNewDay()
Function IsDailyLossExceeded() and any calls to it
Variable dailyLossMoney
Variable dailyLossResetTime
Related code blocks that track and check daily loss based on closed trades per symbol/magic number
Keep:
The new equity drawdown check that uses maxDailyLossAmount (absolute $ loss) and g_initialEquity
All other functionality like trade logic, trailing stops, max risk per trade, max positions, etc.
Updated relevant code sections with old daily loss code removed
1. Inputs: Remove maxDailyLossPercent
Before:
mql5
input double maxDailyLossPercent = 2.0; // Max daily loss as % of account balance
After: Remove this line or comment out.
2. Remove global variables related to daily loss
Before:
mql5
// Globals for keeping daily loss state
double dailyLossMoney = 0.0;
datetime dailyLossResetTime = 0;
After: Remove these two variables.
3. Remove ResetDailyLossIfNewDay() function entirely
4. Remove UpdateDailyLoss()
5. Remove IsDailyLossExceeded() function and calls to it
Certainly!
Here is the full updated Advanced_BoS_EA_MT5.mq5 EA code with all old daily loss percent-based tracking removed and solely using the new combined max daily loss equity-drawdown approach.
Key changes summary:
Removed maxDailyLossPercent input and all functions and logic related to closed-trades daily loss tracking.
The EA now strictly uses maxDailyLossAmount (absolute $ loss) with equity drawdown on account equity.
Behavior: Stops opening new trades when the combined drawdown exceeds maxDailyLossAmount.
Other original features and logic remain unchanged.
occur because the trailing stop functions (UpdateTrailingStopByMarketStructure, UpdateTrailingStopByATR, UpdateTrailingStopHybrid) are called inside OnTick() but not defined (or omitted) in the code you've compiled.
What happened?
In the full code snippet I provided earlier, I omitted the trailing stop function implementations for brevity, with the note for you to keep your original trailing functions there as they are unchanged.
But MQL5 requires all called functions be declared and defined in the source code.
How to fix it
You need to include the full definitions of these three trailing stop functions inside your EA source code.
Full function prototypes you need to include:
mql5
User
full ea code
Assistant
Certainly! Below is the full complete EA source code for your Advanced_BoS_EA_MT5 including:
The combined equity drawdown max daily loss limit (maxDailyLossAmount).
All three trailing stop functions fully included.
Cleaned from old daily loss % code as you requested.
Ready to compile and use on MT5.
mql5
User
The combined equity drawdown stops new trades globally until when?
Assistant
Great question!
How the combined equity drawdown max daily loss check works in this EA:
The EA stores your account equity on its first tick after startup in the variable:
mql5
static double g_initialEquity = 0.0;
On every subsequent tick it measures the drawdown:
If the drawdown exceeds your configured maxDailyLossAmount (e.g., $500), the EA stops opening any new trades indefinitely by returning early from OnTick() before any new order logic.
When does it resume trading?
Currently, the EA will not resume opening new trades until it is restarted or reinitialized because:
g_initialEquity is set only once when it equals zero, and never updated again.
So the threshold for maximum drawdown is fixed relative to that single initial equity snapshot.
Equity later recovers above threshold (drawdown smaller than max)
EA still blocks new trades (because g_initialEquity unchanged)
EA is reloaded / terminal restarted
g_initialEquity resets to current equity, new threshold applied
Summary:
The combined equity drawdown max loss is a one-shot threshold relative to equity at EA start.
Once hit, new trades are blocked until you restart EA or MT5 terminal which resets g_initialEquity.
This means the EA does not dynamically "reset" the max loss limit during the day or after recovery.
How to improve this behavior (optional for you)
User
it must reset daily,
Assistant
Understood! To have the combined equity drawdown max daily loss limit reset daily (at midnight server time), you need to update the EA to reset g_initialEquity at the start of a new day.
How to implement daily reset of initial equity in your EA
Add a global variable to track the last reset day:
mql5
static datetime g_lastResetDay = 0;
Create a function to reset initial equity daily at midnight server time:
void OnTick()
{
ResetDailyEquityIfNewDay();
// rest of your OnTick code ...
What this does:
On each tick, it checks if the day changed since last reset.
If day is new, it updates g_initialEquity to current equity, so your max loss is now measured fresh from the new day’s equity.
Trading resumes if equity has recovered above cooldown or if it's a new day.
User
yes please
Assistant
Certainly! Below is your fully updated EA code including the daily reset of combined equity drawdown at server midnight. This makes the max daily loss limit reset each day automatically, allowing the EA to resume trading fresh every day.
mql5
User
set daily max loss in dollars same value on bots ?
Assistant
Yes. When you run multiple instances of this EA on different charts (symbols) using the same maxDailyLossAmount value, they will all refer to the same account equity and the same combined daily drawdown limit.
How it works:
maxDailyLossAmount defines a global drawdown limit per account, not per symbol or per EA instance.
The EA checks the account equity on each tick and compares it to the baseline equity at daily reset.
If the drawdown from that baseline reaches or exceeds maxDailyLossAmount, all EA instances stop opening new trades simultaneously.
This ensures the daily max loss is effectively shared and enforced globally across all EA instances/bots on the account.
Practical setup:
Use the same maxDailyLossAmount dollar value on all EA instances.
For example, if your max daily loss is $500, set maxDailyLossAmount=500.0 in the inputs for all EA copies.
All bots will detect the same equity and stop trading when the combined loss reaches $500.
Notes:
Each EA instance can have its own magic number (recommended) to keep trades separate.
All must be attached to charts on the same account.
The daily equity reset happens per EA instance but based on the same account equity/time (so effectively in sync).
This approach simplifies risk control because you don’t have to manage separate daily loss values per symbol — you have a single, combined max loss limit.
If you want to, I can help with best practices for setting magic numbers and per-symbol inputs to avoid conflicts.
Summary:
Set the same dollar value for maxDailyLossAmount on all your EA instances to enforce a single combined daily max loss limit across your whole account.
User
how to make ea win more
Assistant
Improving an EA’s win rate (or overall profitability) involves multiple aspects: strategy parameters, risk management, market conditions, and sometimes even code optimization. Since your EA is based on Break of Structure (BoS) with ATR-based SL/TP and trend filtering, here are some targeted suggestions to help increase its effectiveness:
1. Optimize Strategy Parameters
Adjust Lookbacks:
swingLookback and ms_swingLookback control how far the EA looks back for swing highs/lows.
Experiment with slightly longer or shorter lookbacks to better capture meaningful breaks.
Try increasing SL multiplier slightly to let trades breathe or decrease for tighter control.
Adjust Risk:Reward Ratio (r2r_ratio):
Increasing TP relative to SL can improve reward, but watch overall hit rate.
Find balanced R:R ratio where wins compensate for losses.
2. Apply Additional Filters
Stronger Trend Confirmation:
Currently you use 50 EMA on M15 as trend filter.
Consider adding other filters like multi-timeframe trend confluence or momentum indicators (RSI, MACD) to confirm entries.
Volume or Volatility Filters:
Avoid trading during low volume or very high volatility/spikes.
Filter entries during unusual market conditions (e.g., news times).
3. Entry Refinements
Use Confirmation Candles:
Wait for candle close confirming the break of swing high/low before entering.
You can add a small delay or require price to sustain beyond the break level.
Partial Entries or Scaling In:
Add entries in portions rather than full size at once.
Scaling in can improve average entry price and filter false breaks.
4. Trailing Stop and Exit Strategy
User
tell me about this
Assistant
Certainly! Here’s a detailed explanation of the key points that can help your EA (Break of Structure EA) win more — meaning improving profitability, trade accuracy, and overall performance. I’ll break down each concept so you understand why it matters and how you can apply it to your EA or trading approach.
1. Optimizing Strategy Parameters
Swing Lookback (swingLookback, ms_swingLookback):
These control how far back the EA looks to define swing highs/lows—key levels for breakouts.
If too short, you may catch minor swings generating false signals (noise).
If too long, the levels might be outdated and slow to react.
Tuning these (e.g., testing between 15-30 bars) helps the EA find swing levels that better reflect the current market rhythm.
ATR Multipliers (sl_atr_mult, atr_trail_mult):
ATR determines market volatility. Multipliers define stop loss (SL) and trailing stop distance relative to that volatility.
Higher multipliers give more room to avoid being stopped out by regular price fluctuations—good for trending markets.
Lower multipliers tighten stops, increasing win ratio but risk early stop-outs on normal noise.
Risk to Reward Ratio (r2r_ratio):
Defines target profit relative to risk.
Higher R:R means larger take profits, which can improve expectancy but may lower win rate.
Lower R:R usually yields higher win rate but smaller profit relative to risk.
Application: Use backtesting or optimization to find the sweet spot of these parameters based on the instrument and timeframe you trade.
2. Applying Additional Filters
Adding extra confirmation conditions reduces bad trade entries. For example:
Using a faster or slower moving average to confirm trend direction.
Momentum indicators like RSI or MACD to check if the market is overbought/oversold or trending strongly.
Volume filters to verify that breakouts are backed by volume (not just price spikes).
These filters help dismiss false breakouts or low probability trades, improving the quality of trades your EA takes.
3. Entry Refinements
Waiting for candle close beyond swing breaks can reduce fakeouts. Price often temporarily spikes beyond a swing level and then reverses before candle close—waiting for candle confirmation filters these false signals.
User
Waiting for candle close beyond swing breaks can reduce fakeouts. Price often temporarily spikes beyond a swing level and then reverses before candle close—waiting for candle confirmation filters these false signals.
Assistant
Exactly! Waiting for the candle to close beyond your swing break level is a common technique to reduce false breakouts ("fakeouts"), which often happen when price momentarily breaches a key level but doesn't sustain the move.
Why waiting for candle close helps:
Price spikes and wicks:
Price often pokes above (or below) swing highs/lows intra-bar, forming long wicks or shadows, but closes inside or on the opposite side. Entering immediately on the break risks taking a losing trade if the breakout is false.
Confirmation of strength:
A candle close beyond the swing confirms buyer (or seller) control has been sustained through the entire bar, increasing the probability that the breakout will follow through.
This uses current price crossing the swing level but not confirmation on candle close on the swing timeframe.
Modify to wait for candle close on the swingTF timeframe beyond the swing level:
Use the close price of the last completed candle on the swingTF instead of the current ask or bid.
For buy entries:
Check if the close of the last finished bar on swingTF is strictly above the previous swing high.
For sell entries:
Check if the close of the last finished bar on swingTF is strictly below the previous swing low.
Example snippet replacement:
Replace current entries in OnTick() with something like:
mql5
User
yes , with option to enable or disable will be ok?
Assistant
Certainly! I will modify your EA's entry logic to add an input that enables waiting for candle close confirmation beyond the swing breaks. This feature can be toggled on or off by the user.
What will be added:
New boolean input enableCloseConfirmation to enable/disable waiting for candle close beyond swing levels.
When enabled, the EA will require the last completed candle close on the swing timeframe to be beyond the swing high or low for entry.
When disabled, EA behavior remains as before (uses current ask/bid for immediate break).
Here is the full updated entry section from your OnTick() with this feature integrated:
mql5
input bool enableCloseConfirmation = true; // Enable entry only after candle close beyond swing break
// ... Inside OnTick(), after computing lastSwingHigh, lastSwingLow, is_uptrend, is_downtrend etc.
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
int swingCloseShift = 1; // last fully closed bar index
double lastSwingClose = iClose(_Symbol, swingTF, swingCloseShift);
bool buyConfirmed = false;
bool sellConfirmed = false;
if(enableCloseConfirmation)
{
buyConfirmed = (lastSwingClose > lastSwingHigh) && is_uptrend;
sellConfirmed = (lastSwingClose < lastSwingLow) && is_downtrend;
}
else
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
buyConfirmed = (ask > lastSwingHigh) && is_uptrend;
sellConfirmed = (bid < lastSwingLow) && is_downtrend;
}
// Use buyConfirmed and sellConfirmed for entry conditions instead of old checks
if(!enableReverseEntries)
{
if(buyConfirmed)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
// place buy order
}
}
else if(sellConfirmed)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
// place sell order
}
}
}
else
{
// reversed logic using buyConfirmed and sellConfirmed accordingly
}
If you’d like, I can provide your full EA code with this change injected.
This will allow you to switch candle close confirmation on/off without changing code, just via input parameter.
Let me know if you want me to generate full updated EA code with this feature included!
User
yes
Assistant
Certainly! Below is your EA’s full updated code with the new input enableCloseConfirmation that lets you toggle waiting for candle close confirmation beyond swing breaks before entering trades. When enabled, the EA checks the last fully closed bar on the swing timeframe; when disabled, it uses the current price as before.
The errors mean that the trailing stop update functions:
UpdateTrailingStopByMarketStructure
UpdateTrailingStopByATR
UpdateTrailingStopHybrid
are called in your OnTick() but not declared or defined anywhere in the EA source code.
To fix this, you need to provide the full definitions for these functions.
Below are the full definitions based on your original code you provided. Add these functions anywhere in your EA source file, before OnTick() (or after global declarations), so the compiler recognizes them.
mql5
User
entire latest EA code
Assistant
Certainly! Below is your entire latest EA code including the daily equity reset, combined max daily loss in dollars, candle close confirmation toggle, and full trailing stop functions so it compiles and runs without "undeclared identifier" errors.
mql5
User
yes please
Assistant
Sure! Below are example .set files for your two EA instances (e.g., US100 and GER30). You can create these text files, save them with .set extension, and load them into your EA input settings via the MT5 terminal to quickly apply your preferred configurations.
In the EA properties → Inputs → click Load and select US100.set.
Repeat for your GER30 chart with GER30.set.
Notes:
Make sure the magic numbers differ so the EA handles positions separately per symbol.
Adjust parameters as you see fit.
These .set files reflect the latest EA structure with the combined max daily loss, trailing, and candle close confirmation enabled by default.
If you want, I can help you generate .set files with alternative parameters, or assist with batch setups.
Just ask!
User
enableCloseConfirmation , if is on true, no trades open
Assistant
If you have enableCloseConfirmation set to true but your EA never opens trades, it usually means the close of the last completed candle on the swing timeframe is never crossing the swing high or low, so the condition to enter is never met.
Here are some things to check and possible fixes:
1. Verify That Swing High and Low Bars Are Correct
The EA finds the swing high and swing low bars with:
mql5
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
Try temporarily disable enableCloseConfirmation and check if trades open using current ask/bid prices as before — this verifies that your swing levels and conditions in general work. This is working, open trades.
Assistant
Thanks for confirming! Since trades open fine with enableCloseConfirmation = false but not when it's true, the issue is definitely related to how candle close confirmation is checked against swing highs/lows.
Likely causes & fixes:
1. Swing level chosen might be outdated or too far back
The highest/lowest bar found with:
mql5
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
finds the highest high or lowest low in the past swingLookback bars, starting from shift 1 — which may not be the most recent or relevant swing level.
Try reducing swingLookback to a smaller number (e.g., 10 or 15) or picking the swing level at shift 2 or 3 instead of using iHighest/iLowest.
2. Candle close on swingTF may never close beyond swing level
If the swing level is too far above (or below) the most recent candle closes on your swing timeframe, no condition is met.
The 1 starting offset means the previous completed bar, which is fine for indicators.
OrderSend deviation parameter:
You use a fixed deviation of 10, which may or may not be appropriate per broker. Consider making deviation an input parameter for flexibility.
Logging and Errors:
You log errors on order failures, which is excellent.
You may add more verbose logging for state changes (e.g., when max positions limit is reached).
Position types open limit:
Current code permits multiple buys and multiple sells if maxPositions > 1. If you want only one position overall, you can check all positions instead of per type.
Risk calculation uses riskPercent input if useRiskPercent=true, but maxRiskPerTradePercent is also used as a cap—make sure these are consistent to avoid confusion.
Trailing stop in sell market structure trailing:
mql5
if(new_sl < current_sl && new_sl > entry_price)
This might be incorrect because for sell positions, SL is typically above entry price and you want to move SL downwards (closer to price). The condition might need checking since new_sl < current_sl is correct, but new_sl > entry_price may contradict.
Same applies for buy trailing: check logic if SL < entry price or vice versa is appropriate per symbol and broker conventions.
TrailingHybrid uses MIN and MAX of new SLs in buy/sell respectively. This ensures the SL is tightened accordingly.
Slippage and Price Checks:
Before order sending, you might want to ensure the request.price is checked for validity against current Ask or Bid, considering spreads.
OnDeinit Clean-up:
You delete objects and release indicator handles properly.
Summary
Your EA implements quite complex logic with proper precautions and flexibility. The code follows good MQL5 practices. The trailing methods you implemented are useful and the daily loss protections add safety.
If you want, I can help you with:
Adding example usage for iMA and iATR on custom timeframes
Improving trailing stop logic conditions based on SL and entry price
Adding order modification confirmation and handling possible rejections more robustly
Writing a guide to tune parameters to improve performance
Adding additional logging to debug when needed
Incorporating more advanced position management (multiple pairs, average positions, etc.)
If you want me to review or add any specific part, or fix anything, please let me know!
t
h
e
l
ossr
e
a
c
h
es
Max Account Loss (Overall Drawdown cap, e.g., Max Loss): -$1,000
Profit Target: +$500 (not enforced by EA code but you can monitor)
Instruments: US100 and GER30 on two separate charts
Two charts simultaneously — meaning 1 instance of EA per symbol
Recommended Settings and Considerations for Your EA
1. Max Daily Loss Parameter in EA
Your EA's maxDailyLossPercent is percent-based: e.g., 2.0 means 2% of account balance max loss per day.
Your prop firm max loss is an absolute dollar amount.
How to set maxDailyLossPercent:
You need to convert your max daily loss ($500) into a percentage based on your account balance.
Example:
Suppose your starting balance is $10,000
$500 loss = 500 / 10,000 = 5%
So
mql5
maxDailyLossPercent = 5.0;
Set this to the value matching your firm conditions. You could tighten it under 5% (e.g., 4.5%) to have a safety margin.
If your balance differs, adjust accordingly.
2. Max Risk Per Trade %
You also have a max loss per trade of $1,000. Although this is larger than daily loss limit, it's good to cap risk per trade properly.
Set maxRiskPerTradePercent to a low value to avoid risking more than this.
For example, if your balance is 10,000andmaxlosspertrade1,000, risk per trade should never exceed 10%.
mql5
maxRiskPerTradePercent = 10.0; // or less to be safer, e.g. 5%
3. Lot Size and Risk Percent
Since your max loss and daily loss limits are dollar-based, it's safer to enable useRiskPercent = true so the EA calculates lot size dynamically based on ATR and risk %.
Set riskPercent to a safe value per trade. A typical conservative range is 0.5% to 2% risk per trade.
Example:
mql5
useRiskPercent = true;
riskPercent = 1.0; // 1% risk per trade, adjust lower if too aggressive
4. Max Positions
Since you want to trade both US100 and GER30 simultaneously, and you will run one instance of the EA per chart, set:
mql5
maxPositions = 1;
This restricts EA to open only one position per instrument, so you won't over-leverage on that symbol.
Alternatively, if you want multiple positions per symbol, adjust it, but keep in mind risk.
5. Trading Hours
tradeStartHour and tradeEndHour depend on your broker’s server time and when you want to allow trading.
Example for most brokers (GMT+2/3):
mql5
tradeStartHour = 7;
tradeEndHour = 22;
Adjust as per your broker timezone and instrument’s optimal trading hours.
6. ATR and SL multipliers
A higher SL ATR multiplier means more room for price movement, but bigger losses per trade.
If the account size and risk limits are tight, you may want to increase sl_atr_mult to 4 or 5 to prevent premature stops or reduce lot size accordingly.
7. Trailing Stops
Enable trailing stops to lock in profits:
mql5
enableTrailingSL = true;
trailingStopMode = TrailingHybrid; // best combination of MS + ATR
TrailingProfitTriggerPerc = 0.5 means trailing activates after price moves 50% towards TP — a reasonable balance.
8. Enable Reverse Entries
Use default entries first (enableReverseEntries=false) unless you want the opposite trade logic.
9. Magic Numbers
Important: Set different inpMagicNumber for each EA instance on different symbols to avoid confusion.
Example:
US100 chart EA:
mql5
inpMagicNumber = 123456
GER30 chart EA:
mql5
inpMagicNumber = 654321
10. Monitoring and Logs
Keep logs open during initial runs and verify the positions and SL/TP levels.
Watch for lot size, SL distance, and ensure they respect your maximums.
Example Final Settings For Both EAs (assuming $10,000 starting balance)
Parameter
US100 (chart #1)
GER30 (chart #2)
inpMagicNumber
123456
654321
useRiskPercent
true
true
riskPercent
1.0
1.0
maxRiskPerTradePercent
10.0
10.0
maxDailyLossPercent
5.0
5.0
maxPositions
1
1
sl_atr_mult
3
3
atr_trail_mult
2.5
2.5
enableTrailingSL
true
true
trailingStopMode
TrailingHybrid
TrailingHybrid
tradeStartHour
7
7
tradeEndHour
22
22
enableReverseEntries
false
false
Additional Notes
You must verify symbol specifications (min lot, max lot, contract size) for US100/GER30 on your broker to ensure lot sizing works as expected.
Observe slippage and spread conditions especially with volatile indices like US100 and GER30.
Test this setup extensively on a demo or simulation account to tune riskPercent, sl_atr_mult, and trading hours before going live.
If your account balance changes significantly, update maxDailyLossPercent to remain consistent with your $500 loss target.
The EA does not manage your profit target ($500) - you could implement a manual or external monitor to disable the EA or stop trading after reaching the profit target.
How to implement max overall loss ($1,000)?
Since EA tracks daily losses, but not total drawdown, you need:
Manual monitoring of account drawdown and disabling EA if drawdown hits $1,000.
Or extend EA with persistent storage of cumulative losses and stop trading accordingly.
Summary
What to set
Why
maxDailyLossPercent = 5%
Limits daily loss approx 500on10k
maxRiskPerTradePercent = 10%
Limit max risk per trade to approx $1k max loss
useRiskPercent=true + riskPercent=1%
Dynamically size lots for risk control
maxPositions=1
Limit one open position per symbol to avoid overexposure
Separate inpMagicNumber per symbol
To avoid mixing positions in trailing and management
Adjust percentages if your balance differs from $10k, or if your prop account real starting capital is smaller.
If you want, I can help you write a helper script to convert fixed $ max loss values into percent parameters based on input current balance.
Feel free to ask if you want me to explain how to safely backtest this multi-symbol setup or help automate profit target monitoring!
∗
m
e
an
s
t
h
e
∗
∗lowest−
everequitypointallowed∗
∗—i.e.,a∗
∗drawdownfromyourstartingequitynottoexceed
How to handle the Max Loss (Drawdown) -$1,000 with your EA?
Your EA currently supports tracking daily losses via maxDailyLossPercent, but it doesn’t track overall equity drawdown from starting capital or max historical equity.
How to implement or handle Max Loss = $1,000 drawdown:
Option 1: Manual Monitoring + Disable EA
Manually monitor your account equity.
When equity drops $1,000 below your starting balance, stop trading or remove the EA.
You can do this via your broker’s platform or third-party monitoring apps.
Option 2: Add Equity Drawdown Check inside EA (Recommended)
Modify your EA to:
Save the initial account balance (starting equity) on EA start.
void OnTick()
{
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double drawdown = g_initialBalance - currentEquity;
if(drawdown >= 1000.0) // Max Loss limit reached
{
if(!g_maxLossReached)
{
PrintFormat("Max drawdown limit of $1000 reached. No new trades will be opened.");
g_maxLossReached = true;
}
// Return early - do not open new trades
// Optionally consider closing some positions here
return;
}
// Continue your normal EA logic here...
// YOUR EXISTING OnTick content goes here...
}
Integration with Daily Loss Checks
Your EA already prevents trading if daily loss limit exceeded via IsDailyLossExceeded().
You can keep both checks active:
mql5
void OnTick()
{
ResetDailyLossIfNewDay();
UpdateDailyLoss();
if(IsDailyLossExceeded())
{
Print("Daily loss exceeded: stopping trades for today.");
return;
}
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
if(g_initialBalance - currentEquity >= 1000.0)
{
Print("Max drawdown limit hit: stop opening new trades.");
return;
}
// Rest of your trading code...
}
Notes:
Persistent storage:
To survive terminal restarts or EA reattach, you might want to store g_initialBalance in global variables or files so that your starting equity is kept consistent for the max drawdown check.
This depends on your workflow and whether the starting balance can change (e.g., after deposits/withdrawals).
Closing trades on max loss:
If you want the EA to close all open trades when max loss is hit, add code to loop through open positions and close them (be cautious with slippage, spread, and timing).
Disabling EA trading only:
The safest option at first is to stop opening new trades once $1,000 drawdown hit, but keep existing positions for possible recovery or manual closing.
Summary of recommended action for your requirement
Requirement
Action in EA
Max Daily Loss = $500
Use maxDailyLossPercent = (500 / balance) * 100%
Max Loss (drawdown) = $1000
Implement g_initialBalance and check equity drawdown each tick, block new trades when reached
Profit Target = $500
Monitor externally or implement a similar profit target stop logic yourself
Feel free to ask if you want me to provide full code snippets for equity drawdown persistence or profit target management!
maxPositions
1
1 position max on US100
enableTrailingSL
true
Use trailing stop
trailingStopMode
TrailingHybrid (3)
Hybrid trailing method
tradeStartHour
7
Broker server hour time
tradeEndHour
22
Broker server hour time
Other inputs
Default or tuned per preference
ATR multipliers, swing lookback
For GER30 Chart (EA instance #2):
Input Name
Value
Notes
inpMagicNumber
654321
Unique ID for GER30 trades
useRiskPercent
true
Enable % risk per trade
riskPercent
1.0
1% risk per trade
maxRiskPerTradePercent
10.0
Caps maximum risk per trade
maxDailyLossPercent
5.0
Max daily loss = 5% of balance
maxPositions
1
1 position max on GER30
enableTrailingSL
true
Use trailing stop
trailingStopMode
TrailingHybrid (3)
Hybrid trailing method
tradeStartHour
7
Broker server hour time
tradeEndHour
22
Broker server hour time
Other inputs
Default or tuned per preference
ATR multipliers, swing lookback
5. Verify Broker Symbol Naming
Symbols might have suffixes/prefixes differing by broker. Ensure that you use the exact symbol name in each chart and that the EA is attached to the correct chart symbol.
6. Optional: Manual or Automatic Equity Drawdown Handling
If you implement the equity drawdown stop logic (discussed earlier), each EA instance will track drawdown independently based on the broker account which is shared, so risk checks apply globally.
If you want global max loss tracking across symbols (combined), you’ll need external monitoring or adaptations beyond per-instance EA logic.
7. Run EA and Monitor
Start the charts, attach the EAs with your recommended settings.
Watch the Experts & Journal tabs for logs to verify orders, trailing stops, and risk management.
Verify lot size and SL/TP levels are within your acceptable risk limits.
Summary: Two Charts & Two EA Instances
Step
Action
1
Open US100 chart
2
Attach EA, set inpMagicNumber = 123456 and inputs
3
Open GER30 chart
4
Attach EA, set inpMagicNumber = 654321 and inputs
5
Confirm EA runs on each symbol independently, respecting risk limits and max losses
6
Monitor equity drawdown globally manually or extend EA with custom logic
Extra Tip: Visual Settings
You can optionally:
Change chart color schemes per symbol.
Use EA comments or labels to show which magic number is active for easy troubleshooting.
If you want, I can provide you with a recommended input .set file for each symbol so you can just load them quickly into your EA instances on the different charts.
Let me know if you want help creating those set files or automating max drawdown monitoring across symbols!
n
d
e
d
ma
x
Each EA instance doesn’t "know" the other’s losses.
How to handle combined max daily loss across multiple symbols?
You have these options:
Option 1: Centralized Shared Daily Loss Tracking (Advanced)
Store and read a shared resource to aggregate losses across all symbols/EAs on the account.
Possible approaches:
Use Global Variables of Terminal (GVL)
Use a file with synchronization
Use an external DLL or web server for shared state
Each EA instance then reads this shared daily loss and compares to your global max limit.
Option 2: Use Account-wide Equity or Balance Drawdown
Instead of summing closed losses symbol-by-symbol, base max daily loss on equity drawdown of the entire account.
Your EA already can be extended (as I suggested earlier) to track equity vs. initial balance and block opening new trades if drawdown exceeds $1000 max loss or your daily max loss.
This logic is global (account-wide), so both EAs see the same equity number and behave accordingly:
mql5
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
if(g_initialBalance - currentEquity >= 500.0) // Max daily loss reached
{
// Stop trading
return;
}
This approach is simpler and effective for combined loss control.
Option 3: Manual Monitoring Outside EA
Use manual or third-party risk managers or dashboards that monitor combined drawdown and turn off EAs or trading when limits are reached.
Recommended for your use case:
Implement equity drawdown check for daily max loss in the EA's OnTick(). This way:
The two EA instances share the broker account equity info.
Both will stop trading when total equity drops by $500 or more.
This prevents any symbol from exceeding the combined max daily loss as equity is universal.
Example snippet to add at start of OnTick() in your EA:
mql5
static double g_initialEquity = 0;
if(g_initialEquity == 0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY); // set once on first tick
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double drawdown = g_initialEquity - currentEquity;
if(drawdown >= 500.0)
{
Print("Max combined daily loss of $500 exceeded. Stopping new trades.");
return; // skip trading logic and don't open new orders
}
Summary
Question
Answer
Does GER30 EA know if US100 lost money?
No, per-symbol daily loss tracking is separate
Does combined max daily loss work today?
No, unless you implement shared/global tracking
How to enforce combined max daily loss?
Use equity drawdown checks, since equity is global
If you want, I can help you extend your EA with this equity-based combined max loss check so that both US100 and GER30 instances respect the same daily loss limit.
Let me know!
//+------------------------------------------------------------------+
//| Advanced_BoS_EA_MT5.mq5 |
//| Author: LucienWP |
//| Version: 1.5 |
//| Published: 2025-06-XX |
//| Description: Break Of Structure EA |
//| with dynamic lot sizing, dynamic trailing stops (market structure|
//| or ATR or hybrid), throttling and safety buffers |
//+------------------------------------------------------------------+
#property copyright "LucienWP"
#property version "1.5"
#property strict
#property script_show_inputs
#include <Trade\Trade.mqh>
input double inpLot = 0.05; // Fixed lot size per trade
input bool useRiskPercent = false; // Use risk % to calculate lot size
input double riskPercent = 1.0; // Risk % per trade if enabled
input int sl_atr_mult = 3; // SL multiplier for ATR (initial SL distance)
input double r2r_ratio = 2.0; // Risk-to-Reward ratio (TP = SL * r2r_ratio)
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // ATR timeframe
input int atrPeriod = 14; // ATR period
input int swingLookback = 20; // Bars lookback for swing detection (trade entries)
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe for entries
input int maPeriod = 50; // EMA period for trend filter
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trading start hour (server)
input int tradeEndHour = 22; // Trading end hour (server)
input int maxPositions = 1; // Max simultaneous EA positions (0=no limit)
input uint inpMagicNumber = 123456; // Magic number for EA positions (uint for compatibility)
// Trailing stop enable and mode
input bool enableTrailingSL = true; // Enable trailing stop
enum ENUM_TrailingStopMode
{
TrailingNone = 0, // No trailing stop
TrailingMarketStructure = 1, // Trailing by market structure swings
TrailingATR = 2, // Trailing by ATR-based stop loss
TrailingHybrid = 3 // Hybrid trailing: market structure + ATR
};
input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid; // Trailing stop mode selector
// New inputs for trailing settings (separate from entry/trade)
input int ms_swingLookback = 20; // Swing trailing lookback bars (separate from trade entry)
input double atr_trail_mult = 2.5; // ATR trailing multiplier (can differ from SL multiplier)
// Trailing enhancements
input uint TrailUpdateIntervalSec = 15; // Minimum seconds between trailing stop updates per position
input double MinSLBufferATRMult = 1.0; // Minimum SL distance buffer in ATR multiples
input double TrailingProfitTriggerPerc = 0.5; // Trailing activates once price moves this fraction of SL distance in profit
// 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
// --- NEW INPUT: MAX DAILY LOSS in absolute dollars for combined equity drawdown ---
input double maxDailyLossAmount = 500.0; // Max combined daily loss $ amount (equity drawdown)
CTrade trade;
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
struct TrailingUpdateInfo
{
ulong position_ticket;
datetime last_update;
};
TrailingUpdateInfo g_trailingUpdateInfo[];
// Globals for keeping daily loss state
double dailyLossMoney = 0.0;
datetime dailyLossResetTime = 0;
// --- Global static variable to hold initial equity on first tick ---
static double g_initialEquity = 0.0;
//+------------------------------------------------------------------+
void OnInit()
{
PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", __DATE__);
PrintFormat("MagicNumber=%u, SwingTF=%d, ATR period=%d, SL ATR Mult=%d",
inpMagicNumber, swingTF, atrPeriod, sl_atr_mult);
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle == INVALID_HANDLE)
{
Print("Failed to create EMA handle");
return;
}
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
IndicatorRelease(ma_handle);
return;
}
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing high line");
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen);
ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);
if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing low line");
ObjectDelete(0, swingHighLineName);
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed);
ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true);
// Initialize daily loss reset time
dailyLossResetTime = 0;
dailyLossMoney = 0.0;
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(0, swingHighLineName);
ObjectDelete(0, swingLowLineName);
if(ma_handle != INVALID_HANDLE)
{
IndicatorRelease(ma_handle);
ma_handle = INVALID_HANDLE;
}
if(atr_handle != INVALID_HANDLE)
{
IndicatorRelease(atr_handle);
atr_handle = INVALID_HANDLE;
}
}
//+------------------------------------------------------------------+
// Resets daily loss tracking at start of each new day
void ResetDailyLossIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm {};
TimeToStruct(now, tm);
MqlDateTime reset_dt = {};
reset_dt.year = tm.year;
reset_dt.mon = tm.mon;
reset_dt.day = tm.day;
reset_dt.hour = 0;
reset_dt.min = 0;
reset_dt.sec = 0;
datetime resetTimeToday = StructToTime(reset_dt);
if(dailyLossResetTime != resetTimeToday)
{
dailyLossResetTime = resetTimeToday;
dailyLossMoney = 0.0;
Print("Daily loss tracker reset.");
}
}
//+------------------------------------------------------------------+
// Update daily loss as sum of closed negative trades for current day & symbol
void UpdateDailyLoss()
{
datetime dayStart = dailyLossResetTime;
datetime dayEnd = dayStart + 86400; // Next day
double lossToday = 0.0;
int dealsTotal = HistoryDealsTotal();
for(int i=dealsTotal-1; i>=0; i--)
{
ulong ticket = HistoryDealGetTicket(i);
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
if(symbol != _Symbol)
continue;
ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
if(magic != inpMagicNumber)
continue;
datetime dealTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(dealTime < dayStart || dealTime >= dayEnd)
continue;
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit < 0)
lossToday += (-profit);
}
dailyLossMoney = lossToday;
}
//+------------------------------------------------------------------+
// Returns true if daily loss limit exceeded (stop trading)
bool IsDailyLossExceeded()
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0) return false;
double lossPercent = 100.0 * dailyLossMoney / balance;
if(lossPercent >= maxDailyLossPercent)
{
PrintFormat("Daily loss limit reached: %.2f%% (Max allowed %.2f%%). Halting new trades.", lossPercent, maxDailyLossPercent);
return true;
}
return false;
}
//+------------------------------------------------------------------+
// Calculate lot size, capped by max risk per trade percent
double CalculateLotSize(double sl_distance_price)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0 || sl_distance_price <= 0)
{
Print("Invalid inputs for lot size calculation");
return inpLot;
}
double maxRiskMoney = balance * (maxRiskPerTradePercent / 100.0);
double lot = 0.0;
if(!useRiskPercent)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lot = inpLot;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
lot = MathFloor(lot / lot_step) * lot_step;
}
else
{
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
{
Print("Invalid symbol trade parameters for lot calc.");
return inpLot;
}
double point_value = tick_value / tick_size;
double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
if(calculatedLot <= 0)
return inpLot;
double lotMaxRisk = maxRiskMoney / (sl_distance_price * point_value * contract_size);
lot = MathMin(calculatedLot, lotMaxRisk);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lot = MathFloor(lot / lot_step) * lot_step;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
}
return lot;
}
//+------------------------------------------------------------------+
bool IsPositionOpen(ENUM_POSITION_TYPE type)
{
int total = PositionsTotal();
for(int i = 0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == type)
return true;
}
}
}
return false;
}
//+------------------------------------------------------------------+
bool CanUpdateTrailing(ulong ticket)
{
datetime now = TimeCurrent();
int count = ArraySize(g_trailingUpdateInfo);
for(int i=0; i<count; i++)
{
if(g_trailingUpdateInfo[i].position_ticket == ticket)
{
if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec)
return false;
g_trailingUpdateInfo[i].last_update = now;
return true;
}
}
ArrayResize(g_trailingUpdateInfo, count + 1);
g_trailingUpdateInfo[count].position_ticket = ticket;
g_trailingUpdateInfo[count].last_update = now;
return true;
}
//+------------------------------------------------------------------+
// ... [Trailing functions unchanged, omitted here for brevity] ...
//+------------------------------------------------------------------+
void OnTick()
{
// === BEGIN NEW: initialize initial equity once ===
if(g_initialEquity == 0.0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return; // stop trading if combined drawdown hit
}
// === END NEW ===
ResetDailyLossIfNewDay();
UpdateDailyLoss();
if(IsDailyLossExceeded())
return;
if(enableTrailingSL && trailingStopMode != TrailingNone)
{
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(trailingStopMode == TrailingMarketStructure)
UpdateTrailingStopByMarketStructure(ticket);
else if(trailingStopMode == TrailingATR)
UpdateTrailingStopByATR(ticket);
else if(trailingStopMode == TrailingHybrid)
UpdateTrailingStopHybrid(ticket);
}
}
}
}
int openPosCount = 0;
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
openPosCount++;
}
}
}
if(maxPositions > 0 && openPosCount >= maxPositions)
return;
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
double ma_buf[];
ArrayResize(ma_buf, 1);
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
PrintFormat("EMA data copy failed, error %d", GetLastError());
return;
}
double atr_buf[];
ArrayResize(atr_buf, 1);
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
{
PrintFormat("ATR data copy failed, error %d", GetLastError());
return;
}
double ma = ma_buf[0];
double atr = atr_buf[0];
if(atr <= 0)
{
atr = 10.0 * _Point;
Print("ATR value invalid or zero, falling back to 10 points");
}
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
if(highestBar < 0 || lowestBar < 0)
{
Print("Error getting swing high/low bars");
return;
}
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(ask <= 0 || bid <= 0)
return;
double price_htf = iClose(_Symbol, maTimeframe, 1);
if(price_htf <= 0 || ma <= 0)
return;
bool is_uptrend = (price_htf > ma);
bool is_downtrend = (price_htf < ma);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double lot = CalculateLotSize(sl_dist);
if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
return;
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && is_uptrend)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Buy order rejected, retcode %d", result.retcode);
else
PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Sell order rejected, retcode %d", result.retcode);
else
PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
}
}
}
else
{
if(ask > lastSwingHigh && is_uptrend)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
else
PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
else
PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
}
}
}
}
Summary of new behavior:
The variable g_initialEquity stores equity once per EA instance on first tick.
The equity drawdown is checked each tick.
If equity drop exceeds the new param maxDailyLossAmount (e.g., $500), the EA stops opening new trades immediately on all symbols running this EA since equity is shared by the account.
This works across multiple symbols, multiple EA instances, because equity is account-wide.
How to Use:
Set input maxDailyLossAmount = 500.0 (or your desired dollar amount max daily loss limit).
Use your existing maxDailyLossPercent for per-symbol daily loss % limits if you want.
Run an instance of this EA on each symbol/chart with appropriate unique magic numbers.
The combined equity drawdown stops new trades globally.
If you want, I can create .set files or help with further customization.
Just ask!
maxDailyLossPercent
This allows individual symbol risk control alongside global combined equity drawdown control.
5. Minor fixes / casting for PositionGetInteger and comparison
E.g., changed magic number comparison in position enumeration to:
Added comments in code to highlight new added parts for easier maintenance.
What Did NOT Change
Core trade entry and exit logic.
Trailing stop implementation.
Lot sizing algorithm.
Risk % and max positions logic.
Swing detection methods.
Time filter.
Summary Table:
Feature
Description
Status
maxDailyLossAmount input
New parameter for combined max daily loss as absolute $ amount (equity drawdown)
Added
g_initialEquity variable
Holds initial account equity snapshot for drawdown calculation
Added
Equity drawdown check in OnTick
Stops new trades if account equity drops below initial equity minus maxDailyLossAmount
Added
Existing per-symbol daily loss
Tracks daily losses per symbol/magic number (percent-based)
Kept unchanged
Magic number comparison fix
Casting magic number to (long) for safe comparison
Applied
Version updated
From 1.4 to 1.5 to reflect added functionality
Updated
If you want, I can produce a changelog style file or annotate the full EA code with all changes clearly marked so you can maintain version history.
Final notes
The added equity drawdown check works well for multi-symbol multi-instance EA setups sharing the same broker account.
It complements your existing per-symbol daily loss limits for a layered risk management approach.
You may add persistence (to keep g_initialEquity over MT5 restarts) or profit target management in future iterations.
If you want further updates or adjustments (example: auto-closing trades on max loss, profit target automation, persistent storage), just let me know!
Replace with just:
mql5
// No daily loss percent tracking, equity drawdown check handles max daily loss
6. In OnTick(), keep only equity drawdown check as max daily loss condition
mql5
if(g_initialEquity == 0.0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return; // stop trading if combined drawdown hit
}
7. Remove any references to dailyLossMoney, dailyLossResetTime elsewhere.
Summary: Your EA after cleanup will only use one firm daily max loss measure based on absolute equity drawdown, which works globally and avoids discrepancy between symbols.
If you want, I can prepare the full cleaned and updated EA code with the old daily percent loss code removed so you can simply load and test it.
Just confirm, and I'll provide the cleaned full source!
//+------------------------------------------------------------------+
//| Advanced_BoS_EA_MT5.mq5 |
//| Author: LucienWP |
//| Version: 1.5 |
//| Published: 2025-06-XX |
//| Description: Break Of Structure EA |
//| with dynamic lot sizing, dynamic trailing stops (market structure|
//| or ATR or hybrid), throttling and safety buffers |
//+------------------------------------------------------------------+
#property copyright "LucienWP"
#property version "1.5"
#property strict
#property script_show_inputs
#include <Trade\Trade.mqh>
input double inpLot = 0.05; // Fixed lot size per trade
input bool useRiskPercent = false; // Use risk % to calculate lot size
input double riskPercent = 1.0; // Risk % per trade if enabled
input int sl_atr_mult = 3; // SL multiplier for ATR (initial SL distance)
input double r2r_ratio = 2.0; // Risk-to-Reward ratio (TP = SL * r2r_ratio)
input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // ATR timeframe
input int atrPeriod = 14; // ATR period
input int swingLookback = 20; // Bars lookback for swing detection (trade entries)
input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe for entries
input int maPeriod = 50; // EMA period for trend filter
input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe
input int tradeStartHour = 7; // Trading start hour (server)
input int tradeEndHour = 22; // Trading end hour (server)
input int maxPositions = 1; // Max simultaneous EA positions (0=no limit)
input uint inpMagicNumber = 123456; // Magic number for EA positions (uint for compatibility)
// Trailing stop enable and mode
input bool enableTrailingSL = true; // Enable trailing stop
enum ENUM_TrailingStopMode
{
TrailingNone = 0, // No trailing stop
TrailingMarketStructure = 1, // Trailing by market structure swings
TrailingATR = 2, // Trailing by ATR-based stop loss
TrailingHybrid = 3 // Hybrid trailing: market structure + ATR
};
input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid; // Trailing stop mode selector
// New inputs for trailing settings (separate from entry/trade)
input int ms_swingLookback = 20; // Swing trailing lookback bars (separate from trade entry)
input double atr_trail_mult = 2.5; // ATR trailing multiplier (can differ from SL multiplier)
// Trailing enhancements
input uint TrailUpdateIntervalSec = 15; // Minimum seconds between trailing stop updates per position
input double MinSLBufferATRMult = 1.0; // Minimum SL distance buffer in ATR multiples
input double TrailingProfitTriggerPerc = 0.5; // Trailing activates once price moves this fraction of SL distance in profit
// 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 input for max risk per trade (% of account balance)
input double maxRiskPerTradePercent = 1.0; // Max risk per trade as % of account balance
// --- NEW input: MAX DAILY LOSS in absolute dollars for combined equity drawdown ---
input double maxDailyLossAmount = 500.0; // Max combined daily loss $ amount (equity drawdown)
CTrade trade;
int ma_handle = INVALID_HANDLE;
int atr_handle = INVALID_HANDLE;
string swingHighLineName = "SwingHighLine";
string swingLowLineName = "SwingLowLine";
struct TrailingUpdateInfo
{
ulong position_ticket;
datetime last_update;
};
TrailingUpdateInfo g_trailingUpdateInfo[];
// --- Global static variable to hold initial equity on first tick ---
static double g_initialEquity = 0.0;
//+------------------------------------------------------------------+
void OnInit()
{
PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", __DATE__);
PrintFormat("MagicNumber=%u, SwingTF=%d, ATR period=%d, SL ATR Mult=%d",
inpMagicNumber, swingTF, atrPeriod, sl_atr_mult);
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE);
if(ma_handle == INVALID_HANDLE)
{
Print("Failed to create EMA handle");
return;
}
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
IndicatorRelease(ma_handle);
return;
}
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing high line");
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen);
ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);
if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, 0, 0))
{
Print("Failed to create swing low line");
ObjectDelete(0, swingHighLineName);
IndicatorRelease(ma_handle);
IndicatorRelease(atr_handle);
return;
}
ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed);
ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2);
ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true);
ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true);
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
ObjectDelete(0, swingHighLineName);
ObjectDelete(0, swingLowLineName);
if(ma_handle != INVALID_HANDLE)
{
IndicatorRelease(ma_handle);
ma_handle = INVALID_HANDLE;
}
if(atr_handle != INVALID_HANDLE)
{
IndicatorRelease(atr_handle);
atr_handle = INVALID_HANDLE;
}
}
//+------------------------------------------------------------------+
// Calculate lot size, capped by max risk per trade percent
double CalculateLotSize(double sl_distance_price)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
if(balance <= 0 || sl_distance_price <= 0)
{
Print("Invalid inputs for lot size calculation");
return inpLot;
}
double maxRiskMoney = balance * (maxRiskPerTradePercent / 100.0);
double lot = 0.0;
if(!useRiskPercent)
{
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lot = inpLot;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
lot = MathFloor(lot / lot_step) * lot_step;
}
else
{
double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);
if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
{
Print("Invalid symbol trade parameters for lot calc.");
return inpLot;
}
double point_value = tick_value / tick_size;
double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
if(calculatedLot <= 0)
return inpLot;
double lotMaxRisk = maxRiskMoney / (sl_distance_price * point_value * contract_size);
lot = MathMin(calculatedLot, lotMaxRisk);
double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
lot = MathFloor(lot / lot_step) * lot_step;
if(lot < min_lot) lot = min_lot;
if(lot > max_lot) lot = max_lot;
}
return lot;
}
//+------------------------------------------------------------------+
bool IsPositionOpen(ENUM_POSITION_TYPE type)
{
int total = PositionsTotal();
for(int i = 0; i < total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
if(pos_type == type)
return true;
}
}
}
return false;
}
//+------------------------------------------------------------------+
bool CanUpdateTrailing(ulong ticket)
{
datetime now = TimeCurrent();
int count = ArraySize(g_trailingUpdateInfo);
for(int i=0; i<count; i++)
{
if(g_trailingUpdateInfo[i].position_ticket == ticket)
{
if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec)
return false;
g_trailingUpdateInfo[i].last_update = now;
return true;
}
}
ArrayResize(g_trailingUpdateInfo, count + 1);
g_trailingUpdateInfo[count].position_ticket = ticket;
g_trailingUpdateInfo[count].last_update = now;
return true;
}
//+------------------------------------------------------------------+
// Note: All your trailing stop functions remain unchanged here — include as-is.
// For brevity, they are omitted here but **you should keep them** as in your original code.
//+------------------------------------------------------------------+
void OnTick()
{
// Initialize initial equity once on first tick
if(g_initialEquity == 0.0)
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return; // stop trading if combined drawdown hit
}
if(enableTrailingSL && trailingStopMode != TrailingNone)
{
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(trailingStopMode == TrailingMarketStructure)
UpdateTrailingStopByMarketStructure(ticket);
else if(trailingStopMode == TrailingATR)
UpdateTrailingStopByATR(ticket);
else if(trailingStopMode == TrailingHybrid)
UpdateTrailingStopHybrid(ticket);
}
}
}
}
int openPosCount = 0;
int total = PositionsTotal();
for(int i=0; i<total; i++)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
{
openPosCount++;
}
}
}
if(maxPositions > 0 && openPosCount >= maxPositions)
return;
MqlDateTime tm;
TimeToStruct(TimeCurrent(), tm);
if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
return;
double ma_buf[];
ArrayResize(ma_buf, 1);
if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
{
PrintFormat("EMA data copy failed, error %d", GetLastError());
return;
}
double atr_buf[];
ArrayResize(atr_buf, 1);
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
{
PrintFormat("ATR data copy failed, error %d", GetLastError());
return;
}
double ma = ma_buf[0];
double atr = atr_buf[0];
if(atr <= 0)
{
atr = 10.0 * _Point;
Print("ATR value invalid or zero, falling back to 10 points");
}
double sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
if(highestBar < 0 || lowestBar < 0)
{
Print("Error getting swing high/low bars");
return;
}
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if(ask <= 0 || bid <= 0)
return;
double price_htf = iClose(_Symbol, maTimeframe, 1);
if(price_htf <= 0 || ma <= 0)
return;
bool is_uptrend = (price_htf > ma);
bool is_downtrend = (price_htf < ma);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
double lot = CalculateLotSize(sl_dist);
if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
return;
MqlTradeRequest request = {};
MqlTradeResult result = {};
request.symbol = _Symbol;
request.volume = lot;
request.deviation = 10;
request.magic = inpMagicNumber;
if(!enableReverseEntries)
{
if(ask > lastSwingHigh && is_uptrend)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Buy order rejected, retcode %d", result.retcode);
else
PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Sell order rejected, retcode %d", result.retcode);
else
PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
}
}
}
else
{
if(ask > lastSwingHigh && is_uptrend)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_SELL;
request.price = bid;
request.sl = NormalizeDouble(bid + sl_dist, digits);
request.tp = NormalizeDouble(bid - tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
else
PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
}
}
else if(bid < lastSwingLow && is_downtrend)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
request.action = TRADE_ACTION_DEAL;
request.type = ORDER_TYPE_BUY;
request.price = ask;
request.sl = NormalizeDouble(ask - sl_dist, digits);
request.tp = NormalizeDouble(ask + tp_dist, digits);
if(!OrderSend(request, result))
PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
else if(result.retcode != TRADE_RETCODE_DONE)
PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
else
PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
}
}
}
}
Notes:
The trailing stop functions (UpdateTrailingStopByMarketStructure(), UpdateTrailingStopByATR(), and UpdateTrailingStopHybrid()) are omitted above for brevity. Please use your original implementations of these functions as they are unchanged.
You can set the new input parameter maxDailyLossAmount to your firm’s combined dollar loss limit (e.g., 500) to prevent new trades once cumulative equity drawdown hits that.
If you want, I can also help create .set files for easy parameter loading on multiple charts.
Just let me know if you need help with that or with anything else!
Ensure these functions are placed anywhere above or before their calls inside OnTick(). Usually, just paste them after your global variables, before or after OnInit(), or right before OnTick().
If you want, I can provide the full EA code including these trailing functions incorporated into the previous complete code I gave so you have a ready-to-compile file.
Please confirm if you want the full code with trailing functions included, or if you want me to send you those three functions only.
And call CheckDailyReset() near the start of OnTick().
If you want, I can help implement such daily equity reset or more advanced max loss tracking/resume logic in your EA.
To summarize your original question:
"The combined equity drawdown stops new trades globally until when?"
Answer:
It stops new trades indefinitely (until you restart/reinitialize the EA or MT5 terminal) because the baseline equity (g_initialEquity) remains fixed on EA start and does not update automatically.
Let me know if you want me to help implement automatic daily resetting or dynamic trade resuming based on equity!
Load on each chart for your symbols (e.g., US100, GER30) with distinct magic numbers if needed
Set maxDailyLossAmount to your daily max loss in dollars (e.g., 500)
The EA will reset the equity baseline once per day at server midnight automatically
Maximum combined drawdown check applies and will block new trades on exceeding limit
EA resumes trading fresh each day with updated baseline
If you want any additional features or help with setup, just ask!
More Aggressive Trailing:
Adjust trailing stop parameters to lock in profits earlier.
Consider dynamic trailing that tightens with faster market moves.
Add Time-Based Exits:
Close trades after a certain time if no movement, reducing exposure to stagnating trades.
Break-even Stop:
Move SL to breakeven once trade is in reasonable profit.
5. Money Management
Lower Risk Percent:
Sometimes reducing per-trade risk reduces losses and allows the EA to survive longer improving overall profitability.
Max Positions:
Limit concurrent trades to avoid overexposure.
6. Backtesting and Optimization
Walk-Forward Testing:
Optimize parameters on one data period and test on forward periods to avoid curve-fitting.
Use Quality Tick Data:
Better data means more accurate backtests.
Monte Carlo or Stress Testing:
Test EA under parameter perturbations to ensure robustness.
7. Technical Improvements
Slippage and Spread Handling:
Ensure your deviation parameter is adequate to handle broker spreads/slippage.
Order Send Retries:
Implement retries on failed orders due to temporary rejections.
Add Logging and Alerts:
Detect problematic trades or exceptions quickly.
8. Market and Timeframe Selection
Some pairs or indices behave better with BoS strategies.
Adjust timeframe and symbols for best synergy.
Avoid choppy markets.
9. Consider Adding Filters for News Events
Disable trading during high-impact news to avoid false breakouts or slippage.
Summary
Focus Area
Suggestions
Parameters
Tune lookbacks, ATR multipliers, R:R ratio
Filters
Add trend, volume, volatility filters
Entry Criteria
More confirmations, candle closes
Exit Strategies
Aggressive trailing, breakeven stops
Risk Management
Lower risk %, limit max trades
Testing & Optimization
Walk-forward, quality data, stress testing
Technical Checks
Slippage handling, retries
Market & Timing
Optimize pairs/timeframes, avoid news
Would you like help with parameter optimization suggestions or modifying your EA to incorporate some of these ideas? I can also help write specific code snippets for enhanced features like filtering or modified trailing stops.
Scaling in (partial entries) manages risk better and smoothes average price, which may improve trade outcomes in choppy markets.
4. Trailing Stop & Exit Strategy
Trailing stops protect profits by moving the SL closer as price moves in your favor.
Adjust trailing stop aggressiveness: too tight trailing stops may prematurely close good trades; too loose trailing stops may give back profits.
Break-even stops: Moving SL to entry price once in profit avoids turning winners into losers.
Time-based exits: Close trade after a set time if no progress, releasing capital and minimising exposure.
These help maximize gains, preserve profits, and control risk dynamically.
5. Money Management
Proper money management—like keeping per-trade risk low (generally 1-2%)—helps you survive losing streaks and reduces emotional stress.
Controlling the maximum number of open positions avoids overexposure and correlated risks.
6. Backtesting & Optimization
Running thorough backtests over different market conditions and multiple periods ensures your EA isn’t curve-fitted to a narrow data range.
Use walk-forward optimization to test parameter robustness on unseen data.
Prefer backtests performed on high-quality tick or 1-second data for accurate results.
7. Technical Improvements
Accounting for slippage, spread widenings, and order rejections in your code ensures smoother live trading.
Adding retries or handling of temporary rejections can prevent missed trades.
8. Market and Timeframe Selection
Not all symbols behave the same with the same strategy. Some breakouts work better on volatile indices, others on forex pairs.
Matching timeframe with your breakout approach is key (e.g., M5 or M15 for quick breakouts, H1 for swing breaks).
9. News and Event Filters
Trading during high-impact news events can produce erratic price spikes and slippage.
Filtering out trades around major news reduces false breakouts and big losses.
Putting it all together:
To make your EA win more, you want to:
Tune parameters to your trading symbol and timeframe.
Add extra confirmations and filters to reduce bad trades.
Improve trailing stops and exits to lock in profit.
Implement sound risk and trade management.
Use quality backtesting and adapt your strategy to data.
If you want, I can help by:
Suggesting specific parameter ranges to test.
Adding confirmation filters to your EA code.
Implementing trailing stop improvements or break-even stops.
Helping you set up backtesting and optimization.
Would you like me to help with changes or enhancements in your EA code, or guide you on testing and tuning?
double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
double lastClose = iClose(_Symbol, swingTF, 1); // close of last completed swingTF bar
bool buyConfirmed = (lastClose > lastSwingHigh) && is_uptrend;
bool sellConfirmed = (lastClose < lastSwingLow) && is_downtrend;
if(!enableReverseEntries)
{
if(buyConfirmed)
{
if(!IsPositionOpen(POSITION_TYPE_BUY))
{
// Place Buy order logic here, using Ask price etc.
}
}
else if(sellConfirmed)
{
if(!IsPositionOpen(POSITION_TYPE_SELL))
{
// Place Sell order logic here
}
}
}
else
{
// Reverse logic, similar but inverted conditions
}
Benefits:
This simple change makes sure your EA only enters after a full bar closes beyond your swing high/low, filtering many false signals.
It avoids impulsive entries triggered by intra-bar spikes or noise.
Things to consider:
Your EA may enter with a slight lag (by one bar) compared to price spikes, but the tradeoff favoring higher accuracy often outweighs the small delay.
Ensure CopyBuffer, iClose and other functions use correct shift indices (1 for the last fully closed bar).
If you want, I can help modify your full EA code to include this candle close confirmation for entry. Would you like me to do that?
Copy-paste these exactly as is into your EA source (preferably before OnTick()).
This will resolve your compiler errors related to missing trailing stop functions.
Make sure any ms_swingLookback, atr_trail_mult, MinSLBufferATRMult, and TrailingProfitTriggerPerc variables referenced inside these trailing functions are declared globally as in your original EA.
If you want I can also bundle these with your entire latest EA code in one file ready to compile. Just ask!
Copy entire code to a new .mq5 file in your MQL5\Experts folder.
Compile with MetaEditor. No errors should appear.
Attach the EA to multiple charts (e.g., US100 and GER30).
Customize inputs including maxDailyLossAmount, enableCloseConfirmation, enableReverseEntries, etc.
Monitor trades and logs.
If you want me to also generate .set files or help with optimization tips or testing methodology, just ask!
Check if you ever have lastSwingClose > lastSwingHigh (for buy signal).
If not, try reducing swingLookback to catch more recent swing levels.
4. Alternative entry confirmation — only confirm close beyond just previous swing
You might want to check not the highest swing within lookback but the immediate previous swing high and low bars, which can be usually at shift 2 or 3.
Because you use swingTF = M1 (or other), the trade will open only after this smaller timeframe candle closes beyond the swing level — this causes some delay and may reduce signals on very fast markets.
6. Quick fix suggestion for testing
Try temporarily disable enableCloseConfirmation and check if trades open using current ask/bid prices as before — this verifies that your swing levels and conditions in general work.
If you want I can modify your EA to:
Add debug prints for swing levels and closes.
Add a fallback or alternative confirmation logic.
Help you tune swingLookback and swingTF.
Provide a version that optionally logs signals before trading.
Summary
enableCloseConfirmation = true > requires last closed candle on swingTF to close beyond swing high/low.
If swing high/low or last close conditions never met, no trades will open.
Tune/lookback/symbol/timeframes matter a lot for triggers.
Use prints/debugging to check values.
If you want, share your symbol/timeframe and current settings and I can help you tune this specifically or add debug output to pinpoint the issue.
Your enableCloseConfirmation blocks trading because the close is never past the used swing levels.
For testing, try smaller lookback ranges or use fixed offset bars for swing highs/lows.
Use Print statements to see actual bar values and candle closes.
Adjust parameters until candlestick closes can frequently breach those levels on swingTF.
If you want, I can update your full EA with this simpler swing level approach and add debug prints so you can see values in Experts log and adjust swingLookback accordingly.