Search code examples
pine-scriptpine-script-v5pine-script-v4

Declaring and using variables in same line (Pine Script)


Can you explain line 11 and 12? In these lines, the author is declaring TrendUp and TrendDown variables and instantly using it? On that basis what is the initial value of these variables? Please expain whole lines 11 and 12 (below)
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up.
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Thanks!

study("vbm_Buy or Sell Signal", overlay = true)

Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)


Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))


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],1)
MACD = Trend==1? TrendUp: TrendDown

linecolor = Trend == 1 ? blue : red

plot(MACD, color = linecolor , style = line , linewidth = 2,title = "B/S")

plotshape(cross(close,MACD) and close>MACD , "Up Arrow", shape.triangleup,location.belowbar,blue,0,0)
plotshape(cross(MACD,close) and close<MACD , "Down Arrow", shape.triangledown , location.abovebar, red,0,0)
//plot(Trend==1 and Trend[1]==-1,color = linecolor, style = circles, linewidth = 3,title="Trend")

plotarrow(Trend == 1 and Trend[1] == -1 ? Trend : na, title="Up Entry Arrow", colorup=blue, maxheight=40, minheight=30, transp=0)
plotarrow(Trend == -1 and Trend[1] == 1 ? Trend : na, title="Down Entry Arrow", colordown=red, maxheight=40, minheight=30, transp=0)

Solution

  • On the very first bar, TrendUp[1] and close[1] will be na because there are no historical values yet.

    Therefore, on the very first bar, close[1]>TrendUp[1] will be false and TrendUp will get the value of Up.

    So, initially, TrendUp will be equal to Up.