MM Flow
FlowScripts

Perfected FlowScript

default

RSI Pro Default — Perfected Edition is indexed as 334_default.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

14.5 KB

Lines

495

Native Signal Candidates

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

6/6 guarded

Cross Up

line 401:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Cross Down

line 411:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

OB Penetrate

line 421:9

Trigger

(showShapes) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showShapes:input

OS Penetrate

line 431:9

Trigger

(showShapes) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showShapes:input

OB Sustain

line 441:9

Trigger

(showShapes) && (obDuration >= 5)

Value

dynOb

Deps

obDuration:static, showShapes:input

OS Sustain

line 451:9

Trigger

(showShapes) && (osDuration >= 5)

Value

dynOs

Deps

osDuration:static, showShapes:input

334_default.flowscript

source path: kscripts/perfected/334_default.flowscript · sha256:771ad4de5d7c90623209a4d69543878c6b4c0ee63da36938163e26d29da4a2ae

hash verified
//@version=2
// ============================================================================
// RSI Pro Default — Perfected Edition
// Author: V (@vincent60) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #rsi, #momentum, #regime, #meanreversion
//
// Production-quality academically-grounded RSI momentum oscillator with
// moving-average signal line, multi-regime color coding, dynamic thresholds,
// shape markers, and comprehensive fill / histogram visualization.
//
// Research papers underpinning this design:
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI publication. RSI = 100 − [100 / (1 + RS)] where RS = Average Gain /
//     Average Loss. Original smoothing period = 14.
//  2. Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability
//     in Technical Analysis": empirically tested RSI, MACD, and Stochastic;
//     found RSI outperformed the others, though no single indicator is fully
//     reliable in isolation. Supports multi-indicator confirmation.
//  3. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": established momentum as a premier cross-sectional anomaly.
//     Validates RSI's momentum-measurement role.
//  4. 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.
//  5. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
//     and regime classification as leading reversal signals.
// ============================================================================

define(
    title="RSI Pro Default — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- RSI Settings ---
var length = input(
    name="length",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="RSI Settings"
)
var source = input(
    name="source",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close", "open", "high", "low"],
    group="RSI Settings"
)

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

// --- 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 midLevel = input(
    name="midLevel",
    type="number",
    defaultValue=50,
    label="Midline Level",
    constraints={min: 30, max: 70, step: 1},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=false,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volLookback = input(
    name="volLookback",
    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"
)

// --- Display ---
var showLevels = input(
    name="showLevels",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Levels",
    group="Display"
)
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="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 Alert Shapes",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Regime Table",
    group="Display"
)

// --- Colors ---
var rsiColor = input(
    name="rsiColor",
    type="color",
    defaultValue="#7c4dff",
    label="RSI Line Color",
    group="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"
)

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

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

// Select series source
timeseries src = px
if (source == "open") { src = bars.open }
if (source == "high") { src = bars.high }
if (source == "low")  { src = bars.low }

// -----------------------------------------------------------------------------
// 3. WILDER RSI — canonical implementation
// -----------------------------------------------------------------------------
// RSI = 100 − [100 / (1 + RS)] where RS = Average Gain / Average Loss
// Per Wilder (1978), the original uses RMA (smoothed moving average).

timeseries change = src - src[1]
timeseries gain = math.max(change, 0)
timeseries loss = math.max(-change, 0)
timeseries avgGain = rma(gain, length)
timeseries avgLoss = rma(loss, length)

// Guard against division by zero while preserving RSI's up-only and flat regimes.
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : (avgGain > 0 ? 100.0 : 1.0)
timeseries rsi = 100 - (100 / (1 + rs))

// -----------------------------------------------------------------------------
// 4. SIGNAL LINE & MOMENTUM
// -----------------------------------------------------------------------------
timeseries signal = sma(source=rsi, period=signalLen)
timeseries hist = rsi - signal

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
//   Bullish: RSI > signal AND RSI > 50
//   Bearish: RSI < signal AND RSI < 50
//   Neutral: everything else (chop zone)
//   Overbought: RSI > dynamic OB
//   Oversold: RSI < dynamic OS

var regimeBull = rsi > signal && rsi > midLevel
var regimeBear = rsi < signal && rsi < midLevel
var regimeNeutral = !regimeBull && !regimeBear

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

// -----------------------------------------------------------------------------
// 6. 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=rsi, period=volLookback)
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
}

// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Session-level persistence for regime transitions, OB/OS duration, and extremes.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRsi = -999999.0
static sessionLowRsi = 999999.0
static lastBarIndex = 0
static obDuration = 0
static osDuration = 0

var currentBarIndex = bar_index[0]

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

    if (rsi > sessionHighRsi) {
        sessionHighRsi = rsi
    }
    if (rsi < sessionLowRsi) {
        sessionLowRsi = rsi
    }

    var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (rsi > dynOb) {
        obDuration = obDuration + 1
    } else {
        obDuration = 0
    }
    if (rsi < dynOs) {
        osDuration = osDuration + 1
    } else {
        osDuration = 0
    }
}

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

// OB / OS penetrations
var obPenetrate = rsi > dynOb && !isnan(rsi[1]) && rsi[1] <= dynOb
var osPenetrate = rsi < dynOs && !isnan(rsi[1]) && rsi[1] >= dynOs

// OB / OS exit
var obExit = rsi < dynOb && !isnan(rsi[1]) && rsi[1] >= dynOb
var osExit = rsi > dynOs && !isnan(rsi[1]) && rsi[1] <= dynOs

// Divergence-like: RSI makes new extreme while price disagrees
var rsiHigh = highest(source=rsi, period=10)
var rsiLow = lowest(source=rsi, period=10)

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

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

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

// --- RSI Line (regime-colored) ---
plotLine(
    value=rsi,
    width=2,
    colors=[regimeColor],
    label=["RSI"],
    desc=["Wilder RSI (" + length + ") — regime-colored"]
)

// --- Signal SMA ---
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=["#ffffff"],
        label=["Signal SMA"],
        desc=["SMA of RSI (" + signalLen + ")"]
    )
}

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

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

// --- OB / OS Flags (as subtle background bars) ---
timeseries ob = rsi > dynOb
timeseries os = rsi < dynOs

plotBar(
    value=ob ? 2 : 0,
    colors=[transparency(bearColor, 80)],
    width=1,
    label=["OB Flag"],
    desc=["Overbought flag when RSI > " + dynOb]
)
plotBar(
    value=os ? -2 : 0,
    colors=[transparency(bullColor, 80)],
    width=1,
    label=["OS Flag"],
    desc=["Oversold flag when RSI < " + dynOs]
)

// --- Alert Shapes ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="triangleup",
            color=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["RSI crossed above signal SMA — bullish momentum shift"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="triangledown",
            color=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["RSI crossed below signal SMA — bearish momentum shift"]
        )
    }
    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 (obDuration >= 5) {
        plotShape(
            value=dynOb,
            shape="diamond",
            color="#ff1744",
            width=2,
            label=["OB Sustain"],
            desc=["RSI sustained overbought for 5+ bars — exhaustion risk"]
        )
    }
    if (osDuration >= 5) {
        plotShape(
            value=dynOs,
            shape="diamond",
            color="#00e676",
            width=2,
            label=["OS Sustain"],
            desc=["RSI sustained oversold for 5+ bars — bounce potential"]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && 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=[
            ["RSI Pro Default", regimeText],
            ["RSI", rsi[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            ["Session High", sessionHighRsi],
            ["Session Low", sessionLowRsi],
            ["Regime Changes", regimeChangeCount],
            [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
    )
}