MM Flow
FlowScripts

Perfected FlowScript

Orderflow Imbalance

Orderflow Imbalance — Perfected Edition is indexed as 056_orderflow_imbalance.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

12.4 KB

Lines

397

Native Signal Candidates

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

2/2 guarded

Extreme Bull

line 346:9

Trigger

(showShapes) && (extremeBull)

Value

extremeThreshold

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 356:9

Trigger

(showShapes) && (extremeBear)

Value

-extremeThreshold

Deps

extremeBear:var, showShapes:input

056_orderflow_imbalance.flowscript

source path: kscripts/perfected/056_orderflow_imbalance.flowscript · sha256:43dd039e292ae9fd265f73334b420af3dbf989d08e3211b9b8b5721b5a4924f9

hash verified
//@version=2
// ============================================================================
// Orderflow Imbalance — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #orderflow, #orderbook, #delta, #zscore, #regime
//
// Production-quality top-of-book orderflow imbalance implementing the
// canonical OFI formula per Cont, Kukanov & Stoikov (2014), with taker
// buy/sell imbalance, z-score normalization, regime detection (bull/bear/
// neutral), color-coded bars, shape markers for extremes, and session
// persistence tracking via static state.
//
// Research papers underpinning this design:
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events", Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}
//     Cumulative OFI linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t, where λ is inversely proportional to depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
//     Limit Order Book". Extended OFI to multiple depth levels, showing
//     that deeper book levels improve predictive power out-of-sample.
//
//  3. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//     Predictor in a Limit Order Book". Found queue imbalance strongly
//     predicts next mid-price direction via logistic regression.
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates extreme-threshold alerting.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     Z-score event trigger framework: entry thresholds at Δ = d × σ_z.
//     Underpins the z-score normalization and cap design.
//
//  6. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy) used when granular taker-buy/sell data
//     is unavailable: classify as buy if close > open, else sell.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// ============================================================================

define(
    title="Orderflow Imbalance — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Computation ---
var depthPct = input(
    name="depthPct",
    type="number",
    defaultValue=2.0,
    label="Depth % (book depth to measure)",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Computation"
)
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 10, max: 200, step: 5},
    group="Computation"
)
var maLen = input(
    name="maLen",
    type="number",
    defaultValue=7,
    label="EMA Smoothing",
    constraints={min: 1, max: 50, step: 1},
    group="Computation"
)
var cap = input(
    name="cap",
    type="number",
    defaultValue=3.0,
    label="Z-Score Cap (±)",
    constraints={min: 1.0, max: 6.0, step: 0.5},
    group="Computation"
)
var runLen = input(
    name="runLen",
    type="number",
    defaultValue=20,
    label="Persistence Window",
    constraints={min: 5, max: 100, step: 5},
    group="Computation"
)

// --- Thresholds ---
var bullThreshold = input(
    name="bullThreshold",
    type="number",
    defaultValue=1.0,
    label="Bull Regime Threshold (z)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Thresholds"
)
var bearThreshold = input(
    name="bearThreshold",
    type="number",
    defaultValue=-1.0,
    label="Bear Regime Threshold (z)",
    constraints={min: -3.0, max: -0.5, step: 0.5},
    group="Thresholds"
)
var extremeThreshold = input(
    name="extremeThreshold",
    type="number",
    defaultValue=2.0,
    label="Extreme Threshold (z)",
    constraints={min: 1.5, max: 4.0, step: 0.5},
    group="Thresholds"
)

// --- Display ---
var showZ = input(
    name="showZ",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showBars = input(
    name="showBars",
    type="boolean",
    defaultValue=true,
    label="Show Color-Coded Bars",
    group="Display"
)
var showRun = input(
    name="showRun",
    type="boolean",
    defaultValue=true,
    label="Show Persistence Trace",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Shapes",
    group="Display"
)
var showTakerImb = input(
    name="showTakerImb",
    type="boolean",
    defaultValue=true,
    label="Show Taker Imbalance",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Display"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Display"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Display"
)
var emaColor = input(
    name="emaColor",
    type="color",
    defaultValue="#ffeb3b",
    label="EMA Signal Color",
    group="Display"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume

// External feeds: taker volume for buy/sell imbalance
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

if (isnan(c[0]) || isnan(v[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. OFI CALCULATION (per Cont et al. 2014)
// -----------------------------------------------------------------------------
// When taker buy/sell is available, we use the direct feed for higher accuracy.
// Lee-Ready (1991) fallback: close > open → buyer-initiated; else seller-initiated.

timeseries buyVol = isnum(taker.buy) ? taker.buy : (c > o ? v : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (c <= o ? v : 0)

// Per-bar orderflow imbalance: net aggressive volume
// OFI proxy = buy volume − sell volume
timeseries ofiRaw = buyVol - sellVol

// Taker buy/sell imbalance ratio (normalized −1 to +1)
// Imbalance = (buy − sell) / (buy + sell), 0 when equal
timeseries takerTotal = buyVol + sellVol
timeseries takerImb = takerTotal > 0 ? (buyVol - sellVol) / takerTotal : 0

// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Z_t = (OFI_t − μ_t) / σ_t; guard against zero std dev

timeseries ofiMean = sma(ofiRaw, zLen)
timeseries ofiStd = stddev(ofiRaw, zLen)
timeseries zRaw = (ofiStd > 0) ? (ofiRaw - ofiMean) / ofiStd : 0.0

// Clip extremes by cap
timeseries zScore = math.max(math.min(zRaw, cap), -cap)

// EMA-smoothed z-score for signal line
timeseries zEma = ema(zScore, maLen)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION (bull / bear / neutral)
// -----------------------------------------------------------------------------
var regimeBull = zEma > bullThreshold
var regimeBear = zEma < bearThreshold
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// Extreme regime flags
var extremeBull = zEma > extremeThreshold
var extremeBear = zEma < -extremeThreshold

// -----------------------------------------------------------------------------
// 6. PERSISTENCE TRACE (static session tracking)
// -----------------------------------------------------------------------------
// Measures how long one side has stayed in control via EMA of signed z-score.
// Values near +1 = sustained buy pressure; near −1 = sustained sell pressure.

timeseries signed = zScore > 0 ? 1.0 : -1.0
timeseries run = ema(signed, runLen)

// Static session tracking for consecutive regime bars
static bullBars = 0
static bearBars = 0
static lastRegime = 0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
    lastRegime = 1
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
    lastRegime = -1
} else {
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line and threshold hlines ---
hline(value=0, color="#ffffff30", width=1)
hline(value=bullThreshold, color=transparency(bullColor, 70), width=1)
hline(value=bearThreshold, color=transparency(bearColor, 70), width=1)
hline(value=extremeThreshold, color=transparency(bullColor, 50), width=1)
hline(value=-extremeThreshold, color=transparency(bearColor, 50), width=1)

// --- Z-Score EMA line (regime-colored) ---
if (showZ) {
    plotLine(
        value=zEma,
        width=2,
        colors=[regimeColor],
        label=["OFI Z-Score"],
        desc=["EMA-smoothed z-score of per-bar orderflow imbalance (Cont et al. 2014)"]
    )
}

// --- Color-coded bars (plotBar with regime color mapping) ---
if (showBars) {
    var barColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
    plotBar(
        value=zScore,
        colors=[
            transparency(bullColor, 50),
            transparency(bearColor, 50),
            transparency(neutralColor, 50)
        ],
        colorIndex=barColorIdx,
        width=2,
        label=["OFI Bars"],
        desc=["Per-bar z-score; color-coded by regime: bull / bear / neutral"]
    )
}

// --- Persistence trace ---
if (showRun) {
    plotLine(
        value=run,
        width=1,
        colors=[emaColor],
        label=["Persistence"],
        desc=["+1 = sustained buy pressure, −1 = sustained sell pressure (" + runLen + "-bar EMA)"]
    )
}

// --- Taker imbalance overlay (secondary series) ---
if (showTakerImb) {
    plotLine(
        value=takerImb,
        width=1,
        colors=[transparency("#9c27b0", 40)],
        label=["Taker Imb"],
        desc=["Taker buy/sell imbalance: (buy − sell) / (buy + sell); −1 to +1"]
    )
}

// --- Extreme shape markers ---
if (showShapes) {
    if (extremeBull) {
        plotShape(
            value=extremeThreshold,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Extreme Bull"],
            desc=["OFI z-score exceeded +" + extremeThreshold + "; extreme buy pressure detected"]
        )
    }
    if (extremeBear) {
        plotShape(
            value=-extremeThreshold,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Extreme Bear"],
            desc=["OFI z-score below −" + extremeThreshold + "; extreme sell pressure detected"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["OFI — Perfected", regimeText],
            ["Z-Score", zScore[0]],
            ["Z-EMA", zEma[0]],
            ["Persistence", run[0]],
            ["Taker Imb", takerImb[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}