Perfected FlowScript
DIy
DIY Composite Score — Perfected Edition is indexed as 342_diy.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.9 KB
Lines
587
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Trigger
line 492:9
Trigger
(showShapes) && (crossUp)
Value
score
Deps
crossUp:var, showShapes:input
Bear Trigger
line 502:9
Trigger
(showShapes) && (crossDown)
Value
score
Deps
crossDown:var, showShapes:input
Extreme Over
line 512:9
Trigger
(showShapes) && (extremeOver)
Value
score
Deps
extremeOver:var, showShapes:input
Extreme Under
line 522:9
Trigger
(showShapes) && (extremeUnder)
Value
score
Deps
extremeUnder:var, showShapes:input
Bull Confirmed
line 532:9
Trigger
(showShapes) && (regimeBull && bullStreak == 3)
Value
score
Deps
bullStreak:static, regimeBull:var, showShapes:input
Bear Confirmed
line 542:9
Trigger
(showShapes) && (regimeBear && bearStreak == 3)
Value
score
Deps
bearStreak:static, regimeBear:var, showShapes:input
342_diy.flowscript
source path: kscripts/perfected/342_diy.flowscript · sha256:16e9dae4b2085e7dbea114d04d3e159f789e62eb12d90f7a89678ed0fe634737
//@version=2
// ============================================================================
// DIY Composite Score — Perfected Edition
// Author: J (@JDot) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #diy, #composite, #multi-factor, #regime, #scoring
//
// Production-quality custom-build indicator that fuses trend, momentum,
// volatility, and volume into a single 0-100 composite score. Each factor
// is individually normalised, weighted, and visualised. Regime detection,
// dynamic thresholds, color coding, shape markers, and a breakdown table
// provide a complete DIY market-analysis workstation.
//
// Research papers underpinning this design:
// 1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
// RSI and ATR publication. Underpins momentum and volatility factors.
// RSI = 100 − [100 / (1 + RS)]; ATR = SMA(TR, N).
// 2. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
// and the Stochastic Properties of Stock Returns": MA crossovers
// significantly outperform cash benchmarks; validates trend-factor design.
// 3. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
// Losers": momentum as a premier cross-sectional anomaly; supports
// RSI momentum factor weighting.
// 4. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
// in Supply and Demand": liquidity memory explains volatility expansion
// as a regime-shift signal; underpins ATR-expansion factor.
// 5. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
// Trading Activity": volume-based probabilistic buy/sell classification;
// validates volume-confirmation factor.
// ============================================================================
define(
title="DIY Composite Score — Perfected Edition",
position="offchart",
axis=true
)
// ----------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ----------------------------------------------------------------------------
// --- Trend Factor ---
var emaFastLen = input(
name="emaFastLen",
type="number",
defaultValue=12,
label="Fast EMA Length",
constraints={min: 2, max: 100, step: 1},
group="Trend Factor"
)
var emaSlowLen = input(
name="emaSlowLen",
type="number",
defaultValue=26,
label="Slow EMA Length",
constraints={min: 2, max: 200, step: 1},
group="Trend Factor"
)
var trendWeight = input(
name="trendWeight",
type="number",
defaultValue=30,
label="Trend Weight (%)",
constraints={min: 0, max: 100, step: 5},
group="Trend Factor"
)
// --- Momentum Factor ---
var rsiLen = input(
name="rsiLen",
type="number",
defaultValue=14,
label="RSI Length",
constraints={min: 2, max: 50, step: 1},
group="Momentum Factor"
)
var rsiSmooth = input(
name="rsiSmooth",
type="number",
defaultValue=3,
label="RSI EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="Momentum Factor"
)
var momWeight = input(
name="momWeight",
type="number",
defaultValue=30,
label="Momentum Weight (%)",
constraints={min: 0, max: 100, step: 5},
group="Momentum Factor"
)
// --- Volatility Factor ---
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 2, max: 50, step: 1},
group="Volatility Factor"
)
var volLookback = input(
name="volLookback",
type="number",
defaultValue=20,
label="Volatility Lookback",
constraints={min: 5, max: 100, step: 1},
group="Volatility Factor"
)
var volWeight = input(
name="volWeight",
type="number",
defaultValue=20,
label="Volatility Weight (%)",
constraints={min: 0, max: 100, step: 5},
group="Volatility Factor"
)
// --- Volume Factor ---
var volSmaLen = input(
name="volSmaLen",
type="number",
defaultValue=20,
label="Volume SMA Length",
constraints={min: 5, max: 100, step: 1},
group="Volume Factor"
)
var volWeightInput = input(
name="volWeightInput",
type="number",
defaultValue=20,
label="Volume Weight (%)",
constraints={min: 0, max: 100, step: 5},
group="Volume Factor"
)
// --- Composite ---
var scoreSmooth = input(
name="scoreSmooth",
type="number",
defaultValue=3,
label="Composite EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="Composite"
)
var useDynamic = input(
name="useDynamic",
type="boolean",
defaultValue=true,
label="Dynamic Thresholds (volatility-adjusted)",
group="Composite"
)
var dynMult = input(
name="dynMult",
type="number",
defaultValue=1.5,
label="Dynamic Multiplier",
constraints={min: 0.5, max: 5.0, step: 0.1},
group="Composite"
)
// --- Display ---
var showFactors = input(
name="showFactors",
type="boolean",
defaultValue=true,
label="Show Individual Factor Lines",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Score",
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"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Zone Fills",
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="#78909c",
label="Neutral Color",
group="Colors"
)
var scoreColor = input(
name="scoreColor",
type="color",
defaultValue="#7c4dff",
label="Composite Color",
group="Colors"
)
// ----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// Guard volume
var volAvailable = !isnan(bars.volume[0]) && bars.volume[0] > 0
// ----------------------------------------------------------------------------
// 3. FACTOR COMPUTATION
// ----------------------------------------------------------------------------
// -- 3.1 Trend Factor (0-100) --
// EMA alignment: fast above slow = bullish; scaled to 0-100 via distance ratio
timeseries fastEma = ema(source=px, period=emaFastLen)
timeseries slowEma = ema(source=px, period=emaSlowLen)
timeseries emaDiff = fastEma - slowEma
timeseries emaDiffAbs = math.abs(emaDiff)
// Normalise: 50 ± scaled distance, clamped to 0-100
timeseries emaDistRatio = (slowEma > 0) ? (emaDiffAbs / slowEma) * 1000 : 0
timeseries trendRaw = 50 + (emaDiff > 0 ? emaDistRatio : -emaDistRatio)
timeseries trendFactor = math.min(100, math.max(0, trendRaw))
// -- 3.2 Momentum Factor (0-100) --
// Canonical Wilder RSI, then smoothed
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = rma(source=gain, period=rsiLen)
timeseries avgLoss = rma(source=loss, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
timeseries rsiVal = ema(source=rsiRaw, period=rsiSmooth)
// RSI is already 0-100, so momentum factor = RSI directly
timeseries momFactor = rsiVal
// -- 3.3 Volatility Factor (0-100) --
// ATR expansion relative to historical ATR mean: high expansion = bearish (uncertainty)
// Low expansion = bullish (stable trend). Normalised via z-score approach.
timeseries prevClose = px[1]
timeseries tr = math.max(
bars.high - bars.low,
math.max(
math.abs(bars.high - prevClose),
math.abs(bars.low - prevClose)
)
)
timeseries atr = rma(source=tr, period=atrLen)
timeseries atrMean = sma(source=atr, period=volLookback)
timeseries atrStd = stdev(source=atr, period=volLookback)
// Volatility score: 50 when ATR at mean; higher when compressed (bullish stability),
// lower when expanded (bearish uncertainty). Clamp to 0-100.
timeseries atrZ = (atrStd > 0) ? (atr - atrMean) / atrStd : 0
timeseries volRaw = 50 - (atrZ * 25)
timeseries volFactor = math.min(100, math.max(0, volRaw))
// -- 3.4 Volume Factor (0-100) --
// Relative volume with directional bias: up-volume above average = bullish;
// down-volume above average = bearish. Normalised to 0-100.
timeseries volSma = sma(source=bars.volume, period=volSmaLen)
timeseries volRatio = (volSma > 0) ? bars.volume / volSma : 1
timeseries volDir = (px[0] > px[1]) ? 1 : ((px[0] < px[1]) ? -1 : 0)
timeseries volRawScore = 50 + (volDir * (volRatio - 1) * 25)
timeseries volumeFactor = math.min(100, math.max(0, volRawScore))
// If volume is missing, neutral
timeseries volFactorSafe = volAvailable ? volumeFactor : 50
// ----------------------------------------------------------------------------
// 4. COMPOSITE SCORE
// ----------------------------------------------------------------------------
// Normalise weights so they sum to 1.0 even if user sets them to non-100 total
var totalWeight = trendWeight + momWeight + volWeight + volWeightInput
var normTrend = totalWeight > 0 ? trendWeight / totalWeight : 0.25
var normMom = totalWeight > 0 ? momWeight / totalWeight : 0.25
var normVol = totalWeight > 0 ? volWeight / totalWeight : 0.25
var normVolF = totalWeight > 0 ? volWeightInput / totalWeight : 0.25
timeseries composite = (
trendFactor * normTrend +
momFactor * normMom +
volFactor * normVol +
volFactorSafe * normVolF
)
timeseries score = ema(source=composite, period=scoreSmooth)
// ----------------------------------------------------------------------------
// 5. REGIME DETECTION
// ----------------------------------------------------------------------------
// Regime classification:
// Bullish: score > 60 and score > score[1] (rising)
// Bearish: score < 40 and score < score[1] (falling)
// Neutral: everything else
var scoreRising = score[0] > score[1]
var scoreFalling = score[0] < score[1]
var regimeBull = score > 60 && scoreRising
var regimeBear = score < 40 && scoreFalling
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// ----------------------------------------------------------------------------
// 6. DYNAMIC THRESHOLDS
// ----------------------------------------------------------------------------
var scoreVol = stdev(source=score, period=volLookback)
var dynBull = useDynamic ? math.min(85, 60 + scoreVol * dynMult) : 60
var dynBear = useDynamic ? math.max(15, 40 - scoreVol * dynMult) : 40
// Guard: ensure thresholds never cross
if (dynBull <= dynBear) {
dynBull = 60
dynBear = 40
}
// ----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// ----------------------------------------------------------------------------
var crossUp = score > dynBull && score[1] <= dynBull
var crossDown = score < dynBear && score[1] >= dynBear
var exitBull = score < dynBull && score[1] >= dynBull
var exitBear = score > dynBear && score[1] <= dynBear
var extremeOver = score > 85 && score[1] <= 85
var extremeUnder = score < 15 && score[1] >= 15
// ----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// ----------------------------------------------------------------------------
static prevScore = -1.0
static bullStreak = 0
static bearStreak = 0
static neutralStreak = 0
static maxScore = -1.0
static minScore = 101.0
static regimeChanges = 0
static prevRegime = 0
if (prevScore < 0) {
prevScore = score[0]
maxScore = score[0]
minScore = score[0]
}
if (!isLiveUpdate) {
prevScore = score[0]
if (score[0] > maxScore) { maxScore = score[0] }
if (score[0] < minScore) { minScore = score[0] }
if (regimeBull) {
bullStreak = bullStreak + 1
bearStreak = 0
neutralStreak = 0
} else if (regimeBear) {
bearStreak = bearStreak + 1
bullStreak = 0
neutralStreak = 0
} else {
neutralStreak = neutralStreak + 1
bullStreak = 0
bearStreak = 0
}
var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
if (currentRegime != prevRegime) {
regimeChanges = regimeChanges + 1
}
prevRegime = currentRegime
}
// ----------------------------------------------------------------------------
// 9. VISUALIZATION
// ----------------------------------------------------------------------------
// --- Midline ---
hline(value=50, color="#ffffff20", width=1)
// --- Dynamic Zone Fills ---
if (showFill) {
hline(value=dynBull, color=transparency(bullColor, 60), width=1)
hline(value=dynBear, color=transparency(bearColor, 60), width=1)
}
// --- Zone Fill (composite vs neutral band) ---
if (showFill) {
var aboveNeutral = score > 50
plotLine(
value=[score, 50],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=aboveNeutral ? 0 : 1,
fill=true,
label=["Composite", "Neutral"],
desc=["Fill between composite score and neutral midline"]
)
}
// --- Individual Factor Lines ---
if (showFactors) {
plotLine(
value=trendFactor,
width=1,
colors=["#42a5f5"],
label=["Trend"],
desc=["Trend factor (0-100): EMA alignment"]
)
plotLine(
value=momFactor,
width=1,
colors=["#ab47bc"],
label=["Momentum"],
desc=["Momentum factor (0-100): smoothed RSI"]
)
plotLine(
value=volFactor,
width=1,
colors=["#ffa726"],
label=["Volatility"],
desc=["Volatility factor (0-100): ATR compression/expansion"]
)
if (volAvailable) {
plotLine(
value=volFactorSafe,
width=1,
colors=["#8d6e63"],
label=["Volume"],
desc=["Volume factor (0-100): relative volume with directional bias"]
)
}
}
// --- Composite Score (regime-colored) ---
if (showComposite) {
plotLine(
value=score,
width=3,
colors=[regimeColor],
label=["DIY Score"],
desc=["Weighted composite score: trend + momentum + volatility + volume"]
)
}
// --- Momentum Histogram (score vs 50) ---
if (showHistogram) {
timeseries hist = score - 50
var histBull = hist >= 0
plotBar(
value=hist,
colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Score Momentum"],
desc=["Histogram of composite score minus neutral midline"]
)
}
// --- Signal Shapes ---
if (showShapes) {
if (crossUp) {
plotShape(
value=score,
shape="triangleup",
colorIndex=bullColor,
width=2,
label=["Bull Trigger"],
desc=["Score crossed above dynamic bullish threshold"]
)
}
if (crossDown) {
plotShape(
value=score,
shape="triangledown",
colorIndex=bearColor,
width=2,
label=["Bear Trigger"],
desc=["Score crossed below dynamic bearish threshold"]
)
}
if (extremeOver) {
plotShape(
value=score,
shape="xcross",
colorIndex=bearColor,
width=2,
label=["Extreme Over"],
desc=["Score reached extreme overbought territory (>85)"]
)
}
if (extremeUnder) {
plotShape(
value=score,
shape="xcross",
colorIndex=bullColor,
width=2,
label=["Extreme Under"],
desc=["Score reached extreme oversold territory (<15)"]
)
}
if (regimeBull && bullStreak == 3) {
plotShape(
value=score,
shape="arrowup",
colorIndex=bullColor,
width=1,
label=["Bull Confirmed"],
desc=["Bullish regime confirmed after 3 consecutive bars"]
)
}
if (regimeBear && bearStreak == 3) {
plotShape(
value=score,
shape="arrowdown",
colorIndex=bearColor,
width=1,
label=["Bear Confirmed"],
desc=["Bearish regime confirmed after 3 consecutive bars"]
)
}
}
// ----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["DIY Composite Score", regimeText],
["Score", score[0]],
["Trend Factor", trendFactor[0]],
["Momentum Factor", momFactor[0]],
["Volatility Factor", volFactor[0]],
["Volume Factor", volFactorSafe[0]],
["Bull Streak", bullStreak],
["Bear Streak", bearStreak],
["Max Score", maxScore],
["Min Score", minScore],
["Regime Changes", regimeChanges]
],
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
)
}