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.
1//@version=62indicator("Array Creation")34// 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)1112// Pre-sized array with default values13var levels = array.new_float(5, 0.0) // 5 elements, all 0.01415// Array literal syntax (v5+)16var fibLevels = array.from(0.236, 0.382, 0.5, 0.618, 0.786)1718plot(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.
1//@version=62indicator("Array Basics")34var prices = array.new_float(0)56// Push current close onto the array (grows by 1 each bar)7array.push(prices, close)89// Read values by index (0 = first element)10if array.size(prices) > 011 firstPrice = array.get(prices, 0) // oldest12 lastPrice = array.get(prices, array.size(prices) - 1) // newest1314// Maintain a fixed window of 100 elements15if array.size(prices) > 10016 array.shift(prices) // remove the oldest (index 0) element1718// Set a specific index to a new value19if array.size(prices) > 520 array.set(prices, 0, close) // overwrite the first element2122plot(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.
1//@version=62indicator("Array Iteration")34var prices = array.new_float(0)5array.push(prices, close)6if array.size(prices) > 507 array.shift(prices)89// Method 1: Classic for loop with index10sumPrices = 0.011for i = 0 to array.size(prices) - 112 sumPrices += array.get(prices, i)13avgPrice = sumPrices / array.size(prices)1415// Method 2: for...in syntax (cleaner, no manual indexing)16aboveCount = 017for price in prices18 if price > avgPrice19 aboveCount += 12021// Method 3: for...in with index access22maxIdx = 023maxVal = 0.024for [idx, val] in prices25 if val > maxVal26 maxVal := val27 maxIdx := idx2829plot(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). |
1//@version=62indicator("Array Manipulation")34var prices = array.new_float(0)5array.push(prices, close)6if array.size(prices) > 1007 array.shift(prices)89// Sort a COPY (preserve original chronological order)10sorted = array.copy(prices)11array.sort(sorted, order.ascending)1213// Get percentile values from sorted array14p25idx = int(array.size(sorted) * 0.25)15p50idx = int(array.size(sorted) * 0.50)16p75idx = int(array.size(sorted) * 0.75)1718if array.size(sorted) > 1019 p25 = array.get(sorted, p25idx)20 p50 = array.get(sorted, p50idx)21 p75 = array.get(sorted, p75idx)2223 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.
1//@version=62indicator("Array Stats")34var window = array.new_float(0)5array.push(window, close)6if array.size(window) > 1007 array.shift(window)89// Statistical functions10avg = array.avg(window) // mean11med = array.median(window) // median (middle value)12mx = array.max(window) // maximum13mn = array.min(window) // minimum14stdev = array.stdev(window) // standard deviation15vrnce = array.variance(window) // variance1617// Range and normalized position18range = mx - mn19position = range > 0 ? (close - mn) / range * 100 : 502021// Correlation between two arrays22var window2 = array.new_float(0)23array.push(window2, volume)24if array.size(window2) > 10025 array.shift(window2)26corr = array.covariance(window, window2) /27 (array.stdev(window) * array.stdev(window2))2829plot(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.
1//@version=62indicator("Rolling Window Anomaly", overlay=true)34windowSize = input.int(50, "Window Size", minval=10)5threshold = input.float(2.0, "Z-Score Threshold", step=0.1)67var returns = array.new_float(0)8ret = close != 0 ? (close - close[1]) / close[1] * 100 : 0.09array.push(returns, ret)10if array.size(returns) > windowSize11 array.shift(returns)1213// Only calculate when we have a full window14if array.size(returns) >= windowSize15 avg = array.avg(returns)16 stdev = array.stdev(returns)1718 // Z-score: how many standard deviations from the mean?19 zScore = stdev > 0 ? (ret - avg) / stdev : 0.02021 // Flag anomalous moves22 isAnomaly = math.abs(zScore) > threshold23 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.
1//@version=62indicator("Maps Demo")34// Create a map5var rsiMap = map.new<string, float>()67// 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))1112// Get values by key13rsi14 = rsiMap.get("RSI 14")1415// Check if a key exists16hasKey = rsiMap.contains("RSI 14") // true1718// Get all keys19keys = rsiMap.keys() // array of strings: ["RSI 7", "RSI 14", "RSI 21"]2021// Iterate over keys to find the highest RSI22highestRSI = 0.023highestKey = ""24for key in keys25 val = rsiMap.get(key)26 if not na(val) and val > highestRSI27 highestRSI := val28 highestKey := key2930// Get the number of entries31mapSize = rsiMap.size() // 33233// Remove a key34// rsiMap.remove("RSI 7")3536plot(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.
1//@version=62indicator("Matrix Demo")34// Create a 3x3 matrix initialized with zeros5var m = matrix.new<float>(3, 3, 0.0)67// 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))1415// Get a value16rsi14 = matrix.get(m, 0, 1)1718// Get dimensions19rows = matrix.rows(m) // 320cols = matrix.columns(m) // 32122// Get an entire row as an array23rsiRow = matrix.row(m, 0) // [rsi7, rsi14, rsi21]24avgRSI = array.avg(rsiRow)2526// Matrix operations27// matrix.add(m1, m2): element-wise addition28// matrix.mult(m1, m2): matrix multiplication29// matrix.transpose(m): swap rows and columns30// matrix.det(m): determinant31// matrix.inv(m): inverse3233plot(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.
1//@version=62indicator("Price Percentile", overlay=false)34// Inputs5windowSize = input.int(100, "Lookback Window", minval=20, maxval=500,6 group="Settings")7showBands = input.bool(true, "Show Percentile Bands", group="Display")89// Maintain a rolling window of closing prices10var window = array.new_float(0)11array.push(window, close)12if array.size(window) > windowSize13 array.shift(window)1415// Calculate percentile rank of current close16percentileRank = 0.017if array.size(window) >= windowSize18 sorted = array.copy(window)19 array.sort(sorted, order.ascending)2021 // Count values below current close22 belowCount = 023 for val in sorted24 if val < close25 belowCount += 126 percentileRank := belowCount / array.size(sorted) * 1002728 // Get specific percentile values29 if showBands30 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))3536// 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)3940// Reference lines41hline(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)4445// Background flash on extremes46bgcolor(percentileRank > 90 ? color.new(color.red, 88) :47 percentileRank < 10 ? color.new(color.green, 88) : na)Rolling window with array.push() and array.shift()
Sorting a copy for percentile calculation
array.sort() modifies in place. The original chronological order is preserved in the source array while the sorted copy enables percentile lookups.Percentile rank computation
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
[] 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.