Loop through a set or all historical bars in Pine Script

I receive quite a lot of questions about how to loop over the bars in Pine Script. Many of the indicators require this kind of calculation you might have these questions yourself as well. If you’re not very familiar with the way Pine Script works you might implement your code in a very inefficient way. In this article, I’ll show you the correct ways to compute something like that in TradingView.

Let’s imagine that I want to compute the sum of volume for the last 100 bars. If you have experience in another programming language you might code something like that:

sum = 0.0
for i = 0 to 100 
    sum += volume[i]

It’s a possible solution that uses a ‘for’ loop and historical operator ‘[]’, but it’s very slow. If you computing something on the fixed window in Tradingview quite often you’ll find a window function that will help you avoid these loops. For example in this case you can use the “sum” function and the code will look much faster:

sum = math.sum(volume, 100)

You can find quite a lot of functions implemented in Pine Script so first before implementing code check existing futures first and write these kinds of loops only if you have no other choice.

If you need to compute something on the entire history of bars you can try to write a loop that computes this:

sum = 0.0
for i = 0 to bar_index 
    sum += volume[i]

But this will unfortunately will give you an error because you can reference so many bars back:

To solve that you need to know how Pine Script works. In reality, Pine Script is a loop in itself. It executes the script for every bar separately. So you can create a self-reference variable that will implement this logic super simple and fast in the calculation:

sum = 0.0
sum := nz(sum[1]) + volume

Pine Script will execute the code and will compute this variable based on the value of the same variable for the previous bar. Even easier you can create a code using ‘var’ keyword:

var sum = 0.0
sum += volume

So as you can see that the standard loops are really not an option for the Pine Script. You should use always check the built-in functions if you need any windows functionality and use the Pine Script execution model to compute any cumulative values for the entire history.


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 *