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 overall looks well structured and includes ADX filtering and a losing streak filter, along with floating risk cap and trailing stops. Below are a few critical observations and suggestions to ensure correct compilation and proper functioning:
1. Compilation Check
Your code compiles fine for the most part except one potential issue in trailing stop update functions where OrderSend(req, res) is called. In MQL5, the function to send trade requests is OrderSend(MqlTradeRequest&, MqlTradeResult&) which you use correctly. Just ensure your MT5 platform is updated and Trade.mqh is included correctly.
2. Floating Risk Cap (Position Close Logic)
You implemented a floating loss cap where any open position losses exceeding maxRiskPerTradePercent of balance will be closed.
and update their price in OnTick. This is good for visualization but will consume some resources, so consider updating lines less frequently if needed.
8. Minor Improvements / Fixes:
ArrayResize before CopyBuffer:
You do ArrayResize(ma_buf,1) then CopyBuffer(ma_handle, 0, 1, 1, ma_buf) which is correct.
Trailing Stop Validate Prices:
On UpdateTrailingStopByATR() you limit the new SL compared to current price and existing SL properly.
Trailing Hybrid Logic:
You combine MS and ATR trailing stop distances, choosing the safer SL. This logic looks well-thought-out.
Timeframe and Swing Lookback:
You use swingTF=PERIOD_M1 by default and swingLookback=20 bars. Check these settings with your strategy.
9. Suggestions For Further Enhancement
Error Handling for trade.PositionClose(ticket)
You call trade.PositionClose(ticket) without verification of success or error logging.
Add:
if(!trade.PositionClose(ticket))
PrintFormat("Failed to close position %I64d for floating loss cap, error %d", ticket, GetLastError());
Position Open Limit Check
You count positions each tick. If you allow multiple symbols or magic numbers, make sure you count only relevant ones. You do that, so should be fine.
Trailing Stop Updates Frequency TrailUpdateIntervalSec controls trailing SL updates. You run that check each tick, which is fine.
Check Symbol in History Deals
You use string compare to match symbol for losing streak update:
I recommend testing in strategy tester and demo first.
Ensure indicator handles are released properly on deinit.
Add more verbose logs if decision-making steps need debugging.
Manage resource usage on live with timers for non-essential updates like drawing swing lines.
If you want, I can help you integrate a particular feature or review specific parts, or help with optimization/testing tips. Otherwise, your EA is in a good shape for compilation and functional testing.
The daily loss limit in your EA is implemented to prevent new trades from opening once your account equity has dropped by a certain amount during the current trading day. This acts as a form of daily drawdown control or loss limit, which helps protect your account from excessive losses on a single day.
How the Daily Loss Limit Works In Your EA:
Initialization of Daily Equity:
Each new day, the EA stores the account equity at the start of the trading day in the variable g_initialEquity.
If the loss exceeds the user-specified max daily loss, the EA stops opening new trades for the rest of the day:
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return;
}
The configured input controlling this is:
input double maxDailyLossAmount = 500.0;
In simple terms:
Suppose at midnight (or when the EA starts), your equity is $10,000 → this becomes g_initialEquity.
During the trading day, if equity drops to 9,400,yourdrawdownis600.
If your maxDailyLossAmount was set to $500, this means you've exceeded your daily loss limit.
The EA will then stop opening any new trades until the next day when equity is reset.
This mechanism protects your account from continuous losses during a bad trading day, forcing the EA to pause trading until the next day.
What daily loss limit does NOT do:
It does NOT close existing open trades.
It only prevents opening new trades once the loss limit is hit.
You still have manual or auto trade management (like closing trades by floating loss cap or manual intervention).
Why is this useful?
Limits your maximum potential loss per day.
Helps to prevent "blowing" your account by repeatedly entering losing trades.
Encourages discipline and risk control.
Provides a safety net especially during volatile or unexpected market conditions.
If you want to implement an automatic closing of trades once daily loss limit is hit, that would require a different logic, but as per your current EA, the daily loss acts as a stop opening entries filter.
If you want, I can help further explain or improve this feature!
To add automatic closing of all open trades when the daily loss limit is exceeded, you need to modify your OnTick() code where the daily loss check is done.
Currently, you just return (skip placing new trades) when the daily loss limit is exceeded:
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
return;
}
What to do:
Instead of just returning, close all open positions with your EA's magic number and symbol when the daily loss is exceeded.
Here is the modified code snippet with automatic position closing added:
Replace the block above with:
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). Closing all open trades and no new trades allowed.", maxDailyLossAmount, equityDrawdown);
int total = PositionsTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
// Only close positions matching your EA magic number and symbol
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(!trade.PositionClose(ticket))
PrintFormat("Failed to close position %I64d after daily loss limit hit, error %d", ticket, GetLastError());
else
PrintFormat("Position %I64d closed due to daily loss limit.", ticket);
}
}
}
// After closing all positions, prevent further trade opening by returning
return;
}
Explanation:
When the drawdown is greater or equal to your limit (maxDailyLossAmount),
All open trades opened by your EA (same symbol and magic number) are closed immediately.
Errors closing positions are printed to logs for debugging.
After closing, the EA stops further trading for the rest of the tick.
Full context example (replace the existing daily loss check part in OnTick()):
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double equityDrawdown = g_initialEquity - currentEquity;
if(equityDrawdown >= maxDailyLossAmount)
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). Closing all open trades and no new trades allowed.", maxDailyLossAmount, equityDrawdown);
int total = PositionsTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(!trade.PositionClose(ticket))
PrintFormat("Failed to close position %I64d after daily loss limit hit, error %d", ticket, GetLastError());
else
PrintFormat("Position %I64d closed due to daily loss limit.", ticket);
}
}
}
return; // stop further trading
}
Additional suggestions:
You may want to wait for all closes to be fully processed before stopping trading, but that requires extra code to check position status on subsequent ticks.
Make sure your broker or platform supports immediate position closing without delays.
If you want, you can also send email alerts or notifications when daily loss limit is hit and positions are closed.
If you want me to adjust the whole EA or help with any other feature, just ask!
To make your EA stop further trading for the rest of the day after closing all positions due to the daily loss limit, you'll need to add a flag that remembers when the daily loss limit was hit and positions closed. Then, check that flag before opening any new trades on subsequent ticks during the same day.
How to implement "stop trading for rest of the day" after daily loss limit is hit:
Declare a global/static flag variable, e.g.:
static bool g_dailyLossLimitHit = false;
Reset this flag at the start of each new day, together with g_initialEquity. So add this to your daily reset function:
void ResetDailyEquityIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm;
TimeToStruct(now, tm);
MqlDateTime todayMidnight = {};
todayMidnight.year = tm.year;
todayMidnight.mon = tm.mon;
todayMidnight.day = tm.day;
todayMidnight.hour = 0;
todayMidnight.min = 0;
todayMidnight.sec = 0;
datetime midnightTime = StructToTime(todayMidnight);
if(g_lastResetDay != midnightTime)
{
g_lastResetDay = midnightTime;
g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
g_dailyLossLimitHit = false; // reset flag at new day
PrintFormat("Daily equity reset at %s new initialEquity=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity);
}
}
When you detect the daily loss limit exceeding and close positions, set this flag to true:
if(equityDrawdown >= maxDailyLossAmount)
{
if(!g_dailyLossLimitHit) // only do once per day
{
PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). Closing all open trades and no new trades allowed for rest of day.", maxDailyLossAmount, equityDrawdown);
int total = PositionsTotal();
for(int i = total - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(PositionSelectByTicket(ticket))
{
if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
PositionGetString(POSITION_SYMBOL) == _Symbol)
{
if(!trade.PositionClose(ticket))
PrintFormat("Failed to close position %I64d after daily loss limit hit, error %d", ticket, GetLastError());
else
PrintFormat("Position %I64d closed due to daily loss limit.", ticket);
}
}
}
g_dailyLossLimitHit = true; // set flag so no new trades until next day
}
return; // Stop trading for rest of the day
}
Before placing any new trades, check the flag:
At the very start of your OnTick() before any new trade logic:
if(g_dailyLossLimitHit)
{
Print("Daily loss limit has been hit today - no new trades allowed.");
return;
}
Summary of changes:
// Global flag
static bool g_dailyLossLimitHit = false;
// In ResetDailyEquityIfNewDay()
g_dailyLossLimitHit = false;
// In OnTick(), early check:
if(g_dailyLossLimitHit)
{
Print("Daily loss limit has been hit today - no new trades allowed.");
return;
}
// When daily loss limit exceeded:
if(equityDrawdown >= maxDailyLossAmount)
{
if(!g_dailyLossLimitHit)
{
// Close all positions as previously described
g_dailyLossLimitHit = true;
}
return;
}
This will have the desired effect:
At day start, flag reset → trading allowed.
On daily loss limit breach, close all positions → flag set → no more trades that day.
Next day, flag resets → trading resumes.
If you want, I can provide the full modified OnTick() with these changes integrated. Just ask!