MM Flow
FlowScripts

Perfected FlowScript

Enhanced MFI

Enhanced MFI — Perfected Edition is indexed as 108_enhanced_mfi.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.5 KB

Lines

617

Native Signal Candidates

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

8/8 guarded

Bull Div

line 500:9

Trigger

(showAlerts && enableDiv) && (bullDiv)

Value

fastMfi

Deps

bullDiv:var, enableDiv:input, showAlerts:input

Bear Div

line 510:9

Trigger

(showAlerts && enableDiv) && (bearDiv)

Value

fastMfi

Deps

bearDiv:var, enableDiv:input, showAlerts:input

Hidden Bull

line 520:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBullDiv)

Value

fastMfi

Deps

enableDiv:input, hiddenBullDiv:var, showAlerts:input, showHidden:input

Hidden Bear

line 530:9

Trigger

(showAlerts && enableDiv) && (showHidden && hiddenBearDiv)

Value

fastMfi

Deps

enableDiv:input, hiddenBearDiv:var, showAlerts:input, showHidden:input

Cross Up

line 544:9

Trigger

(showAlerts) && (crossUp)

Value

signal

Deps

crossUp:var, showAlerts:input

Cross Down

line 554:9

Trigger

(showAlerts) && (crossDown)

Value

signal

Deps

crossDown:var, showAlerts:input

OB Penetrate

line 564:9

Trigger

(showAlerts) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showAlerts:input

OS Penetrate

line 574:9

Trigger

(showAlerts) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showAlerts:input

108_enhanced_mfi.flowscript

source path: kscripts/perfected/108_enhanced_mfi.flowscript · sha256:08688b5f012f1349ae62a9247769d57b561649658fa9434e15d286687c9eb903

hash verified
//@version=2
// ============================================================================
// Enhanced MFI — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #mfi, #oscillator, #divergence, #volume, #regime
//
// Production-quality academically-grounded dual-period Money Flow Index
// oscillator. Implements Quong & Soudack's canonical MFI formula with full
// stateful divergence detection, dynamic volatility-adjusted thresholds,
// multi-regime color coding, and comprehensive fill / shape / histogram
// visualization.
//
// Research papers underpinning this design:
//  1. Quong & Soudack (1989), "Money Flow Index" — Technical Analysis of
//     Stocks & Commodities, March 1989: canonical MFI publication.
//     MFI = 100 − [100 / (1 + MFR)] where MFR = Σ(positive MF) / Σ(negative MF)
//     over N periods. Typical Price = (H + L + C) / 3. Recommended 90/10
//     overbought/oversold (stricter than RSI's 70/30).
//  2. Hutabarat, Sadalia & Irawati (2025), "Technical Analysis of MACD, SO,
//     RSI, and MFI": multi-indicator accuracy comparison. MFI adds volume
//     weighting to RSI's momentum measurement; noise reduction via MA
//     crossover enhances signal reliability.
//  3. Wilder (1978), "New Concepts in Technical Trading Systems": RSI
//     framework (0-100 range, divergence detection) is the direct ancestor
//     of MFI. Overbought/oversold and divergence conventions follow Wilder.
//  4. StockCharts.com, "Percent B Money Flow Strategy": %B at 0.80+ with
//     high MFI indicates strong buying volume; plunge with low MFI indicates
//     selling volume. Underpins volume-confirmation approach with MFI+MA.
//  5. Murphy (1999), "Technical Analysis of the Financial Markets": divergence
//     as a leading reversal signal — price/indicator disagreement at extremes
//     precedes regime shifts.
// ============================================================================

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

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

// --- MFI Settings ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=14,
    label="Fast MFI Length",
    constraints={min: 2, max: 50, step: 1},
    group="MFI Settings"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=20,
    label="Slow MFI Length",
    constraints={min: 2, max: 50, step: 1},
    group="MFI Settings"
)

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

// --- Thresholds ---
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=80,
    label="Static Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=20,
    label="Static Oversold Level",
    constraints={min: 5, max: 50, 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"
)
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"
)

// --- 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"
)

// --- Display ---
var showFastSlow = input(
    name="showFastSlow",
    type="boolean",
    defaultValue=true,
    label="Show Fast & Slow MFI Lines",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show MFI Ribbon (fast/slow fill)",
    group="Display"
)
var showSignalFill = input(
    name="showSignalFill",
    type="boolean",
    defaultValue=true,
    label="Show Signal Fill (avg/signal fill)",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showObOs = input(
    name="showObOs",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zones",
    group="Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Display"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Display"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffffff",
    label="Signal Line Color",
    group="Display"
)
var divBullColor = input(
    name="divBullColor",
    type="color",
    defaultValue="#00e676",
    label="Bullish Divergence Color",
    group="Display"
)
var divBearColor = input(
    name="divBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Bearish Divergence Color",
    group="Display"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries vol = bars.volume

if (isnan(px[0]) || isnan(high[0]) || isnan(low[0]) || isnan(vol[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. CANONICAL MFI — Quong & Soudack (1989) implementation
// -----------------------------------------------------------------------------
// Typical Price = (High + Low + Close) / 3
// Raw Money Flow = Typical Price × Volume
// Money Flow Ratio = Σ(positive MF) / Σ(negative MF) over N periods
// MFI = 100 − [100 / (1 + MFR)]

// --- Typical Price & Previous ---
timeseries typical = (high + low + px) / 3
timeseries typicalPrev = (high[1] + low[1] + px[1]) / 3

// --- Raw Money Flow ---
timeseries rawMF = typical * vol

// --- Positive / Negative Money Flow ---
timeseries posMF = typical > typicalPrev ? rawMF : 0
timeseries negMF = typical < typicalPrev ? rawMF : 0

// --- Fast MFI ---
timeseries sumPosFast = sum(source=posMF, period=fastLen)
timeseries sumNegFast = sum(source=negMF, period=fastLen)
timeseries mfRatioFast = sumNegFast > 0 ? sumPosFast / sumNegFast : 0
timeseries fastRaw = sumNegFast > 0 ? 100 - (100 / (1 + mfRatioFast)) : 50

// --- Slow MFI ---
timeseries sumPosSlow = sum(source=posMF, period=slowLen)
timeseries sumNegSlow = sum(source=negMF, period=slowLen)
timeseries mfRatioSlow = sumNegSlow > 0 ? sumPosSlow / sumNegSlow : 0
timeseries slowRaw = sumNegSlow > 0 ? 100 - (100 / (1 + mfRatioSlow)) : 50

// -----------------------------------------------------------------------------
// 4. SMOOTHING & SIGNAL
// -----------------------------------------------------------------------------
timeseries fastMfi = ema(source=fastRaw, period=smoothLen)
timeseries slowMfi = ema(source=slowRaw, period=smoothLen)

// Averaged MFI (midpoint of fast and slow)
timeseries avgMfi = (fastMfi + slowMfi) / 2

// Signal SMA
timeseries signal = sma(source=avgMfi, period=signalLen)

// Momentum histogram (MFI minus signal)
timeseries hist = avgMfi - signal

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION
// -----------------------------------------------------------------------------
// Regime classification:
//   Bullish: avgMfi > signal AND avgMfi > 50
//   Bearish: avgMfi < signal AND avgMfi < 50
//   Neutral: everything else (chop zone)

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

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

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

var mfiVol = stddev(source=avgMfi, period=volLookback)
var dynOb = useDynamic ? math.min(95, obLevel + mfiVol * volMultiplier) : obLevel
var dynOs = useDynamic ? math.max(5, osLevel - mfiVol * volMultiplier) : osLevel

// Guard: ensure dynamic bands never cross
if (dynOb <= dynOs) {
    dynOb = 80
    dynOs = 20
}

// -----------------------------------------------------------------------------
// 7. DIVERGENCE DETECTION (stateful via static variables)
// -----------------------------------------------------------------------------
// Regular divergence: price makes higher high / lower low, MFI disagrees.
// Hidden divergence: price makes higher low / lower high, MFI disagrees.
// We track pivot high/low state across bars using static variables.

static prevPxHigh = -1.0
static prevMfiHigh = -1.0
static prevPxLow = -1.0
static prevMfiLow = -1.0
static prevPxHighLow = -1.0
static prevMfiHighLow = -1.0
static prevPxLowHigh = -1.0
static prevMfiLowHigh = -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 = high[0]
    prevMfiHigh = fastMfi[0]
    prevPxLow = low[0]
    prevMfiLow = fastMfi[0]
    prevPxHighLow = high[0]
    prevMfiHighLow = fastMfi[0]
    prevPxLowHigh = low[0]
    prevMfiLowHigh = fastMfi[0]
}

if (!isLiveUpdate && enableDiv) {
    // --- Regular Bearish Divergence ---
    // Price makes a higher high; MFI makes a lower high
    var pxHigh = highest(source=high, period=divLookback)
    var mfiHigh = highest(source=fastMfi, period=divLookback)
    if (high[0] > prevPxHigh) {
        if (fastMfi[0] < prevMfiHigh) {
            bearDiv = true
        }
        prevPxHigh = high[0]
        prevMfiHigh = fastMfi[0]
    }

    // --- Regular Bullish Divergence ---
    // Price makes a lower low; MFI makes a higher low
    var pxLow = lowest(source=low, period=divLookback)
    var mfiLow = lowest(source=fastMfi, period=divLookback)
    if (low[0] < prevPxLow) {
        if (fastMfi[0] > prevMfiLow) {
            bullDiv = true
        }
        prevPxLow = low[0]
        prevMfiLow = fastMfi[0]
    }

    // --- Hidden Divergence ---
    // Hidden bullish: price higher low, MFI lower low
    // Hidden bearish: price lower high, MFI higher high
    if (showHidden) {
        // Hidden bullish: price makes a higher low vs prior low
        if (low[0] > prevPxLow && high[0] < prevPxHigh) {
            if (fastMfi[0] < prevMfiLow) {
                hiddenBullDiv = true
            }
        }
        // Hidden bearish: price makes a lower high vs prior high
        if (high[0] < prevPxHigh && low[0] > prevPxLow) {
            if (fastMfi[0] > prevMfiHigh) {
                hiddenBearDiv = true
            }
        }
    }
}

// -----------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Crossover / crossunder of averaged MFI and signal
var crossUp = avgMfi > signal && avgMfi[1] <= signal[1]
var crossDown = avgMfi < signal && avgMfi[1] >= signal[1]

// OB / OS penetrations (using dynamic or static thresholds)
var obPenetrate = avgMfi > dynOb && avgMfi[1] <= dynOb
var osPenetrate = avgMfi < dynOs && avgMfi[1] >= dynOs

// OB / OS exit (return to neutral zone)
var obExit = avgMfi < dynOb && avgMfi[1] >= dynOb
var osExit = avgMfi > dynOs && avgMfi[1] <= dynOs

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

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

// --- OB / OS Zones ---
if (showObOs) {
    hline(value=dynOb, color=transparency(bearColor, 60), width=1)
    hline(value=dynOs, color=transparency(bullColor, 60), width=1)
}

// --- Fast / Slow MFI Ribbon Fill ---
if (showRibbon) {
    var ribbonBull = fastMfi > slowMfi
    plotLine(
        value=[fastMfi, slowMfi],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Fast MFI", "Slow MFI"],
        desc=["Fast smoothed MFI ribbon edge", "Slow smoothed MFI ribbon edge"]
    )
}

// --- Individual Fast & Slow Lines ---
if (showFastSlow) {
    plotLine(
        value=fastMfi,
        width=2,
        colors=[bullColor],
        label=["Fast MFI"],
        desc=["Fast smoothed MFI (Quong & Soudack " + fastLen + ")"]
    )
    plotLine(
        value=slowMfi,
        width=2,
        colors=[bearColor],
        label=["Slow MFI"],
        desc=["Slow smoothed MFI (Quong & Soudack " + slowLen + ")"]
    )
}

// --- Averaged MFI (regime-colored) ---
plotLine(
    value=avgMfi,
    width=2,
    colors=[regimeColor],
    label=["Avg MFI"],
    desc=["Averaged smoothed MFI (regime-colored)"]
)

// --- Signal SMA ---
plotLine(
    value=signal,
    width=1,
    colors=[signalColor],
    label=["Signal SMA"],
    desc=["SMA of averaged smoothed MFI (" + signalLen + ")"]
)

// --- Signal Fill (avg MFI vs signal) ---
if (showSignalFill) {
    var signalBull = avgMfi > signal
    plotLine(
        value=[avgMfi, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["Avg MFI", "Signal SMA"],
        desc=["Fill between averaged MFI and signal SMA"]
    )
}

// --- 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=["MFI Momentum"],
        desc=["Histogram of averaged MFI minus signal SMA"]
    )
}

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

// --- Alert Shapes (crossovers, OB/OS) ---
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["Averaged MFI crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["Averaged MFI crossed below signal SMA"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=dynOb,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["OB Penetrate"],
            desc=["MFI entered overbought zone (MFI > " + dynOb + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=dynOs,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["OS Penetrate"],
            desc=["MFI entered oversold zone (MFI < " + dynOs + ")"]
        )
    }
}

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

    plotTable(
        data=[
            ["MFI Pro — Perfected", regimeText],
            ["Fast MFI", fastMfi[0]],
            ["Slow MFI", slowMfi[0]],
            ["Avg MFI", avgMfi[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            [obText, osText]
        ],
        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
    )
}