MM Flow
FlowScripts

Perfected FlowScript

Stochastic RSI (StochRSI)

Stochastic RSI (StochRSI) — Perfected Edition is indexed as 132_stochastic_rsi_stochrsi.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

19.3 KB

Lines

667

Native Signal Candidates

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

10/10 guarded

Bull Div

line 527:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

k

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 537:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

k

Deps

bearDiv:var, enableDiv:input, showShapes:input

Hidden Bull

line 547:9

Trigger

(showShapes && enableDiv) && (showHidden && hiddenBullDiv)

Value

k

Deps

enableDiv:input, hiddenBullDiv:var, showHidden:input, showShapes:input

Hidden Bear

line 557:9

Trigger

(showShapes && enableDiv) && (showHidden && hiddenBearDiv)

Value

k

Deps

enableDiv:input, hiddenBearDiv:var, showHidden:input, showShapes:input

Cross Up

line 571:9

Trigger

(showShapes) && (crossUp)

Value

d

Deps

crossUp:var, showShapes:input

Cross Down

line 581:9

Trigger

(showShapes) && (crossDown)

Value

d

Deps

crossDown:var, showShapes:input

OB Penetrate

line 591:9

Trigger

(showShapes) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showShapes:input

OS Penetrate

line 601:9

Trigger

(showShapes) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showShapes:input

Extreme OB

line 611:9

Trigger

(showShapes) && (extremeOverbought)

Value

k

Deps

extremeOverbought:var, showShapes:input

Extreme OS

line 621:9

Trigger

(showShapes) && (extremeOversold)

Value

k

Deps

extremeOversold:var, showShapes:input

132_stochastic_rsi_stochrsi.flowscript

source path: kscripts/perfected/132_stochastic_rsi_stochrsi.flowscript · sha256:7680a9904d4bf8607fb3910d1e5b9fb904d3205a34d11e161126a6f6a9cbc8ba

hash verified
//@version=2
// ============================================================================
// Stochastic RSI (StochRSI) — Perfected Edition
// Author: laegend1 (@laegend1) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #momentum, #oscillator, #overboughtoversold, #offchart, #smoothing
//
// Production-quality academically-grounded Stochastic RSI momentum oscillator.
// Applies the Stochastic formula to RSI values (Chande & Kroll 1994) for
// high-sensitivity boundary-forced oscillation between 0 and 100. Implements
// dual-line %K/%D smoothing, dynamic overbought/oversold zones, full stateful
// divergence detection, regime-based fill, and comprehensive shape/histogram
// visualization.
//
// Research papers underpinning this design:
//  1. Chande & Kroll (1994), "The New Technical Trader": StochRSI origin.
//     StochRSI = (RSI − RSI_low) / (RSI_high − RSI_low) forcing oscillation
//     between 0-100 boundaries, significantly more responsive than raw RSI.
//  2. 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.
//  3. Lane (1950s), Stochastic Oscillator: "momentum changes direction before
//     price." %K = 100 × (Close − Low_n) / (High_n − Low_n); %D = SMA(%K, 3).
//  4. Brock, Lakonishok & LeBaron (1992): comprehensive early academic study
//     of technical trading rules. Found oscillator crossovers significantly
//     outperformed cash benchmarks, validating dual-line signal architecture.
//  5. Hutabarat, Sadalia & Irawati (2025): multi-indicator accuracy comparison
//     found MACD 89%, Stochastic 81%, RSI 79%. StochRSI combines both.
//  6. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
//     as a leading reversal signal — price/indicator disagreement at extremes
//     precedes regime shifts.
// ============================================================================

define(
    title="Stochastic RSI (StochRSI) — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 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 useWilder = input(
    name="useWilder",
    type="boolean",
    defaultValue=true,
    label="Use Wilder Smoothing (RMA)",
    group="RSI Settings"
)

// --- Stochastic Settings ---
var stochLen = input(
    name="stochLen",
    type="number",
    defaultValue=14,
    label="Stochastic Lookback Length",
    constraints={min: 2, max: 50, step: 1},
    group="Stochastic Settings"
)
var kSmooth = input(
    name="kSmooth",
    type="number",
    defaultValue=3,
    label="%K Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Stochastic Settings"
)
var dSmooth = input(
    name="dSmooth",
    type="number",
    defaultValue=3,
    label="%D Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Stochastic Settings"
)

// --- Thresholds ---
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=80,
    label="Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=20,
    label="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 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"
)

// --- 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 showK = input(
    name="showK",
    type="boolean",
    defaultValue=true,
    label="Show %K Line",
    group="Display"
)
var showD = input(
    name="showD",
    type="boolean",
    defaultValue=true,
    label="Show %D Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show %K/%D Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zones",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal Shapes",
    group="Display"
)
var showBgColor = input(
    name="showBgColor",
    type="boolean",
    defaultValue=true,
    label="Dynamic Background Color",
    group="Display"
)

// --- Colors ---
var kColor = input(
    name="kColor",
    type="color",
    defaultValue="#26a69a",
    label="%K Color",
    group="Colors"
)
var dColor = input(
    name="dColor",
    type="color",
    defaultValue="#ef5350",
    label="%D 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"
)
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"
)

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

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 RMA (smoothed moving average) of
// gains/losses with alpha = 1/N.

timeseries diff = px - nz(px[1])
timeseries gain = diff > 0 ? diff : 0
timeseries loss = diff < 0 ? -diff : 0

timeseries avgGain = useWilder ? rma(source=gain, period=rsiLen) : sma(source=gain, period=rsiLen)
timeseries avgLoss = useWilder ? rma(source=loss, period=rsiLen) : sma(source=loss, period=rsiLen)

timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsi = 100 - (100 / (1 + rs))

// -----------------------------------------------------------------------------
// 4. STOCHASTIC OF RSI (Chande & Kroll 1994)
// -----------------------------------------------------------------------------
// StochRSI = (RSI − RSI_low) / (RSI_high − RSI_low) × 100
// Forces oscillation between 0-100 boundaries regardless of RSI range.

timeseries rsiLow = lowest(source=rsi, period=stochLen)
timeseries rsiHigh = highest(source=rsi, period=stochLen)
timeseries rsiRng = rsiHigh - rsiLow

timeseries rawK = rsiRng > 0 ? 100.0 * (rsi - rsiLow) / rsiRng : 0.0

// %K and %D smoothing per Lane's Stochastic methodology
timeseries k = sma(source=rawK, period=kSmooth)
timeseries d = sma(source=k, period=dSmooth)

// Momentum histogram (%K minus %D)
timeseries hist = k - d

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
//   Bullish: k > d AND k > 50
//   Bearish: k < d AND k < 50
//   Neutral: everything else (chop zone)

var regimeBull = k > d && k > 50
var regimeBear = k < d && k < 50
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 StochRSI standard deviation.

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

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

// -----------------------------------------------------------------------------
// 7. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, StochRSI disagrees.
// Hidden divergence: price makes higher low / lower high, StochRSI 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 = h[0]
    prevRsiHigh = k[0]
    prevPxLow = l[0]
    prevRsiLow = k[0]
    prevPxHighLow = h[0]
    prevRsiHighLow = k[0]
    prevPxLowHigh = l[0]
    prevRsiLowHigh = k[0]
}

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

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

    // --- Hidden Divergence ---
    if (showHidden) {
        // Hidden bullish: price makes a higher low, StochRSI lower low
        if (l[0] > prevPxLow && h[0] < prevPxHigh) {
            if (k[0] < prevRsiLow) {
                hiddenBullDiv = true
            }
        }
        // Hidden bearish: price makes a lower high, StochRSI higher high
        if (h[0] < prevPxHigh && l[0] > prevPxLow) {
            if (k[0] > prevRsiHigh) {
                hiddenBearDiv = true
            }
        }
    }
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of %K and %D
var crossUp = k > d && k[1] <= d[1]
var crossDown = k < d && k[1] >= d[1]

// OB / OS penetrations
var obPenetrate = k > dynOb && k[1] <= dynOb
var osPenetrate = k < dynOs && k[1] >= dynOs
var obExit = k < dynOb && k[1] >= dynOb
var osExit = k > dynOs && k[1] <= dynOs

// Extreme readings
var extremeOverbought = k > 95
var extremeOversold = k < 5

// -----------------------------------------------------------------------------
// 9. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static sessionHighK = -999999.0
static sessionLowK = 999999.0
static sessionHighD = -999999.0
static sessionLowD = 999999.0
static crossUpCount = 0
static crossDownCount = 0
static divBullCount = 0
static divBearCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (k[0] > sessionHighK) {
        sessionHighK = k[0]
    }
    if (k[0] < sessionLowK) {
        sessionLowK = k[0]
    }
    if (d[0] > sessionHighD) {
        sessionHighD = d[0]
    }
    if (d[0] < sessionLowD) {
        sessionLowD = d[0]
    }

    if (crossUp) {
        crossUpCount = crossUpCount + 1
    }
    if (crossDown) {
        crossDownCount = crossDownCount + 1
    }
    if (bullDiv || hiddenBullDiv) {
        divBullCount = divBullCount + 1
    }
    if (bearDiv || hiddenBearDiv) {
        divBearCount = divBearCount + 1
    }
}

// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------

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

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

// --- %K / %D Fill ---
if (showFill) {
    var fillBull = k > d
    plotLine(
        value=[k, d],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["%K", "%D"],
        desc=["StochRSI %K line", "StochRSI %D signal line"]
    )
}

// --- %K Line (regime-colored when in extremes) ---
if (showK) {
    var kColorFinal = (k >= dynOb || k <= dynOs) ? (k >= dynOb ? bearColor : bullColor) : kColor
    plotLine(
        value=k,
        width=2,
        colors=[kColorFinal],
        label=["%K"],
        desc=["StochRSI %K (smoothed Stochastic of RSI, " + kSmooth + ")"]
    )
}

// --- %D Line ---
if (showD) {
    plotLine(
        value=d,
        width=1,
        colors=[dColor],
        label=["%D"],
        desc=["StochRSI %D (signal SMA of %K, " + dSmooth + ")"]
    )
}

// --- 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=["StochRSI Momentum"],
        desc=["Histogram of %K minus %D (momentum divergence)"]
    )
}

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

// --- Signal Shapes (crossovers, OB/OS) ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=d,
            shape="circle",
            color=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["%K crossed above %D — bullish momentum shift"]
        )
    }
    if (crossDown) {
        plotShape(
            value=d,
            shape="circle",
            color=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["%K crossed below %D — bearish momentum shift"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=dynOb,
            shape="xcross",
            color=bearColor,
            width=2,
            label=["OB Penetrate"],
            desc=["StochRSI entered overbought zone (" + dynOb + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=dynOs,
            shape="xcross",
            color=bullColor,
            width=2,
            label=["OS Penetrate"],
            desc=["StochRSI entered oversold zone (" + dynOs + ")"]
        )
    }
    if (extremeOverbought) {
        plotShape(
            value=k,
            shape="diamond",
            color=divBearColor,
            width=2,
            label=["Extreme OB"],
            desc=["StochRSI reached extreme overbought (>95) — exhaustion risk"]
        )
    }
    if (extremeOversold) {
        plotShape(
            value=k,
            shape="diamond",
            color=divBullColor,
            width=2,
            label=["Extreme OS"],
            desc=["StochRSI reached extreme oversold (<5) — accumulation zone"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. 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=[
            ["StochRSI — Perfected", regimeText],
            ["%K", k[0]],
            ["%D", d[0]],
            ["Momentum", hist[0]],
            ["RSI Raw", rsi[0]],
            [obText, osText],
            ["Session High %K", sessionHighK],
            ["Session Low %K", sessionLowK],
            ["Cross Ups", crossUpCount],
            ["Cross Downs", crossDownCount]
        ],
        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
    )
}