FAQ

How to Loop Through Arrays in Pine Script?

How to Loop Through Arrays in Pine Script?

TradingView recently added an array feature to Pine Script. This powerful new feature allows traders to build custom datasets by working with one-dimensional data structures. However, given that this is a fairly new feature, there aren’t many examples and tutorials to guide beginners. You may find that even the simplest Pine Script array operations result in some problem or difficulty. 

I created this brief guide to help you learn how to iterate through an array in Pine Script using a for loop. 

Step 1: Define an array

Here’s how to define an array and assign a couple of values.

//@version=4
study("Loop through arrays")

arr = array.new_int(0)

array.push(arr, 1)
array.push(arr, 2)
array.push(arr, 3)
array.push(arr, 4)
array.push(arr, 5)

Step 2: Use a for loop to iterate through the array 

Arrays start at index 0 (zero) and end at the last index (equivalent to the length of the array minus one). We’ll create a string variable and loop through the array to display all the elements on the chart as a label.

lab = ""
for i = 0 to array.size(arr) - 1
    lab := lab + tostring(array.get(arr, i)) + " "
    
l = label.new(bar_index, close, lab)
label.delete(l[1])

This Script should display all the elements of your array as a label. Feel free to try it with different values assigned to the array.

Step 3: Loop backwards through the array 

To further cement your understanding of array iteration in Pine Script, let’s explore how you can loop backward through an array. This challenge requires that we are a bit more creative given that you cannot construct a declining for loop in Pine Script. So how do we go about it? We use the same for loop as in step 2 but then simply calculate indexes backward.

lab = ""
for i = 0 to array.size(arr) - 1
    lab := lab + tostring(array.get(arr, array.size(arr) - 1 - i)) + " "
    
l = label.new(bar_index, close, lab)
label.delete(l[1])

This should display the elements of the array in reverse order.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news