MM Flow
FlowScripts

Perfected FlowScript

Hidden Liquidity Detector

Hidden Liquidity Detector V2 is indexed as 115_hidden_liquidity_detector.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.6 KB

Lines

439

Native Signal Candidates

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

5/5 guarded

Elevated Signal

line 389:9

Trigger

(showShapes) && (crossUpLow)

Value

scoreSmooth

Deps

crossUpLow:var, showShapes:input

High Signal

line 399:9

Trigger

(showShapes) && (crossUpHigh)

Value

scoreSmooth

Deps

crossUpHigh:var, showShapes:input

Extreme Signal

line 409:9

Trigger

(showShapes) && (crossUpExtreme)

Value

scoreSmooth

Deps

crossUpExtreme:var, showShapes:input

High Exit

line 419:9

Trigger

(showShapes) && (crossDnHigh)

Value

scoreSmooth

Deps

crossDnHigh:var, showShapes:input

Elevated Exit

line 429:9

Trigger

(showShapes) && (crossDnLow)

Value

scoreSmooth

Deps

crossDnLow:var, showShapes:input

115_hidden_liquidity_detector.flowscript

source path: kscripts/perfected/115_hidden_liquidity_detector.flowscript · sha256:748af849d4f8026f16595f3540f75ce33bfe0077cc4864c60e58695e418dbd53

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// Hidden Liquidity Detector V2 — Iceberg Orders, Spoofing & Depth Analysis
// Author: D (@ddave334) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #orderbook, #iceberg, #spoofing, #liquidity, #microstructure, #hidden
//
// Detects potential iceberg orders, spoofing patterns, and hidden liquidity
// by analyzing the relationship between trade volume, visible orderbook depth,
// and cancellation dynamics. Uses multi-level depth analysis with geometric
// decaying weights per Xu, Gould & Howison (2019). Outputs a probability score
// with regime detection, color-coded fills, and shape markers.
//
// FORMULA FOUNDATION:
// 1. Iceberg Detection: high volume + stable top-of-book depth → replenishment.
//    Frey & Sandas (2009/2017): iceberg orders display lower temporary impact
//    and higher execution probability than visible orders.
// 2. Spoofing Detection: large depth insertion + rapid cancellation within same bar.
//    Zotikov & Antonov (2021): spoofing shows characteristic depth-peak-then-
//    collapse pattern within 100–500ms.
// 3. Depth-Weighted Composite: Σ w_i × OBI_i / Σ w_i where w_i = decay^(i−1)
//    per Xu, Gould & Howison (2019).
// 4. Regime Segmentation: Low (<33), Elevated (33–66), High (>66) probability.
// 5. Kyle (1985) liquidity dimensions: depth = ability to absorb large orders.
//
// RESEARCH BASIS:
//  • Frey & Sandas (2009/2017), "The Impact of Iceberg Orders in Limit Order
//    Books", J. Trading / Market Microstructure. Iceberg orders reduce adverse
//    selection costs and reveal informed trader intent. Hidden liquidity is
//    estimated at 15–30% of visible depth in equity markets; higher in crypto.
//  • Zotikov & Antonov (2021), "CME Iceberg Order Detection and Prediction".
//    Spoofing detection via cancellation-to-insertion ratio > 0.8 and depth
//    collapse within 500ms. ML models achieve 78% precision on CME LOB data.
//  • Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica 53(6).
//    Three liquidity dimensions: tightness, depth, resiliency. Hidden liquidity
//    improves depth without widening spread (tightness preserved).
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Price impact slope ∝ 1/depth;
//    hidden liquidity flattens the impact curve.
//  • Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a Limit
//    Order Book", arXiv:1907.06230. Multi-level OFI with decaying weights
//    significantly improves prediction vs. top-of-book alone.
//  • 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.
//  • 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).
// ============================================================================

define(
    title="Hidden Liquidity Detector V2",
    position="offchart",
    axis=true
)

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

// --- Depth Configuration ---
var depth1 = input(name="depth1", type="number", defaultValue=0.5, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth2 = input(name="depth2", type="number", defaultValue=1.0, label="Depth Band 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth3 = input(name="depth3", type="number", defaultValue=2.5, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth4 = input(name="depth4", type="number", defaultValue=5.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")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var smoothScore = input(name="smoothScore", type="boolean", defaultValue=true, label="Smooth Probability Score", group="Smoothing")

// --- Thresholds & Regime ---
var lowThresh = input(name="lowThresh", type="number", defaultValue=33.0, label="Elevated Probability Threshold (0-100)", constraints={min: 10.0, max: 90.0, step: 1.0}, group="Thresholds")
var highThresh = input(name="highThresh", type="number", defaultValue=66.0, label="High Probability Threshold (0-100)", constraints={min: 10.0, max: 95.0, step: 1.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=85.0, label="Extreme Probability Threshold (0-100)", constraints={min: 50.0, max: 99.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 Probability Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showScoreLine = input(name="showScoreLine", type="boolean", defaultValue=true, label="Show Smoothed Score Line", group="Display")
var showDepthLines = input(name="showDepthLines", type="boolean", defaultValue=false, label="Show Individual Depth Lines", group="Display")
var showCV = input(name="showCV", type="boolean", defaultValue=false, label="Show Depth CV Diagnostic", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var lowColor = input(name="lowColor", type="color", defaultValue="#26a69a", label="Low/Normal Color", group="Colors")
var elevatedColor = input(name="elevatedColor", type="color", defaultValue="#ffa726", label="Elevated Color", group="Colors")
var highColor = input(name="highColor", type="color", defaultValue="#ef5350", label="High Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff1744", label="Extreme Color", group="Colors")
var scoreLineColor = input(name="scoreLineColor", type="color", defaultValue="#42a5f5", label="Score Line Color", group="Colors")
var bandColor = input(name="bandColor", type="color", defaultValue="#9e9e9e", label="Guide Band Color", group="Colors")
var fillLowColor = input(name="fillLowColor", type="color", defaultValue="#26a69a20", label="Low Fill Color", group="Colors")
var fillElevatedColor = input(name="fillElevatedColor", type="color", defaultValue="#ffa72620", label="Elevated Fill Color", group="Colors")
var fillHighColor = input(name="fillHighColor", type="color", defaultValue="#ef535020", label="High Fill Color", group="Colors")

// -----------------------------------------------------------------------------
// Data Sources
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries closePx = bars.close
timeseries highPx = bars.high
timeseries lowPx = bars.low
timeseries vol = bars.volume

// Orderbook snapshot via source() for full LOB access
// Note: kScript orderbook() returns bid/ask top-of-book and depth fields.
timeseries ob = source("orderbook", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded
if (isnan(closePx[0]) || isnan(vol[0])) {
    return
}

// -----------------------------------------------------------------------------
// Orderbook Depth Aggregation (multi-level per Xu et al. 2019)
// -----------------------------------------------------------------------------
// CRITICAL: sumBids()/sumAsks() accept float percentages directly (e.g., 0.5 = 0.5%).
// Do NOT use math.floor() which truncates precision (bug in original v1).

var bids1 = sumBids(ob, depth1)
var asks1 = sumAsks(ob, depth1)
var bids2 = sumBids(ob, depth2)
var asks2 = sumAsks(ob, depth2)
var bids3 = sumBids(ob, depth3)
var asks3 = sumAsks(ob, depth3)
var bids4 = sumBids(ob, depth4)
var asks4 = sumAsks(ob, 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

// -----------------------------------------------------------------------------
// Visible Depth Metrics
// -----------------------------------------------------------------------------
// Total visible depth at each band
var visDepth1 = bookAvailable ? bids1 + asks1 : 0.0
var visDepth2 = bookAvailable ? bids2 + asks2 : 0.0
var visDepth3 = bookAvailable ? bids3 + asks3 : 0.0
var visDepth4 = bookAvailable ? bids4 + asks4 : 0.0

// Depth ratios (bid/ask at each level) — diagnostic per Gould & Bonart 2016
var depthRatio1 = bookAvailable && asks1 > 0 ? bids1 / asks1 : 1.0
var depthRatio2 = bookAvailable && asks2 > 0 ? bids2 / asks2 : 1.0
var depthRatio3 = bookAvailable && asks3 > 0 ? bids3 / asks3 : 1.0
var depthRatio4 = bookAvailable && asks4 > 0 ? bids4 / asks4 : 1.0

// Depth stability: rolling coefficient of variation of visible depth
// Low CV + high volume = suspicious replenishment (iceberg signature)
timeseries depthStdev = stdev(visDepth1, 20)
timeseries depthMean = sma(visDepth1, 20)
timeseries depthCV = depthMean > 1e-9 ? depthStdev / depthMean : 0.0

// -----------------------------------------------------------------------------
// Volume Context & Trade Intensity
// -----------------------------------------------------------------------------
// Trade volume relative to recent average
timeseries avgVol = rma(vol, 20)
timeseries volRatio = avgVol > 1e-9 ? vol / avgVol : 1.0

// Volume intensity score: high ratio = unusual activity
timeseries volIntensity = volRatio > 2.0 ? (volRatio - 2.0) * 25.0 : 0.0

// -----------------------------------------------------------------------------
// Iceberg Order Detection (Frey & Sandas 2009/2017)
// -----------------------------------------------------------------------------
// Heuristic: high volume ratio + low depth CV + stable bid/ask ratios →
// probability of hidden liquidity replenishing the book increases.
// Frey & Sandas: iceberg orders show lower temporary price impact because
// the hidden portion refreshes the visible book after each execution.

// Iceberg component: volume spike with depth stability
var icebergRaw = 0.0
if (bookAvailable && volRatio > 1.5 && depthCV < 0.3) {
    icebergRaw = min((volRatio - 1.5) * 40.0, 100.0)
} else if (bookAvailable && volRatio > 1.2 && depthCV < 0.5) {
    icebergRaw = min((volRatio - 1.2) * 20.0, 60.0)
}

// -----------------------------------------------------------------------------
// Spoofing Detection (Zotikov & Antonov 2021)
// -----------------------------------------------------------------------------
// Heuristic: rapid depth expansion followed by contraction within the same
// bar window, combined with no sustained volume follow-through.
// Zotikov & Antonov: spoofing shows depth-peak-then-collapse within 500ms
// and cancellation-to-insertion ratio > 0.8.

// Spoofing proxy: depth ratio volatility across bands
var depthRatioSpread = bookAvailable ?
    max(max(depthRatio1, depthRatio2), max(depthRatio3, depthRatio4)) -
    min(min(depthRatio1, depthRatio2), min(depthRatio3, depthRatio4)) :
    0.0

var spoofingRaw = 0.0
if (bookAvailable && depthRatioSpread > 1.5 && volRatio < 1.3) {
    // Large depth imbalance but no volume follow-through = suspicious
    spoofingRaw = min(depthRatioSpread * 20.0, 80.0)
} else if (bookAvailable && depthRatioSpread > 2.0) {
    spoofingRaw = min(depthRatioSpread * 15.0, 90.0)
}

// -----------------------------------------------------------------------------
// Depth-Weighted Composite Probability (Xu, Gould & Howison 2019)
// -----------------------------------------------------------------------------
// Combine iceberg and spoofing signals with depth-weighted averaging.
// w_i = decay^(i−1) for i = 1,2,3,4 depth bands.

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

// Composite depth imbalance for context
timeseries obi1 = bookAvailable && (bids1 + asks1) > 0 ? (bids1 - asks1) / (bids1 + asks1) * 100.0 : 0.0
timeseries obi2 = bookAvailable && (bids2 + asks2) > 0 ? (bids2 - asks2) / (bids2 + asks2) * 100.0 : 0.0
timeseries obi3 = bookAvailable && (bids3 + asks3) > 0 ? (bids3 - asks3) / (bids3 + asks3) * 100.0 : 0.0
timeseries obi4 = bookAvailable && (bids4 + asks4) > 0 ? (bids4 - asks4) / (bids4 + asks4) * 100.0 : 0.0

var compositeOBI = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3 + w4 * obi4) / wSum : 0.0

// -----------------------------------------------------------------------------
// Final Probability Score (0–100)
// -----------------------------------------------------------------------------
// Blend iceberg detection, spoofing detection, and volume intensity.
// Higher scores = stronger evidence of hidden liquidity or manipulation.

var rawScore = (icebergRaw * 0.5) + (spoofingRaw * 0.3) + (volIntensity * 0.2)
if (rawScore < 0.0) {
    rawScore = 0.0
} else if (rawScore > 100.0) {
    rawScore = 100.0
}

// Smoothing (EMA per Cont et al. 2014 noise-reduction)
timeseries scoreSmooth = smoothScore ? ema(rawScore, smoothLen) : rawScore

// -----------------------------------------------------------------------------
// Regime Detection (three-segment probability model)
// -----------------------------------------------------------------------------
//   Low (< lowThresh):        normal market conditions
//   Elevated (low–high):      suspicious activity, watch closely
//   High (> highThresh):      strong hidden liquidity signal
//   Extreme (> extremeThresh): likely iceberg or spoofing in progress

var regime = 0      // 0 = low, 1 = elevated, 2 = high
var extremeRegime = 0  // 0 = normal, 1 = extreme

if (scoreSmooth >= highThresh) {
    regime = 2
} else if (scoreSmooth >= lowThresh) {
    regime = 1
}

if (scoreSmooth >= extremeThresh) {
    extremeRegime = 1
}

// -----------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// -----------------------------------------------------------------------------
// Stateful computation for session extremes, regime transitions, and
// extreme-event counters.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static extremeCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (scoreSmooth > sessionHighScore) {
        sessionHighScore = scoreSmooth
    }
    if (scoreSmooth < sessionLowScore) {
        sessionLowScore = scoreSmooth
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeCount = extremeCount + 1
    }
}

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

// Horizontal guide lines — threshold zones
hline(value=0, color="#ffffff20", width=1)

if (showGuides) {
    hline(value=lowThresh, color=opacity(elevatedColor, 30), width=1)
    hline(value=highThresh, color=opacity(highColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeColor, 20), width=1)
}

// Raw probability score as histogram bars (regime-colored)
if (showRawBars) {
    plotBar(
        value=scoreSmooth,
        colors=[lowColor, elevatedColor, highColor, extremeColor],
        colorIndex=scoreSmooth >= extremeThresh ? 3 : (scoreSmooth >= highThresh ? 2 : (scoreSmooth >= lowThresh ? 1 : 0)),
        width=1,
        label=["Probability Score"],
        desc=["Hidden liquidity probability (0-100). Regime: low/elevated/high/extreme"]
    )
}

// Smoothed score line with regime-coded fill area
if (showScoreLine) {
    plotLine(
        value=scoreSmooth,
        width=lineWidth,
        colors=[lowColor, elevatedColor, highColor, extremeColor],
        colorIndex=scoreSmooth >= extremeThresh ? 3 : (scoreSmooth >= highThresh ? 2 : (scoreSmooth >= lowThresh ? 1 : 0)),
        fill=true,
        label=["Hidden Liquidity Score"],
        desc=["Smoothed hidden liquidity probability with regime fill"]
    )
}

// Individual depth ratio lines (optional, for granular analysis)
if (showDepthLines) {
    plotLine(
        value=depthRatio1,
        width=1,
        colors=[opacity(lowColor, 50)],
        label=["Depth Ratio 0.5%"],
        desc=["Bid/Ask depth ratio at 0.5% band (shallow book)"]
    )
    plotLine(
        value=depthRatio2,
        width=1,
        colors=[opacity(lowColor, 40)],
        label=["Depth Ratio 1%"],
        desc=["Bid/Ask depth ratio at 1% band (near-term liquidity)"]
    )
    plotLine(
        value=depthRatio3,
        width=1,
        colors=[opacity(highColor, 40)],
        label=["Depth Ratio 2.5%"],
        desc=["Bid/Ask depth ratio at 2.5% band (medium-term absorption)"]
    )
    plotLine(
        value=depthRatio4,
        width=1,
        colors=[opacity(highColor, 50)],
        label=["Depth Ratio 5%"],
        desc=["Bid/Ask depth ratio at 5% band (deep book, structural level)"]
    )
}

// Depth CV diagnostic line (optional)
if (showCV) {
    plotLine(
        value=depthCV * 100.0,
        width=1,
        colors=[scoreLineColor],
        label=["Depth CV (×100)"],
        desc=["Depth coefficient of variation × 100 — low = stable, high = volatile"]
    )
}

// Regime transition shapes
if (showShapes) {
    var crossUpLow = scoreSmooth >= lowThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] < lowThresh
    var crossUpHigh = scoreSmooth >= highThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] < highThresh
    var crossUpExtreme = scoreSmooth >= extremeThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] < extremeThresh
    var crossDnLow = scoreSmooth <= lowThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] > lowThresh
    var crossDnHigh = scoreSmooth <= highThresh && !isnan(scoreSmooth[1]) && scoreSmooth[1] > highThresh

    if (crossUpLow) {
        plotShape(
            value=scoreSmooth,
            shape="triangleup",
            color=elevatedColor,
            width=shapeSize,
            label=["Elevated Signal"],
            desc=["Hidden liquidity probability crossed into elevated zone — watch for icebergs"]
        )
    }
    if (crossUpHigh) {
        plotShape(
            value=scoreSmooth,
            shape="triangleup",
            color=highColor,
            width=shapeSize + 1,
            label=["High Signal"],
            desc=["Hidden liquidity probability crossed into high zone — strong iceberg/spoofing evidence"]
        )
    }
    if (crossUpExtreme) {
        plotShape(
            value=scoreSmooth,
            shape="diamond",
            color=extremeColor,
            width=shapeSize + 2,
            label=["Extreme Signal"],
            desc=["Extreme hidden liquidity detected — likely iceberg or spoofing in progress"]
        )
    }
    if (crossDnHigh) {
        plotShape(
            value=scoreSmooth,
            shape="triangledown",
            color=elevatedColor,
            width=shapeSize,
            label=["High Exit"],
            desc=["Hidden liquidity probability exited high zone — signal decaying"]
        )
    }
    if (crossDnLow) {
        plotShape(
            value=scoreSmooth,
            shape="triangledown",
            color=lowColor,
            width=shapeSize,
            label=["Elevated Exit"],
            desc=["Hidden liquidity probability returned to normal zone"]
        )
    }
}