MM Flow
FlowScripts

Perfected FlowScript

CVD Flow Dominance

CVD Flow Dominance V2 is indexed as 002_cvd_flow_dominance.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

13.0 KB

Lines

257

Native Signal Candidates

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

2/2 guarded

Extreme Bull Div

line 220:5

Trigger

(showShapes && extremeBull)

Value

extremeDiv

Deps

extremeBull:var, showShapes:input

Extreme Bear Div

line 230:5

Trigger

(showShapes && extremeBear)

Value

-extremeDiv

Deps

extremeBear:var, showShapes:input

002_cvd_flow_dominance.flowscript

source path: kscripts/perfected/pilot/002_cvd_flow_dominance.flowscript · sha256:e35615e8bad19ffcb723220162ae434e6c43b032766a77515eb87bef27c01ca0

hash verified
//@version=2

// ============================================================================
// CVD Flow Dominance V2 — Spot vs. Perpetual Futures Flow Divergence
// Author: kiyotaka (@kiyotaka) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #perps, #spots, #cvd
//
// This indicator computes Cumulative Volume Delta (CVD) independently for
// spot and perpetual futures venues, standardizes each via rolling-window
// z-score, and surfaces regime divergence as color-coded histograms, filled
// areas, and extreme shape alerts. When spot and perp flow fight each
// other, the divergence channel spikes — often flagging tops, bottoms, or
// squeeze zones where one side gets trapped.
//
// Academic foundation (exact papers & formulas):
//  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:
//     Δp_t = λ·OFI_t + ε_t, where λ is inversely proportional to depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. He & Manela (2022), "Fundamentals of Perpetual Futures".
//     No-arbitrage perp pricing; past-return momentum explains the
//     futures-spot gap with R² > 50%. Supports joint spot+perp divergence
//     interpretation: the gap is driven by funding-cost momentum.
//
//  3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates the divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  4. Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market
//     Microstructure". CME leads price discovery; trade-size divergence
//     between spot and futures supports dual-venue flow analysis.
//
//  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. 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 Flow Dominance V2", 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")

// -- 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 smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Divergence EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Regime Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Divergence Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")

// -- Display --
var showSpotZ    = input(name="showSpotZ",    type="boolean", defaultValue=true,  label="Show Spot CVD Z", group="Display")
var showPerpZ    = input(name="showPerpZ",    type="boolean", defaultValue=true,  label="Show Perp CVD Z", group="Display")
var showCombined = input(name="showCombined", type="boolean", defaultValue=true,  label="Show Combined Flow", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true,  label="Show Divergence Histogram", group="Display")
var showShapes   = input(name="showShapes",   type="boolean", defaultValue=true,  label="Show Extreme Divergence Shapes", group="Display")
var showRawCVD   = input(name="showRawCVD",   type="boolean", defaultValue=false, label="Show Raw CVD Lines", group="Display")
var showPerpOI   = input(name="showPerpOI",   type="boolean", defaultValue=false, label="Show Perp Open Interest", group="Display")

// -- Colors --
var spotColor    = input(name="spotColor",    type="color", defaultValue="#2962ff", label="Spot CVD Color", group="Colors")
var perpColor    = input(name="perpColor",    type="color", defaultValue="#ff6d00", label="Perp CVD Color", group="Colors")
var bullDivColor = input(name="bullDivColor", type="color", defaultValue="#00c853", label="Bullish Divergence Color", group="Colors")
var bearDivColor = input(name="bearDivColor", type="color", defaultValue="#d50000", label="Bearish Divergence Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var combinedColor = input(name="combinedColor", type="color", defaultValue="#ffffff", label="Combined Flow 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)
timeseries perpOI = open_interest(symbol=perpSymbol, exchange=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.
timeseries spotBuy = isnum(spotTaker.buy) ? spotTaker.buy : (spotBars.close > spotBars.open ? spotBars.volume : 0)
timeseries spotSell = isnum(spotTaker.sell) ? spotTaker.sell : (spotBars.close <= spotBars.open ? spotBars.volume : 0)
timeseries spotDelta = spotBuy - spotSell

timeseries perpBuy = isnum(perpTaker.buy) ? perpTaker.buy : (perpBars.close > perpBars.open ? perpBars.volume : 0)
timeseries perpSell = isnum(perpTaker.sell) ? perpTaker.sell : (perpBars.close <= perpBars.open ? perpBars.volume : 0)
timeseries perpDelta = perpBuy - perpSell

// -- 3.2 Rolling-window CVD (stationary approximation of cumulative flow) --
// CVD_t = Σ_{i=0}^{W-1} Δ_{t-i} ; we keep a rolling window so the series remains
// mean-reverting and amenable to z-score standardisation.
timeseries spotCVD = sum(spotDelta, zWindow)
timeseries perpCVD = sum(perpDelta, zWindow)

// -- 3.3 True cumulative CVD via static state (tracked for optional raw display) --
// static persists across bars; we guard each increment against NaN.
static spotCVD_cum = 0.0
static perpCVD_cum = 0.0

if (!isnan(spotDelta[0])) {
    spotCVD_cum = spotCVD_cum + spotDelta[0]
}
if (!isnan(perpDelta[0])) {
    perpCVD_cum = perpCVD_cum + perpDelta[0]
}

// -- 3.4 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (CVD_t − μ_t) / σ_t, where μ_t = SMA(CVD, W), σ_t = StDev(CVD, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
timeseries spotMean = sma(spotCVD, zWindow)
timeseries spotStd  = stdev(spotCVD, zWindow)
timeseries spotZ = (spotStd > 0) ? (spotCVD - spotMean) / spotStd : 0

timeseries perpMean = sma(perpCVD, zWindow)
timeseries perpStd  = stdev(perpCVD, zWindow)
timeseries perpZ = (perpStd > 0) ? (perpCVD - perpMean) / perpStd : 0

// -- 3.5 Combined & Divergence --
// Combined = aligned flow average (momentum when both venues agree).
// Divergence = spot Z − perp Z; positive → spot leading; negative → perp leading.
timeseries combined = ema((spotZ + perpZ) / 2, smoothLen)
timeseries divergence = ema(spotZ - perpZ, smoothLen)

// -- 3.6 Regime detection (configurable thresholds, no magic numbers) --
var bullishDiv = divergence > divThreshold
var bearishDiv = divergence < -divThreshold
var extremeBull = divergence > extremeDiv
var extremeBear = divergence < -extremeDiv
var neutralRegime = !bullishDiv && !bearishDiv

// -- 3.7 Divergence state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static divBullBars = 0
static divBearBars = 0

if (bullishDiv) {
    divBullBars = divBullBars + 1
    divBearBars = 0
    lastRegime = 1
} else if (bearishDiv) {
    divBearBars = divBearBars + 1
    divBullBars = 0
    lastRegime = -1
} else {
    divBullBars = 0
    divBearBars = 0
    lastRegime = 0
}

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

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

// 4.1 Spot & Perp CVD Z-scores (plotLine)
if (showSpotZ) {
    plotLine(value=spotZ, width=2, colors=[spotColor], label=["Spot CVD Z"], desc=["Standardised spot CVD; mean-reverting around 0"])
}
if (showPerpZ) {
    plotLine(value=perpZ, width=2, colors=[perpColor], label=["Perp CVD Z"], desc=["Standardised perp CVD; mean-reverting around 0"])
}

// 4.2 Combined flow with fill area (plotLine + fill)
if (showCombined) {
    plotLine(value=([combined, zeroLine]), width=2, colors=[combinedColor], label=["Combined Flow"], desc=["Average of spot and perp z-scores; aligned flow = momentum"], fill=true)
}

// 4.3 Divergence histogram (plotLine with colorIndex regime coding + fill)
// colorIndex maps: 0 = bullish, 1 = bearish, 2 = neutral
timeseries divColorIdx = bullishDiv ? 0 : (bearishDiv ? 1 : 2)
if (showDivergence) {
    plotLine(
        value=([divergence, zeroLine]),
        width=2,
        colors=[bullDivColor, bearDivColor, neutralColor],
        colorIndex=divColorIdx,
        label=["Divergence"],
        desc=["Spot minus perp z-score; filled histogram colour-coded by regime"],
        fill=true
    )
}

// 4.4 Divergence bars (plotBar) — sign-based colouring
if (showDivergence) {
    plotBar(value=divergence, colors=[bullDivColor, bearDivColor], label=["Divergence Bars"], desc=["Spot minus perp z-score as bars"])
}

// 4.5 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=extremeDiv,
        shape="triangleup",
        colorIndex=bullDivColor,
        width=3,
        label=["Extreme Bull Div"],
        desc=["Spot CVD massively outpacing perp; potential short squeeze / perp trap"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=-extremeDiv,
        shape="triangledown",
        colorIndex=bearDivColor,
        width=3,
        label=["Extreme Bear Div"],
        desc=["Perp CVD massively outpacing spot; potential long squeeze / spot distribution"]
    )
}

// 4.6 Optional raw CVD lines (true cumulative from static state)
if (showRawCVD) {
    plotLine(value=spotCVD_cum, width=1, colors=[spotColor], label=["Spot CVD (Raw)"], desc=["True cumulative spot CVD from first bar"])
    plotLine(value=perpCVD_cum, width=1, colors=[perpColor], label=["Perp CVD (Raw)"], desc=["True cumulative perp CVD from first bar"])
}

// 4.7 Optional perp open interest (demonstrates open_interest API)
if (showPerpOI) {
    plotLine(value=perpOI.close, width=1, colors=["#9c27b0"], label=["Perp OI"], desc=["Perpetual futures open interest (context)"])
}

// 4.8 Reference thresholds (hline)
hline(value=0,                color="#ffffff30", width=1)
hline(value=divThreshold,     color="#ffffff20", width=1)
hline(value=-divThreshold,    color="#ffffff20", width=1)
hline(value=extremeDiv,       color="#ffffff15", width=1)
hline(value=-extremeDiv,      color="#ffffff15", width=1)