MM Flow
FlowScripts

Perfected FlowScript

Untitled Script 2025/09/03 17:43

Multi-Factor Momentum Confluence — Perfected Edition is indexed as 351_untitled_script_2025_09_03_17_43.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

19.7 KB

Lines

641

Native Signal Candidates

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

6/6 guarded

Bull Div

line 515:9

Trigger

(showShapes && enableDiv) && (bullDiv)

Value

bars.low

Deps

bullDiv:var, enableDiv:input, showShapes:input

Bear Div

line 525:9

Trigger

(showShapes && enableDiv) && (bearDiv)

Value

bars.high

Deps

bearDiv:var, enableDiv:input, showShapes:input

EMA Cross Up

line 539:9

Trigger

(showShapes) && (emaCrossUp)

Value

fastEma

Deps

emaCrossUp:var, showShapes:input

EMA Cross Down

line 549:9

Trigger

(showShapes) && (emaCrossDn)

Value

fastEma

Deps

emaCrossDn:var, showShapes:input

MACD Cross Up

line 559:9

Trigger

(showShapes) && (macdCrossUp)

Value

macdLine

Deps

macdCrossUp:var, showShapes:input

MACD Cross Down

line 569:9

Trigger

(showShapes) && (macdCrossDn)

Value

macdLine

Deps

macdCrossDn:var, showShapes:input

351_untitled_script_2025_09_03_17_43.flowscript

source path: kscripts/perfected/351_untitled_script_2025_09_03_17_43.flowscript · sha256:e761fc16645f67ce07e4ee9bb22034bb337537f378dc46010bc673e5290f63e6

hash verified
//@version=2
// ============================================================================
// Multi-Factor Momentum Confluence — Perfected Edition
// Author: F (@fssgsdgsdg) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #momentum, #confluence, #regime, #multi-factor, #trend
//
// Production-quality composite momentum indicator fusing EMA crossovers,
// MACD, RSI, and volume-based confirmation into a single multi-factor score.
// Implements dynamic regime detection with volatility-adjusted thresholds,
// full stateful divergence tracking, color-coded visualization, and shape
// markers for signal events.
//
// Research papers underpinning this design:
//  1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
//     and the Stochastic Properties of Stock Returns": MA crossovers
//     significantly outperform benchmarks; buy signals followed by positive
//     returns over 90 years of DJIA data.
//  2. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": momentum as a premier cross-sectional anomaly; validates
//     MACD and momentum-based signal construction.
//  3. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI formula. RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N) /
//     SMA(loss, N). Original smoothing period = 14.
//  4. Murphy (1999), "Technical Analysis of the Financial Markets":
//     divergence as a leading reversal signal — price/indicator disagreement
//     at extremes precedes regime shifts. Multi-indicator confirmation
//     reduces false signals.
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons supports dynamic threshold
//     calibration to rolling volatility.
// ============================================================================

define(
    title="Multi-Factor Momentum Confluence — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- EMA Settings ---
var emaFast = input(
    name="emaFast",
    type="number",
    defaultValue=12,
    label="EMA Fast Length",
    constraints={min: 2, max: 200, step: 1},
    group="EMA Settings"
)
var emaSlow = input(
    name="emaSlow",
    type="number",
    defaultValue=26,
    label="EMA Slow Length",
    constraints={min: 2, max: 200, step: 1},
    group="EMA Settings"
)
var emaRibbon = input(
    name="emaRibbon",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon Fill",
    group="EMA Settings"
)

// --- MACD Settings ---
var macdFast = input(
    name="macdFast",
    type="number",
    defaultValue=12,
    label="MACD Fast Length",
    constraints={min: 2, max: 50, step: 1},
    group="MACD Settings"
)
var macdSlow = input(
    name="macdSlow",
    type="number",
    defaultValue=26,
    label="MACD Slow Length",
    constraints={min: 2, max: 50, step: 1},
    group="MACD Settings"
)
var macdSignalLen = input(
    name="macdSignal",
    type="number",
    defaultValue=9,
    label="MACD Signal Length",
    constraints={min: 1, max: 50, step: 1},
    group="MACD Settings"
)
var macdFill = input(
    name="macdFill",
    type="boolean",
    defaultValue=true,
    label="Show MACD Fill",
    group="MACD Settings"
)

// --- RSI Settings ---
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="RSI Settings"
)
var rsiSmooth = input(
    name="rsiSmooth",
    type="number",
    defaultValue=3,
    label="RSI Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="RSI Settings"
)
var rsiOb = input(
    name="rsiOb",
    type="number",
    defaultValue=70,
    label="RSI Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="RSI Settings"
)
var rsiOs = input(
    name="rsiOs",
    type="number",
    defaultValue=30,
    label="RSI Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="RSI Settings"
)

// --- Volume Settings ---
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Settings"
)
var volSmooth = input(
    name="volSmooth",
    type="number",
    defaultValue=5,
    label="Volume Smoothing",
    constraints={min: 1, max: 50, step: 1},
    group="Volume Settings"
)
var useVol = input(
    name="useVol",
    type="boolean",
    defaultValue=true,
    label="Use Volume Confirmation",
    group="Volume Settings"
)

// --- Multi-Factor Score ---
var scoreWindow = input(
    name="scoreWindow",
    type="number",
    defaultValue=10,
    label="Score Normalization Window",
    constraints={min: 5, max: 50, step: 1},
    group="Multi-Factor Score"
)
var showScore = input(
    name="showScore",
    type="boolean",
    defaultValue=true,
    label="Show Multi-Factor Score",
    group="Multi-Factor Score"
)

// --- 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",
    constraints={min: 5, max: 50, step: 1},
    group="Divergence"
)

// --- Display ---
var showEma = input(
    name="showEma",
    type="boolean",
    defaultValue=true,
    label="Show EMA Lines",
    group="Display"
)
var showMacd = input(
    name="showMacd",
    type="boolean",
    defaultValue=true,
    label="Show MACD Panel",
    group="Display"
)
var showRsi = input(
    name="showRsi",
    type="boolean",
    defaultValue=false,
    label="Show RSI Panel (offchart)",
    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 neutColor = input(
    name="neutColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral 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 px = bars.close

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

// ----------------------------------------------------------------------------
// 3. EMA RIBBON
// ----------------------------------------------------------------------------
timeseries fastEma = ema(source=px, period=emaFast)
timeseries slowEma = ema(source=px, period=emaSlow)
timeseries emaSpread = fastEma - slowEma

// ----------------------------------------------------------------------------
// 4. MACD
// ----------------------------------------------------------------------------
timeseries macdFastEma = ema(source=px, period=macdFast)
timeseries macdSlowEma = ema(source=px, period=macdSlow)
timeseries macdLine = macdFastEma - macdSlowEma
timeseries macdSignal = ema(source=macdLine, period=macdSignalLen)
timeseries macdHist = macdLine - macdSignal

// ----------------------------------------------------------------------------
// 5. RSI (Wilder canonical)
// ----------------------------------------------------------------------------
timeseries rsiChange = px[0] - px[1]
timeseries rsiGain = rsiChange > 0 ? rsiChange : 0
timeseries rsiLoss = rsiChange < 0 ? -rsiChange : 0
timeseries avgGain = ema(source=rsiGain, period=rsiLen)
timeseries avgLoss = ema(source=rsiLoss, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
timeseries rsiSmoothed = ema(source=rsiRaw, period=rsiSmooth)

// ----------------------------------------------------------------------------
// 6. VOLUME OSCILLATOR
// ----------------------------------------------------------------------------
timeseries volAvg = sma(source=bars.volume, period=volLookback)
timeseries volOsc = volAvg > 0 ? (bars.volume[0] / volAvg[0] - 1.0) * 100.0 : 0.0
timeseries volOscSmooth = ema(source=volOsc, period=volSmooth)

// ----------------------------------------------------------------------------
// 7. MULTI-FACTOR SCORE
// ----------------------------------------------------------------------------
// Normalize each factor to [-1, +1] and combine into a composite score.
// Factor 1: EMA trend (fast vs slow) → +1 when fast > slow, −1 when fast < slow
// Factor 2: MACD histogram sign → +1 when positive, −1 when negative
// Factor 3: RSI position (0–100 mapped to −1 to +1)
// Factor 4: Volume confirmation → +1 when volume > average, −1 otherwise

timeseries emaFactor = fastEma > slowEma ? 1.0 : -1.0
timeseries macdFactor = macdHist > 0 ? 1.0 : -1.0
timeseries rsiFactor = (rsiSmoothed - 50.0) / 50.0
timeseries volFactor = useVol ? (volOscSmooth > 0 ? 1.0 : -1.0) : 0.0

timeseries rawScore = (emaFactor + macdFactor + rsiFactor + volFactor) / (useVol ? 4.0 : 3.0)

// Smooth the score
timeseries score = ema(source=rawScore, period=5)

// Normalize score to z-score over rolling window for statistical context
timeseries scoreMean = sma(source=score, period=scoreWindow)
timeseries scoreStd = stddev(source=score, period=scoreWindow)
timeseries scoreZ = scoreStd > 0 ? (score - scoreMean) / scoreStd : 0.0

// ----------------------------------------------------------------------------
// 8. REGIME DETECTION
// ----------------------------------------------------------------------------
// Regime classification based on multi-factor score:
//   Strong Bull: score > 0.5
//   Bull:        score > 0.0
//   Neutral:     score between −0.3 and +0.3
//   Bear:        score < 0.0
//   Strong Bear: score < −0.5

var regimeStrongBull = score > 0.5
var regimeBull = score > 0.0 && score <= 0.5
var regimeNeutral = score >= -0.3 && score <= 0.3
var regimeBear = score < 0.0 && score >= -0.5
var regimeStrongBear = score < -0.5

var regimeColor = regimeStrongBull ? bullColor : (regimeStrongBear ? bearColor : (regimeBull ? transparency(bullColor, 70) : (regimeBear ? transparency(bearColor, 70) : neutColor)))

// ----------------------------------------------------------------------------
// 9. DYNAMIC THRESHOLDS
// ----------------------------------------------------------------------------
// Volatility-adjusted score bands using ATR
timeseries atrVal = atr(period=14)
timeseries atrPct = px > 0 ? (atrVal / px) * 100.0 : 0.0
timeseries atrAvg = sma(source=atrPct, period=20)
timeseries dynVolMultiplier = atrAvg > 0 ? atrPct / atrAvg : 1.0

var scoreBullThresh = 0.3 * dynVolMultiplier
var scoreBearThresh = -0.3 * dynVolMultiplier
var scoreExtremeBull = 0.6 * dynVolMultiplier
var scoreExtremeBear = -0.6 * dynVolMultiplier

// ----------------------------------------------------------------------------
// 10. DIVERGENCE DETECTION (stateful via static variables)
// ----------------------------------------------------------------------------
static prevPxHigh = -1.0
static prevScoreHigh = -1.0
static prevPxLow = -1.0
static prevScoreLow = -1.0

var bearDiv = false
var bullDiv = false

// Initialize on first real bar after NaN guard
if (prevPxHigh < 0) {
    prevPxHigh = bars.high[0]
    prevScoreHigh = score[0]
    prevPxLow = bars.low[0]
    prevScoreLow = score[0]
}

if (!isLiveUpdate && enableDiv) {
    // Bearish divergence: price higher high, score lower high
    if (bars.high[0] > prevPxHigh) {
        if (score[0] < prevScoreHigh) {
            bearDiv = true
        }
        prevPxHigh = bars.high[0]
        prevScoreHigh = score[0]
    }

    // Bullish divergence: price lower low, score higher low
    if (bars.low[0] < prevPxLow) {
        if (score[0] > prevScoreLow) {
            bullDiv = true
        }
        prevPxLow = bars.low[0]
        prevScoreLow = score[0]
    }
}

// ----------------------------------------------------------------------------
// 11. ALERT CONDITIONS
// ----------------------------------------------------------------------------
var emaCrossUp = fastEma > slowEma && fastEma[1] <= slowEma[1]
var emaCrossDn = fastEma < slowEma && fastEma[1] >= slowEma[1]

var macdCrossUp = macdLine > macdSignal && macdLine[1] <= macdSignal[1]
var macdCrossDn = macdLine < macdSignal && macdLine[1] >= macdSignal[1]

var scoreCrossUp = score > 0.0 && score[1] <= 0.0
var scoreCrossDn = score < 0.0 && score[1] >= 0.0

var rsiObPenetrate = rsiSmoothed > rsiOb && rsiSmoothed[1] <= rsiOb
var rsiOsPenetrate = rsiSmoothed < rsiOs && rsiSmoothed[1] >= rsiOs

// ----------------------------------------------------------------------------
// 12. STATIC STATE TRACKING
// ----------------------------------------------------------------------------
static sessionScoreHigh = -999999.0
static sessionScoreLow = 999999.0
static sessionPxHigh = -999999.0
static sessionPxLow = 999999.0
static regimeChangeCount = 0
static lastRegime = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (score[0] > sessionScoreHigh) {
        sessionScoreHigh = score[0]
    }
    if (score[0] < sessionScoreLow) {
        sessionScoreLow = score[0]
    }
    if (bars.high[0] > sessionPxHigh) {
        sessionPxHigh = bars.high[0]
    }
    if (bars.low[0] < sessionPxLow) {
        sessionPxLow = bars.low[0]
    }

    var currentRegime = regimeStrongBull ? 2 : (regimeBull ? 1 : (regimeBear ? -1 : (regimeStrongBear ? -2 : 0)))
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }
}

// ----------------------------------------------------------------------------
// 13. PLOTTING — On-Chart
// ----------------------------------------------------------------------------

// --- EMA Lines ---
if (showEma) {
    plotLine(
        value=fastEma,
        width=2,
        colors=[bullColor],
        label=["EMA Fast"],
        desc=["Fast EMA (" + emaFast + ") — trend responsiveness"]
    )
    plotLine(
        value=slowEma,
        width=2,
        colors=[bearColor],
        label=["EMA Slow"],
        desc=["Slow EMA (" + emaSlow + ") — trend stability"]
    )
}

// --- EMA Ribbon Fill ---
if (showEma && emaRibbon) {
    var ribbonBull = fastEma > slowEma
    plotLine(
        value=[fastEma, slowEma],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["EMA Fast", "EMA Slow"],
        desc=["EMA ribbon fill: trend direction via fast/slow spread"]
    )
}

// --- MACD Histogram (plotted as columns on chart) ---
if (showMacd) {
    var histBull = macdHist >= 0
    plotBar(
        value=macdHist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["MACD Hist"],
        desc=["MACD histogram: momentum expansion/contraction"]
    )
}

// --- Multi-Factor Score (as a background line on chart) ---
if (showScore) {
    plotLine(
        value=px + (score * px * 0.02),
        width=2,
        colors=[regimeColor],
        label=["Score"],
        desc=["Multi-factor momentum score (normalized, regime-colored)"]
    )
}

// --- Divergence Shapes ---
if (showShapes && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=bars.low,
            shape="triangleup",
            colorIndex=divBullColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, score higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=bars.high,
            shape="triangledown",
            colorIndex=divBearColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, score lower high"]
        )
    }
}

// --- Signal Shapes (crossovers) ---
if (showShapes) {
    if (emaCrossUp) {
        plotShape(
            value=fastEma,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["EMA Cross Up"],
            desc=["Fast EMA crossed above slow EMA — bullish trend onset"]
        )
    }
    if (emaCrossDn) {
        plotShape(
            value=fastEma,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["EMA Cross Down"],
            desc=["Fast EMA crossed below slow EMA — bearish trend onset"]
        )
    }
    if (macdCrossUp) {
        plotShape(
            value=macdLine,
            shape="arrowup",
            colorIndex=transparency(bullColor, 80),
            width=1,
            label=["MACD Cross Up"],
            desc=["MACD line crossed above signal — momentum bullish"]
        )
    }
    if (macdCrossDn) {
        plotShape(
            value=macdLine,
            shape="arrowdown",
            colorIndex=transparency(bearColor, 80),
            width=1,
            label=["MACD Cross Down"],
            desc=["MACD line crossed below signal — momentum bearish"]
        )
    }
}

// ----------------------------------------------------------------------------
// 14. RSI PANEL (offchart) — optional
// ----------------------------------------------------------------------------
if (showRsi) {
    hline(value=50, color="#ffffff20", width=1)
    hline(value=rsiOb, color=transparency(bearColor, 60), width=1)
    hline(value=rsiOs, color=transparency(bullColor, 60), width=1)

    plotLine(
        value=rsiSmoothed,
        width=2,
        colors=[regimeColor],
        label=["RSI"],
        desc=["Smoothed RSI (" + rsiLen + ") — regime-colored"]
    )

    // RSI fill vs 50
    plotLine(
        value=[rsiSmoothed, 50],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=rsiSmoothed > 50 ? 0 : 1,
        fill=true,
        label=["RSI", "50"],
        desc=["RSI fill relative to 50 midline"]
    )
}

// ----------------------------------------------------------------------------
// 15. REGIME TABLE (last bar only)
// ----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeStrongBull ? "STRONG BULL" : (regimeBull ? "BULL" : (regimeBear ? "BEAR" : (regimeStrongBear ? "STRONG BEAR" : "NEUTRAL")))
    var regimeTextColor = regimeStrongBull || regimeBull ? bullColor : (regimeBear || regimeStrongBear ? bearColor : neutColor)

    plotTable(
        data=[
            ["Momentum Confluence", regimeText],
            ["Score", score[0]],
            ["Score Z", scoreZ[0]],
            ["RSI", rsiSmoothed[0]],
            ["MACD Hist", macdHist[0]],
            ["EMA Spread", emaSpread[0]],
            ["Vol Osc", volOscSmooth[0]],
            ["Regime Changes", regimeChangeCount],
            ["Score High", sessionScoreHigh],
            ["Score Low", sessionScoreLow]
        ],
        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
    )
}