Perfected FlowScript
SCF Heuristic
SCF Heuristic — Perfected Edition is indexed as 097_scf_heuristic.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.3 KB
Lines
607
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Cross
line 514:9
Trigger
(showShapes) && (crossUp)
Value
score
Deps
crossUp:var, showShapes:input
Bear Cross
line 524:9
Trigger
(showShapes) && (crossDown)
Value
score
Deps
crossDown:var, showShapes:input
Upper Band Touch
line 534:9
Trigger
(showShapes) && (bandTouchUpper)
Value
bandUpper
Deps
bandTouchUpper:var, showShapes:input
Lower Band Touch
line 544:9
Trigger
(showShapes) && (bandTouchLower)
Value
bandLower
Deps
bandTouchLower:var, showShapes:input
Extreme High
line 554:9
Trigger
(showShapes) && (extremeHigh)
Value
score
Deps
extremeHigh:var, showShapes:input
Extreme Low
line 564:9
Trigger
(showShapes) && (extremeLow)
Value
score
Deps
extremeLow:var, showShapes:input
097_scf_heuristic.flowscript
source path: kscripts/perfected/097_scf_heuristic.flowscript · sha256:c24fde996815881197940202bae37e094b8da0676850039099829e501a98ad24
//@version=2
// ============================================================================
// SCF Heuristic — Perfected Edition
// Author: SoulzBTC (@SoulzBTC) | Enhanced by kScript Perfection Engineer
// Tags: COMPOSITE, #heuristic, #multifactor, #regime, #keltner, #bollinger
//
// Production-grade multi-factor composite heuristic combining normalized
// momentum, volume flow, and volatility regime into a 0–100 score, enhanced
// with Keltner/Bollinger hybrid adaptive bands, Kaufman-style adaptive
// smoothing, regime detection, color-coded fills, and stateful event
// tracking.
//
// Academic foundations:
// 1. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
// Markets": KAMA/ER adaptive smoothing. ER = Change / Volatility;
// SC = [ER × (Fastest SC − Slowest SC) + Slowest SC]². [^9]
// 2. Bollinger (2001), "Bollinger on Bollinger Bands": %B and band-width
// concepts; statistical band construction via rolling σ. [^26]
// 3. Keltner (1960), "How to Make Money in Commodities": ATR-based channel
// width for volatility-adaptive envelopes. [^3]
// 4. Fama & French (1993), "Common Risk Factors": multi-factor composite
// scoring methodology; orthogonal factor aggregation. [^19]
// 5. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
// Stock Returns": composite index construction via weighted proxies. [^32]
// 6. Chande & Kroll (1994), "The New Technical Trader": VIDYA adaptive
// smoothing using CMO as volatility index; adaptive momentum. [^29]
// ============================================================================
define(
title="SCF Heuristic — Perfected Edition",
position="offchart",
axis=true
)
// -------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -------------------------------------------------------------------------
// --- Momentum ---
var momLen = input(
name="momLen",
type="number",
defaultValue=14,
label="Momentum Lookback",
constraints={min: 2, max: 100, step: 1},
group="Momentum"
)
var momNormLen = input(
name="momNormLen",
type="number",
defaultValue=50,
label="Momentum Normalization Window",
constraints={min: 10, max: 200, step: 1},
group="Momentum"
)
// --- Volume ---
var volLen = input(
name="volLen",
type="number",
defaultValue=20,
label="Volume Flow Lookback",
constraints={min: 5, max: 100, step: 1},
group="Volume"
)
var volZLen = input(
name="volZLen",
type="number",
defaultValue=50,
label="Volume Z-Score Lookback",
constraints={min: 10, max: 200, step: 1},
group="Volume"
)
// --- Weights ---
var wMom = input(
name="wMom",
type="number",
defaultValue=0.40,
label="Weight: Momentum",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Weights"
)
var wVol = input(
name="wVol",
type="number",
defaultValue=0.35,
label="Weight: Volume Flow",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Weights"
)
var wVolZ = input(
name="wVolZ",
type="number",
defaultValue=0.25,
label="Weight: Volume Extremity",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Weights"
)
// --- Adaptive Smoothing ---
var useAdaptive = input(
name="useAdaptive",
type="boolean",
defaultValue=true,
label="Use Kaufman Adaptive Smoothing",
group="Adaptive Smoothing"
)
var erLen = input(
name="erLen",
type="number",
defaultValue=10,
label="Efficiency Ratio Period",
constraints={min: 2, max: 50, step: 1},
group="Adaptive Smoothing"
)
var fastSC = input(
name="fastSC",
type="number",
defaultValue=2,
label="Fastest EMA Period",
constraints={min: 2, max: 10, step: 1},
group="Adaptive Smoothing"
)
var slowSC = input(
name="slowSC",
type="number",
defaultValue=30,
label="Slowest EMA Period",
constraints={min: 10, max: 100, step: 1},
group="Adaptive Smoothing"
)
// --- Hybrid Bands ---
var bandLookback = input(
name="bandLookback",
type="number",
defaultValue=20,
label="Band Lookback (σ + ATR)",
constraints={min: 5, max: 100, step: 1},
group="Hybrid Bands"
)
var bandMult = input(
name="bandMult",
type="number",
defaultValue=2.0,
label="Band Multiplier (σ)",
constraints={min: 0.5, max: 5.0, step: 0.1},
group="Hybrid Bands"
)
var atrMult = input(
name="atrMult",
type="number",
defaultValue=1.5,
label="ATR Band Multiplier",
constraints={min: 0.5, max: 5.0, step: 0.1},
group="Hybrid Bands"
)
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 5, max: 100, step: 1},
group="Hybrid Bands"
)
// --- Thresholds ---
var bullLevel = input(
name="bullLevel",
type="number",
defaultValue=60,
label="Bullish Threshold",
constraints={min: 50, max: 80, step: 1},
group="Thresholds"
)
var bearLevel = input(
name="bearLevel",
type="number",
defaultValue=40,
label="Bearish Threshold",
constraints={min: 20, max: 50, step: 1},
group="Thresholds"
)
// --- Display ---
var showScore = input(
name="showScore",
type="boolean",
defaultValue=true,
label="Show Composite Score",
group="Display"
)
var showRaw = input(
name="showRaw",
type="boolean",
defaultValue=false,
label="Show Raw Score",
group="Display"
)
var showBands = input(
name="showBands",
type="boolean",
defaultValue=true,
label="Show Hybrid Bands",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Band Fill",
group="Display"
)
var showHist = input(
name="showHist",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Alert 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 neutColor = input(
name="neutColor",
type="color",
defaultValue="#9e9e9e",
label="Neutral Color",
group="Colors"
)
// -------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries op = bars.open
timeseries hi = bars.high
timeseries lo = bars.low
timeseries vol = bars.volume
if (isnan(px[0]) || isnan(vol[0])) {
return
}
// -------------------------------------------------------------------------
// 3. COMPONENT CALCULATIONS
// -------------------------------------------------------------------------
// --- 3.1 Momentum Component (normalized to 0-100) ---
timeseries mom = px - px[momLen]
timeseries momMean = sma(source=mom, period=momNormLen)
timeseries momStd = stdev(source=mom, period=momNormLen)
timeseries momZ = momStd > 0 ? (mom - momMean) / momStd : 0
timeseries momScore = 50 + 25 * momZ
if (momScore > 100) {
momScore = 100
}
if (momScore < 0) {
momScore = 0
}
// --- 3.2 Volume Flow Component ---
var isUpBar = px > op
var isDnBar = px < op
var signedVol = isUpBar ? vol : (isDnBar ? -vol : 0)
timeseries volFlow = ema(source=signedVol, period=volLen)
timeseries volFlowMean = sma(source=volFlow, period=volZLen)
timeseries volFlowStd = stdev(source=volFlow, period=volZLen)
timeseries volFlowZ = volFlowStd > 0 ? (volFlow - volFlowMean) / volFlowStd : 0
timeseries volScore = 50 + 25 * volFlowZ
if (volScore > 100) {
volScore = 100
}
if (volScore < 0) {
volScore = 0
}
// --- 3.3 Volume Extremity Component ---
timeseries volMean = sma(source=vol, period=volZLen)
timeseries volStd = stdev(source=vol, period=volZLen)
timeseries volZRaw = volStd > 0 ? (vol - volMean) / volStd : 0
timeseries volZScore = 50 + 25 * volZRaw
if (volZScore > 100) {
volZScore = 100
}
if (volZScore < 0) {
volZScore = 0
}
// --- 3.4 Composite Score (weighted) ---
timeseries scoreRaw = wMom * momScore + wVol * volScore + wVolZ * volZScore
// Normalize weights if they don't sum to ~1
var wSum = wMom + wVol + wVolZ
if (wSum > 0) {
scoreRaw = scoreRaw / wSum
}
// -------------------------------------------------------------------------
// 4. ADAPTIVE SMOOTHING (Kaufman Efficiency Ratio)
// -------------------------------------------------------------------------
// ER = Change / Volatility; SC = [ER × (FastSC − SlowSC) + SlowSC]²
// Adapted for kScript: use the ER to blend between fast and slow EMA constants.
timeseries erChange = math.abs(px - px[erLen])
timeseries erVol = 0.0
for (var i = 1; i <= erLen; i = i + 1) {
erVol = erVol + math.abs(px - px[i])
}
timeseries er = erVol > 0 ? erChange / erVol : 0
// Smoothing constant: blend between fast and slow
var fastSCConst = 2.0 / (fastSC + 1.0)
var slowSCConst = 2.0 / (slowSC + 1.0)
timeseries sc = math.pow(er * (fastSCConst - slowSCConst) + slowSCConst, 2)
// KAMA-style adaptive smoothing of scoreRaw
static kamaScore = -1.0
if (kamaScore < 0) {
kamaScore = scoreRaw
} else {
kamaScore = kamaScore + sc * (scoreRaw - kamaScore)
}
timeseries score = useAdaptive ? kamaScore : ema(source=scoreRaw, period=3)
// -------------------------------------------------------------------------
// 5. HYBRID BANDS (Keltner + Bollinger)
// -------------------------------------------------------------------------
// Middle = EMA of score; Upper/Lower = middle ± blend(σ, ATR)
timeseries bandMid = ema(source=score, period=bandLookback)
timeseries bandStd = stdev(source=score, period=bandLookback)
// ATR on score (treat score as price proxy)
timeseries scoreChange = math.abs(score - score[1])
timeseries scoreTR = math.max(scoreChange, math.max(math.abs(score - score[1]), math.abs(score[1] - score[2])))
// Guard: score[2] might be NaN early on
if (isnan(score[2])) {
scoreTR = scoreChange
}
timeseries scoreATR = sma(source=scoreTR, period=atrLen)
// Hybrid band width = max(σ × mult, ATR × atrMult) for robustness
timeseries bandWidth = math.max(bandStd * bandMult, scoreATR * atrMult)
timeseries bandUpper = bandMid + bandWidth
timeseries bandLower = bandMid - bandWidth
// Guard bands within 0-100
if (bandUpper > 100) {
bandUpper = 100
}
if (bandLower < 0) {
bandLower = 0
}
// -------------------------------------------------------------------------
// 6. REGIME DETECTION
// -------------------------------------------------------------------------
// Bullish: score > bullLevel AND score > bandMid
// Bearish: score < bearLevel AND score < bandMid
// Neutral: everything else
var regimeBull = score > bullLevel && score > bandMid
var regimeBear = score < bearLevel && score < bandMid
var regimeNeutral = !regimeBull && !regimeBear
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutColor)
// -------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// -------------------------------------------------------------------------
static prevRegime = 0 // 0=neutral, 1=bull, -1=bear
static prevScore = -1.0
var regimeChange = false
var extremeHigh = false
var extremeLow = false
if (!isLiveUpdate) {
if (prevRegime != 0 && ((regimeBull && prevRegime != 1) || (regimeBear && prevRegime != -1) || (regimeNeutral && prevRegime != 0))) {
regimeChange = true
}
if (score > 90 && prevScore > 0 && score < prevScore) {
extremeHigh = true
}
if (score < 10 && prevScore > 0 && score > prevScore) {
extremeLow = true
}
prevRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
prevScore = score
}
// -------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -------------------------------------------------------------------------
var crossUp = score > bullLevel && score[1] <= bullLevel
var crossDown = score < bearLevel && score[1] >= bearLevel
var bandTouchUpper = score >= bandUpper && score[1] < bandUpper
var bandTouchLower = score <= bandLower && score[1] > bandLower
// -------------------------------------------------------------------------
// 9. PLOTTING
// -------------------------------------------------------------------------
// --- Midline ---
hline(value=50, color="#ffffff20", width=1)
// --- Thresholds ---
hline(value=bullLevel, color=transparency(bullColor, 60), width=1)
hline(value=bearLevel, color=transparency(bearColor, 60), width=1)
// --- Hybrid Band Fill ---
if (showBands && showFill) {
var bandBull = score > bandMid
plotLine(
value=[bandUpper, bandLower],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=bandBull ? 0 : 1,
fill=true,
label=["Upper Band", "Lower Band"],
desc=["Hybrid Keltner/Bollinger upper band", "Hybrid Keltner/Bollinger lower band"]
)
}
// --- Band Lines ---
if (showBands) {
plotLine(
value=bandUpper,
width=1,
colors=[transparency(bullColor, 40)],
label=["Upper Band"],
desc=["Hybrid upper band: max(σ×" + bandMult + ", ATR×" + atrMult + ")"]
)
plotLine(
value=bandLower,
width=1,
colors=[transparency(bearColor, 40)],
label=["Lower Band"],
desc=["Hybrid lower band: max(σ×" + bandMult + ", ATR×" + atrMult + ")"]
)
plotLine(
value=bandMid,
width=1,
colors=["#ffffff40"],
label=["Band Mid"],
desc=["EMA of score (band center)"]
)
}
// --- Score (regime-colored) ---
if (showScore) {
plotLine(
value=score,
width=2,
colors=[regimeColor],
label=["SCF Score"],
desc=["Adaptive composite heuristic score (0-100)"]
)
}
// --- Raw Score ---
if (showRaw) {
plotLine(
value=scoreRaw,
width=1,
colors=["#9e9e9e"],
label=["Raw Score"],
desc=["Unsmoothed composite score"]
)
}
// --- Momentum Histogram (score vs bandMid) ---
if (showHist) {
timeseries hist = score - bandMid
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 score minus band midpoint"]
)
}
// --- Shape Markers ---
if (showShapes) {
if (crossUp) {
plotShape(
value=score,
shape="triangleup",
colorIndex=bullColor,
width=2,
label=["Bull Cross"],
desc=["Score crossed above bullish threshold (" + bullLevel + ")"]
)
}
if (crossDown) {
plotShape(
value=score,
shape="triangledown",
colorIndex=bearColor,
width=2,
label=["Bear Cross"],
desc=["Score crossed below bearish threshold (" + bearLevel + ")"]
)
}
if (bandTouchUpper) {
plotShape(
value=bandUpper,
shape="xcross",
colorIndex=bearColor,
width=2,
label=["Upper Band Touch"],
desc=["Score touched upper hybrid band — potential exhaustion"]
)
}
if (bandTouchLower) {
plotShape(
value=bandLower,
shape="xcross",
colorIndex=bullColor,
width=2,
label=["Lower Band Touch"],
desc=["Score touched lower hybrid band — potential accumulation"]
)
}
if (extremeHigh) {
plotShape(
value=score,
shape="arrowdown",
colorIndex=bearColor,
width=1,
label=["Extreme High"],
desc=["Score > 90 and turning down — extreme bullish exhaustion"]
)
}
if (extremeLow) {
plotShape(
value=score,
shape="arrowup",
colorIndex=bullColor,
width=1,
label=["Extreme Low"],
desc=["Score < 10 and turning up — extreme bearish exhaustion"]
)
}
}
// -------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regimeColor
plotTable(
data=[
["SCF Heuristic — Perfected", regimeText],
["Score", score[0]],
["Band Mid", bandMid[0]],
["Upper Band", bandUpper[0]],
["Lower Band", bandLower[0]],
["Efficiency Ratio", er[0]],
["Momentum", momScore[0]],
["Volume Flow", volScore[0]],
["Volume Z", volZScore[0]]
],
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
)
}