Search code examples
pine-scripttrendline

How to plot a stepline at crossings?


I want to plot a simple trend line (I thought it was simple). when the daily price moves from above the previous quarter high and then crosses below the previous quarter low, I want to plot the previous quarter high as a horizontal line, until the moment that the daily price crosses up above the previous quarter high, then I want to plot the previous quarter low as a horizontal line and so on. I want to plot this as a stepline, but all I get are points at the crossings.

example of line to plot

//@version=3 
//By Juros
study(title="previous Quarter high & low", shorttitle="Prev Quar H-L", overlay=true,     precision=8)
PQH = input(true, title="Show Previous Quarter High & Low?")


//Quarterly
prevQuarterHigh = security(tickerid, '3M', high[1], lookahead=true)
prevQuarterLow = security(tickerid, '3M', low[1], lookahead=true)


plot(PQH and prevQuarterHigh ? prevQuarterHigh : na, title="Prev Quarter High", style=stepline, linewidth=1, color=blue,transp=0)
plot(PQH and prevQuarterLow ? prevQuarterLow : na, title="Prev Quarter Low", style=stepline,    linewidth=1, color=blue,transp=0)

Solution

  • It is relatively simple to do, but your code can't guess what you are trying to do; you need the explicit logic implemented in your code.

    and prevQuarterHigh will always be true because prevQuarterHigh is always different than zero, so the plot statements plotted as long as PQH was also true.

    //@version=3 
    //By Juros
    study(title="previous Quarter high & low", shorttitle="Prev Quar H-L", overlay=true,     precision=8)
    PQH = input(true, title="Show Previous Quarter High & Low?")
    
    //Quarterly
    prevQuarterHigh = security(tickerid, '3M', high[1], lookahead=true)
    prevQuarterLow = security(tickerid, '3M', low[1], lookahead=true)
    
    upTrend = false
    upTrend := (not upTrend[1] and crossover(close, prevQuarterHigh)) or (upTrend[1] and not crossunder(close, prevQuarterLow))
    
    plot(PQH and not upTrend ? prevQuarterHigh : na, title="Prev Quarter High", style=linebr, linewidth=1, color=blue,transp=0)
    plot(PQH and upTrend ? prevQuarterLow : na, title="Prev Quarter Low", style=linebr, linewidth=1, color=blue,transp=0)
    

    enter image description here