Search code examples
pine-scriptcandlestick-chartcryptocurrencyforexcandlesticks

Can i save variable in IF condation in Pinescript?


How i can save the variables in IF condation and show it later ?

Variables show 0 outside IF condation

I wanna show v1 and v2

Click to show the image

//@version=4
study("Test2", shorttitle = "Test2", overlay=true)

v1 = 0.0
v2 = 0.0


r = high - low
large_candle = rising(r,50)

if large_candle
    v1 := high
    v2 := low
    target = "high = " + tostring(v1) + "\n low = " + tostring(v2)
//  label.new(bar_index, high, target, yloc = yloc.abovebar, color = color.red, style = label.style_arrowdown)

if (high-open) > 0.7 * (high-low) and open > close
    target = "Target 1 = " + tostring(v1) + "\n Target 2 = " + tostring(v2)
    label.new(bar_index, high, target, yloc = yloc.abovebar, color = color.black, style = label.style_arrowdown)

barcolor( large_candle ? color.yellow : na)

Note : I really need to save that variables for another code ( I coded this code to be simple ). any idea ?


Solution

  • I thing this is do the job

    if have better answer that will be good :)

    //@version=4
    study("Test2", shorttitle = "Test2", overlay=true)
    
    v1 = 0.0
    v2 = 0.0
    v1 := nz(v1[1])
    v2 := nz(v2[1])
    
    
    r = high - low
    large_candle = rising(r,50)
    
    if large_candle
        v1 := high
        v2 := low
        target = "high = " + tostring(v1) + "\n low = " + tostring(v2)
        label.new(bar_index, high, target, yloc = yloc.abovebar, color = color.red, style = label.style_arrowdown)
    
    if (high-open) > 0.7 * (high-low) and open > close
        target = "Target 1 = " + tostring(v1) + "\n Target 2 = " + tostring(v2)
        label.new(bar_index, high, target, yloc = yloc.abovebar, color = color.black, style = label.style_arrowdown)
    
    barcolor( large_candle ? color.yellow : na)