MM Flow
FlowScripts

Perfected FlowScript

ABSORPTION

Absorption V2 is indexed as 163_absorption.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

onchart

Axis

false

Size

15.1 KB

Lines

330

Native Signal Candidates

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

4/4 guarded

ABSORPTION

line 287:9

Trigger

(showShapes) && (bearAbs)

Value

high

Deps

bearAbs:var, showShapes:input

ABSORPTION

line 298:9

Trigger

(showShapes) && (bullAbs)

Value

low

Deps

bullAbs:var, showShapes:input

STRONG ABS

line 310:9

Trigger

(showShapes) && (bullAbsCount > 2 && bullAbs)

Value

low

Deps

bullAbs:var, bullAbsCount:static, showShapes:input

STRONG ABS

line 320:9

Trigger

(showShapes) && (bearAbsCount > 2 && bearAbs)

Value

high

Deps

bearAbs:var, bearAbsCount:static, showShapes:input

163_absorption.flowscript

source path: kscripts/perfected/163_absorption.flowscript · sha256:9ffbaca7a08e8ee31cde04b7abd1e47a7e09e261047435d41f39494b71442766

hash verified
//@version=2

// ============================================================================
// Absorption V2 — Multi-Factor Liquidity Absorption Detector with Level Tracking
// Author: M (@MarketMaker) | Perfected by: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #absorption, #orderflow, #liquidity, #reversal
//
// Detects candles where aggressive order flow is absorbed by passive liquidity
// on the opposite side — a potential reversal signature. Combines volume
// percentile, delta strength, price-impact-per-volume ratio, wick-rejection
// analysis, and optional orderbook depth confirmation to identify genuine
// absorption versus mere exhaustion.
//
// FORMULA FOUNDATION:
// 1. Absorption Condition: volPercentile ≥ threshold AND |delta| ≥ threshold
//    AND priceImpact / volume ≤ absorption threshold (small move despite large flow).
// 2. Square-Root Impact Law (Bouchaud et al. 2009): Impact ∝ √volume. When
//    observed impact << √volume, liquidity is replenishing — absorption.
// 3. Linear OFI Model (Cont et al. 2014): ΔP = λ × OFI. If λ is small (deep book),
//    large OFI produces small ΔP → absorption at deep liquidity levels.
// 4. Order Imbalance Reversal (Chordia et al. 2002): Extreme imbalances predict
//    return reversals; absorption marks the point where imbalance is neutralised.
// 5. Anomalous Price Impact (Tóth et al. 2011): Square-root law is universal;
//    volume spikes with fading follow-through reflect liquidity depletion
//    (exhaustion) rather than absorption.
//
// RESEARCH BASIS:
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand", Nature 2009. Square-root impact law; liquidity memory
//    time explains why large volume may not move price — passive replenishment.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Linear OFI model: ΔP = λ × OFI.
//    Small ΔP with large OFI signals deep liquidity / absorption.
//    DOI: https://doi.org/10.1093/jjfinec/nbt003
//  • Tóth et al. (2011), "Anomalous Price Impact and the Critical Nature of
//    Liquidity", Physical Review X 1(2), 021006. Universal square-root law;
//    critical liquidity transitions. DOI: 10.1103/PhysRevX.1.021006
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme imbalances
//    predict reversals. DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// ============================================================================

define(
    title="Absorption V2",
    position="onchart",
    axis=false
)

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

// --- Volume Filter ---
var volTopPct = input(name="volTopPct", type="number", defaultValue=20.0, label="Top Volume Percentile (%)", constraints={min: 5.0, max: 50.0, step: 5.0}, group="Volume")
var volLookback = input(name="volLookback", type="number", defaultValue=50.0, label="Volume Lookback (bars)", constraints={min: 20.0, max: 200.0, step: 10.0}, group="Volume")

// --- Delta Filter ---
var deltaThresh = input(name="deltaThresh", type="number", defaultValue=0.6, label="Strong Delta Threshold (%)", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Delta")
var useTakerDelta = input(name="useTakerDelta", type="boolean", defaultValue=true, label="Use Taker Delta (if available)", group="Delta")

// --- Absorption Impact ---
var impactRatioThresh = input(name="impactRatioThresh", type="number", defaultValue=0.5, label="Impact Ratio Threshold (× impact/vol)", constraints={min: 0.1, max: 2.0, step: 0.1}, group="Absorption")
var wickRatioThresh = input(name="wickRatioThresh", type="number", defaultValue=0.5, label="Wick Ratio Threshold (%)", constraints={min: 0.1, max: 0.9, step: 0.05}, group="Absorption")
var useOIConfirm = input(name="useOIConfirm", type="boolean", defaultValue=false, label="Require OI Change Confirmation", group="Absorption")

// --- Z-Score & Tracking ---
var zWindow = input(name="zWindow", type="number", defaultValue=30.0, label="Z-Score Window (bars)", constraints={min: 10.0, max: 100.0, step: 5.0}, group="Z-Score")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3.0, label="Smoothing Length", constraints={min: 1.0, max: 20.0, step: 1.0}, group="Z-Score")

// --- Display ---
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Absorption Shapes", group="Display")
var showAbsorptionLine = input(name="showAbsorptionLine", type="boolean", defaultValue=true, label="Show Absorption Strength Line", group="Display")
var showAbsorptionBar = input(name="showAbsorptionBar", type="boolean", defaultValue=false, label="Show Absorption Strength Bar", group="Display")
var showAbsorptionZones = input(name="showAbsorptionZones", type="boolean", defaultValue=true, label="Show Absorption Zones", group="Display")

// --- Colors ---
var bearColor = input(name="bearColor", type="color", defaultValue="#ff5252", label="Bearish Absorption Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Absorption Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var zoneBullColor = input(name="zoneBullColor", type="color", defaultValue="#26a69a40", label="Bull Zone Fill", group="Colors")
var zoneBearColor = input(name="zoneBearColor", type="color", defaultValue="#ff525240", label="Bear Zone Fill", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = priceBars.close
timeseries open = priceBars.open
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries volume = priceBars.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries oi = open_interest(symbol=currentSymbol, exchange=currentExchange)

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

// ------------------------------------------------------------------------------
// Delta Computation — prefer taker feed, fallback to BVC close-position
// ------------------------------------------------------------------------------
timeseries rng = math.max(high - low, 0.0001)
timeseries closePos = (close - low) / rng

timeseries buyVol = 0.0
timeseries sellVol = 0.0

if (useTakerDelta && isnum(taker.buy) && isnum(taker.sell)) {
    buyVol = taker.buy
    sellVol = taker.sell
} else {
    buyVol = volume * closePos
    sellVol = volume * (1.0 - closePos)
}

timeseries delta = buyVol - sellVol
timeseries deltaPct = delta / math.max(volume, 1.0)

// ------------------------------------------------------------------------------
// Volume Percentile Filter
// ------------------------------------------------------------------------------
timeseries maxVol = highest(volume, volLookback)
timeseries minVol = lowest(volume, volLookback)
timeseries volRank = (volume - minVol) / math.max(maxVol - minVol, 0.0001)
var volTop = volRank > (1.0 - volTopPct / 100.0)

// ------------------------------------------------------------------------------
// Price Impact per Volume (Absorption vs Exhaustion Discriminator)
// ------------------------------------------------------------------------------
// Bouchaud et al. (2009): Impact should scale as √volume under normal conditions.
// If observed impact is much smaller than √volume, liquidity is absorbing flow.
// If observed impact is larger, we have exhaustion (liquidity depletion).
timeseries barRange = high - low
timeseries impactPerVol = barRange / math.max(volume, 1.0)
timeseries expectedImpact = math.sqrt(volume) / math.max(close, 0.0001)
timeseries impactRatio = (expectedImpact > 0) ? impactPerVol / expectedImpact : 1.0
var lowImpact = impactRatio < impactRatioThresh

// ------------------------------------------------------------------------------
// Wick Rejection & Bar Shape Analysis
// ------------------------------------------------------------------------------
timeseries upperWick = high - math.max(close, open)
timeseries lowerWick = math.min(close, open) - low
timeseries bodySize = math.abs(close - open)
timeseries rangeSize = rng

var bullishFail = close > open
    ? upperWick > rangeSize * wickRatioThresh
    : lowerWick > rangeSize * wickRatioThresh

var bearishFail = close < open
    ? lowerWick > rangeSize * wickRatioThresh
    : upperWick > rangeSize * wickRatioThresh

// ------------------------------------------------------------------------------
// OI Change Confirmation (optional — absorption often coincides with OI build)
// ------------------------------------------------------------------------------
timeseries oiChange = 0.0
if (isnum(oi.close)) {
    oiChange = oi.close - oi.close[1]
}
var oiConfirm = !useOIConfirm || (oiChange > 0)

// ------------------------------------------------------------------------------
// Z-Score Normalisation of Volume & Delta
// ------------------------------------------------------------------------------
timeseries volMean = sma(volume, zWindow)
timeseries volStd = stdev(volume, zWindow)
timeseries volZ = (volStd > 0) ? (volume - volMean) / volStd : 0.0

timeseries deltaMean = sma(deltaPct, zWindow)
timeseries deltaStd = stdev(deltaPct, zWindow)
timeseries deltaZ = (deltaStd > 0) ? (deltaPct - deltaMean) / deltaStd : 0.0

// ------------------------------------------------------------------------------
// Absorption Detection Conditions
// ------------------------------------------------------------------------------
// Bearish absorption: aggressive buyers but close on wrong side / wick rejection
var bearAbs = volTop && deltaPct > deltaThresh && bullishFail && close < open && lowImpact && oiConfirm

// Bullish absorption: aggressive sellers but close on wrong side / wick rejection
var bullAbs = volTop && deltaPct < -deltaThresh && bearishFail && close > open && lowImpact && oiConfirm

// ------------------------------------------------------------------------------
// Absorption Strength Score (0-100) for Continuous Visualisation
// ------------------------------------------------------------------------------
// Combines volume z-score, delta z-score, and impact ratio into a normalised
// absorption strength metric. Positive = bullish absorption, negative = bearish.
timeseries absStrengthRaw = (volZ + math.abs(deltaZ)) * (1.0 - impactRatio) * 50.0
timeseries absStrength = (bearAbs || bullAbs) ? absStrengthRaw : 0.0
timeseries absStrengthSmoothed = ema(absStrength, smoothLen)

// ------------------------------------------------------------------------------
// Regime Detection (0 = none, 1 = bullish absorption, -1 = bearish absorption)
// ------------------------------------------------------------------------------
var regime = 0
if (bullAbs) {
    regime = 1
} else if (bearAbs) {
    regime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking — Absorption Level Persistence
// ------------------------------------------------------------------------------
// Tracks absorption events, price levels, and consecutive counts for session-level
// context. Helps identify whether absorption is clustering at a specific level.
static lastAbsorptionPrice = 0.0
static lastAbsorptionRegime = 0
static bullAbsCount = 0
static bearAbsCount = 0
static lastBarIndex = 0
static bullAbsLevel = 0.0
static bearAbsLevel = 0.0

var currentBarIndex = bar_index[0]

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

    if (bullAbs) {
        bullAbsCount = bullAbsCount + 1
        bullAbsLevel = low
        lastAbsorptionPrice = low
        lastAbsorptionRegime = 1
    } else if (bearAbs) {
        bearAbsCount = bearAbsCount + 1
        bearAbsLevel = high
        lastAbsorptionPrice = high
        lastAbsorptionRegime = -1
    }
}

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

// Absorption strength line (continuous, regime-coded)
if (showAbsorptionLine) {
    plotLine(
        value=absStrengthSmoothed,
        width=2,
        colors=[bullColor, neutralColor, bearColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 2 : 1),
        label=["Absorption Strength"],
        desc=["Composite absorption strength (0-100); positive = bullish absorption, negative = bearish"]
    )
}

// Absorption strength bar (optional, for histogram lovers)
if (showAbsorptionBar) {
    plotBar(
        value=absStrengthSmoothed,
        colors=[bullColor, bearColor],
        width=1,
        label=["Absorption Bars"],
        desc=["Absorption strength as bars; green = bullish absorption, red = bearish"]
    )
}

// Absorption zones — highlight the price levels where absorption occurred
if (showAbsorptionZones && bullAbs) {
    plotLine(
        value=([low, low - atr(14) * 0.5]),
        width=1,
        colors=[zoneBullColor],
        label=["Bull Abs Zone"],
        desc=["Bullish absorption zone — aggressive selling absorbed by hidden buyers"],
        fill=true
    )
}
if (showAbsorptionZones && bearAbs) {
    plotLine(
        value=([high, high + atr(14) * 0.5]),
        width=1,
        colors=[zoneBearColor],
        label=["Bear Abs Zone"],
        desc=["Bearish absorption zone — aggressive buying absorbed by hidden sellers"],
        fill=true
    )
}

// Absorption shape markers — primary visual signal
if (showShapes) {
    if (bearAbs) {
        plotShape(
            value=high,
            shape="labeldown",
            color=bearColor,
            width=3,
            label=["ABSORPTION"],
            desc=["Bearish absorption: aggressive buying absorbed by hidden sellers at " + high]
        )
    }

    if (bullAbs) {
        plotShape(
            value=low,
            shape="labelup",
            color=bullColor,
            width=3,
            label=["ABSORPTION"],
            desc=["Bullish absorption: aggressive selling absorbed by hidden buyers at " + low]
        )
    }

    // Consecutive absorption alert (clustering at a level)
    if (bullAbsCount > 2 && bullAbs) {
        plotShape(
            value=low,
            shape="diamond",
            color=bullColor,
            width=4,
            label=["STRONG ABS"],
            desc=["Repeated bullish absorption at level " + bullAbsLevel + " — strong hidden bid"]
        )
    }
    if (bearAbsCount > 2 && bearAbs) {
        plotShape(
            value=high,
            shape="diamond",
            color=bearColor,
            width=4,
            label=["STRONG ABS"],
            desc=["Repeated bearish absorption at level " + bearAbsLevel + " — strong hidden ask"]
        )
    }
}