Quick Answer
An MQL5 daily loss limit needs a defined trading-day reset, a precise profit-and-loss measurement policy, and a persistent lock that prevents new entries once the threshold is reached. Decide whether it measures balance, equity, realized deals, floating P/L, or a combination. For multiple EAs on one account, a limit checked independently by each EA is not a reliable account-wide guard.
Key Facts
| Design choice | Decide before coding | |---|---| | Reset clock | Broker server day, UTC day, or the prop firm's specified session | | Loss measure | Realized P/L, equity drawdown, or both | | Baseline | Day-start balance/equity or a specified reference | | Scope | One EA, one symbol, or the entire account | | Lock behavior | Block entries only, or also close positions / cancel pending orders | | Restart behavior | Preserve the lock and baseline across terminal or EA restarts |
Daily loss rules vary between firms and account types. Some use a fixed starting balance, others use equity including open losses, and the reset may follow a particular server timezone. Do not assume a common definition: check the actual account agreement and use its clock and calculation policy.
Also decide how the guard treats open positions that cross the reset boundary. If the rule is based on total account equity, losses on positions opened yesterday may still matter today. If it is based only on today's closed deals, floating losses may not trigger the same threshold. These are different policies and should not be conflated in the name of a single “daily loss” setting.
Define the Rule Before the Implementation
Suppose an account starts the trading day with a chosen reference value R, and the limit is L in account currency. An equity-based guard might block new trades when:
reference equity - current equity >= loss limit
A percentage threshold can be converted into cash using the reference specified by the rule:
cash limit = reference value × daily loss percentage / 100
That still leaves important choices. Does the system include commissions and swap? Do deposits affect the reference? Do open positions opened before the reset count? Should the EA close open exposure when the limit is hit, or merely prevent new orders? These decisions materially change behavior and must be aligned with the relevant risk policy.
MQL5 Equity-Limit Check
The following example uses the account's current equity and a baseline saved once per broker-server calendar day in a terminal global variable. It is an entry gate for a single coordinated EA instance; it does not close positions, cancel orders, or coordinate independent EAs. The baseline is captured on the first tick on which this code runs for that day, so if the applicable rules require an exact reset snapshot, capture and persist that value at the required reset time instead.
input double DailyLossLimitPercent = 5.0;
int OnInit()
{
if (DailyLossLimitPercent <= 0.0)
{
Print("DailyLossLimitPercent must be greater than zero.");
return INIT_PARAMETERS_INCORRECT;
}
return INIT_SUCCEEDED;
}
string DailyEquityKey()
{
const datetime serverTime = TimeTradeServer();
if (serverTime <= 0)
return "";
MqlDateTime day;
if (!TimeToStruct(serverTime, day))
return "";
return StringFormat("CFO_DLE_%I64d_%04d%02d%02d",
AccountInfoInteger(ACCOUNT_LOGIN),
day.year, day.mon, day.day);
}
bool GetDayStartEquity(double &baseline)
{
const string key = DailyEquityKey();
if (key == "")
{
Print("Cannot read trade-server date for daily loss guard.");
return false;
}
if (!GlobalVariableCheck(key))
{
const double equity = AccountInfoDouble(ACCOUNT_EQUITY);
if (equity <= 0.0 || GlobalVariableSet(key, equity) == 0)
{
Print("Could not persist daily equity baseline. Error: ",
GetLastError());
return false;
}
}
baseline = GlobalVariableGet(key);
return baseline > 0.0;
}
bool DailyLossLimitReached(const double baseline,
const double limitPercent)
{
if (baseline <= 0.0 || limitPercent <= 0.0)
return true;
const double lossLimit = baseline * limitPercent / 100.0;
const double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
return baseline - currentEquity >= lossLimit;
}
void OnTick()
{
double dayStartEquity = 0.0;
if (!GetDayStartEquity(dayStartEquity))
return; // fail closed: do not evaluate new entries without a baseline
if (DailyLossLimitReached(dayStartEquity, DailyLossLimitPercent))
{
Print("Daily equity loss limit reached; new entries are blocked.");
return;
}
// Evaluate entry signals and submit orders only below the limit.
}
The example deliberately fails closed if it cannot obtain or persist the baseline. Terminal global variables are local terminal state, not a distributed lock; two terminals or independent EAs can still race. For an account-wide rule, use one coordinator that owns all relevant entries, or a separately designed shared risk service.
Reliable State and Multiple EAs
The reference and lock must survive an EA restart. Store them persistently with an account-and-date key, validate them at startup, and choose a documented safe behavior if state is missing or corrupt; do not silently reset the counter.
For several strategies on one account, use a shared risk manager or one coordinated component. Separate EAs can race between checking the limit and placing orders, so a terminal global variable alone is not a complete multi-process risk system.
At the point an EA considers a new order, the control flow should be explicit:
1. Read or update the current trading-day state.
2. Calculate loss using the selected policy.
3. If threshold is reached, persist the lock and stop new entries.
4. Apply the documented policy to existing positions and pending orders.
5. Log the reason, reference, measured loss, threshold, and reset time.
Blocking entries does not close positions or cancel pending orders. If the policy requires either action, define its account scope and verify every trade-server response; local checks cannot control unrelated manual or EA trades.
Testing Checklist
Test around the reset boundary, not only midday. Simulate an EA restart after a loss-limit breach and verify the lock remains. Check realized losses, floating losses, commissions, deposits, and positions carried over from the previous day according to the chosen policy. If multiple EAs share the account, test the shared control with overlapping signals.
For prop traders, compare the EA's measurement to the firm's rules and dashboard. A local guard is not a compliance guarantee or protection from gaps. Log whether trading is permitted, why a lock is active, and the next reset time.
Related Guides
- What to check in a trading bot before going live: a pre-live checklist for stops, lot size, spread and trade results
- Filter positions by magic number in MQL5: a code guide
- MQL5 trade retcodes: read CTrade results and handle failures
- MQL5 trailing stop EA: update stops without loosening risk
- Monte Carlo testing for EA robustness: stress the results, not only the average
- MQL5 not enough money error 10019: when the account cannot hold the next position.
Frequently Asked Questions
Treat the Limit as a System Requirement
A daily loss guard depends on a clearly defined rule, persistent state, and account-wide coverage. Test reset boundaries, breaches, restarts, and failed state writes against the broker clock and the applicable account rules. CodeFlowOS can provide a starting MQL5 translation, but cannot infer a drawdown policy. Try the converter, see the conversion guide, risk-based lot sizing, and verification notes, or review plans. Test the guard independently.