Perfected FlowScript
Rsi + Sma
RSI + SMA V2 is indexed as 305_rsi_sma.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
17.2 KB
Lines
568
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Div
line 453:9
Trigger
(showShapes && enableDiv) && (bullDiv)
Value
rsiVal
Deps
bullDiv:var, enableDiv:input, showShapes:input
Bear Div
line 463:9
Trigger
(showShapes && enableDiv) && (bearDiv)
Value
rsiVal
Deps
bearDiv:var, enableDiv:input, showShapes:input
Hidden Bull
line 473:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBullDiv)
Value
rsiVal
Deps
enableDiv:input, hiddenBullDiv:var, showHidden:input, showShapes:input
Hidden Bear
line 483:9
Trigger
(showShapes && enableDiv) && (showHidden && hiddenBearDiv)
Value
rsiVal
Deps
enableDiv:input, hiddenBearDiv:var, showHidden:input, showShapes:input
Cross Up
line 497:9
Trigger
(showShapes) && (crossUp)
Value
smaVal
Deps
crossUp:var, showShapes:input
Cross Down
line 507:9
Trigger
(showShapes) && (crossDown)
Value
smaVal
Deps
crossDown:var, showShapes:input
OB Penetrate
line 517:9
Trigger
(showShapes) && (obPenetrate)
Value
dynOb
Deps
obPenetrate:var, showShapes:input
OS Penetrate
line 527:9
Trigger
(showShapes) && (osPenetrate)
Value
dynOs
Deps
osPenetrate:var, showShapes:input
305_rsi_sma.flowscript
source path: kscripts/perfected/305_rsi_sma.flowscript · sha256:9186039ba29b8dcca2bcd9c25e0c50903c5945384606d55f89aa1144e0048827
//@version=2
// ============================================================================
// RSI + SMA V2 — Production-Quality RSI Momentum with SMA Signal
// Author: S (@Sashi Mix) | Perfected by: kScript Perfection Engineer
// Tags: CORE, #rsi, #sma, #divergence, #trend, #momentum, #regime
//
// Production-quality academically-grounded RSI momentum oscillator with
// SMA signal line, divergence detection, dynamic thresholds, fill
// visualization, and shape-marked signal events.
//
// FORMULA FOUNDATION:
// 1. Wilder RSI (1978): RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N)
// / SMA(loss, N). Canonical 14-period smoothing with Wilder EMA variant.
// 2. SMA Signal Line: SMA of RSI values acts as trend filter per Manasa &
// Reddy (2025) multi-indicator confirmation framework.
// 3. Divergence Detection: Price/RSI disagreement at extremes per Murphy
// (1999) as leading reversal signal — regular and hidden divergence.
// 4. Dynamic Thresholds: Volatility-adjusted OB/OS bands per Poterba &
// Summers (1988) mean-reversion framework.
//
// 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 RSI + SMA dual-indicator 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. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
// Moving Average": SMA offers stability and trend-direction confirmation.
// ============================================================================
define(
title="RSI + SMA V2",
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 (EMA of gains/losses)",
group="RSI Settings"
)
// --- SMA Signal ---
var smaLen = input(
name="smaLen",
type="number",
defaultValue=14,
label="SMA Signal Length",
constraints={min: 2, max: 50, step: 1},
group="SMA Signal"
)
var smoothRsi = input(
name="smoothRsi",
type="number",
defaultValue=3,
label="RSI EMA Smoothing",
constraints={min: 1, max: 20, step: 1},
group="SMA 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 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 showRsiLine = input(
name="showRsiLine",
type="boolean",
defaultValue=true,
label="Show RSI Line",
group="Display"
)
var showSmaLine = input(
name="showSmaLine",
type="boolean",
defaultValue=true,
label="Show SMA Signal Line",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show RSI/SMA 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 showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Signal Shapes",
group="Display"
)
// --- Colors ---
var rsiColor = input(
name="rsiColor",
type="color",
defaultValue="#2962ff",
label="RSI Line Color",
group="Colors"
)
var smaColor = input(
name="smaColor",
type="color",
defaultValue="#ffffff",
label="SMA Signal 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
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// 3. WILDER RSI — canonical implementation (Wilder 1978)
// ------------------------------------------------------------------------------
// RSI = 100 − [100 / (1 + RS)] where RS = Average Gain / Average Loss
// Per Wilder, 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=rsiLen) : sma(source=gain, period=rsiLen)
timeseries avgLoss = useWilder ? ema(source=loss, period=rsiLen) : sma(source=loss, period=rsiLen)
// Guard against division by zero
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
// Optional RSI smoothing
timeseries rsiVal = ema(source=rsiRaw, period=smoothRsi)
// ------------------------------------------------------------------------------
// 4. SMA SIGNAL LINE (Manasa & Reddy 2025 trend confirmation)
// ------------------------------------------------------------------------------
timeseries smaVal = sma(source=rsiVal, period=smaLen)
// Momentum histogram (RSI minus SMA signal)
timeseries hist = rsiVal - smaVal
// ------------------------------------------------------------------------------
// 5. REGIME DETECTION
// ------------------------------------------------------------------------------
// Regime classification:
// Bullish: RSI > SMA AND RSI > 50
// Bearish: RSI < SMA AND RSI < 50
// Neutral: everything else (chop zone)
var regimeBull = rsiVal > smaVal && rsiVal > 50
var regimeBear = rsiVal < smaVal && rsiVal < 50
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
// ------------------------------------------------------------------------------
// 6. DYNAMIC THRESHOLDS (Poterba & Summers 1988)
// ------------------------------------------------------------------------------
// Per Poterba & Summers, mean-reversion intensity varies with volatility.
// We adjust OB/OS bands by rolling RSI standard deviation.
var rsiVol = stddev(source=rsiVal, 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) (Murphy 1999)
// ------------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, RSI disagrees.
// Hidden divergence: price makes higher low / lower high, RSI disagrees.
static prevPxHigh = -1.0
static prevRsiHigh = -1.0
static prevPxLow = -1.0
static prevRsiLow = -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 = rsiVal[0]
prevPxLow = bars.low[0]
prevRsiLow = rsiVal[0]
}
if (!isLiveUpdate && enableDiv) {
// --- Regular Bearish Divergence ---
// Price makes a higher high; RSI makes a lower high
if (bars.high[0] > prevPxHigh) {
if (rsiVal[0] < prevRsiHigh) {
bearDiv = true
}
prevPxHigh = bars.high[0]
prevRsiHigh = rsiVal[0]
}
// --- Regular Bullish Divergence ---
// Price makes a lower low; RSI makes a higher low
if (bars.low[0] < prevPxLow) {
if (rsiVal[0] > prevRsiLow) {
bullDiv = true
}
prevPxLow = bars.low[0]
prevRsiLow = rsiVal[0]
}
// --- Hidden Divergence ---
if (showHidden) {
// Hidden bullish: price higher low, RSI lower low
if (bars.low[0] > prevPxLow && bars.high[0] < prevPxHigh) {
if (rsiVal[0] < prevRsiLow) {
hiddenBullDiv = true
}
}
// Hidden bearish: price lower high, RSI higher high
if (bars.high[0] < prevPxHigh && bars.low[0] > prevPxLow) {
if (rsiVal[0] > prevRsiHigh) {
hiddenBearDiv = true
}
}
}
}
// ------------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// ------------------------------------------------------------------------------
// Crossover / crossunder of RSI and SMA signal
var crossUp = rsiVal > smaVal && !isnan(rsiVal[1]) && rsiVal[1] <= smaVal[1]
var crossDown = rsiVal < smaVal && !isnan(rsiVal[1]) && rsiVal[1] >= smaVal[1]
// OB / OS penetrations (using dynamic or static thresholds)
var obPenetrate = rsiVal > dynOb && !isnan(rsiVal[1]) && rsiVal[1] <= dynOb
var osPenetrate = rsiVal < dynOs && !isnan(rsiVal[1]) && rsiVal[1] >= dynOs
// OB / OS exit (return to neutral zone)
var obExit = rsiVal < dynOb && !isnan(rsiVal[1]) && rsiVal[1] >= dynOb
var osExit = rsiVal > dynOs && !isnan(rsiVal[1]) && rsiVal[1] <= dynOs
// ------------------------------------------------------------------------------
// 9. PLOTTING
// ------------------------------------------------------------------------------
// --- Midline ---
hline(value=50, 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)
}
// --- RSI Line (regime-colored) ---
if (showRsiLine) {
plotLine(
value=rsiVal,
width=2,
colors=[regimeColor],
label=["RSI"],
desc=["Wilder RSI (" + rsiLen + ") with EMA smoothing — regime-colored"]
)
}
// --- SMA Signal Line ---
if (showSmaLine) {
plotLine(
value=smaVal,
width=1,
colors=[smaColor],
label=["SMA Signal"],
desc=["SMA signal line of RSI (" + smaLen + ") — trend filter"]
)
}
// --- RSI / SMA Fill ---
if (showFill) {
var fillBull = rsiVal > smaVal
plotLine(
value=[rsiVal, smaVal],
width=1,
colors=[transparency(bullColor, 25), transparency(bearColor, 25)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["RSI", "SMA"],
desc=["Fill between RSI and SMA signal line — bullish when RSI above 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 RSI minus SMA signal — momentum strength and direction"]
)
}
// --- Divergence Shapes ---
if (showShapes && enableDiv) {
if (bullDiv) {
plotShape(
value=rsiVal,
shape="triangleup",
color=divBullColor,
width=2,
label=["Bull Div"],
desc=["Bullish regular divergence: price lower low, RSI higher low"]
)
}
if (bearDiv) {
plotShape(
value=rsiVal,
shape="triangledown",
color=divBearColor,
width=2,
label=["Bear Div"],
desc=["Bearish regular divergence: price higher high, RSI lower high"]
)
}
if (showHidden && hiddenBullDiv) {
plotShape(
value=rsiVal,
shape="arrowup",
color=divBullColor,
width=1,
label=["Hidden Bull"],
desc=["Hidden bullish divergence: price higher low, RSI lower low"]
)
}
if (showHidden && hiddenBearDiv) {
plotShape(
value=rsiVal,
shape="arrowdown",
color=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=smaVal,
shape="circle",
color=bullColor,
width=2,
label=["Cross Up"],
desc=["RSI crossed above SMA signal line — bullish momentum shift"]
)
}
if (crossDown) {
plotShape(
value=smaVal,
shape="circle",
color=bearColor,
width=2,
label=["Cross Down"],
desc=["RSI crossed below SMA signal line — bearish momentum shift"]
)
}
if (obPenetrate) {
plotShape(
value=dynOb,
shape="xcross",
color=bearColor,
width=2,
label=["OB Penetrate"],
desc=["RSI entered overbought zone (RSI > " + dynOb + ")"]
)
}
if (osPenetrate) {
plotShape(
value=dynOs,
shape="xcross",
color=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=[
["RSI + SMA V2", regimeText],
["RSI", rsiVal[0]],
["SMA Signal", smaVal[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
)
}