MM Flow
FlowScripts

Perfected FlowScript

Orderflow Bar Statistics

Orderflow Bar Statistics — Per-Bar OFI · OIΔ · Funding is indexed as 033_orderflow_bar_statistics.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.9 KB

Lines

380

Native Signal Candidates

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

9/9 guarded

OFI Extreme Bull

line 266:5

Trigger

(showShapes && ofiExtremeBull && ofiBullBars == 1)

Value

ofiZ

Deps

ofiBullBars:static, ofiExtremeBull:var, showShapes:input

OFI Extreme Bear

line 276:5

Trigger

(showShapes && ofiExtremeBear && ofiBearBars == 1)

Value

ofiZ

Deps

ofiBearBars:static, ofiExtremeBear:var, showShapes:input

OIΔ Extreme Bull

line 286:5

Trigger

(showShapes && oidExtremeBull && oidBullBars == 1)

Value

oidZ

Deps

oidBullBars:static, oidExtremeBull:var, showShapes:input

OIΔ Extreme Bear

line 296:5

Trigger

(showShapes && oidExtremeBear && oidBearBars == 1)

Value

oidZ

Deps

oidBearBars:static, oidExtremeBear:var, showShapes:input

FR Extreme Bull

line 306:5

Trigger

(showShapes && fExtremeBull && fBullBars == 1)

Value

fZ

Deps

fBullBars:static, fExtremeBull:var, showShapes:input

FR Extreme Bear

line 316:5

Trigger

(showShapes && fExtremeBear && fBearBars == 1)

Value

fZ

Deps

fBearBars:static, fExtremeBear:var, showShapes:input

Bull Confluence

line 328:5

Trigger

(showConfluence && bullishConfluence && lastConfluenceBar == 1)

Value

compositeZ

Deps

bullishConfluence:var, lastConfluenceBar:static, showConfluence:input

Bear Confluence

line 338:5

Trigger

(showConfluence && bearishConfluence && lastConfluenceBar == 1)

Value

compositeZ

Deps

bearishConfluence:var, lastConfluenceBar:static, showConfluence:input

Unlabeled shape

line 370:5

Trigger

(showRegimeLabel && isLastBar)

Value

bars.high

Deps

isLastBar:builtin, showRegimeLabel:input

033_orderflow_bar_statistics.flowscript

source path: kscripts/perfected/033_orderflow_bar_statistics.flowscript · sha256:f853898974dbf79b9893631949d81e21b9bc2972ebd37fe8d2342f3984c15e0b

hash verified
//@version=2
// ============================================================================
// Orderflow Bar Statistics — Per-Bar OFI, OI Delta & Funding Rate Dashboard
// Author: BackQuant (@BackQuant) — Perfected Edition
// Tags: ADVANCED, CORE, #orderflow, #bar, #funding, #oi, #ofi, #zscore
//
// Production-grade per-bar orderflow dashboard with rolling z-score
// normalization, heat-colored bars by statistical significance, extreme
// shape markers, confluence detection, and session regime tracking.
//
// Academic foundations:
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//    Events" (J. 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 λ ∝ 1/depth.
//    DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  - Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//    and Market Returns" (J. Financial Economics, 65(1), 111–130).
//    [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//    return reversals. Directly motivates the z-score threshold design.
//    DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  - He & Manela (2022), "Fundamentals of Perpetual Futures". No-arbitrage
//    perp pricing; funding rate fair value = E[cost_of_carry] − basis.
//    Supports funding-rate z-score as a mean-reversion signal.
//
//  - Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
//    (Review of Financial Studies, 22(6), 2201–2238). Liquidity spirals:
//    rising OI + rising funding + falling price = potential liquidation
//    cascade. DOI: https://doi.org/10.1093/rfs/hhp069
//
//  - Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    z-score event triggers: z̄_t = (z_t − μ_z) / σ_z; entry thresholds at
//    Δ = d × σ_z (d = 1 or 2). Normalizes heterogeneous signals to common
//    scale for composite scoring.
//
//  - Lee & Ready (1991), "Inferring Trade Direction from Intraday Data"
//    (J. Finance, 46(2), 733–746). Lee-Ready tick classification:
//    close > open → buyer-initiated; else seller-initiated. ~85–93% accuracy.
//    DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// ============================================================================

define(title="Orderflow Bar Statistics — Per-Bar OFI · OIΔ · Funding", position="offchart", axis=true)

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

// -- Computation --
var lookback = input(name="lookback", type="number", defaultValue=30, label="Z-Score Lookback (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="EMA Smooth Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var extZThresh = input(name="extZThresh", type="number", defaultValue=2.0, label="Extreme Z-Score Threshold", constraints={min: 1.0, max: 4.0, step: 0.5}, group="Computation")
var confluenceThresh = input(name="confluenceThresh", type="number", defaultValue=2.0, label="Confluence Alignment Threshold", constraints={min: 1.0, max: 3.0, step: 0.5}, group="Computation")

// -- Display --
var showOFI = input(name="showOFI", type="boolean", defaultValue=true, label="Show OFI Z-Score", group="Display")
var showOIDelta = input(name="showOIDelta", type="boolean", defaultValue=true, label="Show OI Delta Z-Score", group="Display")
var showFunding = input(name="showFunding", type="boolean", defaultValue=true, label="Show Funding Rate Z-Score", group="Display")
var showHeatBars = input(name="showHeatBars", type="boolean", defaultValue=true, label="Show Heat-Colored Bars", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showConfluence = input(name="showConfluence", type="boolean", defaultValue=true, label="Show Confluence Signal", group="Display")
var showRegimeLabel = input(name="showRegimeLabel", type="boolean", defaultValue=true, label="Show Regime Label", group="Display")
var showLabels = input(name="showLabels", type="boolean", defaultValue=true, label="Show Value Labels", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00c853", label="Extreme Bullish Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#d50000", label="Extreme Bearish Color", group="Colors")
var confluenceColor = input(name="confluenceColor", type="color", defaultValue="#ffd700", label="Confluence Color", group="Colors")

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries funding = source("funding_rate", currentSymbol, currentExchange)

// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(bars.close[0]) || !isnum(taker.buy) || isnan(oi.close[0]) || !isnum(funding.value)) {
    return
}

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

// -- 3.1 Per-bar volume delta (Lee-Ready fallback when taker feed is unavailable) --
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (bars.close > bars.open ? bars.volume : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (bars.close <= bars.open ? bars.volume : 0)

// -- 3.2 Orderflow Imbalance (OFI) — normalized to [-1, 1] range --
// Cont-Kukanov-Stoikov (2014) linear price-impact model: Δp ≈ λ·OFI.
// We normalize to taker buy/sell ratio for cross-asset comparability.
timeseries ofi = (buyVol + sellVol > 0) ? (buyVol - sellVol) / (buyVol + sellVol) : 0

// -- 3.3 Open Interest Delta (OIΔ) — net change in open interest per bar --
// Rising OI + rising price = strong trend (new money entering).
// Rising OI + falling price = distribution (new shorts opening).
// Falling OI + rising price = short covering (squeeze).
// Falling OI + falling price = long liquidation.
timeseries oiDelta = oi.close - oi.close[1]

// -- 3.4 Funding Rate (FR) — per-bar funding cost for perp holders --
// He & Manela (2022): FR reflects cost-of-carry minus basis; positive = longs pay shorts.
timeseries fundingVal = isnum(funding.value) ? funding.value : 0

// -- 3.5 Rolling-window z-score normalisation (all denominators guarded against zero) --
// Z_t = (X_t − μ_t) / σ_t, where μ_t = SMA(X, W), σ_t = StDev(X, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
// EMA smoothing applied post-z-score for cleaner signal.

timeseries ofiMean = sma(ofi, lookback)
timeseries ofiStd = stdev(ofi, lookback)
timeseries ofiZ = (ofiStd > 0) ? ema((ofi - ofiMean) / ofiStd, smoothLen) : 0

timeseries oidMean = sma(oiDelta, lookback)
timeseries oidStd = stdev(oiDelta, lookback)
timeseries oidZ = (oidStd > 0) ? ema((oiDelta - oidMean) / oidStd, smoothLen) : 0

timeseries fMean = sma(fundingVal, lookback)
timeseries fStd = stdev(fundingVal, lookback)
timeseries fZ = (fStd > 0) ? ema((fundingVal - fMean) / fStd, smoothLen) : 0

// -- 3.6 Extreme detection (configurable thresholds, no magic numbers) --
var ofiExtremeBull = ofiZ > extZThresh
var ofiExtremeBear = ofiZ < -extZThresh
var oidExtremeBull = oidZ > extZThresh
var oidExtremeBear = oidZ < -extZThresh
var fExtremeBull = fZ > extZThresh
var fExtremeBear = fZ < -extZThresh

// -- 3.7 Confluence detection — all three metrics aligned in same direction --
// Bullish confluence: OFI + OIΔ + Funding all bullish (high z-score).
// Bearish confluence: all three bearish (low z-score).
// Composite score = average of absolute z-scores; signals when all same sign.
timeseries compositeZ = (ofiZ + oidZ + fZ) / 3
var bullishConfluence = ofiZ > confluenceThresh && oidZ > confluenceThresh && fZ > confluenceThresh
var bearishConfluence = ofiZ < -confluenceThresh && oidZ < -confluenceThresh && fZ < -confluenceThresh
var anyConfluence = bullishConfluence || bearishConfluence

// -- 3.8 Regime detection for color coding --
// 1 = bullish regime, -1 = bearish regime, 0 = neutral.
var ofiRegime = ofiZ > 0 ? 1 : (ofiZ < 0 ? -1 : 0)
var oidRegime = oidZ > 0 ? 1 : (oidZ < 0 ? -1 : 0)
var fRegime = fZ > 0 ? 1 : (fZ < 0 ? -1 : 0)

// -- 3.9 Session tracking via static variables --
// Tracks consecutive bars in extreme regimes for context-aware alerting.
static ofiBullBars = 0
static ofiBearBars = 0
static oidBullBars = 0
static oidBearBars = 0
static fBullBars = 0
static fBearBars = 0
static lastConfluenceBar = 0

if (!isLiveUpdate) {
    if (ofiZ > extZThresh) {
        ofiBullBars = ofiBullBars + 1
        ofiBearBars = 0
    } else if (ofiZ < -extZThresh) {
        ofiBearBars = ofiBearBars + 1
        ofiBullBars = 0
    } else {
        ofiBullBars = 0
        ofiBearBars = 0
    }

    if (oidZ > extZThresh) {
        oidBullBars = oidBullBars + 1
        oidBearBars = 0
    } else if (oidZ < -extZThresh) {
        oidBearBars = oidBearBars + 1
        oidBullBars = 0
    } else {
        oidBullBars = 0
        oidBearBars = 0
    }

    if (fZ > extZThresh) {
        fBullBars = fBullBars + 1
        fBearBars = 0
    } else if (fZ < -extZThresh) {
        fBearBars = fBearBars + 1
        fBullBars = 0
    } else {
        fBullBars = 0
        fBearBars = 0
    }

    if (anyConfluence) {
        lastConfluenceBar = lastConfluenceBar + 1
    } else {
        lastConfluenceBar = 0
    }
}

// -- 3.10 Zero-line helper for fill areas --
timeseries zeroLine = 0

// -- 3.11 Heat-color index mapping --
// 0 = extreme bullish (z > 2), 1 = bullish (z > 0), 2 = neutral, 3 = bearish (z < 0), 4 = extreme bearish (z < -2)
timeseries ofiColorIdx = ofiZ > extZThresh ? 0 : (ofiZ > 0 ? 1 : (ofiZ < -extZThresh ? 4 : 3))
timeseries oidColorIdx = oidZ > extZThresh ? 0 : (oidZ > 0 ? 1 : (oidZ < -extZThresh ? 4 : 3))
timeseries fColorIdx = fZ > extZThresh ? 0 : (fZ > 0 ? 1 : (fZ < -extZThresh ? 4 : 3))

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

// 4.1 OFI Z-Score (plotLine with heat colorIndex + fill area)
if (showOFI) {
    plotLine(
        value=([ofiZ, zeroLine]),
        width=2,
        colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
        colorIndex=ofiColorIdx,
        label=["OFI Z"],
        desc=["Orderflow Imbalance z-score: (buy−sell)/(buy+sell) normalised over rolling window."],
        fill=true
    )
}

// 4.2 OI Delta Z-Score (plotLine with heat colorIndex + fill area)
if (showOIDelta) {
    plotLine(
        value=([oidZ, zeroLine]),
        width=2,
        colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
        colorIndex=oidColorIdx,
        label=["OIΔ Z"],
        desc=["Open Interest Delta z-score: change in OI normalised over rolling window."],
        fill=true
    )
}

// 4.3 Funding Rate Z-Score (plotLine with heat colorIndex + fill area)
if (showFunding) {
    plotLine(
        value=([fZ, zeroLine]),
        width=2,
        colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor],
        colorIndex=fColorIdx,
        label=["FR Z"],
        desc=["Funding Rate z-score: per-bar funding cost normalised over rolling window."],
        fill=true
    )
}

// 4.4 Heat-colored bars (plotBar) — sign-based with 5-color heat scale
if (showHeatBars) {
    plotBar(value=ofiZ, colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor], colorIndex=ofiColorIdx, label=["OFI Heat"], desc=["OFI z-score as heat-colored bars"])
    plotBar(value=oidZ, colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor], colorIndex=oidColorIdx, label=["OIΔ Heat"], desc=["OI delta z-score as heat-colored bars"])
    plotBar(value=fZ, colors=[extremeBullColor, bullColor, neutralColor, bearColor, extremeBearColor], colorIndex=fColorIdx, label=["FR Heat"], desc=["Funding rate z-score as heat-colored bars"])
}

// 4.5 Extreme divergence shapes (plotShape) — only on first extreme bar to avoid clutter
if (showShapes && ofiExtremeBull && ofiBullBars == 1) {
    plotShape(
        value=ofiZ,
        shape="triangleup",
        colorIndex=extremeBullColor,
        width=3,
        label=["OFI Extreme Bull"],
        desc=["OFI z-score exceeds +" + extZThresh + ": aggressive buying pressure statistically extreme."]
    )
}
if (showShapes && ofiExtremeBear && ofiBearBars == 1) {
    plotShape(
        value=ofiZ,
        shape="triangledown",
        colorIndex=extremeBearColor,
        width=3,
        label=["OFI Extreme Bear"],
        desc=["OFI z-score below −" + extZThresh + ": aggressive selling pressure statistically extreme."]
    )
}
if (showShapes && oidExtremeBull && oidBullBars == 1) {
    plotShape(
        value=oidZ,
        shape="triangleup",
        colorIndex=extremeBullColor,
        width=3,
        label=["OIΔ Extreme Bull"],
        desc=["OI Delta z-score exceeds +" + extZThresh + ": strong OI increase = new money entering longs."]
    )
}
if (showShapes && oidExtremeBear && oidBearBars == 1) {
    plotShape(
        value=oidZ,
        shape="triangledown",
        colorIndex=extremeBearColor,
        width=3,
        label=["OIΔ Extreme Bear"],
        desc=["OI Delta z-score below −" + extZThresh + ": strong OI decrease = short covering or liquidation."]
    )
}
if (showShapes && fExtremeBull && fBullBars == 1) {
    plotShape(
        value=fZ,
        shape="triangleup",
        colorIndex=extremeBullColor,
        width=3,
        label=["FR Extreme Bull"],
        desc=["Funding Rate z-score exceeds +" + extZThresh + ": highly positive funding = longs crowded, may squeeze."]
    )
}
if (showShapes && fExtremeBear && fBearBars == 1) {
    plotShape(
        value=fZ,
        shape="triangledown",
        colorIndex=extremeBearColor,
        width=3,
        label=["FR Extreme Bear"],
        desc=["Funding Rate z-score below −" + extZThresh + ": highly negative funding = shorts crowded, may squeeze."]
    )
}

// 4.6 Confluence signal (plotShape on composite line)
if (showConfluence && bullishConfluence && lastConfluenceBar == 1) {
    plotShape(
        value=compositeZ,
        shape="triangleup",
        colorIndex=confluenceColor,
        width=4,
        label=["Bull Confluence"],
        desc=["All three metrics (OFI, OIΔ, Funding) aligned bullish with z > confluence threshold."]
    )
}
if (showConfluence && bearishConfluence && lastConfluenceBar == 1) {
    plotShape(
        value=compositeZ,
        shape="triangledown",
        colorIndex=confluenceColor,
        width=4,
        label=["Bear Confluence"],
        desc=["All three metrics (OFI, OIΔ, Funding) aligned bearish with z < −confluence threshold."]
    )
}

// 4.7 Composite confluence line (plotLine)
if (showConfluence) {
    plotLine(
        value=compositeZ,
        width=2,
        colors=[confluenceColor],
        label=["Composite"],
        desc=["Average of OFI, OIΔ, and Funding z-scores. Confluence when all three align."]
    )
}

// 4.8 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=extZThresh, color="#ffffff20", width=1)
hline(value=-extZThresh, color="#ffffff20", width=1)
hline(value=confluenceThresh, color=confluenceColor + "40", width=1)
hline(value=-confluenceThresh, color=confluenceColor + "40", width=1)

// 4.9 Regime label (plotPriceLabel) — shows on last bar
if (showRegimeLabel && isLastBar) {
    var regimeText = bullishConfluence ? "BULL CONFLUENCE" : (bearishConfluence ? "BEAR CONFLUENCE" : (ofiRegime == 1 ? "BULLISH OFI" : (ofiRegime == -1 ? "BEARISH OFI" : "NEUTRAL")))
    var regimeColor = bullishConfluence ? confluenceColor : (bearishConfluence ? confluenceColor : (ofiRegime == 1 ? bullColor : (ofiRegime == -1 ? bearColor : neutralColor)))
    plotPriceLabel(
        price=bars.high,
        text=regimeText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}