MM Flow
FlowScripts

Perfected FlowScript

Liquidity Absorption Velocity

Liquidity Absorption Velocity [Perfected] is indexed as 140_liquidity_absorption_velocity.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.6 KB

Lines

347

Native Signal Candidates

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

4/4 guarded

Bull Regime

line 307:9

Trigger

(showShapes) && (crossBull)

Value

netPressZ

Deps

crossBull:var, showShapes:input

Bear Regime

line 317:9

Trigger

(showShapes) && (crossBear)

Value

netPressZ

Deps

crossBear:var, showShapes:input

Extreme Bull

line 327:9

Trigger

(showShapes) && (extremeBull)

Value

netPressZ

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 337:9

Trigger

(showShapes) && (extremeBear)

Value

netPressZ

Deps

extremeBear:var, showShapes:input

140_liquidity_absorption_velocity.flowscript

source path: kscripts/perfected/140_liquidity_absorption_velocity.flowscript · sha256:80f7e983029d657a973730ced843d4cee803577348c175390e422421af90abf4

hash verified
//@version=2
// ============================================================================
// Liquidity Absorption Velocity — Multi-Depth Orderbook Microstructure [Perfected]
// Author: D (@ddave334)  |  Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, #liquidity, #absorption, #velocity, #orderbook
//
// Measures the rate at which orderbook liquidity is consumed at multiple depth
// levels. Tracks bid/ask absorption separately to identify aggressive market
// participants removing liquidity before major price moves. Features depth-
// weighted composite velocity, volume-weighted normalization, z-score regime
// detection, and shape markers for extreme absorption events.
//
// FORMULA FOUNDATION:
// 1. Absorption Velocity: v = −Δ(Liquidity)/Δt  [Bouchaud et al. 2009]
// 2. Depth-Weighted Composite: Σ w_i × v_i / Σ w_i  [Xu et al. 2019]
// 3. Volume-Weighted Scaling: ṽ = v × (1 + α(V/V̄ − 1))  [Guéant 2017]
// 4. Z-Score Normalization: z = (ṽ − μ) / σ  [Zhao & Palomar 2018]
// 5. Regime Detection: Extreme absorption thresholds at ±1.5σ
//
// RESEARCH BASIS:
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes".
//    Liquidity memory time: after trade, liquidity depletes then recovers.
//    Cumulative impact is sublinear (square-root law).
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events".
//    High absorption velocity → depth depletion → λ increases → larger moves.
//    ΔP = λ · OFI; λ ∝ 1/depth.
//  • Guéant (2017), "Optimal Market Making". Informed flow hitting resting
//    orders maps to aggressive absorption detected by this velocity metric.
//  • Tóth et al. (2011), "Anomalous Price Impact and Critical Liquidity".
//    Price impact is sublinear in volume; critical liquidity thresholds exist.
// ============================================================================

define(
    title="Liquidity Absorption Velocity [Perfected]",
    position="offchart",
    axis=true
)

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

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

// --- Normalization ---
var zLen = input(name="zLen", type="number", defaultValue=30, label="Z-Score Lookback", constraints={min: 5, max: 200, step: 1}, group="Normalization")
var volWeight = input(name="volWeight", type="number", defaultValue=0.5, label="Volume Weight (0-1)", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Normalization")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Normalization")

// --- Thresholds ---
var threshold = input(name="threshold", type="number", defaultValue=1.5, label="Extreme Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Thresholds")

// --- Display ---
var showBidAsk = input(name="showBidAsk", type="boolean", defaultValue=true, label="Show Bid/Ask Absorption", group="Display")
var showNet = input(name="showNet", type="boolean", defaultValue=true, label="Show Net Pressure", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Bid Absorption Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Ask Absorption Color", group="Colors")
var netColor = input(name="netColor", type="color", defaultValue="#ab47bc", label="Net Pressure Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

// NaN guard — prevent execution on incomplete data (Cont et al. 2014 best practice)
if (isnan(c[0]) || isnan(v[0]) || isnan(h[0]) || isnan(l[0])) {
    return
}

// Orderbook data source using kScript v2 API (per pilot 001 specification)
timeseries book = source("orderbook", currentSymbol, currentExchange)

// ------------------------------------------------------------------------------
// Multi-Depth Orderbook Aggregation (Cont et al. 2014 depth-proportional impact)
// ------------------------------------------------------------------------------
// CRITICAL: The original used ob.bid_price / ob.bid_volume which is not the
// kScript v2 orderbook API. Corrected to use sumBids/sumAsks per the pilot
// specification (001_order_book_pressure.flowscript).
//
// Three depth bands (1%, 2.5%, 5%) operationalize Cont et al. (2014) finding
// that price impact slope is inversely proportional to depth.

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)

// Book availability check — prevents NaN/undefined propagation (Gould & Bonart 2016)
var bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0

// ------------------------------------------------------------------------------
// Absorption Velocity Computation (Bouchaud et al. 2009 liquidity digestion)
// ------------------------------------------------------------------------------
// Absorption = negative velocity (liquidity decreasing). When bid liquidity is
// consumed rapidly (bidSum decreases), sellers are aggressively hitting bids →
// bearish pressure. When ask liquidity is consumed (askSum decreases), buyers
// are lifting offers → bullish pressure.

// Raw velocity at each depth: ΔLiquidity/Δt
var bidVel1 = bids1 - nz(bids1[1])
var askVel1 = asks1 - nz(asks1[1])
var bidVel2 = bids2 - nz(bids2[1])
var askVel2 = asks2 - nz(asks2[1])
var bidVel3 = bids3 - nz(bids3[1])
var askVel3 = asks3 - nz(asks3[1])

// Absorption = −velocity (positive = liquidity being consumed)
var bidAbs1 = bookAvailable ? -bidVel1 : 0.0
var askAbs1 = bookAvailable ? -askVel1 : 0.0
var bidAbs2 = bookAvailable ? -bidVel2 : 0.0
var askAbs2 = bookAvailable ? -askVel2 : 0.0
var bidAbs3 = bookAvailable ? -bidVel3 : 0.0
var askAbs3 = bookAvailable ? -askVel3 : 0.0

// ------------------------------------------------------------------------------
// Volume-Weighted Scaling (Guéant 2017 informed flow intensity)
// ------------------------------------------------------------------------------
// Scale absorption by relative volume intensity. High-volume periods amplify
// velocity (more informed flow); low-volume periods dampen it. Dimensional
// consistency: rawAbs × (1 + α(V/V̄ − 1)).

timeseries avgVol = rma(v, zLen)
timeseries volMult = v / max(avgVol, 1e-9)

var bidAbs1W = bidAbs1 * (1.0 + volWeight * (volMult - 1.0))
var askAbs1W = askAbs1 * (1.0 + volWeight * (volMult - 1.0))
var bidAbs2W = bidAbs2 * (1.0 + volWeight * (volMult - 1.0))
var askAbs2W = askAbs2 * (1.0 + volWeight * (volMult - 1.0))
var bidAbs3W = bidAbs3 * (1.0 + volWeight * (volMult - 1.0))
var askAbs3W = askAbs3 * (1.0 + volWeight * (volMult - 1.0))

// ------------------------------------------------------------------------------
// Depth-Weighted Composite (Xu, Gould & Howison 2019 multi-level OFI)
// ------------------------------------------------------------------------------
// Geometrically decaying weights: w_i = decay^(i−1). This improves short-horizon
// prediction vs. top-of-book alone by incorporating deeper book structure.

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

var compBidAbs = wSum > 0 ? (w1 * bidAbs1W + w2 * bidAbs2W + w3 * bidAbs3W) / wSum : 0.0
var compAskAbs = wSum > 0 ? (w1 * askAbs1W + w2 * askAbs2W + w3 * askAbs3W) / wSum : 0.0

// Smoothing (EMA per Cont et al. 2014 noise-reduction)
var smoothBidAbs = ema(compBidAbs, smoothLen)
var smoothAskAbs = ema(compAskAbs, smoothLen)

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Normalize composite absorption to z-scores for cross-asset comparability
// and regime detection. Zero-division guards prevent NaN on flat periods.

var bMean = sma(smoothBidAbs, zLen)
var bStd = stdev(smoothBidAbs, zLen)
var bAbsZ = (smoothBidAbs - bMean) / max(bStd, 1e-9)

var aMean = sma(smoothAskAbs, zLen)
var aStd = stdev(smoothAskAbs, zLen)
var aAbsZ = (smoothAskAbs - aMean) / max(aStd, 1e-9)

// ------------------------------------------------------------------------------
// Net Pressure (positive = more ask absorption than bid = bullish)
// ------------------------------------------------------------------------------
// Net pressure = askAbsZ − bidAbsZ. Positive when buyers are lifting offers
// faster than sellers are hitting bids → bullish pressure.
// Per Cont et al. (2014): ΔP ≈ OFI / Depth; aggressive absorption predicts
// imminent directional moves.

var netPressRaw = aAbsZ - bAbsZ
var netPressSmooth = ema(netPressRaw, smoothLen)

// Net pressure z-score for regime detection
var npMean = sma(netPressSmooth, zLen)
var npStd = stdev(netPressSmooth, zLen)
var netPressZ = (netPressSmooth - npMean) / max(npStd, 1e-9)

// ------------------------------------------------------------------------------
// Regime Detection (5-tier: extreme bull, bull, neutral, bear, extreme bear)
// ------------------------------------------------------------------------------
// Based on net pressure z-score relative to configurable threshold.

var netRegime = 2
if (netPressZ >= threshold * 1.5) {
    netRegime = 0
} else if (netPressZ >= threshold) {
    netRegime = 1
} else if (netPressZ <= -threshold * 1.5) {
    netRegime = 4
} else if (netPressZ <= -threshold) {
    netRegime = 3
} else {
    netRegime = 2
}

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

static lastBarIndex = 0
static sessionHighNetZ = -999999.0
static sessionLowNetZ = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static regimeChangeCount = 0
static lastNetRegime = 2

var currentBarIndex = bar_index[0]

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

    if (netPressZ > sessionHighNetZ) {
        sessionHighNetZ = netPressZ
    }
    if (netPressZ < sessionLowNetZ) {
        sessionLowNetZ = netPressZ
    }

    if (netPressZ >= threshold * 1.5) {
        extremeBullCount = extremeBullCount + 1
    }
    if (netPressZ <= -threshold * 1.5) {
        extremeBearCount = extremeBearCount + 1
    }

    if (lastNetRegime != netRegime) {
        lastNetRegime = netRegime
        regimeChangeCount = regimeChangeCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Fill, Shape, HLine)
// ------------------------------------------------------------------------------

// Zero line and threshold guides
hline(value=0, color="#ffffff30", width=1)
if (showGuides) {
    hline(value=threshold, color=opacity(bidColor, 30), width=1)
    hline(value=-threshold, color=opacity(askColor, 30), width=1)
    hline(value=threshold * 1.5, color=opacity(extremeBullColor, 20), width=1)
    hline(value=-threshold * 1.5, color=opacity(extremeBearColor, 20), width=1)
}

// Bid absorption z-score (positive = bids consumed = sellers aggressive = bearish)
if (showBidAsk) {
    plotLine(
        value=bAbsZ,
        width=1,
        colors=[bidColor],
        label=["Bid Absorption Z"],
        desc=["Bid liquidity absorption z-score (positive = bids consumed = bearish pressure)"]
    )
    plotLine(
        value=aAbsZ,
        width=1,
        colors=[askColor],
        label=["Ask Absorption Z"],
        desc=["Ask liquidity absorption z-score (positive = asks consumed = bullish pressure)"]
    )
}

// Net pressure with 5-tier regime fill
if (showNet) {
    plotLine(
        value=netPressZ,
        width=2,
        colors=[extremeBullColor, bidColor, neutralColor, askColor, extremeBearColor],
        colorIndex=netRegime,
        label=["Net Pressure Z"],
        desc=["Net liquidity pressure z-score (ask minus bid absorption). 5-tier regime fill."],
        fill=true
    )
}

// Shape markers for extreme regime events
if (showShapes) {
    var crossBull = netPressZ >= threshold && !isnan(netPressZ[1]) && netPressZ[1] < threshold
    var crossBear = netPressZ <= -threshold && !isnan(netPressZ[1]) && netPressZ[1] > -threshold
    var extremeBull = netPressZ >= threshold * 1.5 && !isnan(netPressZ[1]) && netPressZ[1] < threshold * 1.5
    var extremeBear = netPressZ <= -threshold * 1.5 && !isnan(netPressZ[1]) && netPressZ[1] > -threshold * 1.5

    if (crossBull) {
        plotShape(
            value=netPressZ,
            shape="triangleup",
            color=bidColor,
            width=3,
            label=["Bull Regime"],
            desc=["Net pressure crossed into bullish regime (buyers aggressively lifting offers)"]
        )
    }
    if (crossBear) {
        plotShape(
            value=netPressZ,
            shape="triangledown",
            color=askColor,
            width=3,
            label=["Bear Regime"],
            desc=["Net pressure crossed into bearish regime (sellers aggressively hitting bids)"]
        )
    }
    if (extremeBull) {
        plotShape(
            value=netPressZ,
            shape="diamond",
            color=extremeBullColor,
            width=4,
            label=["Extreme Bull"],
            desc=["Extreme bullish absorption detected — aggressive offer lifting (institutional buying)"]
        )
    }
    if (extremeBear) {
        plotShape(
            value=netPressZ,
            shape="diamond",
            color=extremeBearColor,
            width=4,
            label=["Extreme Bear"],
            desc=["Extreme bearish absorption detected — aggressive bid hitting (institutional selling)"]
        )
    }
}