Pine close[1] vs MQL5 arrays: indexing and ArraySetAsSeries

Short answer

In Pine, close[1] always means the previous bar. In MQL5 the same value can be close[i - 1], close[i + 1], c[1] or iClose(_Symbol, PERIOD_CURRENT, 1), depending on which array you hold and which way it is indexed, so check every history reference.

In Pine Script, close[1] always means the previous bar. In MQL5 the same value can be close[i - 1], close[i + 1], c[1] or iClose(_Symbol, PERIOD_CURRENT, 1), depending on which array you hold and which way it is indexed. This guide is for developers moving indicator or strategy logic between Pine and MetaTrader who want every history reference to land on the right bar.

How Pine's history operator works

TradingView runs a Pine script once per bar, from the oldest bar to the newest, and every variable becomes a series with one value per bar. The [] operator reads that series n bars back: close[1] is the previous bar's close, chg[2] is your own variable two bars ago, and (high - low)[1] works on any expression. You never write a loop and never manage an index.

Two details matter when converting. First, a reference before the first bar is na, not an error: on bar 0, close[1] is na and so is anything computed from it. Second, on the live bar an indicator recalculates on every tick, but x[1] always refers to the value the previous bar had when it closed.

//@version=6
indicator("Change and 3-bar high")
chg = close - close[1]                 // na on the first bar
hh  = math.max(high, high[1], high[2])
plot(chg, "Change")
plot(hh, "3-bar high")

MQL5 OnCalculate arrays are oldest-first

In MQL5 you write the bar loop yourself. The price arrays passed to OnCalculate (open, high, low, close, time, the volumes) and your indicator buffers are not series-indexed by default: index 0 is the oldest bar on the chart and rates_total - 1 is the bar that is still forming. With that layout, Pine's x[n] is simply x[i - n].

The loop starts at prev_calculated - 1 so the forming bar is recomputed on every tick, which is what Pine does on the realtime bar. The i >= 1 and i >= 2 guards reproduce Pine's na on the first bars; without them the indicator reads index -1 and stops with an "array out of range" error.

#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label1  "Change"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrange
#property indicator_label2  "3-bar high"

double ChgBuf[];
double HhBuf[];

int OnInit()
{
   SetIndexBuffer(0, ChgBuf, INDICATOR_DATA);
   SetIndexBuffer(1, HhBuf, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   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[])
{
   // Oldest bar is index 0, the forming bar is rates_total - 1.
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      // close[1] in Pine is close[i - 1] here; it does not exist on bar 0.
      ChgBuf[i] = (i >= 1) ? close[i] - close[i - 1] : EMPTY_VALUE;
      HhBuf[i]  = (i >= 2) ? MathMax(high[i], MathMax(high[i - 1], high[i - 2]))
                           : EMPTY_VALUE;
     }
   return rates_total;
}

Series indexing: ArraySetAsSeries, CopyClose and iClose

ArraySetAsSeries(arr, true) reverses how an array is indexed so that index 0 is the newest bar. It does not move or copy any data. Many MetaTrader examples use it, because it matches the MQL4 habit of counting bars back from the present. Once an array is series-indexed, Pine's close[1] becomes close[i + 1] and the loop runs downward:

ArraySetAsSeries(close, true);    // now close[0] is the newest bar
ArraySetAsSeries(ChgBuf, true);   // flip the buffer too, or the two disagree
int limit = (prev_calculated > 0) ? rates_total - prev_calculated : rates_total - 2;
for(int i = limit; i >= 0; i--)
   ChgBuf[i] = close[i] - close[i + 1];   // Pine close[1] is now i + 1

Pick one direction for the whole indicator. If you flip close but not the buffer you write into, each value lands at the mirrored end of the chart.

MQL4 is the other way round: the arrays passed to OnCalculate, the predefined Close[] and indicator buffers are all series-indexed by default. Code ported from MQL4 to MQL5 without adjusting the direction is the most common source of indicators that read the wrong bars.

Expert Advisors have no OnCalculate arrays. They read prices with iClose(symbol, timeframe, shift), where shift 0 is the forming bar and shift 1 the last closed bar, or copy a block with CopyClose into an array marked as series:

double c[];
ArraySetAsSeries(c, true);                       // c[0] = newest
if(CopyClose(_Symbol, PERIOD_CURRENT, 0, 3, c) < 3)
   return;
double lastClosed = c[1];                        // the bar that just closed
double prevClosed = c[2];                        // the bar before it
double same       = iClose(_Symbol, PERIOD_CURRENT, 1);   // equals c[1]
PineMQL5, oldest-firstMQL5, series-indexed / EA
closeclose[i]close[i], iClose(..., 0)
close[1]close[i - 1]close[i + 1], iClose(..., 1)
close[n]close[i - n], guard i >= nclose[i + n], guard i + n < rates_total
bar_indexirates_total - 1 - i

History of your own variables

Pine keeps history for every variable automatically. MQL5 does not: a double holds one value. Whenever the Pine script reads myVar[1], or updates a variable from its own previous value, the MQL5 version needs one slot per bar, either an indicator buffer (use INDICATOR_CALCULATIONS if it is not plotted) or an array sized to rates_total.

//@version=6
indicator("Body sum")
float s = na
s := nz(s[1]) + (close - open)
plot(s, "Body sum")
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrSeaGreen
#property indicator_label1  "Body sum"

double SumBuf[];

int OnInit()
{
   SetIndexBuffer(0, SumBuf, 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[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      // Pine: s := nz(s[1]) + (close - open)
      double prev = (i > 0) ? SumBuf[i - 1] : 0.0;
      SumBuf[i] = prev + (close[i] - open[i]);
     }
   return rates_total;
}

Reading SumBuf[i - 1] instead of keeping a running total in a static variable matters on the live bar. OnCalculate recomputes the forming bar on every tick; a running total would add the current bar's body once per tick and drift away from TradingView, then jump back when the chart is reloaded.

Strategies: which bar is close?

By default a Pine strategy evaluates once per bar, when the bar closes, and its orders fill at the next bar's open. In that context close is the final close of the bar that just finished. An MT5 Expert Advisor's OnTick runs on every tick of the forming bar instead. To reproduce the Pine timing, run the logic once on the first tick of a new bar and shift every reference by one: Pine's close becomes iClose(_Symbol, PERIOD_CURRENT, 1) and close[1] becomes shift 2. Forgetting the shift makes the EA trade on an unfinished bar, which shows up as signals that appear and disappear within a bar.

What Stratlate's converter does

The Pine to MQL5 converter forces every OnCalculate price array to oldest-first with ArraySetAsSeries(..., false), in both MQL4 and MQL5 output, so a Pine x[n] always becomes index i - n. Each series variable gets an array sized to rates_total, and a history read before the first bar returns na as it does in Pine. As with any conversion, compile the output in MetaEditor and backtest it before relying on it.

Pitfalls

  • Reading before the first bar. close[i - 1] at i = 0 stops the indicator with "array out of range" in the Experts log. Guard it and write EMPTY_VALUE, the equivalent of Pine's na.
  • Mixed directions. One array series-indexed, another not: the plot looks mirrored or values come from the opposite end of history.
  • MQL4 loops copied into MQL5. Close[i + 1] in an MQL5 oldest-first array reads the next bar. The indicator looks perfect on history because it is reading the future.
  • Static accumulators. A running total in a scalar drifts on the live bar because the forming bar is recalculated on every tick.
  • bar_index assumptions. MT5 history starts wherever the broker's data and the "Max bars in chart" setting allow, so i is not the same number as TradingView's bar_index for the same candle. Logic such as bar_index % 2 or a seed on bar 0 lands on different candles.
  • EA off-by-one. Using shift 0 where the Pine strategy used close trades on an unfinished bar.

FAQ

What is the MQL5 equivalent of close[1] in Pine Script?

Inside an OnCalculate loop with the default oldest-first arrays it is close[i - 1]. If the array is series-indexed with ArraySetAsSeries(close, true) it is close[i + 1]. In an Expert Advisor, iClose(_Symbol, PERIOD_CURRENT, 1) returns the last closed bar.

Are MQL5 indicator arrays series-indexed by default?

No. In MQL5 the price arrays passed to OnCalculate and indicator buffers are indexed oldest-first, so index 0 is the oldest bar. MQL4 passes them series-indexed, with index 0 as the newest bar, which is why code ported from MQL4 often reads the wrong bars.

Does ArraySetAsSeries change the data in the array?

No. It only changes the direction of indexing. The same values stay in memory; index 0 simply refers to the newest element instead of the oldest.

Convert Pine history references automatically

Paste a Pine Script indicator and get MQL5 with every [n] reference mapped to the right bar. Compile the result in MetaEditor and backtest it before you rely on it.

Open the converter

Related guides