MM Flow
FlowScripts

Perfected FlowScript

Market Maker

Market Maker Behavior Detector V2 is indexed as 030_market_maker.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.8 KB

Lines

384

Native Signal Candidates

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

9/9 guarded

ACCUM

line 285:5

Trigger

(showAccumShapes && accumEvent)

Value

lo

Deps

accumEvent:var, showAccumShapes:input

DISTRIB

line 295:5

Trigger

(showDistribShapes && distribEvent)

Value

hi

Deps

distribEvent:var, showDistribShapes:input

GRAB ↑

line 305:5

Trigger

(showGrabShapes && grabUpEvent)

Value

hi

Deps

grabUpEvent:var, showGrabShapes:input

GRAB ↓

line 315:5

Trigger

(showGrabShapes && grabDownEvent)

Value

lo

Deps

grabDownEvent:var, showGrabShapes:input

ACCUM

line 327:5

Trigger

(accumEvent)

Value

lo

Deps

accumEvent:var

DIST

line 338:5

Trigger

(distribEvent)

Value

hi

Deps

distribEvent:var

GRAB↑

line 349:5

Trigger

(grabUpEvent)

Value

hi

Deps

grabUpEvent:var

GRAB↓

line 360:5

Trigger

(grabDownEvent)

Value

lo

Deps

grabDownEvent:var

Unlabeled shape

line 374:5

Trigger

(showRegimeLabel && isLastBar)

Value

hi

Deps

isLastBar:builtin, showRegimeLabel:input

030_market_maker.flowscript

source path: kscripts/perfected/030_market_maker.flowscript · sha256:ef390299bfe659fb0107faac39e7db48760e8ec06126f385c77e5e5df793fdef

hash verified
//@version=2
// ============================================================================
// Market Maker Behavior Detector V2 — Institutional Positioning & Liquidity Dynamics
// Author: E (@edselave) — Perfected by: kScript Perfection Engineer
// Tags: FLOW, SPECIALIZED, #Market, #SmartMoney, #Accumulation, #Distribution, #LiquidityGrab
//
// Production-grade market maker behavior detector with institutional positioning
// detection, Wyckoff phase classification, ATR-scaled thresholds, volume confirmation,
// liquidity grab validation with snap-back confirmation, and regime state tracking.
//
// FORMULA FOUNDATION:
// 1. Wyckoff Phase Detection: Accumulation = flat price + rising buy pressure;
//    Distribution = flat/rising price + rising sell pressure (Wyckoff 1930s).
// 2. Liquidity Grab Model: Fake breakout = break of range extreme + snap-back
//    within recovery ratio × range (Bhusal 2025 stop-hunt logic).
// 3. ATR-Scaled Detection: All thresholds scaled by ATR for instrument-agnostic
//    detection across timeframes and volatility regimes (Kirkpatrick & Dahlquist 2010).
// 4. Volume Confirmation: Behavioral regime validated by volume spike > 1.5× avg
//    (Campbell, Ramadorai & Vuolteenaho 2005 institutional footprint logic).
// 5. Delta Z-Score: (BuyVol − SellVol − μ_Δ) / σ_Δ per Jones & Lipson (2005)
//    countervailing institutional flow dynamics.
//
// RESEARCH BASIS:
//  • Jones & Lipson (2005), "Are Retail Orders Different?" — 1,000 retail shares
//    → 400+ institutional shares opposite within 5 min. Validates smart-money
//    exploitation of retail liquidity as accumulation/distribution mechanic.
//  • Kyle (1985), "Continuous Auctions and Insider Trading" — λ = price impact
//    per unit order flow. Informed traders absorb liquidity before expansion;
//    flat price + informed flow = accumulation signature.
//  • Guéant (2017), "Optimal Market Making" — inventory risk management drives
//    quote placement; market makers accumulate inventory before directional moves.
//  • Bhusal (2025), "Timing the Trap: Stop Hunt Zones & Price Manipulation"
//    (SSRN 5276088). Engineered liquidity traps: false breaks with snap-back
//    validate liquidity grab as observable microstructure phenomenon.
//  • Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape" (NBER 11439).
//    Institutional footprints detectable in trade-size patterns; volume spikes
//    with flat price signal accumulation/distribution.
//  • Wyckoff, R.D. (1930s). "The Richard D. Wyckoff Method" — four phases:
//    Accumulation → Markup → Distribution → Markdown. Effort vs Result:
//    rising volume + flat price = effort without result = accumulation.
//  • Zhang et al. (2023), "Agent-based modeling of cooperative manipulation"
//    (SSRN 5234901). Stop-loss orders exploited to ignite momentum;
//    fake breakouts are rational strategies for large players.
// ============================================================================

define(title="Market Maker Behavior Detector V2", position="onchart", axis=false)

// === USER INPUTS ===
// --- Range Detection ---
var rangeLen = input(name="rangeLen", type="number", defaultValue=20, label="Range Lookback (bars)", constraints={min: 5, max: 100, step: 1}, group="Range Detection")
var flatnessMult = input(name="flatnessMult", type="number", defaultValue=0.5, label="Flatness Threshold (× ATR)", constraints={min: 0.1, max: 3.0, step: 0.1}, group="Range Detection")
var showRange = input(name="showRange", type="boolean", defaultValue=true, label="Show Range Boundaries", group="Range Detection")

// --- Delta / Volume ---
var deltaLen = input(name="deltaLen", type="number", defaultValue=20, label="Delta Z-Score Lookback", constraints={min: 5, max: 100, step: 1}, group="Delta / Volume")
var thresholdZ = input(name="thresholdZ", type="number", defaultValue=1.0, label="Delta Z-Score Threshold", constraints={min: 0.0, max: 5.0, step: 0.1}, group="Delta / Volume")
var volConfirmMult = input(name="volConfirmMult", type="number", defaultValue=1.5, label="Volume Confirmation Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Delta / Volume")
var showDelta = input(name="showDelta", type="boolean", defaultValue=false, label="Show Delta Z-Score Line", group="Delta / Volume")

// --- Liquidity Grab ---
var grabLookback = input(name="grabLookback", type="number", defaultValue=5, label="Grab Lookback (bars)", constraints={min: 2, max: 20, step: 1}, group="Liquidity Grab")
var grabRecoverMult = input(name="grabRecoverMult", type="number", defaultValue=0.5, label="Grab Recovery Ratio (× range)", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Liquidity Grab")
var grabVolConfirm = input(name="grabVolConfirm", type="boolean", defaultValue=true, label="Require Volume Confirmation for Grab", group="Liquidity Grab")

// --- ATR ---
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length", constraints={min: 5, max: 100, step: 1}, group="ATR")

// --- Display ---
var showAccumShapes = input(name="showAccumShapes", type="boolean", defaultValue=true, label="Show Accumulation Shapes", group="Display")
var showDistribShapes = input(name="showDistribShapes", type="boolean", defaultValue=true, label="Show Distribution Shapes", group="Display")
var showGrabShapes = input(name="showGrabShapes", type="boolean", defaultValue=true, label="Show Liquidity Grab Shapes", group="Display")
var showRegimeLabel = input(name="showRegimeLabel", type="boolean", defaultValue=true, label="Show Regime Label", group="Display")
var showRegimeBar = input(name="showRegimeBar", type="boolean", defaultValue=true, label="Show Regime Intensity Bar", group="Display")

// --- Colors ---
var accumColor = input(name="accumColor", type="color", defaultValue="#26a69a", label="Accumulation Color", group="Colors")
var distribColor = input(name="distribColor", type="color", defaultValue="#ef5350", label="Distribution Color", group="Colors")
var grabUpColor = input(name="grabUpColor", type="color", defaultValue="#ffeb3b", label="Grab High Color", group="Colors")
var grabDownColor = input(name="grabDownColor", type="color", defaultValue="#ff9800", label="Grab Low Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")

// === DATA SOURCES ===
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries op = bars.open
timeseries vol = bars.volume

// isnan guard — prevents NaN propagation on startup
if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// === COMPUTATION ===
// ATR (Wilder) with proper True Range formula
timeseries prevClose = isnan(px[1]) ? px : px[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = sma(trueRange, atrLen)

// Range detection with ATR-scaled flatness
timeseries rangeHi = highest(hi, rangeLen)
timeseries rangeLo = lowest(lo, rangeLen)
timeseries rangeSize = rangeHi - rangeLo
timeseries rangeMid = (rangeHi + rangeLo) / 2.0
timeseries flatBound = atr * flatnessMult

// Price is "flat" when close stays within ATR × flatnessMult of range midpoint
timeseries isFlat = math.abs(px - rangeMid) < flatBound

// Buy/Sell volume decomposition with taker volume fallback
timeseries hasTaker = !isnan(taker.buy) && !isnan(taker.sell)
timeseries buyVol = hasTaker ? taker.buy : (px > op ? vol : 0)
timeseries sellVol = hasTaker ? taker.sell : (px <= op ? vol : 0)
timeseries totalVol = buyVol + sellVol

// Delta Z-Score: (current delta − mean delta) / std dev delta
timeseries delta = buyVol - sellVol
timeseries deltaMean = sma(delta, deltaLen)
timeseries deltaStd = stdev(delta, deltaLen)
timeseries deltaZ = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0.0

// Volume confirmation: current volume > average × multiplier
timeseries avgVol = sma(vol, deltaLen)
timeseries volConfirmed = vol > avgVol * volConfirmMult

// --- ACCUMULATION DETECTION ---
// Flat price below range midpoint + rising buy pressure (positive delta Z)
// Volume confirmation required for strong signal
timeseries accumRaw = isFlat && px <= rangeMid && deltaZ > thresholdZ
timeseries accum = accumRaw && volConfirmed

// --- DISTRIBUTION DETECTION ---
// Flat price at/above range midpoint + rising sell pressure (negative delta Z)
timeseries distribRaw = isFlat && px >= rangeMid && deltaZ < -thresholdZ
timeseries distrib = distribRaw && volConfirmed

// --- LIQUIDITY GRAB DETECTION ---
// Fake breakout: price breaks range extreme then snaps back within recovery ratio
timeseries priorHi = highest(hi, grabLookback)
timeseries priorLo = lowest(lo, grabLookback)

// Break above prior high (wick above) then close back below
timeseries brokeHigh = hi > priorHi[1]
timeseries snapBackHigh = brokeHigh && px < hi - (hi - lo) * grabRecoverMult

// Break below prior low (wick below) then close back above
timeseries brokeLow = lo < priorLo[1]
timeseries snapBackLow = brokeLow && px > lo + (hi - lo) * grabRecoverMult

// Volume confirmation for grabs (spike above average during the grab candle)
timeseries grabVol = grabVolConfirm ? vol > avgVol * volConfirmMult : true

// Final grab signals
timeseries grabUp = snapBackHigh && grabVol
timeseries grabDown = snapBackLow && grabVol

// === STATIC STATE: Regime Tracking ===
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

// Current regime: 0=neutral, 1=accumulation, 2=distribution, 3=grabUp, 4=grabDown
static currentRegime = 0
static regimeBar = 0
static regimeDuration = 0
static accumCount = 0
static distribCount = 0
static grabUpCount = 0
static grabDownCount = 0
static lastAccumBar = 0
static lastDistribBar = 0
static lastGrabUpBar = 0
static lastGrabDownBar = 0

if (!isLiveUpdate) {
    if (accum) {
        currentRegime = 1
        regimeBar = barCount
        regimeDuration = 0
        accumCount = accumCount + 1
        lastAccumBar = barCount
    } else if (distrib) {
        currentRegime = 2
        regimeBar = barCount
        regimeDuration = 0
        distribCount = distribCount + 1
        lastDistribBar = barCount
    } else if (grabUp) {
        currentRegime = 3
        regimeBar = barCount
        regimeDuration = 0
        grabUpCount = grabUpCount + 1
        lastGrabUpBar = barCount
    } else if (grabDown) {
        currentRegime = 4
        regimeBar = barCount
        regimeDuration = 0
        grabDownCount = grabDownCount + 1
        lastGrabDownBar = barCount
    } else {
        regimeDuration = regimeDuration + 1
    }
}

// Event flags for plotting (only fire on the bar where regime triggers)
var accumEvent = accum && !isLiveUpdate
var distribEvent = distrib && !isLiveUpdate
var grabUpEvent = grabUp && !isLiveUpdate
var grabDownEvent = grabDown && !isLiveUpdate

// Regime color and label for current state
var regimeColor = currentRegime == 1 ? accumColor : (currentRegime == 2 ? distribColor : (currentRegime == 3 ? grabUpColor : (currentRegime == 4 ? grabDownColor : neutralColor)))
var regimeLabel = currentRegime == 1 ? "ACCUMULATION" : (currentRegime == 2 ? "DISTRIBUTION" : (currentRegime == 3 ? "LIQUIDITY GRAB ↑" : (currentRegime == 4 ? "LIQUIDITY GRAB ↓" : "NEUTRAL")))

// Regime intensity for plotBar (normalized delta Z magnitude, capped at ±3)
var regimeIntensity = 0.0
if (currentRegime == 1) {
    regimeIntensity = math.min(deltaZ, 3.0)
} else if (currentRegime == 2) {
    regimeIntensity = math.max(deltaZ, -3.0)
} else if (currentRegime == 3 || currentRegime == 4) {
    regimeIntensity = (currentRegime == 3) ? 2.0 : -2.0
}

// === PLOTS: RANGE BOUNDARIES ===
if (showRange) {
    plotLine(
        value=rangeHi,
        width=1,
        colors=["#ffffff30"],
        label=["Range High"],
        desc=["Highest high over range lookback. Institutional absorption ceiling."]
    )
    plotLine(
        value=rangeLo,
        width=1,
        colors=["#ffffff30"],
        label=["Range Low"],
        desc=["Lowest low over range lookback. Institutional absorption floor."]
    )
    plotLine(
        value=rangeMid,
        width=1,
        colors=["#ffffff15"],
        label=["Range Mid"],
        desc=["Midpoint of range. Accumulation below, distribution above."]
    )
}

// === PLOTS: DELTA Z-SCORE (optional) ===
if (showDelta) {
    plotLine(
        value=deltaZ,
        width=1,
        colors=[accumColor, distribColor, neutralColor],
        colorIndex=deltaZ > thresholdZ ? 0 : (deltaZ < -thresholdZ ? 1 : 2),
        label=["Delta Z-Score"],
        desc=["Volume delta Z-score: (buy − sell − μ) / σ. >threshold = accumulation; <-threshold = distribution."]
    )
    hline(value=thresholdZ, color=opacity(accumColor, 30), width=1)
    hline(value=-thresholdZ, color=opacity(distribColor, 30), width=1)
    hline(value=0, color="#ffffff20", width=1)
}

// === PLOTS: REGIME INTENSITY BAR ===
if (showRegimeBar) {
    var barColor = currentRegime == 1 ? accumColor : (currentRegime == 2 ? distribColor : (currentRegime == 3 ? grabUpColor : (currentRegime == 4 ? grabDownColor : neutralColor)))
    plotBar(
        value=regimeIntensity,
        colors=[barColor],
        width=1,
        label=["Regime Intensity"],
        desc=["Behavioral regime intensity: accumulation (+), distribution (−), grab (±2)."]
    )
}

// === PLOTS: SHAPE MARKERS FOR REGIME CHANGES ===
if (showAccumShapes && accumEvent) {
    plotShape(
        value=lo,
        shape="triangleup",
        color=accumColor,
        width=5,
        label=["ACCUM"],
        desc=["ACCUMULATION: Flat price below mid + rising buy pressure (ΔZ > threshold) + volume spike. Wyckoff phase signature."]
    )
}
if (showDistribShapes && distribEvent) {
    plotShape(
        value=hi,
        shape="triangledown",
        color=distribColor,
        width=5,
        label=["DISTRIB"],
        desc=["DISTRIBUTION: Flat price above mid + rising sell pressure (ΔZ < −threshold) + volume spike. Wyckoff distribution signature."]
    )
}
if (showGrabShapes && grabUpEvent) {
    plotShape(
        value=hi,
        shape="diamond",
        color=grabUpColor,
        width=5,
        label=["GRAB ↑"],
        desc=["LIQUIDITY GRAB HIGH: Fake breakout above range + snap-back. Stop hunt above prior highs (Bhusal 2025)."]
    )
}
if (showGrabShapes && grabDownEvent) {
    plotShape(
        value=lo,
        shape="diamond",
        color=grabDownColor,
        width=5,
        label=["GRAB ↓"],
        desc=["LIQUIDITY GRAB LOW: Fake breakout below range + snap-back. Stop hunt below prior lows (Bhusal 2025)."]
    )
}

// === PLOTS: PRICE LABELS FOR REGIME ===
if (accumEvent) {
    plotPriceLabel(
        price=lo,
        text="ACCUM",
        type="label",
        color="#ffffff",
        backgroundColor=accumColor,
        size=9,
        fontWeight=700
    )
}
if (distribEvent) {
    plotPriceLabel(
        price=hi,
        text="DIST",
        type="label",
        color="#ffffff",
        backgroundColor=distribColor,
        size=9,
        fontWeight=700
    )
}
if (grabUpEvent) {
    plotPriceLabel(
        price=hi,
        text="GRAB↑",
        type="callout",
        color="#000000",
        backgroundColor=grabUpColor,
        size=9,
        fontWeight=700
    )
}
if (grabDownEvent) {
    plotPriceLabel(
        price=lo,
        text="GRAB↓",
        type="callout",
        color="#000000",
        backgroundColor=grabDownColor,
        size=9,
        fontWeight=700
    )
}

// === REGIME LABEL (plotPriceLabel) ===
if (showRegimeLabel && isLastBar) {
    var labelText = regimeLabel + " | A:" + accumCount + " D:" + distribCount + " G↑:" + grabUpCount + " G↓:" + grabDownCount
    plotPriceLabel(
        price=hi,
        text=labelText,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=9,
        fontWeight=700
    )
}