Overnight Range Breakout [ONRB]

angelotrades509 · study · 318 行 · 点赞 7 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════════════════
// Overnight Range Breakout (ONRB)
// USE
//   Intraday chart <= 15 min (5m recommended) on a futures symbol that includes
//   extended/Globex hours (NQ1!, MNQ1!, ES1! ...). Session math is done in
//   America/New_York regardless of your chart timezone.
// ═══════════════════════════════════════════════════════════════════════════
indicator("Overnight Range Breakout [ONRB]", shorttitle="ONRB", overlay=true, max_labels_count=500, max_lines_count=500)
 
// ─── Inputs ────────────────────────────────────────────────────────────────
string GS = "Sessions"
string tz       = input.string("America/New_York", "Timezone", group=GS)
string ovnSess  = input.session("1800-0930", "Overnight session", group=GS)
string rthSess  = input.session("0930-1600", "RTH session", group=GS)
 
string GB = "Breakout & gap buckets"
string breakMode = input.string("Touch", "Break definition", options=["Touch", "Close beyond level"], group=GB, tooltip="Touch = any trade beyond the level (as in the article). Close beyond = bar must close beyond the level.")
float gapTiny  = input.float(0.15, "Gap 'tiny' below (%)",   minval=0.0, step=0.01, group=GB)
float gapSmall = input.float(0.35, "Gap 'small' below (%)",  minval=0.0, step=0.01, group=GB)
float gapMed   = input.float(0.69, "Gap 'medium' below (%)", minval=0.0, step=0.01, group=GB)
 
string GT = "Trade signals (optional layer)"
bool   showSignals = input.bool(true, "Show long/short signals", group=GT)
bool   biasOnly    = input.bool(true, "Only when first break agrees with midpoint bias", group=GT)
int    sigWindow   = input.int(60, "Signal window (minutes after open)", minval=1, group=GT, tooltip="Article: ~69% of first breaks occur within 30 min, ~81% within 60 min.")
string stopMode    = input.string("Midpoint", "Stop", options=["Midpoint", "Opposite level", "ATR"], group=GT)
float  atrMult     = input.float(1.5, "ATR multiple (ATR stop)", minval=0.1, step=0.1, group=GT)
float  rr          = input.float(2.0, "Target (R multiple)", minval=0.25, step=0.25, group=GT)
 
string GD = "Display"
bool   showFill      = input.bool(true, "Shade overnight range", group=GD)
bool   showWindow    = input.bool(true, "Tint signal window after open", group=GD)
bool   showBiasLbl   = input.bool(true, "Bias label at open", group=GD)
bool   showBrkLbl    = input.bool(true, "First-break / sweep labels", group=GD)
bool   showTradeLbl  = input.bool(true, "Trade exit labels", group=GD)
bool   showTable     = input.bool(true, "Dashboard", group=GD)
string tblPos        = input.string(position.top_right, "Dashboard position", options=[position.top_left, position.top_right, position.bottom_left, position.bottom_right], group=GD)
color  colUp    = input.color(color.new(#26a69a, 0), "Up / high color", group=GD)
color  colDn    = input.color(color.new(#ef5350, 0), "Down / low color", group=GD)
color  colMid   = input.color(color.new(#ff9800, 0), "Midpoint color", group=GD)
color  colRange = input.color(color.new(#2962ff, 0), "Range color", group=GD)
 
if not timeframe.isintraday or timeframe.in_seconds() > 900
    runtime.error("ONRB needs an intraday chart of 15 minutes or lower (5m recommended).")
 
// ─── Article statistics (NQ futures, 2015-2025) ─────────────────────────────
f_prob(int d, int b) =>
    float p = na
    if d == 1
        p := b == 1 ? 66.9 : b == 2 ? 69.8 : b == 3 ? 78.1 : b == 4 ? 81.9 : 76.2
    else if d == -1
        p := b == 1 ? 72.2 : b == 2 ? 76.9 : b == 3 ? 71.8 : b == 4 ? 84.1 : 75.6
    p
 
f_dowBreak(int d) =>
    float r = switch d
        dayofweek.monday    => 91.3
        dayofweek.tuesday   => 97.4
        dayofweek.wednesday => 95.9
        dayofweek.thursday  => 94.0
        dayofweek.friday    => 92.1
        => float(na)
    r
 
f_dowName(int d) =>
    string s = switch d
        dayofweek.monday    => "Mon"
        dayofweek.tuesday   => "Tue"
        dayofweek.wednesday => "Wed"
        dayofweek.thursday  => "Thu"
        dayofweek.friday    => "Fri"
        => "-"
    s
 
f_sweep(int b) => b == 1 ? 32.3 : b == 2 ? 28.3 : b == 3 ? 19.9 : b == 4 ? 12.9 : 22.9
 
f_gapName(int b) => b == 1 ? "tiny" : b == 2 ? "small" : b == 3 ? "medium" : b == 4 ? "large" : "n/a"
 
// ─── Session flags ──────────────────────────────────────────────────────────
bool isOvn    = not na(time(timeframe.period, ovnSess, tz))
bool isRth    = not na(time(timeframe.period, rthSess, tz))
bool newOvn   = isOvn and not isOvn[1]
bool rthStart = isRth and not isRth[1]
bool rthEnd   = not isRth and isRth[1]
 
float atr = ta.atr(14)
 
// ─── State ──────────────────────────────────────────────────────────────────
var float ovnHi = na
var float ovnLo = na
var float onH = na
var float onL = na
var float onMid = na
var float rthOpen = na
var float gapPct = na
var float lastRthClose = na
var int   dir = 0
var int   gapBucket = 0
var int   dow = na
var int   rthStartT = na
var int   firstBrk = 0
var int   firstTime = na
var bool  hiBroke = false
var bool  loBroke = false
var bool  sweepDone = false
var bool  valid = false
 
var int nDone = 0
var int nBrkDone = 0
var int nBias = 0
var int nHit = 0
var int nSweep = 0
 
var bool  tradeOpen = false
var int   tDir = 0
var int   tBar = na
var float tEntry = na
var float tStop = na
var float tTarget = na
var float tRisk = na
var line  lnE = na
var line  lnS = na
var line  lnT = na
var int   nTrades = 0
var int   nWins = 0
var float sumR = 0.0
 
bool firstNow = false
bool sweepNow = false
bool sigLong = false
bool sigShort = false
 
// ─── Overnight range ────────────────────────────────────────────────────────
if newOvn
    ovnHi := high
    ovnLo := low
else if isOvn
    ovnHi := math.max(nz(ovnHi, high), high)
    ovnLo := math.min(nz(ovnLo, low), low)
 
// ─── RTH open: freeze levels, compute bias and gap ──────────────────────────
if rthStart
    valid := not na(ovnHi) and not na(ovnLo)
    onH := ovnHi
    onL := ovnLo
    onMid := (ovnHi + ovnLo) / 2
    rthOpen := open
    rthStartT := time
    dow := dayofweek(time, tz)
    gapPct := na(lastRthClose) ? na : (open - lastRthClose) / lastRthClose * 100
    float ag = math.abs(nz(gapPct))
    gapBucket := na(gapPct) ? 0 : ag < gapTiny ? 1 : ag < gapSmall ? 2 : ag < gapMed ? 3 : 4
    dir := not valid ? 0 : open > onMid ? 1 : open < onMid ? -1 : 0
    firstBrk := 0
    firstTime := na
    hiBroke := false
    loBroke := false
    sweepDone := false
 
// ─── Break detection ────────────────────────────────────────────────────────
if isRth and valid
    bool hiHit = breakMode == "Touch" ? high > onH : close > onH
    bool loHit = breakMode == "Touch" ? low < onL : close < onL
    bool newHi = hiHit and not hiBroke
    bool newLo = loHit and not loBroke
    if firstBrk == 0 and (newHi or newLo)
        firstBrk := newHi and newLo ? 2 : newHi ? 1 : -1
        firstTime := time
        firstNow := true
    if newHi
        hiBroke := true
    if newLo
        loBroke := true
    if hiBroke and loBroke and not sweepDone
        sweepDone := true
        sweepNow := true
        nSweep += 1
 
if firstNow and dir != 0 and firstBrk != 2
    nBias += 1
    if firstBrk == dir
        nHit += 1
 
if rthEnd and valid
    nDone += 1
    if firstBrk != 0
        nBrkDone += 1
 
// ─── Labels ─────────────────────────────────────────────────────────────────
if rthStart and valid and showBiasLbl
    float p0 = f_prob(dir, gapBucket)
    string txt = dir == 0 ? "Neutral (open = mid)" : (dir == 1 ? "Bias ▲ ONH first " : "Bias ▼ ONL first ") + str.tostring(p0, "#.#") + "%"
    label.new(bar_index, rthOpen, txt, style = dir == 1 ? label.style_label_up : dir == -1 ? label.style_label_down : label.style_label_center, color = dir == 1 ? colUp : dir == -1 ? colDn : color.gray, textcolor = color.white, size = size.small)
 
if firstNow and showBrkLbl
    int mins = int((time - rthStartT) / 60000)
    string side = firstBrk == 1 ? "ONH" : firstBrk == -1 ? "ONL" : "ONH+ONL"
    string tag = firstBrk == 2 or dir == 0 ? "" : firstBrk == dir ? " ✔" : " ✖"
    color bc = firstBrk == 1 ? colUp : firstBrk == -1 ? colDn : color.gray
    label.new(bar_index, firstBrk == -1 ? low : high, side + " break +" + str.tostring(mins) + "m" + tag, style = firstBrk == -1 ? label.style_label_up : label.style_label_down, color = bc, textcolor = color.white, size = size.small)
 
if sweepNow and showBrkLbl and not (firstNow and firstBrk == 2)
    label.new(bar_index, high, "SWEEP", style = label.style_label_down, color = color.purple, textcolor = color.white, size = size.small)
 
// ─── Signals and simple trade tracking ──────────────────────────────────────
bool inWindow = isRth and not na(rthStartT) and (time - rthStartT) < sigWindow * 60000
 
if showSignals and firstNow and firstBrk != 2 and inWindow and not tradeOpen and (not biasOnly or firstBrk == dir)
    int d = firstBrk
    float entry = breakMode == "Touch" ? (d == 1 ? onH : onL) : close
    float stp = stopMode == "Midpoint" ? onMid : stopMode == "Opposite level" ? (d == 1 ? onL : onH) : (d == 1 ? entry - atr * atrMult : entry + atr * atrMult)
    float risk = math.abs(entry - stp)
    if risk > syminfo.mintick
        tradeOpen := true
        tDir := d
        tBar := bar_index
        tEntry := entry
        tStop := stp
        tRisk := risk
        tTarget := entry + d * rr * risk
        sigLong := d == 1
        sigShort := d == -1
        lnE := line.new(bar_index, tEntry, bar_index, tEntry, color = color.gray, style = line.style_dashed)
        lnS := line.new(bar_index, tStop, bar_index, tStop, color = colDn, style = line.style_dashed)
        lnT := line.new(bar_index, tTarget, bar_index, tTarget, color = colUp, style = line.style_dashed)
 
if tradeOpen and bar_index > tBar
    float exitR = na
    string why = ""
    if isRth
        bool stopHit = tDir == 1 ? low <= tStop : high >= tStop
        bool tgtHit = tDir == 1 ? high >= tTarget : low <= tTarget
        line.set_x2(lnE, bar_index)
        line.set_x2(lnS, bar_index)
        line.set_x2(lnT, bar_index)
        if stopHit
            exitR := -1.0
            why := "SL"
        else if tgtHit
            exitR := rr
            why := "TP"
    else
        exitR := (lastRthClose - tEntry) * tDir / tRisk
        why := "EOD"
    if not na(exitR)
        nTrades += 1
        sumR += exitR
        if exitR > 0
            nWins += 1
        tradeOpen := false
        if showTradeLbl
            float ly = why == "SL" ? tStop : why == "TP" ? tTarget : lastRthClose
            label.new(bar_index, ly, why + " " + (exitR > 0 ? "+" : "") + str.tostring(math.round(exitR, 2)) + "R", style = label.style_label_left, color = exitR > 0 ? colUp : colDn, textcolor = color.white, size = size.tiny)
 
if isRth
    lastRthClose := close
 
// ─── Plots ──────────────────────────────────────────────────────────────────
float plotH = isOvn ? ovnHi : (isRth and valid ? onH : na)
float plotL = isOvn ? ovnLo : (isRth and valid ? onL : na)
float plotM = isOvn ? (ovnHi + ovnLo) / 2 : (isRth and valid ? onMid : na)
 
pH = plot(plotH, "Overnight High", color = isOvn ? color.new(colRange, 55) : colRange, style = plot.style_linebr, linewidth = 2)
pL = plot(plotL, "Overnight Low", color = isOvn ? color.new(colRange, 55) : colRange, style = plot.style_linebr, linewidth = 2)
plot(plotM, "Overnight Mid", color = isOvn ? color.new(colMid, 55) : colMid, style = plot.style_linebr, linewidth = 1)
fill(pH, pL, color = showFill ? color.new(colRange, 92) : na, title = "Overnight range")
 
bgcolor(showWindow and inWindow ? color.new(color.blue, 94) : na, title = "Signal window")
 
plotshape(sigLong, "Long signal", style = shape.triangleup, location = location.belowbar, color = colUp, size = size.small, text = "L")
plotshape(sigShort, "Short signal", style = shape.triangledown, location = location.abovebar, color = colDn, size = size.small, text = "S")
 
// ─── Alerts ─────────────────────────────────────────────────────────────────
alertcondition(rthStart and valid and dir == 1, "ONRB: bias = ONH first", "ONRB: RTH opened above overnight midpoint - overnight HIGH expected to break first")
alertcondition(rthStart and valid and dir == -1, "ONRB: bias = ONL first", "ONRB: RTH opened below overnight midpoint - overnight LOW expected to break first")
alertcondition(firstNow and firstBrk == 1, "ONRB: overnight high broken first", "ONRB: overnight HIGH broken first")
alertcondition(firstNow and firstBrk == -1, "ONRB: overnight low broken first", "ONRB: overnight LOW broken first")
alertcondition(sweepNow, "ONRB: sweep (both levels broken)", "ONRB: both overnight levels have now been broken")
alertcondition(sigLong, "ONRB: long signal", "ONRB: long signal - overnight high break")
alertcondition(sigShort, "ONRB: short signal", "ONRB: short signal - overnight low break")
 
// ─── Dashboard ──────────────────────────────────────────────────────────────
var table tbl = table.new(tblPos, 2, 13, bgcolor = color.new(color.black, 15), border_width = 1, border_color = color.new(color.gray, 60), frame_width = 1, frame_color = color.new(color.gray, 40))
 
f_cell(int r, string k, string v, color vc) =>
    table.cell(tbl, 0, r, k, text_color = color.silver, text_halign = text.align_left, text_size = size.small)
    table.cell(tbl, 1, r, v, text_color = vc, text_halign = text.align_left, text_size = size.small)
 
if showTable and barstate.islast
    table.cell(tbl, 0, 0, "Overnight Range Breakout", text_color = color.white, text_size = size.small, bgcolor = color.new(colRange, 40))
    table.merge_cells(tbl, 0, 0, 1, 0)
 
    float h = isOvn ? ovnHi : onH
    float l = isOvn ? ovnLo : onL
    bool showDay = not isOvn and valid
    float pp = f_prob(dir, gapBucket)
 
    f_cell(1, isOvn ? "ON High / Low (building)" : "ON High / Low", na(h) ? "-" : str.tostring(h, format.mintick) + " / " + str.tostring(l, format.mintick), color.white)
    f_cell(2, "Mid / Range", na(h) ? "-" : str.tostring((h + l) / 2, format.mintick) + " / " + str.tostring(h - l, format.mintick), color.white)
 
    f_cell(3, "Bias (open vs mid)", not showDay ? "waiting for 09:30 ET" : dir == 1 ? "▲ ONH first" : dir == -1 ? "▼ ONL first" : "neutral", dir == 1 ? colUp : dir == -1 ? colDn : color.gray)
    f_cell(4, "Gap vs prev RTH close", not showDay or na(gapPct) ? "-" : (gapPct > 0 ? "▲ " : gapPct < 0 ? "▼ " : "") + str.tostring(math.abs(gapPct), "#.##") + "% (" + f_gapName(gapBucket) + ")", color.white)
 
    bool gapAgrees = not na(gapPct) and dir != 0 and ((gapPct > 0 and dir == 1) or (gapPct < 0 and dir == -1))
    string gapTxt = not showDay or na(gapPct) or dir == 0 ? "" : gapAgrees ? "  gap ✔" : "  gap ✖"
    f_cell(5, "Est. P(bias side first)", not showDay or na(pp) ? "-" : str.tostring(pp, "#.#") + "%" + gapTxt, color.white)
 
    f_cell(6, "Weekday break rate", not showDay ? "-" : f_dowName(dow) + " " + str.tostring(f_dowBreak(dow), "#.#") + "%", color.white)
    f_cell(7, "Sweep risk (gap size)", not showDay ? "-" : str.tostring(f_sweep(gapBucket), "#.#") + "%", color.white)
 
    string fb = not showDay ? "-" : firstBrk == 0 ? (isRth ? "none yet (" + str.tostring(int((time - rthStartT) / 60000)) + "m)" : "no break") : (firstBrk == 1 ? "ONH" : firstBrk == -1 ? "ONL" : "both") + " @ " + str.format_time(firstTime, "HH:mm", tz) + (firstBrk == 2 or dir == 0 ? "" : firstBrk == dir ? " ✔" : " ✖")
    f_cell(8, "First break", fb, firstBrk == 1 ? colUp : firstBrk == -1 ? colDn : color.white)
 
    f_cell(9, "Chart: bias hit-rate", nBias > 0 ? str.tostring(100.0 * nHit / nBias, "#.#") + "% (" + str.tostring(nHit) + "/" + str.tostring(nBias) + ")" : "n/a", color.white)
    f_cell(10, "Chart: break rate", nDone > 0 ? str.tostring(100.0 * nBrkDone / nDone, "#.#") + "% (" + str.tostring(nDone) + " days)" : "n/a", color.white)
    f_cell(11, "Signals: trades | win% | net R", nTrades > 0 ? str.tostring(nTrades) + " | " + str.tostring(100.0 * nWins / nTrades, "#") + "% | " + (sumR > 0 ? "+" : "") + str.tostring(math.round(sumR, 1)) + "R" : "none", sumR > 0 ? colUp : sumR < 0 ? colDn : color.white)
    f_cell(12, "Stats source", "NQ 2015-25 (article)", color.gray)

← 返回列表