Perfected FlowScript
OB public
OB Public V2 is indexed as 267_ob_public.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
17.6 KB
Lines
409
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 315:9
Trigger
(showShapes) && (crossUp)
Value
compositeOBI
Deps
crossUp:var, showShapes:input
Bear Regime
line 325:9
Trigger
(showShapes) && (crossDn)
Value
compositeOBI
Deps
crossDn:var, showShapes:input
Extreme Bid
line 335:9
Trigger
(showShapes) && (extremeUp)
Value
compositeOBI
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 345:9
Trigger
(showShapes) && (extremeDn)
Value
compositeOBI
Deps
extremeDn:var, showShapes:input
Z+2σ
line 355:9
Trigger
(showShapes) && (zScoreUp)
Value
obiZScore
Deps
showShapes:input, zScoreUp:var
Z-2σ
line 365:9
Trigger
(showShapes) && (zScoreDn)
Value
obiZScore
Deps
showShapes:input, zScoreDn:var
267_ob_public.flowscript
source path: kscripts/perfected/267_ob_public.flowscript · sha256:f0fae8b8f01a2fecbea9cb29dda28335edb3290e78b838b9a859e337846ae613
//@version=2
// ============================================================================
// OB Public V2 — Production-Quality Order Block & Public Orderbook Indicator
// Author: I (@Iopl147u) | Perfected by: kScript Perfection Engineer
// Tags: CORE, ADVANCED, #ob, #trend, #orderbook, #institutional
//
// Order Block identification fused with public orderbook depth analysis,
// z-score normalization, regime detection, and institutional footprint tracking.
//
// FORMULA FOUNDATION:
// 1. Order Block (OB): Zone where institutional accumulation/distribution
// likely occurred, identified by displacement + BOS + volume confirmation.
// Per Campbell, Ramadorai & Vuolteenaho (2005) and Liquidity Finder (2026).
// 2. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol)
// Per Cont, Kukanov & Stoikov (2014); predicts short-term price direction.
// 3. Z-Score Normalization: z = (x − μ) / σ over rolling window.
// Per Zhao & Palomar (2018); mean-reversion entry at ±2σ.
// 4. Regime Segmentation: Buy-heavy / Neutral / Sell-heavy per
// Cartea, Donnelly & Jaimungal (2018).
//
// RESEARCH BASIS:
// • Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
// Order Flow and Stock Returns", J. Financial Economics 77(2), 239–281.
// Institutional footprints detectable from trade-size patterns; regression
// achieves ~12% R² in predicting institutional ownership changes.
// • Jones & Lipson (2005), "Are Retail Orders Different?", J. Financial
// Economics 78(3), 631–649. Institutions systematically trade against retail
// flow within 5 minutes; Order Blocks mark institutional absorption zones.
// • Liquidity Finder (2026), "What Is an Order Block? The Institutional
// Footprint Explained". Valid OB = displacement + BOS + HTF alignment.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI linearly predicts price changes.
// • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
// segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// Z-score event triggers at ±1σ or ±2σ for mean-reversion trading.
// ============================================================================
define(
title="OB Public V2",
position="onchart",
axis=false
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Order Block Settings ---
var obLookback = input(name="obLookback", type="number", defaultValue=20, label="OB Swing Lookback", constraints={min: 5, max: 100, step: 1}, group="Order Block")
var volMul = input(name="volMul", type="number", defaultValue=1.5, label="Volume Confirmation Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Order Block")
var maxBlocks = input(name="maxBlocks", type="number", defaultValue=3, label="Max Active Blocks", constraints={min: 1, max: 10, step: 1}, group="Order Block")
var showOBZones = input(name="showOBZones", type="boolean", defaultValue=true, label="Show OB Zones", group="Order Block")
// --- Orderbook Depth ---
var depth1 = input(name="depth1", type="number", defaultValue=1.0, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var depth2 = input(name="depth2", type="number", defaultValue=2.5, label="Depth Band 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var depth3 = input(name="depth3", type="number", defaultValue=5.0, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Orderbook")
var useDepthWeighting = input(name="useDepthWeighting", type="boolean", defaultValue=true, label="Use Depth-Decaying Weights", group="Orderbook")
var weightDecay = input(name="weightDecay", type="number", defaultValue=0.75, label="Weight Decay Factor", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Orderbook")
// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 1}, group="Z-Score")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Z-Score")
// --- Regime Thresholds ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=33.0, label="Bullish Regime Threshold (%)", constraints={min: 10.0, max: 90.0, step: 1.0}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-33.0, label="Bearish Regime Threshold (%)", constraints={min: -90.0, max: -10.0, step: 1.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=66.0, label="Extreme Imbalance Threshold (%)", constraints={min: 50.0, max: 95.0, step: 1.0}, group="Thresholds")
// --- Display ---
var showOBI = input(name="showOBI", type="boolean", defaultValue=true, label="Show OBI Line", group="Display")
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show OBI Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish OB Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish OB Color", group="Colors")
var bidColor = input(name="bidColor", type="color", defaultValue="#00e676", label="Bid-Dominant Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ff1744", label="Ask-Dominant Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Bid Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Ask Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries open = priceBars.open
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries volume = priceBars.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)
// NaN guard — prevent execution before data is loaded
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Block Detection (Campbell et al. 2005; Liquidity Finder 2026)
// ------------------------------------------------------------------------------
// Valid OB = displacement + BOS + volume confirmation
// Track the most recent opposite candle before a swing break for OB zone bounds
timeseries swingHi = highest(high, obLookback)
timeseries swingLo = lowest(low, obLookback)
timeseries bullCandle = px > open
timeseries bearCandle = px < open
timeseries avgVol = sma(volume, obLookback)
timeseries volConfirm = volume > avgVol * volMul
// Static state for OB tracking (session-level persistence)
static lastBullHigh = 0.0
static lastBullLow = 0.0
static lastBearHigh = 0.0
static lastBearLow = 0.0
static bullOBCount = 0
static bearOBCount = 0
static lastBarIndexOB = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndexOB) {
lastBarIndexOB = currentBarIndex
if (bullCandle) {
lastBullHigh = high
lastBullLow = low
}
if (bearCandle) {
lastBearHigh = high
lastBearLow = low
}
}
timeseries swingBreakUp = px > swingHi[1] && volConfirm
timeseries swingBreakDn = px < swingLo[1] && volConfirm
// ------------------------------------------------------------------------------
// Order Book Depth Aggregation (Cont et al. 2014)
// ------------------------------------------------------------------------------
// Multi-depth OBI with geometrically decaying weights per Xu, Gould & Howison (2019)
var bids1 = sumBids(book, depth1)
var asks1 = sumAsks(book, depth1)
var bids2 = sumBids(book, depth2)
var asks2 = sumAsks(book, depth2)
var bids3 = sumBids(book, depth3)
var asks3 = sumAsks(book, depth3)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0
var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 * 100.0 : 0.0
var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 * 100.0 : 0.0
var obi3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 * 100.0 : 0.0
// Depth-weighted composite OBI
var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
var wSum = w1 + w2 + w3
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3) / wSum : 0.0
// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z = (x − μ) / σ over rolling lookback; mean-reversion signals at ±2σ
var obiMean = sma(compositeOBI, zLookback)
var obiStd = stddev(compositeOBI, zLookback)
var obiZScore = obiStd > 0 ? (compositeOBI - obiMean) / obiStd : 0.0
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes: Sell-heavy, Neutral, Buy-heavy
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (compositeOBI >= bullThresh) {
regime = 1
} else if (compositeOBI <= bearThresh) {
regime = -1
}
if (compositeOBI >= extremeThresh) {
extremeRegime = 1
} else if (compositeOBI <= -extremeThresh) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (compositeOBI > sessionHighOBI) {
sessionHighOBI = compositeOBI
}
if (compositeOBI < sessionLowOBI) {
sessionLowOBI = compositeOBI
}
if (obiZScore > sessionHighZ) {
sessionHighZ = obiZScore
}
if (obiZScore < sessionLowZ) {
sessionLowZ = obiZScore
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBidCount = extremeBidCount + 1
} else if (extremeRegime == -1) {
extremeAskCount = extremeAskCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Order Block Zones, OBI, Z-Score, Shapes, and Guides
// ------------------------------------------------------------------------------
// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=bullThresh, color=opacity(bidColor, 30), width=1)
hline(value=bearThresh, color=opacity(askColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeBidColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(extremeAskColor, 20), width=1)
}
// Order Block Zones (on-chart)
if (showOBZones) {
if (swingBreakUp) {
plotLine(value=lastBearHigh, width=2, colors=[upColor], label=["Bull OB Top"], desc=["Bullish order block top — institutional absorption zone"], forceOnChart=true)
plotLine(value=lastBearLow, width=2, colors=[upColor], label=["Bull OB Bot"], desc=["Bullish order block bottom — institutional absorption zone"], forceOnChart=true)
bullOBCount = bullOBCount + 1
}
if (swingBreakDn) {
plotLine(value=lastBullHigh, width=2, colors=[dnColor], label=["Bear OB Top"], desc=["Bearish order block top — institutional distribution zone"], forceOnChart=true)
plotLine(value=lastBullLow, width=2, colors=[dnColor], label=["Bear OB Bot"], desc=["Bearish order block bottom — institutional distribution zone"], forceOnChart=true)
bearOBCount = bearOBCount + 1
}
}
// Raw composite OBI as histogram bars
if (showRawBars) {
plotBar(
value=compositeOBI,
colors=[bidColor, askColor],
width=1,
label=["Composite OBI"],
desc=["Depth-weighted composite OBI histogram (positive=bid, negative=ask)"]
)
}
// Smoothed OBI line with regime-coded fill
if (showOBI) {
plotLine(
value=compositeOBI,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Composite OBI"],
desc=["Depth-weighted composite OBI. Regime: bull/bear/neutral."],
fill=true
)
}
// Z-Score line
if (showZScore) {
plotLine(
value=obiZScore,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=obiZScore > 1.0 ? 0 : (obiZScore < -1.0 ? 1 : 2),
label=["OBI Z-Score"],
desc=["Z-score of composite OBI over " + zLookback + " bars (Zhao & Palomar 2018)"]
)
}
// Regime transition shapes
if (showShapes) {
var crossUp = compositeOBI >= bullThresh && !isnan(compositeOBI[1]) && compositeOBI[1] < bullThresh
var crossDn = compositeOBI <= bearThresh && !isnan(compositeOBI[1]) && compositeOBI[1] > bearThresh
var extremeUp = compositeOBI >= extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] < extremeThresh
var extremeDn = compositeOBI <= -extremeThresh && !isnan(compositeOBI[1]) && compositeOBI[1] > -extremeThresh
var zScoreUp = obiZScore >= 2.0 && !isnan(obiZScore[1]) && obiZScore[1] < 2.0
var zScoreDn = obiZScore <= -2.0 && !isnan(obiZScore[1]) && obiZScore[1] > -2.0
if (crossUp) {
plotShape(
value=compositeOBI,
shape="triangleup",
color=extremeBidColor,
width=3,
label=["Bull Regime"],
desc=["Composite OBI crossed into bullish regime (buy-heavy)"]
)
}
if (crossDn) {
plotShape(
value=compositeOBI,
shape="triangledown",
color=extremeAskColor,
width=3,
label=["Bear Regime"],
desc=["Composite OBI crossed into bearish regime (sell-heavy)"]
)
}
if (extremeUp) {
plotShape(
value=compositeOBI,
shape="diamond",
color=extremeBidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid pressure detected — deep book buy-heavy imbalance"]
)
}
if (extremeDn) {
plotShape(
value=compositeOBI,
shape="diamond",
color=extremeAskColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask pressure detected — deep book sell-heavy imbalance"]
)
}
if (zScoreUp) {
plotShape(
value=obiZScore,
shape="triangleup",
color=extremeBidColor,
width=2,
label=["Z+2σ"],
desc=["Z-score crossed above +2σ — potential mean-reversion sell zone"]
)
}
if (zScoreDn) {
plotShape(
value=obiZScore,
shape="triangledown",
color=extremeAskColor,
width=2,
label=["Z-2σ"],
desc=["Z-score crossed below -2σ — potential mean-reversion buy zone"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
plotTable(
data=[
["OB Public V2", regimeText],
["Composite OBI", compositeOBI[0]],
["OBI Z-Score", obiZScore[0]],
["Session OBI High", sessionHighOBI],
["Session OBI Low", sessionLowOBI],
["Regime Changes", regimeChangeCount],
["Extreme Bid Count", extremeBidCount],
["Extreme Ask Count", extremeAskCount],
["Bull OBs", bullOBCount],
["Bear OBs", bearOBCount]
],
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
)
}