Perfected FlowScript
Bid/Ask Ratio Oscillator
Bid/Ask Ratio Oscillator V2 is indexed as 235_bid_ask_ratio_oscillator.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
16.4 KB
Lines
364
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 324:9
Trigger
(showShapes) && (crossUp)
Value
composite
Deps
crossUp:var, showShapes:input
Bear Regime
line 334:9
Trigger
(showShapes) && (crossDn)
Value
composite
Deps
crossDn:var, showShapes:input
Extreme Bid
line 344:9
Trigger
(showShapes) && (extremeUp)
Value
composite
Deps
extremeUp:var, showShapes:input
Extreme Ask
line 354:9
Trigger
(showShapes) && (extremeDn)
Value
composite
Deps
extremeDn:var, showShapes:input
235_bid_ask_ratio_oscillator.flowscript
source path: kscripts/perfected/235_bid_ask_ratio_oscillator.flowscript · sha256:d0aa5b69bca6013be1a4ee7d6bc026efb9dc37dbb991b9d59d18a4fc9604fbca
//@version=2
// ============================================================================
// Bid/Ask Ratio Oscillator V2 — Multi-Depth Orderbook Liquidity Dominance
// Author: B (@buyanyjeansnecessary) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #orderbook, #liquidity, #microstructure, #obi, #ratio
//
// Production-quality bid/ask depth ratio oscillator with multi-depth
// aggregation, z-score normalization, regime detection, and session-level
// static tracking. Oscillates around a centerline to show real-time
// liquidity dominance with regime-coded visualizations.
//
// FORMULA FOUNDATION:
// 1. Bid/Ask Ratio: R = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// per Gould & Bonart (2016) queue imbalance framework.
// 2. Multi-Depth Composite: weighted average across depth bands with
// inverse-distance weighting (Xu, Gould & Howison 2019).
// 3. Z-Score Normalization: Z_t = (R_t − μ_t) / σ_t for regime-relative
// readings (Cartea, Donnelly & Jaimungal 2018).
// 4. Regime Segmentation: Bullish (≥ +1/3), Neutral (−1/3, +1/3),
// Bearish (≤ −1/3) per Cartea et al. (2018) three-segment model.
//
// RESEARCH BASIS:
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. OFI = bidVol − askVol drives
// short-term price changes; slope ∝ 1/depth. DOI: 10.1093/jjfinec/nbt003
// • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
// Predictor", Market Microstructure & Liquidity 2(1), 1650006. Queue
// imbalance predicts next-tick direction with significant classification
// improvement. DOI: 10.1142/S2382626616500069
// • Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
// JFE 17(2), 223–249. Spread affects expected returns; liquidity asymmetry
// is priced. DOI: 10.1016/0304-405X(86)90065-6
// • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
// Limit Order Book", arXiv:1907.06230. Multi-level OFI with decaying
// weights improves short-horizon prediction vs. top-of-book alone.
// • 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).
// ============================================================================
define(
title="Bid/Ask Ratio Oscillator 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=14.0, label="Smoothing Length", constraints={min: 1.0, max: 50.0, step: 1.0}, group="Smoothing")
var useEMA = input(name="useEMA", type="boolean", defaultValue=false, label="Use EMA Smoothing", group="Smoothing")
// --- Z-Score ---
var zWindow = input(name="zWindow", type="number", defaultValue=50.0, label="Z-Score Window (bars)", constraints={min: 20.0, max: 200.0, step: 5.0}, group="Z-Score")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Z-Score")
// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=0.333, label="Bullish Regime Threshold", constraints={min: 0.05, max: 0.95, step: 0.05}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-0.333, label="Bearish Regime Threshold", constraints={min: -0.95, max: -0.05, step: 0.05}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=0.7, label="Extreme Imbalance Threshold", constraints={min: 0.5, max: 0.95, step: 0.05}, group="Thresholds")
// --- Display ---
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Ratio", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show 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")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", 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")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#42a5f5", label="Z-Score 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
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Order Book Aggregation (Cont et al. 2014 multi-depth framework)
// ------------------------------------------------------------------------------
// The kScript API accepts depth as a float percentage (e.g., 1.0 = 1%,
// 2.5 = 2.5%). We aggregate across four depth bands to capture shallow
// through deep book structure 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 bids4 = sumBids(book, depth4)
var asks4 = sumAsks(book, depth4)
// Book availability check — prevents NaN/undefined propagation
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0
// ------------------------------------------------------------------------------
// Bid/Ask Ratio Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// R = (Bid − Ask) / (Bid + Ask) ∈ [−1, +1]
// Formula from Gould & Bonart (2016) queue imbalance framework.
var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3
var denom4 = bids4 + asks4
var ratio1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 : 0.0
var ratio2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 : 0.0
var ratio3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 : 0.0
var ratio4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 : 0.0
// ------------------------------------------------------------------------------
// 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 × R_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 compositeRaw = wSum > 0 ? (w1 * ratio1 + w2 * ratio2 + w3 * ratio3 + w4 * ratio4) / wSum : 0.0
// ------------------------------------------------------------------------------
// Smoothing (EMA or SMA per user preference)
// ------------------------------------------------------------------------------
var composite = useEMA ? ema(compositeRaw, smoothLen) : sma(compositeRaw, smoothLen)
var smoothed1 = useEMA ? ema(ratio1, smoothLen) : sma(ratio1, smoothLen)
var smoothed2 = useEMA ? ema(ratio2, smoothLen) : sma(ratio2, smoothLen)
var smoothed3 = useEMA ? ema(ratio3, smoothLen) : sma(ratio3, smoothLen)
var smoothed4 = useEMA ? ema(ratio4, smoothLen) : sma(ratio4, smoothLen)
// ------------------------------------------------------------------------------
// Z-Score Normalization (Cartea et al. 2018 regime-relative detection)
// ------------------------------------------------------------------------------
// Z_t = (R_t − μ_t) / σ_t, where μ_t = SMA(R, W), σ_t = StDev(R, W).
// Normalized ratio allows cross-asset and cross-regime comparison.
timeseries ratioMean = sma(composite, zWindow)
timeseries ratioStd = stdev(composite, zWindow)
timeseries ratioZ = (ratioStd > 0) ? (composite - ratioMean) / ratioStd : 0.0
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes plus extreme:
// Bearish: composite ≤ bearThresh
// Neutral: bearThresh < composite < bullThresh
// Bullish: composite ≥ bullThresh
// Extreme: |composite| ≥ extremeThresh
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (composite >= bullThresh) {
regime = 1
} else if (composite <= bearThresh) {
regime = -1
}
if (composite >= extremeThresh) {
extremeRegime = 1
} else if (composite <= -extremeThresh) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRatio = -999999.0
static sessionLowRatio = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (composite > sessionHighRatio) {
sessionHighRatio = composite
}
if (composite < sessionLowRatio) {
sessionLowRatio = composite
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBidCount = extremeBidCount + 1
} else if (extremeRegime == -1) {
extremeAskCount = extremeAskCount + 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=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)
}
// Composite ratio line with regime-coded fill area
if (showComposite) {
var compColorIdx = regime == 1 ? 0 : (regime == -1 ? 1 : 2)
plotLine(
value=composite,
width=2,
colors=[bidColor, askColor, neutralColor],
colorIndex=compColorIdx,
label=["Composite Ratio"],
desc=["Depth-weighted bid/ask ratio (smoothed). Regime: bull/bear/neutral."],
fill=true
)
}
// Z-Score line (regime-relative liquidity dominance)
if (showZScore && useZScore) {
plotLine(
value=ratioZ,
width=2,
colors=[zScoreColor],
label=["Ratio Z-Score"],
desc=["Z-score normalized bid/ask ratio: (Ratio − μ) / σ"]
)
}
// Histogram (plotBar) — sign-based colouring with extreme regime override
if (showHistogram) {
var histColors = [extremeBidColor, bidColor, askColor, extremeAskColor]
var histIdx = extremeRegime == 1 ? 0 : (regime == 1 ? 1 : (regime == -1 ? 2 : 3))
plotBar(
value=composite,
colors=histColors,
colorIndex=histIdx,
width=1,
label=["Ratio Histogram"],
desc=["Bid/ask ratio histogram (extreme bull/bull/bear/extreme bear)"]
)
}
// Individual depth lines (optional, for granular analysis)
if (showIndividual) {
plotLine(
value=smoothed1,
width=1,
colors=[opacity(bidColor, 50)],
label=["Ratio 1%"],
desc=["Bid/ask ratio at 1% depth (shallow book, top-of-book)"]
)
plotLine(
value=smoothed2,
width=1,
colors=[opacity(bidColor, 40)],
label=["Ratio 2.5%"],
desc=["Bid/ask ratio at 2.5% depth (near-term liquidity)"]
)
plotLine(
value=smoothed3,
width=1,
colors=[opacity(askColor, 40)],
label=["Ratio 5%"],
desc=["Bid/ask ratio at 5% depth (medium-term absorption)"]
)
plotLine(
value=smoothed4,
width=1,
colors=[opacity(askColor, 50)],
label=["Ratio 10%"],
desc=["Bid/ask ratio at 10% depth (deep book, structural level)"]
)
}
// Regime transition shapes — directional signal extraction (Gould & Bonart 2016)
if (showShapes) {
var crossUp = composite >= bullThresh && !isnan(composite[1]) && composite[1] < bullThresh
var crossDn = composite <= bearThresh && !isnan(composite[1]) && composite[1] > bearThresh
var extremeUp = composite >= extremeThresh && !isnan(composite[1]) && composite[1] < extremeThresh
var extremeDn = composite <= -extremeThresh && !isnan(composite[1]) && composite[1] > -extremeThresh
if (crossUp) {
plotShape(
value=composite,
shape="triangleup",
color=extremeBidColor,
width=3,
label=["Bull Regime"],
desc=["Bid/ask ratio crossed into bullish regime (bid-heavy)"]
)
}
if (crossDn) {
plotShape(
value=composite,
shape="triangledown",
color=extremeAskColor,
width=3,
label=["Bear Regime"],
desc=["Bid/ask ratio crossed into bearish regime (ask-heavy)"]
)
}
if (extremeUp) {
plotShape(
value=composite,
shape="diamond",
color=extremeBidColor,
width=4,
label=["Extreme Bid"],
desc=["Extreme bid dominance detected — deep book buy-heavy imbalance"]
)
}
if (extremeDn) {
plotShape(
value=composite,
shape="diamond",
color=extremeAskColor,
width=4,
label=["Extreme Ask"],
desc=["Extreme ask dominance detected — deep book sell-heavy imbalance"]
)
}
}