Perfected FlowScript
CVD Whale Tracking V2
CVD Whale Tracking V2 — Perfected Edition is indexed as 080_cvd_whale_tracking_v2.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
17.5 KB
Lines
416
Native Signal Candidates
5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Whale
line 322:5
Trigger
(showBubbles && isWhale)
Value
whaleCVD
Deps
isWhale:var, showBubbles:input
Whale Cluster Bull
line 335:9
Trigger
(showShapes && whaleCluster) && (whaleBullBars >= minWhaleBars)
Value
whaleCVD
Deps
minWhaleBars:input, showShapes:input, whaleBullBars:static, whaleCluster:var
Whale Cluster Bear
line 345:9
Trigger
(showShapes && whaleCluster) && (whaleBearBars >= minWhaleBars)
Value
whaleCVD
Deps
minWhaleBars:input, showShapes:input, whaleBearBars:static, whaleCluster:var
CVD Bull Div
line 359:9
Trigger
(showShapes && enableDiv) && (cvdBullDiv)
Value
whaleCVD
Deps
cvdBullDiv:var, enableDiv:input, showShapes:input
CVD Bear Div
line 369:9
Trigger
(showShapes && enableDiv) && (cvdBearDiv)
Value
whaleCVD
Deps
cvdBearDiv:var, enableDiv:input, showShapes:input
080_cvd_whale_tracking_v2.flowscript
source path: kscripts/perfected/080_cvd_whale_tracking_v2.flowscript · sha256:8efea534252f64e9f1b1a19e6419d615b207b287cd3958848036738b361f703f
//@version=2
// ============================================================================
// CVD Whale Tracking V2 — Perfected Edition
// Author: Toppy123 (@Toppy123) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #cvd, #whale, #volume, #delta, #orderflow, #accumulation
//
// Production-grade Cumulative Volume Delta (CVD) analysis focused on tracking
// whale-sized order flow imbalances. Implements per-bar delta via Lee-Ready
// tick-classification with taker-volume fallback, rolling-window z-score
// standardization for volume magnitude, stateful whale-event tracking, bubble
// markers for extreme events, divergence detection between price and whale CVD,
// and color-coded regime visualization with fill areas.
//
// Research papers underpinning this design:
// 1. 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}
// Cumulative OFI (CVD) linearly predicts short-term price changes.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
//
// 2. Lillo & Farmer (2004), "The Long Memory of the Efficient Market":
// order flow autocorrelations decay as a power law; cumulative measures
// capture sustained pressure far better than per-bar snapshots.
//
// 3. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
// a High Frequency World" (VPIN): volume-synchronized probability of
// informed trading; whale events map to high-toxicity flow segments.
//
// 4. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand": square-root impact law; large orders have sublinear
// price impact due to liquidity memory, making CVD accumulation critical.
//
// 5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746. Foundational tick-classification
// algorithm (85–93% accuracy) used when granular taker-buy/sell data
// is unavailable: classify as buy if close > open, else sell.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
// 6. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
// Market Returns", Journal of Financial Economics, 65(1), 111–130.
// Extreme |Imbalance| predicts return reversals; motivates the z-score
// threshold design for whale-event detection.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// ============================================================================
define(title="CVD Whale Tracking V2 — Perfected Edition", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var spotSymbol = input(name="spotSymbol", type="string", defaultValue="BTCUSDT", label="Spot Symbol", group="Data Sources")
var spotExch = input(name="spotExch", type="string", defaultValue="BINANCE", label="Spot Exchange", group="Data Sources")
var perpSymbol = input(name="perpSymbol", type="string", defaultValue="BTCUSDT", label="Perp Symbol", group="Data Sources")
var perpExch = input(name="perpExch", type="string", defaultValue="BINANCE_FUTURES", label="Perp Exchange", group="Data Sources")
// -- Whale Detection --
var whaleThreshold = input(name="whaleThreshold", type="number", defaultValue=2.0, label="Whale delta z-score threshold", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Whale Detection")
var lookback = input(name="lookback", type="number", defaultValue=50, label="Z-score lookback", constraints={min: 10, max: 200, step: 5}, group="Whale Detection")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="CVD smoothing length", constraints={min: 1, max: 50, step: 1}, group="Whale Detection")
var useVolumeProxy = input(name="useVolumeProxy", type="boolean", defaultValue=true, label="Use volume*range as trade size proxy", group="Whale Detection")
var minWhaleBars = input(name="minWhaleBars", type="number", defaultValue=2, label="Min consecutive whale bars for cluster", constraints={min: 1, max: 10, step: 1}, group="Whale Detection")
// -- Divergence --
var enableDiv = input(name="enableDiv", type="boolean", defaultValue=true, label="Enable Price-CVD Divergence", group="Divergence")
var divLookback = input(name="divLookback", type="number", defaultValue=10, label="Divergence Lookback", constraints={min: 5, max: 50, step: 1}, group="Divergence")
// -- Display --
var showRawDelta = input(name="showRawDelta", type="boolean", defaultValue=false, label="Show raw per-bar delta", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Delta Z-Score", group="Display")
var showWhaleCVD = input(name="showWhaleCVD", type="boolean", defaultValue=true, label="Show Whale CVD", group="Display")
var showAllCVD = input(name="showAllCVD", type="boolean", defaultValue=true, label="Show Total CVD", group="Display")
var showSmoothCVD = input(name="showSmoothCVD", type="boolean", defaultValue=true, label="Show Smoothed Whale CVD", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Histogram", group="Display")
var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show Whale Bubble Markers", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Divergence Shapes", group="Display")
// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear Color", group="Colors")
var whaleColor = input(name="whaleColor", type="color", defaultValue="#ffeb3b", label="Whale Event Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="Whale CVD Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var divBullColor = input(name="divBullColor", type="color", defaultValue="#00c853", label="Bullish Divergence Color", group="Colors")
var divBearColor = input(name="divBearColor", type="color", defaultValue="#d50000", label="Bearish Divergence Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries spotBars = ohlcv(symbol=spotSymbol, exchange=spotExch)
timeseries perpBars = ohlcv(symbol=perpSymbol, exchange=perpExch)
timeseries spotTaker = source("taker_volume", spotSymbol, spotExch)
timeseries perpTaker = source("taker_volume", perpSymbol, perpExch)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(spotBars.close[0]) || isnan(perpBars.close[0]) || !isnum(spotTaker.buy) || !isnum(perpTaker.buy)) {
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.
// Spot delta
timeseries spotTradeSize = useVolumeProxy ? spotBars.volume * (spotBars.high - spotBars.low) : spotBars.volume
timeseries spotBuy = isnum(spotTaker.buy) ? spotTaker.buy : (spotBars.close > spotBars.open ? spotTradeSize : 0)
timeseries spotSell = isnum(spotTaker.sell) ? spotTaker.sell : (spotBars.close <= spotBars.open ? spotTradeSize : 0)
timeseries spotDelta = spotBuy - spotSell
// Perp delta
timeseries perpTradeSize = useVolumeProxy ? perpBars.volume * (perpBars.high - perpBars.low) : perpBars.volume
timeseries perpBuy = isnum(perpTaker.buy) ? perpTaker.buy : (perpBars.close > perpBars.open ? perpTradeSize : 0)
timeseries perpSell = isnum(perpTaker.sell) ? perpTaker.sell : (perpBars.close <= perpBars.open ? perpTradeSize : 0)
timeseries perpDelta = perpBuy - perpSell
// Combined delta (spot + perp for unified whale tracking)
timeseries barDelta = spotDelta + perpDelta
// -- 3.2 Z-score of bar delta over lookback --
timeseries deltaMean = sma(source=barDelta, period=lookback)
timeseries deltaStd = stdev(source=barDelta, period=lookback)
timeseries deltaZ = (deltaStd > 0) ? (barDelta - deltaMean) / deltaStd : 0
// -- 3.3 Whale events: |delta z-score| > threshold --
var isWhale = abs(deltaZ) > whaleThreshold
var whaleDelta = isWhale ? barDelta : 0
var whaleDirection = isWhale ? (barDelta > 0 ? 1 : -1) : 0
// -- 3.4 Cumulative CVD via static state (true cumulative, guarded against NaN) --
static whaleCVD_cum = 0.0
static allCVD_cum = 0.0
if (!isnan(whaleDelta[0])) {
whaleCVD_cum = whaleCVD_cum + whaleDelta[0]
}
if (!isnan(barDelta[0])) {
allCVD_cum = allCVD_cum + barDelta[0]
}
// Rolling-window CVD (stationary approximation for z-score and display)
timeseries whaleCVD = sum(whaleDelta, lookback)
timeseries allCVD = sum(barDelta, lookback)
// -- 3.5 Smoothed whale CVD --
timeseries smoothCVD = ema(source=whaleCVD, period=smoothLen)
// -- 3.6 Z-score of CVD magnitude (how extreme is the cumulative flow) --
timeseries cvdMean = sma(source=whaleCVD, period=lookback)
timeseries cvdStd = stdev(source=whaleCVD, period=lookback)
timeseries cvdZ = (cvdStd > 0) ? (whaleCVD - cvdMean) / cvdStd : 0
// -- 3.7 Whale event tracking via static variables --
// Tracks consecutive bars in whale regime for context-aware alerting.
static whaleBullBars = 0
static whaleBearBars = 0
static whaleNeutralBars = 0
static lastWhaleRegime = 0
if (isWhale) {
if (barDelta > 0) {
whaleBullBars = whaleBullBars + 1
whaleBearBars = 0
whaleNeutralBars = 0
lastWhaleRegime = 1
} else if (barDelta < 0) {
whaleBearBars = whaleBearBars + 1
whaleBullBars = 0
whaleNeutralBars = 0
lastWhaleRegime = -1
} else {
whaleNeutralBars = whaleNeutralBars + 1
}
} else {
whaleBullBars = 0
whaleBearBars = 0
whaleNeutralBars = whaleNeutralBars + 1
if (whaleNeutralBars > 5) {
lastWhaleRegime = 0
}
}
// Whale cluster: consecutive whale bars in same direction
var whaleCluster = (whaleBullBars >= minWhaleBars || whaleBearBars >= minWhaleBars)
// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0
// -- 3.9 Regime detection (color coding by direction) --
var whaleBull = whaleCVD > 0 && barDelta > 0
var whaleBear = whaleCVD < 0 && barDelta < 0
var neutralRegime = !whaleBull && !whaleBear
// ---------------------------------------------------------------------------
// 4. DIVERGENCE DETECTION (Price vs Whale CVD)
// ---------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, CVD disagrees.
// We track pivot high/low state across bars using static variables.
static divPrevPxHigh = -1.0
static divPrevCvdHigh = -1.0
static divPrevPxLow = -1.0
static divPrevCvdLow = -1.0
var cvdBearDiv = false
var cvdBullDiv = false
if (divPrevPxHigh < 0) {
divPrevPxHigh = perpBars.high[0]
divPrevCvdHigh = whaleCVD[0]
divPrevPxLow = perpBars.low[0]
divPrevCvdLow = whaleCVD[0]
}
if (!isLiveUpdate && enableDiv) {
// Bearish divergence: price higher high, CVD lower high
if (perpBars.high[0] > divPrevPxHigh) {
if (whaleCVD[0] < divPrevCvdHigh) {
cvdBearDiv = true
}
divPrevPxHigh = perpBars.high[0]
divPrevCvdHigh = whaleCVD[0]
}
// Bullish divergence: price lower low, CVD higher low
if (perpBars.low[0] < divPrevPxLow) {
if (whaleCVD[0] > divPrevCvdLow) {
cvdBullDiv = true
}
divPrevPxLow = perpBars.low[0]
divPrevCvdLow = whaleCVD[0]
}
}
// ---------------------------------------------------------------------------
// 5. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill
// ---------------------------------------------------------------------------
// 5.1 Raw per-bar delta (optional, histogram style via plotBar)
if (showRawDelta) {
var rawBull = barDelta >= 0
plotBar(
value=barDelta,
colors=[transparency(bullColor, 50), transparency(bearColor, 50)],
colorIndex=rawBull ? 0 : 1,
width=1,
label=["Bar Delta"],
desc=["Per-bar volume delta (buy − sell)"]
)
}
// 5.2 Delta Z-Score (plotLine)
if (showZScore) {
plotLine(
value=deltaZ,
width=2,
colors=[whaleColor],
label=["Delta Z-Score"],
desc=["Standardized per-bar delta; whale threshold = ±" + whaleThreshold]
)
}
// 5.3 Whale CVD with fill to zero (color-coded by regime)
if (showWhaleCVD) {
var whaleRegimeIdx = whaleBull ? 0 : (whaleBear ? 1 : 2)
plotLine(
value=[whaleCVD, zeroLine],
width=2,
colors=[transparency(bullColor, 40), transparency(bearColor, 40), transparency(neutralColor, 40)],
colorIndex=whaleRegimeIdx,
fill=true,
label=["Whale CVD"],
desc=["Rolling-window whale CVD; color-coded by accumulation/distribution regime"]
)
}
// 5.4 Total CVD (all flow, not just whale)
if (showAllCVD) {
plotLine(
value=allCVD,
width=1,
colors=[transparency(neutralColor, 60)],
label=["Total CVD"],
desc=["Rolling-window total CVD (all flow) for context"]
)
}
// 5.5 Smoothed Whale CVD (plotLine)
if (showSmoothCVD) {
plotLine(
value=smoothCVD,
width=2,
colors=[cvdColor],
label=["Smoothed Whale CVD"],
desc=["EMA-smoothed whale CVD (" + smoothLen + ") for trend clarity"]
)
}
// 5.6 Divergence histogram (price vs whale CVD divergence)
if (showDivergence) {
var divVal = cvdBullDiv ? 1 : (cvdBearDiv ? -1 : 0)
plotBar(
value=divVal,
colors=[transparency(divBullColor, 70), transparency(divBearColor, 70), transparency(neutralColor, 30)],
colorIndex=cvdBullDiv ? 0 : (cvdBearDiv ? 1 : 2),
width=1,
label=["CVD Divergence"],
desc=["Price-CVD divergence: +1 = bullish, −1 = bearish, 0 = none"]
)
}
// 5.7 Whale bubble markers (bubble markers for whale events)
if (showBubbles && isWhale) {
var bubbleColor = barDelta > 0 ? bullColor : bearColor
var bubbleSize = math.min(3, 1 + abs(deltaZ[0]) / whaleThreshold)
plotShape(
value=whaleCVD,
shape="circle",
colorIndex=bubbleColor,
width=bubbleSize,
label=["Whale"],
desc=["Whale event: |z| > " + whaleThreshold + "; delta = " + barDelta[0]]
)
}
// 5.8 Extreme whale cluster shapes (consecutive whale bars)
if (showShapes && whaleCluster) {
if (whaleBullBars >= minWhaleBars) {
plotShape(
value=whaleCVD,
shape="triangleup",
colorIndex=whaleColor,
width=3,
label=["Whale Cluster Bull"],
desc=["Consecutive whale accumulation bars (" + whaleBullBars + ") — potential absorption"]
)
}
if (whaleBearBars >= minWhaleBars) {
plotShape(
value=whaleCVD,
shape="triangledown",
colorIndex=whaleColor,
width=3,
label=["Whale Cluster Bear"],
desc=["Consecutive whale distribution bars (" + whaleBearBars + ") — potential exhaustion"]
)
}
}
// 5.9 Divergence shapes
if (showShapes && enableDiv) {
if (cvdBullDiv) {
plotShape(
value=whaleCVD,
shape="arrowup",
colorIndex=divBullColor,
width=2,
label=["CVD Bull Div"],
desc=["Bullish divergence: price lower low, whale CVD higher low"]
)
}
if (cvdBearDiv) {
plotShape(
value=whaleCVD,
shape="arrowdown",
colorIndex=divBearColor,
width=2,
label=["CVD Bear Div"],
desc=["Bearish divergence: price higher high, whale CVD lower high"]
)
}
}
// 5.10 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=whaleThreshold, color="#ffffff20", width=1)
hline(value=-whaleThreshold, color="#ffffff20", width=1)
// ---------------------------------------------------------------------------
// 6. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = whaleBull ? "ACCUMULATION" : (whaleBear ? "DISTRIBUTION" : "NEUTRAL")
var regimeTextColor = whaleBull ? bullColor : (whaleBear ? bearColor : neutralColor)
plotTable(
data=[
["Whale CVD V2", regimeText],
["Whale CVD", whaleCVD[0]],
["Total CVD", allCVD[0]],
["Smoothed CVD", smoothCVD[0]],
["Delta Z", deltaZ[0]],
["CVD Z", cvdZ[0]],
["Whale Bars", lastWhaleRegime > 0 ? whaleBullBars : whaleBearBars],
["Divergence", cvdBullDiv ? "BULL" : (cvdBearDiv ? "BEAR" : "NONE")]
],
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
)
}