Daily loss limit from server midnight, including floating P/L: how do you measure it in an EA?

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:

  • Deposits and withdrawals (DEAL_TYPE_BALANCE) are deliberately left out, so a withdrawal during the day is not counted as a loss.
  • Server midnight is taken from TimeCurrent(). On symbols whose session opens later (gold often opens at 01:00 server time), iTime(PERIOD_D1) can differ from 00:00, which is why the D1 bar is not used.
  • Some rule sets use the higher of balance or equity at the start of the day. That needs equity sampled exactly at midnight, which cannot be rebuilt from history after a restart. How do you handle that case: a timer that saves equity at 00:00 into a global variable, or something else?
  • Has anyone seen brokers where TimeCurrent() jumps during the weekend gap and the first tick of Monday lands in the wrong day?

Feedback and corrections welcome.

Documentation on MQL5: Deal Properties / Constants, Enumerations and Structures
Documentation on MQL5: Deal Properties / Constants, Enumerations and Structures
  • www.mql5.com
A deal is the reflection of the fact of a trade operation execution based on an order that contains a trade request. Each trade is described by...
[Deleted]
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();
  }

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.

A timer helps detect the change of server day. TimeTradeServer() is estimated by the terminal, though, and the callback can run late. If prices haven’t updated, the equity reading can still reflect the last available quotes.

The fallback in #3 is the part I’d revisit. If the EA was offline at midnight, deal history can help reconstruct the opening balance, but it cannot tell you what open positions were worth at midnight. Say balance was 10,000 and equity was 10,300 at midnight. If you restart at 10,050 equity, the fallback saves 10,050 as the baseline. That changes how much loss the EA will allow.

I’d save the snapshot, observation timestamp and quote freshness once per account, server and server day. If it’s missing, mark the midnight baseline as unknown and use a fallback only if the account rules specify one. Also check how the rules treat deposits, withdrawals, credits and separate charges. If those balance operations are omitted from the reconstruction, their effect remains in the current balance/equity and can distort the reconstructed opening balance.

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.

Ciprian Ghebanoaei #:

Please add your code using the correct editor tool for source code. I have edited your message.

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.
I would treat "monitor only" (log and alert, do not close) as a third mode. It is the safe default while the measurement is being verified.
Midnight part is well covered already. One thing I would add is to check the room before the order goes out and not only the result after. Room left = limit minus today's loss (closed plus floating). The risk of the new order to its stop has to fit in that room.

Otherwise you sit at -2.8% of a 3% limit and open a trade with 1% to the stop. The check said all good when you opened it but the limit is gone the moment it hits SL.

Positions without stop loss I would treat separately. There is no number for what they risk so the room check cant really work for them.