Tradingview Pinescript work with the := operator
Asked Answered
L

1

3

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
Lynnett answered 20/10, 2018 at 7:52 Comment(0)
S
8

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

Sigismondo answered 20/10, 2018 at 11:40 Comment(4)
Pine Script is very difficult to understand. What is "sum := na(sum[1]) ? sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])" means exactly? Trying to convert it to C# code, thanks.Ariana
@TPG, Which part is confusing you in that statement?Sigismondo
I don't understand what is that := means, I actually want to convert the RSI of Pine Script to C#, but not getting the same value so I guess my conversion is incorrect. Let say if my length is 14, is it it will process 14 candles for the RSI? For the first value it's calculated using SMA, then subsequently using the alpha formula?Ariana
#68213125 This is what I am trying to do and unable to achieve. If you could help it will be very much appreciated. Thanks.Ariana

© 2022 - 2024 — McMap. All rights reserved.