Perfected FlowScript
Orderbook sum
Orderbook Sum V2 is indexed as 282_orderbook_sum.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
17.2 KB
Lines
397
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 305:9
Trigger
(showShapes) && (crossUp)
Value
smoothedImb
Deps
crossUp:var, showShapes:input
Bear Regime
line 315:9
Trigger
(showShapes) && (crossDn)
Value
smoothedImb
Deps
crossDn:var, showShapes:input
Extreme Bid
line 325:9
Trigger
(showShapes) && (extremeUp)
Value
smoothedImb
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 335:9
Trigger
(showShapes) && (extremeDn)
Value
smoothedImb
Deps
extremeDn:var, showShapes:input
Z-Extreme Bid
line 345:9
Trigger
(showShapes) && (zCrossUp)
Value
smoothedImb
Deps
showShapes:input, zCrossUp:var
Z-Extreme Ask
line 355:9
Trigger
(showShapes) && (zCrossDn)
Value
smoothedImb
Deps
showShapes:input, zCrossDn:var
282_orderbook_sum.flowscript
source path: kscripts/perfected/282_orderbook_sum.flowscript · sha256:09964878b2bc59cf1f13a9b4348e42bee0ba038f52746eb13c796d7f74021d30
//@version=2
// ============================================================================
// Orderbook Sum V2 — Multi-Depth Aggregate Bid/Ask Totals with Imbalance & Z-Score
// Author: I (@Iopl147u) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #Orderbook, #OB, #microstructure, #imbalance
//
// Multi-depth orderbook sum showing aggregate bid and ask liquidity totals,
// imbalance ratio, z-score normalization, and regime detection. Provides a
// comprehensive view of book depth composition and directional bias.
//
// FORMULA FOUNDATION:
// 1. Orderbook Sum: TotalBid = Σ bids_i, TotalAsk = Σ asks_i at depth level d
// 2. Imbalance Ratio: I = (TotalBid − TotalAsk) / (TotalBid + TotalAsk) ∈ [−1, +1]
// per Korean Derivatives Association (2015).
// 3. Multi-Depth Composite: Weighted average across depth bands (1%, 2.5%, 5%, 10%)
// per Xu, Gould & Howison (2019) multi-level OFI.
// 4. Z-Score: Z = (I − μ_I) / σ_I over rolling lookback; |Z| > 2 flags extremes.
// 5. Regime Segmentation: Sell-heavy, Neutral, Buy-heavy per Cartea et al. (2018).
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI = Σ(E_i × ΔP_i); linear relation
// between order flow imbalance and short-term price changes.
// • Korean Derivatives Association (2015), "Order Imbalance and Return
// Predictability". Full-book imbalance = (BuyQty − SellQty) / (BuyQty + SellQty);
// significant predictor of 5-, 10-, 20-min returns.
// • 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).
// • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
// Order Book", arXiv:1907.06230. Multi-level OFI improves short-horizon
// prediction with each additional depth level.
// • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price Predictor",
// Market Microstructure & Liquidity 2(1), 1650006. Queue imbalance as
// logistic predictor of next-tick direction.
// ============================================================================
define(
title="Orderbook Sum 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 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")
// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
// --- Z-Score ---
var useZscore = input(name="useZscore", type="boolean", defaultValue=true, label="Enable Z-Score Normalization", group="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 zThresh = input(name="zThresh", type="number", defaultValue=2.0, label="Z-Score Extreme Threshold", constraints={min: 1.0, max: 4.0, step: 0.1}, group="Z-Score")
// --- Thresholds & Regime ---
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 showSums = input(name="showSums", type="boolean", defaultValue=true, label="Show Bid/Ask Sum Lines", group="Display")
var showImbalance = input(name="showImbalance", type="boolean", defaultValue=true, label="Show Imbalance Line", group="Display")
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show Imbalance Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showZscore = input(name="showZscore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showRatio = input(name="showRatio", type="boolean", defaultValue=false, label="Show Bid/Ask Ratio", 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 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 book = source("orderbook", currentSymbol, currentExchange)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Multi-Depth Orderbook Sums
// ------------------------------------------------------------------------------
// Aggregate bid and ask liquidity at four depth bands per Cont et al. (2014)
// price-impact slope ∝ 1/depth.
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)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0
// Total sums per depth
var total1 = bids1 + asks1
var total2 = bids2 + asks2
var total3 = bids3 + asks3
var total4 = bids4 + asks4
// Depth-weighted composite totals (Xu, Gould & Howison 2019)
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 compositeTotalBids = wSum > 0 ? (w1 * bids1 + w2 * bids2 + w3 * bids3 + w4 * bids4) / wSum : 0.0
var compositeTotalAsks = wSum > 0 ? (w1 * asks1 + w2 * asks2 + w3 * asks3 + w4 * asks4) / wSum : 0.0
var compositeTotal = compositeTotalBids + compositeTotalAsks
// ------------------------------------------------------------------------------
// Imbalance Ratio Computation (Korean Derivatives Association 2015)
// ------------------------------------------------------------------------------
// Imbalance = (Bid − Ask) / (Bid + Ask) ∈ [−1, +1]
var imb1 = bookAvailable && total1 > 0 ? (bids1 - asks1) / total1 * 100.0 : 0.0
var imb2 = bookAvailable && total2 > 0 ? (bids2 - asks2) / total2 * 100.0 : 0.0
var imb3 = bookAvailable && total3 > 0 ? (bids3 - asks3) / total3 * 100.0 : 0.0
var imb4 = bookAvailable && total4 > 0 ? (bids4 - asks4) / total4 * 100.0 : 0.0
// Depth-weighted composite imbalance
var compositeImb = wSum > 0 ? (w1 * imb1 + w2 * imb2 + w3 * imb3 + w4 * imb4) / wSum : 0.0
// Bid/Ask ratio for 1% depth (diagnostic)
var ratio1 = bookAvailable && asks1 > 0 ? bids1 / asks1 : 1.0
// ------------------------------------------------------------------------------
// Z-Score Normalization
// ------------------------------------------------------------------------------
var imbMean = sma(source=compositeImb, period=zLookback)
var imbStd = stddev(source=compositeImb, period=zLookback)
var zScore = useZscore && imbStd > 0 ? (compositeImb - imbMean) / imbStd : 0.0
var zScoreSmooth = useZscore ? ema(zScore, smoothLen) : zScore
// ------------------------------------------------------------------------------
// Smoothing
// ------------------------------------------------------------------------------
var smoothedImb = ema(compositeImb, smoothLen)
var smoothedBid = ema(compositeTotalBids, smoothLen)
var smoothedAsk = ema(compositeTotalAsks, smoothLen)
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (smoothedImb >= bullThresh) {
regime = 1
} else if (smoothedImb <= bearThresh) {
regime = -1
}
if (smoothedImb >= extremeThresh) {
extremeRegime = 1
} else if (smoothedImb <= -extremeThresh) {
extremeRegime = -1
}
// Z-score extreme flags
var zExtremeBull = useZscore && zScoreSmooth >= zThresh
var zExtremeBear = useZscore && zScoreSmooth <= -zThresh
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighImb = -999999.0
static sessionLowImb = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (compositeImb > sessionHighImb) {
sessionHighImb = compositeImb
}
if (compositeImb < sessionLowImb) {
sessionLowImb = compositeImb
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1 || zExtremeBull) {
extremeBidCount = extremeBidCount + 1
} else if (extremeRegime == -1 || zExtremeBear) {
extremeAskCount = extremeAskCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types
// ------------------------------------------------------------------------------
// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)
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)
// Bid/Ask sum lines (scaled to fit panel; show as percentages of composite total)
if (showSums) {
var bidPct = compositeTotal > 0 ? (compositeTotalBids / compositeTotal) * 100.0 : 50.0
var askPct = compositeTotal > 0 ? (compositeTotalAsks / compositeTotal) * 100.0 : 50.0
var netPct = bidPct - askPct // Same as compositeImb but recalculated for clarity
plotLine(
value=netPct,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Net Imbalance %"],
desc=["Net bid-ask percentage (composite across all depths)"],
fill=true
)
}
// Imbalance line (smoothed, regime-colored)
if (showImbalance) {
plotLine(
value=smoothedImb,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Imbalance (smoothed)"],
desc=["Depth-weighted composite imbalance (EMA-smoothed)"]
)
}
// Raw imbalance histogram
if (showRawBars) {
plotBar(
value=compositeImb,
colors=[bidColor, askColor],
width=1,
label=["Imbalance Raw"],
desc=["Raw depth-weighted composite imbalance histogram"]
)
}
// Z-Score line
if (showZscore && useZscore) {
plotLine(
value=zScoreSmooth * 33.0, // Scale to roughly match imbalance range
width=2,
colors=[extremeBidColor, extremeAskColor, neutralColor],
colorIndex=zScoreSmooth >= zThresh ? 0 : (zScoreSmooth <= -zThresh ? 1 : 2),
label=["Z-Score (scaled)"],
desc=["Z-score normalized imbalance (scaled ×33). |Z|>2 = extreme."]
)
}
// Bid/Ask ratio line
if (showRatio) {
var ratioPct = (ratio1 - 1.0) * 100.0
plotLine(
value=ratioPct,
width=1,
colors=[bidColor, askColor, neutralColor],
colorIndex=ratioPct > 5.0 ? 0 : (ratioPct < -5.0 ? 1 : 2),
label=["Bid/Ask Ratio 1%"],
desc=["Bid/Ask ratio at 1% depth, centered at 0 (positive = bid heavy)"]
)
}
// Regime transition shapes
if (showShapes) {
var crossUp = smoothedImb >= bullThresh && !isnan(smoothedImb[1]) && smoothedImb[1] < bullThresh
var crossDn = smoothedImb <= bearThresh && !isnan(smoothedImb[1]) && smoothedImb[1] > bearThresh
var extremeUp = smoothedImb >= extremeThresh && !isnan(smoothedImb[1]) && smoothedImb[1] < extremeThresh
var extremeDn = smoothedImb <= -extremeThresh && !isnan(smoothedImb[1]) && smoothedImb[1] > -extremeThresh
var zCrossUp = useZscore && zScoreSmooth >= zThresh && !isnan(zScoreSmooth[1]) && zScoreSmooth[1] < zThresh
var zCrossDn = useZscore && zScoreSmooth <= -zThresh && !isnan(zScoreSmooth[1]) && zScoreSmooth[1] > -zThresh
if (crossUp) {
plotShape(
value=smoothedImb,
shape="triangleup",
color=extremeBidColor,
width=3,
label=["Bull Regime"],
desc=["Imbalance crossed into bullish regime (buy-heavy)"]
)
}
if (crossDn) {
plotShape(
value=smoothedImb,
shape="triangledown",
color=extremeAskColor,
width=3,
label=["Bear Regime"],
desc=["Imbalance crossed into bearish regime (sell-heavy)"]
)
}
if (extremeUp) {
plotShape(
value=smoothedImb,
shape="diamond",
color=extremeBidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid pressure — deep book buy-heavy imbalance"]
)
}
if (extremeDn) {
plotShape(
value=smoothedImb,
shape="diamond",
color=extremeAskColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask pressure — deep book sell-heavy imbalance"]
)
}
if (zCrossUp) {
plotShape(
value=smoothedImb,
shape="circle",
color=extremeBidColor,
width=2,
label=["Z-Extreme Bid"],
desc=["Z-score extreme bid event: statistically rare buy pressure"]
)
}
if (zCrossDn) {
plotShape(
value=smoothedImb,
shape="circle",
color=extremeAskColor,
width=2,
label=["Z-Extreme Ask"],
desc=["Z-score extreme ask event: statistically rare sell pressure"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regime == 1 ? extremeBidColor : (regime == -1 ? extremeAskColor : neutralColor)
plotTable(
data=[
["Orderbook Sum V2", regimeText],
["Imbalance", smoothedImb[0]],
["Z-Score", zScoreSmooth[0]],
["Total Bids", compositeTotalBids[0]],
["Total Asks", compositeTotalAsks[0]],
["Regime Changes", regimeChangeCount],
["Extreme Bids", extremeBidCount],
["Extreme Asks", extremeAskCount]
],
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
)
}