Perfected FlowScript
Orderbook Z-score (Fork)
Order Book Z-Score Fork — Perfected Edition is indexed as 291_orderbook_z_score_fork.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
offchart
Axis
true
Size
21.3 KB
Lines
672
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
+2σ Cross
line 559:9
Trigger
(showShapes) && (crossUp2)
Value
zScore
Deps
crossUp2:var, showShapes:input
-2σ Cross
line 569:9
Trigger
(showShapes) && (crossDn2)
Value
zScore
Deps
crossDn2:var, showShapes:input
+3σ Extreme
line 579:9
Trigger
(showShapes) && (crossUp3)
Value
zScore
Deps
crossUp3:var, showShapes:input
-3σ Extreme
line 589:9
Trigger
(showShapes) && (crossDn3)
Value
zScore
Deps
crossDn3:var, showShapes:input
Zero Cross Up
line 599:9
Trigger
(showShapes) && (zeroCrossUp)
Value
0
Deps
showShapes:input, zeroCrossUp:var
Zero Cross Down
line 609:9
Trigger
(showShapes) && (zeroCrossDn)
Value
0
Deps
showShapes:input, zeroCrossDn:var
Signal Cross Up
line 619:9
Trigger
(showShapes) && (sigCrossUp)
Value
signal
Deps
showShapes:input, sigCrossUp:var
Signal Cross Down
line 629:9
Trigger
(showShapes) && (sigCrossDn)
Value
signal
Deps
showShapes:input, sigCrossDn:var
291_orderbook_z_score_fork.flowscript
source path: kscripts/perfected/291_orderbook_z_score_fork.flowscript · sha256:060949363ebf6033c80d1d97907de37117a01b4336f3b33a6cbb628bf0cc15d5
//@version=2
// ============================================================================
// Order Book Z-Score Fork — Perfected Edition
// Author: Tzen Yang (@Tzen Yang) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #orderbook, #zscore, #microstructure, #OBI, #meanreversion
//
// Production-quality multi-depth orderbook imbalance z-score with σ-bands,
// regime detection, fill visualization, and statistical signal extraction.
// Z-score normalization of depth-weighted composite OBI provides a
// mean-reversion framework with ±1σ/±2σ/±3σ probabilistic thresholds.
//
// Research papers underpinning this design:
// 1. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// z-score event triggers for mean reversion; z_t = (x_t − μ) / σ with
// entry thresholds at ±1σ or ±2σ. Formalizes statistical arbitrage
// using normalized spreads.
// 2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// OFI = Σ(ΔBidSize − ΔAskSize); linear price-impact model gives raw OBI
// predictive meaning. Z-scoring OFI makes imbalance statistically
// interpretable across time and instruments.
// 3. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
// Limit Order Book": multi-level OFI with decaying weights significantly
// improves short-horizon prediction vs. top-of-book alone.
// 4. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
// Predictor": queue imbalance logistic regression for next-tick direction
// prediction; z-scored imbalance is a stronger predictor than raw levels.
// 5. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals": three-regime segmentation (sell-heavy, neutral,
// buy-heavy) predicts future price moves; positive changes preceded by
// buy-heavy books, negative by sell-heavy books.
// 6. QuantOracle (2026), "Z-Score vs Bollinger Bands vs RSI: Mean Reversion
// Comparison": ~95% of values in a normal distribution fall within ±2σ;
// shorter lookback = more frequent signals but more noise.
// ============================================================================
define(
title="Order Book Z-Score Fork — Perfected Edition",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- Depth Configuration ---
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="Depth"
)
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="Depth"
)
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="Depth"
)
var depth4 = input(
name="depth4",
type="number",
defaultValue=10.0,
label="Depth Band 4 (%)",
constraints={min: 0.1, max: 50.0, step: 0.1},
group="Depth"
)
var useDepthWeighting = input(
name="useDepthWeighting",
type="boolean",
defaultValue=true,
label="Use Depth-Decaying Weights",
group="Depth"
)
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="Depth"
)
// --- Z-Score ---
var zLookback = input(
name="zLookback",
type="number",
defaultValue=30,
label="Z-Score Lookback",
constraints={min: 10, max: 200, step: 1},
group="Z-Score"
)
var signalLen = input(
name="signalLen",
type="number",
defaultValue=9,
label="Signal SMA Length",
constraints={min: 1, max: 50, step: 1},
group="Z-Score"
)
var sigma1 = input(
name="sigma1",
type="number",
defaultValue=1.0,
label="1σ Band Multiplier",
constraints={min: 0.5, max: 2.0, step: 0.1},
group="Z-Score"
)
var sigma2 = input(
name="sigma2",
type="number",
defaultValue=2.0,
label="2σ Band Multiplier",
constraints={min: 1.0, max: 3.0, step: 0.1},
group="Z-Score"
)
var sigma3 = input(
name="sigma3",
type="number",
defaultValue=3.0,
label="3σ Band Multiplier",
constraints={min: 2.0, max: 4.0, step: 0.1},
group="Z-Score"
)
// --- Display ---
var showZLine = input(
name="showZLine",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal Line",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Z/Signal Fill",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Z Histogram",
group="Display"
)
var showBands = input(
name="showBands",
type="boolean",
defaultValue=true,
label="Show σ Bands",
group="Display"
)
var showBandFills = input(
name="showBandFills",
type="boolean",
defaultValue=true,
label="Show Band Fills",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Signal Shapes",
group="Display"
)
var showIndividual = input(
name="showIndividual",
type="boolean",
defaultValue=false,
label="Show Individual Depth Z-Scores",
group="Display"
)
// --- Colors ---
var bidColor = input(
name="bidColor",
type="color",
defaultValue="#26a69a",
label="Bid-Dominant Color",
group="Colors"
)
var askColor = input(
name="askColor",
type="color",
defaultValue="#ef5350",
label="Ask-Dominant Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var signalColor = input(
name="signalColor",
type="color",
defaultValue="#ffffff",
label="Signal Line Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)
if (isnan(px[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. MULTI-DEPTH OBI COMPUTATION
// -----------------------------------------------------------------------------
// Per Xu, Gould & Howison (2019), multi-level OFI improves prediction.
// We aggregate four depth bands: 1%, 2.5%, 5%, 10% from mid-price.
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 bids4 = sumBids(book, depth4)
var asks4 = sumAsks(book, depth4)
// Book availability guard — prevents NaN/undefined propagation
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0
// Individual OBI with zero-division guards
var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var denom4 = bids4 + asks4
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
var obi4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 * 100.0 : 0.0
// -----------------------------------------------------------------------------
// 4. DEPTH-WEIGHTED COMPOSITE OBI
// -----------------------------------------------------------------------------
// Geometrically decaying weights per Xu, Gould & Howison (2019).
// w_i = decay^(i−1); Composite = Σ w_i × OBI_i / Σ w_i.
var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
var w4 = useDepthWeighting ? weightDecay * weightDecay * weightDecay : 1.0
var wSum = w1 + w2 + w3 + w4
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / wSum : 0.0
// Smooth composite for noise reduction (Cont et al. 2014)
timeseries smoothedComposite = ema(source=compositeOBI, period=5)
// -----------------------------------------------------------------------------
// 5. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// z_t = (x_t − μ_t) / σ_t over lookback window.
// Per Zhao & Palomar (2018), z-score enables threshold-based mean-reversion
// signals that are statistically interpretable across instruments.
timeseries obiMean = sma(source=smoothedComposite, period=zLookback)
timeseries obiStd = stddev(source=smoothedComposite, period=zLookback)
var zRaw = 0.0
if (bookAvailable && obiStd > 0) {
zRaw = (smoothedComposite - obiMean) / obiStd
} else {
zRaw = 0.0
}
// Cap z-score to avoid extreme outliers distorting visualization
var zCap = 5.0
timeseries zScore = zRaw
if (zRaw > zCap) {
zScore = zCap
}
if (zRaw < -zCap) {
zScore = -zCap
}
// Signal line (SMA of z-score)
timeseries signal = sma(source=zScore, period=signalLen)
// Momentum histogram (z-score minus signal)
timeseries zHist = zScore - signal
// -----------------------------------------------------------------------------
// 6. σ-BAND COMPUTATION
// -----------------------------------------------------------------------------
// ±1σ, ±2σ, ±3σ bands with fill. Per QuantOracle (2026), ~68% of values
// fall within ±1σ, ~95% within ±2σ, ~99.7% within ±3σ of a normal distribution.
var band1 = sigma1
var band2 = sigma2
var band3 = sigma3
// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification per Cartea, Donnelly & Jaimungal (2018):
// Mean-reverting: |z| < 1σ (neutral, expected to revert to 0)
// Extreme bid: z > +2σ (buy-heavy, may continue or mean-revert)
// Extreme ask: z < −2σ (sell-heavy, may continue or mean-revert)
// Moderate: 1σ < |z| < 2σ (transition zone)
var regime = 0 // 0 = neutral, 1 = bid, -1 = ask
var extremeRegime = 0 // 0 = normal, 1 = extreme bid, -1 = extreme ask
if (zScore >= band2) {
regime = 1
extremeRegime = 1
} else if (zScore <= -band2) {
regime = -1
extremeRegime = -1
} else if (zScore >= band1) {
regime = 1
} else if (zScore <= -band1) {
regime = -1
}
var regimeColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)
// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Track session extremes, regime transitions, and band-crossing counts.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static cross1PosCount = 0
static cross1NegCount = 0
static cross2PosCount = 0
static cross2NegCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (zScore > sessionHighZ) {
sessionHighZ = zScore
}
if (zScore < sessionLowZ) {
sessionLowZ = zScore
}
var currentRegime = regime
if (currentRegime != lastRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
if (zScore >= band1 && zScore[1] < band1) {
cross1PosCount = cross1PosCount + 1
}
if (zScore <= -band1 && zScore[1] > -band1) {
cross1NegCount = cross1NegCount + 1
}
if (zScore >= band2 && zScore[1] < band2) {
cross2PosCount = cross2PosCount + 1
}
if (zScore <= -band2 && zScore[1] > -band2) {
cross2NegCount = cross2NegCount + 1
}
}
// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp1 = zScore >= band1 && !isnan(zScore[1]) && zScore[1] < band1
var crossDn1 = zScore <= -band1 && !isnan(zScore[1]) && zScore[1] > -band1
var crossUp2 = zScore >= band2 && !isnan(zScore[1]) && zScore[1] < band2
var crossDn2 = zScore <= -band2 && !isnan(zScore[1]) && zScore[1] > -band2
var crossUp3 = zScore >= band3 && !isnan(zScore[1]) && zScore[1] < band3
var crossDn3 = zScore <= -band3 && !isnan(zScore[1]) && zScore[1] > -band3
var zeroCrossUp = zScore > 0 && !isnan(zScore[1]) && zScore[1] <= 0
var zeroCrossDn = zScore < 0 && !isnan(zScore[1]) && zScore[1] >= 0
var sigCrossUp = zScore > signal && !isnan(zScore[1]) && zScore[1] <= signal[1]
var sigCrossDn = zScore < signal && !isnan(zScore[1]) && zScore[1] >= signal[1]
// -----------------------------------------------------------------------------
// 10. PLOTTING — σ Bands & Zero Line
// -----------------------------------------------------------------------------
hline(value=0, color="#ffffff30", width=1)
if (showBands) {
hline(value=band1, color=transparency(bidColor, 50), width=1)
hline(value=-band1, color=transparency(askColor, 50), width=1)
hline(value=band2, color=transparency(bidColor, 40), width=1)
hline(value=-band2, color=transparency(askColor, 40), width=1)
hline(value=band3, color=transparency(bidColor, 20), width=1)
hline(value=-band3, color=transparency(askColor, 20), width=1)
}
// Band fills (1σ→2σ, 2σ→3σ) — signal intensity zones
if (showBandFills) {
// +1σ to +2σ fill
plotLine(
value=[band1, band2],
width=1,
colors=[transparency(bidColor, 10), transparency(bidColor, 10)],
colorIndex=0,
fill=true,
label=["+1σ", "+2σ"],
desc=["Bid-dominant moderate zone", ""]
)
// -1σ to -2σ fill
plotLine(
value=[-band1, -band2],
width=1,
colors=[transparency(askColor, 10), transparency(askColor, 10)],
colorIndex=0,
fill=true,
label=["-1σ", "-2σ"],
desc=["Ask-dominant moderate zone", ""]
)
}
// -----------------------------------------------------------------------------
// 11. PLOTTING — Z-Score & Signal with Fill
// -----------------------------------------------------------------------------
if (showZLine) {
plotLine(
value=zScore,
width=2,
colors=[regimeColor],
label=["Z-Score"],
desc=["Orderbook imbalance z-score (regime-colored)"]
)
}
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=[signalColor],
label=["Signal"],
desc=["Signal SMA of z-score (" + signalLen + ")"]
)
}
if (showFill && showZLine && showSignal) {
var zAboveSignal = zScore > signal
plotLine(
value=[zScore, signal],
width=1,
colors=[transparency(bidColor, 20), transparency(askColor, 20)],
colorIndex=zAboveSignal ? 0 : 1,
fill=true,
label=["Z-Score", "Signal"],
desc=["Fill between z-score and signal", ""]
)
}
// -----------------------------------------------------------------------------
// 12. PLOTTING — Z Histogram
// -----------------------------------------------------------------------------
if (showHistogram) {
var histBull = zHist >= 0
plotBar(
value=zHist,
colors=[transparency(bidColor, 60), transparency(askColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Z Momentum"],
desc=["Histogram of z-score minus signal SMA"]
)
}
// -----------------------------------------------------------------------------
// 13. PLOTTING — Individual Depth Z-Scores (optional)
// -----------------------------------------------------------------------------
if (showIndividual && bookAvailable) {
timeseries obiMean1 = sma(source=obi1, period=zLookback)
timeseries obiStd1 = stddev(source=obi1, period=zLookback)
timeseries z1 = obiStd1 > 0 ? (obi1 - obiMean1) / obiStd1 : 0
timeseries obiMean2 = sma(source=obi2, period=zLookback)
timeseries obiStd2 = stddev(source=obi2, period=zLookback)
timeseries z2 = obiStd2 > 0 ? (obi2 - obiMean2) / obiStd2 : 0
timeseries obiMean3 = sma(source=obi3, period=zLookback)
timeseries obiStd3 = stddev(source=obi3, period=zLookback)
timeseries z3 = obiStd3 > 0 ? (obi3 - obiMean3) / obiStd3 : 0
timeseries obiMean4 = sma(source=obi4, period=zLookback)
timeseries obiStd4 = stddev(source=obi4, period=zLookback)
timeseries z4 = obiStd4 > 0 ? (obi4 - obiMean4) / obiStd4 : 0
plotLine(
value=z1,
width=1,
colors=[transparency(bidColor, 50)],
label=["Z 1%"],
desc=["Z-score at 1% depth (top-of-book)"]
)
plotLine(
value=z2,
width=1,
colors=[transparency(bidColor, 40)],
label=["Z 2.5%"],
desc=["Z-score at 2.5% depth (near-term liquidity)"]
)
plotLine(
value=z3,
width=1,
colors=[transparency(askColor, 40)],
label=["Z 5%"],
desc=["Z-score at 5% depth (medium-term absorption)"]
)
plotLine(
value=z4,
width=1,
colors=[transparency(askColor, 50)],
label=["Z 10%"],
desc=["Z-score at 10% depth (deep book structural level)"]
)
}
// -----------------------------------------------------------------------------
// 14. PLOTTING — Signal Shapes
// -----------------------------------------------------------------------------
if (showShapes) {
if (crossUp2) {
plotShape(
value=zScore,
shape="triangleup",
colorIndex=bidColor,
width=3,
label=["+2σ Cross"],
desc=["Z-score crossed above +2σ — extreme bid imbalance (mean-reversion candidate)"]
)
}
if (crossDn2) {
plotShape(
value=zScore,
shape="triangledown",
colorIndex=askColor,
width=3,
label=["-2σ Cross"],
desc=["Z-score crossed below -2σ — extreme ask imbalance (mean-reversion candidate)"]
)
}
if (crossUp3) {
plotShape(
value=zScore,
shape="diamond",
colorIndex=bidColor,
width=4,
label=["+3σ Extreme"],
desc=["Z-score reached +3σ — extreme outlier (>99.7% probability)"]
)
}
if (crossDn3) {
plotShape(
value=zScore,
shape="diamond",
colorIndex=askColor,
width=4,
label=["-3σ Extreme"],
desc=["Z-score reached -3σ — extreme outlier (<0.3% probability)"]
)
}
if (zeroCrossUp) {
plotShape(
value=0,
shape="circle",
colorIndex=bidColor,
width=2,
label=["Zero Cross Up"],
desc=["Z-score crossed above zero — bid dominance emerging"]
)
}
if (zeroCrossDn) {
plotShape(
value=0,
shape="circle",
colorIndex=askColor,
width=2,
label=["Zero Cross Down"],
desc=["Z-score crossed below zero — ask dominance emerging"]
)
}
if (sigCrossUp) {
plotShape(
value=signal,
shape="arrowup",
colorIndex=bidColor,
width=2,
label=["Signal Cross Up"],
desc=["Z-score crossed above signal SMA — bullish momentum shift"]
)
}
if (sigCrossDn) {
plotShape(
value=signal,
shape="arrowdown",
colorIndex=askColor,
width=2,
label=["Signal Cross Down"],
desc=["Z-score crossed below signal SMA — bearish momentum shift"]
)
}
}
// -----------------------------------------------------------------------------
// 15. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = extremeRegime == 1 ? "EXTREME BID" : (extremeRegime == -1 ? "EXTREME ASK" : (regime == 1 ? "BID DOM" : (regime == -1 ? "ASK DOM" : "NEUTRAL")))
var regimeTextColor = regimeColor
plotTable(
data=[
["OB Z-Score Fork", regimeText],
["Z-Score", zScore[0]],
["Signal", signal[0]],
["Z Momentum", zHist[0]],
["Session High Z", sessionHighZ],
["Session Low Z", sessionLowZ],
["+2σ Crosses", cross2PosCount],
["-2σ Crosses", cross2NegCount],
["Regime Changes", regimeChangeCount]
],
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
)
}