Skip to content

EA Doctor rule · Signals and data

CopyBuffer() or CopyRates() result not checked

A Copy function is called as a plain statement, so the code reads the array even when nothing was copied.

Why it matters

CopyBuffer(), CopyRates() and the other Copy functions return how many elements they copied, or -1. Right after a start, a timeframe change or a new indicator handle the data are often not ready yet (4806, indicator data not found).

The array then keeps its old contents or stays empty, and code that reads it anyway trades on stale values or stops with "array out of range".

When the rule fires

CopyBuffer(), CopyRates(), CopyTime(), CopyOpen(), CopyHigh(), CopyLow(), CopyClose(), CopyTickVolume(), CopyRealVolume(), CopySpread() or CopyTicks() stands on its own as a statement, so its result is never compared.

When it stays quiet

The result is compared with the number of elements asked for (if(CopyBuffer(h, 0, 1, 2, buf) != 2) return;) or stored and checked.

How to fix it

  1. Compare the result with the count you asked for, and return when it is less.
  2. Try again on the next tick; the data arrive within a few ticks.

Code that fires it

MQL5 · fires this rule
int atrH = INVALID_HANDLE;

int OnInit()
  {
   atrH = iATR(_Symbol, PERIOD_CURRENT, 14);
   return(atrH == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED);
  }

double AtrPoints()
  {
   double atr[];
   CopyBuffer(atrH, 0, 1, 1, atr);
   return(atr[0] / _Point);
  }

Fixed code

MQL5 · fixed
int atrH = INVALID_HANDLE;

int OnInit()
  {
   atrH = iATR(_Symbol, PERIOD_CURRENT, 14);
   return(atrH == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED);
  }

double AtrPoints()
  {
   double atr[];
   if(CopyBuffer(atrH, 0, 1, 1, atr) != 1)
      return(0.0);   // not calculated yet: no value on this tick
   return(atr[0] / _Point);
  }

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 signals and data

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.