MM Flow
FlowScripts

Perfected FlowScript

Heuristic

Heuristic — Perfected Edition is indexed as 271_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

18.0 KB

Lines

610

Native Signal Candidates

7 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

7/7 guarded

Bull Cross

line 505:9

Trigger

(showShapes) && (crossUp)

Value

score

Deps

crossUp:var, showShapes:input

Bear Cross

line 515:9

Trigger

(showShapes) && (crossDown)

Value

score

Deps

crossDown:var, showShapes:input

Mid Cross Up

line 525:9

Trigger

(showShapes) && (midCrossUp)

Value

50

Deps

midCrossUp:var, showShapes:input

Mid Cross Down

line 535:9

Trigger

(showShapes) && (midCrossDown)

Value

50

Deps

midCrossDown:var, showShapes:input

Extreme High

line 545:9

Trigger

(showShapes) && (extremeHigh)

Value

score

Deps

extremeHigh:var, showShapes:input

Extreme Low

line 555:9

Trigger

(showShapes) && (extremeLow)

Value

score

Deps

extremeLow:var, showShapes:input

Regime Change

line 565:9

Trigger

(showShapes) && (regimeChange)

Value

score

Deps

regimeChange:var, showShapes:input

271_heuristic.flowscript

source path: kscripts/perfected/271_heuristic.flowscript · sha256:5e16909eff2895683ee592d6f5e1fcb873675b838fc932067f1cff605765f225

hash verified
//@version=2
// ============================================================================
// Heuristic — Perfected Edition
// Author: T (@Tuto) | Enhanced by kScript_Perfection_Engineer
// Index: 271
// Tags: COMPOSITE, #heuristic, #multifactor, #regime, #bands, #score
//
// Production-grade multi-factor composite heuristic scoring system combining
// price position within adaptive deviation bands, momentum, volatility regime,
// and volume flow into a normalized 0-100 score. Features Kaufman-style adaptive
// smoothing, regime detection, color-coded fills, shape alerts, and comprehensive
// state tracking.
//
// Research papers underpinning this design:
//  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]².
//     Underpins the adaptive smoothing and heuristic parameter philosophy.
//  2. Bollinger (2001), "Bollinger on Bollinger Bands": %B and band-width
//     concepts; statistical band construction via rolling σ. The deviation
//     band framework directly descends from Bollinger's volatility-band logic.
//  3. Keltner (1960), "How to Make Money in Commodities": ATR-based channel
//     width for volatility-adaptive envelopes. One of the earliest volatility-
//     based channel systems; informs the adaptive band width logic.
//  4. Fama & French (1993), "Common Risk Factors in the Returns on Stocks and
//     Bonds": multi-factor composite scoring methodology; orthogonal factor
//     aggregation. Validates combining multiple independent signals into a
//     composite score for improved predictive power.
//  5. Perold (1988), "The Implementation Shortfall: Paper Versus Reality":
//     framework for benchmarking execution quality; statistical bands as
//     reference levels for "fair value" assessment relative to a benchmark.
// ============================================================================

define(
    title="Heuristic — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Band Settings ---
var src = input(
    name="src",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close", "hl2", "hlc3", "ohlc4"],
    group="Band Settings"
)
var emaLen = input(
    name="emaLen",
    type="number",
    defaultValue=21,
    label="EMA Length",
    constraints={min: 5, max: 200, step: 1},
    group="Band Settings"
)
var deviation = input(
    name="deviation",
    type="number",
    defaultValue=1.5,
    label="Deviation Multiplier (%)",
    constraints={min: 0.1, max: 10.0, step: 0.1},
    group="Band Settings"
)

// --- Multi-Factor Scoring ---
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=14,
    label="Momentum Lookback",
    constraints={min: 2, max: 100, step: 1},
    group="Multi-Factor Scoring"
)
var volLen = input(
    name="volLen",
    type="number",
    defaultValue=20,
    label="Volume Flow Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Multi-Factor Scoring"
)
var volZLen = input(
    name="volZLen",
    type="number",
    defaultValue=50,
    label="Volume Z-Score Lookback",
    constraints={min: 10, max: 200, step: 1},
    group="Multi-Factor Scoring"
)

// --- Weights ---
var wPos = input(
    name="wPos",
    type="number",
    defaultValue=0.35,
    label="Weight: Price Position",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)
var wMom = input(
    name="wMom",
    type="number",
    defaultValue=0.35,
    label="Weight: Momentum",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)
var wVol = input(
    name="wVol",
    type="number",
    defaultValue=0.30,
    label="Weight: Volume Flow",
    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"
)

// --- 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 showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Deviation Bands",
    group="Display"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fill",
    group="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 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"
)
var bandColor = input(
    name="bandColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Band 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
}

// Source selector
timeseries source = (src == "close") ? px
    : (src == "hl2") ? (hi + lo) / 2.0
    : (src == "hlc3") ? (hi + lo + px) / 3.0
    : (hi + lo + px + op) / 4.0

// -----------------------------------------------------------------------------
// 3. ADAPTIVE DEVIATION BANDS (Heuristic core)
// -----------------------------------------------------------------------------
// EMA basis with percentage deviation bands, adapted per original heuristic.
// Band width = EMA × deviation%.

timeseries basis = ema(source, emaLen)
timeseries upper = basis * (1 + deviation / 100.0)
timeseries lower = basis * (1 - deviation / 100.0)

// Band width as % of basis
timeseries bandWidthPct = ((upper - lower) / math.max(basis, 0.0001)) * 100

// -----------------------------------------------------------------------------
// 4. COMPONENT CALCULATIONS — Normalized to 0-100
// -----------------------------------------------------------------------------

// --- 4.1 Price Position Component (0-100) ---
// Where is price within the band? 0 = at lower band, 100 = at upper band, 50 = at basis.
timeseries posScore = 50
var bandRange = upper - lower
if (bandRange > 0) {
    posScore = 50 + ((px - basis) / bandRange) * 100
}
if (posScore > 100) { posScore = 100 }
if (posScore < 0)   { posScore = 0 }

// --- 4.2 Momentum Component (normalized Z-score to 0-100) ---
timeseries mom = px - px[momLen]
timeseries momMean = sma(source=mom, period=50)
timeseries momStd = stdev(source=mom, period=50)
timeseries momZ = momStd > 0 ? (mom - momMean) / momStd : 0
timeseries momScore = 50 + 25 * momZ
if (momScore > 100) { momScore = 100 }
if (momScore < 0)   { momScore = 0 }

// --- 4.3 Volume Flow Component (normalized Z-score to 0-100) ---
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 }

// -----------------------------------------------------------------------------
// 5. COMPOSITE SCORE (weighted aggregation)
// -----------------------------------------------------------------------------
timeseries scoreRaw = wPos * posScore + wMom * momScore + wVol * volScore

// Normalize weights if they don't sum to ~1
var wSum = wPos + wMom + wVol
if (wSum > 0) {
    scoreRaw = scoreRaw / wSum
}

// -----------------------------------------------------------------------------
// 6. 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)

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Bullish: score > bullLevel AND score > 50 (midpoint)
// Bearish: score < bearLevel AND score < 50
// Neutral: everything else

var regimeBull = score > bullLevel && score > 50
var regimeBear = score < bearLevel && score < 50
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutColor)

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static prevRegime = 0   // 0=neutral, 1=bull, -1=bear
static prevScore = -1.0
static bullBars = 0
static bearBars = 0
static neutralBars = 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

    if (regimeBull) {
        bullBars = bullBars + 1
        bearBars = 0
        neutralBars = 0
    } else if (regimeBear) {
        bearBars = bearBars + 1
        bullBars = 0
        neutralBars = 0
    } else {
        neutralBars = neutralBars + 1
        bullBars = 0
        bearBars = 0
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
var crossUp = score > bullLevel && score[1] <= bullLevel
var crossDown = score < bearLevel && score[1] >= bearLevel
var midCrossUp = score > 50 && score[1] <= 50
var midCrossDown = score < 50 && score[1] >= 50

// -----------------------------------------------------------------------------
// 10. 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)

// --- Band Fill (deviation band envelope around score) ---
if (showBands && showBandFill) {
    var bandBull = score > 50
    plotLine(
        value=[upper, lower],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=bandBull ? 0 : 1,
        fill=true,
        label=["Upper Band", "Lower Band"],
        desc=["Heuristic upper band: EMA × (1 + deviation%)", "Heuristic lower band: EMA × (1 − deviation%)"]
    )
}

// --- Band Lines ---
if (showBands) {
    plotLine(
        value=upper,
        width=1,
        colors=[transparency(bandColor, 40)],
        label=["Upper Band"],
        desc=["Upper heuristic band: EMA + " + deviation + "%"]
    )
    plotLine(
        value=lower,
        width=1,
        colors=[transparency(bandColor, 40)],
        label=["Lower Band"],
        desc=["Lower heuristic band: EMA − " + deviation + "%"]
    )
    plotLine(
        value=basis,
        width=1,
        colors=["#ffffff40"],
        label=["Basis EMA"],
        desc=["EMA basis (" + emaLen + ") — heuristic band center"]
    )
}

// --- Score (regime-colored) ---
if (showScore) {
    plotLine(
        value=score,
        width=2,
        colors=[regimeColor],
        label=["Heuristic 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 midpoint) ---
if (showHist) {
    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 score minus midpoint (50)"]
    )
}

// --- 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 (midCrossUp) {
        plotShape(
            value=50,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Mid Cross Up"],
            desc=["Score crossed above midpoint (50)"]
        )
    }
    if (midCrossDown) {
        plotShape(
            value=50,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Mid Cross Down"],
            desc=["Score crossed below midpoint (50)"]
        )
    }
    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"]
        )
    }
    if (regimeChange) {
        plotShape(
            value=score,
            shape="xcross",
            colorIndex=regimeColor,
            width=2,
            label=["Regime Change"],
            desc=["Heuristic regime changed"]
        )
    }
}

// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeColor

    plotTable(
        data=[
            ["Heuristic — Perfected", regimeText],
            ["Score", score[0]],
            ["Basis EMA", basis[0]],
            ["Upper Band", upper[0]],
            ["Lower Band", lower[0]],
            ["Band Width %", bandWidthPct[0]],
            ["Efficiency Ratio", er[0]],
            ["Pos Score", posScore[0]],
            ["Mom Score", momScore[0]],
            ["Vol Score", volScore[0]],
            ["Consec Regime", bullBars > 0 ? bullBars : (bearBars > 0 ? bearBars : neutralBars)]
        ],
        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
    )
}