MM Flow
FlowScripts

Perfected FlowScript

Bid-Ask Asymmetry Oscillator

Bid-Ask Asymmetry Oscillator V2 is indexed as 242_bid_ask_asymmetry_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.8 KB

Lines

366

Native Signal Candidates

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

4/4 guarded

Bull Regime

line 326:9

Trigger

(showShapes) && (crossUp)

Value

smoothedComposite

Deps

crossUp:var, showShapes:input

Bear Regime

line 336:9

Trigger

(showShapes) && (crossDn)

Value

smoothedComposite

Deps

crossDn:var, showShapes:input

Extreme Bid

line 346:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedComposite

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 356:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedComposite

Deps

extremeDn:var, showShapes:input

242_bid_ask_asymmetry_oscillator.flowscript

source path: kscripts/perfected/242_bid_ask_asymmetry_oscillator.flowscript · sha256:60aaa180637c1c9b7885e4f9d85f8c16dfb89357924eac77be9d31e161aa3a3a

hash verified
//@version=2

// ============================================================================
// Bid-Ask Asymmetry Oscillator V2 — Multi-Level Orderbook Asymmetry with
// Z-Score, Regime Detection & Shape Alerts
// Author: D (@ddave334) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #orderbook, #bidask, #asymmetry, #imbalance, #zscore
//
// Measures the dynamic imbalance between bid and ask liquidity across
// multiple orderbook depth levels using inverse-distance weighting, oscillating
// between −100 (ask dominant) and +100 (bid dominant). The raw asymmetry is
// standardized via a rolling z-score, and regime detection identifies
// extreme imbalance states. Color-coded histograms, momentum tracking, and
// shape markers provide multi-layered visual confirmation of orderbook
// pressure shifts before they appear in price.
//
// Academic foundation (exact papers & formulas):
//  1. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
//     Limit Order Book", arXiv:1907.06230.
//     [Formula] Multi-level OFI = Σ w_i · OFI_i where w_i are decaying
//     weights for deeper levels. Deeper-level imbalance significantly improves
//     short-horizon price prediction vs. top-of-book alone.
//
//  2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events", Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI = Σ(E_i × ΔP_i); ΔP ≈ λ · OFI where λ ∝ 1/depth.
//     Inverse-distance weighting emphasizes near-spread liquidity, which has
//     higher price impact per unit of volume.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  3. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//     Order Book Signals", Applied Mathematical Finance, 25(1), 1–35.
//     [Formula] Regime segmentation: Sell-heavy (−1, −1/3), Neutral
//     (−1/3, 1/3), Buy-heavy (1/3, 1). Positive price changes are preceded by
//     buy-heavy books; negative by sell-heavy.
//
//  4. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//     Predictor in a Limit Order Book", Market Microstructure & Liquidity
//     2(1), 1650006.
//     [Formula] Queue Imbalance = (BidSize − AskSize)/(BidSize + AskSize).
//     Logistic regression predicts next-tick direction with strong
//     statistical significance for liquid stocks.
//
//  5. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
//     Journal of Financial Economics, 17(2), 223–249.
//     [Formula] Expected returns ∝ bid-ask spread. The bid-ask ratio is a
//     dynamic measure of the same liquidity asymmetry that Amihud &
//     Mendelson showed affects expected returns.
//
//  6. Zhao, S. & Palomar, D. P. (2018), "Mean-Reverting Portfolio With Budget
//     Constraint", IEEE Transactions on Signal Processing.
//     [Formula] z̄_t = (z_t − μ_z) / σ_z; entry thresholds at d × σ_z.
//     Formalizes z-score standardization for regime detection.
// ============================================================================

define(title="Bid-Ask Asymmetry Oscillator V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- 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 Inverse-Distance Weighting", 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 & Z-Score --
var smoothLen = input(name="smoothLen", type="number", defaultValue=10, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Smoothing")
var smoothComposite = input(name="smoothComposite", type="boolean", defaultValue=true, label="Smooth Composite Asymmetry", group="Smoothing")

// -- 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 showRawAsym = input(name="showRawAsym", type="boolean", defaultValue=true,  label="Show Raw Asymmetry", group="Display")
var showComposite = input(name="showComposite", type="boolean", defaultValue=true,  label="Show Composite Z-Score", group="Display")
var showMomentum = input(name="showMomentum", type="boolean", defaultValue=true,  label="Show Asymmetry Momentum", 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 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="#78909c", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00c853", label="Extreme Bid Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#d50000", label="Extreme Ask Color", group="Colors")
var momentumColor = input(name="momentumColor", type="color", defaultValue="#ffeb3b", label="Momentum Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries book = source("orderbook", currentSymbol, currentExchange)
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close

// Guard: halt until external feeds have loaded to avoid NaN propagation
if (isnan(close[0]) || !isnum(book.bid)) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Multi-level bid/ask aggregation --
// Xu, Gould & Howison (2019): multi-level OFI significantly improves
// prediction vs. top-of-book alone. We aggregate depth at 4 bands.
// CRITICAL: kScript API accepts depth as float percentage (e.g., 1.0 = 1%).
timeseries bids1 = sumBids(book, depth1)
timeseries asks1 = sumAsks(book, depth1)
timeseries bids2 = sumBids(book, depth2)
timeseries asks2 = sumAsks(book, depth2)
timeseries bids3 = sumBids(book, depth3)
timeseries asks3 = sumAsks(book, depth3)
timeseries bids4 = sumBids(book, depth4)
timeseries 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

// -- 3.2 Asymmetry at each depth band (zero-division guarded) --
// Asymmetry = (Bid − Ask) / (Bid + Ask) × 100, bounded to [−100, +100].
// Formula derived from Gould & Bonart (2016) queue imbalance and
// Korean Derivatives Association (2015) order imbalance ratio.
timeseries denom1 = bids1 + asks1
timeseries denom2 = bids2 + asks2
timeseries denom3 = bids3 + asks3
timeseries denom4 = bids4 + asks4

timeseries asym1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 * 100.0 : 0.0
timeseries asym2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 * 100.0 : 0.0
timeseries asym3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 * 100.0 : 0.0
timeseries asym4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 * 100.0 : 0.0

// -- 3.3 Inverse-distance weighted composite asymmetry (Xu et al. 2019) --
// Multi-level OFI with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3,4. Near-spread liquidity gets higher weight
// because Cont et al. (2014) showed price impact slope ∝ 1/depth.
timeseries w1 = 1.0
timeseries w2 = useDepthWeighting ? weightDecay : 1.0
timeseries w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
timeseries w4 = useDepthWeighting ? weightDecay * weightDecay * weightDecay : 1.0

timeseries wSum = w1 + w2 + w3 + w4
timeseries compositeAsym = wSum > 0 ? (w1 * asym1 + w2 * asym2 + w3 * asym3 + w4 * asym4) / wSum : 0.0

// -- 3.4 Smoothing (EMA per Cont et al. 2014 noise-reduction) --
timeseries smoothed1 = ema(asym1, smoothLen)
timeseries smoothed2 = ema(asym2, smoothLen)
timeseries smoothed3 = ema(asym3, smoothLen)
timeseries smoothed4 = ema(asym4, smoothLen)
timeseries smoothedComposite = smoothComposite ? ema(compositeAsym, smoothLen) : compositeAsym

// -- 3.5 Z-score normalization (Zhao & Palomar 2018) --
// Standardizes composite asymmetry so extreme readings are comparable
// across time and instruments.
timeseries asymMean = sma(smoothedComposite, zWindow)
timeseries asymStd  = stdev(smoothedComposite, zWindow)
timeseries asymZ = (asymStd > 0) ? (smoothedComposite - asymMean) / asymStd * 100.0 : 0.0

// -- 3.6 Regime detection (Cartea, Donnelly & Jaimungal 2018 three-segment model) --
// Segmented into three regimes: Sell-heavy, Neutral, Buy-heavy.
// Positive price changes preceded by buy-heavy books; negative by sell-heavy.
var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

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

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

// -- 3.7 Asymmetry momentum (rate of change) --
// Captures acceleration/deceleration in orderbook pressure before it
// fully appears in price. Related to Orderbook Momentum (BackQuant).
timeseries asymMomentum = smoothedComposite - smoothedComposite[smoothLen]

// -- 3.8 Static state tracking (session-level persistence) --
// Tracks regime transitions, session extremes, and extreme-event counts.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighAsym = -999999.0
static sessionLowAsym = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (smoothedComposite > sessionHighAsym) {
        sessionHighAsym = smoothedComposite
    }
    if (smoothedComposite < sessionLowAsym) {
        sessionLowAsym = smoothedComposite
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeBidCount = extremeBidCount + 1
    } else if (extremeRegime == -1) {
        extremeAskCount = extremeAskCount + 1
    }
}

// -- 3.9 Zero-line helper for fill areas --
timeseries zeroLine = 0.0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// Horizontal guide lines — zero line and configurable threshold zones
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)

// 4.1 Raw composite asymmetry as color-coded histogram bars (bid/ask pressure)
if (showRawAsym) {
    plotBar(
        value=compositeAsym,
        colors=[bidColor, askColor],
        width=1,
        label=["Composite Asymmetry Raw"],
        desc=["Depth-weighted composite asymmetry (positive=bid, negative=ask)"]
    )
}

// 4.2 Smoothed composite asymmetry with regime-coded fill area
if (showComposite) {
    plotLine(
        value=smoothedComposite,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Composite Asymmetry"],
        desc=["Depth-weighted composite asymmetry (EMA-smoothed). Regime: bull/bear/neutral."],
        fill=true
    )
}

// 4.3 Z-score composite line (standardized for cross-time comparison)
if (showComposite) {
    plotLine(
        value=asymZ,
        width=1,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=asymZ > 0 ? 0 : (asymZ < 0 ? 1 : 2),
        label=["Asymmetry Z-Score"],
        desc=["Rolling z-score of smoothed composite asymmetry; standardized deviation from mean"]
    )
}

// 4.4 Asymmetry momentum (rate of change) — early warning signal
if (showMomentum) {
    plotLine(
        value=asymMomentum,
        width=2,
        colors=[momentumColor],
        label=["Asymmetry Momentum"],
        desc=["Rate of change of composite asymmetry; acceleration/deceleration in orderbook pressure"]
    )
}

// 4.5 Individual depth lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=smoothed1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["Asym 1%"],
        desc=["Bid-ask asymmetry at 1% depth (shallow book, top-of-book)"]
    )
    plotLine(
        value=smoothed2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["Asym 2.5%"],
        desc=["Bid-ask asymmetry at 2.5% depth (near-term liquidity)"]
    )
    plotLine(
        value=smoothed3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["Asym 5%"],
        desc=["Bid-ask asymmetry at 5% depth (medium-term absorption)"]
    )
    plotLine(
        value=smoothed4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["Asym 10%"],
        desc=["Bid-ask asymmetry at 10% depth (deep book, structural level)"]
    )
}

// 4.6 Regime transition shapes (plotShape) — directional signal extraction
if (showShapes) {
    var crossUp = smoothedComposite >= bullThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] < bullThresh
    var crossDn = smoothedComposite <= bearThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] > bearThresh
    var extremeUp = smoothedComposite >= extremeThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] < extremeThresh
    var extremeDn = smoothedComposite <= -extremeThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] > -extremeThresh

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