MM Flow
FlowScripts

Perfected FlowScript

Peak and Dip Hunter (Fork)

Peak and Dip Hunter V2 is indexed as 268_peak_and_dip_hunter_fork.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.5 KB

Lines

396

Native Signal Candidates

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

6/6 guarded

Dip

line 293:9

Trigger

(showShapes) && (isDip && (showLow || confidence >= 2))

Value

rsiS

Deps

confidence:var, isDip:var, showLow:input, showShapes:input

Peak

line 304:9

Trigger

(showShapes) && (isPeak && (showLow || confidence >= 2))

Value

rsiS

Deps

confidence:var, isPeak:var, showLow:input, showShapes:input

Bull Regime

line 321:9

Trigger

(showShapes) && (crossUp)

Value

depthRatioS

Deps

crossUp:var, showShapes:input

Bear Regime

line 331:9

Trigger

(showShapes) && (crossDn)

Value

depthRatioS

Deps

crossDn:var, showShapes:input

RSI Overbought

line 341:9

Trigger

(showShapes) && (rsiCrossUp)

Value

rsiS

Deps

rsiCrossUp:var, showShapes:input

RSI Oversold

line 351:9

Trigger

(showShapes) && (rsiCrossDn)

Value

rsiS

Deps

rsiCrossDn:var, showShapes:input

268_peak_and_dip_hunter_fork.flowscript

source path: kscripts/perfected/268_peak_and_dip_hunter_fork.flowscript · sha256:629d7435f0f04e8e098409fdaf433d8137f728889452e4e2f6c6625ff6bcf8f5

hash verified
//@version=2
// ============================================================================
// Peak and Dip Hunter V2 — Production-Quality Swing Extremes Detector
// Author: V (@Veer031718) | Perfected by: kScript Perfection Engineer
// Tags: ADVANCED, CORE, #dip, #top, #ob, #rsi, #swing, #zscore
//
// Multi-signal timing tool that flags likely dips and peaks by fusing RSI
// extremes, volume-delta shock, bid-ask depth imbalance, swing detection,
// z-score normalization, and graded confidence into a unified regime-aware
// indicator.
//
// FORMULA FOUNDATION:
// 1. RSI Extremes: Wilder (1978) RSI < 20 (dip) / > 80 (peak) thresholds.
// 2. Volume-Delta Shock: buy−sell volume vs rolling volatility (Cont et al. 2014).
// 3. Bid-Ask Depth Imbalance: (Bids−Asks)/(Bids+Asks)×100 (Gould & Bonart 2016).
// 4. Z-Score Normalization: z = (x − μ) / σ for statistical context (Zhao & Palomar 2018).
// 5. Swing Detection: Pivot highs/lows over lookback window.
// 6. Regime Segmentation: Bull / Neutral / Bear per Cartea et al. (2018).
//
// RESEARCH BASIS:
//  • Wilder (1978), "New Concepts in Technical Trading Systems": canonical RSI.
//    RSI = 100 − [100 / (1 + RS)] where RS = Average Gain / Average Loss.
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI linearly predicts price changes;
//    extreme delta spikes signal directional exhaustion.
//  • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price Predictor",
//    Market Microstructure & Liquidity 2(1), 1650006. Queue imbalance strongly
//    predicts next-tick direction for liquid Nasdaq stocks.
//  • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
//    Returns", J. Finance 61(4), 1645–1680. Sentiment extremes coincide with peak
//    and dip timing; multi-signal confirmation improves reliability.
//  • 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).
// ============================================================================

define(
    title="Peak and Dip Hunter V2",
    position="offchart",
    axis=true
)

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

// --- RSI Settings ---
var rsiLen = input(name="rsiLen", type="number", defaultValue=14, label="RSI Length", constraints={min: 2, max: 50, step: 1}, group="RSI")
var rsiSmooth = input(name="rsiSmooth", type="number", defaultValue=3, label="RSI Smoothing", constraints={min: 1, max: 20, step: 1}, group="RSI")
var dipThresh = input(name="dipThresh", type="number", defaultValue=20, label="Dip RSI Threshold", constraints={min: 5, max: 45, step: 1}, group="RSI")
var peakThresh = input(name="peakThresh", type="number", defaultValue=80, label="Peak RSI Threshold", constraints={min: 55, max: 95, step: 1}, group="RSI")

// --- Swing Detection ---
var swingLookback = input(name="swingLookback", type="number", defaultValue=5, label="Swing Lookback", constraints={min: 2, max: 20, step: 1}, group="Swing")
var showSwingLevels = input(name="showSwingLevels", type="boolean", defaultValue=true, label="Show Swing Levels", group="Swing")

// --- Orderbook ---
var depth = input(name="depth", type="number", defaultValue=5, label="Orderbook Depth Levels", constraints={min: 1, max: 50, step: 1}, group="Orderbook")
var depthSmooth = input(name="depthSmooth", type="number", defaultValue=3, label="Depth Smoothing", constraints={min: 1, max: 20, step: 1}, group="Orderbook")

// --- Volume-Delta ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Lookback", constraints={min: 5, max: 100, step: 1}, group="Volume-Delta")
var volMul = input(name="volMul", type="number", defaultValue=1.5, label="Volume Spike Multiplier", constraints={min: 1.0, max: 5.0, step: 0.1}, group="Volume-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")

// --- Display ---
var showLow = input(name="showLow", type="boolean", defaultValue=true, label="Show Low-Confidence Signals", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Signal Shapes", group="Display")
var showConfidenceFill = input(name="showConfidenceFill", type="boolean", defaultValue=true, label="Show Confidence Fill", 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="Dip Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Peak Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#00e676", label="Bull Regime Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ff1744", label="Bear Regime Color", group="Colors")

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

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

// ------------------------------------------------------------------------------
// RSI Computation (Wilder 1978 canonical implementation)
// ------------------------------------------------------------------------------
timeseries change = px - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = ema(source=gain, period=rsiLen)
timeseries avgLoss = ema(source=loss, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
timeseries rsiS = ema(rsiRaw, rsiSmooth)

// ------------------------------------------------------------------------------
// Swing Detection (Pivot Highs/Lows)
// ------------------------------------------------------------------------------
timeseries pivotHigh = high == highest(high, swingLookback * 2 + 1)[swingLookback]
timeseries pivotLow = low == lowest(low, swingLookback * 2 + 1)[swingLookback]
timeseries swingHigh = pivotHigh ? high : 0
timeseries swingLow = pivotLow ? low : 0

// ------------------------------------------------------------------------------
// Orderbook Depth Imbalance (Gould & Bonart 2016)
// ------------------------------------------------------------------------------
timeseries bids = sumBids(book, depth)
timeseries asks = sumAsks(book, depth)
var bookAvailable = bids > 0 && asks > 0
var denomDepth = bids + asks
var depthRatio = bookAvailable && denomDepth > 0 ? (bids - asks) / denomDepth * 100.0 : 0.0
timeseries depthRatioS = ema(depthRatio, depthSmooth)

// ------------------------------------------------------------------------------
// Volume-Delta Shock (Cont et al. 2014)
// ------------------------------------------------------------------------------
timeseries avgVol = sma(volume, volLookback)
timeseries volStd = stddev(volume, volLookback)
timeseries volZ = volStd > 0 ? (volume - avgVol) / volStd : 0.0
timeseries volSpike = volume > avgVol * volMul ? 1 : 0

// ------------------------------------------------------------------------------
// Composite Signal & Confidence Grading
// ------------------------------------------------------------------------------
// Three confidence tiers: Low (1), Medium (2), High (3)

var rsiSignal = rsiS < dipThresh ? 1 : (rsiS > peakThresh ? -1 : 0)
var depthSignal = depthRatioS > 20 ? 1 : (depthRatioS < -20 ? -1 : 0)
var confidence = abs(rsiSignal) + abs(depthSignal) + volSpike
var isDip = rsiSignal == 1 && depthSignal == 1
var isPeak = rsiSignal == -1 && depthSignal == -1

// Z-Score of RSI for statistical context
var rsiMean = sma(rsiS, zLookback)
var rsiStd = stddev(rsiS, zLookback)
var rsiZScore = rsiStd > 0 ? (rsiS - rsiMean) / rsiStd : 0.0

// ------------------------------------------------------------------------------
// Regime Detection (Cartea et al. 2018)
// ------------------------------------------------------------------------------
// Regime based on depthRatioS composite

var regime = 0
if (depthRatioS >= bullThresh) {
    regime = 1
} else if (depthRatioS <= bearThresh) {
    regime = -1
}

var regimeColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRSI = 0.0
static sessionLowRSI = 100.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static dipCount = 0
static peakCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (rsiS > sessionHighRSI) {
        sessionHighRSI = rsiS
    }
    if (rsiS < sessionLowRSI) {
        sessionLowRSI = rsiS
    }
    if (rsiZScore > sessionHighZ) {
        sessionHighZ = rsiZScore
    }
    if (rsiZScore < sessionLowZ) {
        sessionLowZ = rsiZScore
    }

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

    if (isDip && confidence >= 2) {
        dipCount = dipCount + 1
    }
    if (isPeak && confidence >= 2) {
        peakCount = peakCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — RSI, Swing Levels, Z-Score, Confidence Fill, Shapes, Guides
// ------------------------------------------------------------------------------

// Horizontal guide lines
hline(value=50, color="#ffffff20", width=1)
if (showGuides) {
    hline(value=dipThresh, color=opacity(upColor, 30), width=1)
    hline(value=peakThresh, color=opacity(dnColor, 30), width=1)
    hline(value=70, color=opacity(bullColor, 20), width=1)
    hline(value=30, color=opacity(bearColor, 20), width=1)
}

// Smoothed RSI with regime-coded fill
plotLine(
    value=rsiS,
    width=2,
    colors=[regimeColor],
    label=["Smoothed RSI"],
    desc=["EMA-smoothed RSI (Wilder " + rsiLen + ") with regime color coding"],
    fill=true
)

// Swing levels (optional)
if (showSwingLevels) {
    plotLine(
        value=swingHigh,
        width=1,
        colors=[opacity(upColor, 40)],
        label=["Swing High"],
        desc=["Pivot high level over " + swingLookback + " bars"]
    )
    plotLine(
        value=swingLow,
        width=1,
        colors=[opacity(dnColor, 40)],
        label=["Swing Low"],
        desc=["Pivot low level over " + swingLookback + " bars"]
    )
}

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

// Confidence fill (composite signal strength)
if (showConfidenceFill) {
    plotBar(
        value=confidence,
        colors=[transparency(upColor, 60), transparency(dnColor, 60), transparency(neutralColor, 60)],
        colorIndex=isDip ? 0 : (isPeak ? 1 : 2),
        width=1,
        label=["Confidence"],
        desc=["Composite confidence: RSI + Depth + Volume (1=Low, 2=Med, 3=High)"]
    )
}

// Depth ratio line
plotLine(
    value=depthRatioS,
    width=1,
    colors=[bullColor, bearColor, neutralColor],
    colorIndex=depthRatioS > 20 ? 0 : (depthRatioS < -20 ? 1 : 2),
    label=["Depth Imbalance"],
    desc=["Depth-weighted bid-ask imbalance (Gould & Bonart 2016)"]
)

// Signal shapes — Dip and Peak with confidence-graded sizing
if (showShapes) {
    if (isDip && (showLow || confidence >= 2)) {
        var shapeSize = confidence >= 3 ? 4 : (confidence >= 2 ? 3 : 2)
        plotShape(
            value=rsiS,
            shape="triangleup",
            color=upColor,
            width=shapeSize,
            label=["Dip"],
            desc=["Dip signal: RSI < " + dipThresh + ", bid-heavy depth, volume confirmed (conf=" + confidence + ")"]
        )
    }
    if (isPeak && (showLow || confidence >= 2)) {
        var shapeSize = confidence >= 3 ? 4 : (confidence >= 2 ? 3 : 2)
        plotShape(
            value=rsiS,
            shape="triangledown",
            color=dnColor,
            width=shapeSize,
            label=["Peak"],
            desc=["Peak signal: RSI > " + peakThresh + ", ask-heavy depth, volume confirmed (conf=" + confidence + ")"]
        )
    }

    // Regime transition shapes
    var crossUp = depthRatioS >= bullThresh && !isnan(depthRatioS[1]) && depthRatioS[1] < bullThresh
    var crossDn = depthRatioS <= bearThresh && !isnan(depthRatioS[1]) && depthRatioS[1] > bearThresh
    var rsiCrossUp = rsiS >= 70 && !isnan(rsiS[1]) && rsiS[1] < 70
    var rsiCrossDn = rsiS <= 30 && !isnan(rsiS[1]) && rsiS[1] > 30

    if (crossUp) {
        plotShape(
            value=depthRatioS,
            shape="circle",
            color=bullColor,
            width=2,
            label=["Bull Regime"],
            desc=["Depth imbalance crossed into bullish regime (buy-heavy)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=depthRatioS,
            shape="circle",
            color=bearColor,
            width=2,
            label=["Bear Regime"],
            desc=["Depth imbalance crossed into bearish regime (sell-heavy)"]
        )
    }
    if (rsiCrossUp) {
        plotShape(
            value=rsiS,
            shape="diamond",
            color=dnColor,
            width=2,
            label=["RSI Overbought"],
            desc=["RSI crossed above 70 — overbought warning"]
        )
    }
    if (rsiCrossDn) {
        plotShape(
            value=rsiS,
            shape="diamond",
            color=upColor,
            width=2,
            label=["RSI Oversold"],
            desc=["RSI crossed below 30 — oversold warning"]
        )
    }
}

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

    plotTable(
        data=[
            ["Peak/Dip Hunter V2", regimeText],
            ["RSI", rsiS[0]],
            ["RSI Z-Score", rsiZScore[0]],
            ["Depth Imbalance", depthRatioS[0]],
            ["Volume Z", volZ[0]],
            ["Confidence", confidence[0]],
            ["Session RSI High", sessionHighRSI],
            ["Session RSI Low", sessionLowRSI],
            ["Dip Count", dipCount],
            ["Peak Count", peakCount],
            ["Regime Changes", regimeChangeCount]
        ],
        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
    )
}