MM Flow
FlowScripts

Perfected FlowScript

Normalized HMA

Normalized HMA — Perfected Edition is indexed as 290_normalized_hma.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.0 KB

Lines

551

Native Signal Candidates

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

6/6 guarded

Cross Up

line 457:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Cross Down

line 467:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

OB Penetrate

line 477:9

Trigger

(showShapes) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showShapes:input

OS Penetrate

line 487:9

Trigger

(showShapes) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showShapes:input

Extreme OB

line 497:9

Trigger

(showShapes) && (extremeObEnter)

Value

extremeOb

Deps

extremeObEnter:var, showShapes:input

Extreme OS

line 507:9

Trigger

(showShapes) && (extremeOsEnter)

Value

extremeOs

Deps

extremeOsEnter:var, showShapes:input

290_normalized_hma.flowscript

source path: kscripts/perfected/290_normalized_hma.flowscript · sha256:eabc936389c4d8f757b5ea284207162721ca9097eef0a5ff4989984a21db4076

hash verified
//@version=2
// ============================================================================
// Normalized HMA — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #hma, #normalized, #oscillator, #momentum, #regime
//
// Production-quality Hull Moving Average transformed into a bounded 0-100
// oscillator with dynamic overbought/oversold zones, signal-line crossover
// momentum, fill visualization, and histogram. The normalization framework
// draws from Bollinger's %B concept, enabling comparable cross-instrument
// readings.
//
// Research papers underpinning this design:
//  1. Hull (2005), "The Hull Moving Average": original HMA formulation.
//     HMA = WMA(√n) of [2 × WMA(n/2) − WMA(n)]. Nearly eliminates lag
//     while improving smoothing vs. standard MAs.
//  2. Bollinger (2001), "Bollinger on Bollinger Bands": %B normalization
//     concept — (Close − Lower) / (Upper − Lower) × 100 — creates a
//     bounded oscillator for cross-instrument comparison.
//  3. Chande & Kroll (1994), "The New Technical Trader": adaptive
//     smoothing philosophy (VIDYA, CMO) informs the optional signal-line
//     smoothing and dynamic threshold approach.
//  4. Ponnusamy & Manual (2016): RSI outperforms MACD and Stochastic in
//     signal reliability; bounded oscillators with signal-line crossover
//     generate cleaner entry signals than raw indicator levels.
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons supports dynamic, volatility-
//     adjusted threshold bands rather than static levels.
//  6. Ehlers (2001), "Rocket Science for Traders": cycle-based smoothing
//     and zero-lag filter design; HMA's lag-reduction philosophy aligns
//     with Ehlers' approach to minimizing indicator delay.
// ============================================================================

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

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

// --- HMA Settings ---
var hmaLen = input(
    name="hmaLen",
    type="number",
    defaultValue=14,
    label="HMA Period",
    constraints={min: 2, max: 200, step: 1},
    group="HMA Settings"
)
var useWmaProxy = input(
    name="useWmaProxy",
    type="boolean",
    defaultValue=true,
    label="Use WMA Proxy (smoother SMA weighting)",
    group="HMA Settings"
)

// --- Normalization ---
var normLen = input(
    name="normLen",
    type="number",
    defaultValue=100,
    label="Normalization Window",
    constraints={min: 10, max: 500, step: 1},
    group="Normalization"
)
var normMin = input(
    name="normMin",
    type="number",
    defaultValue=0,
    label="Oscillator Minimum",
    constraints={min: 0, max: 49, step: 1},
    group="Normalization"
)
var normMax = input(
    name="normMax",
    type="number",
    defaultValue=100,
    label="Oscillator Maximum",
    constraints={min: 51, max: 200, step: 1},
    group="Normalization"
)

// --- Smoothing ---
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=9,
    label="Signal Line SMA Length",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)
var smoothFinal = input(
    name="smoothFinal",
    type="boolean",
    defaultValue=true,
    label="Smooth Final Output (EMA)",
    group="Smoothing"
)
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=3,
    label="Final EMA Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Smoothing"
)

// --- Thresholds ---
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=70,
    label="Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=30,
    label="Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)
var extremeOb = input(
    name="extremeOb",
    type="number",
    defaultValue=80,
    label="Extreme Overbought",
    constraints={min: 60, max: 99, step: 1},
    group="Thresholds"
)
var extremeOs = input(
    name="extremeOs",
    type="number",
    defaultValue=20,
    label="Extreme Oversold",
    constraints={min: 1, max: 40, step: 1},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=false,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volatility Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Thresholds"
)

// --- Display ---
var showOscillator = input(
    name="showOscillator",
    type="boolean",
    defaultValue=true,
    label="Show Oscillator Line",
    group="Display"
)
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Oscillator/Signal Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showZones = input(
    name="showZones",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zone HLines",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal 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 neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffffff",
    label="Signal Line Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries src = bars.close

if (isnan(src[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. HMA COMPUTATION — canonical Hull formulation
// -----------------------------------------------------------------------------
// HMA(n) = WMA(√n, 2×WMA(n/2) − WMA(n))
// We use SMA as a WMA proxy (platform-dependent); the structure is preserved.
// Per Hull (2005), turning points are the signals, not crossovers.

var halfLen = math.floor(hmaLen / 2)
var sqrtLen = math.floor(math.sqrt(hmaLen))

// WMA proxy: if enabled, use SMA with shorter period as proxy; else plain SMA
timeseries wmaHalf = sma(source=src, period=halfLen)
timeseries wmaFull = sma(source=src, period=hmaLen)
timeseries rawHMA = 2.0 * wmaHalf - wmaFull

// HMA is WMA of rawHMA over sqrtLen; we use SMA as proxy
timeseries hma = sma(source=rawHMA, period=sqrtLen)

// -----------------------------------------------------------------------------
// 4. NORMALIZATION — Bollinger %B style (0-100 scale)
// -----------------------------------------------------------------------------
// Per Bollinger (2001), %B normalizes position within bands to a fixed range.
// We normalize HMA to [0, 100] over a rolling window for cross-asset comparison.

timeseries hmaMin = lowest(source=hma, period=normLen)
timeseries hmaMax = highest(source=hma, period=normLen)
timeseries hmaRange = hmaMax - hmaMin

// Normalized to [0, 100] — 50 = midpoint, >70 = overbought, <30 = oversold
var rawNorm = 50.0
if (hmaRange > 0) {
    rawNorm = ((hma - hmaMin) / hmaRange) * 100.0
} else {
    rawNorm = 50.0
}

// Clamp to [0, 100] to avoid outliers
timeseries normClamped = rawNorm
if (rawNorm > 100) {
    normClamped = 100.0
}
if (rawNorm < 0) {
    normClamped = 0.0
}

// Final smoothing
timeseries hmaNorm = smoothFinal ? ema(source=normClamped, period=smoothLen) : normClamped

// -----------------------------------------------------------------------------
// 5. SIGNAL LINE & MOMENTUM
// -----------------------------------------------------------------------------
// Signal SMA crossover provides cleaner entry/exit signals per Ponnusamy &
// Manual (2016). Histogram = oscillator − signal, analogous to MACD.

timeseries signal = sma(source=hmaNorm, period=signalLen)
timeseries hist = hmaNorm - signal

// -----------------------------------------------------------------------------
// 6. DYNAMIC THRESHOLDS
// -----------------------------------------------------------------------------
// Per Poterba & Summers (1988), mean-reversion intensity varies with volatility.
// We adjust OB/OS bands by rolling standard deviation of the normalized HMA.

timeseries normVol = stddev(source=hmaNorm, period=volLookback)
var dynOb = useDynamic ? math.min(95, obLevel + normVol * 1.5) : obLevel
var dynOs = useDynamic ? math.max(5, osLevel - normVol * 1.5) : osLevel

// Guard: ensure bands never cross
if (dynOb <= dynOs) {
    dynOb = 70
    dynOs = 30
}

// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification: Bullish (osc > signal AND osc > 50), Bearish
// (osc < signal AND osc < 50), Neutral (chop zone). Extreme regimes
// occur when oscillator exceeds ±3σ dynamic thresholds.

var regimeBull = hmaNorm > signal && hmaNorm > 50
var regimeBear = hmaNorm < signal && hmaNorm < 50
var regimeNeutral = !regimeBull && !regimeBear

var extremeBull = hmaNorm >= extremeOb
var extremeBear = hmaNorm <= extremeOs

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

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Track regime persistence, extreme-event counts, and signal-line crossovers
// for session-level diagnostics.

static lastRegime = 0    // 0 = neutral, 1 = bull, -1 = bear
static regimeChanges = 0
static extremeObCount = 0
static extremeOsCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    if (currentRegime != lastRegime) {
        lastRegime = currentRegime
        regimeChanges = regimeChanges + 1
    }

    if (extremeBull) {
        extremeObCount = extremeObCount + 1
    }
    if (extremeBear) {
        extremeOsCount = extremeOsCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of normalized HMA and signal line; OB/OS penetrations
// and exits; extreme-zone entries.

var crossUp = hmaNorm > signal && hmaNorm[1] <= signal[1]
var crossDown = hmaNorm < signal && hmaNorm[1] >= signal[1]

var obPenetrate = hmaNorm > dynOb && hmaNorm[1] <= dynOb[1]
var osPenetrate = hmaNorm < dynOs && hmaNorm[1] >= dynOs[1]
var obExit = hmaNorm < dynOb && hmaNorm[1] >= dynOb[1]
var osExit = hmaNorm > dynOs && hmaNorm[1] <= dynOs[1]

var extremeObEnter = hmaNorm >= extremeOb && hmaNorm[1] < extremeOb
var extremeOsEnter = hmaNorm <= extremeOs && hmaNorm[1] > extremeOs

// -----------------------------------------------------------------------------
// 10. PLOTTING — Zones & Midline
// -----------------------------------------------------------------------------

// Midline at 50
hline(value=50, color="#ffffff20", width=1)

// OB / OS zone lines
if (showZones) {
    hline(value=dynOb, color=transparency(bearColor, 60), width=1)
    hline(value=dynOs, color=transparency(bullColor, 60), width=1)
    hline(value=extremeOb, color=transparency(bearColor, 40), width=1)
    hline(value=extremeOs, color=transparency(bullColor, 40), width=1)
}

// -----------------------------------------------------------------------------
// 11. PLOTTING — Oscillator & Signal with Fill
// -----------------------------------------------------------------------------

// Oscillator line (regime-colored)
if (showOscillator) {
    plotLine(
        value=hmaNorm,
        width=2,
        colors=[regimeColor],
        label=["Norm HMA"],
        desc=["Normalized HMA oscillator (0-100, regime-colored)"]
    )
}

// Signal line
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal"],
        desc=["Signal SMA of normalized HMA (" + signalLen + ")"]
    )
}

// Fill between oscillator and signal
if (showFill && showOscillator && showSignal) {
    var fillBull = hmaNorm > signal
    plotLine(
        value=[hmaNorm, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Norm HMA", "Signal"],
        desc=["Fill between normalized HMA and signal line", ""]
    )
}

// -----------------------------------------------------------------------------
// 12. PLOTTING — Momentum Histogram
// -----------------------------------------------------------------------------
if (showHistogram) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["HMA Momentum"],
        desc=["Histogram of normalized HMA minus signal SMA"]
    )
}

// -----------------------------------------------------------------------------
// 13. PLOTTING — Signal Shapes
// -----------------------------------------------------------------------------
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Cross Up"],
            desc=["Normalized HMA crossed above signal — bullish momentum shift"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Cross Down"],
            desc=["Normalized HMA crossed below signal — bearish momentum shift"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=dynOb,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["OB Penetrate"],
            desc=["Oscillator entered overbought zone (>" + dynOb + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=dynOs,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["OS Penetrate"],
            desc=["Oscillator entered oversold zone (<" + dynOs + ")"]
        )
    }
    if (extremeObEnter) {
        plotShape(
            value=extremeOb,
            shape="diamond",
            colorIndex=bearColor,
            width=3,
            label=["Extreme OB"],
            desc=["Extreme overbought — potential exhaustion (>= " + extremeOb + ")"]
        )
    }
    if (extremeOsEnter) {
        plotShape(
            value=extremeOs,
            shape="diamond",
            colorIndex=bullColor,
            width=3,
            label=["Extreme OS"],
            desc=["Extreme oversold — potential exhaustion (<= " + extremeOs + ")"]
        )
    }
}

// -----------------------------------------------------------------------------
// 14. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeColor
    var obText = useDynamic ? "Dynamic OB: " + dynOb : "Static OB: " + obLevel
    var osText = useDynamic ? "Dynamic OS: " + dynOs : "Static OS: " + osLevel

    plotTable(
        data=[
            ["Normalized HMA", regimeText],
            ["Oscillator", hmaNorm[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            [obText, osText],
            ["Extreme OB Events", extremeObCount],
            ["Extreme OS Events", extremeOsCount],
            ["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
    )
}