MM Flow
FlowScripts

Perfected FlowScript

Private1

Private1 — Multi-Factor Composite (Perfected) is indexed as 323_private1.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.1 KB

Lines

614

Native Signal Candidates

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

6/6 guarded

Extreme Bull

line 520:9

Trigger

(showShapes) && (extremeBull)

Value

compZ

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 530:9

Trigger

(showShapes) && (extremeBear)

Value

compZ

Deps

extremeBear:var, showShapes:input

Cross Up

line 540:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Cross Down

line 550:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

OB Penetrate

line 560:9

Trigger

(showShapes) && (obPenetrate)

Value

obLevel

Deps

obPenetrate:var, showShapes:input

OS Penetrate

line 570:9

Trigger

(showShapes) && (osPenetrate)

Value

osLevel

Deps

osPenetrate:var, showShapes:input

323_private1.flowscript

source path: kscripts/perfected/323_private1.flowscript · sha256:ad73acc51f2417ff1ff905bcf3454a710dc0b96dcca966e60b533f57527d4380

hash verified
//@version=2
// ============================================================================
// Private1 — Multi-Factor Composite Indicator (Perfected Edition)
// Author: K (@karlabo93) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #rsi, #momentum, #volatility, #composite, #regime, #zscore
//
// Production-quality multi-factor composite indicator combining RSI momentum,
// price-action trend alignment, volatility regime, and mean-reversion score
// into a unified 0-100 reading with z-score normalisation, regime detection,
// color-coded histograms, and extreme shape alerts.
//
// Academic foundation (exact papers & formulas):
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI publication. RSI = 100 − [100 / (1 + RS)] where RS = SMA(gain, N) /
//     SMA(loss, N). Original smoothing period = 14.
//
//  2. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": established momentum as a premier cross-sectional anomaly.
//     Validates multi-factor momentum scoring.
//     DOI: https://doi.org/10.1111/j.1540-6261.1993.tb04702.x
//
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications": negative autocorrelation at medium horizons; supports
//     dynamic overbought/oversold thresholds calibrated to rolling volatility.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", JFE 65(1), 111–130. Extreme imbalances predict return
//     reversals; supports composite divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  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="Private1 — Multi-Factor Composite (Perfected)",
    position="offchart",
    axis=true
)

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

// -- RSI Factor --
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="RSI Factor"
)
var rsiWeight = input(
    name="rsiWeight",
    type="number",
    defaultValue=0.30,
    label="RSI Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="RSI Factor"
)

// -- Momentum Factor --
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=10,
    label="Momentum Length",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum Factor"
)
var momWeight = input(
    name="momWeight",
    type="number",
    defaultValue=0.25,
    label="Momentum Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Momentum Factor"
)

// -- Trend Factor --
var trendLen = input(
    name="trendLen",
    type="number",
    defaultValue=20,
    label="Trend SMA Length",
    constraints={min: 5, max: 100, step: 1},
    group="Trend Factor"
)
var trendWeight = input(
    name="trendWeight",
    type="number",
    defaultValue=0.25,
    label="Trend Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Trend Factor"
)

// -- Volatility Factor --
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 50, step: 1},
    group="Volatility Factor"
)
var volWeight = input(
    name="volWeight",
    type="number",
    defaultValue=0.20,
    label="Volatility Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Volatility Factor"
)

// -- Normalisation --
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window (bars)",
    constraints={min: 20, max: 200, step: 5},
    group="Normalisation"
)
var smooth = input(
    name="smooth",
    type="number",
    defaultValue=3,
    label="Composite Smoothing",
    constraints={min: 1, max: 20, step: 1},
    group="Normalisation"
)

// -- Thresholds --
var obLevel = input(
    name="obLevel",
    type="number",
    defaultValue=70,
    label="Overbought Level",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var osLevel = input(
    name="osLevel",
    type="number",
    defaultValue=30,
    label="Oversold Level",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)
var divThreshold = input(
    name="divThreshold",
    type="number",
    defaultValue=2.0,
    label="Divergence Regime Threshold (z)",
    constraints={min: 0.5, max: 4.0, step: 0.5},
    group="Thresholds"
)
var extremeDiv = input(
    name="extremeDiv",
    type="number",
    defaultValue=3.0,
    label="Extreme Divergence Threshold (z)",
    constraints={min: 2.0, max: 6.0, step: 0.5},
    group="Thresholds"
)

// -- Display --
var showComposite = input(
    name="showComposite",
    type="boolean",
    defaultValue=true,
    label="Show Composite Score",
    group="Display"
)
var showZ = input(
    name="showZ",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Divergence Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Divergence Shapes",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Bands",
    group="Display"
)
var showFactors = input(
    name="showFactors",
    type="boolean",
    defaultValue=false,
    label="Show Individual Factor Lines",
    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 neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#2962ff",
    label="Base Line Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#ffffff",
    label="Signal Line 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. MULTI-FACTOR SCORING
// ---------------------------------------------------------------------------
// Composite = weighted average of four orthogonal factors:
//   (1) RSI momentum (0-100)
//   (2) Price momentum (normalised rate of change, mapped to 0-100)
//   (3) Trend alignment (close vs SMA, mapped to 0-100)
//   (4) Volatility regime (ATR percentile, mapped to 0-100)
// Each factor is independently computed, then weighted and summed.
// Weights are normalised so they sum to 1.0.

// -- 3.1 RSI Factor (0-100) --
timeseries rsiRaw = rsi(px, rsiLen)

// -- 3.2 Momentum Factor (0-100) --
// Rate of change normalised by rolling standard deviation of price changes
var pxChange = px - px[1]
timeseries momRaw = px[momLen] > 0 ? (px - px[momLen]) / px[momLen] * 100.0 : 0.0
timeseries momStd = stddev(pxChange, zWindow)
timeseries momZ = (momStd > 0) ? momRaw / momStd : 0
// Map z-score to 0-100: sigmoid-like clamp
timeseries momScore = 50 + math.max(-50, math.min(50, momZ * 10))

// -- 3.3 Trend Factor (0-100) --
// Close position relative to SMA, mapped to 0-100
timeseries trendSma = sma(px, trendLen)
timeseries trendDist = trendSma > 0 ? ((px - trendSma) / trendSma) * 100.0 : 0
timeseries trendStd = stddev(trendDist, zWindow)
timeseries trendZ = (trendStd > 0) ? trendDist / trendStd : 0
// Map to 0-100 with 50 = on SMA
timeseries trendScore = 50 + math.max(-50, math.min(50, trendZ * 10))

// -- 3.4 Volatility Factor (0-100) --
// ATR as percentage of price, then percentile-ranked
timeseries atr = tr(bars)
timeseries atrPct = (px > 0) ? (atr / px) * 100.0 : 0
timeseries atrMean = sma(atrPct, zWindow)
timeseries atrStd = stddev(atrPct, zWindow)
timeseries volZ = (atrStd > 0) ? (atrPct - atrMean) / atrStd : 0
// High volatility = 100, low = 0 (inverted for mean-reversion scoring)
timeseries volScore = 50 + math.max(-50, math.min(50, volZ * 10))

// -- 3.5 Weight Normalisation --
// Ensure weights sum to 1.0 to avoid scaling drift
var totalWeight = rsiWeight + momWeight + trendWeight + volWeight
if (totalWeight <= 0) {
    totalWeight = 1.0
}
var wRsi = rsiWeight / totalWeight
var wMom = momWeight / totalWeight
var wTrend = trendWeight / totalWeight
var wVol = volWeight / totalWeight

// -- 3.6 Composite Score (0-100) --
timeseries compositeRaw = (rsiRaw * wRsi) + (momScore * wMom) + (trendScore * wTrend) + (volScore * wVol)
timeseries composite = sma(compositeRaw, smooth)

// -- 3.7 Signal SMA --
timeseries signal = sma(composite, rsiLen)

// ---------------------------------------------------------------------------
// 4. Z-SCORE NORMALISATION
// ---------------------------------------------------------------------------
// Z_t = (Composite_t - mu_t) / sigma_t where mu_t = SMA(Composite, W),
// sigma_t = StDev(Composite, W). Guards: if sigma_t == 0 emit 0.

timeseries compMean = sma(composite, zWindow)
timeseries compStd = stddev(composite, zWindow)
timeseries compZ = (compStd > 0) ? (composite - compMean) / compStd : 0

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on z-score and composite position:
//   Bullish: compZ > divThreshold AND composite > 50
//   Bearish: compZ < -divThreshold AND composite < 50
//   Neutral: everything else

var regimeBull = compZ > divThreshold && composite > 50
var regimeBear = compZ < -divThreshold && composite < 50
var regimeNeutral = !regimeBull && !regimeBear

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

// ---------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
// Tracks consecutive bars in each regime for context-aware alerting.

static lastRegime = 0
static bullBars = 0
static bearBars = 0
static neutralBars = 0
static maxBullZ = 0.0
static maxBearZ = 0.0

if (!isnan(compZ[0])) {
    if (regimeBull) {
        bullBars = bullBars + 1
        bearBars = 0
        neutralBars = 0
        if (compZ[0] > maxBullZ) {
            maxBullZ = compZ[0]
        }
        lastRegime = 1
    } else if (regimeBear) {
        bearBars = bearBars + 1
        bullBars = 0
        neutralBars = 0
        if (compZ[0] < maxBearZ) {
            maxBearZ = compZ[0]
        }
        lastRegime = -1
    } else {
        neutralBars = neutralBars + 1
        bullBars = 0
        bearBars = 0
        lastRegime = 0
    }
}

// ---------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Crossover / crossunder of composite and signal
var crossUp = composite > signal && composite[1] <= signal[1]
var crossDown = composite < signal && composite[1] >= signal[1]

// OB / OS penetrations
var obPenetrate = composite > obLevel && composite[1] <= obLevel
var osPenetrate = composite < osLevel && composite[1] >= osLevel

// Extreme divergence
var extremeBull = compZ > extremeDiv
var extremeBear = compZ < -extremeDiv

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

// 8.1 Reference lines (hline)
hline(value=50,           color="#ffffff30", width=1)
hline(value=divThreshold, color="#ffffff20", width=1)
hline(value=-divThreshold,color="#ffffff20", width=1)
hline(value=extremeDiv,  color="#ffffff15", width=1)
hline(value=-extremeDiv, color="#ffffff15", width=1)

// 8.2 OB / OS bands
if (showBands) {
    hline(value=obLevel, color=transparency(bearColor, 60), width=1)
    hline(value=osLevel, color=transparency(bullColor, 60), width=1)
    hline(value=0,      color="#ffffff20", width=1)
    hline(value=100,    color="#ffffff20", width=1)
}

// 8.3 Composite Score (regime-colored)
if (showComposite) {
    plotLine(
        value=composite,
        width=2,
        colors=[regimeColor],
        label=["Composite Score"],
        desc=["Multi-factor composite score (0-100); weighted RSI + momentum + trend + volatility"]
    )
}

// 8.4 Signal SMA
if (showComposite) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal SMA"],
        desc=["SMA of composite score (" + rsiLen + ")"]
    )
}

// 8.5 Individual Factor Lines (optional)
if (showFactors) {
    plotLine(
        value=rsiRaw,
        width=1,
        colors=["#9c27b0"],
        label=["RSI"],
        desc=["RSI factor (" + rsiLen + ")"]
    )
    plotLine(
        value=momScore,
        width=1,
        colors=["#ff9800"],
        label=["Momentum"],
        desc=["Momentum factor (" + momLen + ")"]
    )
    plotLine(
        value=trendScore,
        width=1,
        colors=["#00bcd4"],
        label=["Trend"],
        desc=["Trend factor (" + trendLen + ")"]
    )
    plotLine(
        value=volScore,
        width=1,
        colors=["#8bc34a"],
        label=["Volatility"],
        desc=["Volatility factor (" + atrLen + ")"]
    )
}

// 8.6 Z-Score Line (regime-colored)
if (showZ) {
    plotLine(
        value=compZ,
        width=2,
        colors=[regimeColor],
        label=["Composite Z-Score"],
        desc=["Rolling z-score of composite score; mean-reverting around 0"]
    )
}

// 8.7 Z-Score Histogram (color-coded by regime)
if (showHistogram) {
    var histBull = compZ >= 0
    plotBar(
        value=compZ,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Composite Z Histogram"],
        desc=["Z-score histogram; positive = bullish regime, negative = bearish regime"]
    )
}

// 8.8 Divergence Fill (composite vs signal, color-coded)
if (showFill) {
    var fillBull = composite > signal
    plotLine(
        value=[composite, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Composite", "Signal"],
        desc=["Fill between composite score and signal SMA; colour-coded by regime"]
    )
}

// 8.9 Extreme divergence shapes (plotShape)
if (showShapes) {
    if (extremeBull) {
        plotShape(
            value=compZ,
            shape="triangleup",
            colorIndex=bullColor,
            width=3,
            label=["Extreme Bull"],
            desc=["Extreme bullish composite (z > " + extremeDiv + "); overbought / distribution risk"]
        )
    }
    if (extremeBear) {
        plotShape(
            value=compZ,
            shape="triangledown",
            colorIndex=bearColor,
            width=3,
            label=["Extreme Bear"],
            desc=["Extreme bearish composite (z < -" + extremeDiv + "); oversold / accumulation opportunity"]
        )
    }
    if (crossUp) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["Composite crossed above signal SMA (bullish bias)"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["Composite crossed below signal SMA (bearish bias)"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=obLevel,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["OB Penetrate"],
            desc=["Composite entered overbought zone (> " + obLevel + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=osLevel,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["OS Penetrate"],
            desc=["Composite entered oversold zone (< " + osLevel + ")"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

    plotTable(
        data=[
            ["Private1 — Perfected", regimeText],
            ["Composite", composite[0]],
            ["Z-Score", compZ[0]],
            ["Signal", signal[0]],
            ["RSI Factor", rsiRaw[0]],
            ["Momentum", momScore[0]],
            ["Trend", trendScore[0]],
            ["Volatility", volScore[0]],
            ["Consecutive Bull", bullBars],
            ["Consecutive Bear", bearBars]
        ],
        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
    )
}