Search code examples
pine-scriptpine-script-v5

high/low from midnight to midnight


I wish to plot the previous days high/low from 0:00 to 0:00 and plot it on the current day. I am finding this a challenge because I dont want to use the standard daily high/low because that is the brokers hours and dont match the high/low that I need when I use UTC-4 New York time.

I can get the high/low for a time range too but not specifically the previous day

I attempted the following code but the plotted high/low repaints over the current day and not show a straight line of the previous day

//@version=5
indicator("Previous Day High and Low 0:00 to 23:55", overlay=true)

// Define the start and end times
startHour = 0
endHour = 23
endMinute = 55

// Determine if the current bar falls within our defined time range
isWithinTimeRange(time) =>
    t = timestamp("UTC", year, month, dayofmonth, hour, minute)
    start_time = timestamp("UTC", year[1], month[1], dayofmonth[1], startHour, 0)
    end_time = timestamp("UTC", year[1], month[1], endHour, endMinute)
    t[1] >= start_time and t[1] <= end_time

// Calculate the high and low for the defined period
var float prevHigh = na
var float prevLow = na

if (isWithinTimeRange(time))
    prevHigh := na(prevHigh) ? high : math.max(prevHigh, high)
    prevLow := na(prevLow) ? low : math.min(prevLow, low)

plot(bar_index[1] == bar_index ? na : prevHigh, title="Previous Day High 0:00 to 23:55", color=color.green, linewidth=2)
plot(bar_index[1] == bar_index ? na : prevLow, title="Previous Day Low 0:00 to 23:55", color=color.red, linewidth=2)

Solution

  • You can use dayofweek() to detect a new day in a desired timezone.

    dayofweek(time, timezone) → series int
    

    Just pass the timezone and then compare its current value with its previous value.

    //@version=5
    indicator("My script", overlay=true)
    
    session_timezone = "GMT-4"
    
    is_new_day_tf = timeframe.change("D")  // This will use exchange's timezone
    
    today_adjusted = dayofweek(time, session_timezone)
    is_new_day = today_adjusted != today_adjusted[1]
    
    plotshape(is_new_day)
    bgcolor(is_new_day_tf ? color.new(color.green, 85) : na)
    

    enter image description here