MM Flow
FlowScripts

Perfected FlowScript

tryewutweryuoewioryweoir

tryewutweryuoewioryweoir — Regime Scorer is indexed as 331_tryewutweryuoewioryweoir.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.5 KB

Lines

521

Native Signal Candidates

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

6/6 guarded

Uptrend

line 416:9

Trigger

(showShapes) && (enterTrend && compUp)

Value

compositeSm

Deps

compUp:var, enterTrend:var, showShapes:input

Downtrend

line 426:9

Trigger

(showShapes) && (enterTrend && !compUp)

Value

compositeSm

Deps

compUp:var, enterTrend:var, showShapes:input

Breakout

line 436:9

Trigger

(showShapes) && (enterBreak)

Value

compositeSm

Deps

enterBreak:var, showShapes:input

Bull Exhaust

line 446:9

Trigger

(showShapes) && (enterExhaust && compUp)

Value

compositeSm

Deps

compUp:var, enterExhaust:var, showShapes:input

Bear Exhaust

line 456:9

Trigger

(showShapes) && (enterExhaust && !compUp)

Value

compositeSm

Deps

compUp:var, enterExhaust:var, showShapes:input

Range

line 466:9

Trigger

(showShapes) && (enterRange && lastRegime != 0)

Value

compositeSm

Deps

enterRange:var, lastRegime:static, showShapes:input

331_tryewutweryuoewioryweoir.flowscript

source path: kscripts/perfected/331_tryewutweryuoewioryweoir.flowscript · sha256:57318f3bd5097b7cb7a4507fc59da48d7af8e949794d51b76b7a536beecfc53e

hash verified
//@version=2
// ============================================================================
// tryewutweryuoewioryweoir — Multi-Factor Market Regime Scorer
// Author: Tzen Yang | Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #regime, #momentum, #volume, #multifactor, #scoring
//
// Transforms the experimental original into a rigorous multi-factor market
// regime scoring engine. Fuses price momentum, volume participation,
// volatility regime, and mean-reversion deviation into a composite "Tryew"
// score. Each factor is normalized and weighted; the composite score is then
// regime-classified into Trending, Ranging, Breaking, or Exhaustion states.
// Color coding, shape markers, and fill areas make regime shifts instantly
// visible. Static variables track consecutive regime duration for context-aware
// alerting.
//
// Academic foundation:
//  1. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers": momentum as a premier cross-sectional anomaly. Underpins the
//     price-momentum factor scoring.
//  2. Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//     autocorrelation at medium horizons; supports the mean-reversion deviation
//     factor and regime-transition detection.
//  3. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand": liquidity memory explains why volume participation
//     must be measured relative to recent history, not in absolute terms.
//     DOI: https://doi.org/10.1016/j.jfin.2008.10.003
//  4. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
//     Markets": KAMA Efficiency Ratio directly inspires the volatility-regime
//     factor — ER = Change / Volatility, distinguishing trending from ranging.
//  5. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
//     order flow imbalance drives price changes. The volume participation factor
//     measures this imbalance via normalized volume deviation.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//  6. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns": extreme imbalances predict return reversals. Informs the
//     Exhaustion regime threshold logic.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
// ============================================================================

define(
    title="tryewutweryuoewioryweoir — Regime Scorer",
    position="offchart",
    axis=true
)

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

// --- Factor Windows ---
var momLen = input(
    name="momLen",
    type="number",
    defaultValue=14,
    label="Momentum Lookback",
    constraints={min: 5, max: 50, step: 1},
    group="Factor Windows"
)
var volLen = input(
    name="volLen",
    type="number",
    defaultValue=20,
    label="Volume Reference Window",
    constraints={min: 10, max: 100, step: 5},
    group="Factor Windows"
)
var regimeLen = input(
    name="regimeLen",
    type="number",
    defaultValue=10,
    label="Volatility Regime Window",
    constraints={min: 5, max: 50, step: 1},
    group="Factor Windows"
)
var devLen = input(
    name="devLen",
    type="number",
    defaultValue=20,
    label="Deviation / Z-Score Window",
    constraints={min: 10, max: 100, step: 5},
    group="Factor Windows"
)

// --- Weights ---
var wMom = input(
    name="wMom",
    type="number",
    defaultValue=0.35,
    label="Momentum Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)
var wVol = input(
    name="wVol",
    type="number",
    defaultValue=0.25,
    label="Volume Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)
var wRegime = input(
    name="wRegime",
    type="number",
    defaultValue=0.25,
    label="Volatility Regime Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)
var wDev = input(
    name="wDev",
    type="number",
    defaultValue=0.15,
    label="Deviation Weight",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Weights"
)

// --- Thresholds ---
var trendThresh = input(
    name="trendThresh",
    type="number",
    defaultValue=0.30,
    label="Trending Regime Threshold",
    constraints={min: 0.1, max: 0.8, step: 0.05},
    group="Thresholds"
)
var exhaustThresh = input(
    name="exhaustThresh",
    type="number",
    defaultValue=0.70,
    label="Exhaustion Regime Threshold",
    constraints={min: 0.5, max: 1.0, step: 0.05},
    group="Thresholds"
)
var breakMult = input(
    name="breakMult",
    type="number",
    defaultValue=2.0,
    label="Breakout Z-Score Multiplier",
    constraints={min: 1.0, max: 4.0, step: 0.5},
    group="Thresholds"
)

// --- Display ---
var showFactors = input(
    name="showFactors",
    type="boolean",
    defaultValue=false,
    label="Show Individual Factor Lines",
    group="Display"
)
var showComposite = input(
    name="showComposite",
    type="boolean",
    defaultValue=true,
    label="Show Composite Score",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Transition Shapes",
    group="Display"
)
var showBars = input(
    name="showBars",
    type="boolean",
    defaultValue=true,
    label="Show Composite Bars",
    group="Display"
)

// --- Colors ---
var trendColor = input(
    name="trendColor",
    type="color",
    defaultValue="#00e676",
    label="Trending Color",
    group="Colors"
)
var rangeColor = input(
    name="rangeColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Ranging Color",
    group="Colors"
)
var breakColor = input(
    name="breakColor",
    type="color",
    defaultValue="#ff9100",
    label="Breaking Color",
    group="Colors"
)
var exhaustColor = input(
    name="exhaustColor",
    type="color",
    defaultValue="#d500f9",
    label="Exhaustion Color",
    group="Colors"
)
var compositeLineColor = input(
    name="compositeLineColor",
    type="color",
    defaultValue="#ffffff",
    label="Composite Line Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// -----------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries vol = bars.volume

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

// -----------------------------------------------------------------------------
// 3. FACTOR COMPUTATION
// -----------------------------------------------------------------------------

// -- 3.1 Momentum Factor (normalized RSI-style 0-1 score) --
// Raw momentum = price change over lookback, normalized by historical volatility
timeseries momRaw = px[0] - px[momLen]
timeseries momVol = stddev(source=px, period=momLen)
timeseries momZ = momVol > 0 ? momRaw / (momVol * math.sqrt(momLen)) : 0
timeseries momScore = math.min(1.0, math.max(-1.0, momZ / 3.0))

// -- 3.2 Volume Participation Factor --
// Relative volume z-score: how unusual is today's volume vs recent history?
timeseries volMean = sma(vol, volLen)
timeseries volStd = stddev(vol, volLen)
timeseries volZ = (volStd > 0) ? (vol - volMean) / volStd : 0
timeseries volScore = math.min(1.0, math.max(-1.0, volZ / 3.0))

// -- 3.3 Volatility Regime Factor (Kaufman Efficiency Ratio inspired) --
// ER = |Net Change| / Sum of absolute changes. High = trending, Low = ranging.
timeseries netChange = math.abs(px[0] - px[regimeLen])
timeseries totalChange = sum(source=math.abs(px - px[1]), period=regimeLen)
timeseries erRaw = totalChange > 0 ? netChange / totalChange : 0
timeseries erScore = erRaw * 2.0 - 1.0  // remap 0..1 to -1..1

// -- 3.4 Mean-Reversion Deviation Factor --
// Z-score of price vs SMA: how extended is price from its mean?
timeseries devMa = sma(px, devLen)
timeseries devSd = stddev(px, devLen)
timeseries devZ = (devSd > 0) ? (px - devMa) / devSd : 0
timeseries devScore = math.min(1.0, math.max(-1.0, devZ / 3.0))

// -- 3.5 Composite Tryew Score (weighted sum, normalized to -1..+1) --
// Normalize weights so they sum to 1.0
timeseries weightSum = wMom + wVol + wRegime + wDev
timeseries nm = weightSum > 0 ? wMom / weightSum : 0.25
timeseries nv = weightSum > 0 ? wVol / weightSum : 0.25
timeseries nr = weightSum > 0 ? wRegime / weightSum : 0.25
timeseries nd = weightSum > 0 ? wDev / weightSum : 0.25

timeseries composite = nm * momScore + nv * volScore + nr * erScore + nd * devScore

// Smooth the composite for cleaner regime reading
timeseries compositeSm = ema(composite, 3)

// -- 3.6 Regime Classification --
// Four regimes: Trending, Ranging, Breaking, Exhaustion
// Trending: |composite| > trendThresh, aligned with momentum
// Breaking: |devZ| > breakMult (price statistically extended)
// Exhaustion: |composite| > exhaustThresh (extreme composite = fatigue)
// Ranging: everything else

var absComp = math.abs(compositeSm)
var isTrending = absComp > trendThresh && absComp < exhaustThresh
var isBreaking = math.abs(devZ) > breakMult
var isExhaustion = absComp >= exhaustThresh
var isRanging = !isTrending && !isBreaking && !isExhaustion

// Directional coloring within each regime
var compUp = compositeSm > 0

// -- 3.7 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static trendBars = 0
static rangeBars = 0
static breakBars = 0
static exhaustBars = 0

if (isTrending) {
    trendBars = trendBars + 1
    rangeBars = 0
    breakBars = 0
    exhaustBars = 0
    lastRegime = 1
} else if (isBreaking) {
    breakBars = breakBars + 1
    trendBars = 0
    rangeBars = 0
    exhaustBars = 0
    lastRegime = 2
} else if (isExhaustion) {
    exhaustBars = exhaustBars + 1
    trendBars = 0
    rangeBars = 0
    breakBars = 0
    lastRegime = 3
} else {
    rangeBars = rangeBars + 1
    trendBars = 0
    breakBars = 0
    exhaustBars = 0
    lastRegime = 0
}

// -- 3.8 Zero-line helper for fill areas --
timeseries zeroLine = 0

// -----------------------------------------------------------------------------
// 4. VISUALIZATION
// -----------------------------------------------------------------------------

// 4.1 Composite Score (plotLine)
if (showComposite) {
    plotLine(
        value=compositeSm,
        width=2,
        colors=[compositeLineColor],
        label=["Tryew Score"],
        desc=["Multi-factor composite score: momentum + volume + regime + deviation"]
    )
}

// 4.2 Individual factor lines (optional)
if (showFactors) {
    plotLine(
        value=momScore,
        width=1,
        colors=["#4fc3f7"],
        label=["Momentum"],
        desc=["Normalized momentum factor (Jegadeesh-Titman)"]
    )
    plotLine(
        value=volScore,
        width=1,
        colors=["#81c784"],
        label=["Volume"],
        desc=["Normalized volume participation factor (Cont et al.)"]
    )
    plotLine(
        value=erScore,
        width=1,
        colors=["#ffb74d"],
        label=["Regime"],
        desc=["Kaufman Efficiency Ratio factor (-1 = ranging, +1 = trending)"]
    )
    plotLine(
        value=devScore,
        width=1,
        colors=["#e57373"],
        label=["Deviation"],
        desc=["Mean-reversion z-score factor (Poterba-Summers)"]
    )
}

// 4.3 Composite fill with regime color coding
// colorIndex maps: 0 = trending, 1 = ranging, 2 = breaking, 3 = exhaustion
var regimeColorIdx = isTrending ? 0 : (isRanging ? 1 : (isBreaking ? 2 : 3))
var regimeFillColor = isTrending ? trendColor : (isRanging ? rangeColor : (isBreaking ? breakColor : exhaustColor))

if (showFill) {
    plotLine(
        value=[compositeSm, zeroLine],
        width=2,
        colors=[transparency(regimeFillColor, 40), transparency(regimeFillColor, 40)],
        colorIndex=0,
        fill=true,
        label=["Tryew Fill"],
        desc=["Regime-colored fill between composite score and zero"]
    )
}

// 4.4 Composite bars (plotBar) — sign-based with regime overlay
if (showBars) {
    var barColor = compUp ?
        (isExhaustion ? exhaustColor : (isBreaking ? breakColor : (isTrending ? trendColor : rangeColor))) :
        (isExhaustion ? exhaustColor : (isBreaking ? breakColor : (isTrending ? trendColor : rangeColor)))
    plotBar(
        value=compositeSm,
        colors=[barColor, barColor],
        colorIndex=compUp ? 0 : 1,
        width=1,
        label=["Tryew Bars"],
        desc=["Composite score bars colored by regime"]
    )
}

// 4.5 Regime transition shapes (plotShape)
// Shape on regime entry (first bar of new regime after at least 3 bars in prior)
if (showShapes) {
    var enterTrend = isTrending && trendBars == 1 && lastRegime != 1
    var enterBreak = isBreaking && breakBars == 1 && lastRegime != 2
    var enterExhaust = isExhaustion && exhaustBars == 1 && lastRegime != 3
    var enterRange = isRanging && rangeBars == 1 && lastRegime != 0

    if (enterTrend && compUp) {
        plotShape(
            value=compositeSm,
            shape="triangleup",
            colorIndex=trendColor,
            width=2,
            label=["Uptrend"],
            desc=["Tryew Score entered bullish trending regime (momentum aligned)"]
        )
    }
    if (enterTrend && !compUp) {
        plotShape(
            value=compositeSm,
            shape="triangledown",
            colorIndex=trendColor,
            width=2,
            label=["Downtrend"],
            desc=["Tryew Score entered bearish trending regime (momentum aligned)"]
        )
    }
    if (enterBreak) {
        plotShape(
            value=compositeSm,
            shape="diamond",
            colorIndex=breakColor,
            width=2,
            label=["Breakout"],
            desc=["Price statistically extended (|z| > " + breakMult + ") — potential breakout"]
        )
    }
    if (enterExhaust && compUp) {
        plotShape(
            value=compositeSm,
            shape="xcross",
            colorIndex=exhaustColor,
            width=2,
            label=["Bull Exhaust"],
            desc=["Tryew Score reached exhaustion threshold — bullish fatigue possible"]
        )
    }
    if (enterExhaust && !compUp) {
        plotShape(
            value=compositeSm,
            shape="xcross",
            colorIndex=exhaustColor,
            width=2,
            label=["Bear Exhaust"],
            desc=["Tryew Score reached exhaustion threshold — bearish fatigue possible"]
        )
    }
    if (enterRange && lastRegime != 0) {
        plotShape(
            value=compositeSm,
            shape="circle",
            colorIndex=rangeColor,
            width=1,
            label=["Range"],
            desc=["Tryew Score returned to ranging regime — no clear directional bias"]
        )
    }
}

// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=trendThresh, color="#ffffff20", width=1)
hline(value=-trendThresh, color="#ffffff20", width=1)
hline(value=exhaustThresh, color="#ffffff15", width=1)
hline(value=-exhaustThresh, color="#ffffff15", width=1)

// -----------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = isTrending ? (compUp ? "TRENDING ↑" : "TRENDING ↓") :
                     (isBreaking ? "BREAKING" :
                     (isExhaustion ? "EXHAUSTION" : "RANGING"))
    var regimeTextColor = isTrending ? trendColor :
                          (isBreaking ? breakColor :
                          (isExhaustion ? exhaustColor : rangeColor))

    plotTable(
        data=[
            ["Tryew Regime Scorer", regimeText],
            ["Composite", compositeSm[0]],
            ["Momentum", momScore[0]],
            ["Volume", volScore[0]],
            ["Efficiency", erScore[0]],
            ["Deviation", devScore[0]],
            ["Trend Bars", trendBars],
            ["Range Bars", rangeBars],
            ["Break Bars", breakBars],
            ["Exhaust Bars", exhaustBars]
        ],
        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
    )
}