Tradingview Pinescript 使用 := 运算符

Tradingview Pinescript work with the := operator

我想了解 := 和 sum[1] 的工作原理。这个sumreturns我6093。但是sum是0,也是sum[1] = 0,我说的对吗? returns我怎么6093了?我搜索了 tradingview wiki,但我不明白。我想将此代码更改为另一种语言,例如 javascript ,c#

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

[] 在 pine-script 中称为 History Referencing Operator。这样,就可以参考系列类型的任何变量的历史值(变量在之前的柱上具有的值)。因此,例如,close[1] returns 昨天的收盘价 - 这也是一个系列。

因此,如果我们分解您的代码(从第一栏开始):

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

现在,对于第二个柱状图:

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

以此类推

看看下面的代码和图表。该图表有 62 条柱线 ,并且 sum1 开始一直上升到 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)