MM Flow
FlowScripts

Perfected FlowScript

Passive Absorption Detector

Passive Absorption Detector — Perfected Edition is indexed as 245_passive_absorption_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

14.3 KB

Lines

444

Native Signal Candidates

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

6/6 guarded

Buy Absorption

line 347:9

Trigger

(showShapes) && (buyAbs && volConfirm)

Value

delta

Deps

buyAbs:var, showShapes:input, volConfirm:var

Sell Absorption

line 357:9

Trigger

(showShapes) && (sellAbs && volConfirm)

Value

delta

Deps

sellAbs:var, showShapes:input, volConfirm:var

Weak Buy Abs

line 367:9

Trigger

(showShapes) && (buyAbs && !volConfirm)

Value

delta

Deps

buyAbs:var, showShapes:input, volConfirm:var

Weak Sell Abs

line 377:9

Trigger

(showShapes) && (sellAbs && !volConfirm)

Value

delta

Deps

sellAbs:var, showShapes:input, volConfirm:var

Buy Cluster

line 391:9

Trigger

(showClusters) && (buyCluster)

Value

delta

Deps

buyCluster:var, showClusters:input

Sell Cluster

line 401:9

Trigger

(showClusters) && (sellCluster)

Value

delta

Deps

sellCluster:var, showClusters:input

245_passive_absorption_detector.flowscript

source path: kscripts/perfected/245_passive_absorption_detector.flowscript · sha256:fe1d2f8b214cfecb87b11f4dd59393ae27a7c8840ab761a11571249e7c786f3f

hash verified
//@version=2
// ============================================================================
// Passive Absorption Detector — Perfected Edition
// Author: M (@MarketMaker) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #absorption, #volume, #delta, #microstructure, #liquidity
//
// Production-quality passive absorption detector identifying large volume
// absorption without corresponding price movement. Implements multi-bar
// cluster detection, volume confirmation, rolling absorption score, and
// static session tracking per Bouchaud-Farmer-Lillo liquidity memory theory.
//
// Research papers underpinning this design:
//  1. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand", Handbook of Financial Markets: established the
//     "liquidity memory time" explanation for the square-root impact law;
//     large orders absorbed without price movement = liquidity replenishment.
//  2. Tóth et al. (2011), Phys Rev X 1(2):021006: market impact has a critical,
//     universal character; the square-root law holds across diverse markets.
//     When aggressive volume fails to move price, absorption is occurring.
//  3. Cont, Kukanov & Stoikov (2014), J. Financial Econometrics 12(1):47-88:
//     OFI explains ~65% of variance in short-term price changes; when OFI is
//     high but price doesn't move, passive liquidity is absorbing the flow.
//  4. Chordia, Roll & Subrahmanyam (2002), JFE 65(1):111-130: extreme order
//     imbalances predict return reversals; absorption at extremes flags
//     potential exhaustion and reversal.
//  5. Easley, López de Prado & O'Hara (2012), RFS 25(5):1457-1493: VPIN
//     (volume-synchronized toxicity) framework; high volume with minimal price
//     impact can signal informed traders being absorbed by market makers.
//  6. Kyle (1985), Econometrica 53(6):1315-1335: price responds linearly to
//     order flow with slope λ (Kyle's Lambda); if price doesn't respond to
//     large flow, λ is temporarily suppressed = absorption.
// ============================================================================

define(
    title="Passive Absorption Detector — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Absorption Detection ---
var absLen = input(
    name="absLen",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Absorption"
)
var moveThresh = input(
    name="moveThresh",
    type="number",
    defaultValue=0.3,
    label="Move Threshold (%)",
    constraints={min: 0.05, max: 2.0, step: 0.05},
    group="Absorption"
)
var deltaThresh = input(
    name="deltaThresh",
    type="number",
    defaultValue=0.6,
    label="Delta Imbalance Threshold",
    constraints={min: 0.1, max: 1.0, step: 0.05},
    group="Absorption"
)
var clusterBars = input(
    name="clusterBars",
    type="number",
    defaultValue=3,
    label="Cluster Detection (bars)",
    constraints={min: 1, max: 10, step: 1},
    group="Absorption"
)

// --- Volume Confirmation ---
var useVolConfirm = input(
    name="useVolConfirm",
    type="boolean",
    defaultValue=true,
    label="Use Volume Confirmation",
    group="Volume"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume SMA Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.5,
    label="Volume Threshold Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volume"
)

// --- Display ---
var showRawDelta = input(
    name="showRawDelta",
    type="boolean",
    defaultValue=true,
    label="Show Raw Delta Bars",
    group="Display"
)
var showAbsScore = input(
    name="showAbsScore",
    type="boolean",
    defaultValue=true,
    label="Show Absorption Score",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Absorption Shapes",
    group="Display"
)
var showClusters = input(
    name="showClusters",
    type="boolean",
    defaultValue=true,
    label="Show Cluster Shapes",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Status Table",
    group="Display"
)

// --- Colors ---
var buyColor = input(
    name="buyColor",
    type="color",
    defaultValue="#26a69a",
    label="Passive Buy Color",
    group="Colors"
)
var sellColor = input(
    name="sellColor",
    type="color",
    defaultValue="#ef5350",
    label="Passive Sell Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var strongAbsColor = input(
    name="strongAbsColor",
    type="color",
    defaultValue="#00e676",
    label="Strong Absorption Color",
    group="Colors"
)
var weakAbsColor = input(
    name="weakAbsColor",
    type="color",
    defaultValue="#ffab00",
    label="Weak Absorption Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries high = bars.high
timeseries low = bars.low
timeseries close = bars.close
timeseries vol = bars.volume
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

if (isnan(close[0]) || isnan(vol[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. PER-BAR DELTA & METRICS
// -----------------------------------------------------------------------------
// Per-bar delta from buy/sell volume classification (Lee-Ready / BVC basis)

timeseries buyV = buySell.buy_volume
timeseries sellV = buySell.sell_volume
timeseries delta = buyV - sellV
timeseries totalVol = buyV + sellV

// Delta imbalance ratio (normalized to [-1, +1])
var imbRatio = totalVol > 0 ? delta / totalVol : 0

// Bar move as % of close (price impact metric)
var barMove = close > 0 ? math.abs(close - close[1]) / close * 100 : 0

// Rolling average delta (for deviation measurement)
timeseries avgDelta = sma(source=delta, period=absLen)
timeseries avgVol = sma(source=totalVol, period=volLookback)

// Delta deviation from rolling average (how unusual is this bar's delta?)
timeseries deltaDev = delta - avgDelta

// -----------------------------------------------------------------------------
// 4. ABSORPTION DETECTION — per-bar and multi-bar cluster
// -----------------------------------------------------------------------------
// Absorption criteria per Bouchaud et al. (2009) and Cont et al. (2014):
// 1. Large |delta| (imbalance) — significant aggressive flow on one side
// 2. Small price move — flow is being absorbed without moving the market
// 3. Volume confirmation — above-average volume strengthens the signal

// Per-bar absorption flags
var buyAbs = math.abs(imbRatio) > deltaThresh && barMove < moveThresh && delta > 0
var sellAbs = math.abs(imbRatio) > deltaThresh && barMove < moveThresh && delta < 0
var volConfirm = useVolConfirm ? totalVol > avgVol * volMultiplier : true

// Absorption strength: combines delta deviation and volume confirmation
var absStrength = 0.0
if (buyAbs || sellAbs) {
    absStrength = volConfirm ? math.abs(deltaDev) / math.abs(avgDelta) : math.abs(deltaDev) / math.abs(avgDelta) * 0.5
}

// Rolling absorption score (smoothed series of absorption events)
timeseries absScore = 0.0
if (buyAbs || sellAbs) {
    absScore = volConfirm ? (buyAbs ? 1 : -1) : (buyAbs ? 0.5 : -0.5)
}
timeseries absScoreSmooth = ema(source=absScore, period=5)

// -----------------------------------------------------------------------------
// 5. CLUSTER DETECTION — consecutive absorption bars
// -----------------------------------------------------------------------------
// Multi-bar clusters indicate sustained absorption, a stronger signal per
// Bouchaud et al. (2009): liquidity memory means repeated absorption
// depletes passive liquidity and may lead to eventual breakout.

static buyClusterCount = 0
static sellClusterCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (buyAbs) {
        buyClusterCount = buyClusterCount + 1
    } else {
        buyClusterCount = 0
    }
    if (sellAbs) {
        sellClusterCount = sellClusterCount + 1
    } else {
        sellClusterCount = 0
    }
}

var buyCluster = buyClusterCount >= clusterBars
var sellCluster = sellClusterCount >= clusterBars

// -----------------------------------------------------------------------------
// 6. STATIC SESSION TRACKING — cumulative absorption stats
// -----------------------------------------------------------------------------
static totalBuyAbs = 0
static totalSellAbs = 0
static totalBuyVol = 0.0
static totalSellVol = 0.0
static maxAbsScore = 0.0
static maxAbsBarVol = 0.0

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    if (buyAbs) {
        totalBuyAbs = totalBuyAbs + 1
        totalBuyVol = totalBuyVol + totalVol
    }
    if (sellAbs) {
        totalSellAbs = totalSellAbs + 1
        totalSellVol = totalSellVol + totalVol
    }
    if (absStrength > maxAbsScore) {
        maxAbsScore = absStrength
    }
    if (totalVol > maxAbsBarVol) {
        maxAbsBarVol = totalVol
    }
}

// -----------------------------------------------------------------------------
// 7. REGIME COLOR INDEXING
// -----------------------------------------------------------------------------
var colIdx = 1  // neutral default
if (buyAbs && volConfirm) {
    colIdx = 0
} else if (sellAbs && volConfirm) {
    colIdx = 2
} else if (buyAbs && !volConfirm) {
    colIdx = 0
} else if (sellAbs && !volConfirm) {
    colIdx = 2
}

// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------

// --- Raw Delta Bars (volume delta visualization) ---
if (showRawDelta) {
    plotBar(
        value=delta,
        colors=[buyColor, neutralColor, sellColor],
        colorIndex=colIdx,
        width=2,
        label=["Raw Delta"],
        desc=["Per-bar buy-sell volume delta (aggressive flow imbalance)"]
    )
}

// --- Absorption Score (smoothed absorption signal) ---
if (showAbsScore) {
    var scoreBull = absScoreSmooth >= 0
    plotLine(
        value=absScoreSmooth,
        width=2,
        colors=[transparency(buyColor, 60), transparency(sellColor, 60)],
        colorIndex=scoreBull ? 0 : 1,
        label=["Absorption Score"],
        desc=["Smoothed absorption score: +1 = strong passive buy absorption, -1 = strong passive sell absorption"]
    )
}

// --- Zero line ---
hline(value=0, color=transparency(neutralColor, 50), width=1)

// --- Absorption shapes (per-bar events) ---
if (showShapes) {
    if (buyAbs && volConfirm) {
        plotShape(
            value=delta,
            shape="triangleup",
            colorIndex=strongAbsColor,
            width=2,
            label=["Buy Absorption"],
            desc=["Passive buy absorption detected: large delta, minimal price move, volume confirmed"]
        )
    }
    if (sellAbs && volConfirm) {
        plotShape(
            value=delta,
            shape="triangledown",
            colorIndex=strongAbsColor,
            width=2,
            label=["Sell Absorption"],
            desc=["Passive sell absorption detected: large delta, minimal price move, volume confirmed"]
        )
    }
    if (buyAbs && !volConfirm) {
        plotShape(
            value=delta,
            shape="arrowup",
            colorIndex=weakAbsColor,
            width=1,
            label=["Weak Buy Abs"],
            desc=["Weak buy absorption: low volume, may be noise"]
        )
    }
    if (sellAbs && !volConfirm) {
        plotShape(
            value=delta,
            shape="arrowdown",
            colorIndex=weakAbsColor,
            width=1,
            label=["Weak Sell Abs"],
            desc=["Weak sell absorption: low volume, may be noise"]
        )
    }
}

// --- Cluster shapes (multi-bar sustained absorption) ---
if (showClusters) {
    if (buyCluster) {
        plotShape(
            value=delta,
            shape="diamond",
            colorIndex=strongAbsColor,
            width=3,
            label=["Buy Cluster"],
            desc=["Sustained passive buy absorption cluster (" + clusterBars + "+ bars) — potential liquidity exhaustion ahead"]
        )
    }
    if (sellCluster) {
        plotShape(
            value=delta,
            shape="diamond",
            colorIndex=strongAbsColor,
            width=3,
            label=["Sell Cluster"],
            desc=["Sustained passive sell absorption cluster (" + clusterBars + "+ bars) — potential liquidity exhaustion ahead"]
        )
    }
}

// -----------------------------------------------------------------------------
// 9. ABSORPTION TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
    var absRegime = totalBuyAbs > totalSellAbs ? "BUY-SIDE DOMINANT" : (totalSellAbs > totalBuyAbs ? "SELL-SIDE DOMINANT" : "BALANCED")
    var absRegimeColor = totalBuyAbs > totalSellAbs ? buyColor : (totalSellAbs > totalBuyAbs ? sellColor : neutralColor)

    plotTable(
        data=[
            ["Absorption Detector Pro", absRegime],
            ["Buy Events", totalBuyAbs],
            ["Sell Events", totalSellAbs],
            ["Buy Volume", totalBuyVol],
            ["Sell Volume", totalSellVol],
            ["Max Abs Score", maxAbsScore],
            ["Max Bar Volume", maxAbsBarVol],
            ["Current Delta", delta[0]],
            ["Avg Delta", avgDelta[0]]
        ],
        position="top_right",
        headerRow=true,
        headerColumn=true,
        textColor="#e2e8f0",
        headerTextColor="#ffffff",
        backgroundColor=transparency("#0f172a", 40),
        headerBackgroundColor=transparency("#1e293b", 40),
        borderColor=transparency("#334155", 40),
        borderWidth=1,
        fontSize=10,
        cellPadding=4
    )
}