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

How to within a specific time; plot the highest high and the lowest low in Pine script


I'm currently stuck in implementing Specific time while plotting the highest high and the lowest low of candle within a session say 0500 - 0800. I already was successfully with the 24 hour pivotal previous highest high and previous lowest low.

study("Color highest bar", overlay = true)

newSession = change(time('D'))

[lo,hi] = security(syminfo.tickerid, 'D', [low,high], lookahead=barmerge.lookahead_on)

isToday = (year == year(timenow)) and (month == month(timenow)) and (dayofmonth == dayofmonth(timenow))
isHist  = not isToday

lobar   = lo == low
hibar   = hi == high

bgcolor(newSession       ? color.white  : na, transp = 75)
bgcolor(lobar and isHist ? color.red    : na, transp = 75)
bgcolor(hibar and isHist ? color.green  : na, transp = 75)


Solution

  • Use input.session to get the session time and then use the time() function to figure out if you are in that session.

    Compare current high/low price with the ones you store in memory while you are in the session and update them if necessary.

    //@version=5
    indicator('HHLL', overlay=true)
    
    session_time = input.session("0500-0800", "Session")
    
    is_in_session = time(timeframe.period, session_time)
    is_new_session = not is_in_session[1] and is_in_session
    
    var float hh = na
    var float ll = na
    
    if (is_new_session)
        hh := high
        ll := low
    else if (is_in_session)
        if (high > hh)
            hh := high
        
        if (low < ll)
            ll := low
    
    plot(is_in_session ? hh : na, "HH", color.green, 1, plot.style_circles)
    plot(is_in_session ? ll : na, "LL", color.red, 1, plot.style_circles)
    

    enter image description here