Blog / Fix MT5 errors · MQL5 · Expert Advisors · Debugging
Array Out of Range: The Most Common MQL Crash
Fix the MQL5 array out of range error. Learn how to identify invalid indexes, correct loop boundaries and safely access indicator and price data.
· 4 min read
Your Expert Advisor compiles successfully, but MT5 reports an array out of range error when you run it.
This happens when your code tries to access an array element that doesn't exist.
For example, an array containing five elements has valid indexes from 0 to 4. Accessing index 5 causes an error. It's a critical runtime error, so MT5 stops the program as soon as it happens.
The most common causes are incorrect loop boundaries, empty arrays and attempts to read indicator or price data that hasn't been fully copied.
Here's how to identify and fix them.
1. Check Your Array Indexes and Loop Boundaries
MQL5 arrays use zero-based indexing. The first element is at index 0.
For example:
double prices[5] = {
1.1000, 1.1010, 1.1020, 1.1030, 1.1040
};The valid indexes are 0, 1, 2, 3 and 4. This access is invalid:
Print(prices[5]);A common way to make the same mistake is using <= instead of < in a loop.
Incorrect:
for(int i = 0; i <= ArraySize(prices); i++)
{
Print(prices[i]);
}ArraySize(prices) returns 5, so the loop attempts to access index 5.
Correct:
for(int i = 0; i < ArraySize(prices); i++)
{
Print(prices[i]);
}The corrected loop stops before reaching the array size.
For a loop running backwards, start at the last valid index:
for(int i = ArraySize(prices) - 1; i >= 0; i--)
{
Print(prices[i]);
}Fix: Check every loop that accesses an array. The index must always be greater than or equal to zero and smaller than the array's size.
2. Check That Dynamic Arrays Contain Elements
Declaring a dynamic array doesn't automatically allocate space for its elements.
For example:
double prices[];
Print(prices[0]);The array has no elements, so accessing index 0 is invalid.
Allocate space before writing to it:
double prices[];
if(ArrayResize(prices, 5) != 5)
{
Print("Failed to resize prices array");
return;
}
prices[0] = 1.1000;
prices[1] = 1.1010;
prices[2] = 1.1020;
prices[3] = 1.1030;
prices[4] = 1.1040;If an array is populated by another function, check its size before accessing it:
if(ArraySize(prices) == 0)
{
Print("Prices array is empty");
return;
}Note that ArrayResize() works on dynamic arrays. It cannot resize fixed-size static arrays or indicator buffers bound using SetIndexBuffer().
3. Check How Much Data CopyBuffer() Returns
An EA can also produce an array error when it requests indicator values that aren't available yet.
For example, suppose you request three moving average values:
double maValues[];
ArraySetAsSeries(maValues, true);
int copied = CopyBuffer(
maHandle,
0,
0,
3,
maValues
);Requesting three values doesn't guarantee that three were copied.
CopyBuffer() returns the number of elements copied, or -1 if the operation fails. It may also return fewer values than requested.
Unsafe access:
double currentMA = maValues[0];
double previousMA = maValues[1];
double olderMA = maValues[2];If fewer than three values were copied, these accesses may be invalid.
Corrected code:
if(maHandle == INVALID_HANDLE)
{
Print("Invalid moving average handle");
return;
}
double maValues[];
ArraySetAsSeries(maValues, true);
int copied = CopyBuffer(
maHandle,
0,
0,
3,
maValues
);
if(copied != 3)
{
PrintFormat("CopyBuffer failed or incomplete: copied=%d",
copied);
return;
}
double currentMA = maValues[0];
double previousMA = maValues[1];
double olderMA = maValues[2];ArraySetAsSeries(maValues, true) makes index 0 refer to the newest element.
You can also check BarsCalculated(maHandle) to determine whether the indicator has calculated enough values. Indicator Handles and CopyBuffer Explained covers handles, buffers and candle positions in more detail.
Fix: Check the indicator handle and the number of values copied before accessing the destination array.
4. Check Historical Data Before Accessing It
The same problem can occur with CopyRates() when your EA requests more candles than the terminal currently has available.
For example:
MqlRates rates[];
ArraySetAsSeries(rates, true);
int copied = CopyRates(
_Symbol,
PERIOD_CURRENT,
0,
100,
rates
);
if(copied != 100)
{
PrintFormat("Insufficient price data: copied=%d",
copied);
return;
}
double closePrice = rates[99].close;
PrintFormat("Close price: %.5f", closePrice);This code checks that all 100 requested candles were copied before accessing rates[99].
Because the array is set as a series, index 0 represents the current candle, while index 99 represents the oldest of the 100 copied candles.
Fix: Never assume that historical data is available just because you requested it. Check the number of copied bars before reading the array.
5. Find the Invalid Index in the Experts Log
If you can't identify where the error occurs, inspect the MT5 Experts log (how to read it).
The message names the source file and the line and column of the invalid access, for example array out of range in 'MyEA.mq5' (128,21). Go to that line in MetaEditor first. If that line runs with many different indexes, add diagnostic messages to find the exact value that fails.
For example:
int size = ArraySize(prices);
int index = 10;
if(index < 0 || index >= size)
{
PrintFormat("Invalid array access: index=%d, size=%d",
index, size);
return;
}
Print(prices[index]);A message such as index=10, size=10 immediately shows the problem: the array has valid indexes from 0 to 9.
Once you identify the failing operation, correct the index calculation or ensure the required data is available.
Don't simply increase the array size to hide the error. If the missing data is essential to a trading decision, the EA should stop that calculation until the problem is resolved.
6. Reproduce the Error in Strategy Tester
After changing the code, run the same scenario that originally caused the error.
In MT5:
- Open Strategy Tester with Ctrl + R.
- Select the affected EA, symbol and timeframe.
- Use the original testing period and modelling settings.
- Run the test and inspect the Journal.
- Confirm that the array error no longer appears.
Pay particular attention to the beginning of the testing period. Your EA may have fewer historical bars available there than it does later in the test.
Also confirm that the corrected EA still generates the expected signals and trade operations.
Conclusion
The MQL5 array out of range error occurs when an EA accesses an index outside an array's valid boundaries.
Start by checking loop conditions and array sizes. If you're retrieving indicator or price data, inspect the return values of CopyBuffer() and CopyRates() before accessing their arrays.
Fix the actual indexing or data-availability problem instead of simply increasing array sizes.
With PositionAlpha's Fix an EA, you paste or upload the EA and describe the problem. The AI returns the complete updated .mq4 or .mq5 file and explains the problems it found and each change it made. Compile the result in MetaEditor and test it in the Strategy Tester and on a demo account before you rely on it.
Build a bot from your idea
Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.