Skip to content

EA Doctor rule · OnTick and performance

Sleep() inside OnTick()

OnTick() pauses with Sleep(), which holds up every other event of the EA and leaves it working with old prices.

Why it matters

An EA handles its events one after another. While OnTick() sleeps, no other tick, timer or trade event of the EA is processed, and the prices the code read before the pause are old when it carries on.

A retry after a requote is better done on the next tick (or after a set time, checked with TimeCurrent()) with fresh prices.

When the rule fires

Sleep() is called in OnTick() or in a function it calls.

When it stays quiet

Sleep() in scripts (OnStart()), in OnInit() or in functions OnTick() never calls.

How to fix it

  1. Return from OnTick() instead of waiting, and remember when to try again.
  2. On the next tick after that time, read fresh prices and retry, with a limit on the number of attempts.

Code that fires it

MQL5 · fires this rule
void OnTick()
  {
   if(PositionsTotal() > 0)
      return;
   trade.SetExpertMagicNumber(InpMagic);
   for(int attempt = 0; attempt < 3; attempt++)
     {
      if(trade.Buy(InpLots, _Symbol) && trade.ResultRetcode() == TRADE_RETCODE_DONE)
         break;
      Sleep(1000);
     }
  }

Fixed code

MQL5 · fixed
int      failures   = 0;
datetime retryAfter = 0;

void OnTick()
  {
   if(PositionsTotal() > 0 || TimeCurrent() < retryAfter)
      return;
   trade.SetExpertMagicNumber(InpMagic);
   if(trade.Buy(InpLots, _Symbol) && trade.ResultRetcode() == TRADE_RETCODE_DONE)
     {
      failures = 0;
      return;
     }
   failures++;
   retryAfter = TimeCurrent() + MathMin(60, 5 * failures);   // the first tick after the pause retries
  }

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.