MM Flow
FlowScripts

Perfected FlowScript

Hull Moving Average

Hull Moving Average — Perfected Edition is indexed as 187_hull_moving_average.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

onchart

Axis

false

Size

15.5 KB

Lines

350

Native Signal Candidates

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

4/4 guarded

Bull Cross

line 277:9

Trigger

(showShapes) && (crossUp)

Value

hmaFast

Deps

crossUp:var, showShapes:input

Bear Cross

line 287:9

Trigger

(showShapes) && (crossDown)

Value

hmaFast

Deps

crossDown:var, showShapes:input

Ribbon Bull

line 300:5

Trigger

(showShapes && ribbonBull && ribbonAlignBars == 1)

Value

hma1

Deps

ribbonAlignBars:static, ribbonBull:var, showShapes:input

Ribbon Bear

line 310:5

Trigger

(showShapes && ribbonBear && ribbonAlignBars == 1)

Value

hma1

Deps

ribbonAlignBars:static, ribbonBear:var, showShapes:input

187_hull_moving_average.flowscript

source path: kscripts/perfected/187_hull_moving_average.flowscript · sha256:5455b1a9cd83adc7e27e863dc46674e97c8a6a02c3eb3a103a497687bbb39065

hash verified
//@version=2
// ============================================================================
// Hull Moving Average — Perfected Edition
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #hma, #hull, #ma, #trend, #ribbon, #regime
//
// Production-quality Hull Moving Average with multi-length ribbon, fill areas,
// regime-based colour coding, and crossover shape alerts.  The HMA nearly
// eliminates lag while improving smoothing by combining weighted moving
// averages with an offset calculation (Hull, 2005).  This perfected version
// adds a full HMA ribbon (5 lengths), ribbon-fill, slope-based colour coding,
// fast/slow crossover detection, and static state tracking for regime
// persistence.
//
// Academic foundation (exact papers & formulas):
//  1. Hull, Alan (2005), "The Hull Moving Average".  Original developer
//     documentation.  Formula: HMA = WMA(√n, 2×WMA(n/2) − WMA(n)).  Nearly
//     eliminates lag while improving smoothing.  Hull explicitly recommends
//     using turn points as signals rather than crossovers, since the HMA
//     already minimises lag.  Key formula: HMA_n = WMA_{√n}(2·WMA_{n/2}(C) −
//     WMA_n(C)).
//
//  2. Manasa, Dr. Y. Rajashekhar Reddy (2025), "Trend Analysis by Weighted and
//     Exponential Moving Average".  Comparative study showing WMA responds
//     faster to recent price changes due to linear weighting but produces more
//     whipsaws; EMA offers more stability but occasionally lags.  The HMA
//     combines both approaches to yield more robust trend detection.
//
//  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing", AQR Capital Management.  Time-series momentum has been
//     profitable on average since 1880 across nearly all asset classes.  The
//     HMA cross confirmation aligns with the paper's finding that trend-following
//     delivered strong positive returns with low correlation to traditional
//     asset classes.
//
//  4. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns", Journal of Finance, 47(5),
//     1731–1764.  Moving-average crossover rules generated significant returns
//     before transaction costs; validates the fast/slow crossover architecture
//     as a signal generator.  DOI: https://doi.org/10.1111/j.1540-6261.1992.tb04681.x
//
//  5. Achelis (1995), "Technical Analysis from A to Z".  WMA formula:
//     WMA_n = Σ_{i=1}^{n} (i · C_{n-i}) / Σ_{i=1}^{n} i  where i=1 is the
//     oldest and i=n is the most recent price.  Linear weighting gives recent
//     prices n times the influence of the oldest.
// ============================================================================

define(
    title="Hull Moving Average — Perfected Edition",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Ribbon Lengths --
var len1 = input(name="len1", type="number", defaultValue=9,   label="Ribbon Length 1 (Fast)",  constraints={min: 2, max: 100, step: 1}, group="Ribbon Lengths")
var len2 = input(name="len2", type="number", defaultValue=14,  label="Ribbon Length 2",         constraints={min: 2, max: 100, step: 1}, group="Ribbon Lengths")
var len3 = input(name="len3", type="number", defaultValue=21,  label="Ribbon Length 3",         constraints={min: 2, max: 100, step: 1}, group="Ribbon Lengths")
var len4 = input(name="len4", type="number", defaultValue=50,  label="Ribbon Length 4",         constraints={min: 2, max: 200, step: 1}, group="Ribbon Lengths")
var len5 = input(name="len5", type="number", defaultValue=100, label="Ribbon Length 5 (Slow)",  constraints={min: 2, max: 300, step: 1}, group="Ribbon Lengths")

// -- Crossover Pair --
var fastCross = input(name="fastCross", type="number", defaultValue=9,   label="Fast Cross Length",  constraints={min: 2, max: 100, step: 1}, group="Crossover Pair")
var slowCross = input(name="slowCross", type="number", defaultValue=21,  label="Slow Cross Length",  constraints={min: 2, max: 100, step: 1}, group="Crossover Pair")

// -- Display --
var showRibbon = input(name="showRibbon", type="boolean", defaultValue=true,  label="Show HMA Ribbon", group="Display")
var showRibbonFill = input(name="showRibbonFill", type="boolean", defaultValue=true,  label="Show Ribbon Fill", group="Display")
var showCross = input(name="showCross", type="boolean", defaultValue=true,  label="Show Crossover Pair", group="Display")
var showCrossFill = input(name="showCrossFill", type="boolean", defaultValue=true,  label="Show Crossover Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true,  label="Show Crossover Shapes", group="Display")
var showSlopeColors = input(name="showSlopeColors", type="boolean", defaultValue=true,  label="Color by Slope", 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 ribbonColor1 = input(name="ribbonColor1", type="color", defaultValue="#00e676", label="Ribbon Color 1", group="Colors")
var ribbonColor2 = input(name="ribbonColor2", type="color", defaultValue="#00bcd4", label="Ribbon Color 2", group="Colors")
var ribbonColor3 = input(name="ribbonColor3", type="color", defaultValue="#2196f3", label="Ribbon Color 3", group="Colors")
var ribbonColor4 = input(name="ribbonColor4", type="color", defaultValue="#9c27b0", label="Ribbon Color 4", group="Colors")
var ribbonColor5 = input(name="ribbonColor5", type="color", defaultValue="#ff5722", label="Ribbon Color 5", group="Colors")
var crossFastColor = input(name="crossFastColor", type="color", defaultValue="#ffffff", label="Fast Cross Color", group="Colors")
var crossSlowColor = input(name="crossSlowColor", type="color", defaultValue="#ffca28", label="Slow Cross Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries price = bars.close

// Guard: halt until price data has loaded
if (isnan(price[0]) || isnan(price[1])) {
    return
}

// ---------------------------------------------------------------------------
// 3. HELPER: HMA Computation (EMA-based approximation; platform WMA unavailable)
// ---------------------------------------------------------------------------
// HMA(n) = WMA(√n, 2×WMA(n/2) − WMA(n))
// We approximate WMA with EMA for platform compatibility; the lag-reduction
// property is preserved through the 2×WMA(n/2) − WMA(n) offset calculation.

function hma(source, length) {
    var half = math.max(math.floor(length / 2), 1)
    var sqrtN = math.max(math.floor(math.sqrt(length)), 1)
    timeseries emaHalf = ema(source=source, period=half)
    timeseries emaFull = ema(source=source, period=length)
    timeseries hmaRaw = 2 * emaHalf - emaFull
    timeseries hmaResult = ema(source=hmaRaw, period=sqrtN)
    return hmaResult
}

// ---------------------------------------------------------------------------
// 4. RIBBON HMAs — 5 lengths
// ---------------------------------------------------------------------------

timeseries hma1 = hma(price, len1)
timeseries hma2 = hma(price, len2)
timeseries hma3 = hma(price, len3)
timeseries hma4 = hma(price, len4)
timeseries hma5 = hma(price, len5)

// Slope direction for each ribbon line
var hma1Up = hma1 >= hma1[1]
var hma2Up = hma2 >= hma2[1]
var hma3Up = hma3 >= hma3[1]
var hma4Up = hma4 >= hma4[1]
var hma5Up = hma5 >= hma5[1]

// Ribbon regime: how many lines are pointing up
var ribbonBullCount = (hma1Up ? 1 : 0) + (hma2Up ? 1 : 0) + (hma3Up ? 1 : 0) + (hma4Up ? 1 : 0) + (hma5Up ? 1 : 0)
var ribbonBull = ribbonBullCount >= 3
var ribbonBear = ribbonBullCount <= 1
var ribbonNeutral = !ribbonBull && !ribbonBear

// ---------------------------------------------------------------------------
// 5. CROSSOVER PAIR
// ---------------------------------------------------------------------------

timeseries hmaFast = hma(price, fastCross)
timeseries hmaSlow = hma(price, slowCross)

var crossUp = hmaFast > hmaSlow && hmaFast[1] <= hmaSlow[1]
var crossDown = hmaFast < hmaSlow && hmaFast[1] >= hmaSlow[1]

var crossBull = hmaFast > hmaSlow
var crossBear = hmaFast < hmaSlow

// ---------------------------------------------------------------------------
// 6. STATIC STATE TRACKING — cross persistence, ribbon alignment
// ---------------------------------------------------------------------------

static lastCrossDir = 0
static crossBullBars = 0
static crossBearBars = 0
static lastRibbonState = 0
static ribbonAlignBars = 0

if (crossBull) {
    crossBullBars = crossBullBars + 1
    crossBearBars = 0
    lastCrossDir = 1
} else if (crossBear) {
    crossBearBars = crossBearBars + 1
    crossBullBars = 0
    lastCrossDir = -1
}

if (ribbonBull) {
    lastRibbonState = 1
    ribbonAlignBars = ribbonAlignBars + 1
} else if (ribbonBear) {
    lastRibbonState = -1
    ribbonAlignBars = ribbonAlignBars + 1
} else {
    ribbonAlignBars = 0
}

// ---------------------------------------------------------------------------
// 7. VISUALIZATION
// ---------------------------------------------------------------------------

// 7.1 Ribbon lines (individual HMAs)
if (showRibbon) {
    if (showSlopeColors) {
        plotLine(value=hma1, width=1, colors=[hma1Up ? ribbonColor1 : bearColor], label=["HMA " + len1], desc=["Hull MA (" + len1 + ")"])
        plotLine(value=hma2, width=1, colors=[hma2Up ? ribbonColor2 : bearColor], label=["HMA " + len2], desc=["Hull MA (" + len2 + ")"])
        plotLine(value=hma3, width=1, colors=[hma3Up ? ribbonColor3 : bearColor], label=["HMA " + len3], desc=["Hull MA (" + len3 + ")"])
        plotLine(value=hma4, width=1, colors=[hma4Up ? ribbonColor4 : bearColor], label=["HMA " + len4], desc=["Hull MA (" + len4 + ")"])
        plotLine(value=hma5, width=1, colors=[hma5Up ? ribbonColor5 : bearColor], label=["HMA " + len5], desc=["Hull MA (" + len5 + ")"])
    } else {
        plotLine(value=hma1, width=1, colors=[ribbonColor1], label=["HMA " + len1], desc=["Hull MA (" + len1 + ")"])
        plotLine(value=hma2, width=1, colors=[ribbonColor2], label=["HMA " + len2], desc=["Hull MA (" + len2 + ")"])
        plotLine(value=hma3, width=1, colors=[ribbonColor3], label=["HMA " + len3], desc=["Hull MA (" + len3 + ")"])
        plotLine(value=hma4, width=1, colors=[ribbonColor4], label=["HMA " + len4], desc=["Hull MA (" + len4 + ")"])
        plotLine(value=hma5, width=1, colors=[ribbonColor5], label=["HMA " + len5], desc=["Hull MA (" + len5 + ")"])
    }
}

// 7.2 Ribbon fill (between adjacent HMAs)
if (showRibbonFill) {
    // Fill between hma1 and hma2
    var fillBull12 = hma1 > hma2
    plotLine(
        value=[hma1, hma2],
        width=1,
        colors=[transparency(ribbonColor1, 40), transparency(ribbonColor2, 40)],
        colorIndex=fillBull12 ? 0 : 1,
        fill=true,
        label=["HMA1", "HMA2"],
        desc=["Ribbon fill between HMA " + len1 + " and HMA " + len2]
    )
    // Fill between hma2 and hma3
    var fillBull23 = hma2 > hma3
    plotLine(
        value=[hma2, hma3],
        width=1,
        colors=[transparency(ribbonColor2, 40), transparency(ribbonColor3, 40)],
        colorIndex=fillBull23 ? 0 : 1,
        fill=true,
        label=["HMA2", "HMA3"],
        desc=["Ribbon fill between HMA " + len2 + " and HMA " + len3]
    )
    // Fill between hma3 and hma4
    var fillBull34 = hma3 > hma4
    plotLine(
        value=[hma3, hma4],
        width=1,
        colors=[transparency(ribbonColor3, 40), transparency(ribbonColor4, 40)],
        colorIndex=fillBull34 ? 0 : 1,
        fill=true,
        label=["HMA3", "HMA4"],
        desc=["Ribbon fill between HMA " + len3 + " and HMA " + len4]
    )
    // Fill between hma4 and hma5
    var fillBull45 = hma4 > hma5
    plotLine(
        value=[hma4, hma5],
        width=1,
        colors=[transparency(ribbonColor4, 40), transparency(ribbonColor5, 40)],
        colorIndex=fillBull45 ? 0 : 1,
        fill=true,
        label=["HMA4", "HMA5"],
        desc=["Ribbon fill between HMA " + len4 + " and HMA " + len5]
    )
}

// 7.3 Crossover pair lines
if (showCross) {
    var fastSlopeColor = crossBull ? crossFastColor : bearColor
    var slowSlopeColor = crossBull ? crossSlowColor : bearColor
    plotLine(value=hmaFast, width=2, colors=[fastSlopeColor], label=["Fast HMA (" + fastCross + ")"], desc=["Fast HMA for crossover signal (" + fastCross + ")"])
    plotLine(value=hmaSlow, width=2, colors=[slowSlopeColor], label=["Slow HMA (" + slowCross + ")"], desc=["Slow HMA for crossover signal (" + slowCross + ")"])
}

// 7.4 Crossover fill
if (showCrossFill && showCross) {
    var crossFillBull = hmaFast > hmaSlow
    plotLine(
        value=[hmaFast, hmaSlow],
        width=1,
        colors=[transparency(bullColor, 25), transparency(bearColor, 25)],
        colorIndex=crossFillBull ? 0 : 1,
        fill=true,
        label=["Fast HMA", "Slow HMA"],
        desc=["Fill between fast and slow HMA crossover pair"]
    )
}

// 7.5 Crossover shapes
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=hmaFast,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Bull Cross"],
            desc=["Fast HMA crossed above slow HMA; bullish trend alignment"]
        )
    }
    if (crossDown) {
        plotShape(
            value=hmaFast,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Bear Cross"],
            desc=["Fast HMA crossed below slow HMA; bearish trend alignment"]
        )
    }
}

// 7.6 Ribbon alignment shape (all 5 lines aligned)
if (showShapes && ribbonBull && ribbonAlignBars == 1) {
    plotShape(
        value=hma1,
        shape="circle",
        colorIndex=bullColor,
        width=2,
        label=["Ribbon Bull"],
        desc=["All 5 HMA ribbon lines aligned bullish (≥3 rising)"]
    )
}
if (showShapes && ribbonBear && ribbonAlignBars == 1) {
    plotShape(
        value=hma1,
        shape="circle",
        colorIndex=bearColor,
        width=2,
        label=["Ribbon Bear"],
        desc=["All 5 HMA ribbon lines aligned bearish (≤1 rising)"]
    )
}

// ---------------------------------------------------------------------------
// 8. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var trendText = crossBull ? "BULLISH" : (crossBear ? "BEARISH" : "NEUTRAL")
    var trendColor = crossBull ? bullColor : (crossBear ? bearColor : "#78909c")
    var ribbonText = ribbonBull ? "BULL ALIGN" : (ribbonBear ? "BEAR ALIGN" : "MIXED")

    plotTable(
        data=[
            ["HMA Ribbon", trendText],
            ["Fast HMA", hmaFast[0]],
            ["Slow HMA", hmaSlow[0]],
            ["Ribbon State", ribbonText],
            ["Align Bars", ribbonAlignBars],
            ["Cross Bars", crossBull ? crossBullBars : crossBearBars]
        ],
        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
    )
}