MM Flow
FlowScripts

Perfected FlowScript

T3 Moving Average

T3 Moving Average — Perfected Edition is indexed as 130_t3_moving_average.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

13.0 KB

Lines

418

Native Signal Candidates

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

6/6 guarded

Fast>Med

line 328:9

Trigger

(showCrossShapes) && (fastCrossMedUp)

Value

t3_fast

Deps

fastCrossMedUp:var, showCrossShapes:input

Fast<Med

line 338:9

Trigger

(showCrossShapes) && (fastCrossMedDn)

Value

t3_fast

Deps

fastCrossMedDn:var, showCrossShapes:input

Med>Slow

line 348:9

Trigger

(showCrossShapes) && (medCrossSlowUp)

Value

t3_med

Deps

medCrossSlowUp:var, showCrossShapes:input

Med<Slow

line 358:9

Trigger

(showCrossShapes) && (medCrossSlowDn)

Value

t3_med

Deps

medCrossSlowDn:var, showCrossShapes:input

Price>T3 Fast

line 368:9

Trigger

(showCrossShapes) && (priceCrossFastUp)

Value

c

Deps

priceCrossFastUp:var, showCrossShapes:input

Price<T3 Fast

line 378:9

Trigger

(showCrossShapes) && (priceCrossFastDn)

Value

c

Deps

priceCrossFastDn:var, showCrossShapes:input

130_t3_moving_average.flowscript

source path: kscripts/perfected/130_t3_moving_average.flowscript · sha256:99712454b1c06df7356782ab9924294e94a4f5aadb7071773f1487825e86cec1

hash verified
//@version=2
// ============================================================================
// T3 Moving Average — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #t3, #tillson, #movingaverage, #trend, #ribbon, #regime
//
// Production-grade T3 Moving Average implementation with Tim Tillson's
// canonical six-layer nested EMA smoothing, multiple T3 lines (fast/medium/slow),
// ribbon fill visualization, color-coded regime detection, crossover shape
// markers, and comprehensive state tracking.
//
// Research papers underpinning this design:
//  1. Tillson (1998), "T3 Moving Average": original six-layer nested EMA
//     recombination using volume factor "a" (default 0.7). Formula:
//     T3 = c1·e6 + c2·e5 + c3·e4 + c4·e3 where c1–c4 are polynomial functions
//     of the volume factor. Designed to reduce lag while maintaining smoothness.
//  2. Mulloy (1994), "Smoothing Data With Faster Moving Averages": introduced
//     DEMA and TEMA as lag-reduction techniques via nested EMAs. T3 extends
//     this philosophy to six layers for superior smoothness.
//  3. Manasa & Reddy (2025), "Trend Analysis by Weighted and EMA": comparative
//     study showing EMA offers more stability than WMA but lags on reversals.
//     Multi-layer nested EMAs (T3) solve this trade-off by deeper smoothing.
//  4. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing": time-series momentum profitable since 1880. T3 as a fast
//     trend filter aligns with the century of trend-following evidence.
//  5. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
//     optimal trend-following under plausible assumptions resembles simple MA
//     crossover rules. T3 crossovers are theoretically justified signals.
// ============================================================================

define(
    title="T3 Moving Average — Perfected Edition",
    position="onchart",
    axis=false
)

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

// --- T3 Lengths ---
var fastLen = input(
    name="fastLen",
    type="number",
    defaultValue=10,
    label="Fast T3 Length",
    constraints={min: 2, max: 100, step: 1},
    group="T3 Lengths"
)
var medLen = input(
    name="medLen",
    type="number",
    defaultValue=20,
    label="Medium T3 Length",
    constraints={min: 2, max: 100, step: 1},
    group="T3 Lengths"
)
var slowLen = input(
    name="slowLen",
    type="number",
    defaultValue=40,
    label="Slow T3 Length",
    constraints={min: 2, max: 200, step: 1},
    group="T3 Lengths"
)

// --- Volume Factor ---
var volumeFactor = input(
    name="volumeFactor",
    type="number",
    defaultValue=0.7,
    label="Volume Factor (a)",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="T3 Settings"
)

// --- Display ---
var showFast = input(
    name="showFast",
    type="boolean",
    defaultValue=true,
    label="Show Fast T3",
    group="Display"
)
var showMed = input(
    name="showMed",
    type="boolean",
    defaultValue=true,
    label="Show Medium T3",
    group="Display"
)
var showSlow = input(
    name="showSlow",
    type="boolean",
    defaultValue=true,
    label="Show Slow T3",
    group="Display"
)
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show T3 Ribbon Fill",
    group="Display"
)
var showCrossShapes = input(
    name="showCrossShapes",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Shapes",
    group="Display"
)
var showUnderlying = input(
    name="showUnderlying",
    type="boolean",
    defaultValue=false,
    label="Show Underlying EMAs (debug)",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Display"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color",
    group="Display"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Display"
)

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

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

// -----------------------------------------------------------------------------
// 3. T3 HELPER FUNCTION
// -----------------------------------------------------------------------------
// Computes T3 for a given length and volume factor using six nested EMAs.
// Tillson coefficients: c1 = -a^3, c2 = 3a^2 + 3a^3, c3 = -6a^2 - 3a - 3a^3,
// c4 = 1 + 3a + a^3 + 3a^2
//
// We compute inline for each length to avoid function-call overhead in kScript.

timeseries a = volumeFactor
timeseries a2 = a * a
timeseries a3 = a2 * a

timeseries c1 = -a3
timeseries c2 = 3.0 * a2 + 3.0 * a3
timeseries c3 = -6.0 * a2 - 3.0 * a - 3.0 * a3
timeseries c4 = 1.0 + 3.0 * a + a3 + 3.0 * a2

// --- Fast T3 ---
timeseries e1_f = ema(c, fastLen)
timeseries e2_f = ema(e1_f, fastLen)
timeseries e3_f = ema(e2_f, fastLen)
timeseries e4_f = ema(e3_f, fastLen)
timeseries e5_f = ema(e4_f, fastLen)
timeseries e6_f = ema(e5_f, fastLen)
timeseries t3_fast = c1 * e6_f + c2 * e5_f + c3 * e4_f + c4 * e3_f

// --- Medium T3 ---
timeseries e1_m = ema(c, medLen)
timeseries e2_m = ema(e1_m, medLen)
timeseries e3_m = ema(e2_m, medLen)
timeseries e4_m = ema(e3_m, medLen)
timeseries e5_m = ema(e4_m, medLen)
timeseries e6_m = ema(e5_m, medLen)
timeseries t3_med = c1 * e6_m + c2 * e5_m + c3 * e4_m + c4 * e3_m

// --- Slow T3 ---
timeseries e1_s = ema(c, slowLen)
timeseries e2_s = ema(e1_s, slowLen)
timeseries e3_s = ema(e2_s, slowLen)
timeseries e4_s = ema(e3_s, slowLen)
timeseries e5_s = ema(e4_s, slowLen)
timeseries e6_s = ema(e5_s, slowLen)
timeseries t3_slow = c1 * e6_s + c2 * e5_s + c3 * e4_s + c4 * e3_s

// -----------------------------------------------------------------------------
// 4. REGIME DETECTION
// -----------------------------------------------------------------------------
// Bullish: price above all T3 lines, fast > med > slow (alignment)
// Bearish: price below all T3 lines, fast < med < slow (alignment)
// Neutral: everything else (chop / convergence)

var priceAboveAll = c > t3_fast && c > t3_med && c > t3_slow
var priceBelowAll = c < t3_fast && c < t3_med && c < t3_slow
var alignmentBull = t3_fast > t3_med && t3_med > t3_slow
var alignmentBear = t3_fast < t3_med && t3_med < t3_slow

var regimeBull = priceAboveAll && alignmentBull
var regimeBear = priceBelowAll && alignmentBear
var regimeNeutral = !regimeBull && !regimeBear

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

// -----------------------------------------------------------------------------
// 5. CROSSOVER DETECTION (static state tracking)
// -----------------------------------------------------------------------------
// Track previous values for crossover detection
static prevT3Fast = 0.0
static prevT3Med = 0.0
static prevT3Slow = 0.0

var fastCrossMedUp = t3_fast > t3_med && prevT3Fast <= prevT3Med
var fastCrossMedDn = t3_fast < t3_med && prevT3Fast >= prevT3Med
var medCrossSlowUp = t3_med > t3_slow && prevT3Med <= prevT3Slow
var medCrossSlowDn = t3_med < t3_slow && prevT3Med >= prevT3Slow
var priceCrossFastUp = c > t3_fast && c[1] <= prevT3Fast
var priceCrossFastDn = c < t3_fast && c[1] >= prevT3Fast

if (!isLiveUpdate) {
    prevT3Fast = t3_fast
    prevT3Med = t3_med
    prevT3Slow = t3_slow
}

// -----------------------------------------------------------------------------
// 6. PLOTTING
// -----------------------------------------------------------------------------

// --- Fast T3 ---
if (showFast) {
    plotLine(
        value=t3_fast,
        width=2,
        colors=[regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)],
        label=["T3 Fast"],
        desc=["Fast T3 Moving Average (Tillson " + fastLen + ")"]
    )
}

// --- Medium T3 ---
if (showMed) {
    plotLine(
        value=t3_med,
        width=2,
        colors=[regimeBull ? transparency(bullColor, 70) : (regimeBear ? transparency(bearColor, 70) : transparency(neutralColor, 70))],
        label=["T3 Medium"],
        desc=["Medium T3 Moving Average (Tillson " + medLen + ")"]
    )
}

// --- Slow T3 ---
if (showSlow) {
    plotLine(
        value=t3_slow,
        width=2,
        colors=[regimeBull ? transparency(bullColor, 85) : (regimeBear ? transparency(bearColor, 85) : transparency(neutralColor, 85))],
        label=["T3 Slow"],
        desc=["Slow T3 Moving Average (Tillson " + slowLen + ")"]
    )
}

// --- Ribbon Fill (Fast vs Medium, Medium vs Slow) ---
if (showRibbon) {
    var ribbonFastBull = t3_fast > t3_med
    plotLine(
        value=[t3_fast, t3_med],
        width=1,
        colors=[transparency(bullColor, 30), transparency(bearColor, 30)],
        colorIndex=ribbonFastBull ? 0 : 1,
        fill=true,
        label=["T3 Fast", "T3 Medium"],
        desc=["Fast T3 ribbon edge", "Medium T3 ribbon edge"]
    )

    var ribbonMedBull = t3_med > t3_slow
    plotLine(
        value=[t3_med, t3_slow],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=ribbonMedBull ? 0 : 1,
        fill=true,
        label=["T3 Medium", "T3 Slow"],
        desc=["Medium T3 ribbon edge", "Slow T3 ribbon edge"]
    )
}

// --- Underlying EMAs (debug) ---
if (showUnderlying) {
    plotLine(
        value=e1_f,
        width=1,
        colors=[transparency(neutralColor, 90)],
        label=["EMA1 Fast"],
        desc=["First EMA layer of fast T3"]
    )
    plotLine(
        value=e3_f,
        width=1,
        colors=[transparency(neutralColor, 80)],
        label=["EMA3 Fast"],
        desc=["Third EMA layer of fast T3"]
    )
    plotLine(
        value=e6_f,
        width=1,
        colors=[transparency(neutralColor, 70)],
        label=["EMA6 Fast"],
        desc=["Sixth EMA layer of fast T3"]
    )
}

// --- Crossover Shapes ---
if (showCrossShapes) {
    if (fastCrossMedUp) {
        plotShape(
            value=t3_fast,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Fast>Med"],
            desc=["Fast T3 crossed above Medium T3 — bullish alignment"]
        )
    }
    if (fastCrossMedDn) {
        plotShape(
            value=t3_fast,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Fast<Med"],
            desc=["Fast T3 crossed below Medium T3 — bearish alignment"]
        )
    }
    if (medCrossSlowUp) {
        plotShape(
            value=t3_med,
            shape="triangleup",
            colorIndex=bullColor,
            width=1,
            label=["Med>Slow"],
            desc=["Medium T3 crossed above Slow T3 — bullish alignment"]
        )
    }
    if (medCrossSlowDn) {
        plotShape(
            value=t3_med,
            shape="triangledown",
            colorIndex=bearColor,
            width=1,
            label=["Med<Slow"],
            desc=["Medium T3 crossed below Slow T3 — bearish alignment"]
        )
    }
    if (priceCrossFastUp) {
        plotShape(
            value=c,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Price>T3 Fast"],
            desc=["Price crossed above Fast T3 — bullish momentum"]
        )
    }
    if (priceCrossFastDn) {
        plotShape(
            value=c,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Price<T3 Fast"],
            desc=["Price crossed below Fast T3 — bearish momentum"]
        )
    }
}

// -----------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var alignmentText = alignmentBull ? "Aligned Up" : (alignmentBear ? "Aligned Down" : "Converged")

    plotTable(
        data=[
            ["T3 MA — Perfected", regimeText],
            ["T3 Fast", t3_fast[0]],
            ["T3 Medium", t3_med[0]],
            ["T3 Slow", t3_slow[0]],
            ["Alignment", alignmentText],
            ["Price vs Fast", c[0] > t3_fast[0] ? "Above" : "Below"]
        ],
        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
    )
}