Perfected FlowScript
Rate of Change
Rate of Change Pro is indexed as 169_rate_of_change.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
15.8 KB
Lines
544
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Cross Up
line 430:9
Trigger
(showShapes) && (crossUp)
Value
signal
Deps
crossUp:var, showShapes:input
Cross Down
line 440:9
Trigger
(showShapes) && (crossDown)
Value
signal
Deps
crossDown:var, showShapes:input
Zero Cross+
line 450:9
Trigger
(showShapes) && (zeroCrossUp)
Value
0
Deps
showShapes:input, zeroCrossUp:var
Zero Cross-
line 460:9
Trigger
(showShapes) && (zeroCrossDown)
Value
0
Deps
showShapes:input, zeroCrossDown:var
Extreme High
line 470:9
Trigger
(showShapes) && (extremeHighHit)
Value
roc
Deps
extremeHighHit:var, showShapes:input
Extreme Low
line 480:9
Trigger
(showShapes) && (extremeLowHit)
Value
roc
Deps
extremeLowHit:var, showShapes:input
Z-Extreme+
line 490:9
Trigger
(showShapes) && (zExtremeUp)
Value
zScore * 5.0
Deps
showShapes:input, zExtremeUp:var
Z-Extreme-
line 500:9
Trigger
(showShapes) && (zExtremeDown)
Value
zScore * 5.0
Deps
showShapes:input, zExtremeDown:var
169_rate_of_change.flowscript
source path: kscripts/perfected/169_rate_of_change.flowscript · sha256:c182e352f691da32de48f34b62e9aadb981a009050869c3ca42dc1c46e68dd50
//@version=2
// ============================================================================
// Rate of Change Pro — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #roc, #rateofchange, #momentum, #oscillator, #regime
//
// Production-quality academically-grounded Rate of Change momentum oscillator.
// Implements canonical RoC with signal-line confirmation, z-score normalization,
// dynamic regime detection, comprehensive fill/shape/histogram visualization,
// and session-level static tracking.
//
// Research papers underpinning this design:
// 1. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
// Losers": established momentum as a premier cross-sectional anomaly.
// Validates RoC's role as a direct momentum gauge.
// 2. Khand et al. (2019), "The Performance of EMA, MACD, RSI and Momentum
// Trading Rules": momentum variants show substantial prognostic capability.
// Supports RoC + signal-line architecture for confirmation.
// 3. Daniel & Moskowitz (2013), "Momentum Crashes": momentum strategies
// experience infrequent strong negative returns. Underpins the need for
// regime detection and z-score normalization to flag crash regimes.
// 4. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
// autocorrelation at medium horizons; supports dynamic thresholds
// calibrated to rolling volatility.
// 5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// z-score event triggers at ±1σ, ±2σ for statistical rarity detection.
// ============================================================================
define(
title="Rate of Change Pro",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- ROC Settings ---
var rocLen = input(
name="rocLen",
type="number",
defaultValue=14,
label="RoC Lookback Length",
constraints={min: 2, max: 100, step: 1},
group="RoC Settings"
)
var src = input(
name="src",
type="select",
defaultValue="close",
label="Source",
options=["close", "open", "high", "low", "hl2", "hlc3"],
group="RoC Settings"
)
// --- Signal Line ---
var signalLen = input(
name="signalLen",
type="number",
defaultValue=9,
label="Signal SMA Length",
constraints={min: 2, max: 50, step: 1},
group="Signal"
)
var signalType = input(
name="signalType",
type="select",
defaultValue="SMA",
label="Signal MA Type",
options=["SMA", "EMA", "WMA"],
group="Signal"
)
// --- Smoothing ---
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="RoC EMA Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Smoothing"
)
// --- Z-Score ---
var zScoreWindow = input(
name="zScoreWindow",
type="number",
defaultValue=20,
label="Z-Score Lookback",
constraints={min: 5, max: 100, step: 1},
group="Z-Score"
)
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Z-Score"
)
var zScoreThresh = input(
name="zScoreThresh",
type="number",
defaultValue=2.0,
label="Z-Score Extreme Threshold",
constraints={min: 1.0, max: 4.0, step: 0.1},
group="Z-Score"
)
// --- Thresholds ---
var accelThresh = input(
name="accelThresh",
type="number",
defaultValue=5.0,
label="Acceleration Threshold (%)",
constraints={min: 1.0, max: 20.0, step: 0.5},
group="Thresholds"
)
var extremeRocHigh = input(
name="extremeRocHigh",
type="number",
defaultValue=15.0,
label="Extreme High RoC (%)",
constraints={min: 5.0, max: 50.0, step: 1.0},
group="Thresholds"
)
var extremeRocLow = input(
name="extremeRocLow",
type="number",
defaultValue=-15.0,
label="Extreme Low RoC (%)",
constraints={min: -50.0, max: -5.0, step: 1.0},
group="Thresholds"
)
// --- Display ---
var showSignalFill = input(
name="showSignalFill",
type="boolean",
defaultValue=true,
label="Show RoC vs Signal Fill",
group="Display"
)
var showZeroFill = input(
name="showZeroFill",
type="boolean",
defaultValue=true,
label="Show Zero-Line 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 Signal Shapes",
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="#ffa726",
label="Signal Line Color",
group="Colors"
)
var neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var zScoreColor = input(
name="zScoreColor",
type="color",
defaultValue="#42a5f5",
label="Z-Score 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
if (isnan(px[0])) {
return
}
// Source selection
timeseries source = (src == "close") ? px
: (src == "open") ? bars.open
: (src == "high") ? bars.high
: (src == "low") ? bars.low
: (src == "hl2") ? (bars.high + bars.low) / 2.0
: (bars.high + bars.low + bars.close) / 3.0
// -----------------------------------------------------------------------------
// 3. RATE OF CHANGE — canonical implementation
// -----------------------------------------------------------------------------
// RoC = 100 × (Close − Close[n]) / Close[n]
// Direct momentum gauge per Jegadeesh & Titman (1993).
// Zero-centered: positive = price higher than n bars ago; negative = lower.
var safeDenom = math.max(source[rocLen], 0.0001)
timeseries rocRaw = 100.0 * (source - source[rocLen]) / safeDenom
// Smoothing (EMA noise-reduction)
timeseries roc = ema(rocRaw, smoothLen)
// -----------------------------------------------------------------------------
// 4. SIGNAL LINE
// -----------------------------------------------------------------------------
// Signal MA of RoC provides a smoother confirmation reference.
// RoC above signal = acceleration; below = deceleration.
timeseries signal = (signalType == "EMA") ? ema(roc, signalLen)
: (signalType == "SMA") ? sma(roc, signalLen)
: wma(roc, signalLen)
// Momentum histogram (RoC minus signal)
timeseries hist = roc - signal
// -----------------------------------------------------------------------------
// 5. Z-SCORE NORMALIZATION (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// Standardizes RoC to identify statistically extreme readings.
timeseries zMean = sma(roc, zScoreWindow)
timeseries zStd = stddev(roc, zScoreWindow)
timeseries zScore = zStd > 0 ? (roc - zMean) / zStd : 0.0
// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
// Bullish: roc > signal AND roc > 0 (accelerating above zero)
// Bearish: roc < signal AND roc < 0 (decelerating below zero)
// Neutral: everything else (chop or transition)
var regimeBull = roc > signal && roc > 0
var regimeBear = roc < signal && roc < 0
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// Extreme regime flags
var extremeBull = roc >= extremeRocHigh
var extremeBear = roc <= extremeRocLow
// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and signal crosses.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighRoc = -999999.0
static sessionLowRoc = 999999.0
static extremeHighCount = 0
static extremeLowCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (roc > sessionHighRoc) {
sessionHighRoc = roc
}
if (roc < sessionLowRoc) {
sessionLowRoc = roc
}
var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
if (lastRegime != currentRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeBull) {
extremeHighCount = extremeHighCount + 1
}
if (extremeBear) {
extremeLowCount = extremeLowCount + 1
}
}
// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of RoC and signal line
var crossUp = roc > signal && roc[1] <= signal[1]
var crossDown = roc < signal && roc[1] >= signal[1]
// Zero-line crosses
var zeroCrossUp = roc > 0 && roc[1] <= 0
var zeroCrossDown = roc < 0 && roc[1] >= 0
// Extreme penetrations
var extremeHighHit = roc >= extremeRocHigh && roc[1] < extremeRocHigh
var extremeLowHit = roc <= extremeRocLow && roc[1] > extremeRocLow
// Z-score extremes
var zExtremeUp = zScore >= zScoreThresh && zScore[1] < zScoreThresh
var zExtremeDown = zScore <= -zScoreThresh && zScore[1] > -zScoreThresh
// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------
// --- Zero line ---
hline(value=0, color="#ffffff20", width=1)
// --- Acceleration thresholds ---
hline(value=accelThresh, color=opacity(bullColor, 20), width=1)
hline(value=-accelThresh, color=opacity(bearColor, 20), width=1)
// --- RoC vs Signal Fill ---
if (showSignalFill) {
var signalBull = roc > signal
plotLine(
value=[roc, signal],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=signalBull ? 0 : 1,
fill=true,
label=["RoC", "Signal"],
desc=["Rate of Change (smoothed)", "Signal MA of RoC"]
)
}
// --- RoC Line (regime-colored) ---
plotLine(
value=roc,
width=2,
colors=[regimeColor],
label=["RoC"],
desc=["Smoothed Rate of Change (" + rocLen + ") — regime-colored"]
)
// --- Signal Line ---
plotLine(
value=signal,
width=1,
colors=[signalColor],
label=["Signal"],
desc=["Signal MA of RoC (" + signalType + " " + signalLen + ")"]
)
// --- Zero-Line Fill (RoC vs 0) ---
if (showZeroFill) {
var zeroBull = roc > 0
plotLine(
value=[roc, 0],
width=1,
colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
colorIndex=zeroBull ? 0 : 1,
fill=true,
label=["RoC", "Zero"],
desc=["Fill between RoC and zero line"]
)
}
// --- 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=["Momentum"],
desc=["Histogram of RoC minus Signal — acceleration/deceleration"]
)
}
// --- Z-Score Line ---
if (showZScore) {
plotLine(
value=zScore * 5.0, // Scale for visual alignment
width=1,
colors=[zScoreColor],
label=["Z-Score (scaled)"],
desc=["Z-score of RoC: (RoC − μ) / σ, scaled ×5"]
)
}
// --- Signal Shapes ---
if (showShapes) {
if (crossUp) {
plotShape(
value=signal,
shape="triangleup",
color=bullColor,
width=2,
label=["Cross Up"],
desc=["RoC crossed above signal — momentum acceleration"]
)
}
if (crossDown) {
plotShape(
value=signal,
shape="triangledown",
color=bearColor,
width=2,
label=["Cross Down"],
desc=["RoC crossed below signal — momentum deceleration"]
)
}
if (zeroCrossUp) {
plotShape(
value=0,
shape="circle",
color=bullColor,
width=2,
label=["Zero Cross+"],
desc=["RoC crossed above zero — positive momentum regime"]
)
}
if (zeroCrossDown) {
plotShape(
value=0,
shape="circle",
color=bearColor,
width=2,
label=["Zero Cross-"],
desc=["RoC crossed below zero — negative momentum regime"]
)
}
if (extremeHighHit) {
plotShape(
value=roc,
shape="diamond",
color=extremeBidColor,
width=3,
label=["Extreme High"],
desc=["RoC reached extreme high level (" + extremeRocHigh + ")"]
)
}
if (extremeLowHit) {
plotShape(
value=roc,
shape="diamond",
color=extremeAskColor,
width=3,
label=["Extreme Low"],
desc=["RoC reached extreme low level (" + extremeRocLow + ")"]
)
}
if (zExtremeUp) {
plotShape(
value=zScore * 5.0,
shape="xcross",
color=zScoreColor,
width=2,
label=["Z-Extreme+"],
desc=["Z-score exceeded +" + zScoreThresh + "σ — statistical extreme"]
)
}
if (zExtremeDown) {
plotShape(
value=zScore * 5.0,
shape="xcross",
color=zScoreColor,
width=2,
label=["Z-Extreme-"],
desc=["Z-score exceeded −" + zScoreThresh + "σ — statistical extreme"]
)
}
}
// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["RoC Pro — Perfected", regimeText],
["RoC", roc[0]],
["Signal", signal[0]],
["Momentum", hist[0]],
["Z-Score", zScore[0]],
["Session High", sessionHighRoc],
["Session Low", sessionLowRoc],
["Regime Changes", regimeChangeCount],
["Extreme High Bars", extremeHighCount],
["Extreme Low Bars", extremeLowCount]
],
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
)
}