close[1] in MQL5: the history operator and array offsets

Short answer

In an MQL5 indicator, Pine's close[1] is close[i - 1] inside the OnCalculate loop over i, because the price arrays arrive oldest-first. Any series the script computes itself needs its own buffer before it can be read n bars back.

In Pine Script close[1] is the previous bar's close and x[n] is the value of any series n bars ago. In MQL5 the same read is an array index relative to the bar being computed: inside the OnCalculate loop over i, close[1] is close[i - 1], because the price arrays arrive oldest-first. A series the script computes itself needs a buffer of its own before it can be offset.

What x[n] computes

Every Pine variable is a series with one value per bar. x[n] reads the value the series had n bars before the current one; x[0] is x. If fewer than n bars exist, the result is na, never an error. The operator applies to anything: built-in prices, user variables, function results (ta.sma(close, 20)[1]) and expressions in parentheses ((high + low)[2]). On the realtime bar x[1] is the committed value of the last closed bar and does not change between ticks, while x[0] does.

Series are addressed newest-first: offset 0 is the current bar, offsets grow into the past. That is the opposite of MQL5's default, and the source of most translation mistakes.

The MQL5 equivalent

OnCalculate hands the indicator open[], high[], low[], close[], time[] and volume arrays with index 0 at the oldest bar and rates_total - 1 at the newest. Looping i upwards reproduces Pine's bar order, and x[n] is x[i - n]. A user series such as mid = (high + low) / 2 is a single number in MQL5 unless it is stored per bar, so give it a calculation buffer and write it on every bar before any offset read.

//@version=6
indicator("history operator demo")
float mid = (high + low) / 2
float mom = close - close[3]
float midBack = mid[2]
plot(mom, "mom")
plot(midBack, "midBack")
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrangeRed

double MomBuf[];      // close - close[3]
double MidBackBuf[];  // mid[2]
double MidBuf[];      // the script's own series `mid`, one slot per bar

const double NA = MathLog(-1.0);

// Pine's x[n] on an oldest-first array: index i - n, na before the start
double Hist(const double &x[], const int i, const int n)
{
   return (i - n >= 0) ? x[i - n] : NA;
}

int OnInit()
{
   SetIndexBuffer(0, MomBuf, INDICATOR_DATA);
   SetIndexBuffer(1, MidBackBuf, INDICATOR_DATA);
   SetIndexBuffer(2, MidBuf, INDICATOR_CALCULATIONS);
   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[])
{
   // Pin the direction: index 0 is the OLDEST bar, like Pine's bar 0.
   ArraySetAsSeries(close, false);
   ArraySetAsSeries(high,  false);
   ArraySetAsSeries(low,   false);

   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // Pine: float mid = (high + low) / 2
      MidBuf[i] = (high[i] + low[i]) / 2.0;
      // Pine: float mom = close - close[3]
      double mom = close[i] - Hist(close, i, 3);
      // Pine: float midBack = mid[2]
      double midBack = Hist(MidBuf, i, 2);
      MomBuf[i]     = MathIsValidNumber(mom)     ? mom     : EMPTY_VALUE;
      MidBackBuf[i] = MathIsValidNumber(midBack) ? midBack : EMPTY_VALUE;
   }
   return rates_total;
}

The Hist helper does what Pine does silently: an index before the first bar returns na instead of raising "array out of range". ArraySetAsSeries(close, false) is the default direction in MQL5 and is stated to make it explicit; in MQL4 the same arrays arrive newest-first, so a program meant to compile in both dialects needs that line.

Where the two differ

AspectPine x[n]MQL5
Index direction0 = current bar, grows into the past0 = oldest bar unless ArraySetAsSeries(arr, true), then 0 = newest
Offset from the bar being computedx[n]x[i - n] oldest-first; x[shift + n] on a series array
Before the first barnaruntime error "array out of range" and the indicator stops; guard i - n >= 0
User seriesevery variable has historyonly arrays do; scalars keep the last assigned value
Function resultsf(x)[1] worksstore the result in a buffer and read the previous slot, or call the native handle with the shift
Size of historylimited by max_bars_back, usually inferredthe whole array; no declaration needed
Realtime barx[1] fixed, x[0] changes per ticksame as long as buf[i-1] is read, not a scalar from the previous call

What the Stratlate converter emits

The engine forces the oldest-first direction with ArraySetAsSeries(arr, false) on every input array at the top of OnCalculate, loops the bar index upwards, and emits x[n] as pine_hist(x, __pineBar, n), a runtime helper that returns PINE_NA when i - n is out of range. A user series that is read with an offset is materialised as an array sized to rates_total (the example's mid became double mid[] with ArrayResize(mid, rates_total)). For time[] and volume arrays the out-of-range read is clamped to the nearest bar instead of na. The mapping is exact and produces no note.

Pitfalls

  • Translating close[1] as close[i + 1]: that is the next bar on an oldest-first array. Symptom: the indicator leads price by one bar on history and reads past the array end on the newest bar.
  • Mixing directions: calling ArraySetAsSeries(close, true) and then indexing a buffer that was left oldest-first. Symptom: a mirror-image plot, or values that are right only near one end of the chart.
  • Offsetting a scalar: double mid = ...; mid[2] does not compile, and the usual fix, a global prevMid, breaks on the forming bar because it is assigned on every tick.
  • No bounds check: close[i - 3] at i = 0 stops the indicator with "array out of range" in the Experts log and leaves the chart empty.
  • Starting the loop at prev_calculated rather than prev_calculated - 1: the forming bar keeps its first-tick values and x[1] read from it on the next bar is wrong.

FAQ

Is MQL5 close[1] the same as Pine close[1]?

Not by default. In an MQL5 indicator close[1] is the second-oldest bar, because OnCalculate arrays are oldest-first. Pine's close[1] is close[i - 1] in the bar loop, or close[1] only after ArraySetAsSeries(close, true) when computing the newest bar at index 0.

How do I reference a previous value of my own variable in MQL5?

Store the variable in an array with one slot per bar, usually an INDICATOR_CALCULATIONS buffer, write it on every bar, and read slot i - n. A plain variable has no history and a static one is not rolled back when the forming bar recalculates.

What does Pine return for close[500] on bar 10?

na. Pine never raises an index error for the history operator. In MQL5 the same read is a runtime error that halts the indicator, so a guard that returns NaN or EMPTY_VALUE for i - n less than 0 is needed to match.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related