MM Flow
FlowScripts

Perfected FlowScript

Kyo - OB Imbalance

Kyo OB Imbalance V2 is indexed as 207_kyo_ob_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

20.3 KB

Lines

451

Native Signal Candidates

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

6/6 guarded

Bull Regime

line 391:9

Trigger

(showShapes) && (crossUp)

Value

smoothedComposite

Deps

crossUp:var, showShapes:input

Bear Regime

line 401:9

Trigger

(showShapes) && (crossDn)

Value

smoothedComposite

Deps

crossDn:var, showShapes:input

Extreme Bid

line 411:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedComposite

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 421:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedComposite

Deps

extremeDn:var, showShapes:input

Z+2σ Cross

line 431:9

Trigger

(showShapes) && (zCrossUp)

Value

obiZClip

Deps

showShapes:input, zCrossUp:var

Z-2σ Cross

line 441:9

Trigger

(showShapes) && (zCrossDn)

Value

obiZClip

Deps

showShapes:input, zCrossDn:var

207_kyo_ob_imbalance.flowscript

source path: kscripts/perfected/207_kyo_ob_imbalance.flowscript · sha256:c8743615a213f18492e61f0fdc6a50b715da59f193adc4a5154fd3168f455106

hash verified
//@version=2
// ============================================================================
// Kyo OB Imbalance V2 — Production-Quality Order Block & Orderbook Imbalance
// Author: K (@Kyoscalper)  |  Perfected by: kScript_Perfection_Engineer
// Tags: CORE, #kyo, #orderbook, #orderblock, #imbalance, #OBI, #microstructure
//
// Combines institutional order block detection with multi-depth order book
// imbalance, z-score normalization, and regime detection for the TradingwithKyo
// community. Detects where unfilled institutional orders create structural
// imbalance, then overlays real-time orderbook pressure to confirm or invalidate.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance (OBI): OBI = (BidVol − AskVol) / (BidVol + AskVol) [−1,+1]
//    per Cont, Kukanov & Stoikov (2014). Depth-weighted composite with decay.
// 2. Z-Score Normalization: z_t = (OBI_t − μ_OBI) / σ_OBI  per Zhao & Palomar (2018).
//    Converts raw OBI into statistically comparable regime units.
// 3. Order Block Detection: Pivot high/low + above-average volume per Campbell,
//    Ramadorai & Vuolteenaho (2005) institutional footprint framework.
// 4. OB Imbalance = (Close − BullOB) − (BearOB − Close)  per Kyo community.
//    Positive = price closer to bullish OB (bid support); negative = bearish.
// 5. Regime Segmentation: Sell-heavy (−1, −1/3), Neutral (−1/3, +1/3),
//    Buy-heavy (+1/3, +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. OFI = Σ(E_i × ΔP_i); slope ∝ 1/depth.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights.
//  • Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//    Order Flow and Stock Returns", NBER 11439. ~12% R² in predicting
//    institutional ownership changes from trade-size patterns.
//  • "What Is an Order Block? The Institutional Footprint Explained" —
//    Liquidity Finder (2026). Valid OB = liquidity event + break of structure
//    + HTF alignment; mitigation = retest of unfilled orders.
//  • Pecchiari (2020), "Orderflow Imbalance and High Frequency Trading",
//    LUISS Thesis. Quantile regression for flow-return relationships.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE Trans. Signal Processing. z-score event triggers at Δ = d × σ_z.
// ============================================================================

define(
    title="Kyo OB Imbalance V2",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Order Block Detection ---
var obLookback = input(name="obLookback", type="number", defaultValue=10, label="OB Lookback (bars)", constraints={min: 5, max: 50, step: 1}, group="Order Blocks")
var pivotLen = input(name="pivotLen", type="number", defaultValue=3, label="Pivot Sensitivity", constraints={min: 1, max: 10, step: 1}, group="Order Blocks")
var volMult = input(name="volMult", type="number", defaultValue=1.5, label="Volume Threshold (x MA)", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Order Blocks")
var volMaLen = input(name="volMaLen", type="number", defaultValue=20, label="Volume MA Length", constraints={min: 5, max: 100, step: 1}, group="Order Blocks")

// --- Orderbook Depth ---
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="Orderbook")
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="Orderbook")
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="Orderbook")
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="Orderbook")
var useDepthWeighting = input(name="useDepthWeighting", type="boolean", defaultValue=true, label="Use Depth-Decaying Weights", group="Orderbook")
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="Orderbook")

// --- Z-Score & Smoothing ---
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Z-Score")
var smoothComposite = input(name="smoothComposite", type="boolean", defaultValue=true, label="Smooth Composite OBI", group="Z-Score")

// --- 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 OB Imbalance 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 OBI Line", group="Display")
var showIndividual = input(name="showIndividual", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showOBLevels = input(name="showOBLevels", type="boolean", defaultValue=true, label="Show OB Levels on Chart", 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")
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish OB Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish OB 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)
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Order Block Detection (Campbell, Ramadorai & Vuolteenaho 2005 framework)
// ------------------------------------------------------------------------------
// Detects pivot highs/lows with above-average volume — institutional footprints.

timeseries vol = priceBars.volume
timeseries volMA = sma(source=vol, period=volMaLen)
timeseries highVol = vol > volMA * volMult

// Pivot detection: new high/low within lookback window
timeseries pivotHi = priceBars.high == highest(source=priceBars.high, period=pivotLen) and priceBars.high[1] != highest(source=priceBars.high, period=pivotLen)
timeseries pivotLo = priceBars.low == lowest(source=priceBars.low, period=pivotLen) and priceBars.low[1] != lowest(source=priceBars.low, period=pivotLen)

// Order block levels: update on qualifying pivot, otherwise persist previous
static bullOB = 0.0
static bearOB = 0.0
static bullOBActive = false
static bearOBActive = false

if (pivotLo and highVol) {
    bullOB = priceBars.low
    bullOBActive = true
}
if (pivotHi and highVol) {
    bearOB = priceBars.high
    bearOBActive = true
}

// OB Imbalance = proximity to bull OB minus proximity to bear OB
// Positive = closer to bullish OB (bid support); negative = closer to bearish
var bullDist = priceBars.close - bullOB
var bearDist = bearOB - priceBars.close
var obImbalance = (bullOBActive ? bullDist : 0) - (bearOBActive ? bearDist : 0)

// ------------------------------------------------------------------------------
// Order Book Aggregation (Cont, Kukanov & Stoikov 2014; Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-depth limit order book with depth-weighted composite.
// CRITICAL: pass float percentages directly to sumBids/sumAsks (no floor/truncation).

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
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0 && bids4 > 0 && asks4 > 0

// ------------------------------------------------------------------------------
// OBI Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// OBI = (Bid − Ask) / (Bid + Ask) ∈ [−1, +1]
// Formula from Order Book Filtration and Directional Signal Extraction (2025)

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

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
var obi4 = bookAvailable && denom4 > 0 ? (bids4 - asks4) / denom4 * 100.0 : 0.0

// Bid/Ask ratio for 1% depth (additional diagnostic per Gould & Bonart 2016)
var ratio1 = bookAvailable && asks1 > 0 ? bids1 / asks1 : 1.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,4.
// Composite = Σ w_i × OBI_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 compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / 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 smoothed4 = ema(obi4, smoothLen)
var smoothedComposite = smoothComposite ? ema(compositeOBI, smoothLen) : compositeOBI

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z_t = (OBI_t − μ_t) / σ_t, where μ_t = SMA(OBI, W), σ_t = StDev(OBI, W).
// Guards: if σ_t == 0 emit 0 to prevent division-by-zero crashes.

timeseries obiMean = sma(smoothedComposite, zWindow)
timeseries obiStd = stdev(smoothedComposite, zWindow)
timeseries obiZ = (obiStd > 0) ? (smoothedComposite - obiMean) / obiStd : 0.0

// Clip z-score to ±4 for display stability
timeseries obiZClip = obiZ > 4.0 ? 4.0 : (obiZ < -4.0 ? -4.0 : obiZ)

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

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
}

// Z-score regime detection for statistical significance
var zRegime = 0
var zExtremeRegime = 0
if (obiZClip >= 2.0) {
    zRegime = 1
} else if (obiZClip <= -2.0) {
    zRegime = -1
}
if (obiZClip >= 3.0) {
    zExtremeRegime = 1
} else if (obiZClip <= -3.0) {
    zExtremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Stateful computation for anchoring, session tracking, and counters.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighOBI = -999999.0
static sessionLowOBI = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.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 (obiZClip > sessionHighZ) {
        sessionHighZ = obiZClip
    }
    if (obiZClip < sessionLowZ) {
        sessionLowZ = obiZClip
    }

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

// OB Imbalance histogram (price-relative order block imbalance)
if (showRawBars) {
    plotBar(
        value=obImbalance,
        colors=[bidColor, askColor],
        width=1,
        label=["OB Imbalance"],
        desc=["Order Block Imbalance: positive=bullish OB closer, negative=bearish OB closer"]
    )
}

// Smoothed composite OBI line 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 OBI"],
        desc=["Depth-weighted composite OBI (EMA-smoothed). Regime: bull/bear/neutral."],
        fill=true
    )
}

// Z-Score line with color-coded regime
if (showZScore) {
    plotLine(
        value=obiZClip,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=zRegime == 1 ? 0 : (zRegime == -1 ? 1 : 2),
        label=["OBI Z-Score"],
        desc=["Z-score normalized composite OBI: ±2σ = significant, ±3σ = extreme"]
    )
}

// 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)"]
    )
    plotLine(
        value=smoothed4,
        width=1,
        colors=[opacity(askColor, 50)],
        label=["OBI 10%"],
        desc=["Order Book Imbalance at 10% depth (deep book, structural level)"]
    )
}

// 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 zCrossUp = obiZClip >= 2.0 && !isnan(obiZClip[1]) && obiZClip[1] < 2.0
    var zCrossDn = obiZClip <= -2.0 && !isnan(obiZClip[1]) && obiZClip[1] > -2.0

    if (crossUp) {
        plotShape(
            value=smoothedComposite,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite OBI crossed into bullish regime (buy-heavy orderbook)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedComposite,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite OBI crossed into bearish regime (sell-heavy orderbook)"]
        )
    }
    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 (zCrossUp) {
        plotShape(
            value=obiZClip,
            shape="triangleup",
            color=extremeBidColor,
            width=2,
            label=["Z+2σ Cross"],
            desc=["OBI Z-score crossed above +2σ — statistically significant bid pressure"]
        )
    }
    if (zCrossDn) {
        plotShape(
            value=obiZClip,
            shape="triangledown",
            color=extremeAskColor,
            width=2,
            label=["Z-2σ Cross"],
            desc=["OBI Z-score crossed below -2σ — statistically significant ask pressure"]
        )
    }
}