Perfected FlowScript
orb by tradjilla
ORB Pro V2 — Opening Range Breakout is indexed as 260_orb_by_tradjilla.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
onchart
Axis
false
Size
15.5 KB
Lines
477
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Long ORB
line 380:5
Trigger
(showBreakouts && upBreakFirst)
Value
pxClose
Deps
showBreakouts:input, upBreakFirst:var
Short ORB
line 390:5
Trigger
(showBreakouts && dnBreakFirst)
Value
pxClose
Deps
dnBreakFirst:var, showBreakouts:input
Long Conf
line 402:5
Trigger
(showBreakouts && upBreak && !upBreakFirst)
Value
pxClose
Deps
showBreakouts:input, upBreak:var, upBreakFirst:var
Short Conf
line 412:5
Trigger
(showBreakouts && dnBreak && !dnBreakFirst)
Value
pxClose
Deps
dnBreak:var, dnBreakFirst:var, showBreakouts:input
260_orb_by_tradjilla.flowscript
source path: kscripts/perfected/260_orb_by_tradjilla.flowscript · sha256:584903d047fa9f2659656531606b1517926c430dba7aca3666c6bee7bccf2643
//@version=2
// ============================================================================
// ORB Pro V2 — Opening Range Breakout by Tradjilla | Perfected Edition
// Author: G (@Ganesh Band) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ONCHART, #orb, #openingrange, #crabel, #breakout, #stretch
//
// Production-quality Opening Range Breakout (ORB) indicator with Crabel stretch
// levels, session-aware detection, z-score normalized range analysis, and
// comprehensive color-coded visualization. Detects the opening range (high/low)
// within a configurable window, computes the Crabel stretch from historical
// true ranges, and marks breakout signals with shape alerts. Static state
// tracks session persistence, range history, and breakout statistics for
// context-aware performance monitoring.
//
// Academic foundation (exact papers & formulas):
// 1. Crabel (1990), "Playing the Opening Range Breakout", Stocks & Commodities
// Magazine. The foundational practitioner work. ORB = trade at a predetermined
// amount (the "stretch") above or below the opening range. Stretch = average
// of previous 10 days' differences between open and its closest extreme.
// ORB is most effective after inside days with narrowest range in 4+ days.
//
// 2. SFI / Concretum Group (2024), "A Profitable Day Trading Strategy For The
// U.S. Equity Market", Swiss Finance Institute Research Paper. Analyzed 5-min
// ORB on 7,000+ US stocks (2016–2023). Top 20 "Stocks in Play" portfolio
// achieved >1,600% total net return, Sharpe 2.81, annualized alpha 36%.
// Compared 5-min, 15-min, 30-min, and 60-min opening ranges.
// URL: https://www.sfi.ch/en/publications/n-24-98
//
// 3. Harris (1986), "A Transaction Data Study of Weekly and Intradaily Patterns
// in Stock Returns", Journal of Financial Economics, 16(1), 99–117.
// Found significant intraday return patterns: first 45 minutes after open
// show strongest effects. U-shaped volume pattern with peaks at open and close.
// Supports the structural rationale for ORB: institutional order flow
// clusters at open, volatility is highest in the first hour.
// DOI: https://doi.org/10.1016/0304-405X(86)90068-8
//
// 4. Steidlmayer & Hawkins (2002), "Steidlmayer on Markets: Trading with Market
// Profile" (2nd ed.), Wiley Trading. The Initial Balance (price range in the
// first hour) is the reference point for the rest of the session. Opening range
// becomes support/resistance for the session. Value Area (~70% of trading)
// and Point of Control (POC) form the auction market structure.
//
// 5. Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section
// of Stock Returns", Journal of Finance, 65(4), 1369–1407.
// Opening half-hour decile spread earns >11 basis points. Day 1 return effect
// is most pronounced at the open. Validates that the opening range contains
// the highest signal-to-noise ratio of any intraday period.
// DOI: https://doi.org/10.1111/j.1540-6261.2010.01573.x
//
// 6. Build Alpha (2026), "Opening Range Breakout Strategy: Complete Guide".
// Key structural reasons ORB works: institutional order flow at open,
// highest volatility in first hour, price discovery at open, and concentrated
// liquidity. Variants: filtered ORB (range width), volume-confirmed ORB,
// ORB with trend bias, and ORB fade (counter-strategy).
// URL: https://www.buildalpha.com/opening-range-breakout/
// ============================================================================
define(
title="ORB Pro V2 — Opening Range Breakout",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Session Settings --
var sessionStartHour = input(
name="sessionStartHour",
type="number",
defaultValue=9,
label="Session Start Hour (UTC)",
constraints={min: 0, max: 23, step: 1},
group="Session Settings"
)
var sessionMins = input(
name="sessionMins",
type="number",
defaultValue=30,
label="OR Window Minutes",
constraints={min: 5, max: 120, step: 5},
group="Session Settings"
)
// -- Stretch (Crabel) --
var stretchMult = input(
name="stretchMult",
type="number",
defaultValue=1.0,
label="Stretch Multiplier",
constraints={min: 0.5, max: 3.0, step: 0.25},
group="Stretch (Crabel)"
)
var stretchLookback = input(
name="stretchLookback",
type="number",
defaultValue=10,
label="Stretch Lookback (periods)",
constraints={min: 5, max: 30, step: 1},
group="Stretch (Crabel)"
)
// -- Range Filter --
var minRangeWidth = input(
name="minRangeWidth",
type="number",
defaultValue=0.0,
label="Min OR Width % (0 = disabled)",
constraints={min: 0, max: 5, step: 0.1},
group="Range Filter"
)
var maxRangeWidth = input(
name="maxRangeWidth",
type="number",
defaultValue=5.0,
label="Max OR Width % (0 = disabled)",
constraints={min: 0, max: 10, step: 0.5},
group="Range Filter"
)
// -- Display --
var showOR = input(
name="showOR",
type="boolean",
defaultValue=true,
label="Show Opening Range",
group="Display"
)
var showStretch = input(
name="showStretch",
type="boolean",
defaultValue=true,
label="Show Stretch Levels",
group="Display"
)
var showBreakouts = input(
name="showBreakouts",
type="boolean",
defaultValue=true,
label="Show Breakout Signals",
group="Display"
)
var showRangeFill = input(
name="showRangeFill",
type="boolean",
defaultValue=true,
label="Show OR Fill",
group="Display"
)
var showStats = input(
name="showStats",
type="boolean",
defaultValue=false,
label="Show Breakout Statistics",
group="Display"
)
// -- Colors --
var orColor = input(
name="orColor",
type="color",
defaultValue="#2962ff",
label="Opening Range Color",
group="Colors"
)
var upColor = input(
name="upColor",
type="color",
defaultValue="#00e676",
label="Long Breakout Color",
group="Colors"
)
var dnColor = input(
name="dnColor",
type="color",
defaultValue="#ff5252",
label="Short Breakout Color",
group="Colors"
)
var stretchColor = input(
name="stretchColor",
type="color",
defaultValue="#ff9800",
label="Stretch Line Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = price.time
timeseries pxClose = price.close
timeseries pxHigh = price.high
timeseries pxLow = price.low
// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(pxClose[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Session identification --
// Per Harris (1986), intraday patterns are driven by clock time. We identify
// session windows by UTC time and track the opening range within each window.
timeseries hourOfDay = (t / 3600000) % 24
timeseries minOfHour = (t / 60000) % 60
// Session ID: unique identifier for each OR window
timeseries sessionId = math.floor(t / (sessionMins * 60000))
// Minutes elapsed within current session window
timeseries minsInSession = ((t % (sessionMins * 60000)) / 60000)
// Is currently within the OR formation window?
var inORWindow = minsInSession < sessionMins
// -- 3.2 Opening range tracking (static state) --
// Track OR high/low across each session window. Reset on session change.
static orHigh = 0.0
static orLow = 1e18
static lastSession = -1
static orWidthPct = 0.0
if (lastSession != sessionId) {
// New session: store previous OR width, then reset
if (orHigh > 0 && orLow < 1e18) {
orWidthPct = (orHigh - orLow) / ((orHigh + orLow) / 2) * 100
}
lastSession = sessionId
orHigh = pxHigh
orLow = pxLow
} else {
// Same session: expand OR bounds if still in formation window
if (inORWindow) {
orHigh = math.max(orHigh, pxHigh)
orLow = math.min(orLow, pxLow)
}
}
// -- 3.3 Range width validation --
// Per Build Alpha (2026): filtered ORB uses range width to avoid breakouts
// from excessively wide (low-conviction) or narrow (noise) ranges.
var orWidth = orHigh - orLow
var orMid = (orHigh + orLow) / 2
var orWidthPctCurrent = orMid > 0 ? (orWidth / orMid) * 100 : 0
var rangeValid = true
if (minRangeWidth > 0 && orWidthPctCurrent < minRangeWidth) {
rangeValid = false
}
if (maxRangeWidth > 0 && orWidthPctCurrent > maxRangeWidth) {
rangeValid = false
}
// -- 3.4 Stretch calculation (Crabel) --
// Per Crabel (1990): stretch = average of previous N periods' true ranges.
// We use a ring buffer of fixed size for historical stretch values.
static stretchBuf = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
timeseries stIdx = sessionId % stretchLookback
timeseries trueRange = pxHigh - pxLow
if (!isnan(trueRange)) {
stretchBuf[stIdx] = trueRange
}
// Average stretch across lookback periods
timeseries avgStretch = 0.0
timeseries i = 0
for i in range(0, stretchLookback) {
avgStretch = avgStretch + stretchBuf[i]
}
avgStretch = (stretchLookback > 0) ? (avgStretch / stretchLookback) * stretchMult : 0
// Stretch levels above/below OR
timeseries longStretch = orHigh + avgStretch
timeseries shortStretch = orLow - avgStretch
// -- 3.5 Z-score normalisation of OR width --
// Compare current OR width to historical average for relative context.
timeseries stretchMean = sma(source=trueRange, period=stretchLookback)
timeseries stretchStd = stdev(source=trueRange, period=stretchLookback)
timeseries rangeZ = (stretchStd > 0) ? (trueRange - stretchMean) / stretchStd : 0
// -- 3.6 Breakout detection --
// Long breakout: close > OR high + stretch; Short breakout: close < OR low - stretch
var upBreak = pxClose > longStretch && rangeValid && !inORWindow
var dnBreak = pxClose < shortStretch && rangeValid && !inORWindow
var upBreakFirst = upBreak && !(pxClose[1] > longStretch[1])
var dnBreakFirst = dnBreak && !(pxClose[1] < shortStretch[1])
// -- 3.7 Regime detection --
var orbBull = upBreak
var orbBear = dnBreak
var orbNeutral = !orbBull && !orbBear
// -- 3.8 Breakout statistics via static state --
static totalUpBreaks = 0
static totalDnBreaks = 0
static totalBreaks = 0
static lastBreakDir = 0
static breakBarsAgo = 0
if (upBreakFirst) {
totalUpBreaks = totalUpBreaks + 1
totalBreaks = totalBreaks + 1
lastBreakDir = 1
breakBarsAgo = 0
} else if (dnBreakFirst) {
totalDnBreaks = totalDnBreaks + 1
totalBreaks = totalBreaks + 1
lastBreakDir = -1
breakBarsAgo = 0
} else {
breakBarsAgo = breakBarsAgo + 1
}
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, fill, hline
// ---------------------------------------------------------------------------
// 4.1 Opening Range high/low lines (plotLine)
if (showOR) {
plotLine(
value=orHigh,
width=1,
colors=[orColor],
label=["OR High"],
desc=["Opening range high (session window = " + sessionMins + " min)"]
)
plotLine(
value=orLow,
width=1,
colors=[orColor],
label=["OR Low"],
desc=["Opening range low (session window = " + sessionMins + " min)"]
)
}
// 4.2 OR fill area (plotLine + fill)
if (showRangeFill) {
var fillBull = pxClose > orMid
plotLine(
value=[orHigh, orLow],
width=1,
colors=[transparency(upColor, 20), transparency(dnColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["OR High", "OR Low"],
desc=["Opening range fill — green = close above mid, red = below"]
)
}
// 4.3 Stretch levels (plotLine) — Crabel extension lines
if (showStretch) {
plotLine(
value=longStretch,
width=1,
colors=[stretchColor],
label=["Long Stretch"],
desc=["Crabel stretch above OR high (lookback " + stretchLookback + ")"]
)
plotLine(
value=shortStretch,
width=1,
colors=[stretchColor],
label=["Short Stretch"],
desc=["Crabel stretch below OR low (lookback " + stretchLookback + ")"]
)
}
// 4.4 Breakout shape markers (plotShape) — triangles on first breakout bar
if (showBreakouts && upBreakFirst) {
plotShape(
value=pxClose,
shape="triangleup",
colorIndex=upColor,
width=3,
label=["Long ORB"],
desc=["Long ORB breakout: close above OR high + stretch"]
)
}
if (showBreakouts && dnBreakFirst) {
plotShape(
value=pxClose,
shape="triangledown",
colorIndex=dnColor,
width=3,
label=["Short ORB"],
desc=["Short ORB breakout: close below OR low - stretch"]
)
}
// 4.5 Breakout confirmation dots (plotShape) — sustained breakout beyond OR
if (showBreakouts && upBreak && !upBreakFirst) {
plotShape(
value=pxClose,
shape="circle",
colorIndex=upColor,
width=1,
label=["Long Conf"],
desc=["Sustained long ORB — price remains above stretch level"]
)
}
if (showBreakouts && dnBreak && !dnBreakFirst) {
plotShape(
value=pxClose,
shape="circle",
colorIndex=dnColor,
width=1,
label=["Short Conf"],
desc=["Sustained short ORB — price remains below stretch level"]
)
}
// 4.6 OR midpoint reference line
hline(value=orMid, color=transparency(orColor, 50), width=1)
// 4.7 Optional breakout statistics (plotLine) — cumulative counts as visual bands
if (showStats) {
plotLine(
value=totalUpBreaks * 0.001,
width=1,
colors=[transparency(upColor, 60)],
label=["Up Break Count"],
desc=["Cumulative long breakout count (scaled)"]
)
plotLine(
value=totalDnBreaks * 0.001,
width=1,
colors=[transparency(dnColor, 60)],
label=["Dn Break Count"],
desc=["Cumulative short breakout count (scaled)"]
)
}
// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = orbBull ? "LONG ORB" : (orbBear ? "SHORT ORB" : "NEUTRAL")
var regimeTextColor = orbBull ? upColor : (orbBear ? dnColor : "#9e9e9e")
var lastBreakText = lastBreakDir == 1 ? "LONG" : (lastBreakDir == -1 ? "SHORT" : "NONE")
plotTable(
data=[
["ORB Pro V2", regimeText],
["OR High", orHigh],
["OR Low", orLow],
["OR Width %", orWidthPctCurrent],
["Stretch", avgStretch],
["Range Z", rangeZ[0]],
["Total Up", totalUpBreaks],
["Total Dn", totalDnBreaks],
["Last Break", lastBreakText],
["Breaks Ago", breakBarsAgo]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=transparency("#0f172a", 40),
headerBackgroundColor=transparency("#1e293b", 40),
borderColor=transparency("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}