//@version=6
// Trading Ranch — Opening Range Breakout
// Use standard candles, ideally 5 minutes. Times are New York time (DST-aware).
// First confirmed close-cross above and below the completed range each weekday.
// Indicator only: signals are observations, not orders or a backtest.
indicator("Trading Ranch ORB 15", shorttitle="TR ORB 15", overlay=true, max_lines_count=100, max_boxes_count=40, max_labels_count=80)

const int ORB_MINUTES = 15
const string TZ = "America/New_York"
const int OPEN_MINUTES = 9 * 60 + 30
const color HIGH_COLOR = #20BC8D
const color LOW_COLOR = #EC5561
const color MID_COLOR = #E7A742
const color PANEL_COLOR = #17231F

int cutoffHour = input.int(16, "Level / signal cutoff hour (ET)", minval=0, maxval=23, group="Session")
int cutoffMinute = input.int(0, "Level / signal cutoff minute", minval=0, maxval=59, group="Session")
int keepSessions = input.int(10, "Sessions to display", minval=1, maxval=20, group="Display")
bool showBox = input.bool(true, "Shade opening range", group="Display")
bool showMidpoint = input.bool(true, "Show midpoint", group="Display")
bool showSignals = input.bool(true, "Show breakout markers", group="Display")
bool showPanel = input.bool(true, "Show status panel", group="Display")

// Reject synthetic / non-minute charts and intervals that cannot form the exact range.
if barstate.isfirst
    if not chart.is_standard or not timeframe.isminutes
        runtime.error("Trading Ranch ORB requires a standard minute chart. Use standard 5-minute candles.")
    if timeframe.multiplier > ORB_MINUTES or ORB_MINUTES % timeframe.multiplier != 0
        runtime.error("Choose a minute interval that divides the opening range exactly. 5 minutes is recommended.")
    if cutoffHour * 60 + cutoffMinute <= OPEN_MINUTES + ORB_MINUTES
        runtime.error("The cutoff must be later than the opening-range end on the same New York day.")

// Each entry owns all drawings for one session, so history is removed together.
type OrbDrawing
    line highLine = na
    line lowLine = na
    line midpointLine = na
    box rangeBox = na
    label longMarker = na
    label shortMarker = na

removeDrawing(OrbDrawing item) =>
    line.delete(item.highLine)
    line.delete(item.lowLine)
    line.delete(item.midpointLine)
    box.delete(item.rangeBox)
    label.delete(item.longMarker)
    label.delete(item.shortMarker)

var array<OrbDrawing> history = array.new<OrbDrawing>()
var OrbDrawing active = na
var int activeDate = na
var float rangeHigh = na
var float rangeLow = na
var bool startSeen = false
var bool contiguous = false
var bool rangeReady = false
var bool longTriggered = false
var bool shortTriggered = false
var int previousRangeClose = na
var int rangeBars = 0

int nyYear = year(time, TZ)
int nyMonth = month(time, TZ)
int nyDay = dayofmonth(time, TZ)
int dateKey = nyYear * 10000 + nyMonth * 100 + nyDay
int rangeStart = timestamp(TZ, nyYear, nyMonth, nyDay, 9, 30)
int rangeEnd = rangeStart + ORB_MINUTES * 60 * 1000
int cutoff = timestamp(TZ, nyYear, nyMonth, nyDay, cutoffHour, cutoffMinute)
int barMs = timeframe.multiplier * 60 * 1000
int expectedBars = int(ORB_MINUTES / timeframe.multiplier)
int nyWeekday = dayofweek(time, TZ)
bool weekday = nyWeekday >= dayofweek.monday and nyWeekday <= dayofweek.friday
bool inRange = weekday and time >= rangeStart and time < rangeEnd
bool straddlesBoundary = (time < rangeStart and time_close > rangeStart) or (time < rangeEnd and time_close > rangeEnd)
if weekday and straddlesBoundary
    runtime.error("Chart bars must align with 09:30 ET and the opening-range end. Use standard 5-minute candles.")

// Calendar-date reset also works when the chart contains only regular-session bars.
if na(activeDate) or dateKey != activeDate
    activeDate := dateKey
    active := na
    rangeHigh := na
    rangeLow := na
    startSeen := false
    contiguous := false
    rangeReady := false
    longTriggered := false
    shortTriggered := false
    previousRangeClose := na
    rangeBars := 0

// An exact 09:30 bar is required. Missing / partial opening data cannot create signals.
if inRange and time == rangeStart
    startSeen := true
    contiguous := true
    previousRangeClose := rangeStart
    active := OrbDrawing.new()
    active.highLine := line.new(rangeStart, high, rangeStart, high, xloc=xloc.bar_time, color=HIGH_COLOR, width=2)
    active.lowLine := line.new(rangeStart, low, rangeStart, low, xloc=xloc.bar_time, color=LOW_COLOR, width=2)
    if showMidpoint
        active.midpointLine := line.new(rangeStart, hl2, rangeStart, hl2, xloc=xloc.bar_time, color=MID_COLOR, style=line.style_dashed)
    if showBox
        active.rangeBox := box.new(rangeStart, high, rangeStart, low, xloc=xloc.bar_time, border_color=color.new(MID_COLOR, 55), bgcolor=color.new(MID_COLOR, 90))
    array.push(history, active)
    if array.size(history) > keepSessions
        removeDrawing(array.shift(history))

if inRange and startSeen and contiguous
    if time != previousRangeClose or time_close != time + barMs or time_close > rangeEnd
        contiguous := false
    else
        rangeHigh := na(rangeHigh) ? high : math.max(rangeHigh, high)
        rangeLow := na(rangeLow) ? low : math.min(rangeLow, low)
        rangeBars += 1
        previousRangeClose := time_close
        rangeReady := barstate.isconfirmed and time_close == rangeEnd and rangeBars == expectedBars
        int rightEdge = rangeReady ? cutoff : math.min(time_close, rangeEnd)
        float midpoint = (rangeHigh + rangeLow) / 2.0
        line.set_xy1(active.highLine, rangeStart, rangeHigh)
        line.set_xy2(active.highLine, rightEdge, rangeHigh)
        line.set_xy1(active.lowLine, rangeStart, rangeLow)
        line.set_xy2(active.lowLine, rightEdge, rangeLow)
        if showMidpoint
            line.set_xy1(active.midpointLine, rangeStart, midpoint)
            line.set_xy2(active.midpointLine, rightEdge, midpoint)
        if showBox
            box.set_top(active.rangeBox, rangeHigh)
            box.set_bottom(active.rangeBox, rangeLow)
            box.set_right(active.rangeBox, math.min(time_close, rangeEnd))

// Remove a partial range instead of displaying it as a completed opening range.
if not na(active) and (not contiguous or (time >= rangeEnd and not rangeReady))
    removeDrawing(array.pop(history))
    active := na
    rangeHigh := na
    rangeLow := na

// The breakout candle must OPEN after the range and CLOSE at/before the cutoff.
// A wick is insufficient. At most one long AND one short can trigger per session.
bool signalWindow = weekday and rangeReady and time >= rangeEnd and time < cutoff and time_close <= cutoff
bool longBreak = signalWindow and barstate.isconfirmed and not longTriggered and close > rangeHigh and close[1] <= rangeHigh
bool shortBreak = signalWindow and barstate.isconfirmed and not shortTriggered and close < rangeLow and close[1] >= rangeLow
if longBreak
    longTriggered := true
    if showSignals
        active.longMarker := label.new(time, low, "15m ORB\nLONG ▲", xloc=xloc.bar_time, yloc=yloc.belowbar, color=HIGH_COLOR, style=label.style_label_up, textcolor=color.white, size=size.tiny)
if shortBreak
    shortTriggered := true
    if showSignals
        active.shortMarker := label.new(time, high, "15m ORB\nSHORT ▼", xloc=xloc.bar_time, yloc=yloc.abovebar, color=LOW_COLOR, style=label.style_label_down, textcolor=color.white, size=size.tiny)

alertcondition(longBreak, "Trading Ranch ORB 15 — Long breakout", "Trading Ranch 15-minute ORB: first confirmed close-cross ABOVE the opening range. {{ticker}} ({{interval}}), close {{close}}.")
alertcondition(shortBreak, "Trading Ranch ORB 15 — Short breakout", "Trading Ranch 15-minute ORB: first confirmed close-cross BELOW the opening range. {{ticker}} ({{interval}}), close {{close}}.")

var table panel = table.new(position.top_right, 2, 6, bgcolor=PANEL_COLOR, frame_color=color.new(MID_COLOR, 35), frame_width=1)
if barstate.isfirst
    table.merge_cells(panel, 0, 0, 1, 0)
if barstate.islast and showPanel
    int asOf = barstate.isrealtime ? timenow : time_close
    string status = not weekday ? "WEEKEND" : asOf < rangeStart ? "WAITING" : asOf >= cutoff ? "CLOSED" : rangeReady ? "READY" : inRange and startSeen and contiguous ? "BUILDING" : "INCOMPLETE DATA"
    color statusColor = rangeReady ? HIGH_COLOR : MID_COLOR
    table.cell(panel, 0, 0, "TRADING RANCH  •  15m ORB", text_color=MID_COLOR, text_size=size.small, bgcolor=PANEL_COLOR)
    table.cell(panel, 0, 1, "09:30–09:45 ET", text_color=color.white, text_size=size.small)
    table.cell(panel, 1, 1, status, text_color=statusColor, text_size=size.small)
    table.cell(panel, 0, 2, "HIGH", text_color=HIGH_COLOR, text_size=size.small)
    table.cell(panel, 1, 2, na(rangeHigh) ? "—" : str.tostring(rangeHigh, format.mintick), text_color=color.white, text_size=size.small)
    table.cell(panel, 0, 3, "LOW", text_color=LOW_COLOR, text_size=size.small)
    table.cell(panel, 1, 3, na(rangeLow) ? "—" : str.tostring(rangeLow, format.mintick), text_color=color.white, text_size=size.small)
    table.cell(panel, 0, 4, "RANGE", text_color=MID_COLOR, text_size=size.small)
    table.cell(panel, 1, 4, na(rangeHigh) ? "—" : str.tostring(rangeHigh - rangeLow, format.mintick), text_color=color.white, text_size=size.small)
    table.cell(panel, 0, 5, "FIRST / DIRECTION", text_color=color.silver, text_size=size.tiny)
    table.cell(panel, 1, 5, "▲ " + (longTriggered ? "✓" : "—") + "   ▼ " + (shortTriggered ? "✓" : "—"), text_color=color.white, text_size=size.small)
