MM Flow
FlowScripts

Perfected FlowScript

test

Test Signal Analyzer — Perfected Edition is indexed as 344_test.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

623

Native Signal Candidates

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

8/8 guarded

Bull Signal

line 505:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Bear Signal

line 515:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

Trend Pass

line 525:9

Trigger

(showShapes) && (trendBull)

Value

trendTest

Deps

showShapes:input, trendBull:var

Trend Fail

line 535:9

Trigger

(showShapes) && (trendBear)

Value

trendTest

Deps

showShapes:input, trendBear:var

Mom Pass

line 545:9

Trigger

(showShapes) && (momBull)

Value

momTest

Deps

momBull:var, showShapes:input

Mom Fail

line 555:9

Trigger

(showShapes) && (momBear)

Value

momTest

Deps

momBear:var, showShapes:input

Bull Confirmed

line 565:9

Trigger

(showShapes) && (regimeBull && bullStreak == 3)

Value

signal

Deps

bullStreak:static, regimeBull:var, showShapes:input

Bear Confirmed

line 575:9

Trigger

(showShapes) && (regimeBear && bearStreak == 3)

Value

signal

Deps

bearStreak:static, regimeBear:var, showShapes:input

344_test.flowscript

source path: kscripts/perfected/344_test.flowscript · sha256:c319011bdce86f624912dbf51ca04b5e891309d58ca663ba1e86cf479ca0ea0e

hash verified
//@version=2

// ============================================================================
// Test Signal Analyzer — Perfected Edition
// Author: J (@Jensen Kau) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #test, #signal, #multi-ma, #convergence, #regime
//
// Production-quality signal validation indicator that tests multiple technical
// conditions simultaneously — trend alignment (multi-MA convergence),
// momentum (RSI), volatility confirmation (ATR), and volume confirmation —
// producing a composite signal score with regime detection, color coding,
// shape markers, and a comprehensive test-results table.
//
// Research papers underpinning this design:
//  1. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules
//     and the Stochastic Properties of Stock Returns": MA-based signals
//     significantly outperform cash; validates multi-MA convergence testing.
//  2. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     RSI and ATR formulas underpin momentum and volatility test components.
//  3. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing": time-series momentum profitable since 1880; justifies trend
//     strength as a primary signal test criterion.
//  4. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": momentum anomaly; RSI test confirms momentum alignment.
//  5. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
//     Trading Activity": volume-based confirmation; validates volume test
//     as a filter for signal quality.
// ============================================================================

define(
    title="Test Signal Analyzer — Perfected Edition",
    position="offchart",
    axis=true
)

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

// --- Trend Test (Multi-MA) ---
var smaLen = input(
    name="smaLen",
    type="number",
    defaultValue=20,
    label="SMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="Trend Test"
)
var emaLen = input(
    name="emaLen",
    type="number",
    defaultValue=12,
    label="EMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="Trend Test"
)
var wmaLen = input(
    name="wmaLen",
    type="number",
    defaultValue=20,
    label="WMA Length",
    constraints={min: 2, max: 200, step: 1},
    group="Trend Test"
)
var trendWeight = input(
    name="trendWeight",
    type="number",
    defaultValue=40,
    label="Trend Test Weight (%)",
    constraints={min: 0, max: 100, step: 5},
    group="Trend Test"
)

// --- Momentum Test (RSI) ---
var rsiLen = input(
    name="rsiLen",
    type="number",
    defaultValue=14,
    label="RSI Length",
    constraints={min: 2, max: 50, step: 1},
    group="Momentum Test"
)
var rsiSmooth = input(
    name="rsiSmooth",
    type="number",
    defaultValue=3,
    label="RSI EMA Smooth",
    constraints={min: 1, max: 20, step: 1},
    group="Momentum Test"
)
var momWeight = input(
    name="momWeight",
    type="number",
    defaultValue=30,
    label="Momentum Test Weight (%)",
    constraints={min: 0, max: 100, step: 5},
    group="Momentum Test"
)

// --- Volatility Test (ATR) ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 2, max: 50, step: 1},
    group="Volatility Test"
)
var volWeight = input(
    name="volWeight",
    type="number",
    defaultValue=15,
    label="Volatility Test Weight (%)",
    constraints={min: 0, max: 100, step: 5},
    group="Volatility Test"
)

// --- Volume Test ---
var volSmaLen = input(
    name="volSmaLen",
    type="number",
    defaultValue=20,
    label="Volume SMA Length",
    constraints={min: 5, max: 100, step: 1},
    group="Volume Test"
)
var volTestWeight = input(
    name="volTestWeight",
    type="number",
    defaultValue=15,
    label="Volume Test Weight (%)",
    constraints={min: 0, max: 100, step: 5},
    group="Volume Test"
)

// --- Signal Thresholds ---
var bullThreshold = input(
    name="bullThreshold",
    type="number",
    defaultValue=60,
    label="Bullish Signal Threshold",
    constraints={min: 50, max: 90, step: 1},
    group="Signal Thresholds"
)
var bearThreshold = input(
    name="bearThreshold",
    type="number",
    defaultValue=40,
    label="Bearish Signal Threshold",
    constraints={min: 10, max: 50, step: 1},
    group="Signal Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=true,
    label="Dynamic Thresholds",
    group="Signal Thresholds"
)
var dynMult = input(
    name="dynMult",
    type="number",
    defaultValue=1.5,
    label="Dynamic Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Signal Thresholds"
)

// --- Display ---
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Score",
    group="Display"
)
var showTests = input(
    name="showTests",
    type="boolean",
    defaultValue=true,
    label="Show Individual Test Lines",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Signal Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Signal Shapes",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Zone Fill",
    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 neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#7c4dff",
    label="Signal Color",
    group="Colors"
)

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

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

var volAvailable = !isnan(bars.volume[0]) && bars.volume[0] > 0

// ----------------------------------------------------------------------------
// 3. TEST COMPUTATION
// ----------------------------------------------------------------------------

// -- 3.1 Trend Test (0-100) --
// Multi-MA alignment: price above all MAs = bullish; below all = bearish.
// Score is weighted by how many MAs agree and how far price is from them.
timeseries sma = sma(source=px, period=smaLen)
timeseries ema = ema(source=px, period=emaLen)
timeseries wma = wma(source=px, period=wmaLen)

var aboveSma = px > sma
var aboveEma = px > ema
var aboveWma = px > wma
var belowSma = px < sma
var belowEma = px < ema
var belowWma = px < wma

var bullCount = (aboveSma ? 1 : 0) + (aboveEma ? 1 : 0) + (aboveWma ? 1 : 0)
var bearCount = (belowSma ? 1 : 0) + (belowEma ? 1 : 0) + (belowWma ? 1 : 0)

// Score: 0-100 based on alignment strength
timeseries trendScore = 50 + ((bullCount - bearCount) * 16.67)
timeseries trendTest = math.min(100, math.max(0, trendScore))

// -- 3.2 Momentum Test (0-100) --
// Canonical RSI smoothed
timeseries change = px[0] - px[1]
timeseries gain = change > 0 ? change : 0
timeseries loss = change < 0 ? -change : 0
timeseries avgGain = rma(source=gain, period=rsiLen)
timeseries avgLoss = rma(source=loss, period=rsiLen)
timeseries rs = avgLoss > 0 ? avgGain / avgLoss : 0
timeseries rsiRaw = 100 - (100 / (1 + rs))
timeseries rsiVal = ema(source=rsiRaw, period=rsiSmooth)
// RSI is already 0-100; bias it slightly: above 50 = bullish momentum
timeseries momTest = rsiVal

// -- 3.3 Volatility Test (0-100) --
// Volatility confirmation: moderate ATR = stable = bullish; extreme = uncertain = bearish
timeseries prevClose = px[1]
timeseries tr = math.max(
    bars.high - bars.low,
    math.max(
        math.abs(bars.high - prevClose),
        math.abs(bars.low - prevClose)
    )
)
timeseries atr = rma(source=tr, period=atrLen)
timeseries atrMean = sma(source=atr, period=20)
timeseries atrStd = stdev(source=atr, period=20)
timeseries atrZ = (atrStd > 0) ? (atr - atrMean) / atrStd : 0
// Moderate ATR = 50; compressed = 75 (bullish stability); expanded = 25 (bearish uncertainty)
timeseries volRaw = 50 - (atrZ * 15)
timeseries volatilityTest = math.min(100, math.max(0, volRaw))

// -- 3.4 Volume Test (0-100) --
// Volume confirmation: above-average volume in trend direction = bullish
timeseries volSma = sma(source=bars.volume, period=volSmaLen)
timeseries volRatio = (volSma > 0) ? bars.volume / volSma : 1
timeseries volDir = (px[0] > px[1]) ? 1 : ((px[0] < px[1]) ? -1 : 0)
timeseries volRawScore = 50 + (volDir * (volRatio - 1) * 25)
timeseries volTestRaw = math.min(100, math.max(0, volRawScore))
timeseries volumeTest = volAvailable ? volTestRaw : 50

// ----------------------------------------------------------------------------
// 4. COMPOSITE SIGNAL SCORE
// ----------------------------------------------------------------------------
var totalWeight = trendWeight + momWeight + volWeight + volTestWeight
var normTrend = totalWeight > 0 ? trendWeight / totalWeight : 0.25
var normMom   = totalWeight > 0 ? momWeight / totalWeight : 0.25
var normVol   = totalWeight > 0 ? volWeight / totalWeight : 0.25
var normVolT  = totalWeight > 0 ? volTestWeight / totalWeight : 0.25

timeseries composite = (
    trendTest * normTrend +
    momTest * normMom +
    volatilityTest * normVol +
    volumeTest * normVolT
)

timeseries signal = ema(source=composite, period=3)

// ----------------------------------------------------------------------------
// 5. REGIME DETECTION
// ----------------------------------------------------------------------------
// Dynamic thresholds
timeseries sigVol = stdev(source=signal, period=20)
var dynBull = useDynamic ? math.min(85, bullThreshold + sigVol[0] * dynMult) : bullThreshold
var dynBear = useDynamic ? math.max(15, bearThreshold - sigVol[0] * dynMult) : bearThreshold

if (dynBull <= dynBear) {
    dynBull = 60
    dynBear = 40
}

var sigRising = signal[0] > signal[1]
var sigFalling = signal[0] < signal[1]
var regimeBull = signal > dynBull && sigRising
var regimeBear = signal < dynBear && sigFalling
var regimeNeutral = !regimeBull && !regimeBear

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

// ----------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// ----------------------------------------------------------------------------
var crossUp = signal > dynBull && signal[1] <= dynBull
var crossDown = signal < dynBear && signal[1] >= dynBear
var exitBull = signal < dynBull && signal[1] >= dynBull
var exitBear = signal > dynBear && signal[1] <= dynBear
var extremeOver = signal > 85
var extremeUnder = signal < 15

// Individual test crossovers
var trendBull = trendTest > 60 && trendTest[1] <= 60
var trendBear = trendTest < 40 && trendTest[1] >= 40
var momBull = momTest > 60 && momTest[1] <= 60
var momBear = momTest < 40 && momTest[1] >= 40

// ----------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// ----------------------------------------------------------------------------
static prevSignal = -1.0
static bullStreak = 0
static bearStreak = 0
static neutralStreak = 0
static passCount = 0
static failCount = 0
static maxSignal = -1.0
static minSignal = 101.0
static prevRegime = 0
static regimeChanges = 0

if (prevSignal < 0) {
    prevSignal = signal[0]
    maxSignal = signal[0]
    minSignal = signal[0]
}

if (!isLiveUpdate) {
    prevSignal = signal[0]
    if (signal[0] > maxSignal) { maxSignal = signal[0] }
    if (signal[0] < minSignal) { minSignal = signal[0] }

    if (regimeBull) {
        bullStreak = bullStreak + 1
        bearStreak = 0
        neutralStreak = 0
        passCount = passCount + 1
    } else if (regimeBear) {
        bearStreak = bearStreak + 1
        bullStreak = 0
        neutralStreak = 0
        failCount = failCount + 1
    } else {
        neutralStreak = neutralStreak + 1
        bullStreak = 0
        bearStreak = 0
    }

    var currentRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
    if (currentRegime != prevRegime) {
        regimeChanges = regimeChanges + 1
    }
    prevRegime = currentRegime
}

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

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

// --- Dynamic Thresholds ---
if (showFill) {
    hline(value=dynBull, color=transparency(bullColor, 60), width=1)
    hline(value=dynBear, color=transparency(bearColor, 60), width=1)
}

// --- Zone Fill (signal vs 50) ---
if (showFill) {
    var aboveMid = signal > 50
    plotLine(
        value=[signal, 50],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=aboveMid ? 0 : 1,
        fill=true,
        label=["Signal", "Neutral"],
        desc=["Fill between signal score and neutral midline"]
    )
}

// --- Individual Test Lines ---
if (showTests) {
    plotLine(
        value=trendTest,
        width=1,
        colors=["#42a5f5"],
        label=["Trend Test"],
        desc=["Trend test score: multi-MA alignment (0-100)"]
    )
    plotLine(
        value=momTest,
        width=1,
        colors=["#ab47bc"],
        label=["Momentum Test"],
        desc=["Momentum test score: smoothed RSI (0-100)"]
    )
    plotLine(
        value=volatilityTest,
        width=1,
        colors=["#ffa726"],
        label=["Volatility Test"],
        desc=["Volatility test score: ATR stability (0-100)"]
    )
    if (volAvailable) {
        plotLine(
            value=volumeTest,
            width=1,
            colors=["#8d6e63"],
            label=["Volume Test"],
            desc=["Volume test score: relative volume confirmation (0-100)"]
        )
    }
}

// --- Composite Signal (regime-colored) ---
if (showSignal) {
    plotLine(
        value=signal,
        width=3,
        colors=[regimeColor],
        label=["Signal Score"],
        desc=["Composite signal score: trend + momentum + volatility + volume"]
    )
}

// --- Signal Histogram ---
if (showHistogram) {
    timeseries hist = signal - 50
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Signal Momentum"],
        desc=["Histogram of signal score minus neutral midline"]
    )
}

// --- Signal Shapes ---
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Bull Signal"],
            desc=["Signal crossed above dynamic bullish threshold"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Bear Signal"],
            desc=["Signal crossed below dynamic bearish threshold"]
        )
    }
    if (trendBull) {
        plotShape(
            value=trendTest,
            shape="arrowup",
            colorIndex=bullColor,
            width=1,
            label=["Trend Pass"],
            desc=["Trend test passed: price above all moving averages"]
        )
    }
    if (trendBear) {
        plotShape(
            value=trendTest,
            shape="arrowdown",
            colorIndex=bearColor,
            width=1,
            label=["Trend Fail"],
            desc=["Trend test failed: price below all moving averages"]
        )
    }
    if (momBull) {
        plotShape(
            value=momTest,
            shape="circle",
            colorIndex=bullColor,
            width=1,
            label=["Mom Pass"],
            desc=["Momentum test passed: RSI entered bullish zone"]
        )
    }
    if (momBear) {
        plotShape(
            value=momTest,
            shape="circle",
            colorIndex=bearColor,
            width=1,
            label=["Mom Fail"],
            desc=["Momentum test failed: RSI entered bearish zone"]
        )
    }
    if (regimeBull && bullStreak == 3) {
        plotShape(
            value=signal,
            shape="xcross",
            colorIndex=bullColor,
            width=2,
            label=["Bull Confirmed"],
            desc=["Bullish regime confirmed after 3 consecutive bars"]
        )
    }
    if (regimeBear && bearStreak == 3) {
        plotShape(
            value=signal,
            shape="xcross",
            colorIndex=bearColor,
            width=2,
            label=["Bear Confirmed"],
            desc=["Bearish regime confirmed after 3 consecutive bars"]
        )
    }
}

// ----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// ----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var totalTests = passCount + failCount
    var passRate = (totalTests > 0) ? (passCount / totalTests) * 100 : 0

    plotTable(
        data=[
            ["Test Signal Analyzer", regimeText],
            ["Signal Score", signal[0]],
            ["Trend Test", trendTest[0]],
            ["Momentum Test", momTest[0]],
            ["Volatility Test", volatilityTest[0]],
            ["Volume Test", volumeTest[0]],
            ["Bull Streak", bullStreak],
            ["Bear Streak", bearStreak],
            ["Max Signal", maxSignal],
            ["Min Signal", minSignal],
            ["Pass Rate", passRate + "%"],
            ["Regime Changes", regimeChanges]
        ],
        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
    )
}