MM Flow
FlowScripts

Perfected FlowScript

Peak and Dip Hunter

Peak and Dip Hunter [BackQuant] — Perfected is indexed as 022_peak_and_dip_hunter.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.0 KB

Lines

520

Native Signal Candidates

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

7/7 guarded

Dip Weak

line 389:5

Trigger

(showWeak && dipWeak)

Value

lo

Deps

dipWeak:var, showWeak:input

Dip Medium

line 400:5

Trigger

(showMedium && dipMedium)

Value

lo

Deps

dipMedium:var, showMedium:input

Dip Strong

line 411:5

Trigger

(showStrong && dipStrong)

Value

lo

Deps

dipStrong:var, showStrong:input

Peak Weak

line 424:5

Trigger

(showWeak && peakWeak)

Value

hi

Deps

peakWeak:var, showWeak:input

Peak Medium

line 435:5

Trigger

(showMedium && peakMedium)

Value

hi

Deps

peakMedium:var, showMedium:input

Peak Strong

line 446:5

Trigger

(showStrong && peakStrong)

Value

hi

Deps

peakStrong:var, showStrong:input

Unlabeled shape

line 470:5

Trigger

(isLastBar)

Value

hi

Deps

isLastBar:builtin

022_peak_and_dip_hunter.flowscript

source path: kscripts/perfected/022_peak_and_dip_hunter.flowscript · sha256:003fa0f2a4e03ba5562da6c8d76e4c972ce9aa36e4236964db4ac3f2c529a730

hash verified
//@version=2
// ============================================================================
// Peak and Dip Hunter [BackQuant] — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, CORE, #dip, #top, #ob, #rsi, #zscore, #multisignal, #confidence
//
// Production-grade multi-signal timing tool that flags likely dips and peaks by
// fusing three inputs into graded confidence scores: RSI extremes with EMA
// smoothing, volume-delta shock (z-score normalized against rolling volatility),
// and bid-ask depth imbalance. Three confidence tiers (weak/medium/strong)
// adjust bubble size and shape. Full color coding by signal type and regime.
//
// Research papers underpinning this design:
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": RSI
//     overbought/oversold thresholds (70/30, extended to 80/20).
//     Canonical RSI = 100 - [100 / (1 + RS)].
//  2. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events": depth imbalance ratio normalization from OFI research.
//     OFI = Σ(E_i × ΔP_i); linear price-impact model.
//  3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns": extreme imbalances predict return reversals.
//  4. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score normalization for entry thresholds; z̄_t = (z_t - μ_z) / σ_z.
//  5. Ponnusamy & Manual (2016): RSI outperforms MACD and Stochastic in
//     signal reliability; multi-indicator confirmation recommended.
//  6. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity":
//     VPIN framework; volume bucket and statistical significance for extreme
//     event detection.
//  7. Baker & Wurgler (2006), "Investor Sentiment": composite sentiment
//     construction; extreme readings often mark reversal points.
// ============================================================================

define(
    title="Peak and Dip Hunter [BackQuant] — Perfected",
    position="onchart",
    axis=false
)

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

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

// --- Volume Delta ---
var deltaLen = input(
    name="deltaLen",
    type="number",
    defaultValue=20,
    label="Delta Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Delta"
)
var deltaZThresh = input(
    name="deltaZThresh",
    type="number",
    defaultValue=2.0,
    label="Delta Z-Score Threshold",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Volume Delta"
)

// --- Orderbook Depth ---
var depthPct = input(
    name="depthPct",
    type="number",
    defaultValue=2.5,
    label="Book Depth (%)",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="Orderbook Depth"
)
var depthThresh = input(
    name="depthThresh",
    type="number",
    defaultValue=0.2,
    label="Depth Imbalance Threshold",
    constraints={min: 0.05, max: 1.0, step: 0.05},
    group="Orderbook Depth"
)

// --- Confidence ---
var showWeak = input(
    name="showWeak",
    type="boolean",
    defaultValue=true,
    label="Show Weak Confidence",
    group="Confidence"
)
var showMedium = input(
    name="showMedium",
    type="boolean",
    defaultValue=true,
    label="Show Medium Confidence",
    group="Confidence"
)
var showStrong = input(
    name="showStrong",
    type="boolean",
    defaultValue=true,
    label="Show Strong Confidence",
    group="Confidence"
)

// --- Display ---
var showRSI = input(
    name="showRSI",
    type="boolean",
    defaultValue=true,
    label="Show RSI Line",
    group="Display"
)
var showRSIFill = input(
    name="showRSIFill",
    type="boolean",
    defaultValue=true,
    label="Show RSI Fill",
    group="Display"
)
var showDeltaZ = input(
    name="showDeltaZ",
    type="boolean",
    defaultValue=false,
    label="Show Delta Z-Score (offchart)",
    group="Display"
)
var showConfidenceBars = input(
    name="showConfidenceBars",
    type="boolean",
    defaultValue=true,
    label="Show Confidence Bars",
    group="Display"
)

// --- Colors ---
var dipColor = input(
    name="dipColor",
    type="color",
    defaultValue="#26a69a",
    label="Dip Color",
    group="Colors"
)
var peakColor = input(
    name="peakColor",
    type="color",
    defaultValue="#ef5350",
    label="Peak Color",
    group="Colors"
)
var weakColor = input(
    name="weakColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Weak Confidence Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
timeseries book = source("orderbook", currentSymbol, currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume
timeseries op = bars.open

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(vol[0])) {
    return
}

// ----------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ----------------------------------------------------------------------------
static lastDipConfidence = 0     // 0=none, 1=weak, 2=medium, 3=strong
static lastPeakConfidence = 0    // 0=none, 1=weak, 2=medium, 3=strong
static dipSignalCount = 0
static peakSignalCount = 0
static dipUpgradeCount = 0
static peakUpgradeCount = 0
static lastRSIRegime = 0         // 0=neutral, 1=bull, 2=bear
static regimeChangeCount = 0
static barCount = 0

// -----------------------------------------------------------------------------
// 3. RSI — CANONICAL WILDER WITH EMA SMOOTHING
// -----------------------------------------------------------------------------
// RSI = 100 - [100 / (1 + RS)] where RS = Average Gain / Average Loss
// We use the smoothed RSI as our momentum extremity detector.
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 smoothRsi = ema(source=rsiRaw, period=rsiSmooth)

// -----------------------------------------------------------------------------
// 4. VOLUME DELTA SHOCK — Z-SCORE NORMALIZED
// -----------------------------------------------------------------------------
// Buy/sell volume classification with fallback to tick rule
timeseries buyVol = isnum(taker.buy) ? taker.buy : (px > op ? vol : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (px <= op ? vol : 0)
timeseries delta = buyVol - sellVol

// Z-score normalization: (delta - mean) / stddev over rolling window
timeseries deltaMean = sma(delta, deltaLen)
timeseries deltaStd = stdev(delta, deltaLen)
timeseries deltaZ = deltaStd > 0 ? (delta - deltaMean) / deltaStd : 0

// Volume-delta shock flags (extreme readings)
var dipDelta = deltaZ < -deltaZThresh
var peakDelta = deltaZ > deltaZThresh

// -----------------------------------------------------------------------------
// 5. BID-ASK DEPTH IMBALANCE
// -----------------------------------------------------------------------------
// Depth-weighted bid/ask imbalance ratio within configurable depth band
timeseries depthLvl = math.max(1, math.floor(depthPct))
timeseries bids = sumBids(book, depthLvl)
timeseries asks = sumAsks(book, depthLvl)
timeseries depthRatio = (bids + asks) > 0 ? (bids - asks) / (bids + asks) * 100 : 0

// Depth imbalance flags
var dipBook = depthRatio > depthThresh
var peakBook = depthRatio < -depthThresh

// -----------------------------------------------------------------------------
// 6. MULTI-SIGNAL FUSION & CONFIDENCE SCORING
// -----------------------------------------------------------------------------
// Three signals: RSI extreme, volume-delta shock, depth imbalance
// Score = count of agreeing signals (0 to 3)
// Graded: 1 = weak, 2 = medium, 3 = strong

var dipRsi = smoothRsi < dipThresh
var peakRsi = smoothRsi > peakThresh

// Dip score: how many of the 3 signals agree on a dip?
var dipScore = (dipRsi ? 1 : 0) + (dipDelta ? 1 : 0) + (dipBook ? 1 : 0)
var peakScore = (peakRsi ? 1 : 0) + (peakDelta ? 1 : 0) + (peakBook ? 1 : 0)

// Confidence classification
var dipWeak = dipScore == 1
var dipMedium = dipScore == 2
var dipStrong = dipScore == 3

var peakWeak = peakScore == 1
var peakMedium = peakScore == 2
var peakStrong = peakScore == 3

// Confidence bars for visualization (positive = dip, negative = peak)
timeseries confidenceScore = 0.0
if (dipScore >= 1) {
    confidenceScore = dipScore
} else if (peakScore >= 1) {
    confidenceScore = -peakScore
}

// Update static state tracking
var currentDipConfidence = dipStrong ? 3 : (dipMedium ? 2 : (dipWeak ? 1 : 0))
var currentPeakConfidence = peakStrong ? 3 : (peakMedium ? 2 : (peakWeak ? 1 : 0))
var currentRSIRegime = rsiRegimeBull ? 1 : (rsiRegimeBear ? 2 : 0)

if (currentDipConfidence >= 1) {
    dipSignalCount = dipSignalCount + 1
}
if (currentPeakConfidence >= 1) {
    peakSignalCount = peakSignalCount + 1
}
if (lastDipConfidence > 0 && currentDipConfidence > lastDipConfidence) {
    dipUpgradeCount = dipUpgradeCount + 1
}
if (lastPeakConfidence > 0 && currentPeakConfidence > lastPeakConfidence) {
    peakUpgradeCount = peakUpgradeCount + 1
}
if (barCount > 0 && currentRSIRegime != lastRSIRegime) {
    regimeChangeCount = regimeChangeCount + 1
}
if (barCount == 0) {
    lastRSIRegime = currentRSIRegime
}
lastDipConfidence = currentDipConfidence
lastPeakConfidence = currentPeakConfidence
lastRSIRegime = currentRSIRegime
barCount = barCount + 1

// -----------------------------------------------------------------------------
// 7. REGIME CONTEXT
// -----------------------------------------------------------------------------
// Overall market regime from RSI position (complementary to dip/peak signals)
var rsiRegimeBull = smoothRsi > 50
var rsiRegimeBear = smoothRsi < 50
var rsiRegimeNeutral = smoothRsi >= 45 && smoothRsi <= 55

var rsiRegimeColor = rsiRegimeBull ? dipColor : (rsiRegimeBear ? peakColor : weakColor)

// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------

// --- RSI Line (regime-colored) ---
if (showRSI) {
    plotLine(
        value=smoothRsi,
        width=2,
        colors=[rsiRegimeColor],
        label=["RSI"],
        desc=["EMA-smoothed RSI (" + rsiLen + "/" + rsiSmooth + ") — regime-colored"]
    )
}

// --- RSI Threshold Fill (overbought/oversold zones) ---
if (showRSIFill) {
    // Overbought zone fill
    plotLine(
        value=[smoothRsi, peakThresh],
        width=0,
        colors=[transparency(peakColor, 15), transparency(peakColor, 15)],
        fill=transparency(peakColor, 15),
        label=["RSI", "Peak"],
        desc=["RSI in overbought zone", "Peak threshold"]
    )
    // Oversold zone fill
    plotLine(
        value=[smoothRsi, dipThresh],
        width=0,
        colors=[transparency(dipColor, 15), transparency(dipColor, 15)],
        fill=transparency(dipColor, 15),
        label=["RSI", "Dip"],
        desc=["RSI in oversold zone", "Dip threshold"]
    )
}

// --- RSI Threshold Lines ---
hline(value=50, color="#ffffff30", width=1)
hline(value=dipThresh, color=transparency(dipColor, 50), width=1)
hline(value=peakThresh, color=transparency(peakColor, 50), width=1)

// --- Confidence Bars (histogram) ---
if (showConfidenceBars) {
    var confBull = confidenceScore >= 0
    plotBar(
        value=confidenceScore,
        colors=[transparency(dipColor, 70), transparency(peakColor, 70)],
        colorIndex=confBull ? 0 : 1,
        width=1,
        label=["Confidence"],
        desc=["Dip/peak confidence score: 1=weak, 2=medium, 3=strong"]
    )
}

// --- Dip Shape Markers (size by confidence) ---
// Weak dips: small circles
if (showWeak && dipWeak) {
    plotShape(
        value=lo,
        shape="circle",
        colorIndex=weakColor,
        width=2,
        label=["Dip Weak"],
        desc=["Weak dip: 1 of 3 signals aligned (RSI=" + dipRsi + ", Delta=" + dipDelta + ", Book=" + dipBook + ")"]
    )
}
// Medium dips: medium circles
if (showMedium && dipMedium) {
    plotShape(
        value=lo,
        shape="circle",
        colorIndex=dipColor,
        width=4,
        label=["Dip Medium"],
        desc=["Medium dip: 2 of 3 signals aligned (RSI=" + dipRsi + ", Delta=" + dipDelta + ", Book=" + dipBook + ")"]
    )
}
// Strong dips: large triangles
if (showStrong && dipStrong) {
    plotShape(
        value=lo,
        shape="triangleup",
        colorIndex=dipColor,
        width=6,
        label=["Dip Strong"],
        desc=["Strong dip: 3 of 3 signals aligned (RSI=" + dipRsi + ", Delta=" + dipDelta + ", Book=" + dipBook + ")"]
    )
}

// --- Peak Shape Markers (size by confidence) ---
// Weak peaks: small circles
if (showWeak && peakWeak) {
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=weakColor,
        width=2,
        label=["Peak Weak"],
        desc=["Weak peak: 1 of 3 signals aligned (RSI=" + peakRsi + ", Delta=" + peakDelta + ", Book=" + peakBook + ")"]
    )
}
// Medium peaks: medium circles
if (showMedium && peakMedium) {
    plotShape(
        value=hi,
        shape="circle",
        colorIndex=peakColor,
        width=4,
        label=["Peak Medium"],
        desc=["Medium peak: 2 of 3 signals aligned (RSI=" + peakRsi + ", Delta=" + peakDelta + ", Book=" + peakBook + ")"]
    )
}
// Strong peaks: large triangles
if (showStrong && peakStrong) {
    plotShape(
        value=hi,
        shape="triangledown",
        colorIndex=peakColor,
        width=6,
        label=["Peak Strong"],
        desc=["Strong peak: 3 of 3 signals aligned (RSI=" + peakRsi + ", Delta=" + peakDelta + ", Book=" + peakBook + ")"]
    )
}

// --- Delta Z-Score (optional offchart) ---
if (showDeltaZ) {
    plotLine(
        value=deltaZ,
        width=1,
        colors=[transparency("#42a5f5", 60)],
        label=["Delta Z"],
        desc=["Volume delta z-score (rolling " + deltaLen + ")"]
    )
}

// --- Regime Price Label (last bar) ---
if (isLastBar) {
    var rsiLabel = rsiRegimeBull ? "RSI BULLISH" : (rsiRegimeBear ? "RSI BEARISH" : "RSI NEUTRAL")
    plotPriceLabel(
        price=hi,
        text=rsiLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=rsiRegimeColor,
        size=9,
        fontWeight=600
    )
}

// -----------------------------------------------------------------------------
// 9. SUMMARY TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var latestDip = dipStrong ? "STRONG" : (dipMedium ? "MEDIUM" : (dipWeak ? "WEAK" : "NONE"))
    var latestPeak = peakStrong ? "STRONG" : (peakMedium ? "MEDIUM" : (peakWeak ? "WEAK" : "NONE"))
    var latestDipColor = dipStrong ? dipColor : (dipMedium ? dipColor : (dipWeak ? weakColor : "#ffffff"))
    var latestPeakColor = peakStrong ? peakColor : (peakMedium ? peakColor : (peakWeak ? weakColor : "#ffffff"))

    plotTable(
        data=[
            ["Peak & Dip Hunter — Perfected", "RSI: " + smoothRsi[0]],
            ["Dip Signal", latestDip],
            ["Peak Signal", latestPeak],
            ["RSI Thresholds", dipThresh + " / " + peakThresh],
            ["Delta Z", deltaZ[0]],
            ["Depth Ratio", depthRatio[0]],
            ["Dip Score", dipScore],
            ["Peak Score", peakScore],
            ["Dip Signals (Total)", dipSignalCount],
            ["Peak Signals (Total)", peakSignalCount],
            ["Dip Upgrades", dipUpgradeCount],
            ["Peak Upgrades", peakUpgradeCount],
            ["RSI Regime Changes", regimeChangeCount],
            ["Bars Processed", barCount]
        ],
        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
    )
}