MM Flow
FlowScripts

Perfected FlowScript

Bid/Ask Ratio

Bid/Ask Ratio V2 is indexed as 189_bid_ask_ratio.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

15.5 KB

Lines

351

Native Signal Candidates

4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

4/4 guarded

Bull Regime

line 311:9

Trigger

(showShapes) && (crossUp)

Value

smoothedZ

Deps

crossUp:var, showShapes:input

Bear Regime

line 321:9

Trigger

(showShapes) && (crossDn)

Value

smoothedZ

Deps

crossDn:var, showShapes:input

Extreme Bid

line 331:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedZ

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 341:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedZ

Deps

extremeDn:var, showShapes:input

189_bid_ask_ratio.flowscript

source path: kscripts/perfected/189_bid_ask_ratio.flowscript · sha256:8803b631e384be064689baddac6ecb99fac74d2001953934fdfd7b6203a830fd

hash verified
//@version=2
// ============================================================================
// Bid/Ask Ratio V2 — Production-Quality Orderbook Microstructure Indicator
// Author: kiyotaka (@kiyotaka) | Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #bidask, #ratio, #microstructure, #zscore
//
// Real-time bid/ask volume ratio with z-score normalization, multi-depth
// aggregation, regime detection, and academic microstructure foundations.
//
// FORMULA FOUNDATION:
// 1. Bid/Ask Ratio: R = BidVol / AskVol  (≥1 = bid-heavy, <1 = ask-heavy)
//    Per Gould & Bonart (2016), queue imbalance predicts next-tick direction.
// 2. Z-Score Normalization: z = (R − μ_R) / σ_R  per Cont et al. (2014)
//    normalization for regime-independent thresholding.
// 3. Log-Ratio Transformation: ln(R) for symmetric bounded visualization.
// 4. Regime Segmentation: Buy-heavy (z > +1), Neutral (−1 ≤ z ≤ +1),
//    Sell-heavy (z < −1) per Cartea, Donnelly & Jaimungal (2018).
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Linear price-impact model;
//    slope ∝ 1/depth.
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//    Predictor", Market Microstructure & Liquidity 2(1), 1650006. Logistic
//    regression between queue imbalance and next-tick direction.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy, Neutral, Buy-heavy.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance",
//    arXiv:1907.06230. Multi-level OFI with decaying weights improves
//    short-horizon prediction vs. top-of-book alone.
// ============================================================================

define(
    title="Bid/Ask Ratio 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")

// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 500, step: 1}, group="Z-Score")
var useLogTransform = input(name="useLogTransform", type="boolean", defaultValue=true, label="Use Log-Ratio Transform", group="Z-Score")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Z-Score Threshold", constraints={min: 0.0, max: 5.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Z-Score Threshold", constraints={min: -5.0, max: 0.0, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")
var showRawBars = input(name="showRawBars", type="boolean", defaultValue=true, label="Show Raw Ratio Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true, label="Show Composite Z-Score Line", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Ratios", group="Display")
var showUnnormalized = input(name="showUnnormalized", type="boolean", defaultValue=false, label="Show Unnormalized 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
// ------------------------------------------------------------------------------
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 — Real LOB Data
// ------------------------------------------------------------------------------
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

// ------------------------------------------------------------------------------
// Bid/Ask Ratio Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// Ratio = Bid / Ask  (≥1 bid-heavy, <1 ask-heavy)
// Per Gould & Bonart (2016), queue imbalance as next-tick predictor.

var ratio1 = bookAvailable && asks1 > 0 ? bids1 / asks1 : 1.0
var ratio2 = bookAvailable && asks2 > 0 ? bids2 / asks2 : 1.0
var ratio3 = bookAvailable && asks3 > 0 ? bids3 / asks3 : 1.0
var ratio4 = bookAvailable && asks4 > 0 ? bids4 / asks4 : 1.0

// Log-ratio transform for symmetric bounded visualization (ln(1)=0, ln>0=bid-heavy, ln<0=ask-heavy)
var logRatio1 = useLogTransform && ratio1 > 0 ? ln(ratio1) : (ratio1 - 1.0)
var logRatio2 = useLogTransform && ratio2 > 0 ? ln(ratio2) : (ratio2 - 1.0)
var logRatio3 = useLogTransform && ratio3 > 0 ? ln(ratio3) : (ratio3 - 1.0)
var logRatio4 = useLogTransform && ratio4 > 0 ? ln(ratio4) : (ratio4 - 1.0)

// ------------------------------------------------------------------------------
// Depth-Weighted Composite Ratio (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level ratio with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3,4.
// Composite = Σ w_i × lnRatio_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 compositeLogRatio = wSum > 0 ? (w1 * logRatio1 + w2 * logRatio2 + w3 * logRatio3 + w4 * logRatio4) / wSum : 0.0

// ------------------------------------------------------------------------------
// Z-Score Normalization (Cont et al. 2014 regime-independent thresholding)
// ------------------------------------------------------------------------------
// z = (value − mean) / stdDev over lookback window
// Enables regime-independent thresholding across volatile and calm markets.

var meanRatio = sma(source=compositeLogRatio, period=zLookback)
var stdRatio = stddev(source=compositeLogRatio, period=zLookback)
var zScore = stdRatio > 0 ? (compositeLogRatio - meanRatio) / stdRatio : 0.0

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothed1 = ema(logRatio1, smoothLen)
var smoothed2 = ema(logRatio2, smoothLen)
var smoothed3 = ema(logRatio3, smoothLen)
var smoothed4 = ema(logRatio4, smoothLen)
var smoothedZ = ema(zScore, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes:
//   Sell-heavy: z ≤ bearThresh
//   Neutral:    bearThresh < z < bullThresh
//   Buy-heavy:  z ≥ bullThresh

var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

if (smoothedZ >= bullThresh) {
    regime = 1
} else if (smoothedZ <= bearThresh) {
    regime = -1
}

if (smoothedZ >= extremeThresh) {
    extremeRegime = 1
} else if (smoothedZ <= -extremeThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for anchoring, session tracking, and counters.
// Tracks regime transitions, session extremes, and extreme-event counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 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 (zScore > sessionHighZ) {
        sessionHighZ = zScore
    }
    if (zScore < sessionLowZ) {
        sessionLowZ = zScore
    }

    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)
}

// Raw z-score as histogram bars (bid/ask pressure visualization)
if (showRawBars) {
    plotBar(
        value=zScore,
        colors=[bidColor, askColor],
        width=1,
        label=["Z-Score Raw"],
        desc=["Z-score of depth-weighted bid/ask log-ratio (positive=bid-heavy, negative=ask-heavy)"]
    )
}

// Smoothed z-score line with regime-coded fill area
if (showComposite) {
    plotLine(
        value=smoothedZ,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Z-Score Composite"],
        desc=["EMA-smoothed z-score of composite bid/ask ratio. Regime: bull/bear/neutral."],
        fill=true
    )
}

// Individual depth ratio lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=smoothed1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["Ratio 1%"],
        desc=["Bid/Ask log-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 log-ratio at 2.5% depth (near-term liquidity)"]
    )
    plotLine(
        value=smoothed3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["Ratio 5%"],
        desc=["Bid/Ask log-ratio at 5% depth (medium-term absorption)"]
    )
    plotLine(
        value=smoothed4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["Ratio 10%"],
        desc=["Bid/Ask log-ratio at 10% depth (deep book, structural level)"]
    )
}

// Unnormalized ratio line (1% depth diagnostic, per Gould & Bonart 2016)
if (showUnnormalized) {
    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=["Raw Ratio 1%"],
        desc=["Unnormalized bid/ask ratio at 1% depth, centered at 0 (positive = bid heavy)"]
    )
}

// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
if (showShapes) {
    var crossUp = smoothedZ >= bullThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < bullThresh
    var crossDn = smoothedZ <= bearThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > bearThresh
    var extremeUp = smoothedZ >= extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] < extremeThresh
    var extremeDn = smoothedZ <= -extremeThresh && !isnan(smoothedZ[1]) && smoothedZ[1] > -extremeThresh

    if (crossUp) {
        plotShape(
            value=smoothedZ,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Z-score crossed into bullish regime (buy-heavy bid/ask ratio)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedZ,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Z-score crossed into bearish regime (sell-heavy bid/ask ratio)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid dominance detected — deep book buy-heavy ratio"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smoothedZ,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask dominance detected — deep book sell-heavy ratio"]
        )
    }
}