array namespace
Overview
Section titled “Overview”Arrays are dynamic lists that hold values you can add, remove, or modify at runtime. Pine Script exposes arrays through the array. namespace, which offers constructors (array.new_*) and utility functions (array.push, array.get, array.sort, …). Use arrays when you need to store collections whose size changes during script execution.
Note. Arrays exist only while the script runs. They are not plotted automatically, so you must read values back (`array.get`) and draw them if you want to visualize contents.
Common constructors
Section titled “Common constructors”| Function | Purpose |
|---|---|
array.new_float(size, initial_value) | Create a float array with size elements initialized to initial_value (defaults to na). |
array.new_int(size, initial_value) | Create an integer array. |
array.new_bool(size, initial_value) | Create a boolean array. |
array.new_string(size, initial_value) | Create a string array. |
Common operations
Section titled “Common operations”| Function | Description |
|---|---|
array.push(id, value) | Append value to the end of the array. |
array.pop(id) | Remove and return the last element. |
array.unshift(id, value) | Insert value at the beginning of the array. |
array.shift(id) | Remove and return the first element. |
array.get(id, index) | Read the value at index. |
array.set(id, index, value) | Replace the element at index. |
array.size(id) | Return the number of elements. |
array.clear(id) | Remove all elements. |
See the array module docs for the full API.
Example
Section titled “Example”//@version=5indicator("Array moving window", overlay=false)
window = input.int(5, "Window size", minval=1, maxval=100)threshold = input.float(0.0, "Highlight threshold")
var float[] recentDiffs = array.new_float()
if barstate.isnew diff = close - close[1] array.push(recentDiffs, diff) if array.size(recentDiffs) > window array.shift(recentDiffs)
sum = 0.0 for i = 0 to array.size(recentDiffs) - 1 sum += array.get(recentDiffs, i)
avgDiff = sum / math.max(array.size(recentDiffs), 1) plot(avgDiff, "Avg diff") bgcolor(avgDiff > threshold ? color.new(color.green, 90) : na)