Emre Ekşioğlu
Emre Ekşioğlu

Reputation: 359

Tradingview Pinescript work with the := operator

I want to understand how to := and sum[1] works. This sum returns me 6093. But sum is 0, also sum[1] = 0 , am I right? How it returns me 6093? I searched the tradingview wiki, but i didnt understand. I want to change this code to another language for example javascript , c#

testfu(x,y)=>
    sum = 0.0
    sum:= 1+ nz(sum[1])
    sum

Upvotes: 3

Views: 8202

Answers (1)

vitruvius
vitruvius

Reputation: 21342

[] in pine-script is called History Referencing Operator. With that, it is possible to refer to the historical values of any variable of a series type (values which the variable had on the previous bars). So, for example, close[1] returns yesterday's close price -which is also a series.

So, if we break your code down (starting from the very first bar):

testfu(x,y)=>
    sum = 0.0           // You set sum to 0.0
    sum:= 1+ nz(sum[1]) // You add 1 to whatever value sum had one bar ago
                        // which is 0, because it's the first bar (no previous value)
    sum                 // Your function returns 1 + 0 = 1 for the very first bar

Now, for the second bar:

testfu(x,y)=>
    sum = 0.0           // You set sum to 0.0
    sum:= 1+ nz(sum[1]) // You add 1 to whatever value sum had one bar ago
                        // which is 1, because it was set to 1 for the first bar
    sum                 // Your function now returns 1 + 1 = 2 for the second bar

And so on.

Have a look at the following code and chart. The chart has 62 bars, and sum starts from 1 and goes all the way up to 62.

//@version=3
study("My Script", overlay=false)

foo() =>
    sum = 0.0
    sum:= 1 + nz(sum[1])
    sum

plot(series=foo(), title="sum", color=red, linewidth=4)

enter image description here

Upvotes: 8

Related Questions