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
- Return from
OnTick()instead of waiting, and remember when to try again. - On the next tick after that time, read fresh prices and retry, with a limit on the number of attempts.
Code that fires it
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
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.
Related MQL5 errors
More rules on ontick and performance
- HighIndicator handle created on every tickAn indicator function such as iMA() or iCustom() is called in OnTick(), so a handle is requested on every tick instead of once in OnInit().
- MediumBar-based logic runs on every tickOnTick() copies bar data and makes entry decisions on every tick, with no check for a new bar anywhere in the EA.
- MediumThe whole trade history loaded on every tickHistorySelect(0, …) is called from OnTick(), so every deal and order of the account is loaded again on each tick.
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.