MM Flow
FlowScripts

Perfected FlowScript

Liquidity Imbalance Oscillator

Liquidity Imbalance Oscillator V2 is indexed as 010_liquidity_imbalance_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

17.1 KB

Lines

384

Native Signal Candidates

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

6/6 guarded

Bull Regime

line 324:9

Trigger

(showShapes) && (crossUp)

Value

smoothedComposite

Deps

crossUp:var, showShapes:input

Bear Regime

line 334:9

Trigger

(showShapes) && (crossDn)

Value

smoothedComposite

Deps

crossDn:var, showShapes:input

Extreme Bid

line 344:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedComposite

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 354:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedComposite

Deps

extremeDn:var, showShapes:input

Bull Exit

line 364:9

Trigger

(showShapes) && (exitUp)

Value

smoothedComposite

Deps

exitUp:var, showShapes:input

Bear Exit

line 374:9

Trigger

(showShapes) && (exitDn)

Value

smoothedComposite

Deps

exitDn:var, showShapes:input

010_liquidity_imbalance_oscillator.flowscript

source path: kscripts/perfected/010_liquidity_imbalance_oscillator.flowscript · sha256:e87d60d4e7c1688b3811ad57018f0d9a885e2ee1f6e919499064ccf0636d0292

hash verified
//@version=2
// ============================================================================
// Liquidity Imbalance Oscillator V2 — Production-Grade Orderbook Microstructure Indicator
// Author: kiyotaka (@kiyotaka)  |  Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, CORE, #bidask, #liquidity, #orderbook, #OBI, #microstructure
//
// Multi-depth limit order book imbalance oscillator with depth-weighted composite,
// regime detection, fill-area visualization, and academic microstructure foundations.
// Plots as a bounded oscillator in [-100, +100] with regime-coded color and
// transition shape markers.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) × 100  [−100, +100]
// 2. Depth-Weighted Composite OBI: Σ w_i × OBI_i / Σ w_i  where w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019), multi-level OFI with decaying weights.
// 3. Regime Segmentation: Sell-heavy (−100, −33), Neutral (−33, +33),
//    Buy-heavy (+33, +100) per Cartea, Donnelly & Jaimungal (2018).
// 4. Linear Price-Impact Model: ΔP ≈ OFI / Depth  per Cont, Kukanov & Stoikov (2014).
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI explains ~65% of mid-price variance;
//    slope ∝ 1/depth. Multi-depth bands operationalize this finding.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights significantly
//    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
//    predicts future price direction: buy-heavy → positive moves; sell-heavy → negative.
//  • 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.
//  • Order Book Filtration and Directional Signal Extraction (2025). OBI as bounded
//    regime indicator; |OBI| → 100 flags directional extremes.
//  • Korean Derivatives Association (2015), "Order Imbalance and Return Predictability".
//    Full-book imbalance predicts 5-, 10-, 20-min returns on KOSPI 200 futures.
// ============================================================================

define(
    title="Liquidity Imbalance 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 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")
var smoothComposite = input(name="smoothComposite", type="boolean", defaultValue=true, label="Smooth Composite OBI", 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 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 OBI 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 Line", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Display")
var showRegimeFill = input(name="showRegimeFill", type="boolean", defaultValue=true, label="Show Regime Fill Areas", 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
// ------------------------------------------------------------------------------
// CRITICAL BUG FIX: Removed math.floor() and math.max() which incorrectly
// truncated float percentages to integer levels. The original code:
//   sumBids(book, math.max(1, math.floor(depthPct)))
// was a critical bug: depthPct=2.5 → floor(2.5)=2 → max(1,2)=2, losing the 0.5%
// precision entirely. The kScript API accepts depth as a float percentage.
//
// 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%) 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)

// 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

// ------------------------------------------------------------------------------
// OBI Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// OBI = (Bid − Ask) / (Bid + Ask) × 100  ∈ [−100, +100]
// Formula from Order Book Filtration and Directional Signal Extraction (2025)
// and Korean Derivatives Association (2015).

var denom1 = bids1 + asks1
var denom2 = bids2 + asks2
var denom3 = bids3 + asks3

var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 * 100.0 : 0.0
var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 * 100.0 : 0.0
var obi3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 * 100.0 : 0.0

// ------------------------------------------------------------------------------
// Depth-Weighted Composite OBI (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level OFI with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3.
// Composite = Σ w_i × OBI_i / Σ w_i.
// This significantly improves short-horizon prediction vs. top-of-book alone.

var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0

var wSum = w1 + w2 + w3
var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3) / wSum : 0.0

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothed1 = ema(obi1, smoothLen)
var smoothed2 = ema(obi2, smoothLen)
var smoothed3 = ema(obi3, smoothLen)
var smoothedComposite = smoothComposite ? ema(compositeOBI, smoothLen) : compositeOBI

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes:
//   Sell-heavy: OBI ≤ bearThresh
//   Neutral:    bearThresh < OBI < bullThresh
//   Buy-heavy:  OBI ≥ bullThresh
// These segments predict future price moves: positive changes preceded by
// buy-heavy books; negative changes by sell-heavy books.
// An additional extreme tier flags statistically rare imbalance events.

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
}

// ------------------------------------------------------------------------------
// 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 sessionHighOBI = -999999.0
static sessionLowOBI = 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 (compositeOBI > sessionHighOBI) {
        sessionHighOBI = compositeOBI
    }
    if (compositeOBI < sessionLowOBI) {
        sessionLowOBI = compositeOBI
    }

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

// Regime fill areas — background color bands between thresholds
if (showRegimeFill) {
    // Buy-heavy zone fill (between bullThresh and extremeThresh)
    plotLine(
        value=[bullThresh, extremeThresh],
        width=0,
        colors=[opacity(bidColor, 10)],
        fill=opacity(bidColor, 8),
        label=["Bull Zone Fill"],
        desc=["Background fill for buy-heavy regime zone"]
    )
    // Sell-heavy zone fill (between bearThresh and -extremeThresh)
    plotLine(
        value=[bearThresh, -extremeThresh],
        width=0,
        colors=[opacity(askColor, 10)],
        fill=opacity(askColor, 8),
        label=["Bear Zone Fill"],
        desc=["Background fill for sell-heavy regime zone"]
    )
}

// Raw composite OBI as histogram bars (bid/ask pressure visualization)
if (showRawBars) {
    plotBar(
        value=compositeOBI,
        colors=[bidColor, askColor],
        width=1,
        label=["Composite OBI Raw"],
        desc=["Depth-weighted composite OBI histogram (positive=bid, negative=ask)"]
    )
}

// Smoothed composite line with regime-coded color and fill area
if (showComposite) {
    var lineColor = extremeRegime == 1 ? extremeBidColor : (extremeRegime == -1 ? extremeAskColor : (regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)))
    plotLine(
        value=smoothedComposite,
        width=2,
        colors=[lineColor],
        label=["Composite OBI"],
        desc=["Depth-weighted composite OBI (EMA-smoothed). Regime: bull/bear/neutral/extreme."]
    )

    // Fill area between zero line and composite value for visual emphasis
    plotLine(
        value=[smoothedComposite, 0],
        width=0,
        colors=[lineColor, lineColor],
        fill=opacity(lineColor, 15),
        label=["OBI Fill", "Zero"],
        desc=["Fill area between OBI line and zero", "Zero reference line"]
    )
}

// Individual depth lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=smoothed1,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["OBI 1%"],
        desc=["Order Book Imbalance at 1% depth (shallow book, top-of-book)"]
    )
    plotLine(
        value=smoothed2,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["OBI 2.5%"],
        desc=["Order Book Imbalance at 2.5% depth (near-term liquidity)"]
    )
    plotLine(
        value=smoothed3,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["OBI 5%"],
        desc=["Order Book Imbalance at 5% depth (medium-term absorption)"]
    )
}

// Regime transition shapes — directional signal extraction (Cartea et al. 2018)
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
    var exitUp = smoothedComposite < bullThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] >= bullThresh
    var exitDn = smoothedComposite > bearThresh && !isnan(smoothedComposite[1]) && smoothedComposite[1] <= bearThresh

    if (crossUp) {
        plotShape(
            value=smoothedComposite,
            shape="triangleup",
            color=bidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite OBI crossed into bullish regime (buy-heavy)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedComposite,
            shape="triangledown",
            color=askColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite OBI crossed into bearish regime (sell-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"]
        )
    }
    if (exitUp) {
        plotShape(
            value=smoothedComposite,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Bull Exit"],
            desc=["OBI exited bullish regime back to neutral"]
        )
    }
    if (exitDn) {
        plotShape(
            value=smoothedComposite,
            shape="circle",
            color=neutralColor,
            width=2,
            label=["Bear Exit"],
            desc=["OBI exited bearish regime back to neutral"]
        )
    }
}