Perfected FlowScript
RMA RSI
RMA RSI — Perfected Edition is indexed as 129_rma_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
16.5 KB
Lines
556
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Div
line 442:9
Trigger
(showShapes && enableDiv) && (bullDiv)
Value
rsi
Deps
bullDiv:var, enableDiv:input, showShapes:input
Bear Div
line 452:9
Trigger
(showShapes && enableDiv) && (bearDiv)
Value
rsi
Deps
bearDiv:var, enableDiv:input, showShapes:input
Hidden Bull
line 462:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBullDiv)
Value
rsi
Deps
enableDiv:input, hiddenBullDiv:var, showHidden:input, showShapes:input
Hidden Bear
line 472:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBearDiv)
Value
rsi
Deps
enableDiv:input, hiddenBearDiv:var, showHidden:input, showShapes:input
Cross Up
line 486:9
Trigger
(showShapes) && (crossUp)
Value
signal
Deps
crossUp:var, showShapes:input
Cross Down
line 496:9
Trigger
(showShapes) && (crossDown)
Value
signal
Deps
crossDown:var, showShapes:input
OB Penetrate
line 506:9
Trigger
(showShapes) && (obPenetrate)
Value
dynOb
Deps
obPenetrate:var, showShapes:input
OS Penetrate
line 516:9
Trigger
(showShapes) && (osPenetrate)
Value
dynOs
Deps
osPenetrate:var, showShapes:input
129_rma_rsi.flowscript
source path: kscripts/perfected/129_rma_rsi.flowscript · sha256:cb409e8b2e41d671a510a07e2b09402206d362c795b385227817ff68409eeadf
//@version=2
// ============================================================================
// RMA RSI — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #rsi, #rma, #wilder, #divergence, #momentum, #meanreversion
//
// Production-grade RSI momentum oscillator with Wilder's canonical RMA
// smoothing, full stateful divergence detection, dynamic volatility-adjusted
// overbought/oversold zones, multi-regime color coding, and comprehensive
// fill / shape / ribbon 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 = RMA(gain, N) /
// RMA(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.
// ============================================================================
define(
title="RMA RSI — 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 (Wilder RMA)",
constraints={min: 2, max: 50, step: 1},
group="RSI Settings"
)
var signalLen = input(
name="signalLen",
type="number",
defaultValue=9,
label="Signal Line EMA Length",
constraints={min: 2, max: 50, step: 1},
group="RSI Settings"
)
// --- 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 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 showBands = input(
name="showBands",
type="boolean",
defaultValue=true,
label="Show OB/OS Zones",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal Line (EMA of RSI)",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show RSI / 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"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bull Color",
group="Display"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bear Color",
group="Display"
)
var signalColor = input(
name="signalColor",
type="color",
defaultValue="#ffeb3b",
label="Signal Line Color",
group="Display"
)
var divBullColor = input(
name="divBullColor",
type="color",
defaultValue="#00e676",
label="Bullish Divergence Color",
group="Display"
)
var divBearColor = input(
name="divBearColor",
type="color",
defaultValue="#ff5252",
label="Bearish Divergence Color",
group="Display"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. RMA RSI — canonical Wilder implementation
// -----------------------------------------------------------------------------
// RSI = 100 − [100 / (1 + RS)] where RS = Average Gain / Average Loss
// Per Wilder (1978), RMA uses alpha = 1/N: RMA_t = (RMA_{t-1}*(N-1) + X_t) / N
// Seeded with SMA over the first N periods.
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
// Wilder RMA (also known as SMMA/RMA): alpha = 1/period
static avgGain = 0.0
static avgLoss = 0.0
static rmaSeeded = false
if (!rmaSeeded) {
// On first real bar after NaN guard, seed with SMA
if (barIndex >= rsiLen - 1) {
avgGain = sma(gain, rsiLen)
avgLoss = sma(loss, rsiLen)
rmaSeeded = true
}
}
if (rmaSeeded) {
avgGain = (nz(avgGain) * (rsiLen - 1) + gain) / rsiLen
avgLoss = (nz(avgLoss) * (rsiLen - 1) + loss) / rsiLen
}
// Guard against division by zero
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsi = 100 - (100 / (1 + rs))
// -----------------------------------------------------------------------------
// 4. SIGNAL LINE & MOMENTUM
// -----------------------------------------------------------------------------
timeseries signal = ema(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)
var regimeBull = rsi > signal && rsi > 50
var regimeBear = rsi < signal && rsi < 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 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. 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 = rsi[0]
prevPxLow = bars.low[0]
prevRsiLow = rsi[0]
prevPxHighLow = bars.high[0]
prevRsiHighLow = rsi[0]
prevPxLowHigh = bars.low[0]
prevRsiLowHigh = rsi[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=rsi, period=divLookback)
if (bars.high[0] > prevPxHigh) {
if (rsi[0] < prevRsiHigh) {
bearDiv = true
}
prevPxHigh = bars.high[0]
prevRsiHigh = rsi[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=rsi, period=divLookback)
if (bars.low[0] < prevPxLow) {
if (rsi[0] > prevRsiLow) {
bullDiv = true
}
prevPxLow = bars.low[0]
prevRsiLow = rsi[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 (rsi[0] < prevRsiLow) {
hiddenBullDiv = true
}
}
// Hidden bearish: price makes a lower high vs prior high
if (bars.high[0] < prevPxHigh && bars.low[0] > prevPxLow) {
if (rsi[0] > prevRsiHigh) {
hiddenBearDiv = true
}
}
}
}
// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of RSI and signal
var crossUp = rsi > signal && rsi[1] <= signal[1]
var crossDown = rsi < signal && rsi[1] >= signal[1]
// OB / OS penetrations (using dynamic or static thresholds)
var obPenetrate = rsi > dynOb && rsi[1] <= dynOb
var osPenetrate = rsi < dynOs && rsi[1] >= dynOs
// OB / OS exit (return to neutral zone)
var obExit = rsi < dynOb && rsi[1] >= dynOb
var osExit = rsi > dynOs && rsi[1] <= dynOs
// -----------------------------------------------------------------------------
// 9. 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)
// Fill between OB and OS zones for the neutral band
plotLine(
value=[dynOb, dynOs],
width=1,
colors=[transparency(bearColor, 10), transparency(bullColor, 10)],
fill=true,
label=["OB Zone", "OS Zone"],
desc=["Overbought zone boundary", "Oversold zone boundary"]
)
}
// --- RSI Line (regime-colored) ---
plotLine(
value=rsi,
width=2,
colors=[regimeColor],
label=["RMA RSI"],
desc=["RMA RSI (Wilder " + rsiLen + ") — canonical momentum oscillator"]
)
// --- Signal Line ---
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=[signalColor],
label=["Signal EMA"],
desc=["EMA of RSI (" + signalLen + ") — momentum signal line"]
)
}
// --- RSI / Signal Fill ---
if (showFill && 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=["RMA RSI", "Signal EMA"],
desc=["Fill between RMA RSI and signal EMA"]
)
}
// --- 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 RMA RSI minus signal EMA"]
)
}
// --- Divergence Shapes ---
if (showShapes && enableDiv) {
if (bullDiv) {
plotShape(
value=rsi,
shape="triangleup",
colorIndex=divBullColor,
width=2,
label=["Bull Div"],
desc=["Bullish regular divergence: price lower low, RSI higher low"]
)
}
if (bearDiv) {
plotShape(
value=rsi,
shape="triangledown",
colorIndex=divBearColor,
width=2,
label=["Bear Div"],
desc=["Bearish regular divergence: price higher high, RSI lower high"]
)
}
if (showHidden && hiddenBullDiv) {
plotShape(
value=rsi,
shape="arrowup",
colorIndex=divBullColor,
width=1,
label=["Hidden Bull"],
desc=["Hidden bullish divergence: price higher low, RSI lower low"]
)
}
if (showHidden && hiddenBearDiv) {
plotShape(
value=rsi,
shape="arrowdown",
colorIndex=divBearColor,
width=1,
label=["Hidden Bear"],
desc=["Hidden bearish divergence: price lower high, RSI higher high"]
)
}
}
// --- Alert Shapes (crossovers, OB/OS) ---
if (showShapes) {
if (crossUp) {
plotShape(
value=signal,
shape="circle",
colorIndex=bullColor,
width=2,
label=["Cross Up"],
desc=["RMA RSI crossed above signal EMA"]
)
}
if (crossDown) {
plotShape(
value=signal,
shape="circle",
colorIndex=bearColor,
width=2,
label=["Cross Down"],
desc=["RMA RSI crossed below signal EMA"]
)
}
if (obPenetrate) {
plotShape(
value=dynOb,
shape="xcross",
colorIndex=bearColor,
width=2,
label=["OB Penetrate"],
desc=["RSI entered overbought zone (RSI > " + dynOb + ")"]
)
}
if (osPenetrate) {
plotShape(
value=dynOs,
shape="xcross",
colorIndex=bullColor,
width=2,
label=["OS Penetrate"],
desc=["RSI entered oversold zone (RSI < " + dynOs + ")"]
)
}
}
// -----------------------------------------------------------------------------
// 10. 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=[
["RMA RSI — Perfected", regimeText],
["RMA RSI", rsi[0]],
["Signal", signal[0]],
["Momentum", hist[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
)
}