ArraySetAsSeries in Pine Script: index direction and []

Short answer

Nothing to set: every Pine series is newest-first. close[0] is the current bar and close[5] is five bars ago, so both arr[i + n] after ArraySetAsSeries and the oldest-first arr[i - n] become series[n].

ArraySetAsSeries(array, true) changes the indexing direction of a dynamic MQL5 array so that element 0 is the newest bar and higher indices go back in time, the way MQL4 price arrays always worked. Pine Script needs no such call: every series is addressed newest-first through the history operator, close[0] is the current bar and close[5] is five bars ago. The MQL5 pair "set as series, then read arr[i + n]" becomes series[n], and the oldest-first form arr[i - n] also becomes series[n].

What ArraySetAsSeries computes

It is a flag on the array, not a copy. After ArraySetAsSeries(a, true), a[0] refers to what was a[ArraySize(a) - 1]; the memory does not move and the flag can be flipped back. It only works on dynamic arrays and on the arrays MetaTrader passes to OnCalculate; a fixed-size local array cannot be made a series. Indicator buffers bound with SetIndexBuffer and the OnCalculate price arrays are oldest-first by default in MQL5, so a per-bar loop runs from prev_calculated - 1 up to rates_total - 1 and "n bars ago" is close[i - n]. After the flag is set, the same loop runs from limit - 1 down to 0 and "n bars ago" is close[i + n]. CopyBuffer and CopyRates respect the flag of the destination array, which is why ArraySetAsSeries(dst, true) is called before copying when the author wants dst[0] to be the latest value.

In Pine the direction is fixed and there is no index variable at all. The script runs on one bar; x[n] on any series x (built-in or your own variable) is the value n bars earlier, n must be a non-negative integer, and a reference before the first bar of the chart yields na rather than an error. The only place where you index with a variable is inside a for loop that walks history on the current bar, for example for k = 0 to len - 1 with high[k].

The Pine Script equivalent

An indicator that plots the close from n bars ago, written in MQL5 with a series-flagged buffer and a descending loop, and in Pine with one history read.

//@version=6
indicator("Close n bars ago", overlay = true)

len = input.int(5, "Bars back")

// Every series is "as series" in Pine: [0] is the current bar, [len] is len bars ago,
// and reading past the first bar gives na instead of an out-of-range error.
prevClose = close[len]

plot(prevClose, "Close n bars ago", color = color.rgb(147, 112, 219))
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrMediumPurple

input int InpLen = 5;   // Bars back

double PrevCloseBuffer[];

int OnInit()
{
   SetIndexBuffer(0, PrevCloseBuffer, INDICATOR_DATA);
   // Make the buffer newest-first so PrevCloseBuffer[0] is the current bar, like Pine's [0].
   ArraySetAsSeries(PrevCloseBuffer, true);
   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[])
{
   // The input arrays arrive oldest-first; flip close[] so close[i + InpLen] is "InpLen bars ago".
   ArraySetAsSeries(close, true);

   int limit = rates_total - prev_calculated;
   if(prev_calculated > 0)
      limit++;                                   // recompute the forming bar (index 0)

   for(int i = limit - 1; i >= 0; i--)           // newest-first: count down to the current bar
   {
      if(i + InpLen >= rates_total)
         PrevCloseBuffer[i] = EMPTY_VALUE;       // no bar that far back
      else
         PrevCloseBuffer[i] = close[i + InpLen]; // Pine: close[InpLen]
   }
   return(rates_total);
}

The conversion rule in one line: find the loop variable i in every index expression and remove it, keeping the distance. close[i + 5] (series) and close[i - 5] (non-series) both become close[5]; Buf[i] becomes buf; Buf[i + 1] (series) and Buf[i - 1] (non-series) both become buf[1].

Where the two differ

TopicMQL5 arraysPine series
DirectionOldest-first by default; flag per arrayAlways newest-first
Current bara[rates_total - 1] or a[0] when seriesa or a[0]
Out of rangeRuntime error "array out of range", indicator stopsna
Negative indexErrorCompile error; the future does not exist
Future bara[i + 1] readable in oldest-first mode (repaints)Not expressible
Writinga[i] = v anywhereOnly the current bar: a := v; history is read-only
Variable indexEverywhereAny series int works for built-ins and most variables; a few functions require a constant
Mixed flagsBuffers and price arrays can differ; a common bug sourceNo flags

The write rule is the deep difference. MQL5 code sometimes patches an earlier element (Buf[i - 1] = Buf[i] to extend a line, or a zigzag that moves its last pivot). Pine cannot change a past value of a series; such logic has to be restated as a drawing (line.new, label.new) or as a value that is only committed once it is final.

What the Stratlate converter emits

The MQL5 to Pine engine consumes ArraySetAsSeries once per program to decide the index direction of the whole OnCalculate sweep (IndicatorLowering.seriesAreOldestFirst: MQL5 defaults to oldest-first, and any ArraySetAsSeries(x, true) on a buffer or price array switches the sweep to newest-first). Each call is reported as absorbed, "Pine series are always newest-first; the emitted sweep already reads in that direction", and the index arithmetic is rewritten relative to the current bar, so close[i + InpLen] in the program above is emitted as close[math.max(0, InpLen)] and Buf[i] as a plain reassignment of Buf. The math.max(0, …) guard is there because Pine rejects a negative offset. A program that reads a future element (a[i + 1] with oldest-first arrays) cannot be expressed and the report says which read was not mapped; such indicators need to be restated by hand before conversion.

Pitfalls

  • Converting close[i - 1] from an oldest-first loop as close[-1]. Pine's offset is a distance into the past; the correct form is close[1]. Symptom: compile error about a negative or non-constant offset.
  • Forgetting that ArraySetAsSeries on close inside OnCalculate affects every later read in that function. If the MQL5 author flipped close but not high, the two arrays point opposite ways; translate each index expression according to its own array's flag.
  • Reading arr[i] for a Pine array object. Pine's [] on an array variable is the history operator (the array instance from i bars ago), not element access; use array.get(arr, i).
  • Assuming out-of-range reads fail. On the first bars of a chart close[20] is na silently; comparisons with na are false, so a condition that depends on it is quietly never true. Check with na() or nz() when that matters.
  • Keeping the descending for loop. A per-bar loop over all history is unnecessary in Pine and hits the execution time limit.

FAQ

Is there a Pine function to reverse a series like ArraySetAsSeries(false)?

No, and it is not needed. A Pine series is not a container you index freely; [n] always means "n bars ago". If you need an oldest-first container, build an array with array.push on each bar and index it with array.get.

How do I translate loops that read arr[i + k] for k = 1..N?

If the loop computes a sum, maximum or similar, replace it with the matching ta.* function (ta.sma, ta.highest, math.sum). Otherwise keep a for k = 1 to N loop on the current bar and read series[k]; the loop runs once per bar, not once per bar per history.

What does Pine do when an index exceeds the available history?

It returns na for numeric and string series and false for boolean ones. There is no exception and the script keeps running, which is the opposite of MQL5's "array out of range" runtime error that halts the indicator.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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