Perfected FlowScript
index promax
Index Pro Max — Perfected Edition is indexed as 333_index_promax.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
18.2 KB
Lines
584
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Cross Up
line 490:9
Trigger
(showShapes) && (crossUp)
Value
signal
Deps
crossUp:var, showShapes:input
Cross Down
line 500:9
Trigger
(showShapes) && (crossDown)
Value
signal
Deps
crossDown:var, showShapes:input
OB Penetrate
line 510:9
Trigger
(showShapes) && (obPenetrate)
Value
dynOb
Deps
obPenetrate:var, showShapes:input
OS Penetrate
line 520:9
Trigger
(showShapes) && (osPenetrate)
Value
dynOs
Deps
osPenetrate:var, showShapes:input
Extreme OB
line 530:9
Trigger
(showShapes) && (extremeObHit)
Value
extremeOb
Deps
extremeObHit:var, showShapes:input
Extreme OS
line 540:9
Trigger
(showShapes) && (extremeOsHit)
Value
extremeOs
Deps
extremeOsHit:var, showShapes:input
333_index_promax.flowscript
source path: kscripts/perfected/333_index_promax.flowscript · sha256:7ee856b00c87414cb9c435551468ae1d90b972f7ae648df95a60e7d70151e026
//@version=2
// ============================================================================
// Index Pro Max — Perfected Edition
// Author: Tzen Yang | Enhanced by kScript Perfection Engineer
// Tags: CORE, ADVANCED, #composite, #index, #zscore, #regime, #momentum, #trend
//
// Production-quality composite index combining multi-factor scoring,
// z-score normalization, regime detection, and comprehensive visualization.
// Blends RSI momentum, EMA trend bias, price position, and volatility regime
// into a single normalized oscillator with dynamic threshold adaptation.
//
// Research papers underpinning this design:
// 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 the momentum component's predictive role.
// 3. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
// Moving Average": comparative study showing EMA crossover systems
// capture trend direction with superior stability to WMA alternatives.
// 4. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
// Implications": negative autocorrelation at medium horizons; supports
// z-score normalization and dynamic threshold calibration.
// 5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// formalizes z-score event triggers for trading signals. Normalized
// spread z̄_t = (z_t − μ_z) / σ_z measures distance to equilibrium in
// standard deviations, with entry thresholds at Δ = d × σ_z.
// 6. Bollinger (2001), "Bollinger on Bollinger Bands": z-score normalization
// of price relative to rolling mean and standard deviation creates a
// robust mean-reversion framework applicable to composite indices.
// ============================================================================
define(
title="Index Pro Max — Perfected Edition",
position="offchart",
axis=true
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- RSI Momentum Component ---
var rsiLen = input(
name="rsiLen",
type="number",
defaultValue=14,
label="RSI Length",
constraints={min: 2, max: 50, step: 1},
group="Momentum"
)
var rsiSmooth = input(
name="rsiSmooth",
type="number",
defaultValue=3,
label="RSI EMA Smoothing",
constraints={min: 1, max: 20, step: 1},
group="Momentum"
)
// --- Trend Component ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=21,
label="Fast EMA Length",
constraints={min: 2, max: 100, step: 1},
group="Trend"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=55,
label="Slow EMA Length",
constraints={min: 5, max: 200, step: 1},
group="Trend"
)
// --- Position Component ---
var posLookback = input(
name="posLookback",
type="number",
defaultValue=14,
label="Position Lookback (rolling range)",
constraints={min: 5, max: 100, step: 1},
group="Position"
)
// --- Volatility / Z-Score ---
var zScoreLen = input(
name="zScoreLen",
type="number",
defaultValue=20,
label="Z-Score Lookback",
constraints={min: 10, max: 100, step: 1},
group="Z-Score"
)
var useDynamicThresholds = input(
name="useDynamicThresholds",
type="boolean",
defaultValue=true,
label="Dynamic Thresholds (volatility-adjusted)",
group="Z-Score"
)
var volMultiplier = input(
name="volMultiplier",
type="number",
defaultValue=1.5,
label="Volatility Multiplier",
constraints={min: 0.5, max: 3.0, step: 0.1},
group="Z-Score"
)
// --- Composite Scoring ---
var momentumWeight = input(
name="momentumWeight",
type="number",
defaultValue=0.35,
label="Momentum Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Scoring"
)
var trendWeight = input(
name="trendWeight",
type="number",
defaultValue=0.35,
label="Trend Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Scoring"
)
var positionWeight = input(
name="positionWeight",
type="number",
defaultValue=0.30,
label="Position Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Scoring"
)
// --- Display ---
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Line",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal SMA",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
var showComponents = input(
name="showComponents",
type="boolean",
defaultValue=false,
label="Show Component Lines",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Composite/Signal Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Alert Shapes",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Regime Table",
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 neutralColor = input(
name="neutralColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
var compositeColor = input(
name="compositeColor",
type="color",
defaultValue="#2962ff",
label="Composite Line 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. COMPONENT CALCULATIONS
// -----------------------------------------------------------------------------
// --- Component 1: RSI Momentum (normalized to -1..+1) ---
// Wilder (1978) canonical RSI
timeseries change = px - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = rma(gain, rsiLen)
timeseries avgLoss = rma(loss, rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : (avgGain > 0 ? 100.0 : 1.0)
timeseries rsiVal = 100 - (100 / (1 + rs))
timeseries rsiPart = (rsiVal - 50.0) / 50.0
// --- Component 2: EMA Trend Bias (normalized by ATR) ---
timeseries fastEma = ema(px, fastLen)
timeseries slowEma = ema(px, slowLen)
timeseries atrV = atr(period=rsiLen)
timeseries trendPart = atrV > 0 ? (fastEma - slowEma) / atrV : 0.0
trendPart = math.max(-1.0, math.min(1.0, trendPart))
// --- Component 3: Price Position in Rolling Range ---
timeseries hiAll = highest(px, posLookback)
timeseries loAll = lowest(px, posLookback)
timeseries rangeV = hiAll - loAll
timeseries posPart = rangeV > 0 ? 2.0 * (px - loAll) / rangeV - 1.0 : 0.0
// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018) and Bollinger (2001): normalize each component
// to its own rolling z-score for cross-sectional comparability.
timeseries rsiMean = sma(rsiPart, zScoreLen)
timeseries rsiStd = stddev(rsiPart, zScoreLen)
timeseries rsiZ = rsiStd > 0 ? (rsiPart - rsiMean) / rsiStd : 0.0
timeseries trendMean = sma(trendPart, zScoreLen)
timeseries trendStd = stddev(trendPart, zScoreLen)
timeseries trendZ = trendStd > 0 ? (trendPart - trendMean) / trendStd : 0.0
timeseries posMean = sma(posPart, zScoreLen)
timeseries posStd = stddev(posPart, zScoreLen)
timeseries posZ = posStd > 0 ? (posPart - posMean) / posStd : 0.0
// Clip z-scores to ±3 sigma to prevent outlier distortion
timeseries rsiZClip = math.max(-3.0, math.min(3.0, rsiZ))
timeseries trendZClip = math.max(-3.0, math.min(3.0, trendZ))
timeseries posZClip = math.max(-3.0, math.min(3.0, posZ))
// -----------------------------------------------------------------------------
// 5. MULTI-FACTOR COMPOSITE SCORING
// -----------------------------------------------------------------------------
// Weighted combination of z-score-normalized components.
// Weights are user-configurable and sum to 1.0 by default.
timeseries weightSum = momentumWeight + trendWeight + positionWeight
timeseries compositeRaw = weightSum > 0 ?
(momentumWeight * rsiZClip + trendWeight * trendZClip + positionWeight * posZClip) / weightSum :
0.0
// Scale composite to -100..+100 for oscillator readability
timeseries composite = compositeRaw * 33.333
// Signal SMA for crossover detection
timeseries signal = sma(composite, 14)
// Momentum histogram
timeseries hist = composite - signal
// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Three-regime classification:
// Bullish: composite > signal AND composite > 0
// Bearish: composite < signal AND composite < 0
// Neutral: everything else (chop / consolidation)
var regimeBull = composite > signal && composite > 0
var regimeBear = composite < signal && composite < 0
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// -----------------------------------------------------------------------------
// 7. DYNAMIC THRESHOLDS (volatility-adjusted)
// -----------------------------------------------------------------------------
// Per Poterba & Summers (1988): mean-reversion intensity varies with volatility.
// Adjust overbought/oversold bands by rolling composite standard deviation.
var compVol = stddev(source=composite, period=zScoreLen)
var dynOb = useDynamicThresholds ? math.min(80, 50 + compVol * volMultiplier) : 50
var dynOs = useDynamicThresholds ? math.max(-80, -50 - compVol * volMultiplier) : -50
if (dynOb <= dynOs) {
dynOb = 50
dynOs = -50
}
// Extreme thresholds
timeseries extremeOb = dynOb + 20
timeseries extremeOs = dynOs - 20
// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Session-level persistence for regime transitions, extremes, and counters.
static sessionHighComposite = -999999.0
static sessionLowComposite = 999999.0
static lastRegime = 0
static regimeChangeCount = 0
static lastBarIndex = 0
static obDuration = 0
static osDuration = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (composite > sessionHighComposite) {
sessionHighComposite = composite
}
if (composite < sessionLowComposite) {
sessionLowComposite = composite
}
var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
if (lastRegime != currentRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
if (composite > dynOb) {
obDuration = obDuration + 1
} else {
obDuration = 0
}
if (composite < dynOs) {
osDuration = osDuration + 1
} else {
osDuration = 0
}
}
// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of composite and signal
var crossUp = composite > signal && !isnan(composite[1]) && composite[1] <= signal[1]
var crossDown = composite < signal && !isnan(composite[1]) && composite[1] >= signal[1]
// OB / OS penetrations (using dynamic or static thresholds)
var obPenetrate = composite > dynOb && !isnan(composite[1]) && composite[1] <= dynOb
var osPenetrate = composite < dynOs && !isnan(composite[1]) && composite[1] >= dynOs
// OB / OS exit (return to neutral zone)
var obExit = composite < dynOb && !isnan(composite[1]) && composite[1] >= dynOb
var osExit = composite > dynOs && !isnan(composite[1]) && composite[1] <= dynOs
// Extreme conditions
var extremeObHit = composite > extremeOb && !isnan(composite[1]) && composite[1] <= extremeOb
var extremeOsHit = composite < extremeOs && !isnan(composite[1]) && composite[1] >= extremeOs
// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------
// --- Midline ---
hline(value=0, color="#ffffff20", width=1)
// --- Threshold zones ---
hline(value=dynOb, color=transparency(bearColor, 60), width=1)
hline(value=dynOs, color=transparency(bullColor, 60), width=1)
// --- Composite line (regime-colored) ---
if (showComposite) {
plotLine(
value=composite,
width=2,
colors=[regimeColor],
label=["Composite Index"],
desc=["Multi-factor composite index (z-score normalized, -100 to +100)"]
)
}
// --- Signal SMA ---
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=["#ffffff"],
label=["Signal SMA"],
desc=["14-period SMA of composite index"]
)
}
// --- Composite/Signal Fill ---
if (showFill && showComposite && showSignal) {
var fillBull = composite > signal
plotLine(
value=[composite, signal],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=fillBull ? 0 : 1,
fill=true,
label=["Composite", "Signal"],
desc=["Fill between composite index and signal SMA"]
)
}
// --- Momentum Histogram (color-coded) ---
if (showHistogram) {
var histBull = hist >= 0
var histStrong = math.abs(hist) > 10
plotBar(
value=hist,
colors=[
histStrong ? bullColor : transparency(bullColor, 60),
histStrong ? bearColor : transparency(bearColor, 60)
],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Momentum"],
desc=["Histogram of composite minus signal SMA"]
)
}
// --- Component Lines (optional) ---
if (showComponents) {
plotLine(
value=rsiZClip * 33.333,
width=1,
colors=["#ff9800"],
label=["Momentum Z"],
desc=["RSI momentum component (z-score scaled)"]
)
plotLine(
value=trendZClip * 33.333,
width=1,
colors=["#9c27b0"],
label=["Trend Z"],
desc=["EMA trend component (z-score scaled)"]
)
plotLine(
value=posZClip * 33.333,
width=1,
colors=["#00bcd4"],
label=["Position Z"],
desc=["Price position component (z-score scaled)"]
)
}
// --- Alert Shapes ---
if (showShapes) {
if (crossUp) {
plotShape(
value=signal,
shape="triangleup",
color=bullColor,
width=2,
label=["Cross Up"],
desc=["Composite crossed above signal SMA — bullish momentum shift"]
)
}
if (crossDown) {
plotShape(
value=signal,
shape="triangledown",
color=bearColor,
width=2,
label=["Cross Down"],
desc=["Composite crossed below signal SMA — bearish momentum shift"]
)
}
if (obPenetrate) {
plotShape(
value=dynOb,
shape="xcross",
color=bearColor,
width=2,
label=["OB Penetrate"],
desc=["Composite entered overbought zone (> " + dynOb + ")"]
)
}
if (osPenetrate) {
plotShape(
value=dynOs,
shape="xcross",
color=bullColor,
width=2,
label=["OS Penetrate"],
desc=["Composite entered oversold zone (< " + dynOs + ")"]
)
}
if (extremeObHit) {
plotShape(
value=extremeOb,
shape="diamond",
color="#ff1744",
width=3,
label=["Extreme OB"],
desc=["Extreme overbought condition — mean reversion likely"]
)
}
if (extremeOsHit) {
plotShape(
value=extremeOs,
shape="diamond",
color="#00e676",
width=3,
label=["Extreme OS"],
desc=["Extreme oversold condition — mean reversion likely"]
)
}
}
// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
var obText = useDynamicThresholds ? "Dynamic OB: " + dynOb : "Static OB: 50"
var osText = useDynamicThresholds ? "Dynamic OS: " + dynOs : "Static OS: -50"
plotTable(
data=[
["Index Pro Max", regimeText],
["Composite", composite[0]],
["Signal", signal[0]],
["Momentum", hist[0]],
["Session High", sessionHighComposite],
["Session Low", sessionLowComposite],
["Regime Changes", regimeChangeCount],
[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
)
}