We have updated Pine Script. The latest version contains the long-awaited features: loops and mutable variables. Besides, we released multiple improvements and bug fixes for strategies.
As you know, Pine Script is a series-oriented scripting language, where most of goals are achieved by converting series values with help of built-in functions. Yet we received a lot of feedback describing disadvantages of such approach and showing high demand on statements for loops.
Loop and mutable variables syntax is demonstrated below:
//@version=2 study("Simple Moving Average") len = input(9) sum = 0 for i = 0 to len-1 sum := sum + close[i] plot(sum/len)
‘sum’ is a mutable variable and a new value can be given to it by an operator ‘:=’ in body of the loop.
Please note that we recommend to use a built-in function ‘sma’ for Moving Average as it calculates faster.
It’s just a very simple example, the loop doesn’t even return a value here (a = for …). You can use ‘break’ and ‘continue’ in loop body and set a step size for the counter (for … by 2). To learn more about loops and mutable variable, check our Tutorial.