Perfected FlowScript
Orderbook Spread
Orderbook Spread V2 is indexed as 042_orderbook_spread.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
19.8 KB
Lines
414
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Wide Spread
line 374:9
Trigger
(showShapes) && (crossWide)
Value
smoothedCompositeRS
Deps
crossWide:var, showShapes:input
Tight Spread
line 384:9
Trigger
(showShapes) && (crossTight)
Value
smoothedCompositeRS
Deps
crossTight:var, showShapes:input
Extreme Spread
line 394:9
Trigger
(showShapes) && (crossExtreme)
Value
smoothedCompositeRS
Deps
crossExtreme:var, showShapes:input
Vol Spike
line 404:9
Trigger
(showShapes) && (volSpike)
Value
spreadVol
Deps
showShapes:input, volSpike:var
042_orderbook_spread.flowscript
source path: kscripts/perfected/042_orderbook_spread.flowscript · sha256:09cbf72254eb14e2806c46cb225b3dc8fa7b1e068ff2a454eac24feee8c9d66a
//@version=2
// ============================================================================
// Orderbook Spread V2 — Production-Quality Spread & Liquidity Microstructure Indicator
// Author: BackQuant (@BackQuant) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #orderbook, #spread, #ratio, #liquidity, #microstructure
//
// Multi-depth bid-ask spread analysis with spread normalization, dynamic spread
// regime detection, adverse selection cost estimation, and session-level tracking.
//
// FORMULA FOUNDATION:
// 1. Bid-Ask Spread: S = Ask − Bid (absolute spread in price units)
// 2. Relative Spread (normalized by mid-price): RS = S / MidPrice × 10000
// (basis points, comparable across assets), per Amihud & Mendelson (1986).
// 3. Spread Regime Classification:
// Tight (RS ≤ tightThresh), Normal, Wide (RS ≥ wideThresh),
// Extreme (RS ≥ extremeThresh) — per Handa, Schwartz & Tiwari (2002).
// 4. Adverse Selection Cost (proxy): λ = |ΔPrice| / Spread per Glosten & Milgrom (1985)
// and Handa et al. (2002). Higher λ → greater informed-trading component.
// 5. Spread Volatility (dynamic analysis): σ_S = rolling_std(S, window) per
// Chinese stock market spread dynamics research (2012).
// 6. Multi-depth spread comparison reveals liquidity structure: shallow spreads
// vs. deep spreads diverge when spoofing or layered liquidity is present.
//
// RESEARCH BASIS:
// • Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
// J. Financial Economics 17(2), 223–249. Spread as proxy for illiquidity;
// expected returns increase with spread. Normalization makes spreads
// comparable across assets and time periods.
// • Handa, Schwartz & Tiwari (2002), "Determinants of the Bid-Ask Spread",
// J. Financial Markets. Spread = f(valuation differences, adverse selection).
// Spread regimes classify liquidity state.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI and depth relationship;
// deeper books absorb order flow with smaller price impact.
// • Lipton, Pesavento & Sotiropoulos (2013), arXiv:1312.0514. Spread-normalized
// price moves: future price change / spread stays bounded.
// • Glosten & Milgrom (1985), "Bid, Ask and Transaction Prices in a Specialist
// Market with Heterogeneously Informed Traders", J. Financial Economics 14(1),
// 71–100. Adverse selection component drives spread width.
// • Chinese Stock Market Spread Dynamics (2012), Physica A 391(4), 1503–1511.
// Spread volatility exhibits long-range correlation; multifractal spread
// return dynamics inform regime detection.
// ============================================================================
define(
title="Orderbook Spread V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- 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 useDepthSpread = input(name="useDepthSpread", type="boolean", defaultValue=true, label="Show Depth-Normalized Spread", group="Depth")
var useRelativeSpread = input(name="useRelativeSpread", type="boolean", defaultValue=true, label="Show Relative Spread (bps)", group="Depth")
// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var smoothComposite = input(name="smoothComposite", type="boolean", defaultValue=true, label="Smooth Composite Spread", group="Smoothing")
var volWindow = input(name="volWindow", type="number", defaultValue=20, label="Spread Volatility Window", constraints={min: 5, max: 100, step: 1}, group="Smoothing")
// --- Thresholds & Regime ---
var tightThresh = input(name="tightThresh", type="number", defaultValue=5.0, label="Tight Spread Threshold (bps)", constraints={min: 0.5, max: 50.0, step: 0.5}, group="Thresholds")
var wideThresh = input(name="wideThresh", type="number", defaultValue=25.0, label="Wide Spread Threshold (bps)", constraints={min: 5.0, max: 200.0, step: 1.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=50.0, label="Extreme Spread Threshold (bps)", constraints={min: 10.0, max: 500.0, step: 1.0}, group="Thresholds")
// --- Adverse Selection ---
var showAdverseSel = input(name="showAdverseSel", type="boolean", defaultValue=true, label="Show Adverse Selection Proxy", group="Adverse Selection")
var adverseLen = input(name="adverseLen", type="number", defaultValue=10, label="Adverse Selection EMA Length", constraints={min: 3, max: 50, step: 1}, group="Adverse Selection")
// --- Display ---
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showRawSpread = input(name="showRawSpread", type="boolean", defaultValue=false, label="Show Raw Spread (price units)", group="Display")
var showRelative = input(name="showRelative", type="boolean", defaultValue=true, label="Show Relative Spread (bps)", group="Display")
var showSpreadVol = input(name="showSpreadVol", type="boolean", defaultValue=true, label="Show Spread Volatility", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Spreads", group="Display")
// --- Colors ---
var tightColor = input(name="tightColor", type="color", defaultValue="#26a69a", label="Tight Spread Color", group="Colors")
var normalColor = input(name="normalColor", type="color", defaultValue="#42a5f5", label="Normal Spread Color", group="Colors")
var wideColor = input(name="wideColor", type="color", defaultValue="#ff7043", label="Wide Spread Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ef5350", label="Extreme Spread Color", group="Colors")
var adverseColor = input(name="adverseColor", type="color", defaultValue="#ab47bc", label="Adverse Selection Color", group="Colors")
var volColor = input(name="volColor", type="color", defaultValue="#ffca28", label="Spread Volatility Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)
// NaN guard — prevent execution before data is loaded (Cont et al. 2014 data-integrity best practice)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Book Aggregation — Actual L2 depth data
// ------------------------------------------------------------------------------
// CRITICAL: Using real orderbook depth aggregation rather than synthetic proxies.
// The original script used price-action proxies (highest(high, d) - close) which
// are fundamentally flawed for spread analysis because they ignore the actual
// resting liquidity structure. We now use sumBids/sumAsks per kScript API.
//
// Research basis: Cont, Kukanov & Stoikov (2014) showed that actual orderbook
// depth absorbs order flow with slope ∝ 1/depth. Synthetic proxies cannot
// capture this relationship.
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 check — prevents NaN/undefined propagation (Gould & Bonart 2016 robustness)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0
// ------------------------------------------------------------------------------
// Spread Computation (Absolute, Relative, and Depth-Normalized)
// ------------------------------------------------------------------------------
// 1. Absolute Spread: S = Ask − Bid (price units)
// 2. Relative Spread: RS = (Ask − Bid) / MidPrice × 10000 (basis points)
// per Amihud & Mendelson (1986) spread normalization.
// 3. Depth-Normalized Spread: S / (Bid + Ask) × 100 (similar to OBI scaling)
var midPrice = (px + px) / 2 // Using close as mid proxy; for true mid: (bestBid + bestAsk)/2
var midSafe = midPrice > 0 ? midPrice : px
var spread1 = bookAvailable ? asks1 - bids1 : 0.0
var spread2 = bookAvailable ? asks2 - bids2 : 0.0
var spread3 = bookAvailable ? asks3 - bids3 : 0.0
var spread4 = bookAvailable ? asks4 - bids4 : 0.0
var relSpread1 = bookAvailable && midSafe > 0 ? (asks1 - bids1) / midSafe * 10000.0 : 0.0
var relSpread2 = bookAvailable && midSafe > 0 ? (asks2 - bids2) / midSafe * 10000.0 : 0.0
var relSpread3 = bookAvailable && midSafe > 0 ? (asks3 - bids3) / midSafe * 10000.0 : 0.0
var relSpread4 = bookAvailable && midSafe > 0 ? (asks4 - bids4) / midSafe * 10000.0 : 0.0
var depthNorm1 = bookAvailable && (bids1 + asks1) > 0 ? (asks1 - bids1) / (bids1 + asks1) * 100.0 : 0.0
var depthNorm2 = bookAvailable && (bids2 + asks2) > 0 ? (asks2 - bids2) / (bids2 + asks2) * 100.0 : 0.0
var depthNorm3 = bookAvailable && (bids3 + asks3) > 0 ? (asks3 - bids3) / (bids3 + asks3) * 100.0 : 0.0
var depthNorm4 = bookAvailable && (bids4 + asks4) > 0 ? (asks4 - bids4) / (bids4 + asks4) * 100.0 : 0.0
// Composite relative spread (average of depth bands, depth-decay weighted)
var w1 = 1.0
var w2 = 0.75
var w3 = 0.5625
var w4 = 0.421875
var wSum = w1 + w2 + w3 + w4
var compositeRS = wSum > 0 ? (w1 * relSpread1 + w2 * relSpread2 + w3 * relSpread3 + w4 * relSpread4) / wSum : 0.0
var compositeDN = wSum > 0 ? (w1 * depthNorm1 + w2 * depthNorm2 + w3 * depthNorm3 + w4 * depthNorm4) / wSum : 0.0
// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothedRS1 = ema(relSpread1, smoothLen)
var smoothedRS2 = ema(relSpread2, smoothLen)
var smoothedRS3 = ema(relSpread3, smoothLen)
var smoothedRS4 = ema(relSpread4, smoothLen)
var smoothedCompositeRS = smoothComposite ? ema(compositeRS, smoothLen) : compositeRS
var smoothedCompositeDN = smoothComposite ? ema(compositeDN, smoothLen) : compositeDN
// ------------------------------------------------------------------------------
// Spread Volatility — Dynamic Spread Analysis (Physica A 2012)
// ------------------------------------------------------------------------------
// Spread volatility exhibits long-range correlation and informs regime shifts.
// σ_S = rolling standard deviation of relative spread.
var spreadMean = sma(smoothedCompositeRS, volWindow)
var spreadDev = stdev(smoothedCompositeRS, volWindow)
var spreadVol = spreadDev > 0 ? spreadDev : 0.0
var spreadZ = spreadDev > 0 ? (smoothedCompositeRS - spreadMean) / spreadDev : 0.0
// ------------------------------------------------------------------------------
// Adverse Selection Cost Estimation (Glosten & Milgrom 1985; Handa et al. 2002)
// ------------------------------------------------------------------------------
// λ = |price change| / spread — proxy for information content in trades.
// Higher λ indicates greater adverse selection; market makers widen spreads.
var priceChange = math.abs(px - px[1])
var adverseSel = smoothedCompositeRS > 0 ? priceChange / (smoothedCompositeRS / 10000.0 * midSafe) : 0.0
var adverseSelEma = ema(adverseSel, adverseLen)
// ------------------------------------------------------------------------------
// Regime Detection (Handa, Schwartz & Tiwari 2002 spread regime model)
// ------------------------------------------------------------------------------
// Tight: RS ≤ tightThresh (high liquidity, low adverse selection)
// Normal: tightThresh < RS < wideThresh
// Wide: RS ≥ wideThresh (low liquidity, information asymmetry)
// Extreme: RS ≥ extremeThresh (market stress, potential halts)
var spreadRegime = 0 // 0 = tight, 1 = normal, 2 = wide, 3 = extreme
var extremeRegime = 0 // 0 = normal, 1 = extreme spike
if (smoothedCompositeRS >= extremeThresh) {
spreadRegime = 3
extremeRegime = 1
} else if (smoothedCompositeRS >= wideThresh) {
spreadRegime = 2
} else if (smoothedCompositeRS <= tightThresh) {
spreadRegime = 0
} else {
spreadRegime = 1
}
// Volatility regime: z-score > 2 = statistically unusual spread widening
var volRegime = spreadZ >= 2.0 ? 1 : (spreadZ <= -2.0 ? -1 : 0)
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks session spread extremes, regime transitions, and spike counts.
static lastRegime = -1
static regimeChangeCount = 0
static sessionHighSpread = 0.0
static sessionLowSpread = 999999.0
static extremeSpikeCount = 0
static tightCount = 0
static wideCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (smoothedCompositeRS > sessionHighSpread) {
sessionHighSpread = smoothedCompositeRS
}
if (smoothedCompositeRS < sessionLowSpread && smoothedCompositeRS > 0) {
sessionLowSpread = smoothedCompositeRS
}
if (lastRegime != spreadRegime) {
lastRegime = spreadRegime
regimeChangeCount = regimeChangeCount + 1
}
if (spreadRegime == 3) {
extremeSpikeCount = extremeSpikeCount + 1
} else if (spreadRegime == 0) {
tightCount = tightCount + 1
} else if (spreadRegime == 2) {
wideCount = wideCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines — zero line and configurable threshold zones
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
hline(value=tightThresh, color=opacity(tightColor, 30), width=1)
hline(value=wideThresh, color=opacity(wideColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeColor, 20), width=1)
}
// Raw composite relative spread as histogram bars (regime-colored)
if (showRelative) {
var spreadColor = spreadRegime == 0 ? tightColor : (spreadRegime == 1 ? normalColor : (spreadRegime == 2 ? wideColor : extremeColor))
plotBar(
value=smoothedCompositeRS,
colors=[tightColor, normalColor, wideColor, extremeColor],
colorIndex=spreadRegime,
width=1,
label=["Composite Spread (bps)"],
desc=["Depth-weighted composite relative spread in basis points. Regime: tight/normal/wide/extreme."]
)
}
// Smoothed composite relative spread line with regime-coded fill area
if (showRelative) {
plotLine(
value=smoothedCompositeRS,
width=2,
colors=[tightColor, normalColor, wideColor, extremeColor],
colorIndex=spreadRegime,
label=["Composite Spread"],
desc=["Depth-weighted composite relative spread (EMA-smoothed). Regime: tight/normal/wide/extreme."],
fill=true
)
}
// Depth-normalized composite spread (OBI-style scaling)
if (useDepthSpread) {
plotLine(
value=smoothedCompositeDN,
width=1,
colors=[opacity(tightColor, 50), opacity(normalColor, 50), opacity(wideColor, 50), opacity(extremeColor, 50)],
colorIndex=spreadRegime,
label=["Depth-Normalized Spread"],
desc=["Composite spread normalized by depth: (ask−bid)/(ask+bid) × 100. Comparable to OBI scaling."]
)
}
// Individual depth spread lines (optional, for granular liquidity structure analysis)
if (showIndividual) {
plotLine(
value=smoothedRS1,
width=1,
colors=[opacity(tightColor, 60)],
label=["Spread 1%"],
desc=["Relative spread at 1% depth (shallow book, top-of-book)"]
)
plotLine(
value=smoothedRS2,
width=1,
colors=[opacity(normalColor, 60)],
label=["Spread 2.5%"],
desc=["Relative spread at 2.5% depth (near-term liquidity)"]
)
plotLine(
value=smoothedRS3,
width=1,
colors=[opacity(wideColor, 60)],
label=["Spread 5%"],
desc=["Relative spread at 5% depth (medium-term absorption)"]
)
plotLine(
value=smoothedRS4,
width=1,
colors=[opacity(extremeColor, 60)],
label=["Spread 10%"],
desc=["Relative spread at 10% depth (deep book, structural level)"]
)
}
// Spread volatility line (dynamic spread analysis)
if (showSpreadVol) {
plotLine(
value=spreadVol,
width=1,
colors=[volColor],
label=["Spread Volatility"],
desc=["Rolling standard deviation of composite spread. Long-range correlation informs regime shifts."]
)
}
// Adverse selection cost proxy (Glosten & Milgrom 1985)
if (showAdverseSel) {
plotLine(
value=adverseSelEma,
width=1,
colors=[adverseColor],
label=["Adverse Selection λ"],
desc=["Adverse selection proxy: |ΔPrice| / Spread. Higher λ → greater informed trading."]
)
}
// Regime transition shapes — spread spike and regime change detection
if (showShapes) {
var crossWide = smoothedCompositeRS >= wideThresh && !isnan(smoothedCompositeRS[1]) && smoothedCompositeRS[1] < wideThresh
var crossTight = smoothedCompositeRS <= tightThresh && !isnan(smoothedCompositeRS[1]) && smoothedCompositeRS[1] > tightThresh
var crossExtreme = smoothedCompositeRS >= extremeThresh && !isnan(smoothedCompositeRS[1]) && smoothedCompositeRS[1] < extremeThresh
var volSpike = spreadZ >= 2.0 && !isnan(spreadZ[1]) && spreadZ[1] < 2.0
if (crossWide) {
plotShape(
value=smoothedCompositeRS,
shape="triangledown",
color=wideColor,
width=3,
label=["Wide Spread"],
desc=["Spread crossed into wide regime — liquidity deteriorating, possible adverse selection."]
)
}
if (crossTight) {
plotShape(
value=smoothedCompositeRS,
shape="triangleup",
color=tightColor,
width=3,
label=["Tight Spread"],
desc=["Spread crossed into tight regime — high liquidity, low adverse selection."]
)
}
if (crossExtreme) {
plotShape(
value=smoothedCompositeRS,
shape="diamond",
color=extremeColor,
width=4,
label=["Extreme Spread"],
desc=["Extreme spread detected — market stress, potential halt or news event."]
)
}
if (volSpike) {
plotShape(
value=spreadVol,
shape="flag",
color=volColor,
width=3,
label=["Vol Spike"],
desc=["Spread volatility spike (z ≥ 2) — statistically unusual spread widening."]
)
}
}