For loop in TradingView

In this article we discuss how the for loop in TradingView works. For statement allows to execute a number of instructions repeatedly.

To have access to and use the for statement, one should specify the version >= 2 of Pine Script language in the very first line of code, for example:

//@version=3
study("My sma")
my_sma(price, length) => 
    sum = price 
    for i = 1 to length-1 
        sum := sum + price[i] 
    sum / length 

plot(my_sma(close,14))

Variable sum is a mutable variable and a new value can be given to it by an operator := in body of the loop. Also note that we recommend to use a built-in function sma for Moving Average as it calculates faster.

Here’s what the documentation says:

You currently cannot evaluate a variable when setting another one, so the fix is to set it to the string that $PATH evals to at that point. You can just docker run -it imagename:version echo $PATH.

This is a coding tip. It gets a highlight like you’d expect. Pretty sweet right. Also, don’t forget that more can be less, except when it’s clearly more. Thanks!

So there you have it.