How to loop/iterate through an array in Pine Script with a “for/in” statement

Arrays are pretty crucial for Pine Script. From the time of their release, it immediately became Pine’s essential feature. Some time ago, I published an article about how to loop through an array in Pine Script. But language evolves quite quickly, and there is already a much more convenient way to iterate through an array. For that, you can use the “for/in” statement.

Let’s start with defining an array in Pine Script:

arr = array.from(1, 5, 2, 4 , 3)

To display an array on the screen, you can use. labels:

if barstate.islast
    label.new(bar_index, close, str.tostring(arr))

It’s quite easy to use “for/in” statement in Pine Script. Here is the syntax to get array elements in a loop one by one. This code will compute sum for all elements in the array:

sum = 0
for el in arr
    sum += el

You can also iterate both through indices/values at the same time. Here is an example of when we compute sum values with an odd index:

sum_even = 0
for [ind, el]  in arr
    if ind % 2 == 1
        sum_even += el

Here is the full code used in the article:

//@version=5
indicator("For-In")

arr = array.from(1, 5, 2, 4 , 3)

if barstate.islast
    label.new(bar_index, close, str.tostring(arr))

sum = 0
for el in arr
    sum += el

if barstate.islast
    label.new(bar_index + 5, close, str.tostring(sum))

sum_even = 0
for [ind, el]  in arr
    if ind % 2 == 1
        sum_even += el

if barstate.islast
    label.new(bar_index + 10, close, str.tostring(sum_even))

plot(close)


Follow me on TradingView and YouTube.

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

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.