MM Flow
FlowScripts

Perfected FlowScript

Orderbook Skew

Orderbook Skew V2 is indexed as 088_orderbook_skew.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.5 KB

Lines

379

Native Signal Candidates

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

6/6 guarded

Bull Regime

line 319:9

Trigger

(showShapes) && (crossUp)

Value

smoothedComposite

Deps

crossUp:var, showShapes:input

Bear Regime

line 329:9

Trigger

(showShapes) && (crossDn)

Value

smoothedComposite

Deps

crossDn:var, showShapes:input

Extreme Bid

line 339:9

Trigger

(showShapes) && (extremeUp)

Value

smoothedComposite

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 349:9

Trigger

(showShapes) && (extremeDn)

Value

smoothedComposite

Deps

extremeDn:var, showShapes:input

Z+ Extreme

line 359:9

Trigger

(showShapes) && (zExtremeUp)

Value

zScore

Deps

showShapes:input, zExtremeUp:var

Z− Extreme

line 369:9

Trigger

(showShapes) && (zExtremeDn)

Value

zScore

Deps

showShapes:input, zExtremeDn:var

088_orderbook_skew.flowscript

source path: kscripts/perfected/088_orderbook_skew.flowscript · sha256:8c2a0b9035a44ba169f27c2ccc165d2396be8e84c13f4c6d5226e64cd697c857

hash verified
//@version=2
// ============================================================================
// Orderbook Skew V2 — Production-Quality Asymmetry Detector
// Author: N (@neongrace)  |  Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #orderbook, #skew, #asymmetry, #microstructure, #imbalance, #OBI
//
// Measures orderbook skew (asymmetry in depth) across three depth layers —
// near-surface, mid, and far — with weighted composite, z-score normalization,
// regime detection, color-coded visualization, and shape markers. Reveals whether
// price moves are backed by real liquidity or just surface games.
//
// FORMULA FOUNDATION:
// 1. Orderbook Skew: Skew = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
//    per Order Book Filtration (2025). Measures tilt at each depth layer.
// 2. Depth-Weighted Composite Skew: Σ w_i × Skew_i / Σ w_i, w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019). Near-surface (1%) gets highest weight;
//    far (15%) gets lowest. Deeper levels improve short-horizon prediction.
// 3. Z-Score Normalization: z = (Skew − μ_Skew) / σ_Skew per Zhao & Palomar (2018).
//    Enables cross-asset comparability and mean-reversion signal detection.
// 4. Regime Segmentation: Sell-heavy (−1, −1/3), Neutral (−1/3, +1/3),
//    Buy-heavy (+1/3, +1) per Cartea, Donnelly & Jaimungal (2018).
// 5. Divergence Detection: When near-surface and far-depth skew diverge,
//    shallow liquidity is tactical (flipping) while deeper players are anchored.
//    per Lipton, Pesavento & Sotiropoulos (2013) — L1 signal strongest but
//    most transient; deeper levels show structural commitment.
//
// RESEARCH BASIS:
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Deeper-level imbalance significantly improves
//    short-horizon price prediction compared to top-of-book alone. The three-layer
//    skew analysis directly applies this finding.
//  • Lipton, Pesavento & Sotiropoulos (2013), "Trade Arrival Dynamics and Quote
//    Imbalance in a Limit Order Book", arXiv:1312.0514. L1 imbalance strongest
//    predictor but weakens with depth. The script's layer comparison reveals when
//    shallow and deep levels diverge, indicating tactical vs. structural flow.
//  • Paddrik, Hayes, Scherer & Beling (2014), "Effects of Limit Order Book
//    Information Level on Market Stability Metrics", OFR Working Paper 2014-09.
//    Developed OBWA using first 10 best bid/ask ticks. Deeper book information
//    improves market stability assessment — supports multi-layer skew analysis.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI = Σ(E_bid^i − E_ask^i);
//    linear price-impact model; slope ∝ 1/depth. Asymmetry at shallow levels has
//    higher immediate price impact than deep-level asymmetry.
//  • 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̄_t = (z_t − μ_z) / σ_z; entry thresholds
//    at d × σ_z. Formalizes z-score normalization framework.
//  • 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.
// ============================================================================

define(
    title="Orderbook Skew V2",
    position="offchart",
    axis=true
)

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

// --- Depth Configuration ---
var depthNear = input(name="depthNear", type="number", defaultValue=1.0, label="Near-Surface Depth (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depthMid = input(name="depthMid", type="number", defaultValue=5.0, label="Mid Depth (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depthFar = input(name="depthFar", type="number", defaultValue=15.0, label="Far Depth (%)", 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=10, 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 Skew", group="Smoothing")

// --- Z-Score ---
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Enable Z-Score Normalization", group="Z-Score")
var zScoreWindow = input(name="zScoreWindow", type="number", defaultValue=50, label="Z-Score Lookback Window", constraints={min: 10, max: 200, step: 5}, 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 Raw Skew Bars", 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 showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", 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 zScoreColor = input(name="zScoreColor", type="color", defaultValue="#ffca28", label="Z-Score 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
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Order Book Aggregation
// ------------------------------------------------------------------------------
var bidsNear = sumBids(book, depthNear)
var asksNear = sumAsks(book, depthNear)
var bidsMid = sumBids(book, depthMid)
var asksMid = sumAsks(book, depthMid)
var bidsFar = sumBids(book, depthFar)
var asksFar = sumAsks(book, depthFar)

// Book availability check — prevents NaN/undefined propagation
var bookAvailable = bidsNear > 0 && asksNear > 0 && bidsMid > 0 && asksMid > 0 && bidsFar > 0 && asksFar > 0

// ------------------------------------------------------------------------------
// Skew Computation with Zero-Division Guards
// ------------------------------------------------------------------------------
// Skew = (BidVol − AskVol) / (BidVol + AskVol) ∈ [−1, +1]
// per Order Book Filtration (2025) and Cont et al. (2014).

var denomNear = bidsNear + asksNear
var denomMid = bidsMid + asksMid
var denomFar = bidsFar + asksFar

var skewNear = bookAvailable && denomNear > 0 ? (bidsNear - asksNear) / denomNear * 100.0 : 0.0
var skewMid = bookAvailable && denomMid > 0 ? (bidsMid - asksMid) / denomMid * 100.0 : 0.0
var skewFar = bookAvailable && denomFar > 0 ? (bidsFar - asksFar) / denomFar * 100.0 : 0.0

// ------------------------------------------------------------------------------
// Depth-Weighted Composite Skew (Xu, Gould & Howison 2019)
// ------------------------------------------------------------------------------
// Multi-level skew with geometrically decaying weights.
// w_i = decay^(i−1) for i = 1,2,3 (near, mid, far).
// Near-surface gets highest weight; far depth gets lowest.
// Composite = Σ w_i × Skew_i / Σ w_i.

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

var wSum = w1 + w2 + w3
var compositeSkew = wSum > 0 ? (w1 * skewNear + w2 * skewMid + w3 * skewFar) / wSum : 0.0

// ------------------------------------------------------------------------------
// Smoothing (EMA per Cont et al. 2014 noise-reduction)
// ------------------------------------------------------------------------------
var smoothedNear = ema(skewNear, smoothLen)
var smoothedMid = ema(skewMid, smoothLen)
var smoothedFar = ema(skewFar, smoothLen)
var smoothedComposite = smoothComposite ? ema(compositeSkew, smoothLen) : compositeSkew

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z = (current − mean) / stddev over rolling window.
// Enables cross-asset comparability and mean-reversion signal detection.

var skewMean = sma(smoothedComposite, zScoreWindow)
var skewStd = stdev(smoothedComposite, zScoreWindow)
var zScore = useZScore && skewStd > 0 ? (smoothedComposite - skewMean) / skewStd : 0.0

// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes:
//   Sell-heavy: Skew ≤ bearThresh
//   Neutral:    bearThresh < Skew < bullThresh
//   Buy-heavy:  Skew ≥ 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
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighSkew = -999999.0
static sessionLowSkew = 999999.0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (compositeSkew > sessionHighSkew) {
        sessionHighSkew = compositeSkew
    }
    if (compositeSkew < sessionLowSkew) {
        sessionLowSkew = compositeSkew
    }

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

// Raw normalized composite skew as color-coded histogram bars
if (showRawBars) {
    plotBar(
        value=smoothedComposite,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        width=1,
        label=["Composite Skew"],
        desc=["Depth-weighted composite skew (positive=bid, negative=ask). Regime-coded."]
    )
}

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

// Z-Score line (cross-asset comparable mean-reversion signal)
if (showZScore && useZScore) {
    plotLine(
        value=zScore,
        width=1,
        colors=[zScoreColor],
        label=["Z-Score"],
        desc=["Rolling z-score of composite skew. |z| > 2 flags statistically extreme asymmetry."]
    )
}

// Individual depth lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=smoothedNear,
        width=1,
        colors=[opacity(bidColor, 50)],
        label=["Skew Near"],
        desc=["Near-surface skew at 1% depth (shallow book, tactical, flips quickly)"]
    )
    plotLine(
        value=smoothedMid,
        width=1,
        colors=[opacity(bidColor, 40)],
        label=["Skew Mid"],
        desc=["Mid-depth skew at 5% (intermediate liquidity layer)"]
    )
    plotLine(
        value=smoothedFar,
        width=1,
        colors=[opacity(askColor, 40)],
        label=["Skew Far"],
        desc=["Far-depth skew at 15% (deep book, structural, slow to change)"]
    )
}

// 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 zExtremeUp = useZScore && zScore >= 2.0 && !isnan(zScore[1]) && zScore[1] < 2.0
    var zExtremeDn = useZScore && zScore <= -2.0 && !isnan(zScore[1]) && zScore[1] > -2.0

    if (crossUp) {
        plotShape(
            value=smoothedComposite,
            shape="triangleup",
            color=extremeBidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Composite skew crossed into bullish regime (buy-heavy)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothedComposite,
            shape="triangledown",
            color=extremeAskColor,
            width=3,
            label=["Bear Regime"],
            desc=["Composite skew crossed into bearish regime (sell-heavy)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=smoothedComposite,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid skew detected — deep book buy-heavy asymmetry"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=smoothedComposite,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask skew detected — deep book sell-heavy asymmetry"]
        )
    }
    if (zExtremeUp) {
        plotShape(
            value=zScore,
            shape="flag",
            color=extremeBidColor,
            width=3,
            label=["Z+ Extreme"],
            desc=["Z-score extreme: statistically unusual buy-heavy skew (z ≥ 2)"]
        )
    }
    if (zExtremeDn) {
        plotShape(
            value=zScore,
            shape="flag",
            color=extremeAskColor,
            width=3,
            label=["Z− Extreme"],
            desc=["Z-score extreme: statistically unusual sell-heavy skew (z ≤ −2)"]
        )
    }
}