MM Flow
FlowScripts

Perfected FlowScript

Exponential Hull Moving Average

Exponential Hull Moving Average V2 is indexed as 106_exponential_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

12.0 KB

Lines

372

Native Signal Candidates

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

6/6 guarded

Price Cross Up

line 312:9

Trigger

(showShapes) && (crossUp)

Value

low

Deps

crossUp:var, showShapes:input

Price Cross Down

line 322:9

Trigger

(showShapes) && (crossDown)

Value

high

Deps

crossDown:var, showShapes:input

Signal Cross Up

line 332:9

Trigger

(showShapes) && (sigCrossUp)

Value

low

Deps

showShapes:input, sigCrossUp:var

Signal Cross Down

line 342:9

Trigger

(showShapes) && (sigCrossDown)

Value

high

Deps

showShapes:input, sigCrossDown:var

Slope Turn Up

line 352:9

Trigger

(showShapes) && (slopeTurnUp)

Value

ehma

Deps

showShapes:input, slopeTurnUp:var

Slope Turn Down

line 362:9

Trigger

(showShapes) && (slopeTurnDown)

Value

ehma

Deps

showShapes:input, slopeTurnDown:var

106_exponential_hull_moving_average.flowscript

source path: kscripts/perfected/106_exponential_hull_moving_average.flowscript · sha256:d51422a5b6e07860a79bb93f1ca39c5873e4a11e10072a982bb11ece78cf0c18

hash verified
//@version=2

// ============================================================================
// Exponential Hull Moving Average V2 — EHMA with Trend-State Visualisation
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #hull, #ema, #movingaverage, #trend, #regime
//
// A fast, smooth trend line based on Hull logic but built with EMAs.
// Takes 2 × EMA(price, len/2) − EMA(price, len) to emphasise recent moves,
// then smooths that with EMA over sqrt(len). Less lag than a standard EMA
// of the same length while maintaining superior smoothness. This perfected
// edition adds directional colour coding, fill areas, slope histogram, and
// shape markers for trend-change detection.
//
// Academic foundation (exact papers & formulas):
//  1. Hull (2005), "The Hull Moving Average".
//     [Formula] HMA = WMA(√n) of [2 × WMA(n/2) − WMA(n)].
//     Nearly eliminates lag while improving smoothing. The script adapts
//     Hull's core logic to EMAs for faster responsiveness in crypto markets.
//
//  2. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
//     Moving Average". Comparative study showing EMA responds faster to
//     recent price changes than WMA but produces more whipsaws. The EHMA
//     attempts to get the best of both: EMA responsiveness with Hull's lag
//     reduction. DOI: forthcoming
//
//  3. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs",
//     Journal of Portfolio Management, 49(5), 108–124.
//     Mathematical justification for MA-based trend-following rules;
//     shorter-lag MAs improve signal timing at the cost of modestly
//     higher whipsaw frequency. DOI: 10.3905/jpm.2023.1.502
//
//  4. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
//     and the Stochastic Properties of Stock Returns", Journal of Finance,
//     47(5), 1731–1764. Foundational evidence that MA crossover strategies
//     generate significant returns; validates trend-following MA logic.
//     DOI: https://doi.org/10.1111/j.1540-6261.1992.tb04681.x
//
//  5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing", Journal of Portfolio Management, 40(5), 103–120.
//     Time-series momentum profitable on average since 1880 across global
//     markets; supports MA-based bias lines as trend-following tools.
//     DOI: 10.3905/jpm.2014.40.5.103
//
//  6. Zakamulin (2015), "Market Timing with Moving Averages", SSRN 2585050.
//     Comprehensive survey: EMA outperforms SMA in trend detection speed;
//     Hull-type offset further reduces lag without excessive noise increase.
// ============================================================================

define(
    title="Exponential Hull Moving Average V2",
    position="onchart",
    axis=false
)

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

// --- Computation ---
var length = input(
    name="length",
    type="number",
    defaultValue=20,
    label="Base Length",
    constraints={min: 5, max: 200, step: 5},
    group="Computation"
)
var srcChoice = input(
    name="srcChoice",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close", "hl2", "hlc3", "ohlc4"],
    group="Computation"
)
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal EMA",
    group="Computation"
)
var sigLen = input(
    name="sigLen",
    type="number",
    defaultValue=9,
    label="Signal EMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="Computation"
)

// --- Display ---
var showEHMA = input(
    name="showEHMA",
    type="boolean",
    defaultValue=true,
    label="Show EHMA Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show EHMA/Price Fill",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill",
    group="Display"
)
var showSlopeHist = input(
    name="showSlopeHist",
    type="boolean",
    defaultValue=true,
    label="Show Slope Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Trend-Change Shapes",
    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 signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#2962ff",
    label="Signal Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = pxTS.close
timeseries high = pxTS.high
timeseries low = pxTS.low
timeseries open = pxTS.open

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

// -----------------------------------------------------------------------------
// 3. SOURCE SELECTION
// -----------------------------------------------------------------------------
timeseries src = srcChoice == "close" ? close : (srcChoice == "hl2" ? (high + low) / 2 : (srcChoice == "hlc3" ? (high + low + close) / 3 : (high + low + close + open) / 4))

// -----------------------------------------------------------------------------
// 4. HULL LOGIC WITH EMAs
// -----------------------------------------------------------------------------
// EHMA = EMA(√n) of [2 × EMA(n/2) − EMA(n)]
// Hull's original uses WMA; we substitute EMA for faster responsiveness.

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

// Guard: minimum period of 1 for EMA
timeseries emaFast = ema(source=src, period=math.max(halfLen, 1))
timeseries emaSlow = ema(source=src, period=math.max(length, 1))
timeseries hullDiff = 2 * emaFast - emaSlow
timeseries ehma = ema(source=hullDiff, period=math.max(sqrtLen, 1))

// -----------------------------------------------------------------------------
// 5. SIGNAL EMA & SLOPE
// -----------------------------------------------------------------------------
timeseries sigEMA = ema(source=ehma, period=math.max(sigLen, 1))

// Slope of EHMA (rate of change per bar)
timeseries ehmaSlope = ehma - ehma[1]
timeseries sigSlope = sigEMA - sigEMA[1]

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION
// -----------------------------------------------------------------------------
// Trend classification:
//   Bullish: price > EHMA AND EHMA > signal AND EHMA slope > 0
//   Bearish: price < EHMA AND EHMA < signal AND EHMA slope < 0
//   Neutral: everything else (chop / transition zone)

var regimeBull = close > ehma && ehma > sigEMA && ehmaSlope > 0
var regimeBear = close < ehma && ehma < sigEMA && ehmaSlope < 0
var regimeNeutral = !regimeBull && !regimeBear

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

// Direction: rising EHMA vs falling EHMA (for colour coding)
var ehmaRising = ehmaSlope > 0
var ehmaFalling = ehmaSlope < 0

// -----------------------------------------------------------------------------
// 7. TREND-CHANGE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Tracks crossovers and slope changes for shape markers.

static prevRegime = 0
static prevEhmaSlope = 0.0

var crossUp = close > ehma && close[1] <= ehma[1]
var crossDown = close < ehma && close[1] >= ehma[1]
var sigCrossUp = ehma > sigEMA && ehma[1] <= sigEMA[1]
var sigCrossDown = ehma < sigEMA && ehma[1] >= sigEMA[1]
var slopeTurnUp = ehmaSlope > 0 && prevEhmaSlope <= 0
var slopeTurnDown = ehmaSlope < 0 && prevEhmaSlope >= 0

if (!isnan(bar_index[0])) {
    prevRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    prevEhmaSlope = ehmaSlope
}

// -----------------------------------------------------------------------------
// 8. VISUALIZATION
// -----------------------------------------------------------------------------

// --- EHMA line with directional colour coding ---
if (showEHMA) {
    plotLine(
        value=ehma,
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=ehmaRising ? 0 : (ehmaFalling ? 1 : 2),
        label=["EHMA"],
        desc=["Exponential Hull MA (len=" + length + "); green = rising, red = falling"]
    )
}

// --- EHMA / Price fill area ---
if (showFill) {
    var priceAbove = close > ehma
    plotLine(
        value=[close, ehma],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=priceAbove ? 0 : 1,
        fill=true,
        label=["Price", "EHMA"],
        desc=["Fill between price and EHMA; colour indicates bullish/bearish bias"]
    )
}

// --- Signal EMA ---
if (showSignal) {
    plotLine(
        value=sigEMA,
        width=1,
        colors=[signalColor],
        label=["Signal EMA"],
        desc=["EMA of EHMA (len=" + sigLen + "); faster cross reference"]
    )
}

// --- Signal fill (EHMA vs signal) ---
if (showSignalFill && showSignal) {
    var ehmaAboveSig = ehma > sigEMA
    plotLine(
        value=[ehma, sigEMA],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=ehmaAboveSig ? 0 : 1,
        fill=true,
        label=["EHMA", "Signal"],
        desc=["Fill between EHMA and signal EMA"]
    )
}

// --- Slope histogram (EHMA rate of change) ---
if (showSlopeHist) {
    var slopeBull = ehmaSlope >= 0
    plotBar(
        value=ehmaSlope,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=slopeBull ? 0 : 1,
        width=1,
        label=["EHMA Slope"],
        desc=["Rate of change of EHMA; positive = accelerating up, negative = accelerating down"]
    )
}

// --- Trend-change shapes (plotShape) ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            color=bullColor,
            width=3,
            label=["Price Cross Up"],
            desc=["Price crossed above EHMA; potential bullish momentum shift"]
        )
    }
    if (crossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            color=bearColor,
            width=3,
            label=["Price Cross Down"],
            desc=["Price crossed below EHMA; potential bearish momentum shift"]
        )
    }
    if (sigCrossUp) {
        plotShape(
            value=low,
            shape="arrowup",
            color=signalColor,
            width=2,
            label=["Signal Cross Up"],
            desc=["EHMA crossed above signal EMA; bullish trend confirmation"]
        )
    }
    if (sigCrossDown) {
        plotShape(
            value=high,
            shape="arrowdown",
            color=signalColor,
            width=2,
            label=["Signal Cross Down"],
            desc=["EHMA crossed below signal EMA; bearish trend confirmation"]
        )
    }
    if (slopeTurnUp) {
        plotShape(
            value=ehma,
            shape="circle",
            color=bullColor,
            width=2,
            label=["Slope Turn Up"],
            desc=["EHMA slope turned positive; deceleration of downtrend or acceleration of uptrend"]
        )
    }
    if (slopeTurnDown) {
        plotShape(
            value=ehma,
            shape="circle",
            color=bearColor,
            width=2,
            label=["Slope Turn Down"],
            desc=["EHMA slope turned negative; deceleration of uptrend or acceleration of downtrend"]
        )
    }
}