Skip to content

EA Doctor rule · OnTick and performance

Indicator handle created on every tick

An indicator function such as iMA() or iCustom() is called in OnTick(), so a handle is requested on every tick instead of once in OnInit().

Why it matters

In MQL5, iMA(), iRSI(), iCustom() and the other indicator functions create an indicator in the terminal and return a handle; the values are read later with CopyBuffer(). They are meant to be called once, in OnInit(), and released with IndicatorRelease() when they are no longer needed.

Called on every tick, each call goes through the terminal again, and the data of a freshly created indicator are often not calculated yet, so CopyBuffer() fails (4806) and signals are missed. In the tester it makes the EA much slower.

When the rule fires

An indicator function that returns a handle (iMA(), iRSI(), iATR(), iMACD(), iBands(), iStochastic(), iCustom() and the other built-in ones) is called in OnTick(), OnTimer() or OnCalculate(), or in a function they call, and the handle it is assigned to is not compared with INVALID_HANDLE before the call.

When it stays quiet

Handles created in OnInit(), and lazy creation guarded by if(handle == INVALID_HANDLE) handle = iMA(…);.

How to fix it

  1. Create each handle once in OnInit() and keep it in a global variable; stop with INIT_FAILED when it is INVALID_HANDLE.
  2. Release it in OnDeinit() with IndicatorRelease().
  3. In OnTick(), only call CopyBuffer() on the stored handle.

Code that fires it

MQL5 · fires this rule
void OnTick()
  {
   double ma[];
   const int h = iMA(_Symbol, PERIOD_CURRENT, 50, 0, MODE_EMA, PRICE_CLOSE);
   if(CopyBuffer(h, 0, 1, 1, ma) != 1)
      return;
   Comment("EMA 50: ", DoubleToString(ma[0], _Digits));
  }

Fixed code

MQL5 · fixed
int maHandle = INVALID_HANDLE;

int OnInit()
  {
   maHandle = iMA(_Symbol, PERIOD_CURRENT, 50, 0, MODE_EMA, PRICE_CLOSE);
   if(maHandle == INVALID_HANDLE)
     {
      Print("iMA failed: ", GetLastError());
      return(INIT_FAILED);
     }
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {
   IndicatorRelease(maHandle);
   Comment("");
  }

void OnTick()
  {
   double ma[];
   if(CopyBuffer(maHandle, 0, 1, 1, ma) != 1)
      return;
   Comment("EMA 50: ", DoubleToString(ma[0], _Digits));
  }

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.