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
- Compare the result with the count you asked for, and return when it is less.
- Try again on the next tick; the data arrive within a few ticks.
Code that fires it
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
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.
Related MQL5 errors
More rules on signals and data
- MediumSignal read from the bar that is still formingThe EA compares indicator values of bar 0, which change with every tick until the bar closes, so its entries differ from what the chart shows later.
- MediumIndicator handle not checked for INVALID_HANDLEAn indicator handle is stored without checking for INVALID_HANDLE, so a missing custom indicator goes unnoticed and every read fails.
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.