MM Flow
FlowScripts

Perfected FlowScript

Volume Delta Divergence [Alien_Algorithms]

Volume Delta Divergence [Alien_Algorithms] — Perfected Edition is indexed as 218_volume_delta_divergence_alien_algorithms.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

onchart

Axis

false

Size

17.3 KB

Lines

514

Native Signal Candidates

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

6/6 guarded

Bull Div Conf

line 419:9

Trigger

(showShapes) && (bullDivConfirmed)

Value

bars.low

Deps

bullDivConfirmed:var, showShapes:input

Bull Div

line 428:9

Trigger

(showShapes) && (bullDiv)

Value

bars.low

Deps

bullDiv:var, showShapes:input

Bear Div Conf

line 438:9

Trigger

(showShapes) && (bearDivConfirmed)

Value

bars.high

Deps

bearDivConfirmed:var, showShapes:input

Bear Div

line 447:9

Trigger

(showShapes) && (bearDiv)

Value

bars.high

Deps

bearDiv:var, showShapes:input

Bull Div Exhaust

line 457:9

Trigger

(showShapes) && (bullDivExhaustion)

Value

bars.low

Deps

bullDivExhaustion:var, showShapes:input

Bear Div Exhaust

line 467:9

Trigger

(showShapes) && (bearDivExhaustion)

Value

bars.high

Deps

bearDivExhaustion:var, showShapes:input

218_volume_delta_divergence_alien_algorithms.flowscript

source path: kscripts/perfected/218_volume_delta_divergence_alien_algorithms.flowscript · sha256:b54f8c9dcbb78ac50caf5a2028995d3762bca813e89fd9539aa12c404883aa7f

hash verified
//@version=2
// ============================================================================
// Volume Delta Divergence [Alien_Algorithms] — Perfected Edition
// Author: Alien_Algorithms | Enhanced by kScript Perfection Engineer
// Tags: ONCHART, #volume-delta, #divergence, #price-volume, #reversal, #order-flow
//
// Production-grade price-volume delta divergence overlay detecting bullish and
// bearish divergences where price reaches a new extreme but volume delta
// (buy-initiated minus sell-initiated) fails to confirm, signalling latent
// order-flow exhaustion and potential reversal. Implements Lee-Ready tick
// classification, rolling-window pivot detection, static divergence state
// tracking, and multi-threshold signal scoring with shape markers.
//
// Research papers underpinning this design:
//  1. 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 volume-delta divergence design.
//     DOI: 10.1016/S0304-405X(02)00136-8
//  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 linearly predicts short-term price changes. Volume delta is the
//     trade-level proxy for OFI when order-book data is unavailable.
//     DOI: 10.1093/jjfinec/nbt003
//  3. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. The canonical tick-test algorithm:
//     classify as buyer-initiated if close > open (or close > previous close),
//     else seller-initiated. 85–93% accuracy in liquid markets.
//     DOI: 10.1111/j.1540-6261.1991.tb02683.x
//  4. 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 divergence signal. DOI: 10.2307/1913210
//  5. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
//     as a leading reversal signal — price/indicator disagreement at extremes
//     precedes regime shifts. Applies directly to price-volume delta divergence.
//  6. Dacorogna et al. (2001), "An Introduction to High-Frequency Finance":
//     volume-based indicators predict reversals at daily horizons when volume
//     fails to confirm price moves. DOI: 10.1007/978-3-662-04396-3
// ============================================================================

define(
    title="Volume Delta Divergence [Alien_Algorithms] — Perfected Edition",
    position="onchart",
    axis=false
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Divergence Detection ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Pivot Lookback (bars)",
    constraints={min: 5, max: 100, step: 1},
    group="Divergence Detection"
)
var confirmBars = input(
    name="confirmBars",
    type="number",
    defaultValue=2,
    label="Confirmation Bars (min overlap)",
    constraints={min: 1, max: 10, step: 1},
    group="Divergence Detection"
)

// --- Volume Delta ---
var deltaMaLen = input(
    name="deltaMaLen",
    type="number",
    defaultValue=14,
    label="Delta MA Length",
    constraints={min: 5, max: 50, step: 1},
    group="Volume Delta"
)
var deltaSmooth = input(
    name="deltaSmooth",
    type="number",
    defaultValue=3,
    label="Delta EMA Smooth",
    constraints={min: 1, max: 20, step: 1},
    group="Volume Delta"
)

// --- Signal Strength ---
var strengthMult = input(
    name="strengthMult",
    type="number",
    defaultValue=1.5,
    label="Signal Strength Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Signal Strength"
)
var minDeltaDev = input(
    name="minDeltaDev",
    type="number",
    defaultValue=0.5,
    label="Min Delta Deviation (× stddev)",
    constraints={min: 0.1, max: 3.0, step: 0.1},
    group="Signal Strength"
)

// --- Display ---
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Volume Delta",
    group="Display"
)
var showDeltaMA = input(
    name="showDeltaMA",
    type="boolean",
    defaultValue=true,
    label="Show Delta MA",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Delta Histogram",
    group="Display"
)
var showDivergence = input(
    name="showDivergence",
    type="boolean",
    defaultValue=true,
    label="Show Divergence Markers",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Divergence Shapes",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Stats Table",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral 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"
)
var strongColor = input(
    name="strongColor",
    type="color",
    defaultValue="#ffd54f",
    label="Strong Signal Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)

if (isnan(bars.close[0]) || isnan(bars.high[0]) || isnan(bars.low[0]) || isnan(bars.volume[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. VOLUME DELTA COMPUTATION (Lee-Ready tick classification)
// -----------------------------------------------------------------------------
// Lee-Ready (1991) tick test: close > open → buyer-initiated volume;
// close <= open → seller-initiated volume. We use close vs open for
// per-bar classification (more accurate than close vs close[1] for
// multi-timeframe analysis).

timeseries upBar = bars.close > bars.open
timeseries buyVol = upBar ? bars.volume : 0
timeseries sellVol = upBar ? 0 : bars.volume
timeseries deltaRaw = buyVol - sellVol

// Signed delta: positive = more buying pressure, negative = more selling pressure
// When using close vs open, the sign is always consistent with the bar direction.
// For a more nuanced approach, we also weight by price change magnitude:
timeseries priceChg = bars.close - bars.open
timeseries priceChgPct = bars.close > 0 ? priceChg / bars.close : 0
timeseries deltaWeighted = deltaRaw * (1 + math.abs(priceChgPct))

// Smoothed delta
timeseries delta = ema(source=deltaWeighted, period=deltaSmooth)
timeseries deltaMA = ema(source=delta, period=deltaMaLen)

// Delta deviation from its moving average (signal strength)
timeseries deltaDev = delta - deltaMA
timeseries deltaStd = stddev(source=deltaDev, period=lookback)

// -----------------------------------------------------------------------------
// 4. PIVOT DETECTION FOR DIVERGENCE
// -----------------------------------------------------------------------------
// We detect local price highs/lows and delta highs/lows using rolling windows.
// A divergence occurs when price makes a new extreme but delta does not.

// -- 4.1 Price extremes --
timeseries priceHi = highest(source=bars.high, period=lookback)
timeseries priceLo = lowest(source=bars.low, period=lookback)

// Previous-window extremes (for comparing across non-overlapping windows)
// We use a lagged lookback to get the prior window's high/low
timeseries prevPriceHi = highest(source=bars.high[lookback], period=lookback)
timeseries prevPriceLo = lowest(source=bars.low[lookback], period=lookback)

// -- 4.2 Delta extremes --
timeseries deltaHi = highest(source=delta, period=lookback)
timeseries deltaLo = lowest(source=delta, period=lookback)

timeseries prevDeltaHi = highest(source=delta[lookback], period=lookback)
timeseries prevDeltaLo = lowest(source=delta[lookback], period=lookback)

// -- 4.3 Divergence detection (guarded) --
// Bullish divergence: price makes new low, but delta makes higher low
// Bearish divergence: price makes new high, but delta makes lower high

var bullDivRaw = false
var bearDivRaw = false

// Bearish divergence: new price high + delta not making new high (weaker buying)
if (bars.high[0] >= priceHi[0] && delta[0] < prevDeltaHi[0]) {
    bearDivRaw = true
}

// Bullish divergence: new price low + delta not making new low (weaker selling)
if (bars.low[0] <= priceLo[0] && delta[0] > prevDeltaLo[0]) {
    bullDivRaw = true
}

// -- 4.4 Signal strength filtering --
// Only flag divergence if delta deviation is statistically significant
var divStrong = math.abs(deltaDev) > deltaStd * minDeltaDev
var bullDiv = bullDivRaw && divStrong
var bearDiv = bearDivRaw && divStrong

// -----------------------------------------------------------------------------
// 5. STATIC DIVERGENCE STATE TRACKING
// -----------------------------------------------------------------------------
// Track consecutive divergence bars, last divergence bar, and cumulative counts
// for context-aware alerting and table display.

static bullDivBars = 0
static bearDivBars = 0
static lastBullDivBar = 0
static lastBearDivBar = 0
static totalBullDiv = 0
static totalBearDiv = 0
static maxBullScore = 0.0
static maxBearScore = 0.0
static prevPriceAtBullDiv = 0.0
static prevPriceAtBearDiv = 0.0
static prevDeltaAtBullDiv = 0.0
static prevDeltaAtBearDiv = 0.0

if (!isLiveUpdate) {
    if (bullDiv) {
        bullDivBars = bullDivBars + 1
        bearDivBars = 0
        lastBullDivBar = barCount
        totalBullDiv = totalBullDiv + 1
        prevPriceAtBullDiv = bars.low[0]
        prevDeltaAtBullDiv = delta[0]
        // Score = price decline % × delta improvement ratio
        var bullScore = math.abs(priceChgPct) * (delta[0] / prevDeltaLo[0])
        if (bullScore > maxBullScore) {
            maxBullScore = bullScore
        }
    } else if (bearDiv) {
        bearDivBars = bearDivBars + 1
        bullDivBars = 0
        lastBearDivBar = barCount
        totalBearDiv = totalBearDiv + 1
        prevPriceAtBearDiv = bars.high[0]
        prevDeltaAtBearDiv = delta[0]
        // Score = price rise % × delta deterioration ratio
        var bearScore = math.abs(priceChgPct) * (prevDeltaHi[0] / delta[0])
        if (bearScore > maxBearScore) {
            maxBearScore = bearScore
        }
    } else {
        bullDivBars = 0
        bearDivBars = 0
    }
}

// -- 5.1 Divergence confirmation (multiple bars) --
var bullDivConfirmed = bullDivBars >= confirmBars
var bearDivConfirmed = bearDivBars >= confirmBars

// -- 5.2 Divergence exhaustion (price reversing after divergence) --
var bullDivExhaustion = bullDivBars[1] > 0 && bars.close > bars.open && bars.close > bars.close[1]
var bearDivExhaustion = bearDivBars[1] > 0 && bars.close < bars.open && bars.close < bars.close[1]

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION (delta pressure regime)
// -----------------------------------------------------------------------------
// Regime classification based on delta vs its MA:
//   Bullish pressure: delta > MA and delta > 0
//   Bearish pressure: delta < MA and delta < 0
//   Neutral: everything else

var deltaBull = delta > deltaMA && delta > 0
var deltaBear = delta < deltaMA && delta < 0
var deltaNeutral = !deltaBull && !deltaBear

var deltaRegimeColor = deltaBull ? bullColor : (deltaBear ? bearColor : neutralColor)

// -----------------------------------------------------------------------------
// 7. PLOTTING
// -----------------------------------------------------------------------------

// -- 7.1 Zero reference line --
hline(value=0, color="#ffffff20", width=1)

// -- 7.2 Volume Delta (raw or smoothed) --
if (showDelta) {
    var deltaColorIdx = delta > 0 ? 0 : 1
    plotLine(
        value=delta,
        width=2,
        colors=[bullColor, bearColor],
        colorIndex=deltaColorIdx,
        label=["Volume Delta"],
        desc=["Signed volume delta (buy − sell) via Lee-Ready tick classification"]
    )
}

// -- 7.3 Delta MA --
if (showDeltaMA) {
    plotLine(
        value=deltaMA,
        width=1,
        colors=[neutralColor],
        label=["Delta MA"],
        desc=["EMA of volume delta (" + deltaMaLen + ")"]
    )
}

// -- 7.4 Delta histogram (regime-coded fill between delta and MA) --
if (showHistogram) {
    var histBull = delta > deltaMA
    plotLine(
        value=[delta, deltaMA],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=histBull ? 0 : 1,
        fill=true,
        label=["Delta", "Delta MA"],
        desc=["Fill between delta and its MA; green = bullish pressure, red = bearish pressure"]
    )
}

// -- 7.5 Divergence markers on price (offset above/below) --
if (showDivergence) {
    if (bullDiv) {
        plotLine(
            value=bars.low * 0.998,
            width=2,
            colors=[divBullColor],
            label=["Bull Divergence"],
            desc=["Bullish divergence: price lower low, delta higher low"]
        )
    }
    if (bearDiv) {
        plotLine(
            value=bars.high * 1.002,
            width=2,
            colors=[divBearColor],
            label=["Bear Divergence"],
            desc=["Bearish divergence: price higher high, delta lower high"]
        )
    }
}

// -- 7.6 Divergence shape markers --
if (showShapes) {
    if (bullDivConfirmed) {
        plotShape(
            value=bars.low,
            shape="triangleup",
            colorIndex=divBullColor,
            width=2,
            label=["Bull Div Conf"],
            desc=["Confirmed bullish divergence: " + bullDivBars + " consecutive bars"]
        )
    } else if (bullDiv) {
        plotShape(
            value=bars.low,
            shape="circle",
            colorIndex=divBullColor,
            width=1,
            label=["Bull Div"],
            desc=["Bullish divergence forming"]
        )
    }
    if (bearDivConfirmed) {
        plotShape(
            value=bars.high,
            shape="triangledown",
            colorIndex=divBearColor,
            width=2,
            label=["Bear Div Conf"],
            desc=["Confirmed bearish divergence: " + bearDivBars + " consecutive bars"]
        )
    } else if (bearDiv) {
        plotShape(
            value=bars.high,
            shape="circle",
            colorIndex=divBearColor,
            width=1,
            label=["Bear Div"],
            desc=["Bearish divergence forming"]
        )
    }
    if (bullDivExhaustion) {
        plotShape(
            value=bars.low,
            shape="arrowup",
            colorIndex=strongColor,
            width=2,
            label=["Bull Div Exhaust"],
            desc=["Bullish divergence exhaustion: price reversing up"]
        )
    }
    if (bearDivExhaustion) {
        plotShape(
            value=bars.high,
            shape="arrowdown",
            colorIndex=strongColor,
            width=2,
            label=["Bear Div Exhaust"],
            desc=["Bearish divergence exhaustion: price reversing down"]
        )
    }
}

// -----------------------------------------------------------------------------
// 8. STATS TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
    var divStatus = bullDivConfirmed ? "BULL DIV CONFIRMED" : (
        bearDivConfirmed ? "BEAR DIV CONFIRMED" : (bullDiv ? "Bull Div Forming" : (bearDiv ? "Bear Div Forming" : "No Divergence"))
    )
    var divStatusColor = bullDivConfirmed || bullDiv ? divBullColor : (
        bearDivConfirmed || bearDiv ? divBearColor : neutralColor
    )

    plotTable(
        data=[
            ["Vol Delta Divergence", divStatus],
            ["Delta", math.round(delta[0], 0)],
            ["Delta MA", math.round(deltaMA[0], 0)],
            ["Delta Dev", math.round(deltaDev[0], 0)],
            ["Price Chg %", math.round(priceChgPct[0] * 100, 2)],
            ["Bull Div Count", totalBullDiv],
            ["Bear Div Count", totalBearDiv],
            ["Max Bull Score", math.round(maxBullScore, 2)],
            ["Max Bear Score", math.round(maxBearScore, 2)]
        ],
        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
    )
}