MM Flow
FlowScripts

Perfected FlowScript

Detrend CVD interactions

Detrend CVD Interactions — Perfected is indexed as 228_detrend_cvd_interactions.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.4 KB

Lines

426

Native Signal Candidates

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

2/2 guarded

Extreme Bull Z

line 364:5

Trigger

(showShapes && extremeBull)

Value

extremeZ

Deps

extremeBull:var, showShapes:input

Extreme Bear Z

line 374:5

Trigger

(showShapes && extremeBear)

Value

-extremeZ

Deps

extremeBear:var, showShapes:input

228_detrend_cvd_interactions.flowscript

source path: kscripts/perfected/228_detrend_cvd_interactions.flowscript · sha256:9b76d118c65f4e8716f17beb45a46ae9c6fe1738d417c266f072f67afb0d81d9

hash verified
//@version=2
// ============================================================================
// Detrend CVD Interactions — Perfected Edition
// Author: F (@Flavio Desescolarize) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #cvd, #detrend, #interactions, #zscore, #regime
//
// Detrends the Cumulative Volume Delta (CVD) series via a rolling trend
// baseline, then standardizes the residual via z-score and creates interaction
// signals with price momentum. Zero-line crossings mark regime changes; extreme
// z-score divergences flag behavioral shifts in aggressive order flow.
//
// Academic foundation:
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] CVD_t = Σ(buy_vol_t − sell_vol_t); linear price-impact model:
//     Δp_t = λ·CVD_t + ε_t. DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme |Imbalance| predicts return reversals; motivates detrending
//     and threshold-based regime design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  3. Lillo & Farmer (2004), "The Long Memory of the Efficient Market", SNDE
//     8(3), 1–35. Order flow exhibits long-memory (power-law autocorrelations);
//     cumulative measures require trend removal to remain stationary.
//
//  4. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ underpins the price-CVD interaction coefficient.
//     DOI: https://doi.org/10.2307/1913210
//
//  5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Tick-classification baseline
//     (85–93% accuracy) when taker-buy/sell data is unavailable.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
// ============================================================================

define(
    title="Detrend CVD Interactions — Perfected",
    position="offchart",
    axis=true
)

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

// -- CVD Computation --
var trendLen = input(
    name="trendLen",
    type="number",
    defaultValue=50,
    label="Trend Length (SMA)",
    constraints={min: 10, max: 200, step: 5},
    group="CVD Computation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="CVD Computation"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 20, max: 200, step: 5},
    group="CVD Computation"
)

// -- Interaction --
var usePriceMom = input(
    name="usePriceMom",
    type="boolean",
    defaultValue=true,
    label="Enable Price Momentum Interaction",
    group="Interaction"
)
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=10,
    label="Price Momentum Length",
    constraints={min: 2, max: 50, step: 1},
    group="Interaction"
)
var interactionWeight = input(
    name="interactionWeight",
    type="number",
    defaultValue=0.3,
    label="Interaction Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Interaction"
)

// -- Thresholds --
var posThreshold = input(
    name="posThreshold",
    type="number",
    defaultValue=0.0,
    label="Positive Threshold",
    constraints={min: -2.0, max: 2.0, step: 0.25},
    group="Thresholds"
)
var negThreshold = input(
    name="negThreshold",
    type="number",
    defaultValue=0.0,
    label="Negative Threshold",
    constraints={min: -2.0, max: 2.0, step: 0.25},
    group="Thresholds"
)
var extremeZ = input(
    name="extremeZ",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.25},
    group="Thresholds"
)

// -- Display --
var showTrend = input(
    name="showTrend",
    type="boolean",
    defaultValue=true,
    label="Show Trend Baseline",
    group="Display"
)
var showDetCVD = input(
    name="showDetCVD",
    type="boolean",
    defaultValue=true,
    label="Show Detrended CVD",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score",
    group="Display"
)
var showInteraction = input(
    name="showInteraction",
    type="boolean",
    defaultValue=true,
    label="Show Interaction Signal",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Shape Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Fill Areas",
    group="Display"
)

// -- Colors --
var posColor = input(
    name="posColor",
    type="color",
    defaultValue="#26a69a",
    label="Positive Color",
    group="Colors"
)
var negColor = input(
    name="negColor",
    type="color",
    defaultValue="#ef5350",
    label="Negative Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var trendColor = input(
    name="trendColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Trend Color",
    group="Colors"
)
var zColor = input(
    name="zColor",
    type="color",
    defaultValue="#42a5f5",
    label="Z-Score Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries buySell = buy_sell_volume(symbol=currentSymbol, exchange=currentExchange)

if (isnan(bars.close[0]) || isnan(buySell.buy_volume[0]) || isnan(buySell.sell_volume[0])) {
    return
}

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

// -- 3.1 Per-bar delta --
timeseries delta = buySell.buy_volume - buySell.sell_volume

// -- 3.2 Cumulative CVD via static state (guarded against NaN) --
static cvdState = 0.0
if (!isnan(delta[0])) {
    cvdState = cvdState + delta[0]
}
timeseries cvd = cvdState

// -- 3.3 Trend baseline (rolling SMA) and detrended CVD --
timeseries trend = sma(source=cvd, period=trendLen)
timeseries detCvd = cvd - trend

// -- 3.4 Smoothed detrended series --
timeseries smooth = sma(source=detCvd, period=smoothLen)

// -- 3.5 Z-score normalisation of detrended CVD (denominator guarded) --
timeseries detMean = sma(source=detCvd, period=zWindow)
timeseries detStd = stdev(source=detCvd, period=zWindow)
timeseries detZ = (detStd > 0) ? (detCvd - detMean) / detStd : 0

// -- 3.6 Price momentum interaction --
// Interaction = detrended CVD blended with price momentum direction.
// Positive interaction: aggressive buying coincides with upward price momentum.
timeseries priceMom = bars.close[0] - bars.close[momLen]
timeseries priceMomNorm = (detStd > 0) ? priceMom / detStd : 0
timeseries interaction = (usePriceMom)
    ? (1 - interactionWeight) * smooth + interactionWeight * priceMomNorm
    : smooth

// -- 3.7 Regime detection (multi-threshold) --
var regimeBull = smooth > posThreshold
var regimeBear = smooth < negThreshold
var regimeNeutral = !regimeBull && !regimeBear

var extremeBull = detZ > extremeZ
var extremeBear = detZ < -extremeZ

// -- 3.8 Divergence histogram (interaction minus zero) --
timeseries zeroLine = 0
timeseries hist = interaction - zeroLine

// -- 3.9 Static regime tracking (consecutive bars per regime) --
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
    neutralBars = 0
    lastRegime = 1
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
    neutralBars = 0
    lastRegime = -1
} else {
    neutralBars = neutralBars + 1
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 Trend baseline (plotLine)
if (showTrend) {
    plotLine(
        value=trend,
        colors=[trendColor],
        width=1,
        label=["Trend (SMA)"],
        desc=["Rolling CVD trend baseline; deviations from this = flow regime shifts"]
    )
}

// 4.2 Detrended CVD (plotLine with regime colorIndex)
if (showDetCVD) {
    timeseries detColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
    plotLine(
        value=([smooth, zeroLine]),
        width=2,
        colors=[posColor, negColor, neutralColor],
        colorIndex=detColorIdx,
        label=["Detrended CVD"],
        desc=["CVD minus rolling trend; zero-line = regime boundary; color = regime"],
        fill=showFill
    )
}

// 4.3 Z-score (plotLine)
if (showZScore) {
    plotLine(
        value=detZ,
        colors=[zColor],
        width=2,
        label=["Detrended Z-Score"],
        desc=["Z-score of detrended CVD; ±" + extremeZ + " = extreme regime"]
    )
}

// 4.4 Interaction signal (plotLine with fill)
if (showInteraction) {
    timeseries intColorIdx = interaction >= 0 ? 0 : 1
    plotLine(
        value=([interaction, zeroLine]),
        width=2,
        colors=[transparency(posColor, 40), transparency(negColor, 40)],
        colorIndex=intColorIdx,
        label=["Interaction Signal"],
        desc=["Detrended CVD blended with price momentum"],
        fill=showFill
    )
}

// 4.5 Histogram (plotBar with regime color)
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(posColor, 60), transparency(negColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["CVD Histogram"],
        desc=["Detrended CVD histogram; sign = direction, magnitude = intensity"]
    )
}

// 4.6 Extreme divergence shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=extremeZ,
        shape="triangleup",
        colorIndex=posColor,
        width=3,
        label=["Extreme Bull Z"],
        desc=["Detrended CVD z-score > +" + extremeZ + "; aggressive buying extreme"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=-extremeZ,
        shape="triangledown",
        colorIndex=negColor,
        width=3,
        label=["Extreme Bear Z"],
        desc=["Detrended CVD z-score < -" + extremeZ + "; aggressive selling extreme"]
    )
}

// 4.7 Zero line and threshold hlines
hline(value=0, color="#ffffff30", width=1)
if (posThreshold != 0) {
    hline(value=posThreshold, color=transparency(posColor, 60), width=1)
}
if (negThreshold != 0) {
    hline(value=negThreshold, color=transparency(negColor, 60), width=1)
}
if (showZScore) {
    hline(value=extremeZ, color=transparency(zColor, 40), width=1)
    hline(value=-extremeZ, color=transparency(zColor, 40), width=1)
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? posColor : (regimeBear ? negColor : neutralColor)

    plotTable(
        data=[
            ["Detrend CVD — Perfected", regimeText],
            ["Detrended CVD", smooth[0]],
            ["Z-Score", detZ[0]],
            ["Interaction", interaction[0]],
            ["Bull Bars", bullBars],
            ["Bear Bars", bearBars]
        ],
        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
    )
}