MM Flow
FlowScripts

Perfected FlowScript

MACD

MACD — Perfected Edition is indexed as 270_macd.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

16.4 KB

Lines

553

Native Signal Candidates

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

10/10 guarded

Sig Cross Up

line 417:9

Trigger

(showShapes) && (sigCrossUp)

Value

sigLine

Deps

showShapes:input, sigCrossUp:var

Sig Cross Down

line 427:9

Trigger

(showShapes) && (sigCrossDown)

Value

sigLine

Deps

showShapes:input, sigCrossDown:var

Zero Cross Up

line 437:9

Trigger

(showShapes) && (zeroCrossUp)

Value

0

Deps

showShapes:input, zeroCrossUp:var

Zero Cross Down

line 447:9

Trigger

(showShapes) && (zeroCrossDown)

Value

0

Deps

showShapes:input, zeroCrossDown:var

Upper Penetrate

line 457:9

Trigger

(showShapes) && (upperPenetrate)

Value

dynUpper

Deps

showShapes:input, upperPenetrate:var

Lower Penetrate

line 467:9

Trigger

(showShapes) && (lowerPenetrate)

Value

dynLower

Deps

lowerPenetrate:var, showShapes:input

Bull Div

line 481:9

Trigger

(showDivShapes && enableDiv) && (bullDiv)

Value

macdLine

Deps

bullDiv:var, enableDiv:input, showDivShapes:input

Bear Div

line 491:9

Trigger

(showDivShapes && enableDiv) && (bearDiv)

Value

macdLine

Deps

bearDiv:var, enableDiv:input, showDivShapes:input

Hidden Bull

line 501:9

Trigger

(showDivShapes && enableDiv) && (showHidden && hiddenBullDiv)

Value

macdLine

Deps

enableDiv:input, hiddenBullDiv:var, showDivShapes:input, showHidden:input

Hidden Bear

line 511:9

Trigger

(showDivShapes && enableDiv) && (showHidden && hiddenBearDiv)

Value

macdLine

Deps

enableDiv:input, hiddenBearDiv:var, showDivShapes:input, showHidden:input

270_macd.flowscript

source path: kscripts/perfected/270_macd.flowscript · sha256:f90bb4e3c3a9b393e90e6434ac08558b58800a73fefda85c4f193dea8c322c80

hash verified
//@version=2
// ============================================================================
// MACD — Perfected Edition
// Author: T (@Tuto) | Enhanced by kScript_Perfection_Engineer
// Index: 270
// Tags: CORE, #macd, #divergence, #momentum, #trend, #regime
//
// Production-quality Gerald Appel MACD with full divergence detection,
// dynamic volatility-adjusted thresholds, histogram color coding by regime
// and momentum (growing/shrinking), fill visualization, shape markers for
// crossovers, and comprehensive academic grounding.
//
// Research papers underpinning this design:
//  1. Porselvi R. & Dr. Meenakshi A. (2024), "A Study On The Effectiveness Of
//     Moving Average Convergence And Divergence (MACD)". Direct academic study
//     comparing Centreline Crossover vs. Signal Line Crossover vs. Buy-and-Hold.
//     Found Centre Line Crossover was same or more profitable than Signal Line
//     Crossover. Key formula: MACD Line = EMA(12) − EMA(26); Signal = EMA(9);
//     Histogram = MACD − Signal.
//  2. Hutabarat, Sadalia & Irawati (2025), "Technical Analysis of MACD,
//     Stochastic Oscillator, RSI, and Money Flow Index". Multi-indicator accuracy
//     comparison on IDX30 Index found MACD at 89% accuracy, outperforming SO (81%),
//     RSI (79%), and MFI (63%). Statistical tests showed only MACD was effective.
//  3. Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability
//     in Technical Analysis". Experimental testing found no single indicator fully
//     reliable using standard rules alone; recommends multi-indicator confirmation.
//     Underpins the enhanced MACD with divergence and regime filters.
//  4. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns". Seminal 90-year DJIA study
//     validating MA crossover rules as significantly profitable; foundational
//     for MACD's EMA-crossover architecture.
//  5. Appel (2005), "Technical Analysis: Power Tools for Active Investors".
//     Original MACD proponent; divergence as leading reversal signal when price
//     and MACD disagree at extremes. Centreline and signal-line crossovers as
//     primary trading signals.
// ============================================================================

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

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

// --- MACD Settings ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=12,
    label="Fast EMA Length",
    constraints={min: 2, max: 50, step: 1},
    group="MACD Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=26,
    label="Slow EMA Length",
    constraints={min: 2, max: 100, step: 1},
    group="MACD Settings"
)
var sigLen = input(
    name="sigLen",
    type="number",
    defaultValue=9,
    label="Signal Length",
    constraints={min: 2, max: 50, step: 1},
    group="MACD Settings"
)
var src = input(
    name="src",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close", "open", "hlc3", "ohlc4"],
    group="MACD Settings"
)

// --- Divergence ---
var enableDiv = input(
    name="enableDiv",
    type="boolean",
    defaultValue=true,
    label="Enable Divergence Detection",
    group="Divergence"
)
var divLookback = input(
    name="divLookback",
    type="number",
    defaultValue=10,
    label="Divergence Lookback (pivot bars)",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)
var showHidden = input(
    name="showHidden",
    type="boolean",
    defaultValue=true,
    label="Show Hidden Divergence",
    group="Divergence"
)

// --- 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"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.5,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Fill MACD vs Signal",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    group="Display"
)
var showDivShapes = input(
    name="showDivShapes",
    type="boolean",
    defaultValue=true,
    label="Show Divergence Shapes",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Colors"
)
var macdColor = input(
    name="macdColor",
    type="color",
    defaultValue="#2196f3",
    label="MACD Line Color",
    group="Colors"
)
var sigColor = input(
    name="sigColor",
    type="color",
    defaultValue="#ff9800",
    label="Signal Line Color",
    group="Colors"
)
var divBullColor = input(
    name="divBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Divergence Color",
    group="Colors"
)
var divBearColor = input(
    name="divBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Divergence Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = bars.open
timeseries h = bars.high
timeseries l = bars.low
timeseries c = bars.close
timeseries hlc3 = (h + l + c) / 3.0
timeseries ohlc4 = (o + h + l + c) / 4.0

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

timeseries source = src == "close" ? c : (src == "open" ? o : (src == "hlc3" ? hlc3 : ohlc4))

// -----------------------------------------------------------------------------
// 3. CANONICAL MACD
// -----------------------------------------------------------------------------
// Per Appel (1970s): MACD = EMA(fast) − EMA(slow); Signal = EMA(MACD, sig)

timeseries macdLine = ema(source, fastLen) - ema(source, slowLen)
timeseries sigLine = ema(macdLine, sigLen)
timeseries hist = macdLine - sigLine

// Histogram regime: growing (bull) vs shrinking (bear)
var histGrowing = hist >= hist[1]
var histShrinking = hist < hist[1]

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// MACD > 0 = bullish momentum; MACD < 0 = bearish momentum
// MACD > Signal = accelerating; MACD < Signal = decelerating

var regimeBull = macdLine > 0 && macdLine > sigLine
var regimeBear = macdLine < 0 && macdLine < sigLine
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? upColor : (regimeBear ? dnColor : "#9e9e9e")

// -----------------------------------------------------------------------------
// 5. DYNAMIC THRESHOLDS
// -----------------------------------------------------------------------------
// Adjust MACD overbought/oversold bands by rolling standard deviation of
// the MACD line itself, per volatility-adaptive threshold design.

var macdVol = stddev(source=macdLine, period=volLookback)
var dynUpper = useDynamic ? macdVol * volMultiplier : 0
var dynLower = useDynamic ? -macdVol * volMultiplier : 0

// -----------------------------------------------------------------------------
// 6. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, MACD disagrees.
// Hidden divergence: price makes higher low / lower high, MACD disagrees.

static prevPxHigh = -1.0
static prevMacdHigh = -1.0
static prevPxLow = -1.0
static prevMacdLow = -1.0

var bearDiv = false
var bullDiv = false
var hiddenBearDiv = false
var hiddenBullDiv = false

// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
    prevPxHigh = h[0]
    prevMacdHigh = macdLine[0]
    prevPxLow = l[0]
    prevMacdLow = macdLine[0]
}

if (!isLiveUpdate && enableDiv) {
    // --- Regular Bearish Divergence ---
    // Price higher high; MACD lower high
    if (h[0] > prevPxHigh) {
        if (macdLine[0] < prevMacdHigh) {
            bearDiv = true
        }
        prevPxHigh = h[0]
        prevMacdHigh = macdLine[0]
    }

    // --- Regular Bullish Divergence ---
    // Price lower low; MACD higher low
    if (l[0] < prevPxLow) {
        if (macdLine[0] > prevMacdLow) {
            bullDiv = true
        }
        prevPxLow = l[0]
        prevMacdLow = macdLine[0]
    }

    // --- Hidden Divergence ---
    if (showHidden) {
        // Hidden bullish: price higher low, MACD lower low
        if (l[0] > prevPxLow && h[0] < prevPxHigh) {
            if (macdLine[0] < prevMacdLow) {
                hiddenBullDiv = true
            }
        }
        // Hidden bearish: price lower high, MACD higher high
        if (h[0] < prevPxHigh && l[0] > prevPxLow) {
            if (macdLine[0] > prevMacdHigh) {
                hiddenBearDiv = true
            }
        }
    }
}

// -----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING — Consecutive bars in regime
// -----------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static neutralBars = 0

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
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Signal crossovers
var sigCrossUp = macdLine > sigLine && macdLine[1] <= sigLine[1]
var sigCrossDown = macdLine < sigLine && macdLine[1] >= sigLine[1]

// Zero-line crossovers
var zeroCrossUp = macdLine > 0 && macdLine[1] <= 0
var zeroCrossDown = macdLine < 0 && macdLine[1] >= 0

// Dynamic threshold penetrations (only when enabled)
var upperPenetrate = useDynamic && macdLine > dynUpper && macdLine[1] <= dynUpper
var lowerPenetrate = useDynamic && macdLine < dynLower && macdLine[1] >= dynLower

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line ---
hline(value=0, color="#ffffff30", width=1)

// --- Dynamic threshold hlines (if enabled) ---
if (useDynamic) {
    hline(value=dynUpper, color=transparency(dnColor, 70), width=1)
    hline(value=dynLower, color=transparency(upColor, 70), width=1)
}

// --- Histogram with color coding: green=growing, red=shrinking ---
if (showHist) {
    var histColor = hist >= 0
        ? (histGrowing ? transparency(upColor, 40) : transparency(upColor, 70))
        : (histShrinking ? transparency(dnColor, 40) : transparency(dnColor, 70))
    plotBar(
        value=hist,
        colors=[histColor],
        width=2,
        label=["Histogram"],
        desc=["MACD − Signal; lighter = growing momentum, darker = shrinking"]
    )
}

// --- MACD line (regime-colored) ---
plotLine(
    value=macdLine,
    width=2,
    colors=[regimeColor],
    label=["MACD"],
    desc=["EMA(" + fastLen + ") − EMA(" + slowLen + "); regime-colored"]
)

// --- Signal line ---
plotLine(
    value=sigLine,
    width=2,
    colors=[sigColor],
    label=["Signal"],
    desc=["EMA of MACD line (" + sigLen + ")"]
)

// --- Fill between MACD and Signal ---
if (showFill) {
    var fillBull = macdLine > sigLine
    plotLine(
        value=[macdLine, sigLine],
        width=1,
        colors=[transparency(upColor, 20), transparency(dnColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["MACD", "Signal"],
        desc=["Fill between MACD line and signal line"]
    )
}

// --- Crossover shapes (signal + zero-line) ---
if (showShapes) {
    if (sigCrossUp) {
        plotShape(
            value=sigLine,
            shape="triangleup",
            colorIndex=upColor,
            width=2,
            label=["Sig Cross Up"],
            desc=["MACD crossed above signal line"]
        )
    }
    if (sigCrossDown) {
        plotShape(
            value=sigLine,
            shape="triangledown",
            colorIndex=dnColor,
            width=2,
            label=["Sig Cross Down"],
            desc=["MACD crossed below signal line"]
        )
    }
    if (zeroCrossUp) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=upColor,
            width=2,
            label=["Zero Cross Up"],
            desc=["MACD crossed above zero line"]
        )
    }
    if (zeroCrossDown) {
        plotShape(
            value=0,
            shape="circle",
            colorIndex=dnColor,
            width=2,
            label=["Zero Cross Down"],
            desc=["MACD crossed below zero line"]
        )
    }
    if (upperPenetrate) {
        plotShape(
            value=dynUpper,
            shape="xcross",
            colorIndex=dnColor,
            width=2,
            label=["Upper Penetrate"],
            desc=["MACD penetrated dynamic upper threshold"]
        )
    }
    if (lowerPenetrate) {
        plotShape(
            value=dynLower,
            shape="xcross",
            colorIndex=upColor,
            width=2,
            label=["Lower Penetrate"],
            desc=["MACD penetrated dynamic lower threshold"]
        )
    }
}

// --- Divergence shapes ---
if (showDivShapes && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=macdLine,
            shape="triangleup",
            colorIndex=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, MACD higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=macdLine,
            shape="triangledown",
            colorIndex=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, MACD lower high"]
        )
    }
    if (showHidden && hiddenBullDiv) {
        plotShape(
            value=macdLine,
            shape="arrowup",
            colorIndex=divBullColor,
            width=1,
            label=["Hidden Bull"],
            desc=["Hidden bullish divergence: price higher low, MACD lower low"]
        )
    }
    if (showHidden && hiddenBearDiv) {
        plotShape(
            value=macdLine,
            shape="arrowdown",
            colorIndex=divBearColor,
            width=1,
            label=["Hidden Bear"],
            desc=["Hidden bearish divergence: price lower high, MACD higher high"]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? upColor : (regimeBear ? dnColor : "#9e9e9e")

    plotTable(
        data=[
            ["MACD — Perfected", regimeText],
            ["MACD", macdLine[0]],
            ["Signal", sigLine[0]],
            ["Histogram", hist[0]],
            ["Source", src],
            ["Fast EMA", fastLen],
            ["Slow EMA", slowLen],
            ["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
    )
}