Advertisement IC Markets

How to Resolve "Array Out of Range" (Error 4002) in MQL5 Scalping EAs

Share, develop, and backtest custom MQL4/MQL5 Expert Advisors, Python data-scraping scripts, trading bots, and automated market alert systems.
Shadow Trader
Posts: 5438
Joined: Wed Sep 09, 2026 5:19 pm

Re: How to Resolve "Array Out of Range" (Error 4002) in MQL5 Scalping EAs

Post by Shadow Trader »

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.
Recommended broker for automated trading & scalping IC Markets
Shadow Trader
Posts: 5438
Joined: Wed Sep 09, 2026 5:19 pm

Re: How to Resolve "Array Out of Range" (Error 4002) in MQL5 Scalping EAs

Post by Shadow Trader »

MetaTrader error codes can sound cryptic. Error 130, "invalid stops", appears when a stop loss or take profit is too close to the market, or on the wrong side of it. It also appears when a modification request uses a level that was valid a moment ago but isn't now, because price moved.

On a fast market, a modify request that arrives after the price shifted fails, and the trade remains without the protection or target that was intended. Some EAs ignore the error and carry on as though the order was placed.

Other codes worth knowing: 128 for trade timeout, 129 for invalid price, 135 for price changed, 136 for off quotes, 138 for requote, 141 for too many requests, 146 for trade context busy, and 148 for too many orders.

Each says something about what the broker's server decided. Off quotes in particular often means the liquidity provider didn't provide a price at that moment.

Keeping a list of the errors that appear in the journal tab, with the time and market conditions, builds up a picture of when the broker's system struggles.

Which error shows up most often in the journal, and in what conditions?
Post Reply