MM Flow
FlowScripts

Perfected FlowScript

Normalized T3

Normalized T3 V2 — Momentum Oscillator is indexed as 176_normalized_t3.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

13.8 KB

Lines

347

Native Signal Candidates

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

4/4 guarded

Cross Up

line 277:9

Trigger

(showShapes) && (crossUp)

Value

signal

Deps

crossUp:var, showShapes:input

Cross Down

line 287:9

Trigger

(showShapes) && (crossDown)

Value

signal

Deps

crossDown:var, showShapes:input

OB Penetrate

line 297:9

Trigger

(showShapes) && (obPenetrate)

Value

dynOb

Deps

obPenetrate:var, showShapes:input

OS Penetrate

line 307:9

Trigger

(showShapes) && (osPenetrate)

Value

dynOs

Deps

osPenetrate:var, showShapes:input

176_normalized_t3.flowscript

source path: kscripts/perfected/176_normalized_t3.flowscript · sha256:5c82c38c6f1d266403a6be9b7f265e53a0116dd69bec7bc5dc873043cf98e668

hash verified
//@version=2

// ============================================================================
// Normalized T3 V2 — Tillson T3 Momentum Oscillator with Regime Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #t3, #momentum, #oscillator, #zscore, #regime, #overbought, #oversold
//
// This indicator computes Tim Tillson's T3 Moving Average via six chained EMAs
// with canonical polynomial coefficients, then normalises the T3 deviation from
// price into a 0-100 oscillator (inspired by Bollinger %B) or a z-score scale.
// Overbought/oversold zones are user-configurable and optionally dynamic.
// A signal SMA provides crossover entries, fill areas visualise momentum, and
// shape markers flag extreme penetrations. Static state tracks consecutive bars
// in each regime for context-aware alerting.
//
// Academic foundation (exact papers & formulas):
//  1. Tillson (1998), "T3 Moving Average". T3 = c1×e6 + c2×e5 + c3×e4 + c4×e3
//     where c1–c4 are polynomial functions of volume factor "a" (default 0.7).
//     Six nested EMAs with deliberate lag reduction and smoothness preservation.
//
//  2. Bollinger (2001), "Bollinger on Bollinger Bands". %B normalisation:
//     %B = (Close − Lower Band) / (Upper Band − Lower Band) × 100.
//     Motivates the 0-100 oscillator scale for cross-asset comparability.
//
//  3. Mulloy (1994), "Smoothing Data With Faster Moving Averages". DEMA and
//     TEMA as lag-reduction techniques via nested EMAs; T3 extends to six layers.
//
//  4. Wilder (1978), "New Concepts in Technical Trading Systems". RSI's
//     bounded 0-100 oscillator design paradigm; overbought/oversold thresholds
//     at 70/30 as reversal-expectation zones.
//
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices". Negative
//     autocorrelation at medium horizons supports dynamic volatility-adjusted
//     thresholds calibrated to rolling standard deviation.
//
//  6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
//     z-score normalisation: z_t = (x_t − μ) / σ; robust deviation detection
//     with MAD-based outlier resistance.
// ============================================================================

define(title="Normalized T3 V2 — Momentum Oscillator", position="offchart", axis=true)

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

// -- T3 Settings --
var len = input(name="len", type="number", defaultValue=20, label="T3 Length", constraints={min: 2, max: 100, step: 1}, group="T3 Settings")
var aFactor = input(name="aFactor", type="number", defaultValue=0.7, label="Volume Factor (a)", constraints={min: 0.0, max: 1.0, step: 0.05}, group="T3 Settings")

// -- Normalization --
var normMode = input(name="normMode", type="select", defaultValue="0-100 Scale", label="Normalization Mode", options=["0-100 Scale", "Z-Score"], group="Normalization")
var normLen = input(name="normLen", type="number", defaultValue=50, label="Normalization Window", constraints={min: 10, max: 200, step: 5}, group="Normalization")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Output Smoothing", constraints={min: 1, max: 20, step: 1}, group="Normalization")

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

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

// -- Display --
var showT3 = input(name="showT3", type="boolean", defaultValue=true, label="Show T3 Oscillator", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal Line", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Fill Area", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Momentum Bars", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show OB/OS Zones", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bearish 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="#ffffff", label="Signal Color", group="Colors")
var obColor = input(name="obColor", type="color", defaultValue="#ff5252", label="Overbought Zone Color", group="Colors")
var osColor = input(name="osColor", type="color", defaultValue="#00e676", label="Oversold Zone Color", group="Colors")

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

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

// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(close[0])) {
    return
}

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

// -- 3.1 T3 Moving Average — six chained EMAs with Tillson coefficients --
// Tillson (1998): T3 = c1×e6 + c2×e5 + c3×e4 + c4×e3
// e1 = EMA(close, len); e2 = EMA(e1, len); ... e6 = EMA(e5, len)
// c1 = -a³; c2 = 3a² + 3a³; c3 = -3 - 6a² - 3a³; c4 = 1 + 3a + 3a² + a³

timeseries e1 = ema(close, len)
timeseries e2 = ema(e1, len)
timeseries e3 = ema(e2, len)
timeseries e4 = ema(e3, len)
timeseries e5 = ema(e4, len)
timeseries e6 = ema(e5, len)

// Polynomial coefficients
var a2 = aFactor * aFactor
var a3 = a2 * aFactor
var c1 = -a3
var c2 = 3.0 * a2 + 3.0 * a3
var c3 = -3.0 - 6.0 * a2 - 3.0 * a3
var c4 = 1.0 + 3.0 * aFactor + 3.0 * a2 + a3

timeseries t3 = c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3

// -- 3.2 Normalization --
// Mode A: 0-100 Scale (Bollinger %B inspired)
//   %B = (Close - Lower Band) / (Upper Band - Lower Band) × 100
// Mode B: Z-Score (Zhao & Palomar 2018)

timeseries t3Dev = close - t3
timeseries t3DevMean = sma(t3Dev, normLen)
timeseries t3DevStd = stdev(t3Dev, normLen)
timeseries t3DevMin = lowest(t3Dev, normLen)
timeseries t3DevMax = highest(t3Dev, normLen)
timeseries t3Range = math.max(t3DevMax - t3DevMin, 0.0001)

// 0-100 scale: (%B-style) position of deviation within recent range
timeseries t3PctB = (t3Dev - t3DevMin) / t3Range * 100
// Z-score: standard deviation from mean
timeseries t3Z = (t3DevStd > 0) ? (t3Dev - t3DevMean) / t3DevStd : 0

// Select mode and smooth
timeseries t3Raw = (normMode == "0-100 Scale") ? t3PctB : (t3Z * 25 + 50)
timeseries t3Norm = ema(t3Raw, smoothLen)
// Clip to valid 0-100 range for safety
timeseries t3Final = math.max(math.min(t3Norm, 100), 0)

// -- 3.3 Signal SMA --
timeseries signal = sma(t3Final, signalLen)

// -- 3.4 Momentum histogram (oscillator minus signal) --
timeseries hist = t3Final - signal

// -- 3.5 Dynamic thresholds (Poterba & Summers 1988) --
// Adjust OB/OS bands by rolling oscillator standard deviation
var t3Vol = stddev(t3Final, volLookback)
var dynOb = useDynamic ? math.min(95, obLevel + t3Vol * volMultiplier / 10) : obLevel
var dynOs = useDynamic ? math.max(5, osLevel - t3Vol * volMultiplier / 10) : osLevel

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

// -- 3.6 Regime detection --
// Bullish: oscillator > signal AND oscillator > 50
// Bearish: oscillator < signal AND oscillator < 50
// Overbought: oscillator > dynOb; Oversold: oscillator < dynOs
var regimeBull = t3Final > signal && t3Final > 50
var regimeBear = t3Final < signal && t3Final < 50
var regimeNeutral = !regimeBull && !regimeBear
var obRegime = t3Final > dynOb
var osRegime = t3Final < dynOs

// -- 3.7 Alert conditions (crossovers, OB/OS penetrations) --
var crossUp = t3Final > signal && t3Final[1] <= signal[1]
var crossDown = t3Final < signal && t3Final[1] >= signal[1]
var obPenetrate = t3Final > dynOb && t3Final[1] <= dynOb[1]
var osPenetrate = t3Final < dynOs && t3Final[1] >= dynOs[1]
var obExit = t3Final < dynOb && t3Final[1] >= dynOb[1]
var osExit = t3Final > dynOs && t3Final[1] <= dynOs[1]

// -- 3.8 Static state tracking for consecutive regime bars --
static lastRegime = 0
static bullBars = 0
static bearBars = 0
static obBars = 0
static osBars = 0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
    lastRegime = 1
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
    lastRegime = -1
} else {
    bullBars = 0
    bearBars = 0
    lastRegime = 0
}

if (obRegime) {
    obBars = obBars + 1
} else {
    obBars = 0
}
if (osRegime) {
    osBars = osBars + 1
} else {
    osBars = 0
}

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

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

// 4.2 OB / OS Zones (hline)
if (showZones) {
    hline(value=dynOb, color=transparency(obColor, 60), width=1)
    hline(value=dynOs, color=transparency(osColor, 60), width=1)
}

// 4.3 T3 Oscillator (plotLine) — regime colour coding
if (showT3) {
    var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    plotLine(
        value=t3Final,
        width=2,
        colors=[regimeColor],
        label=["T3 Oscillator"],
        desc=["Normalized T3 momentum oscillator (" + normMode + "; " + smoothLen + "-bar smooth)"]
    )
}

// 4.4 Signal SMA (plotLine)
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal SMA"],
        desc=["SMA of T3 oscillator (" + signalLen + " bars)"]
    )
}

// 4.5 Fill area between oscillator and signal
if (showFill && showT3 && showSignal) {
    var fillBull = t3Final > signal
    plotLine(
        value=[t3Final, signal],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["T3 Oscillator", "Signal SMA"],
        desc=["Fill between T3 oscillator and signal SMA"]
    )
}

// 4.6 Momentum histogram (plotBar)
if (showBars) {
    var histBull = hist >= 0
    plotBar(
        value=hist,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Momentum"],
        desc=["Histogram of T3 oscillator minus signal SMA"]
    )
}

// 4.7 Extreme shapes (plotShape) — OB/OS penetrations and crossovers
if (showShapes) {
    if (crossUp) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Up"],
            desc=["T3 oscillator crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=signal,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Down"],
            desc=["T3 oscillator crossed below signal SMA"]
        )
    }
    if (obPenetrate) {
        plotShape(
            value=dynOb,
            shape="xcross",
            colorIndex=obColor,
            width=2,
            label=["OB Penetrate"],
            desc=["T3 oscillator entered overbought zone ( > " + dynOb + ")"]
        )
    }
    if (osPenetrate) {
        plotShape(
            value=dynOs,
            shape="xcross",
            colorIndex=osColor,
            width=2,
            label=["OS Penetrate"],
            desc=["T3 oscillator entered oversold zone ( < " + dynOs + ")"]
        )
    }
}

// 4.8 Regime table (last bar only)
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var obText = useDynamic ? "Dynamic OB: " + dynOb : "Static OB: " + obLevel
    var osText = useDynamic ? "Dynamic OS: " + dynOs : "Static OS: " + osLevel
    plotTable(
        data=[
            ["Normalized T3 V2", regimeText],
            ["T3 Oscillator", t3Final[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            [obText, osText],
            ["Bull Bars", bullBars],
            ["Bear Bars", 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
    )
}