Skip to main content

Arrays & Data Structures

Introduction to arrays, array loops, for...in syntax, inserting, removing, sorting, merging, array correlation, maps, and matrices.

Introduction to Arrays

Arrays are ordered collections of values of the same type. While PineScript's history operator [] gives you access to past bar values, arrays give you a mutable, resizable collection that you can sort, filter, aggregate, and transform. Arrays unlock custom calculations that built-in functions cannot provide: custom percentiles, rolling windows, dynamic support/resistance tracking, and correlation analysis.

Think of an array as a numbered list where you can add items to the end, remove items from the beginning, insert items at any position, sort the entire list, and compute statistics on all items at once. On every bar, you can push the current close into the array, remove the oldest value to maintain a fixed window size, and then compute the median: something the history operator alone cannot do.

Creating Arrays

Arrays are created with array.new_<type>()functions. You specify the initial size (can be 0) and an optional default value. Always declare arrays with var so they persist across bars, without var, the array would be recreated empty on every bar.

pine-Array creation methods
1//@version=6
2indicator("Array Creation")
3
4// Empty arrays (will be populated dynamically)
5var closes = array.new_float(0)
6var volumes = array.new_float(0)
7var signals = array.new_bool(0)
8var labels = array.new_string(0)
9var colors = array.new_color(0)
10var integers = array.new_int(0)
11
12// Pre-sized array with default values
13var levels = array.new_float(5, 0.0) // 5 elements, all 0.0
14
15// Array literal syntax (v5+)
16var fibLevels = array.from(0.236, 0.382, 0.5, 0.618, 0.786)
17
18plot(array.size(closes), "Array Size")

Core Operations: push, get, set, size

The four most fundamental array operations are array.push() (add to end), array.get() (read by index), array.set() (write by index), and array.size() (count elements). These are the building blocks of every array-based pattern.

pine-Basic array operations
1//@version=6
2indicator("Array Basics")
3
4var prices = array.new_float(0)
5
6// Push current close onto the array (grows by 1 each bar)
7array.push(prices, close)
8
9// Read values by index (0 = first element)
10if array.size(prices) > 0
11 firstPrice = array.get(prices, 0) // oldest
12 lastPrice = array.get(prices, array.size(prices) - 1) // newest
13
14// Maintain a fixed window of 100 elements
15if array.size(prices) > 100
16 array.shift(prices) // remove the oldest (index 0) element
17
18// Set a specific index to a new value
19if array.size(prices) > 5
20 array.set(prices, 0, close) // overwrite the first element
21
22plot(array.size(prices), "Window Size")

Iterating Over Arrays

PineScript provides two ways to loop through arrays: the classic for loop with array.size(), and the cleaner for...in syntax that automatically iterates over each element.

pine-Two iteration patterns
1//@version=6
2indicator("Array Iteration")
3
4var prices = array.new_float(0)
5array.push(prices, close)
6if array.size(prices) > 50
7 array.shift(prices)
8
9// Method 1: Classic for loop with index
10sumPrices = 0.0
11for i = 0 to array.size(prices) - 1
12 sumPrices += array.get(prices, i)
13avgPrice = sumPrices / array.size(prices)
14
15// Method 2: for...in syntax (cleaner, no manual indexing)
16aboveCount = 0
17for price in prices
18 if price > avgPrice
19 aboveCount += 1
20
21// Method 3: for...in with index access
22maxIdx = 0
23maxVal = 0.0
24for [idx, val] in prices
25 if val > maxVal
26 maxVal := val
27 maxIdx := idx
28
29plot(avgPrice, "Avg", color.blue, 2)
30plot(aboveCount, "Above Avg Count", color.orange)

Array Manipulation: Remove, Insert, Sort, Merge

Beyond basic push/get, arrays support a rich set of manipulation operations. Understanding these transforms your arrays from simple lists into powerful analytical tools.

array.shift(arr)Removes and returns the FIRST element (index 0). Use for FIFO rolling windows.
array.pop(arr)Removes and returns the LAST element. Use for LIFO stack patterns.
array.unshift(arr, val)Inserts a value at the BEGINNING (index 0). All other elements shift right.
array.insert(arr, idx, val)Inserts a value at a specific index. Elements at and after idx shift right.
array.remove(arr, idx)Removes the element at a specific index. Subsequent elements shift left.
array.sort(arr, order)Sorts in place. order.ascending or order.descending. Essential for percentile calculations.
array.concat(arr1, arr2)Appends all elements of arr2 to the end of arr1.
array.copy(arr)Creates a shallow copy. Essential before sorting if you need the original order preserved.
array.clear(arr)Removes all elements, resetting size to 0.
array.slice(arr, from, to)Returns a new array containing elements from index from to to (exclusive).
pine-Sorting and merging
1//@version=6
2indicator("Array Manipulation")
3
4var prices = array.new_float(0)
5array.push(prices, close)
6if array.size(prices) > 100
7 array.shift(prices)
8
9// Sort a COPY (preserve original chronological order)
10sorted = array.copy(prices)
11array.sort(sorted, order.ascending)
12
13// Get percentile values from sorted array
14p25idx = int(array.size(sorted) * 0.25)
15p50idx = int(array.size(sorted) * 0.50)
16p75idx = int(array.size(sorted) * 0.75)
17
18if array.size(sorted) > 10
19 p25 = array.get(sorted, p25idx)
20 p50 = array.get(sorted, p50idx)
21 p75 = array.get(sorted, p75idx)
22
23 plot(p25, "25th %ile", color.red)
24 plot(p50, "50th %ile", color.white)
25 plot(p75, "75th %ile", color.green)

Array Statistics

PineScript provides built-in statistical functions on arrays. These are optimized and significantly faster than computing statistics manually in a loop.

pine-Built-in array statistics
1//@version=6
2indicator("Array Stats")
3
4var window = array.new_float(0)
5array.push(window, close)
6if array.size(window) > 100
7 array.shift(window)
8
9// Statistical functions
10avg = array.avg(window) // mean
11med = array.median(window) // median (middle value)
12mx = array.max(window) // maximum
13mn = array.min(window) // minimum
14stdev = array.stdev(window) // standard deviation
15vrnce = array.variance(window) // variance
16
17// Range and normalized position
18range = mx - mn
19position = range > 0 ? (close - mn) / range * 100 : 50
20
21// Correlation between two arrays
22var window2 = array.new_float(0)
23array.push(window2, volume)
24if array.size(window2) > 100
25 array.shift(window2)
26corr = array.covariance(window, window2) /
27 (array.stdev(window) * array.stdev(window2))
28
29plot(avg, "Mean", color.blue, 2)
30plot(avg + stdev * 2, "Upper 2σ", color.new(color.red, 50))
31plot(avg - stdev * 2, "Lower 2σ", color.new(color.green, 50))

Rolling Window Pattern

The rolling window is the most common array pattern in PineScript. On every bar, you push a new value and remove the oldest, maintaining a fixed-size window. This lets you compute statistics, detect anomalies, and track distributions over a moving period.

pine-Rolling window with anomaly detection
1//@version=6
2indicator("Rolling Window Anomaly", overlay=true)
3
4windowSize = input.int(50, "Window Size", minval=10)
5threshold = input.float(2.0, "Z-Score Threshold", step=0.1)
6
7var returns = array.new_float(0)
8ret = close != 0 ? (close - close[1]) / close[1] * 100 : 0.0
9array.push(returns, ret)
10if array.size(returns) > windowSize
11 array.shift(returns)
12
13// Only calculate when we have a full window
14if array.size(returns) >= windowSize
15 avg = array.avg(returns)
16 stdev = array.stdev(returns)
17
18 // Z-score: how many standard deviations from the mean?
19 zScore = stdev > 0 ? (ret - avg) / stdev : 0.0
20
21 // Flag anomalous moves
22 isAnomaly = math.abs(zScore) > threshold
23 plotshape(isAnomaly and zScore > 0, "Positive Anomaly",
24 shape.diamond, location.abovebar, color.green, size=size.small)
25 plotshape(isAnomaly and zScore < 0, "Negative Anomaly",
26 shape.diamond, location.belowbar, color.red, size=size.small)

Maps: Key-Value Stores

Maps (dictionaries) store key-value pairs. They let you associate names with values, which is cleaner than parallel arrays when you need to track labeled data like RSI values for different timeframes or price levels for different support/resistance zones.

pine-Map operations
1//@version=6
2indicator("Maps Demo")
3
4// Create a map
5var rsiMap = map.new<string, float>()
6
7// Put values (add or update key-value pairs)
8rsiMap.put("RSI 7", ta.rsi(close, 7))
9rsiMap.put("RSI 14", ta.rsi(close, 14))
10rsiMap.put("RSI 21", ta.rsi(close, 21))
11
12// Get values by key
13rsi14 = rsiMap.get("RSI 14")
14
15// Check if a key exists
16hasKey = rsiMap.contains("RSI 14") // true
17
18// Get all keys
19keys = rsiMap.keys() // array of strings: ["RSI 7", "RSI 14", "RSI 21"]
20
21// Iterate over keys to find the highest RSI
22highestRSI = 0.0
23highestKey = ""
24for key in keys
25 val = rsiMap.get(key)
26 if not na(val) and val > highestRSI
27 highestRSI := val
28 highestKey := key
29
30// Get the number of entries
31mapSize = rsiMap.size() // 3
32
33// Remove a key
34// rsiMap.remove("RSI 7")
35
36plot(nz(rsi14), "RSI 14", color.white, 2)

Matrices: 2D Data Structures

Matrices are two-dimensional arrays. They are useful for correlation tables, multi-asset comparison grids, and any calculation that naturally maps to rows and columns. PineScript provides a full set of matrix operations including element access, row/column operations, and mathematical functions.

pine-Matrix basics
1//@version=6
2indicator("Matrix Demo")
3
4// Create a 3x3 matrix initialized with zeros
5var m = matrix.new<float>(3, 3, 0.0)
6
7// Set individual elements: matrix.set(matrix, row, col, value)
8matrix.set(m, 0, 0, ta.rsi(close, 7))
9matrix.set(m, 0, 1, ta.rsi(close, 14))
10matrix.set(m, 0, 2, ta.rsi(close, 21))
11matrix.set(m, 1, 0, ta.sma(close, 7))
12matrix.set(m, 1, 1, ta.sma(close, 14))
13matrix.set(m, 1, 2, ta.sma(close, 21))
14
15// Get a value
16rsi14 = matrix.get(m, 0, 1)
17
18// Get dimensions
19rows = matrix.rows(m) // 3
20cols = matrix.columns(m) // 3
21
22// Get an entire row as an array
23rsiRow = matrix.row(m, 0) // [rsi7, rsi14, rsi21]
24avgRSI = array.avg(rsiRow)
25
26// Matrix operations
27// matrix.add(m1, m2): element-wise addition
28// matrix.mult(m1, m2): matrix multiplication
29// matrix.transpose(m): swap rows and columns
30// matrix.det(m): determinant
31// matrix.inv(m): inverse
32
33plot(nz(avgRSI), "Avg RSI", color.yellow, 2)

Complete Build: Custom Percentile Indicator

Let's combine arrays, sorting, statistics, and visualization into a production-grade indicator that shows where the current price sits within its historical distribution. This is a powerful tool for identifying when an asset is trading at extreme levels relative to its own recent history.

pine-Price Percentile Indicator (full script)
1//@version=6
2indicator("Price Percentile", overlay=false)
3
4// Inputs
5windowSize = input.int(100, "Lookback Window", minval=20, maxval=500,
6 group="Settings")
7showBands = input.bool(true, "Show Percentile Bands", group="Display")
8
9// Maintain a rolling window of closing prices
10var window = array.new_float(0)
11array.push(window, close)
12if array.size(window) > windowSize
13 array.shift(window)
14
15// Calculate percentile rank of current close
16percentileRank = 0.0
17if array.size(window) >= windowSize
18 sorted = array.copy(window)
19 array.sort(sorted, order.ascending)
20
21 // Count values below current close
22 belowCount = 0
23 for val in sorted
24 if val < close
25 belowCount += 1
26 percentileRank := belowCount / array.size(sorted) * 100
27
28 // Get specific percentile values
29 if showBands
30 p10 = array.get(sorted, int(array.size(sorted) * 0.10))
31 p25 = array.get(sorted, int(array.size(sorted) * 0.25))
32 p50 = array.get(sorted, int(array.size(sorted) * 0.50))
33 p75 = array.get(sorted, int(array.size(sorted) * 0.75))
34 p90 = array.get(sorted, int(array.size(sorted) * 0.90))
35
36// Plot percentile rank (0-100 scale like RSI)
37pctColor = color.from_gradient(percentileRank, 10, 90, color.green, color.red)
38plot(percentileRank, "Percentile Rank", pctColor, 3)
39
40// Reference lines
41hline(90, "90th %ile", color.new(color.red, 60), hline.style_dashed)
42hline(50, "50th %ile", color.new(color.gray, 60))
43hline(10, "10th %ile", color.new(color.green, 60), hline.style_dashed)
44
45// Background flash on extremes
46bgcolor(percentileRank > 90 ? color.new(color.red, 88) :
47 percentileRank < 10 ? color.new(color.green, 88) : na)
1

Rolling window with array.push() and array.shift()

On every bar, the current close is pushed to the end of the array. Once the array exceeds the window size, the oldest element is removed from the front. This maintains a fixed-size sliding window.
2

Sorting a copy for percentile calculation

We copy the array before sorting because array.sort() modifies in place. The original chronological order is preserved in the source array while the sorted copy enables percentile lookups.
3

Percentile rank computation

Count how many values in the sorted window are below the current close, divide by the window size, and multiply by 100. A rank of 95 means the current price is higher than 95% of the values in the lookback window: an extreme reading.
4

Gradient visualization

color.from_gradient() maps the percentile to a color spectrum: green at the bottom (oversold), red at the top (overbought). This makes extreme readings visually obvious at a glance.

When to use arrays vs the history operator

Use the [] history operator when you need a specific past value (e.g., close[14]). Use arrays when you need to aggregate, sort, filter, or statistically analyze a collection of values. If you find yourself writing a for loop that just sums close[i] values, use ta.sma() instead. Arrays shine when built-in functions cannot do what you need.

Put this lesson to work

Free on Thrive, no account needed.