Perfected FlowScript
Momentum
Momentum [Perfected] is indexed as 103_momentum.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
540
Native Signal Candidates
10 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Zero Cross Up
line 406:9
Trigger
(showAlertShapes) && (zeroCrossUp)
Value
avgMom
Deps
showAlertShapes:input, zeroCrossUp:var
Zero Cross Down
line 416:9
Trigger
(showAlertShapes) && (zeroCrossDown)
Value
avgMom
Deps
showAlertShapes:input, zeroCrossDown:var
Signal Cross Up
line 426:9
Trigger
(showAlertShapes) && (signalCrossUp)
Value
signal
Deps
showAlertShapes:input, signalCrossUp:var
Signal Cross Down
line 436:9
Trigger
(showAlertShapes) && (signalCrossDown)
Value
signal
Deps
showAlertShapes:input, signalCrossDown:var
Fast>Slow
line 446:9
Trigger
(showAlertShapes) && (fastSlowCrossUp)
Value
momFastSm
Deps
fastSlowCrossUp:var, showAlertShapes:input
Fast<Slow
line 456:9
Trigger
(showAlertShapes) && (fastSlowCrossDown)
Value
momFastSm
Deps
fastSlowCrossDown:var, showAlertShapes:input
Z-Extreme High
line 466:9
Trigger
(showAlertShapes) && (zExtremeHigh)
Value
zscore
Deps
showAlertShapes:input, zExtremeHigh:var
Z-Extreme Low
line 476:9
Trigger
(showAlertShapes) && (zExtremeLow)
Value
zscore
Deps
showAlertShapes:input, zExtremeLow:var
Momentum Flip Up
line 486:9
Trigger
(showAlertShapes) && (momFlipUp)
Value
avgMom
Deps
momFlipUp:var, showAlertShapes:input
Momentum Flip Down
line 496:9
Trigger
(showAlertShapes) && (momFlipDown)
Value
avgMom
Deps
momFlipDown:var, showAlertShapes:input
103_momentum.flowscript
source path: kscripts/perfected/103_momentum.flowscript · sha256:ae6e8aad072968ef968d7152b7d73630d1184d1800a2ec6724193b74550622d7
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Momentum Oscillator [Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #momentum, #roc, #oscillator, #zscore, #regime, #momentumcrashes
//
// Production-quality dual-period momentum oscillator with z-score normalization,
// regime detection, color-coded histogram with fill, comprehensive shape markers,
// and dynamic threshold adaptation. Uses static variables for stateful tracking
// of prior momentum values and cross detection.
//
// Research papers underpinning this design:
// - Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers":
// seminal momentum anomaly; past 3-12 month returns predict future returns.
// - Khand et al. (2019), "Performance of EMA, MACD, RSI and Momentum Trading
// Rules": Momentum = Close(t) − Close(t−n); profitable after transaction costs.
// - Daniel & Moskowitz (2013), "Momentum Crashes": momentum crashes are
// forecastable; occur after market declines, high vol; dynamic momentum based
// on forecasts of mean and variance generates ~2× Sharpe ratio.
// - Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing": time-series momentum profitable since 1880 across all major
// asset classes.
// - Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
// autocorrelation at medium horizons; supports dynamic threshold calibration.
// ============================================================================
define(
title="Momentum [Perfected]",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// User Inputs — grouped with constraints
// ---------------------------------------------------------------------------
// --- Momentum Settings ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=10,
label="Fast Momentum Length",
constraints={min: 2, max: 100, step: 1},
group="Momentum Settings"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=20,
label="Slow Momentum Length",
constraints={min: 2, max: 100, step: 1},
group="Momentum Settings"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="EMA Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Momentum Settings"
)
var signalLen = input(
name="signalLen",
type="number",
defaultValue=14,
label="Signal SMA Length",
constraints={min: 2, max: 50, step: 1},
group="Momentum Settings"
)
// --- Z-Score ---
var showZscore = input(
name="showZscore",
type="boolean",
defaultValue=true,
label="Show Z-Score",
group="Z-Score"
)
var zLookback = input(
name="zLookback",
type="number",
defaultValue=50,
label="Z-Score Lookback",
constraints={min: 10, max: 200, step: 5},
group="Z-Score"
)
var zExtreme = input(
name="zExtreme",
type="number",
defaultValue=2.0,
label="Extreme Z-Score Threshold",
constraints={min: 1.0, max: 4.0, step: 0.25},
group="Z-Score"
)
// --- Dynamic 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 showFastSlow = input(
name="showFastSlow",
type="boolean",
defaultValue=true,
label="Show Fast & Slow Momentum",
group="Display"
)
var showRibbon = input(
name="showRibbon",
type="boolean",
defaultValue=true,
label="Show Momentum Ribbon",
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 showAlertShapes = input(
name="showAlertShapes",
type="boolean",
defaultValue=true,
label="Show Alert Shapes",
group="Display"
)
var shapeSize = input(
name="shapeSize",
type="number",
defaultValue=2,
label="Shape Size",
constraints={min: 1, max: 4, step: 1},
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="#ffffff",
label="Signal Line Color",
group="Colors"
)
var slowColor = input(
name="slowColor",
type="color",
defaultValue="#ff9800",
label="Slow Momentum Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// Data Sources & NaN Guard
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// ---------------------------------------------------------------------------
// Momentum Computation (Rate of Change: Close(t) − Close(t−n))
// ---------------------------------------------------------------------------
// Fast momentum
timeseries momFast = px - px[fastLen]
// Slow momentum
timeseries momSlow = px - px[slowLen]
// Smoothing
timeseries momFastSm = ema(source=momFast, period=smoothLen)
timeseries momSlowSm = ema(source=momSlow, period=smoothLen)
// Averaged momentum (midpoint of fast and slow)
timeseries avgMom = (momFastSm + momSlowSm) / 2
// Signal SMA
timeseries signal = sma(source=avgMom, period=signalLen)
// Momentum histogram (avg momentum minus signal)
timeseries hist = avgMom - signal
// ---------------------------------------------------------------------------
// Z-Score Normalization
// ---------------------------------------------------------------------------
timeseries zMean = sma(source=avgMom, period=zLookback)
timeseries zStd = stddev(source=avgMom, period=zLookback)
timeseries zscore = zStd > 0 ? (avgMom - zMean) / zStd : 0
// ---------------------------------------------------------------------------
// Dynamic Thresholds (volatility-adjusted)
// ---------------------------------------------------------------------------
var momVol = stddev(source=avgMom, period=volLookback)
var dynUpper = useDynamic ? momVol * volMultiplier : 0
var dynLower = useDynamic ? -momVol * volMultiplier : 0
// ---------------------------------------------------------------------------
// Regime Detection
// ---------------------------------------------------------------------------
// Regime classification:
// Bullish: avgMom > signal AND avgMom > 0
// Bearish: avgMom < signal AND avgMom < 0
// Neutral: everything else (chop zone)
var regimeBull = avgMom > signal && avgMom > 0
var regimeBear = avgMom < signal && avgMom < 0
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
// ---------------------------------------------------------------------------
// Static Variables for Stateful Tracking
// ---------------------------------------------------------------------------
static prevMomFast = 0.0
static prevMomSlow = 0.0
static prevAvgMom = 0.0
// Initialize
if (prevAvgMom == 0.0 && !isnan(avgMom[0])) {
prevMomFast = momFastSm[0]
prevMomSlow = momSlowSm[0]
prevAvgMom = avgMom[0]
}
// ---------------------------------------------------------------------------
// Alert Conditions
// ---------------------------------------------------------------------------
// Zero-line cross
var zeroCrossUp = avgMom > 0 && avgMom[1] <= 0
var zeroCrossDown = avgMom < 0 && avgMom[1] >= 0
// Signal cross
var signalCrossUp = avgMom > signal && avgMom[1] <= signal[1]
var signalCrossDown = avgMom < signal && avgMom[1] >= signal[1]
// Fast/Slow cross
var fastSlowCrossUp = momFastSm > momSlowSm && momFastSm[1] <= momSlowSm[1]
var fastSlowCrossDown = momFastSm < momSlowSm && momFastSm[1] >= momSlowSm[1]
// Z-Score extremes
var zExtremeHigh = zscore > zExtreme && zscore[1] <= zExtreme
var zExtremeLow = zscore < -zExtreme && zscore[1] >= -zExtreme
// Momentum flip (direction change)
var momFlipUp = avgMom > 0 && avgMom[1] < 0
var momFlipDown = avgMom < 0 && avgMom[1] > 0
// Update previous values
prevMomFast = momFastSm[0]
prevMomSlow = momSlowSm[0]
prevAvgMom = avgMom[0]
// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------
// --- Zero Line ---
hline(value=0, color="#ffffff20", width=1)
// --- Dynamic Thresholds ---
if (useDynamic) {
hline(value=dynUpper, color=transparency(bearColor, 60), width=1)
hline(value=dynLower, color=transparency(bullColor, 60), width=1)
}
// --- Fast / Slow Momentum Ribbon Fill ---
if (showRibbon) {
var ribbonBull = momFastSm > momSlowSm
plotLine(
value=[momFastSm, momSlowSm],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
colorIndex=ribbonBull ? 0 : 1,
fill=true,
label=["Fast Momentum", "Slow Momentum"],
desc=["Fast smoothed momentum ribbon edge", "Slow smoothed momentum ribbon edge"]
)
}
// --- Individual Fast & Slow Lines ---
if (showFastSlow) {
plotLine(
value=momFastSm,
width=2,
colors=[bullColor],
label=["Fast Momentum"],
desc=["Fast smoothed momentum (" + fastLen + ")"]
)
plotLine(
value=momSlowSm,
width=2,
colors=[slowColor],
label=["Slow Momentum"],
desc=["Slow smoothed momentum (" + slowLen + ")"]
)
}
// --- Averaged Momentum (regime-colored) ---
plotLine(
value=avgMom,
width=2,
colors=[regimeColor],
label=["Avg Momentum"],
desc=["Averaged smoothed momentum (regime-colored)"]
)
// --- Signal SMA ---
plotLine(
value=signal,
width=1,
colors=[signalColor],
label=["Signal SMA"],
desc=["SMA of averaged momentum (" + signalLen + ")"]
)
// --- Signal Fill (avg momentum vs signal) ---
if (showSignalFill) {
var signalBull = avgMom > signal
plotLine(
value=[avgMom, signal],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=signalBull ? 0 : 1,
fill=true,
label=["Avg Momentum", "Signal SMA"],
desc=["Fill between averaged momentum and signal 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=["Momentum"],
desc=["Histogram of averaged momentum minus signal SMA"]
)
}
// --- Z-Score Line ---
if (showZscore) {
plotLine(
value=zscore,
width=2,
colors=[bullColor, bearColor],
colorIndex=zscore >= 0 ? 0 : 1,
label=["Z-Score"],
desc=["Z-score of averaged momentum"]
)
hline(value=zExtreme, color=transparency(bearColor, 60), width=1)
hline(value=-zExtreme, color=transparency(bullColor, 60), width=1)
}
// --- Shape Markers ---
if (showAlertShapes) {
if (zeroCrossUp) {
plotShape(
value=avgMom,
shape="triangleup",
colorIndex=bullColor,
width=shapeSize,
label=["Zero Cross Up"],
desc=["Momentum crossed above zero"]
)
}
if (zeroCrossDown) {
plotShape(
value=avgMom,
shape="triangledown",
colorIndex=bearColor,
width=shapeSize,
label=["Zero Cross Down"],
desc=["Momentum crossed below zero"]
)
}
if (signalCrossUp) {
plotShape(
value=signal,
shape="circle",
colorIndex=bullColor,
width=shapeSize,
label=["Signal Cross Up"],
desc=["Momentum crossed above signal SMA"]
)
}
if (signalCrossDown) {
plotShape(
value=signal,
shape="circle",
colorIndex=bearColor,
width=shapeSize,
label=["Signal Cross Down"],
desc=["Momentum crossed below signal SMA"]
)
}
if (fastSlowCrossUp) {
plotShape(
value=momFastSm,
shape="arrowup",
colorIndex=bullColor,
width=shapeSize - 1,
label=["Fast>Slow"],
desc=["Fast momentum crossed above slow momentum"]
)
}
if (fastSlowCrossDown) {
plotShape(
value=momFastSm,
shape="arrowdown",
colorIndex=bearColor,
width=shapeSize - 1,
label=["Fast<Slow"],
desc=["Fast momentum crossed below slow momentum"]
)
}
if (zExtremeHigh) {
plotShape(
value=zscore,
shape="xcross",
colorIndex=bearColor,
width=shapeSize,
label=["Z-Extreme High"],
desc=["Z-Score exceeded +" + zExtreme]
)
}
if (zExtremeLow) {
plotShape(
value=zscore,
shape="xcross",
colorIndex=bullColor,
width=shapeSize,
label=["Z-Extreme Low"],
desc=["Z-Score exceeded -" + zExtreme]
)
}
if (momFlipUp) {
plotShape(
value=avgMom,
shape="triangleup",
colorIndex=bullColor,
width=shapeSize,
label=["Momentum Flip Up"],
desc=["Momentum flipped from negative to positive"]
)
}
if (momFlipDown) {
plotShape(
value=avgMom,
shape="triangledown",
colorIndex=bearColor,
width=shapeSize,
label=["Momentum Flip Down"],
desc=["Momentum flipped from positive to negative"]
)
}
}
// ---------------------------------------------------------------------------
// Regime Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")
var upperText = useDynamic ? "Dynamic Upper: " + dynUpper : "Static Upper: 0"
var lowerText = useDynamic ? "Dynamic Lower: " + dynLower : "Static Lower: 0"
plotTable(
data=[
["Momentum [Perfected]", regimeText],
["Fast Momentum", momFastSm[0]],
["Slow Momentum", momSlowSm[0]],
["Avg Momentum", avgMom[0]],
["Signal", signal[0]],
["Histogram", hist[0]],
["Z-Score", zscore[0]],
[upperText, lowerText]
],
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
)
}