Perfected FlowScript
CVD Tracking Whale
CVD Tracking Whale — Perfected Edition is indexed as 120_cvd_tracking_whale.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
15.9 KB
Lines
526
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Whale Buy
line 411:9
Trigger
(showWhale) && (extremeWhaleUp)
Value
cvdZ
Deps
extremeWhaleUp:var, showWhale:input
Whale Buy
line 420:9
Trigger
(showWhale) && (whaleUp)
Value
cvdZ
Deps
showWhale:input, whaleUp:var
Extreme Whale Sell
line 431:9
Trigger
(showWhale) && (extremeWhaleDn)
Value
cvdZ
Deps
extremeWhaleDn:var, showWhale:input
Whale Sell
line 440:9
Trigger
(showWhale) && (whaleDn)
Value
cvdZ
Deps
showWhale:input, whaleDn:var
Bull Div
line 454:9
Trigger
(showDivergenceShapes && enableDiv) && (bullDiv)
Value
cvdSmooth
Deps
bullDiv:var, enableDiv:input, showDivergenceShapes:input
Bear Div
line 464:9
Trigger
(showDivergenceShapes && enableDiv) && (bearDiv)
Value
cvdSmooth
Deps
bearDiv:var, enableDiv:input, showDivergenceShapes:input
120_cvd_tracking_whale.flowscript
source path: kscripts/perfected/120_cvd_tracking_whale.flowscript · sha256:d756e97c8f47085d49054a239985d99b8e6295999ec7a6fd93d2a152fdc37fc4
//@version=2
// ============================================================================
// CVD Tracking Whale — Perfected Edition
// Author: Toppy123 (@Toppy123) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #cvd, #whale, #volume, #orderflow, #divergence
//
// Production-quality cumulative volume delta tracker with whale-size event
// detection, z-score normalization, stateful divergence, and multi-regime
// color coding. Identifies large-participant accumulation/distribution via
// statistically-significant CVD deviations combined with elevated volume.
//
// Research papers underpinning this design:
// 1. Campbell, Ramadorai & Vuolteenaho (2005), "Caught On Tape: Institutional
// Order Flow and Stock Returns". Regression-based method achieves ~12% R²
// in predicting institutional ownership from trade-size patterns; validates
// that large participants leave detectable traces in volume data.
// 2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// Journal of Financial Econometrics, 12(1), 47–88.
// [Formula] OFI_t = Σ(E⁺ − E⁻); ΔP = λ · OFI + ε. Sustained CVD builds
// (whale accumulation) must eventually move price unless absorbed by
// latent liquidity. DOI: https://doi.org/10.1093/jjfinec/nbt003
// 3. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
// a High-Frequency World". VPIN = Σ|V_buy − V_sell| / ΣV_total over volume
// buckets; anticipates informed trading. Conceptually similar to whale
// detection—identifying periods where volume imbalance suggests informed
// (large) participant activity.
// 4. Jones & Lipson (2005), "Are Retail Orders Different?", Journal of
// Finance. Institutions systematically trade against retail flow within
// five minutes; whale CVD divergence flags institutional-engineered moves.
// DOI: https://doi.org/10.1111/j.1540-6261.2005.00743.x
// 5. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
// 53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise. Kyle's λ
// establishes the linear price-impact coefficient that underpins every
// delta-based trading signal. DOI: https://doi.org/10.2307/1913210
// ============================================================================
define(
title="CVD Tracking Whale — Perfected Edition",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- CVD Settings ---
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=7,
label="CVD Smoothing Length",
constraints={min: 1, max: 50, step: 1},
group="CVD Settings"
)
var zLen = input(
name="zLen",
type="number",
defaultValue=50,
label="Z-Score Lookback",
constraints={min: 10, max: 200, step: 5},
group="CVD Settings"
)
// --- Whale Detection ---
var threshold = input(
name="threshold",
type="number",
defaultValue=2.0,
label="Whale Threshold (σ)",
constraints={min: 0.5, max: 5.0, step: 0.5},
group="Whale Detection"
)
var extremeThreshold = input(
name="extremeThreshold",
type="number",
defaultValue=3.0,
label="Extreme Whale Threshold (σ)",
constraints={min: 1.5, max: 6.0, step: 0.5},
group="Whale Detection"
)
var minVolMult = input(
name="minVolMult",
type="number",
defaultValue=1.5,
label="Min Volume Multiple vs Avg",
constraints={min: 1.0, max: 5.0, step: 0.5},
group="Whale Detection"
)
// --- Divergence ---
var enableDiv = input(
name="enableDiv",
type="boolean",
defaultValue=true,
label="Enable Divergence Detection",
group="Divergence"
)
var divLookback = input(
name="divLookback",
type="number",
defaultValue=10,
label="Divergence Lookback (pivot bars)",
constraints={min: 5, max: 50, step: 1},
group="Divergence"
)
// --- Display ---
var showCVD = input(
name="showCVD",
type="boolean",
defaultValue=true,
label="Show CVD Line",
group="Display"
)
var showZ = input(
name="showZ",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showWhale = input(
name="showWhale",
type="boolean",
defaultValue=true,
label="Show Whale Markers",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show CVD Fill",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
var showDivergenceShapes = input(
name="showDivergenceShapes",
type="boolean",
defaultValue=true,
label="Show 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 zColor = input(
name="zColor",
type="color",
defaultValue="#ab47bc",
label="Z-Score Color",
group="Colors"
)
var whaleBullColor = input(
name="whaleBullColor",
type="color",
defaultValue="#00e676",
label="Whale Buy Color",
group="Colors"
)
var whaleBearColor = input(
name="whaleBearColor",
type="color",
defaultValue="#ff5252",
label="Whale Sell Color",
group="Colors"
)
var divBullColor = input(
name="divBullColor",
type="color",
defaultValue="#00e676",
label="Bullish Divergence Color",
group="Colors"
)
var divBearColor = input(
name="divBearColor",
type="color",
defaultValue="#ff5252",
label="Bearish Divergence Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries o = bars.open
timeseries v = bars.volume
// Guard: halt until primary data feed is loaded
if (isnan(c[0])) {
return
}
// Attempt taker_volume source (preferred for accuracy)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
var hasTaker = isnum(taker.buy)
// Orderbook snapshot for midpoint-based fallback
timeseries ob = orderbook(symbol=currentSymbol, exchange=currentExchange)
timeseries bidPx = ob.bid_price
timeseries askPx = ob.ask_price
var hasOrderbook = isnum(bidPx[0]) && isnum(askPx[0])
// -----------------------------------------------------------------------------
// 3. PER-BAR DELTA — multi-source with automatic fallback
// -----------------------------------------------------------------------------
// Priority: 1 taker_volume buy/sell, 2 orderbook midpoint heuristic,
// 3 Lee-Ready tick test (close vs open)
timeseries mid = (h + l) / 2.0
var tickUp = c > c[1]
timeseries buyVol
timeseries sellVol
if (hasTaker) {
// Direct taker volume (most accurate)
buyVol = taker.buy
sellVol = taker.sell
} else if (hasOrderbook) {
// Orderbook midpoint heuristic: close vs midpoint with tick-test refinement
buyVol = ((c >= mid) || (tickUp && (c - l) > (h - c))) ? v : 0.0
sellVol = ((c < mid) || (!tickUp && (c - l) <= (h - c))) ? v : 0.0
} else {
// Lee-Ready (1991) tick test: close > open → buyer-initiated
buyVol = (c > o) ? v : 0.0
sellVol = (c <= o) ? v : 0.0
}
timeseries delta = buyVol - sellVol
// -----------------------------------------------------------------------------
// 4. CVD — rolling-window and true cumulative via static
// -----------------------------------------------------------------------------
// Rolling-window CVD (stationary, mean-reverting)
timeseries cvdRoll = sum(delta, zLen)
// True cumulative CVD via static state
static cvdCum = 0.0
if (!isnan(delta[0])) {
cvdCum = cvdCum + delta[0]
}
// Smoothed CVD
timeseries cvdSmooth = ema(cvdRoll, smoothLen)
// -----------------------------------------------------------------------------
// 5. Z-SCORE & WHALE DETECTION
// -----------------------------------------------------------------------------
timeseries avgVol = rma(v, zLen)
timeseries cvdMean = sma(cvdSmooth, zLen)
timeseries cvdStd = stdev(cvdSmooth, zLen)
timeseries cvdZ = (cvdStd > 0) ? (cvdSmooth - cvdMean) / cvdStd : 0
// Volume ratio for whale sizing
timeseries volRatio = (avgVol > 0) ? v / avgVol : 0
// Whale events: |z| > threshold AND volume elevated
var whaleUp = (cvdZ > threshold) && (volRatio > minVolMult)
var whaleDn = (cvdZ < -threshold) && (volRatio > minVolMult)
var extremeWhaleUp = (cvdZ > extremeThreshold) && (volRatio > minVolMult)
var extremeWhaleDn = (cvdZ < -extremeThreshold) && (volRatio > minVolMult)
// Regime detection
var regimeBull = cvdZ > 0 && cvdSmooth > cvdMean
var regimeBear = cvdZ < 0 && cvdSmooth < cvdMean
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastWhaleUp = false
static lastWhaleDn = false
static whaleUpBars = 0
static whaleDnBars = 0
static prevPxHigh = -1.0
static prevCvdHigh = -1.0
static prevPxLow = -1.0
static prevCvdLow = -1.0
if (whaleUp) {
whaleUpBars = whaleUpBars + 1
whaleDnBars = 0
} else if (whaleDn) {
whaleUpBars = 0
whaleDnBars = whaleDnBars + 1
} else {
whaleUpBars = 0
whaleDnBars = 0
}
lastWhaleUp = whaleUp
lastWhaleDn = whaleDn
// -----------------------------------------------------------------------------
// 7. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, CVD disagrees.
// We track pivot high/low state across bars using static variables.
var bearDiv = false
var bullDiv = false
// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
prevPxHigh = h[0]
prevCvdHigh = cvdSmooth[0]
prevPxLow = l[0]
prevCvdLow = cvdSmooth[0]
}
if (!isLiveUpdate && enableDiv) {
// --- Regular Bearish Divergence ---
// Price makes a higher high; CVD makes a lower high
if (h[0] > prevPxHigh) {
if (cvdSmooth[0] < prevCvdHigh) {
bearDiv = true
}
prevPxHigh = h[0]
prevCvdHigh = cvdSmooth[0]
}
// --- Regular Bullish Divergence ---
// Price makes a lower low; CVD makes a higher low
if (l[0] < prevPxLow) {
if (cvdSmooth[0] > prevCvdLow) {
bullDiv = true
}
prevPxLow = l[0]
prevCvdLow = cvdSmooth[0]
}
}
// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var whaleUpFirst = whaleUp && !lastWhaleUp
var whaleDnFirst = whaleDn && !lastWhaleDn
var zCrossUp = cvdZ > 0 && cvdZ[1] <= 0
var zCrossDn = cvdZ < 0 && cvdZ[1] >= 0
// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------
timeseries zeroLine = 0
// --- CVD Line (regime-colored) ---
if (showCVD) {
plotLine(
value=cvdSmooth,
width=2,
colors=[regimeColor],
label=["CVD Smooth"],
desc=["Smoothed rolling-window CVD (regime-colored)"]
)
}
// --- CVD Fill (vs zero line) ---
if (showFill) {
var cvdBull = cvdSmooth > 0
plotLine(
value=[cvdSmooth, zeroLine],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=cvdBull ? 0 : 1,
fill=true,
label=["CVD", "Zero"],
desc=["Fill between CVD and zero line"]
)
}
// --- Z-Score Line ---
if (showZ) {
plotLine(
value=cvdZ,
width=1,
colors=[zColor],
label=["CVD Z-Score"],
desc=["Z-score of smoothed CVD over " + zLen + " bars"]
)
}
// --- Whale Bubble Markers ---
if (showWhale) {
if (extremeWhaleUp) {
plotShape(
value=cvdZ,
shape="circle",
colorIndex=whaleBullColor,
width=3,
label=["Extreme Whale Buy"],
desc=["Extreme whale accumulation: z > " + extremeThreshold + " with elevated volume"]
)
} else if (whaleUp) {
plotShape(
value=cvdZ,
shape="circle",
colorIndex=whaleBullColor,
width=2,
label=["Whale Buy"],
desc=["Whale accumulation: z > " + threshold + " with elevated volume"]
)
}
if (extremeWhaleDn) {
plotShape(
value=cvdZ,
shape="circle",
colorIndex=whaleBearColor,
width=3,
label=["Extreme Whale Sell"],
desc=["Extreme whale distribution: z < -" + extremeThreshold + " with elevated volume"]
)
} else if (whaleDn) {
plotShape(
value=cvdZ,
shape="circle",
colorIndex=whaleBearColor,
width=2,
label=["Whale Sell"],
desc=["Whale distribution: z < -" + threshold + " with elevated volume"]
)
}
}
// --- Divergence Shapes ---
if (showDivergenceShapes && enableDiv) {
if (bullDiv) {
plotShape(
value=cvdSmooth,
shape="triangleup",
colorIndex=divBullColor,
width=2,
label=["Bull Div"],
desc=["Bullish divergence: price lower low, CVD higher low"]
)
}
if (bearDiv) {
plotShape(
value=cvdSmooth,
shape="triangledown",
colorIndex=divBearColor,
width=2,
label=["Bear Div"],
desc=["Bearish divergence: price higher high, CVD lower high"]
)
}
}
// --- Momentum Histogram (CVD z-score) ---
if (showHistogram) {
var histBull = cvdZ > 0
plotBar(
value=cvdZ,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["CVD Momentum"],
desc=["Z-score histogram: deviation from mean"]
)
}
// --- Reference Lines ---
hline(value=0, color="#ffffff30", width=1)
hline(value=threshold, color=transparency(bullColor, 50), width=1)
hline(value=-threshold, color=transparency(bearColor, 50), width=1)
hline(value=extremeThreshold, color=transparency(bullColor, 30), width=1)
hline(value=-extremeThreshold, color=transparency(bearColor, 30), width=1)
// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
plotTable(
data=[
["CVD Whale — Perfected", regimeText],
["CVD Smooth", cvdSmooth[0]],
["CVD Z-Score", cvdZ[0]],
["Vol Ratio", volRatio[0]],
["Whale Up Bars", whaleUpBars],
["Whale Dn Bars", whaleDnBars],
["Threshold", threshold],
["Extreme", extremeThreshold]
],
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
)
}