MM Flow
FlowScripts

Perfected FlowScript

delta turn

Delta Turn V2 is indexed as 269_delta_turn.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

15.9 KB

Lines

396

Native Signal Candidates

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

8/8 guarded

Delta Turn Up

line 272:9

Trigger

(showShapes) && (turnUp)

Value

delta

Deps

showShapes:input, turnUp:var

Delta Turn Down

line 282:9

Trigger

(showShapes) && (turnDn)

Value

delta

Deps

showShapes:input, turnDn:var

Momentum Turn Up

line 292:9

Trigger

(showShapes) && (histTurnUp)

Value

hist

Deps

histTurnUp:var, showShapes:input

Momentum Turn Down

line 302:9

Trigger

(showShapes) && (histTurnDn)

Value

hist

Deps

histTurnDn:var, showShapes:input

Extreme Bid

line 319:9

Trigger

(showShapes) && (extremeUp)

Value

delta

Deps

extremeUp:var, showShapes:input

Extreme Ask

line 329:9

Trigger

(showShapes) && (extremeDn)

Value

delta

Deps

extremeDn:var, showShapes:input

Z+2σ

line 339:9

Trigger

(showShapes) && (zScoreUp)

Value

deltaZScore

Deps

showShapes:input, zScoreUp:var

Z-2σ

line 349:9

Trigger

(showShapes) && (zScoreDn)

Value

deltaZScore

Deps

showShapes:input, zScoreDn:var

269_delta_turn.flowscript

source path: kscripts/perfected/269_delta_turn.flowscript · sha256:6f334e937313219b0a700d9bd7a27ef7cb6a561b01f5d3e7c465acab174b558b

hash verified
//@version=2
// ============================================================================
// Delta Turn V2 — Production-Quality Volume Delta Turning Point Indicator
// Author: L (@Luv Chen) | Perfected by: kScript Perfection Engineer
// Tags: SPECIALIZED, #deltaturn, #volume, #orderflow, #momentum, #regime
//
// Directional analysis of volume delta to detect trend flips, using the sign
// and momentum of aggressive order flow as a leading indicator of price
// turning points. Features z-score normalization, regime detection, momentum
// histogram, and comprehensive shape-marked signal extraction.
//
// FORMULA FOUNDATION:
// 1. Volume Delta: Δ = BidVol − AskVol (aggressive buy minus sell volume).
//    Per Lee & Ready (1991) and Easley, López de Prado & O'Hara (2012).
// 2. Delta Turn: Sign change in smoothed delta (positive→negative or vice versa).
//    Per Cont, Kukanov & Stoikov (2014): OFI direction shifts predict price moves.
// 3. Z-Score Normalization: z = (Δ − μ) / σ over rolling window.
//    Per Zhao & Palomar (2018); mean-reversion entry at ±2σ.
// 4. Momentum Histogram: Delta minus its signal SMA — visualizes acceleration.
// 5. Regime Segmentation: Bull / Neutral / Bear per Cartea et al. (2018).
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. ΔPrice ≈ λ × OFI where λ ∝ 1/Depth;
//    OFI explains ~65% of variance in contemporaneous mid-price changes.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Market returns
//    reverse after high-negative-imbalance, large-negative-return days — directly
//    supporting delta-turn-based reversal detection.
//  • Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica 53(6),
//    1315–1335. Lambda = price impact coefficient; delta direction changes precede
//    price direction changes as informed flow shifts.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//    Z-score event triggers at ±1σ or ±2σ for mean-reversion trading.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy (−1,−1/3), Neutral (−1/3,1/3), Buy-heavy (1/3,1).
//  • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//    J. Finance 46(2), 733–746. Bedrock of all volume delta calculations;
//    ~85–93% accuracy on NYSE TORQ data.
// ============================================================================

define(
    title="Delta Turn V2",
    position="offchart",
    axis=true
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Delta Settings ---
var lookback = input(name="lookback", type="number", defaultValue=10, label="Delta Lookback", constraints={min: 2, max: 50, step: 1}, group="Delta")
var smooth = input(name="smooth", type="number", defaultValue=3, label="Delta Smoothing", constraints={min: 1, max: 20, step: 1}, group="Delta")
var signalLen = input(name="signalLen", type="number", defaultValue=14, label="Signal SMA Length", constraints={min: 2, max: 50, step: 1}, group="Delta")
var depth = input(name="depth", type="number", defaultValue=3, label="Orderbook Depth", constraints={min: 1, max: 50, step: 1}, group="Delta")

// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 1}, group="Z-Score")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Z-Score")

// --- Regime Thresholds ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=33.0, label="Bullish Regime Threshold (%)", constraints={min: 10.0, max: 90.0, step: 1.0}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-33.0, label="Bearish Regime Threshold (%)", constraints={min: -90.0, max: -10.0, step: 1.0}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=66.0, label="Extreme Threshold (%)", constraints={min: 50.0, max: 95.0, step: 1.0}, group="Thresholds")

// --- Display ---
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Momentum Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Turn Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Bullish Turn Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Bearish Turn Color", group="Colors")
var bidColor = input(name="bidColor", type="color", defaultValue="#00e676", label="Bid-Dominant Color", group="Colors")
var askColor = input(name="askColor", type="color", defaultValue="#ff1744", label="Ask-Dominant Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBidColor = input(name="extremeBidColor", type="color", defaultValue="#00e676", label="Extreme Bid Color", group="Colors")
var extremeAskColor = input(name="extremeAskColor", type="color", defaultValue="#ff1744", label="Extreme Ask Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries open = priceBars.open
timeseries high = priceBars.high
timeseries low = priceBars.low
timeseries volume = priceBars.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)

if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Volume Delta Computation (Lee & Ready 1991; Cont et al. 2014)
// ------------------------------------------------------------------------------
timeseries bids = sumBids(book, depth)
timeseries asks = sumAsks(book, depth)
var bookAvailable = bids > 0 && asks > 0

var rawDelta = bookAvailable ? bids - asks : 0.0
var delta = sma(rawDelta, smooth)
var deltaPrev = delta[1]

// Signal SMA for momentum
var signal = sma(delta, signalLen)

// Momentum histogram (delta minus signal)
var hist = delta - signal

// ------------------------------------------------------------------------------
// Turn Detection (Cont et al. 2014; Chordia et al. 2002)
// ------------------------------------------------------------------------------
// Sign change in smoothed delta indicates order flow direction shift

var turnUp = !isnan(deltaPrev) && deltaPrev < 0 && delta > 0
var turnDn = !isnan(deltaPrev) && deltaPrev > 0 && delta < 0

// Momentum turn: histogram sign change (acceleration shift)
var histTurnUp = !isnan(hist[1]) && hist[1] < 0 && hist > 0
var histTurnDn = !isnan(hist[1]) && hist[1] > 0 && hist < 0

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// Z-score of delta for statistical context on turning points

var deltaMean = sma(delta, zLookback)
var deltaStd = stddev(delta, zLookback)
var deltaZScore = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0.0

// ------------------------------------------------------------------------------
// Regime Detection (Cartea et al. 2018)
// ------------------------------------------------------------------------------
// Based on normalized delta relative to thresholds

var deltaPct = bookAvailable && (bids + asks) > 0 ? (bids - asks) / (bids + asks) * 100.0 : 0.0
var deltaPctS = sma(deltaPct, smooth)

var regime = 0      // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0  // 0 = normal, 1 = extreme bull, -1 = extreme bear

if (deltaPctS >= bullThresh) {
    regime = 1
} else if (deltaPctS <= bearThresh) {
    regime = -1
}

if (deltaPctS >= extremeThresh) {
    extremeRegime = 1
} else if (deltaPctS <= -extremeThresh) {
    extremeRegime = -1
}

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static turnUpCount = 0
static turnDnCount = 0
static extremeBidCount = 0
static extremeAskCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (delta > sessionHighDelta) {
        sessionHighDelta = delta
    }
    if (delta < sessionLowDelta) {
        sessionLowDelta = delta
    }
    if (deltaZScore > sessionHighZ) {
        sessionHighZ = deltaZScore
    }
    if (deltaZScore < sessionLowZ) {
        sessionLowZ = deltaZScore
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (turnUp) {
        turnUpCount = turnUpCount + 1
    }
    if (turnDn) {
        turnDnCount = turnDnCount + 1
    }

    if (extremeRegime == 1) {
        extremeBidCount = extremeBidCount + 1
    } else if (extremeRegime == -1) {
        extremeAskCount = extremeAskCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Delta Line, Histogram, Z-Score, Shapes, Guides, Fill
// ------------------------------------------------------------------------------

// Horizontal guide lines
hline(value=0, color="#ffffff40", width=1)
if (showGuides) {
    hline(value=bullThresh, color=opacity(bidColor, 30), width=1)
    hline(value=bearThresh, color=opacity(askColor, 30), width=1)
    hline(value=extremeThresh, color=opacity(extremeBidColor, 20), width=1)
    hline(value=-extremeThresh, color=opacity(extremeAskColor, 20), width=1)
}

// Smoothed delta line with regime-coded fill
plotLine(
    value=delta,
    width=2,
    colors=[bidColor, askColor, neutralColor],
    colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
    label=["Delta"],
    desc=["SMA-smoothed bid-ask delta (positive=bid-heavy, negative=ask-heavy)"],
    fill=true
)

// Signal SMA
plotLine(
    value=signal,
    width=1,
    colors=["#ffffff"],
    label=["Signal SMA"],
    desc=["SMA of smoothed delta (" + signalLen + ") — trend reference"]
)

// Momentum histogram (color-coded by regime and sign)
if (showHistogram) {
    var histBull = hist >= 0
    var histColor = histBull ? (regime == 1 ? bidColor : neutralColor) : (regime == -1 ? askColor : neutralColor)
    plotBar(
        value=hist,
        colors=[transparency(bidColor, 60), transparency(askColor, 60), transparency(neutralColor, 60)],
        colorIndex=histBull ? (regime == 1 ? 0 : 2) : (regime == -1 ? 1 : 2),
        width=1,
        label=["Delta Momentum"],
        desc=["Histogram of delta minus signal SMA — acceleration/deceleration"]
    )
}

// Z-Score line
if (showZScore) {
    plotLine(
        value=deltaZScore,
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=deltaZScore > 1.0 ? 0 : (deltaZScore < -1.0 ? 1 : 2),
        label=["Delta Z-Score"],
        desc=["Z-score of smoothed delta over " + zLookback + " bars (Zhao & Palomar 2018)"]
    )
}

// Turn shapes
if (showShapes) {
    if (turnUp) {
        plotShape(
            value=delta,
            shape="triangleup",
            color=upColor,
            width=3,
            label=["Delta Turn Up"],
            desc=["Delta flipped positive — bid flow overtaking ask flow (trend flip up)"]
        )
    }
    if (turnDn) {
        plotShape(
            value=delta,
            shape="triangledown",
            color=dnColor,
            width=3,
            label=["Delta Turn Down"],
            desc=["Delta flipped negative — ask flow overtaking bid flow (trend flip down)"]
        )
    }
    if (histTurnUp) {
        plotShape(
            value=hist,
            shape="arrowup",
            color=upColor,
            width=2,
            label=["Momentum Turn Up"],
            desc=["Histogram momentum turned positive — delta accelerating above signal"]
        )
    }
    if (histTurnDn) {
        plotShape(
            value=hist,
            shape="arrowdown",
            color=dnColor,
            width=2,
            label=["Momentum Turn Down"],
            desc=["Histogram momentum turned negative — delta decelerating below signal"]
        )
    }

    // Extreme regime shapes
    var extremeUp = deltaPctS >= extremeThresh && !isnan(deltaPctS[1]) && deltaPctS[1] < extremeThresh
    var extremeDn = deltaPctS <= -extremeThresh && !isnan(deltaPctS[1]) && deltaPctS[1] > -extremeThresh
    var zScoreUp = deltaZScore >= 2.0 && !isnan(deltaZScore[1]) && deltaZScore[1] < 2.0
    var zScoreDn = deltaZScore <= -2.0 && !isnan(deltaZScore[1]) && deltaZScore[1] > -2.0

    if (extremeUp) {
        plotShape(
            value=delta,
            shape="diamond",
            color=extremeBidColor,
            width=4,
            label=["Extreme Bid"],
            desc=["Extreme bid dominance detected — deep book buy-heavy delta"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=delta,
            shape="diamond",
            color=extremeAskColor,
            width=4,
            label=["Extreme Ask"],
            desc=["Extreme ask dominance detected — deep book sell-heavy delta"]
        )
    }
    if (zScoreUp) {
        plotShape(
            value=deltaZScore,
            shape="triangleup",
            color=extremeBidColor,
            width=2,
            label=["Z+2σ"],
            desc=["Z-score crossed above +2σ — potential mean-reversion sell zone"]
        )
    }
    if (zScoreDn) {
        plotShape(
            value=deltaZScore,
            shape="triangledown",
            color=extremeAskColor,
            width=2,
            label=["Z-2σ"],
            desc=["Z-score crossed below -2σ — potential mean-reversion buy zone"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? bidColor : (regime == -1 ? askColor : neutralColor)

    plotTable(
        data=[
            ["Delta Turn V2", regimeText],
            ["Delta", delta[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            ["Delta Z-Score", deltaZScore[0]],
            ["Delta %", deltaPctS[0]],
            ["Session Delta High", sessionHighDelta],
            ["Session Delta Low", sessionLowDelta],
            ["Turn Up Count", turnUpCount],
            ["Turn Down Count", turnDnCount],
            ["Regime Changes", regimeChangeCount],
            ["Extreme Bid Count", extremeBidCount],
            ["Extreme Ask Count", extremeAskCount]
        ],
        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
    )
}