Perfected FlowScript
OB Ratio for 1 side
OB Ratio for 1 Side V2 Perfected is indexed as 349_ob_ratio_for_1_side.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
18.0 KB
Lines
393
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Heavy Regime
line 333:9
Trigger
(showShape) && (crossUpHeavy)
Value
selectedRatio
Deps
crossUpHeavy:var, showShape:input
Light Regime
line 343:9
Trigger
(showShape) && (crossDnLight)
Value
selectedRatio
Deps
crossDnLight:var, showShape:input
Extreme Heavy
line 353:9
Trigger
(showShape) && (crossUpExtreme)
Value
selectedRatio
Deps
crossUpExtreme:var, showShape:input
Extreme Light
line 363:9
Trigger
(showShape) && (crossDnExtreme)
Value
selectedRatio
Deps
crossDnExtreme:var, showShape:input
Z+ Cross
line 373:9
Trigger
(showShape) && (zCrossUp)
Value
ratioZS
Deps
showShape:input, zCrossUp:var
Z− Cross
line 383:9
Trigger
(showShape) && (zCrossDn)
Value
ratioZS
Deps
showShape:input, zCrossDn:var
349_ob_ratio_for_1_side.flowscript
source path: kscripts/perfected/349_ob_ratio_for_1_side.flowscript · sha256:f251750556ba8ab479cd52a38c5c58845792cd45c0d8395b282999e9860c6565
//@version=2
// ============================================================================
// OB Ratio for 1 Side V2 — Production-Quality Single-Side Orderbook Ratio
// Author: I (@Iopl147u) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #ratio, #microstructure, #OBI, #regime
//
// Single-side orderbook ratio measuring the relative depth or pressure on one
// side of the limit order book (bid or ask), with z-score normalization,
// regime detection, color-coded histogram, and shape markers for threshold
// crossings. The ratio is normalized to [0, 1] and then z-scored for
// statistical comparison across time and assets.
//
// FORMULA FOUNDATION:
// 1. Single-Side Ratio: Ratio_Side = SideDepth / TotalDepth ∈ [0, 1]
// per Cont, Kukanov & Stoikov (2014). A bid ratio > 0.5 indicates buy-heavy
// book; ask ratio > 0.5 indicates sell-heavy book.
// 2. Z-Score Normalization: z̄ = (Ratio − μ_Ratio) / σ_Ratio per Zhao & Palomar (2018).
// Entry thresholds at ±1σ, ±2σ for statistical clarity and cross-asset comparability.
// 3. Regime Segmentation: Light (< 0.4), Neutral (0.4–0.6), Heavy (> 0.6)
// per Cartea, Donnelly & Jaimungal (2018) three-segment model adapted to
// single-side ratios.
// 4. Order Imbalance and Return Predictability: Korean Derivatives Association (2015).
// Higher buy-minus-sell ratios predict higher future returns over 5/10/20-min.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI segments: Sell-heavy (−1 to −1/3),
// Neutral (−1/3 to 1/3), Buy-heavy (1/3 to 1). Single-side ratio is a direct
// component of this broader imbalance framework.
// • Korean Derivatives Association (2015), "Order Imbalance and Return
// Predictability". Order imbalance = (buy_orderbook − sell_orderbook) /
// (buy_orderbook + sell_orderbook). Higher buy ratios predict higher future returns.
// • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", Appl. Math. Finance 25(1), 1–35. Segmented volume
// imbalance into three regimes; positive price moves preceded by buy-heavy books.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// z̄ₜ = (zₜ − μz) / σz; entry thresholds at d × σz. Enables z-score normalization
// of ratio signals for cross-asset comparability.
// • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price Predictor",
// Market Microstructure & Liquidity 2(1), 1650006. Queue imbalance logistic
// regression for next-tick direction prediction.
// ============================================================================
define(
title="OB Ratio for 1 Side V2 Perfected",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Side Configuration ---
var side = input(name="side", type="select", defaultValue="bid", label="Show Side", options=["bid", "ask"], group="Side")
// --- 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 Configuration ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 500, step: 5}, group="Z-Score")
var zSmooth = input(name="zSmooth", type="number", defaultValue=3, label="Z-Score EMA Smoothing", constraints={min: 1, max: 50, step: 1}, group="Z-Score")
// --- Regime Thresholds ---
var heavyThresh = input(name="heavyThresh", type="number", defaultValue=0.6, label="Heavy Ratio Threshold", constraints={min: 0.51, max: 0.95, step: 0.01}, group="Thresholds")
var lightThresh = input(name="lightThresh", type="number", defaultValue=0.4, label="Light Ratio Threshold", constraints={min: 0.05, max: 0.49, step: 0.01}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=0.75, label="Extreme Ratio Threshold", constraints={min: 0.6, max: 0.99, step: 0.01}, group="Thresholds")
// --- Display ---
var showRatio = input(name="showRatio", type="boolean", defaultValue=true, label="Show Ratio Line", group="Display")
var showRawRatio = input(name="showRawRatio", type="boolean", defaultValue=true, label="Show Raw Ratio Histogram", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showShape = input(name="showShape", type="boolean", defaultValue=true, label="Show Threshold Shapes", group="Display")
var showBothSides = input(name="showBothSides", type="boolean", defaultValue=false, label="Show Both Sides (context)", 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
// ------------------------------------------------------------------------------
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]) || isnan(book[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
// CRITICAL: The kScript API accepts depth as a float percentage (e.g., 1.0 = 1%).
// Research basis: Cont, Kukanov & Stoikov (2014) showed price impact slope
// is inversely proportional to depth; deeper books absorb imbalance with
// smaller price moves. The multi-depth bands (1%, 2.5%, 5%, 10%) directly
// operationalize this finding.
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
// ------------------------------------------------------------------------------
// Single-Side Ratio Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// BidRatio = BidDepth / (BidDepth + AskDepth) ∈ [0, 1]
// AskRatio = AskDepth / (BidDepth + AskDepth) ∈ [0, 1]
// A ratio > 0.5 indicates dominance of that side.
// Per Korean Derivatives Association (2015): higher bid ratios predict higher future returns.
var total1 = bids1 + asks1
var total2 = bids2 + asks2
var total3 = bids3 + asks3
var total4 = bids4 + asks4
var bidRatio1 = bookAvailable && total1 > 0 ? bids1 / total1 : 0.5
var bidRatio2 = bookAvailable && total2 > 0 ? bids2 / total2 : 0.5
var bidRatio3 = bookAvailable && total3 > 0 ? bids3 / total3 : 0.5
var bidRatio4 = bookAvailable && total4 > 0 ? bids4 / total4 : 0.5
var askRatio1 = bookAvailable && total1 > 0 ? asks1 / total1 : 0.5
var askRatio2 = bookAvailable && total2 > 0 ? asks2 / total2 : 0.5
var askRatio3 = bookAvailable && total3 > 0 ? asks3 / total3 : 0.5
var askRatio4 = bookAvailable && total4 > 0 ? asks4 / total4 : 0.5
// ------------------------------------------------------------------------------
// Depth-Weighted Composite Ratio (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level OFI with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3,4.
// Composite = Σ w_i × Ratio_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 compositeBidRatio = wSum > 0 ? (w1 * bidRatio1 + w2 * bidRatio2 + w3 * bidRatio3 + w4 * bidRatio4) / wSum : 0.5
var compositeAskRatio = wSum > 0 ? (w1 * askRatio1 + w2 * askRatio2 + w3 * askRatio3 + w4 * askRatio4) / wSum : 0.5
// Selected side ratio (the primary indicator value)
var selectedRatio = side == "bid" ? compositeBidRatio : compositeAskRatio
var oppositeRatio = side == "bid" ? compositeAskRatio : compositeBidRatio
// ------------------------------------------------------------------------------
// Z-Score Normalization of the Selected-Side Ratio (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z̄ = (Ratio − μ_Ratio) / σ_Ratio over rolling lookback.
// Surfaces when the single-side dominance is statistically extreme relative to recent history.
timeseries ratioMean = sma(selectedRatio, zLookback)
timeseries ratioStd = stdev(selectedRatio, zLookback)
// NaN guard: if std is zero or undefined, z-score is zero (no deviation)
var ratioZ = (!isnan(ratioMean) && !isnan(ratioStd) && ratioStd > 0) ? (selectedRatio - ratioMean) / ratioStd : 0.0
timeseries ratioZS = ema(ratioZ, zSmooth)
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 adapted to single-side ratios)
// ------------------------------------------------------------------------------
// Segmented into three regimes based on the raw ratio:
// Heavy: ratio ≥ heavyThresh (dominant side is very strong)
// Neutral: lightThresh < ratio < heavyThresh
// Light: ratio ≤ lightThresh (dominant side is weak)
// Also tracks extreme: ratio ≥ extremeThresh or ratio ≤ (1 − extremeThresh)
var regime = 0 // 0 = neutral, 1 = heavy, -1 = light
var extremeRegime = 0 // 0 = normal, 1 = extreme heavy, -1 = extreme light
if (selectedRatio >= heavyThresh) {
regime = 1
} else if (selectedRatio <= lightThresh) {
regime = -1
}
if (selectedRatio >= extremeThresh) {
extremeRegime = 1
} else if (selectedRatio <= (1.0 - extremeThresh)) {
extremeRegime = -1
}
// Z-score regime (for color-coding the z-score line)
var zRegime = 0
if (ratioZS >= 1.0) {
zRegime = 1
} else if (ratioZS <= -1.0) {
zRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks extreme-event counts, session ratio extremes, and regime transitions.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRatio = -999999.0
static sessionLowRatio = 999999.0
static extremeHeavyCount = 0
static extremeLightCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (selectedRatio > sessionHighRatio) {
sessionHighRatio = selectedRatio
}
if (selectedRatio < sessionLowRatio) {
sessionLowRatio = selectedRatio
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeHeavyCount = extremeHeavyCount + 1
} else if (extremeRegime == -1) {
extremeLightCount = extremeLightCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Horizontal guide lines — 0.5 midpoint and configurable threshold zones
hline(value=0.5, color="#ffffff30", width=1)
var contextColor = side == "bid" ? bidColor : askColor
var contextExtremeColor = side == "bid" ? extremeBidColor : extremeAskColor
var contextOppColor = side == "bid" ? askColor : bidColor
// Threshold guide lines
hline(value=heavyThresh, color=opacity(contextColor, 30), width=1)
hline(value=lightThresh, color=opacity(contextOppColor, 30), width=1)
// Raw ratio as color-coded histogram (centered at 0.5)
if (showRawRatio) {
var histValue = (selectedRatio - 0.5) * 2.0 // normalize to [-1, +1] for histogram
var histColor = regime == 1 ? contextColor : (regime == -1 ? contextOppColor : neutralColor)
plotBar(
value=histValue,
colors=[histColor],
width=1,
label=["Ratio Histogram"],
desc=["Single-side orderbook ratio histogram centered at 0 (positive = " + side + "-heavy)"]
)
}
// Smoothed ratio line with regime-coded fill area
if (showRatio) {
plotLine(
value=selectedRatio,
width=2,
colors=[contextColor, contextOppColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Ratio Line"],
desc=["Depth-weighted composite " + side + " ratio. Regime: heavy/neutral/light."],
fill=true
)
}
// Z-score line (normalized ratio deviation)
if (showZScore) {
var zColor = zRegime == 1 ? contextColor : (zRegime == -1 ? contextOppColor : neutralColor)
plotLine(
value=ratioZS,
width=2,
colors=[zColor],
label=["Ratio Z-Score"],
desc=["Z-score of composite " + side + " ratio: (Ratio − SMA) / StdDev"]
)
hline(value=1.0, color=opacity(contextColor, 20), width=1)
hline(value=-1.0, color=opacity(contextOppColor, 20), width=1)
hline(value=2.0, color=opacity(contextExtremeColor, 15), width=1)
hline(value=-2.0, color=opacity(contextExtremeColor, 15), width=1)
}
// Both sides context (optional, for comparative analysis)
if (showBothSides) {
plotLine(
value=compositeBidRatio,
width=1,
colors=[opacity(bidColor, 40)],
label=["Bid Ratio"],
desc=["Composite bid ratio across all depth bands (context)"]
)
plotLine(
value=compositeAskRatio,
width=1,
colors=[opacity(askColor, 40)],
label=["Ask Ratio"],
desc=["Composite ask ratio across all depth bands (context)"]
)
}
// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
if (showShape) {
var crossUpHeavy = selectedRatio >= heavyThresh && !isnan(selectedRatio[1]) && selectedRatio[1] < heavyThresh
var crossDnLight = selectedRatio <= lightThresh && !isnan(selectedRatio[1]) && selectedRatio[1] > lightThresh
var crossUpExtreme = selectedRatio >= extremeThresh && !isnan(selectedRatio[1]) && selectedRatio[1] < extremeThresh
var crossDnExtreme = selectedRatio <= (1.0 - extremeThresh) && !isnan(selectedRatio[1]) && selectedRatio[1] > (1.0 - extremeThresh)
var zCrossUp = ratioZS >= 1.0 && !isnan(ratioZS[1]) && ratioZS[1] < 1.0
var zCrossDn = ratioZS <= -1.0 && !isnan(ratioZS[1]) && ratioZS[1] > -1.0
if (crossUpHeavy) {
plotShape(
value=selectedRatio,
shape="triangleup",
color=contextColor,
width=3,
label=["Heavy Regime"],
desc=[side + " ratio crossed into heavy regime (" + side + "-dominant book)"]
)
}
if (crossDnLight) {
plotShape(
value=selectedRatio,
shape="triangledown",
color=contextOppColor,
width=3,
label=["Light Regime"],
desc=[side + " ratio crossed into light regime (" + side + "-weak book)"]
)
}
if (crossUpExtreme) {
plotShape(
value=selectedRatio,
shape="diamond",
color=contextExtremeColor,
width=4,
label=["Extreme Heavy"],
desc=["Extreme " + side + " dominance detected — ratio ≥ " + extremeThresh]
)
}
if (crossDnExtreme) {
plotShape(
value=selectedRatio,
shape="diamond",
color=contextExtremeColor,
width=4,
label=["Extreme Light"],
desc=["Extreme " + side + " weakness detected — ratio ≤ " + (1.0 - extremeThresh)]
)
}
if (zCrossUp) {
plotShape(
value=ratioZS,
shape="circle",
color=contextColor,
width=2,
label=["Z+ Cross"],
desc=["Z-score crossed above +1σ — statistically significant " + side + " strength"]
)
}
if (zCrossDn) {
plotShape(
value=ratioZS,
shape="circle",
color=contextOppColor,
width=2,
label=["Z− Cross"],
desc=["Z-score crossed below -1σ — statistically significant " + side + " weakness"]
)
}
}