How do you do a loop in Pine Script? I’m glad you asked. Loops are powerful. Very powerful. Loops can be used to count, to add things, to average things, to find things, and for a lot of other useful math calculations.
Many of Pine Script’s built in functions use for loops. Writing them isn’t hard syntactically, but Pine has some weird quirks with loops that, unless you know what’s going on in their compiler, it can be hard to debug issues.
What is a loop?
A loop is a chunk of code that want the computer to run again and again and again. It’s something you want it to run multiple times for the purpose of some kind of calculation or display of information.
Loops in Pine Script are “for loops”. The word “for” is a special programming word that is used like this context: “for each apple in the basket: cut the apple in half”. No, Pine Script is not that Englishy, but you get the idea.
Examples of For Loops in Pine Script
The most common example is the simple moving average or sma. The math behind the SMA is you loop over the last N bars, add up the series value you want to average from each one, then divide by N.
In pseudo code, it looks something like this:
total = 0 n = 7 for each of the last n bars total = total + close sma = total / n
Does that make sense? See how that works?
This is a very simple example, but many complex programs are and can be built from for loops.
How to write a for loop in Pine Script
Ready to get your hands dirty? Good, let’s do this.
We’re going to write our own SMA function.
First you need to prepare a couple things. You need to know what you’re calculating. For an SMA, we’re adding up the sum of a certain number of bars.
So we need to know the number of bars (let’s call this N), and we need a place to store the sun as we go.
float total = 0 int n = 30
Great, so far so good.
Next we’ll do the loop. Each for loop defines the specific code you want to run multiple times. And that code is “scoped” or lives in its own container, if you will. Because of this we write the n
and total
variables first, outside of the loops scope container, so that we can access them after the loop is done. The loop however can access these variables and even modify them. (And they’ll stay modified after the loop is over.)
float total = 0 int n = 30 SMA = for i = 0 to n-1 total := total + close[i] sma = total / n
That’s it! The SMA
variable will hold the value of the Smoothed Moving Average over the last 30 bars (including the current candle). If you’ve programmed in other languages before, you probably noticed this is weird…yes, in PIne Script, for
loops return a value. The for
loop returns the last value that was calculated. If you break
early from the loop, it behaves the same way.
If you’re new to programming, you might be asking why we go from 0 to n-1
instead of 1 to n
. Well…computers count from 0. So, to do 30 iterations, we have to go from 0 to 29 instead of 1 to 30. If did do 1 to n
, in this case, our SMA would NOT include the value of the current candle, since our first call would use close[1]
(one candle before the previous) instead of close[0]
(the current candle).
Loops in Pine Script are great, you can do so much and make some very useful functions. Built in functions like valuewhen
, barssince
, and pivothigh
use loops, just to name a few. But there are some things to look out for when writing your own Pine Script loops.
Ending A Loop Early
If you’re using a for loop to look for something, (say, if the current price is higher than any of the 30 previous highs) it would make sense to stop looking if you found your answer early. Pine Script in TradingView is very computationally expensive and the more work your code does, the longer your script takes to run. And if it takes too long, TradingView will give you an error. So you have to be mindful of your script’s performance.
One great way to help performance when writing loops is to end early. You do this using the keyword break
in your loop at the point you want it to end.
For example…
int n = 30 SMA = for i = 0 to n-1 if i == 15 break
Ok, yes, this loop doesn’t actually do or calculate anything, but it does end halfway through. It works by checking if i
is equal to 15
(half of n
), and if so, we say break
. This means “break the loop”. AKA, stop the loop and continue with the rest of the code. This can be very useful depending on what you’re trying to do and varies based on the logic in your loop.
Need help? Reach out to us in Discord. Want to hire us? Reach out in Discord as well 🙂