Back to TradingView PineScript for CFD Traders
Part 2

Arrays and matrices: working with multiple series

Pine arrays are fixed at runtime. Matrices are 2D. Both are how you do work Pine's vector model can't express directly.

Intermediate10 min readBeginner → AdvancedLesson 09 / 17
Try it in TradingView
Rolling high of up-bar closes

The array only accepts closes from up bars and drops the oldest when it hits 50. The green line is the highest of those — something no single built-in gives you.

//@version=5
indicator("Lesson 9 - Arrays", overlay=true)

// Keep the last 50 closes, but only from up bars.
var float[] upCloses = array.new_float(50)

if close > close[1]
    array.push(upCloses, close)
    if array.size(upCloses) > 50
        array.shift(upCloses)

// array.max of an empty array errors — guard with na.
float highestUpClose = array.size(upCloses) > 0 ? array.max(upCloses) : na

plot(highestUpClose, "Highest up-close (last 50)", color=color.green, linewidth=2)
plot(close, "Close", color=color.gray, linewidth=1)
To run it
  1. 1. Open any chart in TradingView and click Pine Editor at the bottom.
  2. 2. Select everything in the editor and paste this over it, then click Save.
  3. 3. Click Add to chart. Open the Strategy Tester tab if it is a strategy.

Arrays are dynamic, with limits

Unlike Python lists, Pine arrays have a maximum size set when you create them:

var float[] prices = array.new_float(20)
array.push(prices, close)
array.shift(prices)

This keeps the last 20 closes. array.push appends to the end, array.shift removes from the front. When the array hits its max size, the oldest element is dropped automatically.

Common array operations

array.size(a), array.get(a, i), array.set(a, i, value), array.sum(a), array.avg(a), array.max(a), array.min(a), array.includes(a, v). The full reference is in the Pine v5 manual.

Why arrays matter in Pine

The vector model gives you all bars at once — but it doesn't give you a way to do something like "the highest high of the last 20 up-bars". For that you push the relevant values into an array and scan it.

Matrices for 2D work

array.new_matrix(rows, cols, initValue) gives you a 2D structure. Useful for portfolio-level indicators, correlation tables, and order-book approximations.

A worked example: rolling high of up-bars

var float[] upCloses = array.new_float(50)
if close > close[1]
    array.push(upCloses, close)
if array.size(upCloses) > 50
    array.shift(upCloses)

highestUpClose = array.max(upCloses)
plot(highestUpClose)

What to take from this

Arrays and matrices are escape hatches when Pine's vector model doesn't fit. For 90% of CFD indicators you won't need them — but when you do, they are how you keep the script fast instead of looping bar by bar.

What you just did

Lesson 09 of 17 in TradingView PineScript for CFD Traders. When you have run the examples or read the section, tick it off and move to the next lesson.