MM Flow
FlowScripts

Perfected FlowScript

SCF CVD BTC Spot

SCF CVD BTC Spot V2 is indexed as 072_scf_cvd_btc_spot.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

14.1 KB

Lines

342

Native Signal Candidates

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

4/4 guarded

Bull Div

line 295:9

Trigger

(showShapes) && (bullDiv)

Value

cvdSm

Deps

bullDiv:var, showShapes:input

Bear Div

line 305:9

Trigger

(showShapes) && (bearDiv)

Value

cvdSm

Deps

bearDiv:var, showShapes:input

Extreme Bull Div

line 315:9

Trigger

(showShapes) && (extremeBullDiv)

Value

cvdSm

Deps

extremeBullDiv:var, showShapes:input

Extreme Bear Div

line 325:9

Trigger

(showShapes) && (extremeBearDiv)

Value

cvdSm

Deps

extremeBearDiv:var, showShapes:input

072_scf_cvd_btc_spot.flowscript

source path: kscripts/perfected/072_scf_cvd_btc_spot.flowscript · sha256:7722e9479fee5da8681f73df579f3894fd8f9ba04a0e961c8d4b762aa562296c

hash verified
//@version=2

// ============================================================================
// SCF CVD BTC Spot V2 — Cumulative Volume Delta with Divergence Detection
// Author: SoulzBTC (@SoulzBTC) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, FLOW, #cvd, #btc, #spot, #divergence, #delta
//
// Computes cumulative volume delta (CVD) for BTC spot with Lee-Ready
// classification, taker-volume feed fallback, divergence detection vs. price,
// and color-coded regime visualization. The CVD line reveals institutional
// positioning; divergence between CVD and price flags potential reversals.
//
// Academic foundation (exact papers & formulas):
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.
//     [Formula] Tick test: classify as buy if close > open, else sell.
//     Accuracy: 85–93% on NYSE TORQ data. Foundational trade-direction
//     inference when taker-buy/sell feeds are unavailable.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  2. 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
//
//  3. 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.
//
//  4. 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
//
//  5. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow exhibits long-memory autocorrelation (power-law decay).
//     Justifies cumulative measures (CVD) over per-bar delta: sustained
//     pressure accumulates and drives trends.
//     https://arxiv.org/abs/cond-mat/0311053
//
//  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 underpinning
//     all delta-based trading signals.
//     DOI: https://doi.org/10.2307/1913210
//
//  7. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand", Handbook of Financial Markets, 57–160.
//     Square-root impact law: large delta events have sublinear price impact
//     due to liquidity memory. CVD divergence from price flags absorption
//     or exhaustion regimes.
// ============================================================================

define(title="SCF CVD BTC Spot V2", position="offchart", axis=true)

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

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=20, label="EMA Smoothing Length", constraints={min: 1, max: 100, step: 1}, group="Computation")
var extraSmooth = input(name="extraSmooth", type="number", defaultValue=50, label="Long EMA Smoothing Length", constraints={min: 5, max: 200, step: 5}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var divLookback = input(name="divLookback", type="number", defaultValue=14, label="Divergence Lookback (bars)", constraints={min: 5, max: 50, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Threshold (z)", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Computation")

// -- Display --
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showLong = input(name="showLong", type="boolean", defaultValue=true, label="Show Long EMA", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=false, label="Show CVD Z-Score", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Fills", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Divergence Shapes", group="Display")
var showCVDBar = input(name="showCVDBar", type="boolean", defaultValue=false, label="Show CVD Histogram", group="Display")

// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Rising CVD Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Falling CVD Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#ffffff", label="CVD Base Color", group="Colors")
var longColor = input(name="longColor", type="color", defaultValue="#ffeb3b", label="Long EMA 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 extremeBuyColor = input(name="extremeBuyColor", type="color", defaultValue="#00c853", label="Extreme Buy Color", group="Colors")
var extremeSellColor = input(name="extremeSellColor", type="color", defaultValue="#d50000", label="Extreme Sell Color", group="Colors")

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

timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
    return
}

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

// -- 3.1 Volume Delta — taker feed preferred, Lee-Ready fallback, BVC final fallback --
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// BVC (Easley et al. 2012): probabilistic split by bar position within range.

timeseries buyVol = 0.0
timeseries sellVol = 0.0

if (isnum(taker.buy) && isnum(taker.sell)) {
    // Direct taker feed available — highest accuracy
    buyVol = taker.buy
    sellVol = taker.sell
} else {
    // Fallback 1: Lee-Ready tick test (85–93% accuracy)
    // Fallback 2: BVC probabilistic split when doji / ambiguous
    timeseries range_ = h - l
    timeseries upW = math.max(c - o, 0.0)
    timeseries dnW = math.max(o - c, 0.0)
    buyVol = range_ > 0 ? v * (upW / range_) : v * 0.5
    sellVol = range_ > 0 ? v * (dnW / range_) : v * 0.5
}

timeseries delta = buyVol - sellVol

// -- 3.2 True cumulative CVD via static state (persistent across bars) --
// static persists across bars; we guard each increment against NaN.
// CVD_t = CVD_{t−1} + Δ_t. Long-memory property (Lillo & Farmer 2004)
// justifies cumulative over per-bar delta.

static cvd = 0.0
if (!isnan(delta[0])) {
    cvd = cvd + delta[0]
}

// -- 3.3 EMA smoothing (Cont et al. 2014 noise-reduction) --
timeseries cvdSm = ema(cvd, smoothLen)
timeseries cvdXL = ema(cvd, extraSmooth)

// -- 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 cvdMean = sma(cvd, zWindow)
timeseries cvdStd = stdev(cvd, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvd - cvdMean) / cvdStd : 0.0

// -- 3.5 Slope / regime detection (color coding by CVD slope) --
// Rising CVD = aggressive buying accumulating (upColor).
// Falling CVD = aggressive selling accumulating (dnColor).
// Cross detection for fill transitions.

var cvdRising = cvdSm >= cvdSm[1]
var cvdFalling = cvdSm < cvdSm[1]
var cvdCrossUp = cvdRising && !isnan(cvdSm[1]) && cvdSm[1] < cvdSm[2]
var cvdCrossDown = cvdFalling && !isnan(cvdSm[1]) && cvdSm[1] >= cvdSm[2]

// -- 3.6 Divergence Detection (Chordia et al. 2002) --
// Bullish divergence: price makes lower low, CVD makes higher low.
// Bearish divergence: price makes higher high, CVD makes lower high.
// We use a rolling-window comparison to detect divergence.

timeseries priceLL = lowest(c, divLookback)
timeseries priceHH = highest(c, divLookback)
timeseries cvdLL = lowest(cvdSm, divLookback)
timeseries cvdHH = highest(cvdSm, divLookback)

var bullDiv = c < c[1] && c == priceLL && cvdSm > cvdSm[1] && cvdSm == cvdLL
var bearDiv = c > c[1] && c == priceHH && cvdSm < cvdSm[1] && cvdSm == cvdHH
var extremeBullDiv = bullDiv && cvdZ > divThreshold
var extremeBearDiv = bearDiv && cvdZ < -divThreshold

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

// -- 3.8 Regime detection (configurable thresholds) --
var bullRegime = cvdZ > divThreshold
var bearRegime = cvdZ < -divThreshold
var neutralRegime = !bullRegime && !bearRegime

// -- 3.9 Static state tracking — session-level persistence --
// Tracks divergence counts, session extremes, and regime transitions for
// context-aware alerting.

static lastRegime = 0
static divBullCount = 0
static divBearCount = 0
static sessionHighCVD = -999999999.0
static sessionLowCVD = 999999999.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (cvd > sessionHighCVD) {
        sessionHighCVD = cvd
    }
    if (cvd < sessionLowCVD) {
        sessionLowCVD = cvd
    }

    if (bullDiv) {
        divBullCount = divBullCount + 1
    }
    if (bearDiv) {
        divBearCount = divBearCount + 1
    }

    if (bullRegime) {
        lastRegime = 1
    } else if (bearRegime) {
        lastRegime = -1
    } else {
        lastRegime = 0
    }
}

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

// 4.1 CVD line with slope-based color coding (plotLine + fill)
if (showCVD) {
    plotLine(
        value=([cvdSm, cvdSm[1]]),
        width=2,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=cvdRising ? 0 : 1,
        label=["CVD (smoothed)"],
        desc=["Spot CVD smoothed via EMA; color = slope (rising=accumulation, falling=distribution)"],
        fill=true
    )
}

// 4.2 Long EMA (plotLine)
if (showLong) {
    plotLine(
        value=cvdXL,
        width=2,
        colors=[longColor],
        label=["Long EMA"],
        desc=["Heavy smoothing for major cycle detection (Lillo & Farmer 2004 long-memory)"]
    )
}

// 4.3 CVD Z-Score (plotLine) — optional reference
if (showZScore) {
    plotLine(
        value=cvdZ,
        width=1,
        colors=[upColor, dnColor, neutralColor],
        colorIndex=cvdZ > 0 ? 0 : 1,
        label=["CVD Z-Score"],
        desc=["Rolling-window z-score of raw CVD; regime-coded by sign"]
    )
}

// 4.4 Divergence fill area between CVD and long EMA (plotLine + fill)
if (showDivergence) {
    plotLine(
        value=([cvdSm, cvdXL]),
        width=1,
        colors=[opacity(bullDivColor, 30), opacity(bearDivColor, 30)],
        colorIndex=cvdSm > cvdXL ? 0 : 1,
        label=["CVD Divergence Fill"],
        desc=["Fill between CVD and long EMA; widening gap = divergence building"],
        fill=true
    )
}

// 4.5 CVD histogram (plotBar) — optional bar-level view
if (showCVDBar) {
    plotBar(
        value=cvdSm,
        colors=[upColor, dnColor],
        width=1,
        label=["CVD Histogram"],
        desc=["Smoothed CVD as histogram; positive = buy-heavy, negative = sell-heavy"]
    )
}

// 4.6 Divergence shapes (plotShape) — triangles for divergence, diamonds for extreme
if (showShapes) {
    if (bullDiv) {
        plotShape(
            value=cvdSm,
            shape="triangleup",
            colorIndex=bullDivColor,
            width=3,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, CVD higher low (Chordia et al. 2002 reversal signal)"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=cvdSm,
            shape="triangledown",
            colorIndex=bearDivColor,
            width=3,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, CVD lower high (Chordia et al. 2002 reversal signal)"]
        )
    }
    if (extremeBullDiv) {
        plotShape(
            value=cvdSm,
            shape="diamond",
            colorIndex=extremeBuyColor,
            width=4,
            label=["Extreme Bull Div"],
            desc=["Extreme bullish divergence with high z-score; strong reversal probability"]
        )
    }
    if (extremeBearDiv) {
        plotShape(
            value=cvdSm,
            shape="diamond",
            colorIndex=extremeSellColor,
            width=4,
            label=["Extreme Bear Div"],
            desc=["Extreme bearish divergence with low z-score; strong reversal probability"]
        )
    }
}

// 4.7 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showZScore) {
    hline(value=divThreshold, color="#ffffff20", width=1)
    hline(value=-divThreshold, color="#ffffff20", width=1)
}