Re: How to Resolve "Array Out of Range" (Error 4002) in MQL5 Scalping EAs
Posted: Fri Oct 23, 2026 6:30 am
One cause that has not come up yet is the lookback inside the loop rather than the copy itself. For a series indexed loop that reads 20 bars back from index i, the first full pass has to start at rates_total minus 21, not rates_total minus 1.
Otherwise the first value it reads, at i plus 20, is past the end of the array. Later passes hide the problem, because once prev_calculated is set the loop only touches the newest bars.
That is why this version of 4002 shows up on attach, after a timeframe switch or after a history reload. It matches the random London open feeling LondonScalper described.
iBarShift is another quiet source. With the exact flag set it returns minus one when no bar matches the time, and using that straight as an index gives the same error.
The journal line saves guessing. MT5 prints the source file with a line and column number next to the error, so the failing index takes a minute to find.
A habit that covers most of these is to work out the lowest valid start index once, from the copied count and the longest lookback, and clamp every loop to it. A crash then becomes a skipped tick.
Otherwise the first value it reads, at i plus 20, is past the end of the array. Later passes hide the problem, because once prev_calculated is set the loop only touches the newest bars.
That is why this version of 4002 shows up on attach, after a timeframe switch or after a history reload. It matches the random London open feeling LondonScalper described.
iBarShift is another quiet source. With the exact flag set it returns minus one when no bar matches the time, and using that straight as an index gives the same error.
The journal line saves guessing. MT5 prints the source file with a line and column number next to the error, so the failing index takes a minute to find.
A habit that covers most of these is to work out the lowest valid start index once, from the copied count and the longest lookback, and clamp every loop to it. A crash then becomes a skipped tick.