Skip to content

EA Doctor rule · OnTick and performance

The whole trade history loaded on every tick

HistorySelect(0, …) is called from OnTick(), so every deal and order of the account is loaded again on each tick.

Why it matters

HistorySelect(0, TimeCurrent()) loads every deal and order of the account into the EA's history cache. On an account with years of trading that is thousands of records, loaded again on every tick: the EA slows down and so does the terminal.

A daily loss limit needs today's deals, a weekly report the last week. Select the window the code needs, and only when it needs it.

When the rule fires

HistorySelect() is called with 0 as its start date in OnTick() or in a function it calls.

When it stays quiet

A start date other than 0 (the start of the day, the week), or history read in OnInit() or OnTradeTransaction() only.

How to fix it

  1. Select from the start of the period you need: HistorySelect(dayStart, TimeCurrent()).
  2. Keep the result in a variable and refresh it when a deal happens (OnTradeTransaction()) or once per bar, not on every tick.

Code that fires it

MQL5 · fires this rule
double ClosedProfitToday()
  {
   MqlDateTime t;
   TimeToStruct(TimeCurrent(), t);
   t.hour = 0;
   t.min  = 0;
   t.sec  = 0;
   const datetime dayStart = StructToTime(t);
   double sum = 0.0;
   if(!HistorySelect(0, TimeCurrent()))
      return(0.0);
   for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
     {
      const ulong deal = HistoryDealGetTicket(i);
      if(deal > 0 && (datetime)HistoryDealGetInteger(deal, DEAL_TIME) >= dayStart
         && HistoryDealGetInteger(deal, DEAL_MAGIC) == InpMagic)
         sum += HistoryDealGetDouble(deal, DEAL_PROFIT);
     }
   return(sum);
  }

void OnTick()
  {
   if(ClosedProfitToday() <= -100.0)
      return;   // daily loss reached
  }

Fixed code

MQL5 · fixed
double ClosedProfitToday()
  {
   MqlDateTime t;
   TimeToStruct(TimeCurrent(), t);
   t.hour = 0;
   t.min  = 0;
   t.sec  = 0;
   const datetime dayStart = StructToTime(t);
   double sum = 0.0;
   if(!HistorySelect(dayStart, TimeCurrent()))
      return(0.0);
   for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
     {
      const ulong deal = HistoryDealGetTicket(i);
      if(deal > 0 && HistoryDealGetInteger(deal, DEAL_MAGIC) == InpMagic)
         sum += HistoryDealGetDouble(deal, DEAL_PROFIT);
     }
   return(sum);
  }

void OnTick()
  {
   if(ClosedProfitToday() <= -100.0)
      return;   // daily loss reached
  }

The fixed code shows this rule’s fix and compiles in MetaEditor for MetaTrader 5 (with CTrade trade, InpLots and InpMagic declared, as in a typical EA). Other rules may still apply to it as a fragment: check your whole EA.

More rules on ontick and performance

Sources

Get your EA fixed

Check a whole EA for this and 29 other mistakes with EA Doctor, free and in your browser. Or send it to us: we confirm the price in writing, then fix it.