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.
Post Reply
FTtrader
Posts: 567
Joined: Mon Aug 03, 2026 2:43 pm

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

Post by FTtrader »

Hi traders, scalpers,

i created this post to share some tips and tricks how to handle common issue in developing custom indicators in MQL5, Error 4002.

If you are building or running high-frequency scalping EAs in MetaTrader 5, you have likely run into the dreaded "Array out of range" error in your Journal tab. This is a fatal execution error that instantly halts your Expert Advisor—which is the absolute last thing you want to happen during a volatile liquidity spike.

Unlike MQL4, MQL5 is highly asynchronous. When your EA requests historical data (like indicator buffers or price action arrays), the terminal doesn't guarantee that the data is immediately available in memory. If your EA tries to access an index before verifying the array is populated, it crashes.

Here is a breakdown of why this happens and the exact architectural pattern you should use to fix it.

The Root Cause
In a scalping EA, speed is everything. We often rely on CopyBuffer, CopyRates, or CopyTicks inside the OnTick() function to make split-second execution decisions.

The error triggers when you do something like this:

Code: Select all

// ❌ THE FLAWED APPROACH
double rsi_buffer[];
CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer);

// If the terminal hasn't loaded the data yet, CopyBuffer returns -1.
// The array is empty. Accessing index [0] crashes the EA.
double current_rsi = rsi_buffer[0];
The Solution: Defensive Data Handling
To build an enterprise-grade EA that can run for months without crashing, you must treat every data request as a potential point of failure.

You need to implement a three-step validation check:

1.) Verify the exact number of elements returned by the Copy... function.

2.) Handle terminal data synchronization delays gracefully.

3.) Explicitly verify ArraySize() before mapping data to your execution logic.

Here is the robust implementation:

Code: Select all

// ✅ THE ROBUST APPROACH
void OnTick()
  {
      // 1. Define dynamic array for the indicator or price data
      double rsi_buffer[];
      
      // 2. Set the array as series (index 0 = current candle)
      ArraySetAsSeries(rsi_buffer, true);
      
      // 3. Attempt to copy the data and store the result
      int copied = CopyBuffer(rsi_handle, 0, 0, 3, rsi_buffer);
      
      // 4. Validate the response BEFORE accessing the array
      if(copied <= 0)
        {
            // The terminal is still syncing, or there is a history error.
            // Do NOT proceed. Exit the OnTick and wait for the next incoming tick.
            Print("Data not ready or CopyBuffer error: ", GetLastError());
            return; 
        }
        
      // 5. Final safety check on array bounds
      if(ArraySize(rsi_buffer) < 3)
        {
            Print("Insufficient array size for strategy logic.");
            return;
        }

      // 6. Safe to execute your scalping logic
      double current_rsi = rsi_buffer[0];
      double previous_rsi = rsi_buffer[1];
      
      // ... entry criteria logic ...
  }
Key Takeaways for Robust Scalping Logic:

Never assume the terminal is ready: Always capture the integer return value of CopyBuffer or CopyRates. If it is less than or equal to zero, simply return; out of the tick.

Watch your indexing: Remember that MQL5 arrays are not time-series by default. Always use ArraySetAsSeries(array, true) if you want index [0] to represent the current active candle.

Initialize properly: Make sure your indicator handles (e.g., rsi_handle) are successfully created in OnInit(), not re-created on every tick.

Have you run into any specific edge cases with array indexing during high-impact news events? Drop your snippets below and we can optimize them.
Recommended broker for automated trading & scalping IC Markets
LondonScalper
Posts: 618
Joined: Sat Sep 05, 2026 7:54 am

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

Post by LondonScalper »

FTtrader wrote:Unlike MQL4, MQL5 is highly asynchronous... If your EA tries to access an index before verifying the array is populated, it crashes.
This is one of those bugs that feels like “random London open sabotage” until you’ve been burned by it twice.

The pattern that saved me: never assume CopyBuffer / CopyRates returned what you asked for — check the returned count, then bound every index against that count, then decide. On a thin history or after a reconnect, “Array out of range” is the terminal telling you your EA lied about readiness.

For scalping EAs specifically I’d also:
  • Fail closed (no new orders) when data isn’t ready — don’t “retry into the spike” blindly
  • Log the symbol, timeframe, requested bars, and returned bars on every 4002 path
  • Warm up indicators on timer/init before the first trading tick is allowed
There’s a near-duplicate thread with a [FIXED] tag floating around; worth cross-linking so people don’t maintain two slightly different fix stories. Are you seeing 4002 mostly on init, or mid-session after a weekend gap?
PropScalpDesk
Posts: 114
Joined: Sat Sep 19, 2026 7:50 pm

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

Post by PropScalpDesk »

Error 4002: bounds-check before live lots

Same family of problem as the fixed thread: array out of range will halt a scalp EA while the market is moving. Whether you are coding indicators or full robots in MQL5, bounds and CopyRates failure paths need to be boringly defensive.

What I insist on before any non-micro size next to my discretionary Frankfurt book: stress a short-history load, weekend gap reopen, and symbol change. Early return on failure beats a dead expert in the journal during London.

Also keep a manual kill path. Automation errors arrive at inconvenient times.

If two builds disagree in tester versus a thin live chart reopen, I trust the failure and fix bounds before blaming the broker feed.

I refuse to run untested indicator includes on the same chart as live execution. Isolation keeps a bad array from taking the whole desk down.

Have you reproduced 4002 on purpose in tester/with short history, or only seen it live when Bars was thinner than your lookback assumed?
Post Reply