Perfected FlowScript
asdf
Multi-Factor Market Score V2 Perfected is indexed as 350_asdf.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
21.3 KB
Lines
488
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 376:9
Trigger
(showShape) && (crossUp)
Value
scoreZS
Deps
crossUp:var, showShape:input
Bear Regime
line 386:9
Trigger
(showShape) && (crossDn)
Value
scoreZS
Deps
crossDn:var, showShape:input
Extreme Bull
line 396:9
Trigger
(showShape) && (extremeUp)
Value
scoreZS
Deps
extremeUp:var, showShape:input
Extreme Bear
line 406:9
Trigger
(showShape) && (extremeDn)
Value
scoreZS
Deps
extremeDn:var, showShape:input
+1σ Cross
line 416:9
Trigger
(showShape) && (band1CrossUp)
Value
scoreZS
Deps
band1CrossUp:var, showShape:input
-1σ Cross
line 426:9
Trigger
(showShape) && (band1CrossDn)
Value
scoreZS
Deps
band1CrossDn:var, showShape:input
+2σ Cross
line 436:9
Trigger
(showShape) && (band2CrossUp)
Value
scoreZS
Deps
band2CrossUp:var, showShape:input
-2σ Cross
line 446:9
Trigger
(showShape) && (band2CrossDn)
Value
scoreZS
Deps
band2CrossDn:var, showShape:input
350_asdf.flowscript
source path: kscripts/perfected/350_asdf.flowscript · sha256:d1274a4b3526ba41057c1900c781e7ccf5134497fa810f9316b24422bcb6a8df
//@version=2
// ============================================================================
// Multi-Factor Market Score (MFMS) — Adaptive Composite Scoring Indicator
// Author: TestingTY (@TestingTY) | Perfected by: kScript Perfection Engineer
// Tags: CORE, ADVANCED, #composite, #multifactor, #momentum, #trend, #volatility
//
// Production-quality multi-factor composite scoring indicator combining trend,
// momentum, volatility, and volume signals into a unified directional score.
// Includes z-score normalization, regime detection, color-coded histogram and
// line visualization, fill areas, shape markers, and session-level static tracking.
//
// FORMULA FOUNDATION:
// 1. Trend Factor: EMA slope normalized by price level, measuring directional
// bias per Hurst, Ooi & Pedersen (2014) time-series momentum framework.
// 2. Momentum Factor: RSI-based momentum score per Wilder (1978), capturing
// rate-of-change intensity on a 0-100 scale.
// 3. Volatility Factor: ATR ratio (short-term vs long-term) per Bollinger (2001)
// volatility expansion/contraction framework.
// 4. Volume Factor: Volume z-score per Lee & Ready (1991) and Easley, López de
// Prado & O'Hara (2012) volume-based information flow.
// 5. Composite Score: Weighted average of all factors, z-score normalized
// per Zhao & Palomar (2018) for statistical threshold clarity.
// 6. Regime Segmentation: Bull (score > +1σ), Neutral (−1σ to +1σ), Bear
// (score < −1σ) per Cartea, Donnelly & Jaimungal (2018) three-segment model.
//
// RESEARCH BASIS:
// • Wilder (1978), "New Concepts in Technical Trading Systems". Canonical RSI
// formula; RSI = 100 − [100 / (1 + RS)]. Original smoothing period = 14.
// • Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling Losers".
// Established momentum as a premier cross-sectional anomaly.
// • Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and the
// Stochastic Properties of Stock Returns". MA crossover rules significantly
// outperformed cash benchmarks using 90 years of DJIA data.
// • Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing". Time-series momentum has been profitable since 1880 across
// nearly all asset classes.
// • Bollinger (2001), "Bollinger on Bollinger Bands". Volatility expansion and
// contraction (the "Squeeze") as regime shift signal.
// • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand". Liquidity memory time explains volatility expansion.
// • Lee & Ready (1991), "Inferring Trade Direction from Intraday Data".
// Foundational algorithm for classifying trades as buyer- or seller-initiated.
// • Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
// Activity". BVC classifies volume probabilistically using price distribution.
// • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// z̄ₜ = (zₜ − μz) / σz; entry thresholds at d × σz for signal clarity.
// • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
// segmentation for signal classification.
// ============================================================================
define(
title="Multi-Factor Market Score V2 Perfected",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Trend Settings ---
var trendLen = input(name="trendLen", type="number", defaultValue=20, label="Trend EMA Length", constraints={min: 5, max: 200, step: 1}, group="Trend")
var trendWeight = input(name="trendWeight", type="number", defaultValue=0.25, label="Trend Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Trend")
// --- Momentum Settings ---
var momLen = input(name="momLen", type="number", defaultValue=14, label="Momentum RSI Length", constraints={min: 2, max: 50, step: 1}, group="Momentum")
var momWeight = input(name="momWeight", type="number", defaultValue=0.30, label="Momentum Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Momentum")
// --- Volatility Settings ---
var volShort = input(name="volShort", type="number", defaultValue=9, label="Volatility Short ATR", constraints={min: 2, max: 50, step: 1}, group="Volatility")
var volLong = input(name="volLong", type="number", defaultValue=40, label="Volatility Long ATR", constraints={min: 10, max: 200, step: 1}, group="Volatility")
var volWeight = input(name="volWeight", type="number", defaultValue=0.20, label="Volatility Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Volatility")
// --- Volume Settings ---
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volume Lookback", constraints={min: 5, max: 100, step: 1}, group="Volume")
var volScoreWeight = input(name="volScoreWeight", type="number", defaultValue=0.25, label="Volume Weight", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Volume")
// --- Composite Score ---
var scoreLookback = input(name="scoreLookback", type="number", defaultValue=50, label="Score Z-Lookback", constraints={min: 10, max: 200, step: 5}, group="Composite")
var scoreSmooth = input(name="scoreSmooth", type="number", defaultValue=3, label="Score EMA Smooth", constraints={min: 1, max: 50, step: 1}, group="Composite")
var autoBalance = input(name="autoBalance", type="boolean", defaultValue=true, label="Auto-Balance Weights", group="Composite")
// --- Regime Thresholds ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Threshold (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Threshold (σ)", constraints={min: -5.0, max: -0.1, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Thresholds")
// --- Display ---
var showScore = input(name="showScore", type="boolean", defaultValue=true, label="Show Composite Score Line", group="Display")
var showRawScore = input(name="showRawScore", type="boolean", defaultValue=true, label="Show Raw Score Histogram", group="Display")
var showFactors = input(name="showFactors", type="boolean", defaultValue=false, label="Show Individual Factors", group="Display")
var showShape = input(name="showShape", type="boolean", defaultValue=true, label="Show Threshold Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Score Fill", group="Display")
var showBand = input(name="showBand", type="boolean", defaultValue=true, label="Show σ Bands", group="Display")
// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bull Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bear Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries vol = bars.volume
if (isnan(px[0]) || isnan(vol[0])) {
return
}
// ------------------------------------------------------------------------------
// Factor 1: Trend (EMA Slope Normalized)
// ------------------------------------------------------------------------------
// Trend score = normalized EMA slope ∈ [−1, +1]
// Positive = price above EMA and rising; negative = price below EMA and falling.
// Per Hurst, Ooi & Pedersen (2014): time-series momentum is profitable across
// nearly all asset classes since 1880.
timeseries trendEma = ema(px, trendLen)
timeseries emaSlope = trendEma - trendEma[1]
timeseries emaSlopeNorm = emaSlope / math.max(math.abs(nz(trendEma, 1.0)), 0.0001) * 100.0
// Normalize to a bounded [-1, +1] range using a sigmoid-like clamp
var trendScore = math.max(-1.0, math.min(1.0, emaSlopeNorm * 5.0))
// ------------------------------------------------------------------------------
// Factor 2: Momentum (RSI Centered)
// ------------------------------------------------------------------------------
// Momentum score = (RSI − 50) / 50 ∈ [−1, +1]
// Per Wilder (1978): RSI measures speed and magnitude of price changes.
// Per Jegadeesh & Titman (1993): momentum is a premier cross-sectional anomaly.
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = ema(gain, momLen)
timeseries avgLoss = ema(loss, momLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsi = 100 - (100 / (1 + rs))
var momentumScore = (rsi - 50.0) / 50.0
momentumScore = math.max(-1.0, math.min(1.0, momentumScore))
// ------------------------------------------------------------------------------
// Factor 3: Volatility (ATR Expansion/Contraction)
// ------------------------------------------------------------------------------
// Volatility score = (ATR_short / ATR_long − 1) × 2 ∈ [−1, +1]
// Per Bollinger (2001): volatility expansion precedes directional moves;
// contraction (Squeeze) precedes breakouts.
// Per Bouchaud, Farmer & Lillo (2009): liquidity memory explains why volatility
// expansion signals regime shifts.
timeseries tr = math.max(high - low, math.max(math.abs(high - px[1]), math.abs(low - px[1])))
timeseries atrShort = ema(tr, volShort)
timeseries atrLong = ema(tr, volLong)
var volatilityScore = 0.0
if (atrLong > 0) {
volatilityScore = (atrShort / atrLong - 1.0) * 3.0
volatilityScore = math.max(-1.0, math.min(1.0, volatilityScore))
}
// ------------------------------------------------------------------------------
// Factor 4: Volume (Volume Z-Score)
// ------------------------------------------------------------------------------
// Volume score = volume z-score clamped to [−1, +1]
// Per Lee & Ready (1991): volume classification reveals information flow.
// Per Easley, López de Prado & O'Hara (2012): BVC uses volume buckets for
// probabilistic buy/sell classification.
timeseries volMean = ema(vol, volLookback)
timeseries volDev = ema(math.abs(vol - volMean), volLookback) * 1.253
// Bias correction: EMA of absolute deviations ≈ σ / 1.253
var volumeScore = 0.0
if (volDev > 0) {
volumeScore = (vol - volMean) / volDev
volumeScore = math.max(-1.0, math.min(1.0, volumeScore / 3.0))
}
// ------------------------------------------------------------------------------
// Composite Score (Weighted Average)
// ------------------------------------------------------------------------------
// Auto-balance weights to sum to 1.0 if enabled.
// If auto-balance is off, user weights are used directly (may not sum to 1.0).
var totalWeight = trendWeight + momWeight + volWeight + volScoreWeight
var weightScale = autoBalance && totalWeight > 0 ? 1.0 / totalWeight : 1.0
var wTrend = trendWeight * weightScale
var wMom = momWeight * weightScale
var wVol = volWeight * weightScale
var wVolScore = volScoreWeight * weightScale
var rawScore = wTrend * trendScore + wMom * momentumScore + wVol * volatilityScore + wVolScore * volumeScore
// ------------------------------------------------------------------------------
// Z-Score Normalization of Composite Score (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z̄ = (Score − μ_Score) / σ_Score over rolling lookback.
// Provides statistical clarity and cross-asset comparability.
timeseries scoreMean = sma(rawScore, scoreLookback)
timeseries scoreStd = stdev(rawScore, scoreLookback)
var scoreZ = (!isnan(scoreMean) && !isnan(scoreStd) && scoreStd > 0) ? (rawScore - scoreMean) / scoreStd : 0.0
timeseries scoreZS = ema(scoreZ, scoreSmooth)
// ------------------------------------------------------------------------------
// Regime Detection (Cartea, Donnelly & Jaimungal 2018 three-segment model)
// ------------------------------------------------------------------------------
// Segmented into three regimes based on z-score:
// Bull: z ≥ bullThresh
// Neutral: bearThresh < z < bullThresh
// Bear: z ≤ bearThresh
// Extreme Bull: z ≥ extremeThresh
// Extreme Bear: z ≤ -extremeThresh
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (scoreZS >= bullThresh) {
regime = 1
} else if (scoreZS <= bearThresh) {
regime = -1
}
if (scoreZS >= extremeThresh) {
extremeRegime = 1
} else if (scoreZS <= -extremeThresh) {
extremeRegime = -1
}
// Regime color for line plotting
var regimeColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks extreme-event counts, session score extremes, and regime transitions.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighScore = -999999.0
static sessionLowScore = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
// New bar — update session tracking
lastBarIndex = currentBarIndex
if (scoreZS > sessionHighScore) {
sessionHighScore = scoreZS
}
if (scoreZS < sessionLowScore) {
sessionLowScore = scoreZS
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBullCount = extremeBullCount + 1
} else if (extremeRegime == -1) {
extremeBearCount = extremeBearCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------
// Zero reference line
hline(value=0, color="#ffffff30", width=1)
// Sigma band lines
if (showBand) {
hline(value=1, color=opacity(bullColor, 30), width=1)
hline(value=-1, color=opacity(bearColor, 30), width=1)
hline(value=2, color=opacity(extremeBullColor, 20), width=1)
hline(value=-2, color=opacity(extremeBearColor, 20), width=1)
hline(value=3, color=opacity(extremeBullColor, 12), width=1)
hline(value=-3, color=opacity(extremeBearColor, 12), width=1)
}
// Raw composite score as color-coded histogram
if (showRawScore) {
var histColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotBar(
value=scoreZ,
colors=[histColor],
width=1,
label=["Score Histogram"],
desc=["Raw composite score histogram (positive = bullish, negative = bearish)"]
)
}
// Smoothed composite score line with regime-coded fill area
if (showScore) {
plotLine(
value=scoreZS,
width=2,
colors=[regimeColor],
label=["Composite Score"],
desc=["Multi-factor market score (trend + momentum + volatility + volume). Regime-coded."],
fill=showFill
)
}
// Fill area between score line and zero
if (showFill && showScore) {
plotLine(
value=[scoreZS, 0],
width=0,
colors=[regimeColor, regimeColor],
fill=opacity(regimeColor, 10),
label=["Score Fill", "Zero"],
desc=["Fill area between composite score and zero reference", "Zero reference line"]
)
}
// Individual factor lines (optional, for diagnostic analysis)
if (showFactors) {
plotLine(
value=trendScore,
width=1,
colors=[opacity("#2196f3", 50)],
label=["Trend Factor"],
desc=["Trend factor: normalized EMA slope (blue = up, red = down)"]
)
plotLine(
value=momentumScore,
width=1,
colors=[opacity("#ff9800", 50)],
label=["Momentum Factor"],
desc=["Momentum factor: centered RSI (orange = strong, grey = weak)"]
)
plotLine(
value=volatilityScore,
width=1,
colors=[opacity("#9c27b0", 50)],
label=["Volatility Factor"],
desc=["Volatility factor: ATR expansion/contraction (purple = expanding)"]
)
plotLine(
value=volumeScore,
width=1,
colors=[opacity("#00bcd4", 50)],
label=["Volume Factor"],
desc=["Volume factor: volume z-score (cyan = above average, grey = normal)"]
)
}
// Regime transition shapes — directional signal extraction
if (showShape) {
var crossUp = scoreZS >= bullThresh && !isnan(scoreZS[1]) && scoreZS[1] < bullThresh
var crossDn = scoreZS <= bearThresh && !isnan(scoreZS[1]) && scoreZS[1] > bearThresh
var extremeUp = scoreZS >= extremeThresh && !isnan(scoreZS[1]) && scoreZS[1] < extremeThresh
var extremeDn = scoreZS <= -extremeThresh && !isnan(scoreZS[1]) && scoreZS[1] > -extremeThresh
var band1CrossUp = scoreZS >= 1.0 && !isnan(scoreZS[1]) && scoreZS[1] < 1.0
var band1CrossDn = scoreZS <= -1.0 && !isnan(scoreZS[1]) && scoreZS[1] > -1.0
var band2CrossUp = scoreZS >= 2.0 && !isnan(scoreZS[1]) && scoreZS[1] < 2.0
var band2CrossDn = scoreZS <= -2.0 && !isnan(scoreZS[1]) && scoreZS[1] > -2.0
if (crossUp) {
plotShape(
value=scoreZS,
shape="triangleup",
color=bullColor,
width=3,
label=["Bull Regime"],
desc=["Composite score crossed into bullish regime (multi-factor alignment up)"]
)
}
if (crossDn) {
plotShape(
value=scoreZS,
shape="triangledown",
color=bearColor,
width=3,
label=["Bear Regime"],
desc=["Composite score crossed into bearish regime (multi-factor alignment down)"]
)
}
if (extremeUp) {
plotShape(
value=scoreZS,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Bull"],
desc=["Extreme bullish alignment detected — all factors converging upward"]
)
}
if (extremeDn) {
plotShape(
value=scoreZS,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Bear"],
desc=["Extreme bearish alignment detected — all factors converging downward"]
)
}
if (band1CrossUp) {
plotShape(
value=scoreZS,
shape="circle",
color=bullColor,
width=2,
label=["+1σ Cross"],
desc=["Score crossed above +1σ — above-average bullish composite"]
)
}
if (band1CrossDn) {
plotShape(
value=scoreZS,
shape="circle",
color=bearColor,
width=2,
label=["-1σ Cross"],
desc=["Score crossed below -1σ — above-average bearish composite"]
)
}
if (band2CrossUp) {
plotShape(
value=scoreZS,
shape="cross",
color=extremeBullColor,
width=2,
label=["+2σ Cross"],
desc=["Score crossed above +2σ — strong bullish composite alignment"]
)
}
if (band2CrossDn) {
plotShape(
value=scoreZS,
shape="cross",
color=extremeBearColor,
width=2,
label=["-2σ Cross"],
desc=["Score crossed below -2σ — strong bearish composite alignment"]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotTable(
data=[
["Multi-Factor Market Score", regimeText],
["Trend Score", trendScore],
["Momentum Score", momentumScore],
["Volatility Score", volatilityScore],
["Volume Score", volumeScore],
["Composite Z", scoreZS],
["Regime Changes", regimeChangeCount],
["Extreme Events", extremeBullCount + extremeBearCount]
],
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
)
}