Daily loss limit from server midnight, including floating P/L: how do you measure it in an EA?
Here is how you can combine the midnight snapshot with your stateless fallback: //+------------------------------------------------------------------+ //| Helper: Build unique GlobalVariable key per account & server day | //+------------------------------------------------------------------+ string GetDayBaselineKey(datetime dayStart) { return StringFormat("DD_BASE_%I64d_%I64d", AccountInfoInteger(ACCOUNT_LOGIN), (long)dayStart); } //+------------------------------------------------------------------+ //| Stateless fallback from deal history (your original logic) | //+------------------------------------------------------------------+ double ReconstructDayStartBalance(datetime dayStart, datetime serverNow) { if(!HistorySelect(dayStart, serverNow + 60)) return AccountInfoDouble(ACCOUNT_BALANCE); double realised = 0.0; for(int i = HistoryDealsTotal() - 1; i >= 0; i--) { ulong ticket = HistoryDealGetTicket(i); long type = HistoryDealGetInteger(ticket, DEAL_TYPE); if(type == DEAL_TYPE_BUY || type == DEAL_TYPE_SELL) { realised += HistoryDealGetDouble(ticket, DEAL_PROFIT) + HistoryDealGetDouble(ticket, DEAL_SWAP) + HistoryDealGetDouble(ticket, DEAL_COMMISSION) + HistoryDealGetDouble(ticket, DEAL_FEE); } } return AccountInfoDouble(ACCOUNT_BALANCE) - realised; } //+------------------------------------------------------------------+ //| Returns stored 00:00 high-water mark, or initializes it | //+------------------------------------------------------------------+ double GetDayStartBaseline() { datetime serverNow = TimeTradeServer(); datetime dayStart = serverNow - (serverNow % 86400); string gvKey = GetDayBaselineKey(dayStart); if(GlobalVariableCheck(gvKey)) return GlobalVariableGet(gvKey); // First time seeing this day: // If called right at 00:00 rollover, balance & equity are live at midnight. // If attached mid-day, reconstruct starting balance and compare with current equity. double startBal = ReconstructDayStartBalance(dayStart, serverNow); double baseline = MathMax(startBal, AccountInfoDouble(ACCOUNT_EQUITY)); GlobalVariableSet(gvKey, baseline); GlobalVariablesFlush(); // Persist to disk immediately in case of restart return baseline; } //+------------------------------------------------------------------+ //| Call EventSetTimer(1) in OnInit() so rollover fires without ticks| //+------------------------------------------------------------------+ void OnTimer() { // Ensures the 00:00 snapshot triggers even on symbols with 01:00 open GetDayStartBaseline(); } double TodayResult() { return AccountInfoDouble(ACCOUNT_EQUITY) - GetDayStartBaseline(); }
Thank you both, very useful.
@Ilyas De: the stored day label checked on every event is cleaner than waiting for 00:00, and ignoring a backwards date jump covers the weekend case.
@Joseph Sunday: good point on gold having no ticks between 00:00 and 01:00 server time, so the check belongs in OnTimer as well as OnTick. The extra deal types (DEAL_TYPE_CREDIT, DEAL_TYPE_CORRECTION, DEAL_TYPE_COMMISSION_DAILY) are a fair catch too.
Putting it together: a one-second timer compares the server date with a label in a terminal global variable keyed by login; on change it saves MathMax(balance, equity) and calls GlobalVariablesFlush(). The history rebuild stays only as the fallback when the EA is first attached mid-day.
Three practical points from running day-loss guards on several accounts at once, on top of the snapshot approach above:
1. Cache the history rebuild. HistorySelect() plus a loop over all of today's deals on every tick gets slow on busy accounts. Recompute the realised total only when OnTradeTransaction() reports a new deal (TRADE_TRANSACTION_DEAL_ADD) and keep it in a variable. The per-tick check is then just equity minus the stored baseline.
2. Terminal global variables are deleted after 4 weeks without access. If the EA only touches the baseline key once per day that is fine, but a baseline kept in a global variable for an account that sits idle (EA removed for a month, then re-attached) will silently be gone, and the fallback will run without you noticing. Log a clear message whenever the fallback is used so you can tell a real snapshot from a reconstructed one.
3. If more than one EA runs on the same account, they must share one baseline. Key the global variable by account login and server day only, not by magic number or EA name, otherwise each EA gets its own midnight value (taken at different times after a restart) and they disagree about how much of the limit is used. Let one EA own the write and have the others only read it.
Also worth testing the limit logic with equity going below the threshold while positions are open: decide up front whether hitting the limit should close everything or only block new entries, because closing at a bad moment (wide spread at rollover) can itself add to the loss.
Just a few practical details that I haven't seen above, from implementing the same thing:
1) Day id with a configurable reset hour avoids any iTime/D1 dependency (so the gold 01:00 open doesn't matter): id = (TimeTradeServer() - reset_hour*3600) / 86400
2) Equity already contains floating P/L, so loss = reference - ACCOUNT_EQUITY. The reference depends on the firm's rule: day-start balance, day-start equity, or the higher of both. Percent limits are often calculated from the INITIAL balance, not the day-start one - worth checking the rules text.
3) Act a bit before the limit (I use 95%), because closing positions takes time and slippage on the way out counts too.
4) Regarding the restart concern: if the stored snapshot is missing, I would not guess it from history for the "higher of balance/equity" rule. Treat it as unknown and fall back to the balance-based reference only.
Minimal skeleton (global variables survive terminal restarts):
long DayId() { datetime t = TimeTradeServer(); if(t <= 0) return -1; // disconnected return (t - InpResetHour*3600) / 86400; } string Key(const string what) { return StringFormat("DL_%I64d_%s", AccountInfoInteger(ACCOUNT_LOGIN), what); } bool LimitBreached() { long id = DayId(); if(id < 0) return false; if(!GlobalVariableCheck(Key("day")) || (long)GlobalVariableGet(Key("day")) != id) { GlobalVariableSet(Key("day"), (double)id); GlobalVariableSet(Key("bal"), AccountInfoDouble(ACCOUNT_BALANCE)); GlobalVariableSet(Key("eq"), AccountInfoDouble(ACCOUNT_EQUITY)); } double ref = MathMax(GlobalVariableGet(Key("bal")), GlobalVariableGet(Key("eq"))); double loss = ref - AccountInfoDouble(ACCOUNT_EQUITY); double lim = InpInitBalance * InpLimitPct / 100.0; return loss >= lim * InpActAt; }
Call it from both OnTick and OnTimer (1 s), since the chart symbol may not tick. Deposits/withdrawals during the day still need separate handling.
The measurement side of this has been covered well (day id from TimeTradeServer(), snapshot on first tick of the new day, GlobalVariablesFlush(), and not inventing a midnight equity figure from history after a mid-day restart).
The part I would add is what the EA does after the limit is true, because that is where a lock becomes dangerous on a multi-EA account.
A daily loss cap can be an account-level prop rule (flatten everything) or an EA-level guard (only this magic, optionally only this symbol). Those are different behaviours and are worth making explicit. Closing every position on the account from an EA that was only meant to police its own trades will take out other systems, and a manual trade, without the user expecting it.
When I want the EA-level version, I iterate PositionsTotal() backward, match POSITION_MAGIC (and usually POSITION_SYMBOL), and close by ticket. I also stop placing new orders until the next day id, including pending orders with that magic. I do not use PositionsTotal() as a live index after a close; the ticket list is collected first.
#include <Trade\Trade.mqh> int MatchingPositions(const long magic, const bool this_symbol, ulong &tickets[]) { ArrayResize(tickets, 0); for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(this_symbol && PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if(PositionGetInteger(POSITION_MAGIC) != magic) continue; int sz = ArraySize(tickets); ArrayResize(tickets, sz + 1); tickets[sz] = ticket; } return ArraySize(tickets); } bool CloseMatching(const long magic, const bool this_symbol) { ulong tickets[]; int n = MatchingPositions(magic, this_symbol, tickets); CTrade trade; trade.SetAsyncMode(false); bool ok = true; for(int i=0; i<n; i++) { if(!trade.PositionClose(tickets[i])) { PrintFormat("close #%I64u failed retcode=%u %s", tickets[i], trade.ResultRetcode(), trade.ResultRetcodeDescription()); ok = false; } } return ok; }
A few operational details that go with this:
- Call the check from OnTimer as well as OnTick. A quiet symbol will not tick at the reset hour, and a lock that only runs in OnTick can sit there with a breached limit until the next quote.
- Closing is not instantaneous. If the rule is "1% of equity", start the close a little early; the fills, spread and slippage on the way out still count. Several replies already said this, and it is the part that shows up live more than in the tester.
- On a netting account, PositionClose closes the whole position. On a hedging account it closes one ticket. If the account is netting and several EAs share the symbol, an EA-level lock cannot close "only its own" volume — there is only one position. That is a good reason to keep a flatten-everything option explicit, and to test both account modes.
Many prop-style rules measure the daily loss limit from midnight on the broker's server clock and include floating P/L (equity), not only closed trades. Below is the approach we use in an EA to get the day's starting balance and the running result for the day, closed plus open, without storing anything between restarts.
Notes and open questions:
Feedback and corrections welcome.