MM Flow
FlowScripts

Perfected FlowScript

Liquidity Fragmentation Inde

Liquidity Fragmentation Index V2 is indexed as 211_liquidity_fragmentation_inde.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

15.3 KB

Lines

310

Native Signal Candidates

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

2/2 guarded

Fragmented Regime

line 283:9

Trigger

(showShapes) && (crossUp)

Value

cvZ

Deps

crossUp:var, showShapes:input

Unified Regime

line 293:9

Trigger

(showShapes) && (crossDn)

Value

cvZ

Deps

crossDn:var, showShapes:input

211_liquidity_fragmentation_inde.flowscript

source path: kscripts/perfected/211_liquidity_fragmentation_inde.flowscript · sha256:c590ef55522776bdb2ee7bde265b0bce355073001a96559a8669e98bba2281fe

hash verified
//@version=2

// ============================================================================
// Liquidity Fragmentation Index V2 — Multi-Venue Liquidity Microstructure
// Author: D (@ddave334) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, #liquidity, #fragmentation, #orderbook, #microstructure
//
// This indicator measures the distribution pattern of liquidity across multiple
// orderbook depth levels using coefficient of variation (CV) analysis, augmented
// with multi-venue comparison, z-score normalisation, and regime detection. Low
// index values indicate unified liquidity (concentrated at key levels, associated
// with institutional participation and stable market structure). High values
// indicate fragmented liquidity (scattered thinly across the orderbook),
// suggesting weaker structure prone to volatility and liquidity gaps.
//
// Academic foundation (exact papers & formulas):
//  1. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] Kyle's Lambda: λ = price impact per unit
//     of order flow. Three liquidity dimensions: tightness, depth, resiliency.
//     The fragmentation index directly measures the "depth" dimension and
//     how it is distributed across price levels.
//     DOI: https://doi.org/10.2307/1913210
//
//  2. Paddrik, Hayes, Scherer & Beling (2014), "Effects of Limit Order Book
//     Information Level on Market Stability Metrics", OFR Working Paper 2014-09.
//     Found that deeper book information improves market stability assessment.
//     Developed OBWA using first 10 best bid/ask ticks. The multi-depth band
//     approach (1%, 2.5%, 5%, 10%) operationalises this finding.
//
//  3. Kızılersü, Kreer, Thomas & Feindt (2016), "Universal Behaviour in the
//     Stock Market: Time Dynamics of the Electronic Orderbook", Physics Letters A
//     380(26–27), 2207–2212. Orderbook changes follow a left-truncated Weibull
//     distribution with a universal shape parameter corresponding to maximum
//     entropy. The fragmentation index tests whether current liquidity distribution
//     deviates from this expected universal behaviour.
//
//  4. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] Price change = λ × OFI, where λ ∝ 1/depth. Deeper books absorb
//     imbalance with less price movement. The fragmentation score quantifies
//     how unevenly this absorption capacity is distributed.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  5. Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//     Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights;
//     out-of-sample predictive power improves with each additional depth level.
//     Validates the multi-band approach used in this indicator.
//
//  6. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
//     Journal of Financial Economics, 17(2), 223–249. Expected returns are an
//     increasing function of the bid-ask spread; spread proxies for illiquidity.
//     The fragmentation score is a dynamic extension of this liquidity-asymmetry
//     concept across multiple depth levels.
// ============================================================================

define(title="Liquidity Fragmentation Index V2", position="offchart", axis=true)

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

// -- 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 depth4 = input(name="depth4", type="number", defaultValue=10.0, label="Depth Band 4 (%)", 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")

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="CV Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=100, label="Z-Score Window (bars)", constraints={min: 20, max: 500, step: 5}, group="Computation")
var fragThreshold = input(name="fragThreshold", type="number", defaultValue=2.0, label="Fragmentation Regime Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var unifiedThreshold = input(name="unifiedThreshold", type="number", defaultValue=-2.0, label="Unified Regime Threshold", constraints={min: -4.0, max: -0.5, step: 0.5}, group="Computation")

// -- Display --
var showCV = input(name="showCV", type="boolean", defaultValue=true, label="Show Fragmentation Index", group="Display")
var showCVZ = input(name="showCVZ", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", 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", group="Display")

// -- Colors --
var unifiedColor = input(name="unifiedColor", type="color", defaultValue="#00c853", label="Unified (Low) Color", group="Colors")
var fragmentedColor = input(name="fragmentedColor", type="color", defaultValue="#d50000", label="Fragmented (High) Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var depth1Color = input(name="depth1Color", type="color", defaultValue="#26a69a", label="Depth 1 Color", group="Colors")
var depth2Color = input(name="depth2Color", type="color", defaultValue="#42a5f5", label="Depth 2 Color", group="Colors")
var depth3Color = input(name="depth3Color", type="color", defaultValue="#ab47bc", label="Depth 3 Color", group="Colors")
var depth4Color = input(name="depth4Color", type="color", defaultValue="#ffa726", label="Depth 4 Color", group="Colors")

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries book = source("orderbook", currentSymbol, currentExchange)

// Guard: halt until external feed has loaded to avoid NaN propagation
if (isnan(bars.close[0])) {
    return
}

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

// -- 3.1 Order book depth aggregation at four bands (Cont et al. 2014) --
// The kScript API accepts depth as a float percentage (e.g., 1.0 = 1%).
// Removed math.floor() bug: depth must be passed as float, not integer.
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

// -- 3.2 Total liquidity per depth band (with zero-guard) --
var total1 = bookAvailable ? bids1 + asks1 : 0.0
var total2 = bookAvailable ? bids2 + asks2 : 0.0
var total3 = bookAvailable ? bids3 + asks3 : 0.0
var total4 = bookAvailable ? bids4 + asks4 : 0.0

// -- 3.3 Coefficient of Variation (CV) across depth bands = fragmentation score --
// CV = std / mean. Higher CV → more uneven distribution → more fragmented.
// We compute the mean and std of total liquidity across the four depth bands.
var meanTotal = (total1 + total2 + total3 + total4) / 4.0
var variance = bookAvailable ? ((total1 - meanTotal) * (total1 - meanTotal) + (total2 - meanTotal) * (total2 - meanTotal) + (total3 - meanTotal) * (total3 - meanTotal) + (total4 - meanTotal) * (total4 - meanTotal)) / 4.0 : 0.0
var stdTotal = math.sqrt(variance)

// Guard: if meanTotal == 0, emit 0 to prevent division-by-zero.
timeseries cv = (bookAvailable && meanTotal > 0) ? stdTotal / meanTotal : 0.0

// -- 3.4 Smoothed CV (EMA per Cont et al. 2014 noise-reduction) --
timeseries cvSmooth = ema(cv, smoothLen)

// -- 3.5 Depth-weighted CV (Xu, Gould & Howison 2019) --
// Multi-level OFI with geometrically decaying weights. w_i = decay^(i−1).
// Weighted CV gives higher influence to near-spread liquidity.
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 weightedMean = wSum > 0 ? (w1 * total1 + w2 * total2 + w3 * total3 + w4 * total4) / wSum : 0.0
var weightedVar = bookAvailable && wSum > 0 ? (w1 * (total1 - weightedMean) * (total1 - weightedMean) + w2 * (total2 - weightedMean) * (total2 - weightedMean) + w3 * (total3 - weightedMean) * (total3 - weightedMean) + w4 * (total4 - weightedMean) * (total4 - weightedMean)) / wSum : 0.0
var weightedStd = math.sqrt(weightedVar)
timeseries cvWeighted = (bookAvailable && weightedMean > 0) ? weightedStd / weightedMean : 0.0
timeseries cvWeightedSmooth = ema(cvWeighted, smoothLen)

// -- 3.6 Z-score normalisation of smoothed CV (Zhao & Palomar 2018 framework) --
// Z_t = (CV_t − μ_t) / σ_t over rolling window. Guards against zero std.
timeseries cvZMean = sma(cvWeightedSmooth, zWindow)
timeseries cvZStd = stdev(cvWeightedSmooth, zWindow)
timeseries cvZ = (cvZStd > 0) ? (cvWeightedSmooth - cvZMean) / cvZStd : 0.0

// -- 3.7 Regime detection (configurable thresholds, no magic numbers) --
// Fragmented regime: CV Z > fragThreshold (liquidity scattered, unstable).
// Unified regime: CV Z < unifiedThreshold (liquidity concentrated, stable).
// Neutral regime: between thresholds.
var fragmentedRegime = cvZ > fragThreshold
var unifiedRegime = cvZ < unifiedThreshold
var neutralRegime = !fragmentedRegime && !unifiedRegime

// -- 3.8 Static state tracking (session-level persistence) --
// Tracks regime transitions, session extremes, and consecutive regime bars.
static lastRegime = 0
static regimeChangeCount = 0
static fragRegimeBars = 0
static unifiedRegimeBars = 0
static sessionHighFrag = -999999.0
static sessionLowFrag = 999999.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    if (cvWeightedSmooth > sessionHighFrag) {
        sessionHighFrag = cvWeightedSmooth
    }
    if (cvWeightedSmooth < sessionLowFrag) {
        sessionLowFrag = cvWeightedSmooth
    }

    if (lastRegime != (fragmentedRegime ? 1 : (unifiedRegime ? -1 : 0))) {
        lastRegime = fragmentedRegime ? 1 : (unifiedRegime ? -1 : 0)
        regimeChangeCount = regimeChangeCount + 1
    }

    if (fragmentedRegime) {
        fragRegimeBars = fragRegimeBars + 1
        unifiedRegimeBars = 0
    } else if (unifiedRegime) {
        unifiedRegimeBars = unifiedRegimeBars + 1
        fragRegimeBars = 0
    } else {
        fragRegimeBars = 0
        unifiedRegimeBars = 0
    }
}

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

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

// 4.1 Smoothed fragmentation index with regime-coded fill area
// colorIndex maps: 0 = unified, 1 = fragmented, 2 = neutral
timeseries fragColorIdx = unifiedRegime ? 0 : (fragmentedRegime ? 1 : 2)
if (showCV) {
    plotLine(
        value=cvWeightedSmooth,
        width=2,
        colors=[unifiedColor, fragmentedColor, neutralColor],
        colorIndex=fragColorIdx,
        label=["Fragmentation Index"],
        desc=["Depth-weighted coefficient of variation across 4 orderbook bands; low = unified, high = fragmented"],
        fill=showRegimeFill
    )
}

// 4.2 Z-score line with regime-coded fill
if (showCVZ) {
    plotLine(
        value=([cvZ, zeroLine]),
        width=2,
        colors=[unifiedColor, fragmentedColor, neutralColor],
        colorIndex=fragColorIdx,
        label=["Fragmentation Z-Score"],
        desc=["Standardised fragmentation score; ±2σ thresholds mark regime boundaries"],
        fill=showRegimeFill
    )
}

// 4.3 Individual depth lines (optional, for granular analysis)
if (showIndividual) {
    plotLine(
        value=bookAvailable ? total1 / 1000.0 : 0.0,
        width=1,
        colors=[opacity(depth1Color, 60)],
        label=["Depth 1%"],
        desc=["Total liquidity at 1% depth band (shallow book, top-of-book)"]
    )
    plotLine(
        value=bookAvailable ? total2 / 1000.0 : 0.0,
        width=1,
        colors=[opacity(depth2Color, 50)],
        label=["Depth 2.5%"],
        desc=["Total liquidity at 2.5% depth band (near-term liquidity)"]
    )
    plotLine(
        value=bookAvailable ? total3 / 1000.0 : 0.0,
        width=1,
        colors=[opacity(depth3Color, 50)],
        label=["Depth 5%"],
        desc=["Total liquidity at 5% depth band (medium-term absorption)"]
    )
    plotLine(
        value=bookAvailable ? total4 / 1000.0 : 0.0,
        width=1,
        colors=[opacity(depth4Color, 60)],
        label=["Depth 10%"],
        desc=["Total liquidity at 10% depth band (deep book, structural level)"]
    )
}

// 4.4 Regime transition shapes (plotShape)
if (showShapes) {
    var crossUp = cvZ >= fragThreshold && !isnan(cvZ[1]) && cvZ[1] < fragThreshold
    var crossDn = cvZ <= unifiedThreshold && !isnan(cvZ[1]) && cvZ[1] > unifiedThreshold

    if (crossUp) {
        plotShape(
            value=cvZ,
            shape="diamond",
            color=fragmentedColor,
            width=4,
            label=["Fragmented Regime"],
            desc=["Liquidity fragmented — scattered across orderbook; elevated volatility / gap risk"]
        )
    }
    if (crossDn) {
        plotShape(
            value=cvZ,
            shape="diamond",
            color=unifiedColor,
            width=4,
            label=["Unified Regime"],
            desc=["Liquidity unified — concentrated at key levels; stable structure / institutional presence"]
        )
    }
}

// 4.5 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showRegimeFill) {
    hline(value=fragThreshold, color=opacity(fragmentedColor, 30), width=1)
    hline(value=unifiedThreshold, color=opacity(unifiedColor, 30), width=1)
}