简体   繁体   中英

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

[] 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)

在此处输入图片说明

To answer the part of the question, about the := operator:

It assigns a new value to an already set variable. In any other language you could replace this with a single = .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM