本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Bitpunk
//@version=6
indicator("Session Drive - Opening Range Breakout (ORB) [bitpunk]", shorttitle="bitpunk.session-drive", overlay=true, max_boxes_count=16)
// Independent public implementation of a fixed New York opening-range breakout.
// Fixed US cash-open identity; chart display timezone does not change it.
int confirmationCloses = input.int(5, "Confirmation Closes", minval=1, maxval=6, tooltip="Five (default) requires five adjacent completed 1-minute source closes outside the same opening edge. Choose 1–6 closes: lower counts accept earlier; higher counts require longer persistence. The chart timeframe changes only the display. Only completed 1-minute source candles count; a closed source event can appear inside a developing 3m/5m chart candle.", display=display.none)
// Display and theme
bool enableSignals = input.bool(true, "Enable Signals", group="Signals", tooltip="Enable entry markers and signal alerts. Disabling keeps structure, setup state and context readings active. Recreate existing alerts after changing this setting.", display=display.none)
bool showStructure = input.bool(true, "Structure", group="Display", tooltip="Show the current setup and its exact price boundaries. Hiding it does not change entries or alerts.", display=display.none)
int historyCount = input.int(6, "Previous Structures", minval=0, maxval=12, group="Display", tooltip="Number of completed boxes to retain quietly. Zero keeps only the current opportunity. This setting does not limit historical entry marks.", display=display.none)
string panelChoice = input.string("bottom", "Status Panel", options=["none", "bottom", "top", "bottom-left", "top-left"], group="Display", tooltip="Shows the latest confirmed setup state. None hides only the panel.", display=display.none)
string panelSize = input.string("small", "Panel Size", options=["small", "medium", "large"], group="Display", tooltip="Shared card scale: small, medium or large. Bottom and top use the right corners; left variants use the left corners.", display=display.none)
string structureEffects = input.string("Enhanced", "Structure Effects", options=["Normal", "Enhanced"], group="Display", tooltip="Exact 2px boundaries stay clear in both modes. Enhanced adds a native edge-to-center glass gradient. Dotted outlines develop; solid outlines are locked. Appearance never changes entries.", display=display.none)
string signalEffects = input.string("Enhanced", "Signal Effects", options=["Normal", "Enhanced"], group="Display", tooltip="Normal uses compact ▲/▼ entry labels. Enhanced adds larger labels and a pin with a soft glow at the confirmed close. Appearance does not change signals.", display=display.none)
color bullColor = input.color(color.rgb(0, 194, 255), "Bull", inline="theme", group="Theme Colors", display=display.none, tooltip="Long-side colors. All directional effects derive from Bull and Bear and adapt to the chart background.")
color bearColor = input.color(color.rgb(255, 56, 100), "Bear", inline="theme", group="Theme Colors", display=display.none, tooltip="Short-side colors. All directional effects derive from Bull and Bear and adapt to the chart background.")
// Public visual conventions: Pullback Reclaim and script-visual-style.md.
f_panel_position(string choice) =>
switch choice
"top" => position.top_right
"top-left" => position.top_left
"bottom-left" => position.bottom_left
=> position.bottom_right
f_dim(color source, float strength) =>
color.from_gradient(strength, 0, 1, chart.bg_color, source)
f_ink(color source) =>
float luminance = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
luminance > 128 ? color.from_gradient(0.35, 0, 1, source, chart.fg_color) : source
f_signal(color source) =>
float luminance = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
luminance > 128 ? color.from_gradient(0.50, 0, 1, source, chart.fg_color) : color.from_gradient(0.78, 0, 1, chart.bg_color, source)
f_tf() =>
float seconds = timeframe.isticks ? na : timeframe.in_seconds()
seconds < 60 ? str.tostring(seconds) + "s" : seconds < 3600 ? str.tostring(seconds / 60) + "m" : seconds < 86400 ? str.tostring(seconds / 3600) + "h" : timeframe.period == "D" ? "1D" : timeframe.period == "W" ? "1W" : timeframe.period == "M" ? "1M" : timeframe.period
var color neutralColor = chart.fg_color
var color bullInk = f_ink(bullColor)
var color bearInk = f_ink(bearColor)
var color bullSignal = f_signal(bullColor)
var color bearSignal = f_signal(bearColor)
f_archive(box drawing, int side, array<box> history, int keep) =>
if not na(drawing)
color accent = side > 0 ? bullColor : side < 0 ? bearColor : neutralColor
box.set_bgcolor(drawing, color.new(accent, 98))
box.set_border_color(drawing, color.new(f_ink(accent), 88))
array.push(history, drawing)
if array.size(history) > keep
box.delete(array.shift(history))
0
// One market clock. Host timeframe is used only for support and projection.
string clock = "America/New_York"
int openingMinutes = 15
bool cashInstrument = syminfo.type == "stock" or syminfo.type == "fund"
bool supported = chart.is_standard and timeframe.isminutes and (timeframe.multiplier == 1 or timeframe.multiplier == 3 or timeframe.multiplier == 5) and cashInstrument and syminfo.timezone == clock
// Primitive snapshots keep all histories and lifecycle decisions in the 1m context.
type SourceFrame
int day
int at
int closedAt
float upper
float lower
bool finalized
bool valid
bool ready
bool consumed
int pending
int streak
int statusCode
int eventAt
int eventClosedAt
int eventSide
float eventPrice
f_source() =>
int dayKey = year(time, clock) * 10000 + month(time, clock) * 100 + dayofmonth(time, clock)
int openAt = timestamp(clock, year(time, clock), month(time, clock), dayofmonth(time, clock), 9, 30)
int rangeEnd = openAt + openingMinutes * 60000
int cutoff = timestamp(clock, year(time, clock), month(time, clock), dayofmonth(time, clock), 11, 30)
int durationMs = 60000
bool regular = session.ismarket and dayofweek(time, clock) >= dayofweek.monday and dayofweek(time, clock) <= dayofweek.friday
bool opening = regular and time >= openAt and time < rangeEnd
bool pricesReady = not na(high) and not na(low) and not na(close) and high >= low and close >= low and close <= high
var int currentDay = na
var int expectedTime = na
var int previousClose = na
var float rangeHigh = na
var float rangeLow = na
var bool complete = true
var bool rangeValid = false
var bool finalized = false
var bool ready = false
var bool consumed = false
var int pendingSide = 0
var int streak = 0
var int statusCode = 0
var int eventAt = na
var int eventClosedAt = na
var int eventSide = 0
var float eventPrice = na
if na(currentDay) or dayKey != currentDay
currentDay := dayKey
expectedTime := openAt
previousClose := na
rangeHigh := na
rangeLow := na
complete := true
rangeValid := false
finalized := false
ready := false
consumed := false
pendingSide := 0
streak := 0
statusCode := 0
eventAt := na
eventClosedAt := na
eventSide := 0
eventPrice := na
if opening
bool aligned = time == expectedTime and time_close == time + durationMs and time_close <= rangeEnd
complete := complete and aligned and not finalized and pricesReady
expectedTime := time_close
previousClose := time_close
rangeHigh := na(rangeHigh) ? high : math.max(rangeHigh, high)
rangeLow := na(rangeLow) ? low : math.min(rangeLow, low)
statusCode := 1
if time_close == rangeEnd
finalized := true
bool valid = complete and expectedTime == rangeEnd and rangeHigh > rangeLow
rangeValid := valid
ready := valid
statusCode := valid ? 3 : 2
else if time >= rangeEnd and time < cutoff
if not finalized
complete := false
statusCode := 2
else if ready and not consumed and regular
if time != previousClose or time_close != time + durationMs
pendingSide := 0
streak := 0
previousClose := time_close
if time_close < cutoff and time_close == time + durationMs and pricesReady
int side = close > rangeHigh ? 1 : close < rangeLow ? -1 : 0
streak := side == 0 ? 0 : side == pendingSide ? streak + 1 : 1
pendingSide := side
statusCode := side == 0 ? 8 : 9
if streak >= confirmationCloses
consumed := true
eventAt := time
eventClosedAt := time_close
eventSide := side
eventPrice := close
statusCode := side > 0 ? 10 : 11
else
pendingSide := 0
streak := 0
if time_close >= cutoff
ready := false
statusCode := 12
else
statusCode := 13
else if time >= cutoff
ready := false
if not consumed
statusCode := 12
SourceFrame.new(currentDay, time, time_close, rangeHigh, rangeLow, finalized, rangeValid, ready, consumed, pendingSide, streak, statusCode, eventAt, eventClosedAt, eventSide, eventPrice)
// Fixed source history, including history before the host-chart visible prefix.
array<SourceFrame> samples = array.new<SourceFrame>()
if supported
samples := request.security_lower_tf(ticker.modify(syminfo.tickerid, session=session.regular), "1", f_source(), ignore_invalid_timeframe=true, calc_bars_count=100000)
// Immutable snapshots: preserve the latest confirmed reference across host rollback.
varip SourceFrame view = na
if array.size(samples) > 0
for i = 0 to array.size(samples) - 1
SourceFrame frame = array.get(samples, i)
// No request-context barstate.isconfirmed: reject a developing 1m close.
bool closed = frame.closedAt <= time_close and (not barstate.isrealtime or frame.closedAt <= timenow)
if closed and (na(view) or frame.closedAt >= view.closedAt)
view := frame
int dayKey = year(time, clock) * 10000 + month(time, clock) * 100 + dayofmonth(time, clock)
int openAt = timestamp(clock, year(time, clock), month(time, clock), dayofmonth(time, clock), 9, 30)
int rangeEnd = openAt + openingMinutes * 60000
int cutoff = timestamp(clock, year(time, clock), month(time, clock), dayofmonth(time, clock), 11, 30)
bool sameDay = supported and not na(view) and view.day == dayKey
bool opening = time < rangeEnd and time_close > openAt
bool rangeValid = sameDay and view.valid
bool finalized = sameDay and view.finalized
bool ready = sameDay and view.ready
bool consumed = sameDay and view.consumed
float rangeHigh = sameDay ? view.upper : na
float rangeLow = sameDay ? view.lower : na
int pendingSide = sameDay ? view.pending : 0
int streak = sameDay ? view.streak : 0
bool eventHere = sameDay and not na(view.eventAt) and view.eventAt >= time and view.eventAt < time_close
bool longSignal = eventHere and view.eventSide == 1
bool shortSignal = eventHere and view.eventSide == -1
float signalPrice = eventHere ? view.eventPrice : na
int statusCode = sameDay ? view.statusCode : 0
string sourceStatus = switch statusCode
1 => "Building 15m opening range"
2 => "Opening 1m data incomplete"
3 => "Ready · wait for 1m close"
8 => "Ready · inside range"
9 => (pendingSide > 0 ? "Long" : "Short") + " acceptance · " + str.tostring(streak) + "/" + str.tostring(confirmationCloses)
10 => "Long confirmed · " + str.format_time(view.eventClosedAt, "HH:mm", clock)
11 => "Short confirmed · " + str.format_time(view.eventClosedAt, "HH:mm", clock)
12 => "Entry window closed"
13 => "Entry 1m data incomplete"
=> "Waiting for open"
// Missing source is measured in physical minutes, never in host-chart updates.
int observedAt = barstate.isrealtime ? timenow : time_close
bool sourceStale = sameDay and observedAt > view.closedAt + 60000 and observedAt >= openAt and observedAt < cutoff
string panelStatus = not supported ? "US stock / ETF · 1m, 3m, 5m" : not sameDay ? "Waiting for 1m source" : sourceStale ? "Waiting for closed 1m data" : sourceStatus
// Host objects only visualize the canonical snapshot; they never own the setup.
var box activeBox = na
var array<box> history = array.new<box>()
var int drawingDay = na
var bool drawingValid = false
if sameDay
if na(drawingDay) or drawingDay != dayKey
if not na(activeBox)
if drawingValid
f_archive(activeBox, 0, history, historyCount)
else
box.delete(activeBox)
activeBox := na
drawingDay := dayKey
drawingValid := rangeValid
bool developing = view.at >= openAt and view.at < rangeEnd and not finalized and view.statusCode == 1
bool active = developing or rangeValid and ready and not consumed or eventHere
if showStructure and active and not na(rangeHigh) and not na(rangeLow)
if na(activeBox)
activeBox := box.new(openAt, rangeHigh, view.closedAt, rangeLow, xloc=xloc.bar_time, border_color=color.new(neutralColor, structureEffects == "Enhanced" ? 76 : 84), bgcolor=color.new(neutralColor, 100), border_style=line.style_dotted)
box.set_top(activeBox, rangeHigh)
box.set_bottom(activeBox, rangeLow)
box.set_right(activeBox, eventHere ? view.eventClosedAt : math.min(view.closedAt, cutoff))
box.set_border_style(activeBox, finalized ? line.style_solid : line.style_dotted)
if not na(activeBox) and (consumed or view.closedAt >= cutoff)
f_archive(activeBox, consumed ? view.eventSide : 0, history, historyCount)
activeBox := na
else if not na(activeBox) and not active
box.delete(activeBox)
activeBox := na
bool visible = showStructure and supported and sameDay and finalized and (ready and not consumed or longSignal or shortSignal)
float upper = visible ? rangeHigh : na
float lower = visible ? rangeLow : na
upperPlot = plot(upper, "Opening High", color.new(bullInk, pendingSide == 1 ? 8 : structureEffects == "Enhanced" ? 32 : 52), 2, plot.style_linebr, display=display.pane)
lowerPlot = plot(lower, "Opening Low", color.new(bearInk, pendingSide == -1 ? 8 : structureEffects == "Enhanced" ? 32 : 52), 2, plot.style_linebr, display=display.pane)
float midpoint = (upper + lower) / 2
centerMask = plot(midpoint, "Range Glass Center", color=na, display=display.none, editable=false)
color upperGlass = color.new(bullInk, structureEffects == "Enhanced" ? (pendingSide == 1 ? 87 : 94) : 98)
color lowerGlass = color.new(bearInk, structureEffects == "Enhanced" ? (pendingSide == -1 ? 87 : 94) : 98)
fill(upperPlot, centerMask, upper, midpoint, upperGlass, color.new(bullInk, 100), title="Upper Range Glass", fillgaps=false)
fill(centerMask, lowerPlot, midpoint, lower, color.new(bearInk, 100), lowerGlass, title="Lower Range Glass", fillgaps=false)
plot(sameDay and rangeValid ? rangeHigh : na, "Exact Opening High", display=display.data_window)
plot(sameDay and rangeValid ? rangeLow : na, "Exact Opening Low", display=display.data_window)
plot(supported ? openingMinutes : na, "Opening Minutes", display=display.data_window)
// Confirmed audit facts remain available with all structure effects hidden.
plot(sameDay ? streak : na, "Acceptance Closes", display=display.data_window)
int setupPhase = longSignal or shortSignal ? 5 : sameDay and ready and not consumed ? (streak > 0 ? 3 : 2) : sameDay and opening and not finalized ? 1 : 0
plot(setupPhase, "Setup Phase", display=display.data_window)
plot(sameDay ? view.closedAt / 1000 : na, "Source Close Time", display=display.data_window)
plot(enableSignals and (eventHere) ? view.eventClosedAt / 1000 : na, "Entry Time", display=display.data_window)
// Fixed sizes keep plotshape parameters const; every display switch is cosmetic.
bool enhancedSignal = signalEffects == "Enhanced"
color entryAccent = longSignal ? bullColor : bearColor
color entryInk = longSignal ? bullSignal : bearSignal
plotshape(enableSignals and (enhancedSignal and (longSignal or shortSignal)) ? signalPrice : na, "Entry Glow", shape.circle, location.absolute, color.new(entryAccent, 80), size=size.large, display=display.pane)
plotshape(enableSignals and (enhancedSignal and (longSignal or shortSignal)) ? signalPrice : na, "Entry Close Pin", shape.circle, location.absolute, entryInk, size=size.tiny, display=display.pane)
plotshape(enableSignals and (enhancedSignal and longSignal), "Long Entry", shape.labelup, location.belowbar, bullSignal, text="▲", textcolor=color.white, size=size.small, display=display.pane)
plotshape(enableSignals and (not enhancedSignal and longSignal), "Long Normal", shape.labelup, location.belowbar, bullSignal, text="▲", textcolor=color.white, size=size.tiny, display=display.pane)
plotshape(enableSignals and (enhancedSignal and shortSignal), "Short Entry", shape.labeldown, location.abovebar, bearSignal, text="▼", textcolor=color.white, size=size.small, display=display.pane)
plotshape(enableSignals and (not enhancedSignal and shortSignal), "Short Normal", shape.labeldown, location.abovebar, bearSignal, text="▼", textcolor=color.white, size=size.tiny, display=display.pane)
plot(enableSignals and (longSignal) ? signalPrice : na, "Long Entry Close", display=display.data_window)
plot(enableSignals and (shortSignal) ? signalPrice : na, "Short Entry Close", display=display.data_window)
// A new alert instance must not catch up an earlier event inside a larger host.
varip int liveSince = na
if barstate.isrealtime and na(liveSince)
liveSince := timenow
bool liveEvent = not barstate.isrealtime or (eventHere and not na(liveSince) and view.eventClosedAt >= liveSince)
// Select a directional condition OR Any alert() function call to avoid duplicates.
alertcondition(enableSignals and (longSignal and liveEvent), "Long Entry", '1m ▲ LONG @{{plot("Long Entry Close")}}')
alertcondition(enableSignals and (shortSignal and liveEvent), "Short Entry", '1m ▼ SHORT @{{plot("Short Entry Close")}}')
// A source event may confirm inside a developing 3m/5m host candle.
varip int lastAlertAt = na
if enableSignals and barstate.isrealtime and (longSignal or shortSignal) and liveEvent and (na(lastAlertAt) or view.eventClosedAt != lastAlertAt)
alert("1m" + (longSignal ? " ▲ LONG @" : " ▼ SHORT @") + str.tostring(signalPrice, format.mintick) + " · NY " + str.format_time(view.eventClosedAt, "HH:mm", clock), alert.freq_all)
lastAlertAt := view.eventClosedAt
// The panel reports confirmed state, not an ongoing trade or a probability.
var table panel = na
if barstate.islast
if panelChoice == "none"
if not na(panel)
table.delete(panel)
panel := na
else
if na(panel)
panel := table.new(position.bottom_right, 1, 2, bgcolor=f_dim(chart.fg_color, 0.025), frame_color=f_dim(chart.fg_color, 0.12), frame_width=1, border_width=0)
table.set_position(panel, f_panel_position(panelChoice))
string panelTextSize = panelSize == "small" ? size.tiny : panelSize == "large" ? size.normal : size.small
string panelHeadingSize = panelSize == "small" ? size.small : panelSize == "large" ? size.large : size.normal
color panelAccent = str.startswith(panelStatus, "Long") ? bullColor : str.startswith(panelStatus, "Short") ? bearColor : neutralColor
table.cell(panel, 0, 0, " OPENING RANGE · " + str.tostring(openingMinutes) + "m · 1m DATA / " + f_tf() + " ", bgcolor=f_dim(panelAccent, 0.06), text_color=f_ink(panelAccent), text_size=panelHeadingSize, text_halign=text.align_left)
table.cell(panel, 0, 1, " " + panelStatus + " ", text_color=str.startswith(panelStatus, "Long") or str.startswith(panelStatus, "Short") ? f_ink(panelAccent) : f_dim(chart.fg_color, 0.86), text_size=panelTextSize, text_halign=text.align_left)