How to add an element to the start of a Pine Script array?
How to add an element to the start of a Pine Script array?
Section titled “How to add an element to the start of a Pine Script array?”TL;DR
Usearray.unshift()to prepend elements, maintain array size, and manage rolling windows in Pine Script.
At a Glance
Section titled “At a Glance”| Difficulty | Beginner |
| Time to implement | 5-10 min |
| Category | Arrays |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=5indicator("Array prepend demo", overlay=false)
arr = array.new_float()array.unshift(arr, close) // add latest close to front
plot(array.size(arr) > 0 ? arr[0] : na, "Newest value")Why It Matters
Section titled “Why It Matters”Sometimes you want the newest values at index 0 for easy access (e.g., to maintain a rolling list or feed custom logic). Prepending lets you treat arr[0] as “most recent” with minimal bookkeeping.
What You’ll Learn
Section titled “What You’ll Learn”- Creating arrays and adding elements to the front
- Maintaining a fixed-size rolling buffer
- Displaying array contents for debugging
- Combining
unshift()with other array operations
Quick Reference
Section titled “Quick Reference”| Call | Purpose |
|---|---|
array.new_*() | Creates array storage for integers, floats, etc. |
array.unshift(id, value) | Inserts value at index 0. |
array.pop(id) | Removes the last element (useful to keep size constant). |
array.get(id, index) | Reads values at a specific index. |
array.size(id) | Returns the number of elements currently stored. |
Implementation Blueprint
Section titled “Implementation Blueprint”-
Create or reuse the array
Decide which data type you need—float, int, bool, etc.—and initialise once withvar.var arr = array.new_float() -
Prepend the new value
Callarray.unshift()each time you want to add to the front.array.unshift(arr, close) -
Optionally trim the array
If you only need the N most recent elements, pop the last one when size exceeds your target.if array.size(arr) > 10array.pop(arr)
Example Playbook
Section titled “Example Playbook”//@version=5indicator("Rolling window with unshift", overlay=false)
length = input.int(5, "Window size", minval=1)var float[] values = array.new_float()
array.unshift(values, close)if array.size(values) > length array.pop(values)
rollingAvg = array.size(values) > 0 ? array.sum(values) / array.size(values) : na
plot(close, "Close", color=color.gray)plot(rollingAvg, "Rolling avg (front-based)", color=color.orange)- Newest values always reside at index 0, simplifying custom calculations.
- Popping the array after exceeding `length` keeps the window fixed-size.
- The example demonstrates how to derive statistics from the front-based buffer.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”- Avoid repeatedly creating arrays inside the main code block; use
varto initialise once. - Accessing array elements is zero-based—
arr[0]is the newest afterunshift(). - For performance, try to keep array sizes small if you frequently call
unshift()andpop(). - If you only need historical values occasionally, consider using built-in series indexing (
value[bar_index]) instead of arrays.
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”Why am I seeing runtime error when accessing arr[0]?
Section titled “Why am I seeing runtime error when accessing arr[0]?”Ensure the array is not empty (array.size(arr) > 0) before reading index 0.
Do I need to clear the array each bar?
Section titled “Do I need to clear the array each bar?”No. Arrays persist across bars. Use array.clear(arr) only when you want to reset the buffer manually.
Key Takeaways
Section titled “Key Takeaways”array.unshift()is the go-to method for prepending values.- Combine it with
array.pop()to manage rolling windows of data. - Always guard against empty arrays when reading indices.
- Arrays give you flexible storage beyond built-in series referencing.
Keep Going
Section titled “Keep Going”- Open AI Editor to apply the pattern with guided assistance
- Browse PineScript Examples for ready-to-run templates
- Connect to Live Trading when you are ready to automate
Adapted from tradingcode.net, optimised for Algo Trade Analytics users.