MM Flow
FlowScripts

Perfected FlowScript

ITC Delta Bar

ITC Delta Bar Pro is indexed as 095_itc_delta_bar.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

16.1 KB

Lines

529

Native Signal Candidates

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

8/8 guarded

Ultra Buy

line 406:9

Trigger

(showExtremeShapes) && (isUltraBuy)

Value

barDelta

Deps

isUltraBuy:var, showExtremeShapes:input

Ultra Sell

line 416:9

Trigger

(showExtremeShapes) && (isUltraSell)

Value

barDelta

Deps

isUltraSell:var, showExtremeShapes:input

Extreme Buy

line 428:9

Trigger

(showExtremeShapes) && (isExtremeBuy && !isUltraBuy)

Value

barDelta

Deps

isExtremeBuy:var, isUltraBuy:var, showExtremeShapes:input

Extreme Sell

line 438:9

Trigger

(showExtremeShapes) && (isExtremeSell && !isUltraSell)

Value

barDelta

Deps

isExtremeSell:var, isUltraSell:var, showExtremeShapes:input

Buy Flip

line 450:9

Trigger

(showExtremeShapes) && (regimeFlipBuy)

Value

barDelta

Deps

regimeFlipBuy:var, showExtremeShapes:input

Sell Flip

line 460:9

Trigger

(showExtremeShapes) && (regimeFlipSell)

Value

barDelta

Deps

regimeFlipSell:var, showExtremeShapes:input

Delta Bull Div

line 474:9

Trigger

(showDivergence) && (bullDiv)

Value

barDelta

Deps

bullDiv:var, showDivergence:input

Delta Bear Div

line 484:9

Trigger

(showDivergence) && (bearDiv)

Value

barDelta

Deps

bearDiv:var, showDivergence:input

095_itc_delta_bar.flowscript

source path: kscripts/perfected/095_itc_delta_bar.flowscript · sha256:b8f4bf76a24f75a8a67b08fdb900e58487852680c1c9309897531d166bf78424

hash verified
//@version=2

// ============================================================================
// ITC Delta Bar Pro — Institutional Order-Flow Delta with CVD & Extremes
// Author: P (@PatrikHaim) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, VOLUME, #delta, #cvd, #orderflow, #itc, #extremes
//
// Displays per-bar buy/sell delta, cumulative delta (CVD), rolling max/min
// extremes, and divergence detection. Color-codes aggressive buyer vs seller
// pressure with shape alerts at extreme deltas, regime tracking, and ITC-style
// visual delta bars. Ideal for reading real-time order flow at key levels.
//
// Academic foundation (exact papers & formulas):
//  1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Tick-test: close > open → buy;
//     close < open → sell. 85–93% accuracy. Foundation for per-bar delta.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  2. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
//     Trading Activity". BVC probabilistic bucket classification. Volume
//     direction is more robust in aggregate than trade-by-trade. Validates
//     bar-level delta aggregation for crypto/HFT markets.
//     URL: https://ssrn.com/abstract=1989555
//
//  3. 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. Kyle's λ inversely proportional to depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  4. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's lambda establishes the linear price-impact coefficient that
//     underpins every delta-based trading signal.
//     DOI: https://doi.org/10.2307/1913210
//
//  5. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme |Imbalance| predicts return reversals. Directly motivates the
//     extreme-delta threshold design and divergence detection.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  6. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand". Square-root impact law; liquidity memory.
//     Absorption = volume fails to move price; exhaustion = volume spikes
//     but follow-through fades. Explains delta-bar behaviour at extremes.
//     URL: https://arxiv.org/abs/0809.0822
//
//  7. Huddleston (ICT) / SMC practitioner framework: delta extremes flag
//     institutional absorption or exhaustion. Smart money concepts treat
//     extreme delta as potential trap zones (inducement + liquidity sweep).
// ============================================================================

define(title="ITC Delta Bar Pro", position="offchart", axis=true)

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

// -- Computation --
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Extreme Lookback (bars)",
    constraints={min: 5, max: 100, step: 5},
    group="Computation"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="CVD EMA Smooth",
    constraints={min: 1, max: 30, step: 1},
    group="Computation"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=14,
    label="Divergence Lookback (bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Computation"
)

// -- Thresholds --
var extremeRatio = input(
    name="extremeRatio",
    type="number",
    defaultValue=0.8,
    label="Extreme Delta Ratio (0.5–1.0 of max/min)",
    constraints={min: 0.5, max: 1.0, step: 0.05},
    group="Thresholds"
)
var useVolNorm = input(
    name="useVolNorm",
    type="boolean",
    defaultValue=true,
    label="Volume-normalise delta (delta / volume)",
    group="Thresholds"
)

// -- Display --
var showVolume = input(
    name="showVolume",
    type="boolean",
    defaultValue=true,
    label="Show Volume Bars",
    group="Display"
)
var showDelta = input(
    name="showDelta",
    type="boolean",
    defaultValue=true,
    label="Show Per-Bar Delta",
    group="Display"
)
var showCumDelta = input(
    name="showCumDelta",
    type="boolean",
    defaultValue=true,
    label="Show Cumulative Delta (CVD)",
    group="Display"
)
var showExtremeShapes = input(
    name="showExtremeShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Delta Shapes",
    group="Display"
)
var showDivergence = input(
    name="showDivergence",
    type="boolean",
    defaultValue=true,
    label="Show Price-Delta Divergence",
    group="Display"
)
var showDeltaFill = input(
    name="showDeltaFill",
    type="boolean",
    defaultValue=true,
    label="Show Delta Fill (zero baseline)",
    group="Display"
)

// -- Colors --
var buyColor = input(
    name="buyColor",
    type="color",
    defaultValue="#00c853",
    label="Aggressive Buy Color",
    group="Colors"
)
var sellColor = input(
    name="sellColor",
    type="color",
    defaultValue="#d50000",
    label="Aggressive Sell Color",
    group="Colors"
)
var volColor = input(
    name="volColor",
    type="color",
    defaultValue="#2962ff",
    label="Volume Color",
    group="Colors"
)
var cvdColor = input(
    name="cvdColor",
    type="color",
    defaultValue="#ff9800",
    label="CVD Line Color",
    group="Colors"
)
var extremeBuyColor = input(
    name="extremeBuyColor",
    type="color",
    defaultValue="#00e676",
    label="Extreme Buy Shape Color",
    group="Colors"
)
var extremeSellColor = input(
    name="extremeSellColor",
    type="color",
    defaultValue="#ff5252",
    label="Extreme Sell Shape Color",
    group="Colors"
)

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries open = bars.open
timeseries vol = bars.volume

// Guard: halt until all OHLCV data have loaded
if (isnan(close[0]) || isnan(open[0]) || isnan(vol[0])) {
    return
}

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

// -- 3.1 Per-bar buy/sell classification (Lee-Ready 1991 tick test) --
// close > open → buyer-initiated (aggressive buying)
// close < open → seller-initiated (aggressive selling)
// BVC-style: entire bar volume assigned to the dominant side.

var isUpBar = close > open
var isDnBar = close < open
var buyVol = isUpBar ? vol : 0
var sellVol = isDnBar ? vol : 0
var barDelta = buyVol - sellVol

// -- 3.2 Volume-normalised delta (optional, for cross-asset comparability) --
var barDeltaNorm = useVolNorm && vol > 0 ? barDelta / vol : barDelta

// -- 3.3 Cumulative Delta (CVD) via static state --
// Static persists across bars; we guard each increment against NaN.
// Per Cont et al. (2014): cumulative OFI linearly predicts price changes.

static cumDelta = 0.0
if (!isnan(barDelta[0])) {
    cumDelta = cumDelta + barDelta[0]
}

var cumDeltaSm = ema(source=cumDelta, period=smoothLen)

// -- 3.4 Rolling max/min delta over lookback --
var maxDelta = highest(source=barDeltaNorm, period=lookback)
var minDelta = lowest(source=barDeltaNorm, period=lookback)

// -- 3.5 Extreme delta detection --
// Extreme = current delta within extremeRatio of the lookback max/min.
// Per Chordia et al. (2002): extreme imbalances predict reversals.
var isExtremeBuy = barDeltaNorm >= maxDelta * extremeRatio && maxDelta > 0
var isExtremeSell = barDeltaNorm <= minDelta * extremeRatio && minDelta < 0
var isUltraBuy = barDeltaNorm == maxDelta && maxDelta > 0
var isUltraSell = barDeltaNorm == minDelta && minDelta < 0

// -- 3.6 Regime detection (buyer pressure vs seller pressure) --
var buyerDominant = barDelta > 0
var sellerDominant = barDelta < 0
var neutralBar = barDelta == 0

// -- 3.7 Regime state tracking via static variables --
static prevDominant = 0
static buyStreak = 0
static sellStreak = 0
static neutralStreak = 0

var regimeFlipBuy = false
var regimeFlipSell = false

var currDominant = buyerDominant ? 1 : (sellerDominant ? -1 : 0)

if (buyerDominant) {
    buyStreak = buyStreak + 1
    sellStreak = 0
    neutralStreak = 0
    if (prevDominant == -1) {
        regimeFlipBuy = true
    }
} else if (sellerDominant) {
    sellStreak = sellStreak + 1
    buyStreak = 0
    neutralStreak = 0
    if (prevDominant == 1) {
        regimeFlipSell = true
    }
} else {
    neutralStreak = neutralStreak + 1
    buyStreak = 0
    sellStreak = 0
}
prevDominant = currDominant

// -- 3.8 Price-Delta divergence detection (stateful via static) --
// Regular divergence: price makes higher high / lower low, delta disagrees.

static prevPxHighDelta = -1.0
static prevDeltaHigh = -1.0
static prevPxLowDelta = -1.0
static prevDeltaLow = -1.0

var bearDiv = false
var bullDiv = false

if (prevPxHighDelta < 0) {
    prevPxHighDelta = bars.high[0]
    prevDeltaHigh = barDeltaNorm[0]
    prevPxLowDelta = bars.low[0]
    prevDeltaLow = barDeltaNorm[0]
}

if (!isLiveUpdate) {
    // Bearish divergence: price higher high, delta lower high
    var pxHighDiv = highest(source=bars.high, period=divLookback)
    var deltaHighDiv = highest(source=barDeltaNorm, period=divLookback)
    if (bars.high[0] > prevPxHighDelta) {
        if (barDeltaNorm[0] < prevDeltaHigh) {
            bearDiv = true
        }
        prevPxHighDelta = bars.high[0]
        prevDeltaHigh = barDeltaNorm[0]
    }

    // Bullish divergence: price lower low, delta higher low
    var pxLowDiv = lowest(source=bars.low, period=divLookback)
    var deltaLowDiv = lowest(source=barDeltaNorm, period=divLookback)
    if (bars.low[0] < prevPxLowDelta) {
        if (barDeltaNorm[0] > prevDeltaLow) {
            bullDiv = true
        }
        prevPxLowDelta = bars.low[0]
        prevDeltaLow = barDeltaNorm[0]
    }
}

// -- 3.9 Zero-line helper --
timeseries zeroLine = 0

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

// 4.1 Zero line
hline(value=0, color="#ffffff30", width=1)

// 4.2 Volume bars (separate from delta)
if (showVolume) {
    plotBar(
        value=vol,
        colors=[transparency(volColor, 60)],
        width=1,
        label=["Volume"],
        desc=["Total bar volume"]
    )
}

// 4.3 Per-bar delta with fill and color coding
if (showDelta) {
    var deltaColor = barDelta > 0 ? buyColor : (barDelta < 0 ? sellColor : "#78909c")

    // Delta line
    plotLine(
        value=barDelta,
        width=2,
        colors=[deltaColor],
        label=["Bar Delta"],
        desc=["Per-bar buy minus sell volume (Lee-Ready tick test)"]
    )

    // Delta fill to zero
    if (showDeltaFill) {
        var fillDeltaColor = barDelta > 0 ? transparency(buyColor, 70) : transparency(sellColor, 70)
        plotLine(
            value=[barDelta, zeroLine],
            width=1,
            colors=[fillDeltaColor],
            fill=true,
            label=["Delta Fill"],
            desc=["Filled delta histogram to zero line"]
        )
    }

    // Delta bars (histogram)
    plotBar(
        value=barDelta,
        colors=[transparency(buyColor, 50), transparency(sellColor, 50)],
        colorIndex=buyerDominant ? 0 : 1,
        width=1,
        label=["Delta Bars"],
        desc=["Per-bar delta as histogram bars"]
    )
}

// 4.4 Cumulative Delta (CVD) line
if (showCumDelta) {
    plotLine(
        value=cumDeltaSm,
        width=2,
        colors=[cvdColor],
        label=["CVD (Smoothed)"],
        desc=["Cumulative delta smoothed by EMA (" + smoothLen + ")"]
    )
    plotLine(
        value=cumDelta,
        width=1,
        colors=[transparency(cvdColor, 50)],
        label=["CVD (Raw)"],
        desc=["True cumulative delta from first bar"]
    )
}

// 4.5 Extreme delta shape alerts
if (showExtremeShapes) {
    // Ultra extreme (absolute max/min in lookback)
    if (isUltraBuy) {
        plotShape(
            value=barDelta,
            shape="triangleup",
            colorIndex=extremeBuyColor,
            width=3,
            label=["Ultra Buy"],
            desc=["Maximum delta in lookback: aggressive buying climax (absorption zone)"]
        )
    }
    if (isUltraSell) {
        plotShape(
            value=barDelta,
            shape="triangledown",
            colorIndex=extremeSellColor,
            width=3,
            label=["Ultra Sell"],
            desc=["Minimum delta in lookback: aggressive selling climax (exhaustion zone)"]
        )
    }

    // Extreme but not absolute max/min
    if (isExtremeBuy && !isUltraBuy) {
        plotShape(
            value=barDelta,
            shape="circle",
            colorIndex=extremeBuyColor,
            width=2,
            label=["Extreme Buy"],
            desc=["Delta near lookback maximum: strong buyer pressure"]
        )
    }
    if (isExtremeSell && !isUltraSell) {
        plotShape(
            value=barDelta,
            shape="circle",
            colorIndex=extremeSellColor,
            width=2,
            label=["Extreme Sell"],
            desc=["Delta near lookback minimum: strong seller pressure"]
        )
    }

    // Regime flip shapes
    if (regimeFlipBuy) {
        plotShape(
            value=barDelta,
            shape="arrowup",
            colorIndex=buyColor,
            width=1,
            label=["Buy Flip"],
            desc=["Delta flipped from sell-dominated to buy-dominated"]
        )
    }
    if (regimeFlipSell) {
        plotShape(
            value=barDelta,
            shape="arrowdown",
            colorIndex=sellColor,
            width=1,
            label=["Sell Flip"],
            desc=["Delta flipped from buy-dominated to sell-dominated"]
        )
    }
}

// 4.6 Price-Delta divergence shapes
if (showDivergence) {
    if (bullDiv) {
        plotShape(
            value=barDelta,
            shape="triangleup",
            colorIndex=extremeBuyColor,
            width=2,
            label=["Delta Bull Div"],
            desc=["Bullish divergence: price lower low, delta higher low (buying pressure building)"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=barDelta,
            shape="triangledown",
            colorIndex=extremeSellColor,
            width=2,
            label=["Delta Bear Div"],
            desc=["Bearish divergence: price higher high, delta lower high (selling pressure building)"]
        )
    }
}

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = buyerDominant ? "BUY PRESSURE" : (sellerDominant ? "SELL PRESSURE" : "NEUTRAL")
    var regimeTextColor = buyerDominant ? buyColor : (sellerDominant ? sellColor : "#78909c")
    var normLabel = useVolNorm ? " (norm)" : ""

    plotTable(
        data=[
            ["ITC Delta Bar Pro", regimeText],
            ["Bar Delta" + normLabel, barDeltaNorm[0]],
            ["CVD (Smoothed)", cumDeltaSm[0]],
            ["CVD (Raw)", cumDelta],
            ["Buy Streak", buyStreak],
            ["Sell Streak", sellStreak],
            ["Max Delta" + normLabel, maxDelta[0]],
            ["Min Delta" + normLabel, minDelta[0]],
            ["Bull Div", bullDiv ? "YES" : "NO"],
            ["Bear Div", bearDiv ? "YES" : "NO"]
        ],
        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
    )
}