Array out of range in a converted MQL5 indicator: the fix

Short answer

It is almost always a history read such as close[i - 1] or Buf[i - Length] on the first bars, where the index is negative: Pine returns na there, MQL5 aborts. Decide what the first Length bars hold (EMPTY_VALUE, Pine's na) and make the loop skip the lookback on those bars.

The indicator compiles, you drop it on a chart, nothing is drawn, and the Experts tab of the Toolbox shows array out of range in 'aoor.mq5' (16,35): the file name, then the line and column of the read that went past the end of an array. In code ported from Pine Script the read is nearly always a history lookup, close[i - 1] or Buf[i - Length], executed on the first bars where i - 1 or i - Length is negative. Pine returns na there; MQL5 aborts the program.

Why it happens when converting Pine Script

In Pine, close[1] on the very first bar of the chart is not an error. The history operator returns na whenever it reaches before bar 0, and everything built on it (ta.change, ta.sma, your own x[len]) carries that na through the warm-up bars silently. Nobody writes a guard, because the language is the guard.

MQL5 arrays are plain memory. OnCalculate hands you close[] with rates_total elements, oldest first, and reading close[-1] is a runtime error that terminates the current OnCalculate call. The terminal logs array out of range, the indicator's buffers keep whatever they held, and the plot stays empty. There is no exception to catch; the only defence is never to form a negative index. Three ported patterns do exactly that:

  • A loop starting at i = 0 (or at prev_calculated - 1, which is 0 on the first call) that reads close[i - 1].
  • A lookback loop for(k = 0; k < Length; k++) sum += src[i - k]; run on bars where i < Length - 1.
  • A buffer sized for the chart but indexed with a Pine-style offset in the other direction after ArraySetAsSeries, so the overrun happens at the newest end instead of the oldest.

Fix

The smallest program that reproduces it is a one-bar change, close - close[1] in Pine. Attached to EURUSD H1 in MetaTrader 5 build 6140 it logs array out of range in 'aoor.mq5' (16,35) on the first tick and never draws:

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
double Buf[];
int OnInit()
{
   SetIndexBuffer(0, Buf, INDICATOR_DATA);
   return INIT_SUCCEEDED;
}
int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[], const double &close[],
                const long &tick_volume[], const long &volume[], const int &spread[])
{
   for(int i = prev_calculated > 0 ? prev_calculated - 1 : 0; i < rates_total; i++)
      Buf[i] = close[i] - close[i - 1];
   return rates_total;
}

Line 16, column 35 is close[i - 1] with i == 0. The fix has two parts, and both are needed. Decide what the first Length bars should hold (Pine says na, which is EMPTY_VALUE in a plot buffer), and make the loop skip the lookback on those bars. The generalised version, ta.change(close, len):

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label1  "Change"

input int Length = 10;   // Pine: ta.change(close, len) = close - close[len]

double Buf[];

int OnInit()
{
   SetIndexBuffer(0, Buf, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, Length);   // the first Length bars are na in Pine
   return INIT_SUCCEEDED;
}

int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[],
                const double &open[], const double &high[], const double &low[], const double &close[],
                const long &tick_volume[], const long &volume[], const int &spread[])
{
   if(rates_total <= Length)
      return 0;                                           // not enough history yet; try again next tick

   // Oldest-first (the MQL5 default): bar i reads its past at i - n, so
   // the first bar that can look back Length bars is i == Length.
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      if(i < Length)
      {
         Buf[i] = EMPTY_VALUE;                            // Pine: na
         continue;
      }
      Buf[i] = close[i] - close[i - Length];              // never below index 0
   }
   return rates_total;
}

This compiles without warnings and runs on the same chart with no journal entries. The pieces:

  • if(rates_total <= Length) return 0; covers the chart with fewer bars than the lookback. Returning 0 tells the terminal nothing was calculated, so the next call starts from scratch rather than from a half-filled state.
  • Inside the loop, if(i < Length) { Buf[i] = EMPTY_VALUE; continue; } is the na that Pine gave you for free. Writing EMPTY_VALUE explicitly matters: a fresh buffer holds garbage, not zero, and the terminal would draw it.
  • PLOT_DRAW_BEGIN is cosmetic but tells the terminal not to try to draw the first Length bars, which also hides the join at the left edge.
  • The loop still starts at prev_calculated - 1 on later ticks. The guard is cheap; do not try to be clever by starting at MathMax(prev_calculated - 1, Length) unless you also fill the skipped bars, or the first Length elements stay uninitialised.

For an SMA-style lookback loop the same guard applies with Length - 1: bar i can sum Length values once i >= Length - 1.

Series indexing flips the guard

Many MQL4-era examples call ArraySetAsSeries(close, true) so that index 0 is the newest bar, as in Pine. Then the previous bar is close[i + 1], not close[i - 1], and the overrun happens at the old end: i + Length must stay below rates_total. The equivalent guard is if(i + Length >= rates_total) { Buf[i] = EMPTY_VALUE; continue; }, and the loop that walks from old to new runs for(i = rates_total - 1 - start_offset; i >= 0; i--). A buffer you set as series must be set every call, because the terminal may reallocate it; set the orientation in OnInit for your own buffers and at the top of OnCalculate for the price arrays. Mixing the two orientations in one file is the most common way to get an out-of-range read that only appears on some charts. The series history guide walks through both layouts side by side.

Other causes of the same message

  • A dynamic array never sized. double tmp[]; tmp[0] = x; fails at index 0 because the array has zero elements. ArrayResize(tmp, n) first. An indicator buffer that was declared but never passed to SetIndexBuffer fails the same way on its first write; the journal entry points at that line.
  • Buffer index past indicator_buffers. SetIndexBuffer(2, ...) with #property indicator_buffers 2 returns false, the array stays unsized, and the first write to it is out of range.
  • CopyBuffer that returned fewer elements than you read. On the first ticks a handle may deliver less than requested. Check the return value and size the loop by it, not by rates_total.
  • Reading another timeframe by shift. iBarShift returns -1 when the time is outside the available history; indexing a copied array with it is out of range. Guard the -1.
  • Strings and StringGetCharacter. The same error text appears for a character index past the string length. Rare in ported indicators, but the message is identical.
  • Converted code. The Stratlate converter never indexes a price or series array with a raw offset. A Pine close[1] is emitted as pine_hist(close, __pineBar, 1), which returns the runtime's na value when the index would fall below 0 or beyond the array, and every windowed helper such as pine_sma(src, i, len) returns na until bar len - 1. If you add your own close[__pineBar - n] to a generated file, you reintroduce the problem; use pine_hist.

Pitfalls

  • Testing only on a chart with thousands of bars. The error is on bar 0 and happens on the first call, regardless of chart length, so it always fires; but a lookback of 200 on a symbol with 150 bars of history fails on the rates_total <= Length check, which only shows up on thin symbols or short timeframes. Test on a fresh symbol with little history.
  • Guarding with i > 0 only. That covers close[i - 1] and nothing else. Make the guard the maximum lookback the bar needs, including nested ones (an EMA of an RSI needs both lengths).
  • Returning rates_total after an early exit. If you leave the loop early on a short chart and still return rates_total, the terminal assumes every bar is done and will not recalculate them when history arrives. Return 0.
  • Leaving warm-up bars at 0 instead of EMPTY_VALUE. A separate-window oscillator then shows a flat line at zero for the first Length bars where TradingView shows nothing, and any comparison against the original reports a mismatch on exactly those bars.
  • Reading prev_calculated as "bars already safe". After a history reload the terminal can pass prev_calculated == 0 again at any time; the guard must live inside the loop, not only in the start calculation.

FAQ

Where do I see the array out of range message in MetaTrader 5?

In the Experts tab of the Toolbox window (View, Toolbox, then Experts), or in the file MQL5\Logs\YYYYMMDD.log inside the terminal's data folder. The entry names the program, the line and the column, so open the source at that position: the index expression there is the one to guard.

Why does the same Pine logic not need a guard on TradingView?

Because the history operator returns na when it reaches before the first bar, and arithmetic on na yields na. MQL5 arrays have no such value; a negative index is an error. Writing EMPTY_VALUE into the warm-up bars and skipping the lookback reproduces Pine's behaviour exactly.

Does the Stratlate converter guard history reads?

Yes. close[n] becomes pine_hist(close, bar, n), which returns the runtime's na constant when the index would leave the array, and the ta.* helpers return na until they have a full window. The generated indicator should still be compiled and compared against the original on the same bars; the guard prevents the crash, it does not prove the values match.

Let the converter do the mechanical part

Paste the original script and get a conversion that compiles, with every construct that could not be carried over reported instead of hidden. Review, compile and backtest the result before trading.

Open the converter

Related