本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// Jilly's ORB + Noise Band
//
// Opening-range breakout that only takes the break when the Noise Band confirms
// it: price must be outside the opening range AND outside the time-of-day noise
// band (and beyond session VWAP) at a checkpoint close. One trade per session,
// held with a wide ATR catastrophe stop and flattened late in the day.
//
// Credit: the noise band ("noise area") concept, its time-of-day σ and the
// gap-adjusted reference come from Carlo Zarattini, Andrew Aziz and Andrea
// Barbon, "Beat the Market: An Effective Intraday Momentum Strategy for S&P500
// ETF (SPY)" (2024). The band code follows Jilly's Noise Band; the ORB trigger
// is credited to Redditor SimpleAromatic2128.
//
// Defaults = the recommended config from a 1-minute MNQ research backtest:
// Band N = 20, k = 1.25, Gap-adjusted reference
// OR 09:30–09:45, trigger buffer 0.3 × ATR5
// Entry 15-min checkpoints from 09:45 to 14:00
// Exit stop 10 × ATR5 (catastrophe stop), target 1R (= 10 × ATR5), flat at
// 15:45; whichever comes first. Option: Target = ATR multiple 5
// (backtest: slightly smoother curve for slightly less net).
// Backtest of those settings on 1m MNQ, 1 contract, net of $1.80 RT:
// 2021–2023 (in-sample): 344 trades, win 64%, PF 1.80, +$17.7k, max DD $1.7k, Sharpe 2.4
// 2024 – Sep 2026 (OOS): 287 trades, win 58%, PF 1.52, +$15.1k, max DD $1.4k, Sharpe 1.5
// A TradingView 1-minute chart loads far less history than that, so the table
// here covers only the bars on the chart.
//
// Band
// move(t) = |close at t / session open − 1|, t = minutes since the session
// start at the bar close
// σ(t) = mean of move(t) over the prior N sessions (today excluded)
// Upper = upRef × (1 + k·σ(t)) Lower = dnRef × (1 − k·σ(t))
// ref = session open, or Gap-adjusted: up = max(open, prior close),
// dn = min(open, prior close)
// VWAP = session VWAP of hlc3 anchored at the session start
//
// Signals – evaluated only at checkpoints (bar closes at start + cadence·j),
// after the OR has formed and up to the last entry time, once per session
// LONG close > ORH + buffer·ATR5 and close > Upper and close > VWAP
// SHORT close < ORL − buffer·ATR5 and close < Lower and close < VWAP
// Fills at the OPEN OF THE NEXT BAR. Markers are drawn on that fill bar.
// Exit (resting orders, checked on every bar including the fill bar)
// Stop ATR: entry ∓ m × ATR5 (ATR5 at the signal, rounded to the tick)
// Opposite OR: long ORL, short ORH
// ORM: the OR midpoint (ORH + ORL) / 2, rounded to the tick
// (an OR-based level not beyond the fill falls back to the ATR stop)
// fills at the stop, or at the bar open if it opens through it
// Target R multiple: entry ± R × stop distance; ATR multiple: entry ±
// multiple × ATR5; or None. Fills at the target.
// Stop wins if both are inside the same bar.
// Flat at the close of the bar ending at the flat time, or of the session's
// last bar if it ends earlier.
// Boxes green = entry → furthest price in the trade's favour, red = entry
// → furthest price against it; both grow with the trade and are
// projected "Box projection" bars ahead while open. At the exit the
// box on the closing side is set to entry → exit price and stamped
// with the trade's net $; the other keeps its furthest excursion.
//
// Performance table: trades, win %, PF, expectancy, net P&L, max DD, buy-and-
// hold P&L / max DD from the first trade, first trade time. Net of the "Round-
// trip cost per contract" input for "Contracts". Hypothetical results from the
// indicator's modeled fills over the loaded chart history.
//
// Chart: MNQ1! (or NQ1!) on 1, 5 or 15 minutes, with the default electronic-
// trading-hours session so the 5-min ATR includes overnight bars as in the
// backtest. The checkpoint closes, OR, bands at the checkpoints, fills and flat
// are the same on all three; finer charts only time the stop / target more
// precisely and give a slightly finer VWAP (15-min needs cadence 15 or 30).
// Turn on back-adjustment (B-ADJ) for the continuous contract: the Gap-adjusted
// reference uses the prior session's close. The roll guard also falls back to
// the open on the first session on/after each quarterly expiry (3rd Friday of
// Mar/Jun/Sep/Dec). σ needs N completed sessions of chart history before the
// first signal.
//
// Notes: exchange-holiday sessions that halt at 13:00 (≥ 3 h before the session
// end) are dropped from σ and from the prior close once they finish, as in the
// backtest; the indicator can still trade on them (the backtest did not). 13:15
// half-days count normally. σ ignores minutes missing from a half-day.
//
// For research and educational use only. Not financial advice. Simulated
// results do not guarantee future performance.
// ─────────────────────────────────────────────────────────────────────────────
indicator("Jilly's ORB + Noise Band", shorttitle = "ORB+NB", overlay = true, max_labels_count = 500, max_boxes_count = 500)
// ── Inputs ───────────────────────────────────────────────────────────────────
grpB = "Noise Band"
N = input.int(20, "Lookback N (sessions)", minval = 2, maxval = 60, group = grpB)
k = input.float(1.25, "Band multiplier k", minval = 0.1, step = 0.05, group = grpB)
refMode = input.string("Gap-adjusted", "Reference", options = ["Open", "Gap-adjusted"], group = grpB)
rollGuard = input.bool(true, "Roll guard (Gap-adjusted)", group = grpB,
tooltip = "On the first session on/after each quarterly expiry (3rd Friday of Mar/Jun/Sep/Dec) use the open instead of the prior close, so a continuous-contract roll gap is not read as a real gap.")
useNB = input.bool(true, "Require Noise Band confirmation", group = grpB,
tooltip = "Off = plain ORB entry (OR break + VWAP), for comparison.")
grpO = "Opening Range"
orLen = input.int(15, "OR length (min)", minval = 1, maxval = 120, group = grpO)
bufAtr = input.float(0.3, "Trigger buffer × ATR", minval = 0.0, step = 0.05, group = grpO,
tooltip = "Long needs close > ORH + buffer × ATR, short close < ORL − buffer × ATR.")
useOR = input.bool(true, "Require OR break", group = grpO,
tooltip = "Off = plain Noise Band entry (band + VWAP), for comparison.")
grpT = "Timing"
cadence = input.int(15, "Checkpoint cadence (min)", options = [5, 15, 30], group = grpT)
lastEntry = input.string("14:00", "Last entry checkpoint (HH:MM)", group = grpT)
flatAt = input.string("15:45", "Flat time (HH:MM)", group = grpT,
tooltip = "Open trades are closed at the close of the bar ending at this time. The backtest found 15:15–15:45 best; the last 15 minutes tended to give back.")
grpTr = "Trading"
qty = input.int(1, "Contracts", minval = 1, group = grpTr,
tooltip = "Position size for the performance table and the box $ stamps (this indicator places no orders).")
rtCost = input.float(1.80, "Round-trip cost per contract ($)", minval = 0, step = 0.1, group = grpTr,
tooltip = "Default $1.80 = $0.40/side commission + 1 tick ($0.50) slippage per side on MNQ. Set this to your own costs.")
grpSL = "Stop Loss"
stopMode = input.string("ATR", "Stop", options = ["ATR", "Opposite OR", "ORM"], group = grpSL,
tooltip = "ATR: entry ∓ multiple × ATR. Opposite OR: long ORL, short ORH. ORM: the OR midpoint, (ORH + ORL) / 2. Backtest: the wide ATR stop beat the OR-based stops; stops under ~4 × ATR cut trades that would have closed green.")
stopMult = input.float(10.0, "ATR multiple", minval = 0.1, step = 0.5, group = grpSL,
tooltip = "Used when Stop = ATR. Wide on purpose: it is a catastrophe stop.")
grpTP = "Take Profit"
tgtMode = input.string("R multiple", "Target", options = ["R multiple", "ATR multiple", "None"], group = grpTP,
tooltip = "R multiple: take profit at R × the stop distance. ATR multiple: at entry ± multiple × ATR, whatever the stop. None: hold to the stop or the flat time. Backtest: targets of 2–3 × ATR cut the big winners; ~5 × ATR was slightly smoother than none; with the 10 × ATR stop, 1R (= 10 × ATR) is rarely reached and behaves like None.")
tgtR = input.float(1.0, "R multiple (× risk)", minval = 0.1, step = 0.25, group = grpTP,
tooltip = "Used when Target = R multiple. Risk = the entry-to-stop distance of the selected stop, so with the 10 × ATR stop 1R = 10 × ATR; with Opposite OR, 1R = the distance to the far OR line.")
tgtAtr = input.float(5.0, "ATR multiple", minval = 0.1, step = 0.5, group = grpTP,
tooltip = "Used when Target = ATR multiple: entry ± this many ATRs, whatever the stop.")
grpA = "ATR"
atrLen = input.int(9, "ATR length", minval = 1, group = grpA,
tooltip = "One ATR feeds the OR trigger buffer, the ATR stop and the ATR target. It is read at the signal bar's close.")
atrTf = input.timeframe("5", "ATR timeframe", group = grpA)
grpS = "Session"
sess = input.session("0930-1600", "Session", group = grpS,
tooltip = "Regular session in the timezone below. Its start anchors the open, the OR, the moves and the VWAP.")
tz = input.string("America/New_York", "Timezone", group = grpS)
grpD = "Display"
showSig = input.bool(true, "Entry / exit markers", group = grpD)
showStop = input.bool(true, "Stop / target lines", group = grpD)
showTradeBoxes = input.bool(true, "Show SL/TP boxes", group = grpD,
tooltip = "Green box = entry to the furthest price in the trade's favour, red box = entry to the furthest price against it; both grow with the trade and are projected ahead while it is open. At the exit both are trimmed to the exit bar, the box on the side the trade closed on is set to entry → exit price and stamped with the trade's net $. The stop and target levels are the lines.")
showORl = input.bool(true, "OR high / low / mid", group = grpD)
showVwap = input.bool(true, "Session VWAP", group = grpD)
showOpen = input.bool(true, "Reference (open) line", group = grpD)
showBg = input.bool(true, "Shade time in position", group = grpD)
showCk = input.bool(true, "Checkpoint dots", group = grpD,
tooltip = "A dot under each bar whose close is an entry checkpoint (after the OR, up to the last entry time).")
showStats = input.bool(true, "Show performance table", group = grpD,
tooltip = "Closed-trade stats over this chart's history: fills at the modeled prices (next-bar open, stop / target price, flat-time close), net of the round-trip cost in Trading. Hypothetical and indicative only.")
statsPos = input.string("Top Right", "Table position", options = ["Top Left", "Top Right", "Top Center", "Middle Left", "Middle Right", "Bottom Left", "Bottom Right", "Bottom Center"], group = grpD)
boxLead = input.int(5, "Box projection (bars ahead)", minval = 0, group = grpD)
cBand = input.color(#2a78d6, "Band", group = grpD)
cVwap = input.color(#eb6834, "VWAP", group = grpD)
cOR = input.color(#787b86, "OR", group = grpD)
cOpen = input.color(color.purple, "Session open", group = grpD)
// ── Constants ────────────────────────────────────────────────────────────────
// "HH:MM" (or "HHMM") -> minutes after midnight
hhmm(string t) =>
c = str.replace_all(t, ":", "")
int(str.tonumber(str.substring(c, 0, 2))) * 60 + int(str.tonumber(str.substring(c, 2, 4)))
sessParts = str.split(str.split(sess, ":").get(0), "-")
START_MIN = hhmm(sessParts.get(0))
END_MIN = hhmm(sessParts.get(1))
RTH_MIN = (END_MIN - START_MIN + 1440) % 1440 == 0 ? 1440 : (END_MIN - START_MIN + 1440) % 1440 // session length, minutes
LAST_KEY = (hhmm(lastEntry) - START_MIN + 1440) % 1440 // minutes since the start at the last entry checkpoint
FLAT_KEY = math.min((hhmm(flatAt) - START_MIN + 1440) % 1440, RTH_MIN)
STUB_KEY = RTH_MIN - 180 // a session ending this early is an exchange-holiday stub
// SL/TP box colours
cRisk = color.new(color.red, 85)
cRiskB = color.new(color.red, 50)
cProfit = color.new(color.green, 85)
cProfitB = color.new(color.green, 50)
// A price distance rounded to the tick, at least one tick (resting orders sit on ticks)
tickDist(float d) => math.max(math.round(d / syminfo.mintick) * syminfo.mintick, syminfo.mintick)
TF_MIN = timeframe.multiplier // chart minutes per bar
if barstate.isfirst and (not timeframe.isminutes or cadence % TF_MIN != 0 or orLen % TF_MIN != 0)
runtime.error("ORB + Noise Band: use a minute chart (1, 5 or 15 min) whose interval divides the checkpoint cadence and the OR length.")
if barstate.isfirst and (FLAT_KEY <= orLen or LAST_KEY <= orLen)
runtime.error("ORB + Noise Band: the last entry and flat times must be after the opening range.")
// ── State ────────────────────────────────────────────────────────────────────
inRTH = not na(time(timeframe.period, sess, tz))
newSess = inRTH and not inRTH[1]
endedEarly = inRTH[1] and not inRTH // first bar after an RTH session
// ATR of the latest closed `atrTf` bar at this bar's close (no future data). Chart interval <= atrTf:
// a regular request (lookahead off). Chart interval > atrTf (e.g. 15-min chart, 5-min ATR): the last
// atrTf bar inside this chart bar, which closes with it.
float atrHtf = na
if timeframe.in_seconds() <= timeframe.in_seconds(atrTf)
atrHtf := request.security(syminfo.tickerid, atrTf, ta.atr(atrLen), lookahead = barmerge.lookahead_off)
else
atrIntra = request.security_lower_tf(syminfo.tickerid, atrTf, ta.atr(atrLen))
atrHtf := atrIntra.size() > 0 ? atrIntra.last() : na
var matrix<float> mv = matrix.new<float>(N + 1, RTH_MIN + 1, na) // ring buffer: N prior days + today
var int dayCount = 0
var int row = 0
var bool validDay = false
var bool rollSess = false
var int lastRollYm = 0
var float dayOpen = na
var float priorClose = na
var float sessClose = na // latest close of the current valid session
var int sessLastKey = 0 // its latest key (detects holiday stubs once the session is over)
var float goodClose = na // last close of the latest full session (Gap-adjusted prior close)
var int sessStart = na
var float cumPV = 0.0
var float cumV = 0.0
var int lastKey = 0
var float lastMove = na
var float orh = na
var float orl = na
var bool tradedToday = false
var int heldSide = 0 // open position side
var float entryPx = na
var float stopPx = na
var float tgtPx = na
var int pendEntry = 0 // side to open at this bar's open (0 = none)
var float pendAtr = na // ATR at the signal, for the stop
var int entryBar = na
var box riskBox = na
var box profBox = na
var float favPx = na // furthest price in the trade's favour so far (green box edge)
var float advPx = na // furthest price against it so far (red box edge)
var label lblORH = na // end-of-line labels for the current session (earlier sessions' stay put)
var label lblORL = na
var label lblORM = na
var label lblOpen = na
// Buy & hold benchmark for the table: long from the first trade's entry, marked on bar closes
var float bhPx = na
var int firstTradeT = na
var float bhPk = 0.0
var float bhDD = 0.0
bool longSig = false
bool shortSig = false
bool exitSig = false
drawExit(float px, string txt, string tip) =>
if showSig
label.new(bar_index, px, txt, style = label.style_label_center, color = color.new(chart.fg_color, 85),
textcolor = chart.fg_color, size = size.small, tooltip = tip + " @ " + str.tostring(px, format.mintick))
// Tiny name tag at the right end of a line, vertically centred on it; follows the line's latest bar
endLabel(label lb, float y, string txt, color c) =>
label l = lb
if na(l)
l := label.new(bar_index, y, txt, style = label.style_label_left, color = color.new(color.black, 100),
textcolor = c, size = size.tiny)
else
label.set_xy(l, bar_index, y)
l
posFromStr(string s) =>
switch s
"Top Left" => position.top_left
"Top Right" => position.top_right
"Top Center" => position.top_center
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
=> position.bottom_center
fPct(int w, int n) =>
n > 0 ? str.tostring(100.0 * w / n, "#.#") + "%" : "—"
fPF(float gp, float gl) =>
gl > 0 ? str.tostring(gp / gl, "#.##") : gp > 0 ? "∞" : "—"
// Expectancy: net $ per closed trade, green when positive, red when negative
fExp(float net, int n) =>
n > 0 ? (net < 0 ? "-$" : "$") + str.tostring(math.abs(net / n), "#,##0.00") : "—"
cExp(float net, int n) =>
n == 0 ? color.white : net >= 0 ? color.new(color.green, 0) : color.new(color.red, 0)
// Closed-trade performance stats (one object so helper functions can update it)
type Stats
int cntL = 0
int cntS = 0
int winL = 0
int winS = 0
float gpL = 0.0
float glL = 0.0
float gpS = 0.0
float glS = 0.0
float eq = 0.0
float eqPk = 0.0
float mdd = 0.0
float eqL = 0.0 // per-side closed-trade equity, peak and max drawdown
float eqPkL = 0.0
float mddL = 0.0
float eqS = 0.0
float eqPkS = 0.0
float mddS = 0.0
var Stats stats = Stats.new()
// Net $ of a closed trade
tradeUsd(float pts) =>
pts * syminfo.pointvalue * qty - rtCost * qty
recordTrade(Stats s, int side, float pnl) =>
if side == 1
s.cntL += 1
if pnl > 0
s.winL += 1
s.gpL += pnl
else
s.glL += -pnl
else
s.cntS += 1
if pnl > 0
s.winS += 1
s.gpS += pnl
else
s.glS += -pnl
s.eq += pnl
s.eqPk := math.max(s.eqPk, s.eq)
s.mdd := math.max(s.mdd, s.eqPk - s.eq)
if side == 1
s.eqL += pnl
s.eqPkL := math.max(s.eqPkL, s.eqL)
s.mddL := math.max(s.mddL, s.eqPkL - s.eqL)
else
s.eqS += pnl
s.eqPkS := math.max(s.eqPkS, s.eqS)
s.mddS := math.max(s.mddS, s.eqPkS - s.eqS)
pnl
// Signed dollar string for box text: +$1,250 / −$450
usd(float v) =>
(v < 0 ? "−$" : "+$") + str.tostring(math.abs(v), "#,##0")
// Freeze the trade's boxes at its exit, both trimmed to the exit bar. The box on the side the trade closed
// on is snapped to entry → exit price (created if price never went that way before the exit) and stamped
// with the net $ at its outer edge; the other box keeps the furthest excursion the trade reached.
closeBoxes(box rb, box pb, float exitPx, int exitBar, int startBar, int side, float entry, float pnl) =>
won = side * (exitPx - entry) > 0
if not na(rb)
box.set_right(rb, exitBar)
if not na(pb)
box.set_right(pb, exitBar)
if showTradeBoxes and exitPx != entry
box res = won ? pb : rb
if na(res)
res := box.new(startBar, math.max(entry, exitPx), exitBar, math.min(entry, exitPx),
border_color = won ? cProfitB : cRiskB, bgcolor = won ? cProfit : cRisk)
else
box.set_top(res, math.max(entry, exitPx))
box.set_bottom(res, math.min(entry, exitPx))
// outer edge: long winner → top, long loser → bottom, short winner → bottom, short loser → top
atBottom = won != (side == 1)
box.set_text(res, usd(pnl))
box.set_text_halign(res, text.align_center)
box.set_text_valign(res, atBottom ? text.align_bottom : text.align_top)
box.set_text_color(res, pnl > 0 ? color.green : color.red)
box.set_text_size(res, size.small)
won // explicit return so the if-chains' mixed branch types are not the function's value
// ── Entry decided at the previous bar's checkpoint fills at this bar's open ──
if pendEntry != 0
heldSide := pendEntry
entryPx := open
// OR-based stop level; if it is not beyond the fill (possible with "Require OR break" off) use the ATR stop
float orLvl = stopMode == "Opposite OR" ? (pendEntry == 1 ? orl : orh) : math.round_to_mintick(math.avg(orh, orl))
float orDist = pendEntry * (open - orLvl)
float dist = stopMode == "ATR" or orDist <= 0 ? tickDist(stopMult * pendAtr) : orDist
float tgtDist = tgtMode == "R multiple" ? tgtR * dist : tgtMode == "ATR multiple" ? tickDist(tgtAtr * pendAtr) : na
stopPx := open - pendEntry * dist
tgtPx := na(tgtDist) ? na : open + pendEntry * tgtDist
entryBar := bar_index
favPx := open // the boxes start flat at the entry and grow from there
advPx := open
if na(bhPx)
bhPx := open // buy-and-hold benchmark anchors at the first trade's entry
firstTradeT := time
if showSig
label.new(bar_index, open, pendEntry == 1 ? "L" : "S",
style = pendEntry == 1 ? label.style_label_up : label.style_label_down,
color = pendEntry == 1 ? color.teal : color.red, textcolor = color.white, size = size.small,
tooltip = (pendEntry == 1 ? "Long" : "Short") + " fill @ " + str.tostring(open, format.mintick)
+ "\nStop " + str.tostring(stopPx, format.mintick) + " (" + str.tostring(dist, format.mintick) + " pts)"
+ (na(tgtPx) ? "" : "\nTarget " + str.tostring(tgtPx, format.mintick)))
pendEntry := 0
// A session that ended before the flat time (half-day, missing bars): flatten at the last session close.
if endedEarly and heldSide != 0
pnlE = recordTrade(stats, heldSide, tradeUsd(heldSide * (close[1] - entryPx)))
closeBoxes(riskBox, profBox, close[1], bar_index - 1, entryBar, heldSide, entryPx, pnlE)
riskBox := na
profBox := na
if showSig
label.new(bar_index - 1, close[1], "✕", style = label.style_label_center, color = color.new(chart.fg_color, 85),
textcolor = chart.fg_color, size = size.small, tooltip = "Session ended early: flat @ " + str.tostring(close[1], format.mintick))
heldSide := 0
entryPx := na
stopPx := na
tgtPx := na
exitSig := true
// ── New session ──────────────────────────────────────────────────────────────
// A session whose first bar is not at the session start (chart history starting mid-session) is skipped entirely.
if newSess
// The previous valid session is now complete: drop an exchange-holiday stub from σ and the prior close.
if validDay and sessLastKey > 0
if sessLastKey <= STUB_KEY
mv.fill(na, row, row + 1)
dayCount -= 1
else
goodClose := sessClose
priorClose := goodClose
validDay := hour(time, tz) * 60 + minute(time, tz) == START_MIN
rollSess := false
if validDay
dayCount += 1
row := dayCount % (N + 1)
mv.fill(na, row, row + 1)
// roll guard: first session on/after the 3rd Friday of Mar/Jun/Sep/Dec
y = year(time, tz)
m = month(time, tz)
if rollGuard and m % 3 == 0
dow1 = dayofweek(timestamp(tz, y, m, 1, 0, 0), tz)
thirdFri = 1 + (dayofweek.friday - dow1 + 7) % 7 + 14
if dayofmonth(time, tz) >= thirdFri and lastRollYm != y * 100 + m
rollSess := true
lastRollYm := y * 100 + m
dayOpen := open
sessStart := time
sessLastKey := 0
cumPV := 0.0
cumV := 0.0
lastKey := 0
lastMove := na
orh := na
orl := na
tradedToday := false
riskBox := na
profBox := na
lblORH := na
lblORL := na
lblORM := na
lblOpen := na
heldSide := 0
entryPx := na
stopPx := na
tgtPx := na
// ── Band, VWAP, OR, exits, signals ───────────────────────────────────────────
float sig = na
float UB = na
float LB = na
float vw = na
float upRef = na
float dnRef = na
bool isCheck = false
bool orDone = false
if inRTH and not na(sessStart) and validDay
key = int(math.round((time_close - sessStart) / 60000.0)) // minutes since the session start at the bar close
sessClose := close
sessLastKey := key
cumPV += hlc3 * volume
cumV += volume
vw := cumV > 0 ? cumPV / cumV : close
// Opening range: the first orLen minutes
if key <= orLen
orh := na(orh) ? high : math.max(orh, high)
orl := na(orl) ? low : math.min(orl, low)
orDone := key >= orLen
if key >= 1 and key <= RTH_MIN
mvNow = math.abs(close / dayOpen - 1)
// missing minutes carry the previous move forward
if not na(lastMove) and key > lastKey + 1
for c = lastKey + 1 to key - 1
mv.set(row, c, lastMove)
// σ from the N prior sessions only (minutes a half-day never reached are skipped); today's value is stored after
if dayCount > N
s = 0.0
cnt = 0
for r = 0 to N
if r != row
v = mv.get(r, key)
if not na(v)
s += v
cnt += 1
sig := cnt > 0 ? s / cnt : na
mv.set(row, key, mvNow)
lastKey := key
lastMove := mvNow
if not na(sig)
gapRef = refMode == "Gap-adjusted" and not rollSess and not na(priorClose)
upRef := gapRef ? math.max(dayOpen, priorClose) : dayOpen
dnRef := gapRef ? math.min(dayOpen, priorClose) : dayOpen
UB := upRef * (1 + k * sig)
LB := dnRef * (1 - k * sig)
// Exits: resting stop, then target (stop wins inside the same bar), then the flat time.
if heldSide != 0
hitS = heldSide == 1 ? low <= stopPx : high >= stopPx
hitT = not na(tgtPx) and (heldSide == 1 ? high >= tgtPx : low <= tgtPx)
float xPx = na
string xTxt = ""
string xTip = ""
if hitS
xPx := heldSide == 1 ? math.min(open, stopPx) : math.max(open, stopPx)
xTxt := "SL"
xTip := "Stop"
else if hitT
xPx := tgtPx
xTxt := "TP"
xTip := "Target"
else if key >= FLAT_KEY
xPx := close
xTxt := "✕"
xTip := "Flat time"
if not na(xPx)
pnlX = recordTrade(stats, heldSide, tradeUsd(heldSide * (xPx - entryPx)))
closeBoxes(riskBox, profBox, xPx, bar_index, entryBar, heldSide, entryPx, pnlX)
riskBox := na
profBox := na
drawExit(xPx, xTxt, xTip)
heldSide := 0
entryPx := na
stopPx := na
tgtPx := na
exitSig := true
// Entry: once per session, at a checkpoint after the OR, with time left to fill before the flat
isCheck := key % cadence == 0 and key > orLen and key <= LAST_KEY and key + TF_MIN < FLAT_KEY
if isCheck and not tradedToday and heldSide == 0 and orDone and not na(atrHtf) and (not useNB or not na(sig))
goL = (not useOR or close > orh + bufAtr * atrHtf) and (not useNB or close > UB) and close > vw
goS = (not useOR or close < orl - bufAtr * atrHtf) and (not useNB or close < LB) and close < vw
if goL or goS
pendEntry := goL ? 1 : -1
pendAtr := atrHtf
tradedToday := true
longSig := goL
shortSig := goS
// ── Live boxes: green = entry → furthest price in the trade's favour, red = entry → furthest against it.
// Both grow with the trade (never shrink while it is open) and are projected `boxLead` bars ahead.
if showTradeBoxes and heldSide != 0
favPx := heldSide == 1 ? math.max(favPx, high) : math.min(favPx, low)
advPx := heldSide == 1 ? math.min(advPx, low) : math.max(advPx, high)
if heldSide * (favPx - entryPx) > 0
if na(profBox)
profBox := box.new(entryBar, math.max(entryPx, favPx), bar_index + boxLead, math.min(entryPx, favPx),
border_color = cProfitB, bgcolor = cProfit)
else
box.set_top(profBox, math.max(entryPx, favPx))
box.set_bottom(profBox, math.min(entryPx, favPx))
box.set_right(profBox, bar_index + boxLead)
if heldSide * (advPx - entryPx) < 0
if na(riskBox)
riskBox := box.new(entryBar, math.max(entryPx, advPx), bar_index + boxLead, math.min(entryPx, advPx),
border_color = cRiskB, bgcolor = cRisk)
else
box.set_top(riskBox, math.max(entryPx, advPx))
box.set_bottom(riskBox, math.min(entryPx, advPx))
box.set_right(riskBox, bar_index + boxLead)
// Buy & hold benchmark equity (bar closes since the first trade's entry)
if barstate.isconfirmed and not na(bhPx)
bhEqNow = (close - bhPx) * syminfo.pointvalue * qty
bhPk := math.max(bhPk, bhEqNow)
bhDD := math.max(bhDD, bhPk - bhEqNow)
// ── Plots ────────────────────────────────────────────────────────────────────
orm = math.avg(orh, orl)
plot(UB, "Upper band", color = cBand, linewidth = 2, style = plot.style_linebr)
plot(LB, "Lower band", color = cBand, linewidth = 2, style = plot.style_linebr)
plot(showVwap and inRTH ? vw : na, "Session VWAP", color = cVwap, linewidth = 2, style = plot.style_linebr)
plot(showOpen and inRTH and validDay ? dayOpen : na, "Session open", color = cOpen, style = plot.style_linebr)
plot(showORl and orDone ? orh : na, "OR high", color = cOR, style = plot.style_linebr)
plot(showORl and orDone ? orl : na, "OR low", color = cOR, style = plot.style_linebr)
plot(showORl and orDone ? orm : na, "OR mid", color = cOR, style = plot.style_linebr, linestyle = plot.linestyle_dashed)
plot(showStop and heldSide != 0 ? stopPx : na, "Stop", color = color.red, style = plot.style_linebr)
plot(showStop and heldSide != 0 ? tgtPx : na, "Target", color = color.green, style = plot.style_linebr)
if showORl and orDone
lblORH := endLabel(lblORH, orh, "ORH", cOR)
lblORL := endLabel(lblORL, orl, "ORL", cOR)
lblORM := endLabel(lblORM, orm, "ORM", cOR)
if showOpen and inRTH and validDay
lblOpen := endLabel(lblOpen, dayOpen, "Opening", cOpen)
plotshape(showCk and isCheck, "Checkpoint", shape.circle, location.bottom, color.new(chart.fg_color, 60), size = size.tiny)
bgcolor(showBg and heldSide == 1 ? color.new(color.teal, 92) : showBg and heldSide == -1 ? color.new(color.red, 92) : na)
// ── Alerts (fire on the checkpoint bar close; the fill is the next bar's open) ─
alertcondition(longSig, "ORB+NB long", "ORB+NB LONG on {{ticker}}: checkpoint close {{close}} above the OR and the upper band; fill at next bar open")
alertcondition(shortSig, "ORB+NB short", "ORB+NB SHORT on {{ticker}}: checkpoint close {{close}} below the OR and the lower band; fill at next bar open")
alertcondition(exitSig, "ORB+NB exit", "ORB+NB EXIT on {{ticker}} at {{close}}")
// ── Performance table ────────────────────────────────────────────────────────
fUsd(float v) =>
(v < 0 ? "-$" : "$") + str.tostring(math.abs(v), "#,##0")
cPnl(float v) =>
v >= 0 ? color.green : color.red
cell(table t, int c, int r, string txt, color tc = color.white, color bg = na) =>
table.cell(t, c, r, txt, text_color = tc, bgcolor = bg, text_size = size.small)
var table statsTbl = showStats ? table.new(posFromStr(statsPos), 4, 10, bgcolor = color.new(color.black, 20),
border_width = 1, border_color = color.new(color.gray, 50)) : na
if showStats and barstate.islast
color hdrBg = color.new(color.blue, 70)
color lblBg = color.new(color.black, 50)
int tot = stats.cntL + stats.cntS
float netL = stats.gpL - stats.glL
float netS = stats.gpS - stats.glS
float bhEq = na(bhPx) ? na : (close - bhPx) * syminfo.pointvalue * qty
cell(statsTbl, 0, 0, "ORB + NB", bg = hdrBg)
cell(statsTbl, 1, 0, "All", bg = hdrBg)
cell(statsTbl, 2, 0, "Long", bg = hdrBg)
cell(statsTbl, 3, 0, "Short", bg = hdrBg)
rowNames = array.from("Trades", "Win %", "PF", "Expectancy", "P&L", "Closed-trade Max DD", "B&H P&L", "B&H Max DD", "First trade")
for i = 0 to rowNames.size() - 1
cell(statsTbl, 0, i + 1, rowNames.get(i), bg = lblBg)
cell(statsTbl, 1, 1, str.tostring(tot))
cell(statsTbl, 2, 1, str.tostring(stats.cntL))
cell(statsTbl, 3, 1, str.tostring(stats.cntS))
cell(statsTbl, 1, 2, fPct(stats.winL + stats.winS, tot))
cell(statsTbl, 2, 2, fPct(stats.winL, stats.cntL))
cell(statsTbl, 3, 2, fPct(stats.winS, stats.cntS))
cell(statsTbl, 1, 3, fPF(stats.gpL + stats.gpS, stats.glL + stats.glS))
cell(statsTbl, 2, 3, fPF(stats.gpL, stats.glL))
cell(statsTbl, 3, 3, fPF(stats.gpS, stats.glS))
cell(statsTbl, 1, 4, fExp(stats.eq, tot), cExp(stats.eq, tot))
cell(statsTbl, 2, 4, fExp(netL, stats.cntL), cExp(netL, stats.cntL))
cell(statsTbl, 3, 4, fExp(netS, stats.cntS), cExp(netS, stats.cntS))
cell(statsTbl, 1, 5, tot == 0 ? "—" : fUsd(stats.eq), tot == 0 ? color.white : cPnl(stats.eq))
cell(statsTbl, 2, 5, stats.cntL == 0 ? "—" : fUsd(netL), stats.cntL == 0 ? color.white : cPnl(netL))
cell(statsTbl, 3, 5, stats.cntS == 0 ? "—" : fUsd(netS), stats.cntS == 0 ? color.white : cPnl(netS))
cell(statsTbl, 1, 6, fUsd(stats.mdd), color.red)
cell(statsTbl, 2, 6, stats.cntL == 0 ? "—" : fUsd(stats.mddL), color.red)
cell(statsTbl, 3, 6, stats.cntS == 0 ? "—" : fUsd(stats.mddS), color.red)
cell(statsTbl, 1, 7, na(bhEq) ? "—" : fUsd(bhEq), na(bhEq) ? color.white : cPnl(bhEq))
cell(statsTbl, 1, 8, na(bhPx) ? "—" : fUsd(bhDD), color.red)
cell(statsTbl, 1, 9, na(firstTradeT) ? "—" : str.format_time(firstTradeT, "dd MMM yy HH:mm", tz))
for r = 7 to 9
cell(statsTbl, 2, r, "")
cell(statsTbl, 3, r, "")