Search code examples
pine-scripttradingindicator

interpret tradingview pine-script self-referencing variable value


I need someone interpret or convert this line of pine-script code to any other language please:

TrendUp = close[1] > TrendUp[1] ? max(100, TrendUp[1]) : 100

Actually the weird part is TrendUp[1]. how it is evaluated and what is its value?

The full code is:

Up = hl2 - atr(1)
Dn = hl2 + atr(1)

TrendUp = close[1] > TrendUp[1] ? max(Up, TrendUp[1]) : Up
TrendDown = close[1] < TrendDown[1] ? min(Dn, TrendDown[1]) : Dn
Trend = close > TrendDown[1] ? 1 : close < TrendUp[1] ? -1 : nz(Trend[1], 0)

plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=lime, maxheight=1000, minheight=50, transp=85)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=1000, minheight=50, transp=85)  

And the result on the chart are those long vertical red/green arrows:

vdub indicator signal provider

thanks in advance.


Solution

  • [] in pinescript is called History Reference Operator. You can use this operator to access historical values of a variable.

    For example, close[3] will return whatever the close price was three bars ago. Note that the history reference operator will return n/a for the very first bar of the chart.

    After reading the link I provided, to understand the below code I suggest you plot some of those variables.

    TrendUp = close[1] > TrendUp[1] ? max(Up, TrendUp[1]) : Up

    You should have a look at what values close[1], TrendUp[1] and Up have. Simplest way to do is create a new indicator with overlay=false and remove all plot statements. Then add the below code to the very end of the script.

    plot(series=TrendUp, color=green)
    plot(series=TrendUp[1], color=red)
    plot(series=close[1], color=orange)
    plot(series=Up, color=white)
    

    Below image is a screenshot from the very first bar of the chart. As I said, TrendUp[1] and close[1] have the value n/a. So, close[1] > TrendUp[1] evaluates to false and UpTrend gets the value of Up, which is 85.1 at that time.

    enter image description here

    So, this is how you start. Then hover your mouse over the next bars and keep looking at the values. You can also plot the close price to get a better understanding.

    Remember, TrendUp[1] refers to the value of TrendUp one bar ago. So, there is a one bar delay between the red and green plots.