Skip to main content

Pine Script array.push() — How to Add Elements to Arrays

· 9 min read
Pineify Team
Pine Script and AI trading workflow research team

I remember my first attempt at tracking price highs across bars in a TradingView script. I used a regular variable and lost every value except the last one. Pine Script array.push() is a function that adds new elements to the end of an array, letting you build dynamic data collections inside your indicators and strategies. Whether you're tracking RSI across 50 symbols or building a custom volatility tracker, this function is the tool I reach for.

Table of Contents

  1. How array.push() Works
  2. Basic Syntax and Implementation
  3. Real-World Trading Examples
  4. Advanced Array Management Techniques
  5. Common Mistakes and Best Practices
  6. Performance Optimization Tips

How array.push() Works

Think of array.push() like adding a new card to the bottom of a deck. Every time you call it, you're putting a new value at the end of your array. The array grows by one element each call. Simple.

Here's the thing — unlike regular variables that hold one value, arrays collect values over time. Want to remember every high from the last 20 bars? array.push() makes this dead simple.

Basic Syntax and Implementation

Pine Script array.push() Syntax

The array.push() function in Pine Script follows this syntax:

array.push(id, value) → void
  • id: The array identifier
  • value: The element to add to the array
  • Returns: Nothing (void function)

Simple array.push() Example

Here's how it actually works:

//@version=5
indicator("Array Push Example", overlay=true)

// Create an empty array for storing prices
var priceArray = array.new_float(0)

// Add today's close to our collection
array.push(priceArray, close)

// Show how many prices we've collected
label.new(bar_index, high, "Prices stored: " + str.tostring(array.size(priceArray)))

That's it. Every bar, we add the closing price to our collection. You'll see the count go up until... well, we'll talk about that in a moment.

The Best Pine Script Generator

Real-World Trading Examples

Let me walk through a few practical ways I've used array.push() in my own TradingView setups.

Example 1: Building a Rolling Window of Price Highs

I use this pattern constantly — tracking recent highs for AAPL or SPY on a 15-minute chart:

//@version=5
indicator("Recent Highs Tracker")

var recentHighs = array.new_float(0)

if barstate.isconfirmed
array.push(recentHighs, high)

// Keep only the last 20 highs
if array.size(recentHighs) > 20
array.shift(recentHighs)

See that array.shift()? That's your cleanup crew. Without it, your array grows until Pine Script hits its internal limits. I've accidentally let arrays balloon past 50,000 elements before — the script just stops working.

Example 2: Multi-Symbol Data Collection

Here's a trick for tracking multiple tickers in one script:

var symbolArray = array.new_string(0)
var rsiArray = array.new_float(0)

// Store symbol and its RSI
array.push(symbolArray, syminfo.ticker)
array.push(rsiArray, ta.rsi(close, 14))

This becomes really useful when you're scanning for oversold stocks. I've used this pattern to build a screener across the S&P 500, though I haven't tested it with more than 200 symbols.

Advanced Array Management Techniques

Using Arrays as LIFO Stacks

You know those spring-loaded plate dispensers at buffets? That's what arrays do when you use push and pop together:

var priceStack = array.new_float(0)

// Add a price to the top of our stack
array.push(priceStack, close)

// Later, grab the most recent price
if array.size(priceStack) > 0
latestPrice = array.pop(priceStack)

This works great for trailing stops. I prefer this over calculating on the fly because you can inspect the stack at any point during development. If you're new to Pine Script, you might want to start with the beginners guide to Pine Script first.

Common Mistakes and Best Practices

Mistake 1: Improper Variable Declaration

This one bit me hard when I started:

// This seems fine...
var myArray = array.new_float(0)
array.push(myArray, close)

The problem? That array keeps growing forever because var makes it persist across all bars. Your array will have thousands of elements before you realize it.

Better approach for most cases:

// Start fresh each bar
newArray = array.new_float(0)
array.push(newArray, close)

I don't use the var approach unless I explicitly need cross-bar persistence — and even then I cap the size.

Mistake 2: Poor Memory Management

Pine Script arrays can hold up to 100,000 elements, but honestly, you don't want to get anywhere near that. Here's my rule of thumb:

// Keep arrays small and manageable
if array.size(myArray) > 50
array.shift(myArray) // Remove the oldest
array.push(myArray, new_value) // Add the newest

I keep most arrays under 200 elements. Going past 1,000 has caused slowdowns on my machine during real-time bars.

Performance Optimization Tips

Technique 1: Efficient Data Processing

Once you've got the basics down, you can combine array.push() with loops and sorting like this:

var analysisArray = array.new_float(0)

// Collect EMA values
array.push(analysisArray, ta.ema(close, 20))

// When we have enough data, sort and find the median
if array.size(analysisArray) >= 10
array.sort(analysisArray, order.ascending)
medianValue = array.get(analysisArray, math.floor(array.size(analysisArray) / 2))

Technique 2: Selective Data Storage

Instead of collecting everything, be selective:

var bigMoves = array.new_float(0)

// Only track significant price movements
if math.abs(close - close[1]) > ta.atr(14) * 0.5
array.push(bigMoves, close - close[1])

This way you're only storing data that actually matters. I've found this cuts memory usage by roughly 80% compared to collecting every single bar. For more on working with data collections, check out for loops in Pine Script — they pair naturally with array operations.

That covers the core patterns I reach for when using array.push(). If you're collecting data for indicators, make sure you also understand repainting in Pine Script — it can invalidate everything you've stored.

What does array.push() do in Pine Script?

It adds a new element to the end of an existing array. Each call increases the array size by one. Returns nothing — the array gets modified in place. I use it in pretty much every script I write.

What is the maximum number of elements a Pine Script array can hold?

Pine Script allows up to 100,000 elements per array. In practice, I stay under 1,000. Push past that and you'll hit runtime errors and lag during real-time bars. I learned that one the hard way.

How do I prevent a Pine Script array from growing indefinitely?

Call array.shift() to drop the oldest element when the array passes your size limit. I shift then push every bar — that gives you a fixed-length rolling window that never gets out of hand.

What is the difference between array.push() and array.unshift() in Pine Script?

Array.push() adds to the end, array.unshift() inserts at the beginning. For a rolling window where the newest data sits at the tail, push() paired with shift() is the way to go.

Should I use the var keyword when declaring an array for array.push()?

Use var when the array needs to persist across bars — like building a price history. Skip it if you want a fresh array each bar. Var without a size cap is the most common bug I see in array code posted on TradingView forums.

Can I use array.push() inside an if block or only at the top level?

You can call push() anywhere — inside if blocks, for loops, even custom functions. I wrap mine in if barstate.isconfirmed so data only gets captured after the bar closes. That avoids half-baked values.

How do I use array.push() together with array.pop() as a LIFO stack?

Push values with array.push(), then pull the latest one back with array.pop(). Pop removes the last element and returns it — true last-in, first-out. I use this combo for trailing stops and recent support or resistance levels.

The Best Pine Script Generator