本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// =============================================================================
// Opening Range Breakout Stats
// -----------------------------------------------------------------------------
// Draws a user-defined opening range every day and tabulates, on the chart's
// loaded history, what actually happened after it: which side broke, how often
// the first break closed back inside, how often it was still valid at the end
// of the day, and how far it extended.
//
// - Close-based events on confirmed bars only: nothing repaints.
// - Every rate is shown with its sample size and a Wilson 95% margin.
// - The numbers describe the loaded history of THIS chart. They are base rates,
// not signals and not a forecast.
// =============================================================================
indicator("Opening Range Breakout Stats", shorttitle = "ORB Stats", overlay = true, max_boxes_count = 100)
// ─── Inputs ──────────────────────────────────────────────────────────────────
string GRP_R = "Range window"
string GRP_S = "Statistics"
string GRP_V = "Display"
string presetIn = input.string("New York first 30 min", "Preset", options = ["Asia range", "London first hour", "New York first 30 min", "Custom"], group = GRP_R, tooltip = "Asia range: 00:00-08:00 London time. London first hour: 08:00-09:00 London time. New York first 30 min: 09:30-10:00 New York time. All presets follow daylight saving time. Use a chart timeframe at or below the window length.")
string custSess = input.session("0930-1000", "Custom window", group = GRP_R, tooltip = "Used only when Preset = Custom.")
string custTz = input.string("America/New_York", "Custom timezone", options = ["America/New_York", "America/Chicago", "Europe/London", "Europe/Paris", "Asia/Tokyo", "Asia/Singapore", "Australia/Sydney", "UTC"], group = GRP_R)
int horizonMin = input.int(30, "Failed-break horizon (minutes)", minval = 1, group = GRP_S, tooltip = "A first break counts as failed when a bar closes back inside the range within this many minutes after the break bar.")
bool showBoxes = input.bool(true, "Draw range boxes", group = GRP_V)
bool showLevels = input.bool(true, "Extend range high / low", group = GRP_V)
bool showMarks = input.bool(true, "Mark first break and failed break", group = GRP_V)
bool showDash = input.bool(true, "Show dashboard", group = GRP_V)
string dashPos = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GRP_V)
string dashSize = input.string("Normal", "Dashboard text size", options = ["Small", "Normal", "Large"], group = GRP_V)
// ─── Constants ───────────────────────────────────────────────────────────────
color C_BULL = #26A69A
color C_BEAR = #EF5350
color C_WARN = #FFA726
color C_NEUT = #787B86
color C_TEXT = #FFFFFF
color C_LBL = #B2B5BE
color C_HEAD = #2962FF
color C_BG = #131722
color C_CHIP = #2A2E39
// ─── Helpers ─────────────────────────────────────────────────────────────────
f_pos(string _p) =>
_p == "Top right" ? position.top_right : _p == "Bottom right" ? position.bottom_right : _p == "Top left" ? position.top_left : position.bottom_left
f_size(string _s) =>
_s == "Small" ? size.small : _s == "Large" ? size.large : size.normal
f_pct(int _k, int _n) =>
string s = _n > 0 ? str.tostring(100.0 * _k / _n, "0") + "%" : "-"
s
// Wilson 95% score interval: returns [centre, half-width] as fractions.
f_wilson(int _k, int _n) =>
float ctr = na
float half = na
if _n > 0
float z = 1.96
float p = _k / float(_n)
float den = 1.0 + z * z / _n
ctr := (p + z * z / (2.0 * _n)) / den
half := z * math.sqrt(p * (1.0 - p) / _n + z * z / (4.0 * _n * _n)) / den
[ctr, half]
f_rate(int _k, int _n) =>
[ctr, half] = f_wilson(_k, _n)
string s = _n > 0 ? str.tostring(100.0 * _k / _n, "0") + "% ±" + str.tostring(100.0 * half, "0") : "-"
bool above = _n > 0 and ctr - half > 0.5
bool below = _n > 0 and ctr + half < 0.5
[s, above, below]
// ─── Window resolution ───────────────────────────────────────────────────────
string sess = custSess
string tz = custTz
if presetIn == "Asia range"
sess := "0000-0800"
tz := "Europe/London"
else if presetIn == "London first hour"
sess := "0800-0900"
tz := "Europe/London"
else if presetIn == "New York first 30 min"
sess := "0930-1000"
tz := "America/New_York"
bool tfOk = timeframe.isintraday
bool inWin = tfOk and not na(time(timeframe.period, sess, tz))
bool winStart = inWin and not inWin[1]
bool winEnd = not inWin and inWin[1]
int horizonBars = math.max(1, math.round(horizonMin * 60.0 / timeframe.in_seconds()))
// ─── State of the current day ────────────────────────────────────────────────
var float rH = na
var float rL = na
var bool rangeDone = false
var bool rangeValid = false
var int brkDir = 0
var int brkBar = na
var bool failed = false
var bool resolved = false
var bool brokeUp = false
var bool brokeDn = false
var float ext = 0.0
var box rBox = na
// ─── Tallies over the loaded history ─────────────────────────────────────────
var int nDays = 0
var int nUpOnly = 0
var int nDnOnly = 0
var int nBoth = 0
var int nNone = 0
var int nBrkDays = 0
var int nHeld = 0
var int nRes = 0
var int nFail = 0
var array<float> exts = array.new<float>()
// ─── Events of the current bar ───────────────────────────────────────────────
bool evBreakUp = false
bool evBreakDn = false
bool evFailUp = false
bool evFailDn = false
if winStart
// Close the books on the previous day before starting a new range.
if rangeDone and rangeValid and not na(rH) and rH > rL
nDays += 1
if brokeUp and brokeDn
nBoth += 1
else if brokeUp
nUpOnly += 1
else if brokeDn
nDnOnly += 1
else
nNone += 1
if brkDir != 0
nBrkDays += 1
bool held = brkDir == 1 ? close[1] > rH : close[1] < rL
if held
nHeld += 1
if resolved
nRes += 1
if failed
nFail += 1
float rHeight = rH - rL
array.push(exts, rHeight > 0 ? ext / rHeight : 0.0)
rH := high
rL := low
rangeDone := false
rangeValid := bar_index > 0
brkDir := 0
brkBar := na
failed := false
resolved := false
brokeUp := false
brokeDn := false
ext := 0.0
if showBoxes
rBox := box.new(left = bar_index, top = high, right = bar_index, bottom = low, border_color = color.new(C_HEAD, 10), border_width = 2, bgcolor = color.new(C_HEAD, 82))
else if inWin
rH := math.max(rH, high)
rL := math.min(rL, low)
if showBoxes and not na(rBox)
box.set_right(rBox, bar_index)
box.set_top(rBox, rH)
box.set_bottom(rBox, rL)
if winEnd and not na(rH)
rangeDone := true
if rangeDone and not inWin and rangeValid and barstate.isconfirmed and rH > rL
if close > rH
brokeUp := true
if close < rL
brokeDn := true
if brkDir == 0
if close > rH
brkDir := 1
brkBar := bar_index
ext := math.max(0.0, high - rH)
evBreakUp := true
else if close < rL
brkDir := -1
brkBar := bar_index
ext := math.max(0.0, rL - low)
evBreakDn := true
else
int k = bar_index - brkBar
if not resolved
bool backIn = brkDir == 1 ? close <= rH : close >= rL
if k <= horizonBars and backIn
failed := true
resolved := true
if brkDir == 1
evFailUp := true
else
evFailDn := true
else if k >= horizonBars
resolved := true
ext := math.max(ext, brkDir == 1 ? high - rH : rL - low)
// ─── Chart drawings ──────────────────────────────────────────────────────────
bool lvlOn = showLevels and rangeDone and not inWin
plot(lvlOn ? rH : na, "Range high", color = C_HEAD, style = plot.style_linebr, linewidth = 2)
plot(lvlOn ? rL : na, "Range low", color = C_HEAD, style = plot.style_linebr, linewidth = 2)
plotshape(showMarks and evBreakUp, "First break up", style = shape.triangleup, location = location.belowbar, color = C_BULL, size = size.small)
plotshape(showMarks and evBreakDn, "First break down", style = shape.triangledown, location = location.abovebar, color = C_BEAR, size = size.small)
plotshape(showMarks and evFailUp, "Up break failed", style = shape.xcross, location = location.abovebar, color = C_WARN, size = size.small)
plotshape(showMarks and evFailDn, "Down break failed", style = shape.xcross, location = location.belowbar, color = C_WARN, size = size.small)
// ─── Dashboard ───────────────────────────────────────────────────────────────
var table dash = table.new(f_pos(dashPos), 3, 9, bgcolor = C_BG, border_width = 1, border_color = C_CHIP, frame_width = 2, frame_color = C_HEAD)
f_row(table _t, int _r, string _name, string _val, color _valCol, string _chip, color _chipBg, string _tip) =>
table.cell(_t, 0, _r, _name, text_color = C_LBL, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_left, tooltip = _tip)
table.cell(_t, 1, _r, _val, text_color = _valCol, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_right, tooltip = _tip)
table.cell(_t, 2, _r, _chip, text_color = C_TEXT, bgcolor = _chipBg, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = _tip)
if showDash and barstate.islast
table.cell(dash, 0, 0, "ORB STATS", text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_left)
table.cell(dash, 1, 0, presetIn, text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_right)
table.cell(dash, 2, 0, str.tostring(nDays) + " days", text_color = C_TEXT, bgcolor = C_HEAD, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = "Number of complete days measured in the loaded history of this chart.")
if not tfOk
f_row(dash, 1, "Use an intraday timeframe", "", C_WARN, "", C_BG, "The range window is defined in hours and minutes.")
else if nDays == 0
f_row(dash, 1, "No complete range yet", "", C_WARN, "", C_BG, "No day with a complete window in the loaded history. Check the window, the timezone and the chart timeframe.")
else
string tipSide = "Days on which a bar closed outside the range on that side, between the end of the window and the next window."
string tipFlip = " Coin flip = the 95% interval contains 50%."
f_row(dash, 1, "Up only", f_pct(nUpOnly, nDays), C_BULL, str.tostring(nUpOnly), C_CHIP, tipSide)
f_row(dash, 2, "Down only", f_pct(nDnOnly, nDays), C_BEAR, str.tostring(nDnOnly), C_CHIP, tipSide)
f_row(dash, 3, "Both sides", f_pct(nBoth, nDays), C_WARN, str.tostring(nBoth), C_CHIP, tipSide)
f_row(dash, 4, "No break", f_pct(nNone, nDays), C_TEXT, str.tostring(nNone), C_CHIP, "Days on which no bar closed outside the range.")
[sFail, failAbove, failBelow] = f_rate(nFail, nRes)
string chipFail = failAbove ? "Above 50%" : failBelow ? "Below 50%" : "Coin flip"
color colFail = failAbove ? C_WARN : failBelow ? C_BULL : C_NEUT
f_row(dash, 5, "First break failed", sFail, C_TEXT, chipFail, colFail, "Share of first breaks followed by a close back inside the range within the horizon (" + str.tostring(horizonMin) + " min), n = " + str.tostring(nRes) + ". Wilson 95% margin." + tipFlip + " A quick close back inside is common for any nearby level, so compare windows and markets before reading this as an edge.")
[sHeld, heldAbove, heldBelow] = f_rate(nHeld, nBrkDays)
string chipHeld = heldAbove ? "Above 50%" : heldBelow ? "Below 50%" : "Coin flip"
color colHeld = heldAbove ? C_BULL : heldBelow ? C_WARN : C_NEUT
f_row(dash, 6, "Held at day end", sHeld, C_TEXT, chipHeld, colHeld, "Share of first breaks with the last close before the next window still beyond the broken side, n = " + str.tostring(nBrkDays) + ". Wilson 95% margin." + tipFlip)
float medExt = array.median(exts)
f_row(dash, 7, "Median extension", na(medExt) ? "-" : str.tostring(medExt, "0.00") + " x range", C_TEXT, "", C_BG, "Median of the furthest move beyond the broken side after the first break, in multiples of the range height, n = " + str.tostring(array.size(exts)) + ".")
string st = inWin ? "Range forming" : not rangeDone ? "Waiting for window" : brkDir == 0 ? "Inside range" : brkDir == 1 ? (failed ? "Up break failed" : resolved ? "Up break holding" : "Up break, in horizon") : (failed ? "Down break failed" : resolved ? "Down break holding" : "Down break, in horizon")
color stBg = failed ? C_WARN : brkDir == 1 ? C_BULL : brkDir == -1 ? C_BEAR : C_NEUT
table.cell(dash, 0, 8, "Today", text_color = C_LBL, bgcolor = C_BG, text_size = f_size(dashSize), text_halign = text.align_left)
table.cell(dash, 1, 8, st, text_color = C_TEXT, bgcolor = stBg, text_size = f_size(dashSize), text_halign = text.align_center, tooltip = "State of the current day. Descriptive only.")
table.merge_cells(dash, 1, 8, 2, 8)
// ─── Alerts (single-bar events, confirmed bars) ──────────────────────────────
alertcondition(evBreakUp, "First break up", "ORB Stats: first close above the range on {{ticker}}")
alertcondition(evBreakDn, "First break down", "ORB Stats: first close below the range on {{ticker}}")
alertcondition(evFailUp or evFailDn, "First break failed", "ORB Stats: the first break closed back inside the range on {{ticker}}")
// =============================================================================
// No indicator is infallible. Nothing here is financial advice — every trading
// decision is your own.
// =============================================================================