MM Flow
FlowScripts

Perfected FlowScript

Whale Dominant

Whale Dominant V2 is indexed as 105_whale_dominant.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

12.7 KB

Lines

286

Native Signal Candidates

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

2/2 guarded

Whale Bubble

line 236:5

Trigger

(showBubbles && isWhale)

Value

whaleZ > 0 ? high : low

Deps

isWhale:var, showBubbles:input

Extreme Whale

line 249:5

Trigger

(showShapes && whaleExtreme)

Value

whaleZ > 0 ? high : low

Deps

showShapes:input, whaleExtreme:var

105_whale_dominant.flowscript

source path: kscripts/perfected/105_whale_dominant.flowscript · sha256:2272fd6a413f3e210804c2c640f53e56d6e792c83240b3415ad0da588aa8e002

hash verified
//@version=2

// ============================================================================
// Whale Dominant V2 — Whale-Sized Volume Delta & Orderbook Dominance
// Author: Toppy123 (@Toppy123) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, #whale, #volume, #orderbook, #cvd, #delta
//
// Detects and visualizes whale-dominant order flow by isolating statistically
// extreme volume bars (z-score filtered), tracking their cumulative delta
// (CVD), and overlaying orderbook imbalance. Whale-sized bars are rendered as
// z-score-scaled bubbles with directional color coding, while a smoothed whale
// CVD line reveals sustained large-player participation patterns.
//
// Academic foundation (exact papers & formulas):
//  1. Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
//     Order Flow and Stock Returns", Journal of Financial Economics, 77(2), 411–441.
//     [Formula] Institutional footprint detection from trade-size patterns;
//     large trades (>$30k) carry detectable price-impact signatures.
//     DOI: https://doi.org/10.1016/j.jfineco.2004.07.001
//
//  2. Jones & Lipson (2005), "Are Retail Orders Different?", Journal of Financial
//     Economics, 78(3), 631–669. Retail vs. institutional order flow dynamics;
//     institutional orders systematically trade against retail within 5 minutes.
//     DOI: https://doi.org/10.1016/j.jfineco.2005.03.009
//
//  3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}
//     Price impact slope ∝ 1/depth; larger orders have greater impact in
//     shallower books. Directly motivates whale-dominance tracking.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  4. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//     a High-Frequency World" (VPIN). Review of Financial Studies, 25(5), 1457–1493.
//     VPIN = Σ|V_buy − V_sell| / ΣV_total over volume buckets; anticipates
//     market stress events. DOI: https://doi.org/10.1093/rfs/hhs053
//
//  5. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow autocorrelations decay as power law; cumulative measures
//     (CVD) capture sustained institutional pressure. arXiv:cond-mat/0311053
//
//  6. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy): classify as buy if close > open, else sell.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// ============================================================================

define(title="Whale Dominant V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 20, max: 200, step: 5}, group="Computation")
var whaleThreshold = input(name="whaleThreshold", type="number", defaultValue=2.0, label="Whale Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="Whale CVD Smooth Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var obDepth = input(name="obDepth", type="number", defaultValue=5, label="Orderbook Depth (%)", constraints={min: 1, max: 20, step: 1}, group="Computation")
var imbSmooth = input(name="imbSmooth", type="number", defaultValue=3, label="Imbalance Smooth Length", constraints={min: 1, max: 20, step: 1}, group="Computation")

// -- Display --
var showWhaleCVD = input(name="showWhaleCVD", type="boolean", defaultValue=true, label="Show Whale CVD", group="Display")
var showImbalance = input(name="showImbalance", type="boolean", defaultValue=true, label="Show Whale-Side Imbalance", group="Display")
var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show Whale Bubbles", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Whale Z Histogram", group="Display")
var showRawVolZ = input(name="showRawVolZ", type="boolean", defaultValue=false, label="Show Raw Volume Z-Score", group="Display")

// -- Colors --
var bidColor = input(name="bidColor", type="color", defaultValue="#26a69a", label="Whale Bid Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ef5350", label="Whale Ask Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#ff9800", label="Whale CVD Color", group="Colors")
var imbBidColor = input(name="imbBidColor", type="color", defaultValue="#00c853", label="Imbalance Bid Color", group="Colors")
var imbAskColor = input(name="imbAskColor", type="color", defaultValue="#d50000", label="Imbalance Ask Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ff9100", label="Extreme Event Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries book = source("orderbook", currentSymbol, currentExchange)

timeseries close = bars.close
timeseries open = bars.open
timeseries high = bars.high
timeseries low = bars.low
timeseries vol = bars.volume

// Guard: halt until OHLCV and orderbook data have loaded to avoid NaN propagation
if (isnan(close[0]) || isnan(vol[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Per-bar volume delta (Lee-Ready fallback when taker feed is unavailable) --
// Lee-Ready (1991) tick test: close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, we prefer the direct feed for higher accuracy.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (close > open ? vol : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (close <= open ? vol : 0)
timeseries barDelta = buyVol - sellVol

// -- 3.2 Volume z-score to detect whale-sized bars --
// z_t = (V_t − μ_t) / σ_t; bars exceeding threshold are classified as whale events.
timeseries volMean = sma(vol, zWindow)
timeseries volStd = stdev(vol, zWindow)
timeseries volZ = (volStd > 0) ? (vol - volMean) / volStd : 0

// Whale classification: volume bar exceeds the user-configured σ threshold
var isWhale = volZ > whaleThreshold

// -- 3.3 Whale delta: delta from whale-sized bars only --
// Isolates institutional footprint by zeroing non-whale bars.
timeseries whaleDelta = isWhale ? barDelta : 0

// -- 3.4 True cumulative Whale CVD via static state (persistent across bars) --
// CVD_t = Σ_{i=0}^{t} whaleΔ_i. static persists across bars; guard each increment.
static whaleCVD_cum = 0.0

if (!isnan(whaleDelta[0])) {
    whaleCVD_cum = whaleCVD_cum + whaleDelta[0]
}

// -- 3.5 Smoothed whale CVD for display --
timeseries whaleCVD_sm = ema(whaleCVD_cum, smoothLen)

// -- 3.6 Whale delta z-score (standardized whale pressure) --
// Measures how extreme the current whale delta is relative to recent whale history.
timeseries whaleMean = sma(whaleDelta, zWindow)
timeseries whaleStd = stdev(whaleDelta, zWindow)
timeseries whaleZ = (whaleStd > 0) ? (whaleDelta - whaleMean) / whaleStd : 0

// -- 3.7 Orderbook imbalance at configured depth --
// Imbalance ratio = (bid − ask) / (bid + ask); range [−1, 1].
// Positive = bid-heavy (supportive), negative = ask-heavy (resistive).
timeseries bidVol = sumBids(book, obDepth)
timeseries askVol = sumAsks(book, obDepth)
timeseries obTotal = bidVol + askVol
timeseries obImbRaw = (obTotal > 0) ? (bidVol - askVol) / obTotal : 0
timeseries obImb = ema(obImbRaw, imbSmooth)

// -- 3.8 Regime detection (configurable thresholds, no magic numbers) --
var whaleBull = whaleZ > 0 && isWhale
var whaleBear = whaleZ < 0 && isWhale
var whaleExtreme = abs(whaleZ) > whaleThreshold * 1.5
var imbBull = obImb > 0.2
var imbBear = obImb < -0.2

// -- 3.9 Static state tracking — session-level persistence --
// Tracks cumulative whale flow, regime duration, and extreme event counts.
static cumWhaleBuy = 0.0
static cumWhaleSell = 0.0
static whaleBullBars = 0
static whaleBearBars = 0
static lastRegime = 0
static extremeWhaleCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (!isnan(buyVol[0]) && isWhale) {
        cumWhaleBuy = cumWhaleBuy + buyVol[0]
    }
    if (!isnan(sellVol[0]) && isWhale) {
        cumWhaleSell = cumWhaleSell + sellVol[0]
    }

    if (whaleBull) {
        whaleBullBars = whaleBullBars + 1
        whaleBearBars = 0
        lastRegime = 1
    } else if (whaleBear) {
        whaleBearBars = whaleBearBars + 1
        whaleBullBars = 0
        lastRegime = -1
    } else {
        whaleBullBars = 0
        whaleBearBars = 0
        lastRegime = 0
    }

    if (whaleExtreme) {
        extremeWhaleCount = extremeWhaleCount + 1
    }
}

// -- 3.10 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 Whale CVD line (plotLine) — regime-colored by slope direction
if (showWhaleCVD) {
    var cvdRising = whaleCVD_sm > whaleCVD_sm[1]
    plotLine(
        value=whaleCVD_sm,
        width=2,
        colors=[cvdRising ? bidColor : askColor],
        label=["Whale CVD"],
        desc=["Smoothed cumulative whale delta; direction-coded by slope"]
    )
}

// 4.2 Orderbook imbalance (plotLine) with fill to zero
if (showImbalance) {
    var imbColorIdx = obImb >= 0 ? 0 : 1
    plotLine(
        value=([obImb, zeroLine]),
        width=2,
        colors=[imbBidColor, imbAskColor, neutralColor],
        colorIndex=imbColorIdx,
        fill=true,
        label=["OB Imbalance"],
        desc=["Orderbook imbalance at " + obDepth + "% depth; filled histogram"]
    )
}

// 4.3 Whale bubble markers (plotShape) — z-score sized, directionally colored
// Bubbles appear at bar highs for whale buy bars and at bar lows for whale sell bars.
if (showBubbles && isWhale) {
    var bubbleSize = math.min(math.abs(volZ) * 2.0, 12)
    var bubbleColor = whaleZ > 0 ? bidColor : askColor
    var bubbleOpacity = whaleExtreme ? 90 : 60

    plotShape(
        value=whaleZ > 0 ? high : low,
        shape="circle",
        color=opacity(bubbleColor, bubbleOpacity),
        width=bubbleSize,
        label=["Whale Bubble"],
        desc=["Whale-sized volume bar (z > " + whaleThreshold + "); size ∝ z-score"]
    )
}

// 4.4 Extreme whale shapes (plotShape) — diamond markers for extreme events
if (showShapes && whaleExtreme) {
    var extremeShape = whaleZ > 0 ? "triangleup" : "triangledown"
    plotShape(
        value=whaleZ > 0 ? high : low,
        shape=extremeShape,
        color=extremeColor,
        width=4,
        label=["Extreme Whale"],
        desc=["Extreme whale event (|z| > 1.5× threshold); potential institutional absorption"]
    )
}

// 4.5 Whale Z histogram (plotBar) — color-coded by direction and regime
if (showHistogram) {
    var histColors = whaleExtreme ? [extremeColor, extremeColor] : [bidColor, askColor]
    plotBar(
        value=whaleZ,
        colors=histColors,
        width=1,
        label=["Whale Z"],
        desc=["Whale delta z-score; orange = statistically extreme regime"]
    )
}

// 4.6 Optional raw volume z-score (plotLine)
if (showRawVolZ) {
    plotLine(
        value=volZ,
        width=1,
        colors=[neutralColor],
        label=["Volume Z"],
        desc=["Raw volume z-score; context for whale threshold calibration"]
    )
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=whaleThreshold, color=opacity(bidColor, 20), width=1)
hline(value=-whaleThreshold, color=opacity(askColor, 20), width=1)