MM Flow
FlowScripts

Perfected FlowScript

ITC Momentum RSI

ITC Momentum RSI V2 is indexed as 160_itc_momentum_rsi.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

24.1 KB

Lines

771

Native Signal Candidates

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

10/10 guarded

Bull Div

line 633:9

Trigger

(showAlerts && enableDiv) && (bullDiv)

Value

fastRsi

Deps

bullDiv:var, enableDiv:input, showAlerts:input

Bear Div

line 643:9

Trigger

(showAlerts && enableDiv) && (bearDiv)

Value

fastRsi

Deps

bearDiv:var, enableDiv:input, showAlerts:input

Hidden Bull

line 653:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBullDiv)

Value

fastRsi

Deps

enableDiv:input, hiddenBullDiv:var, showAlerts:input, showHidden:input

Hidden Bear

line 663:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBearDiv)

Value

fastRsi

Deps

enableDiv:input, hiddenBearDiv:var, showAlerts:input, showHidden:input

Cross Up

line 677:9

Trigger

(showAlerts) && (crossUp)

Value

signal

Deps

crossUp:var, showAlerts:input

Cross Down

line 687:9

Trigger

(showAlerts) && (crossDown)

Value

signal

Deps

crossDown:var, showAlerts:input

OB Penetrate

line 697:9

Trigger

(showAlerts) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showAlerts:input

OS Penetrate

line 707:9

Trigger

(showAlerts) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showAlerts:input

Mom Cross Up

line 717:9

Trigger

(showAlerts) && (histCrossUp)

Value

0

Deps

histCrossUp:var, showAlerts:input

Mom Cross Down

line 727:9

Trigger

(showAlerts) && (histCrossDown)

Value

0

Deps

histCrossDown:var, showAlerts:input

160_itc_momentum_rsi.flowscript

source path: kscripts/perfected/160_itc_momentum_rsi.flowscript · sha256:11ba8dff157da36119e03281c7a1cb5a8f922e66f22054ce11aa23718d49eff1

hash verified
//@version=2
// ============================================================================
// ITC Momentum RSI V2 — Production-Quality Enhanced RSI with Momentum
// Author: P (@PatrikHaim)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, #rsi, #momentum, #volume, #divergence, #regime
//
// Production-quality academically-grounded enhanced RSI momentum oscillator.
// Combines centered RSI with volume-validated momentum, divergence detection,
// dynamic overbought/oversold zones, and comprehensive fill / shape / histogram
// visualization.
//
// FORMULA FOUNDATION:
// 1. Wilder's RSI: RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N) / SMA(loss, N)
//    per Wilder (1978). Original smoothing period = 14.
// 2. Momentum-Enhanced RSI: RSI_mom = RSI × (1 + λ × momentum) where λ is a
//    momentum-weighting coefficient per Jegadeesh & Titman (1993).
// 3. Volume-Weighted Momentum: M = sign(ΔP) × |ΔP| × volume / price  normalized
//    per Chordia, Roll & Subrahmanyam (2002) volume-validated move framework.
// 4. Divergence Detection: price makes higher high / lower low while RSI disagrees
//    per Murphy (1999). Regular divergence (reversal) + hidden divergence (continuation).
// 5. Dynamic OB/OS Zones: Rolling volatility-adjusted thresholds per
//    Poterba & Summers (1988) mean-reversion intensity.
//
// RESEARCH BASIS:
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI publication. RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N) /
//     SMA(loss, N). Original smoothing period = 14.
//  2. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": established momentum as a premier cross-sectional anomaly.
//     Validates RSI's momentum-measurement role.
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications": negative autocorrelation at medium horizons; supports
//     dynamic overbought/oversold thresholds calibrated to rolling volatility.
//  4. Ponnusamy & Manual (2016): experimental finding that RSI outperforms MACD
//     and Stochastic in signal reliability; multi-indicator confirmation
//     recommended. Underpins the dual-RSI + signal-line architecture.
//  5. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
//     as a leading reversal signal — price/indicator disagreement at extremes
//     precedes regime shifts.
//  6. Quong & Soudack (1989), "Money Flow Index": MFI = volume-weighted RSI.
//     Validates combining price momentum with volume pressure.
//  7. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns": volume-validated moves are more reliable predictors.
// ============================================================================

define(
    title="ITC Momentum RSI V2",
    position="offchart",
    axis=true
)

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

// --- RSI Settings ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=14,
    label="Fast RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="RSI Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=20,
    label="Slow RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="RSI Settings"
)
var useWilder = input(
    name="useWilder",
    type="boolean",
    defaultValue=true,
    label="Use Wilder Smoothing (EMA of gains/losses)",
    group="RSI Settings"
)

// --- Momentum Enhancement ---
var momFactor = input(
    name="momFactor",
    type="number",
    defaultValue=0.5,
    label="Momentum Weight Factor",
    constraints={min: 0.0, max: 2.0, step: 0.1},
    group="Momentum"
)
var useVolWeight = input(
    name="useVolWeight",
    type="boolean",
    defaultValue=true,
    label="Use Volume-Weighted Momentum",
    group="Momentum"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=14,
    label="Volume Momentum Lookback",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal SMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Smoothing"
)

// --- Thresholds ---
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=70,
    label="Static Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=30,
    label="Static Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=false,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volThreshLookback = input(
    name="volThreshLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Thresholds"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.5,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)

// --- Divergence ---
var enableDiv = input(
    name="enableDiv",
    type="boolean",
    defaultValue=true,
    label="Enable Divergence Detection",
    group="Divergence"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=10,
    label="Divergence Lookback (pivot bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)
var showHidden = input(
    name="showHidden",
    type="boolean",
    defaultValue=true,
    label="Show Hidden Divergence",
    group="Divergence"
)

// --- Display ---
var showFastSlow = input(
    name="showFastSlow",
    type="boolean",
    defaultValue=true,
    label="Show Fast & Slow RSI Lines",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show RSI Ribbon (fast/slow fill)",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill (avg/signal fill)",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showObOs = input(
    name="showObOs",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zones",
    group="Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)
var showCentered = input(
    name="showCentered",
    type="boolean",
    defaultValue=true,
    label="Show Centered RSI (shifted around zero)",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffffff",
    label="Signal Line 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 momPosColor = input(
    name="momPosColor",
    type="color",
    defaultValue="#42a5f5",
    label="Momentum Positive Color",
    group="Colors"
)
var momNegColor = input(
    name="momNegColor",
    type="color",
    defaultValue="#ffa726",
    label="Momentum Negative 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"
)

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

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

// -----------------------------------------------------------------------------
// 3. WILDER RSI — canonical implementation
// -----------------------------------------------------------------------------
// RSI = 100 − [100 / (1 + RS)] where RS = Average Gain / Average Loss
// Per Wilder (1978), the original uses a smoothed moving average of gains/losses.
// We offer both the canonical SMA-based RS and the smoothed EMA variant.

// Price change
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0

// Average gain/loss using Wilder smoothing (EMA with alpha = 1/N)
// or standard SMA per user toggle
timeseries avgGain = useWilder ? ema(source=gain, period=fastLen) : sma(source=gain, period=fastLen)
timeseries avgLoss = useWilder ? ema(source=loss, period=fastLen) : sma(source=loss, period=fastLen)

// Guard against division by zero
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries fastRaw = 100 - (100 / (1 + rs))

// Slow RSI
timeseries slowGain = change > 0 ? change : 0
timeseries slowLoss = change < 0 ? -change : 0
timeseries avgGainSlow = useWilder ? ema(source=slowGain, period=slowLen) : sma(source=slowGain, period=slowLen)
timeseries avgLossSlow = useWilder ? ema(source=slowLoss, period=slowLen) : sma(source=slowLoss, period=slowLen)
timeseries rsSlow = avgLossSlow > 0 ? avgGainSlow / avgLossSlow : 0
timeseries slowRaw = 100 - (100 / (1 + rsSlow))

// -----------------------------------------------------------------------------
// 4. VOLUME-WEIGHTED MOMENTUM (Chordia et al. 2002)
// -----------------------------------------------------------------------------
// Volume-validated momentum: signed price change weighted by relative volume.
// Inflow = positive volume × momentum; Outflow = negative volume × momentum.
// Per Quong & Soudack (1989) MFI concept and Chordia et al. (2002) volume-validation.

timeseries volAvg = sma(volume, volLookback)
timeseries volRatio = volAvg > 0 ? volume / volAvg : 1.0
timeseries signedChange = math.sign(change) * math.abs(px[0] - px[volLookback])
timeseries volMom = useVolWeight ? signedChange * volRatio / math.max(px[0], 0.0001) : signedChange / math.max(px[0], 0.0001)

// -----------------------------------------------------------------------------
// 5. MOMENTUM-ENHANCED RSI
// -----------------------------------------------------------------------------
// RSI_mom = RSI × (1 + λ × momentum) clamped to [0, 100]
// Per Jegadeesh & Titman (1993) momentum factor applied to RSI oscillator.
// Momentum factor amplifies RSI when volume-validated momentum aligns with price direction.

timeseries momFactorNorm = math.tanh(volMom * 10.0)  // bounded to [-1, +1]
timeseries fastMomRaw = fastRaw * (1.0 + momFactor * momFactorNorm)
timeseries slowMomRaw = slowRaw * (1.0 + momFactor * momFactorNorm)

// Clamp to valid RSI bounds
fastMomRaw = math.min(100.0, math.max(0.0, fastMomRaw))
slowMomRaw = math.min(100.0, math.max(0.0, slowMomRaw))

// -----------------------------------------------------------------------------
// 6. SMOOTHING & SIGNAL
// -----------------------------------------------------------------------------
timeseries fastRsi = ema(source=fastMomRaw, period=smoothLen)
timeseries slowRsi = ema(source=slowMomRaw, period=smoothLen)

// Averaged RSI (midpoint of fast and slow)
timeseries avgRsi = (fastRsi + slowRsi) / 2

// Signal SMA
timeseries signal = sma(source=avgRsi, period=signalLen)

// Momentum histogram (RSI minus signal)
timeseries hist = avgRsi - signal

// Centered RSI (shifted around zero for bipolar visualization)
timeseries rsiCentered = avgRsi - 50.0

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
//   Bullish: avgRsi > signal AND avgRsi > 50
//   Bearish: avgRsi < signal AND avgRsi < 50
//   Neutral: everything else (chop zone)

var regimeBull = avgRsi > signal && avgRsi > 50
var regimeBear = avgRsi < signal && avgRsi < 50
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

// -----------------------------------------------------------------------------
// 8. DYNAMIC THRESHOLDS
// -----------------------------------------------------------------------------
// Per Poterba & Summers (1988), mean-reversion intensity varies with volatility.
// We adjust OB/OS bands by rolling RSI standard deviation.

var rsiVol = stddev(source=avgRsi, period=volThreshLookback)
var dynOb = useDynamic ? math.min(95, obLevel + rsiVol * volMultiplier) : obLevel
var dynOs = useDynamic ? math.max(5, osLevel - rsiVol * volMultiplier) : osLevel

// Guard: ensure dynamic bands never cross
if (dynOb <= dynOs) {
    dynOb = 70
    dynOs = 30
}

// -----------------------------------------------------------------------------
// 9. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, RSI disagrees.
// Hidden divergence: price makes higher low / lower high, RSI disagrees.
// We track pivot high/low state across bars using static variables.

static prevPxHigh = -1.0
static prevRsiHigh = -1.0
static prevPxLow = -1.0
static prevRsiLow = -1.0
static prevPxHighLow = -1.0
static prevRsiHighLow = -1.0
static prevPxLowHigh = -1.0
static prevRsiLowHigh = -1.0

var bearDiv = false
var bullDiv = false
var hiddenBearDiv = false
var hiddenBullDiv = false

// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
    prevPxHigh = bars.high[0]
    prevRsiHigh = fastRsi[0]
    prevPxLow = bars.low[0]
    prevRsiLow = fastRsi[0]
    prevPxHighLow = bars.high[0]
    prevRsiHighLow = fastRsi[0]
    prevPxLowHigh = bars.low[0]
    prevRsiLowHigh = fastRsi[0]
}

if (!isLiveUpdate && enableDiv) {
    // --- Regular Bearish Divergence ---
    // Price makes a higher high; RSI makes a lower high
    var pxHigh = highest(source=bars.high, period=divLookback)
    var rsiHigh = highest(source=fastRsi, period=divLookback)
    if (bars.high[0] > prevPxHigh) {
        if (fastRsi[0] < prevRsiHigh) {
            bearDiv = true
        }
        prevPxHigh = bars.high[0]
        prevRsiHigh = fastRsi[0]
    }

    // --- Regular Bullish Divergence ---
    // Price makes a lower low; RSI makes a higher low
    var pxLow = lowest(source=bars.low, period=divLookback)
    var rsiLow = lowest(source=fastRsi, period=divLookback)
    if (bars.low[0] < prevPxLow) {
        if (fastRsi[0] > prevRsiLow) {
            bullDiv = true
        }
        prevPxLow = bars.low[0]
        prevRsiLow = fastRsi[0]
    }

    // --- Hidden Divergence ---
    // Hidden bullish: price higher low, RSI lower low
    // Hidden bearish: price lower high, RSI higher high
    if (showHidden) {
        // Hidden bullish: price makes a higher low vs prior low
        if (bars.low[0] > prevPxLow && bars.high[0] < prevPxHigh) {
            if (fastRsi[0] < prevRsiLow) {
                hiddenBullDiv = true
            }
        }
        // Hidden bearish: price makes a lower high vs prior high
        if (bars.high[0] < prevPxHigh && bars.low[0] > prevPxLow) {
            if (fastRsi[0] > prevRsiHigh) {
                hiddenBearDiv = true
            }
        }
    }
}

// -----------------------------------------------------------------------------
// 10. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of averaged RSI and signal
var crossUp = avgRsi > signal && !isnan(avgRsi[1]) && avgRsi[1] <= signal[1]
var crossDown = avgRsi < signal && !isnan(avgRsi[1]) && avgRsi[1] >= signal[1]

// OB / OS penetrations (using dynamic or static thresholds)
var obPenetrate = avgRsi > dynOb && !isnan(avgRsi[1]) && avgRsi[1] <= dynOb
var osPenetrate = avgRsi < dynOs && !isnan(avgRsi[1]) && avgRsi[1] >= dynOs

// OB / OS exit (return to neutral zone)
var obExit = avgRsi < dynOb && !isnan(avgRsi[1]) && avgRsi[1] >= dynOb
var osExit = avgRsi > dynOs && !isnan(avgRsi[1]) && avgRsi[1] <= dynOs

// Momentum histogram cross of zero
var histCrossUp = hist > 0 && !isnan(hist[1]) && hist[1] <= 0
var histCrossDown = hist < 0 && !isnan(hist[1]) && hist[1] >= 0

// -----------------------------------------------------------------------------
// 11. PLOTTING
// -----------------------------------------------------------------------------

// --- Midline ---
hline(value=50, color="#ffffff20", width=1)

// --- Centered zero line for centered RSI ---
if (showCentered) {
    hline(value=0, color="#ffffff20", width=1)
}

// --- OB / OS Zones ---
if (showObOs) {
    hline(value=dynOb, color=transparency(bearColor, 60), width=1)
    hline(value=dynOs, color=transparency(bullColor, 60), width=1)
}

// --- Fast / Slow RSI Ribbon Fill ---
if (showRibbon) {
    var ribbonBull = fastRsi > slowRsi
    plotLine(
        value=[fastRsi, slowRsi],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast RSI", "Slow RSI"],
        desc=["Fast smoothed momentum-enhanced RSI ribbon edge", "Slow smoothed momentum-enhanced RSI ribbon edge"]
    )
}

// --- Individual Fast & Slow Lines ---
if (showFastSlow) {
    plotLine(
        value=fastRsi,
        width=2,
        colors=[bullColor],
        label=["Fast RSI"],
        desc=["Fast smoothed momentum-enhanced RSI (Wilder " + fastLen + ")"]
    )
    plotLine(
        value=slowRsi,
        width=2,
        colors=[bearColor],
        label=["Slow RSI"],
        desc=["Slow smoothed momentum-enhanced RSI (Wilder " + slowLen + ")"]
    )
}

// --- Averaged RSI (regime-colored) ---
plotLine(
    value=avgRsi,
    width=2,
    colors=[regimeColor],
    label=["Avg RSI"],
    desc=["Averaged smoothed momentum-enhanced RSI (regime-colored)"]
)

// --- Centered RSI (shifted around zero) ---
if (showCentered) {
    plotLine(
        value=rsiCentered,
        width=2,
        colors=[momPosColor, momNegColor, neutralColor],
        colorIndex=rsiCentered > 0 ? 0 : (rsiCentered < 0 ? 1 : 2),
        label=["Centered RSI"],
        desc=["RSI shifted around zero (-50..+50) with momentum enhancement"]
    )
}

// --- Signal SMA ---
plotLine(
    value=signal,
    width=1,
    colors=[signalColor],
    label=["Signal SMA"],
    desc=["SMA of averaged smoothed momentum-enhanced RSI (" + signalLen + ")"]
)

// --- Signal Fill (avg RSI vs signal) ---
if (showSignalFill) {
    var signalBull = avgRsi > signal
    plotLine(
        value=[avgRsi, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["Avg RSI", "Signal SMA"],
        desc=["Fill between averaged momentum RSI and signal SMA"]
    )
}

// --- Momentum Histogram ---
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["RSI Momentum"],
        desc=["Histogram of averaged momentum RSI minus signal SMA"]
    )
}

// --- Divergence Shapes ---
if (showAlerts && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=fastRsi,
            shape="triangleup",
            color=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish regular divergence: price lower low, RSI higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=fastRsi,
            shape="triangledown",
            color=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish regular divergence: price higher high, RSI lower high"]
        )
    }
    if (showHidden && hiddenBullDiv) {
        plotShape(
            value=fastRsi,
            shape="arrowup",
            color=divBullColor,
            width=1,
            label=["Hidden Bull"],
            desc=["Hidden bullish divergence: price higher low, RSI lower low"]
        )
    }
    if (showHidden && hiddenBearDiv) {
        plotShape(
            value=fastRsi,
            shape="arrowdown",
            color=divBearColor,
            width=1,
            label=["Hidden Bear"],
            desc=["Hidden bearish divergence: price lower high, RSI higher high"]
        )
    }
}

// --- Alert Shapes (crossovers, OB/OS, momentum zero-cross) ---
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="circle",
            color=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["Averaged momentum RSI crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="circle",
            color=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["Averaged momentum RSI crossed below signal SMA"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=dynOb,
            shape="xcross",
            color=bearColor,
            width=2,
            label=["OB Penetrate"],
            desc=["Price entered overbought zone (RSI > " + dynOb + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=dynOs,
            shape="xcross",
            color=bullColor,
            width=2,
            label=["OS Penetrate"],
            desc=["Price entered oversold zone (RSI < " + dynOs + ")"]
        )
    }
    if (histCrossUp) {
        plotShape(
            value=0,
            shape="triangleup",
            color=extremeBidColor,
            width=2,
            label=["Mom Cross Up"],
            desc=["Momentum histogram crossed above zero — bullish thrust"]
        )
    }
    if (histCrossDown) {
        plotShape(
            value=0,
            shape="triangledown",
            color=extremeAskColor,
            width=2,
            label=["Mom Cross Down"],
            desc=["Momentum histogram crossed below zero — bearish thrust"]
        )
    }
}

// -----------------------------------------------------------------------------
// 12. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
    var obText = useDynamic ? "Dynamic OB: " + dynOb : "Static OB: " + obLevel
    var osText = useDynamic ? "Dynamic OS: " + dynOs : "Static OS: " + osLevel

    plotTable(
        data=[
            ["ITC Momentum RSI V2", regimeText],
            ["Fast RSI", fastRsi[0]],
            ["Slow RSI", slowRsi[0]],
            ["Avg RSI", avgRsi[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            ["Centered RSI", rsiCentered[0]],
            [obText, osText]
        ],
        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
    )
}