Daily loss limit from server midnight, including floating P/L: how do you measure it in an EA?
Instead of a timer trying to catch exactly 00:00, compare a stored day label against the current one on every tick. The moment they differ, capture balance/equity into that stored state and update the label, right there, no scheduling involved.
This solves both your open questions at once. There's no missed tick at midnight to worry about, since you're not waiting for a specific timestamp, just checking "is today's date different from what I last saved." And it survives restarts, since the label and the captured value live in a file or global variable instead of only in memory.
For the weekend gap: it doesn't matter that TimeCurrent() jumps. Whatever the first tick after the gap reports, you just check whether its date differs from the stored one. If it does, that's a new day, however large the jump was. The only case worth guarding against is a backwards jump (next tick reports an earlier date than what's stored), which should just be ignored rather than triggering a reset.
Nice, clean stateless approach for reconstructing the starting balance without external state. There are a few subtle MQL5 details in the snippet and your two open questions worth watching in production:
1. Subtle edge cases in DayStartBalance()
- Non-trade cash adjustments: Filtering strictly by DEAL_TYPE_BUY || DEAL_TYPE_SELL deliberately excludes DEAL_TYPE_BALANCE, which is great, but brokers also use DEAL_TYPE_CREDIT, DEAL_TYPE_BONUS, DEAL_TYPE_CORRECTION, or DEAL_TYPE_COMMISSION_DAILY (for end-of-day swap/commission charges). If your broker posts daily commission or balance corrections as separate deal types rather than on the closing deal, those will drift your reconstructed starting balance unless explicitly accounted for.
- HistorySelect(dayStart, now) boundary: Passing now (which is TimeCurrent()) can occasionally miss a deal executed in the exact same second if the server clock ticks slightly ahead or during heavy execution. Passing now + 60 (or TimeTradeServer() + 60) as the upper bound avoids edge-second clipping.
- Entry deals with commission: Even though DEAL_ENTRY_IN deals have 0.0 profit, they often carry half of the round-turn DEAL_COMMISSION, so iterating over all deals (both IN and OUT) as you did is the right call.
2. Handling "Higher of Balance or Equity at 00:00"
As you noted, floating equity at 00:00 cannot be reconstructed from deal history alone after a terminal restart. The standard production pattern is a hybrid approach:
- Use EventSetTimer(1) (not OnTick(), because symbols like XAUUSD or indices may have no ticks between 00:00 and 01:00) to detect when the server day rolls over (currentDay != lastRecordedDay).
- Immediately snapshot MathMax(AccountInfoDouble(ACCOUNT_BALANCE), AccountInfoDouble(ACCOUNT_EQUITY)) into a Terminal Global Variable (GlobalVariableSet) keyed by account login and date, and flush it to disk with GlobalVariablesFlush() so it survives a terminal crash or VPS reboot.
- Use your HistorySelect() reconstruction as the automatic fallback only if the EA is attached mid-day for the first time and no Global Variable exists for today's date.
3. Weekend TimeCurrent() jumps on Monday open
Yes, this happens regularly depending on how the broker's quote feed behaves over the weekend:
- TimeCurrent() reflects the last quote timestamp of the symbol the EA is attached to (or the latest market watch tick). Over the weekend, TimeCurrent() stays frozen at Friday 23:59:xx until the first tick arrives.
- If your EA is attached to a symbol whose session opens later than 00:00 on Monday (e.g., XAUUSD or an equity index), TimeCurrent() will still report Friday's date during the first hour of Monday until that chart's symbol receives a tick, whereas TimeTradeServer() advances with the server clock.
- Using TimeTradeServer() instead of TimeCurrent() for day-boundary checks avoids getting stuck on Friday's timestamp while waiting for a late-opening symbol to print its first Monday tick.
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(); }
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.
double DayStartBalance() { datetime now = TimeCurrent(); datetime dayStart = now - (now % 86400); // 00:00 on the broker's server clock if(!HistorySelect(dayStart, now)) 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; } double TodayResult() // closed + floating since server midnight { return AccountInfoDouble(ACCOUNT_EQUITY) - DayStartBalance(); }Notes and open questions:
Feedback and corrections welcome.