MM Flow
FlowScripts

Perfected FlowScript

As you wish ema

As You Wish EMA — Perfected Edition is indexed as 172_as_you_wish_ema.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

16.7 KB

Lines

514

Native Signal Candidates

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

3/3 guarded

EMA Cross Up

line 439:5

Trigger

(showCrossMarkers && crossUpEvent)

Value

source

Deps

crossUpEvent:var, showCrossMarkers:input

EMA Cross Down

line 449:5

Trigger

(showCrossMarkers && crossDnEvent)

Value

source

Deps

crossDnEvent:var, showCrossMarkers:input

Unlabeled shape

line 477:5

Trigger

(isLastBar)

Value

source

Deps

isLastBar:builtin

172_as_you_wish_ema.flowscript

source path: kscripts/perfected/172_as_you_wish_ema.flowscript · sha256:c839dd70e5c8fcb29d6dd8fc858591851782b6b8ff4a0dce7bea646c29ddc35a

hash verified
//@version=2
// ============================================================================
// As You Wish EMA — Multi-EMA Ribbon & Regime Detection (Perfected Edition)
// Author: M (@Mrfameee) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #ema, #ribbon, #guppy, #regime, #trend, #crossover
//
// Production-grade customizable multi-EMA overlay with up to 10 lines,
// Guppy-style cluster analysis, regime-based color coding, ribbon fill,
// crossover shape markers, and trend strength measurement. Implements
// academic research on EMA responsiveness, trend-following profitability,
// and multiple moving average systems.
//
// Academic foundations:
//  1. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
//     Moving Average" (IJRIAS). EMA offers stability but lags in reversals;
//     multiple EMAs show trend hierarchy and strength. WMA responds faster
//     but produces more whipsaws. Combined approach yields robust decisions.
//  2. Guppy (1990s-2000s), Guppy Multiple Moving Average (GMMA). Two clusters
//     of EMAs: short-term (3,5,8,10,12,15) representing trader sentiment,
//     long-term (30,35,40,45,50,60) representing investor behavior. Ribbon
//     separation = trend strength; compression = consolidation.
//  3. Wilder (1978), "New Concepts in Technical Trading Systems" (Trend Res).
//     Introduced smoothing methodology underlying EMA. EMA = price[t] * k +
//     EMA[t-1] * (1-k) where k = 2/(N+1). The exponential weighting gives
//     more importance to recent prices while retaining historical memory.
//  4. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
//     the Stochastic Properties of Stock Returns" (J. Finance). Moving average
//     crossovers significantly outperformed buy-and-hold on 90 years of DJIA.
//     Buy signals followed by positive returns; sell by negative. Triggered
//     academic revival of technical analysis research.
//  5. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
//     Investing" (AQR). Trend-following profitable since 1880 across all major
//     asset classes. EMA-based trend alignment is a key component of
//     time-series momentum strategies. Simple trend rules are robust.
//  6. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
//     Losers" (J. Finance, 48(1)). Seminal momentum anomaly paper. Past
//     winners continue winning; past losers continue losing. Validates
//     trend-following as a premier cross-sectional anomaly.
// ============================================================================

define(
    title="As You Wish EMA — Perfected Edition",
    position="onchart",
    axis=false
)

// === USER INPUTS ===
// --- EMA Settings ---
var src = input(
    name="src",
    type="select",
    defaultValue="close",
    label="Source",
    options=["close","open","high","low","hl2","hlc3","ohlc4"],
    group="EMA Settings"
)
var numEMAs = input(
    name="numEMAs",
    type="number",
    defaultValue=6,
    label="Number of EMAs (1-10)",
    constraints={min: 1, max: 10, step: 1},
    group="EMA Settings"
)
var baseLen = input(
    name="baseLen",
    type="number",
    defaultValue=9,
    label="Base Length",
    constraints={min: 2, max: 200, step: 1},
    group="EMA Settings"
)
var lenStep = input(
    name="lenStep",
    type="number",
    defaultValue=7,
    label="Length Step",
    constraints={min: 1, max: 50, step: 1},
    group="EMA Settings"
)

// --- Ribbon & Fill ---
var showRibbon = input(
    name="showRibbon",
    type="boolean",
    defaultValue=true,
    label="Show EMA Ribbon Fill",
    group="Ribbon & Fill"
)
var showClusterFill = input(
    name="showClusterFill",
    type="boolean",
    defaultValue=true,
    label="Show Fast/Slow Cluster Fill",
    group="Ribbon & Fill"
)
var showCrossMarkers = input(
    name="showCrossMarkers",
    type="boolean",
    defaultValue=true,
    label="Show Crossover Markers",
    group="Ribbon & Fill"
)

// --- Trend Strength ---
var showTrendStrength = input(
    name="showTrendStrength",
    type="boolean",
    defaultValue=true,
    label="Show Trend Strength",
    group="Trend Strength"
)
var strengthLen = input(
    name="strengthLen",
    type="number",
    defaultValue=14,
    label="ATR Length for Strength",
    constraints={min: 5, max: 50, step: 1},
    group="Trend Strength"
)

// --- Display ---
var lineWidth = input(
    name="lineWidth",
    type="number",
    defaultValue=1,
    label="Line Width",
    constraints={min: 1, max: 5, step: 1},
    group="Display"
)
var showPriceLine = input(
    name="showPriceLine",
    type="boolean",
    defaultValue=false,
    label="Show Source Price Line",
    group="Display"
)

// --- Colors ---
var palette = input(
    name="palette",
    type="select",
    defaultValue="Rainbow",
    label="Color Palette",
    options=["Rainbow","Heat","Ocean","Sunset","Greyscale","Neon","Bull/Bear"],
    group="Colors"
)
var baseColor = input(
    name="baseColor",
    type="color",
    defaultValue="#26a69a",
    label="Base Color (palette anchor)",
    group="Colors"
)
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bullish Regime Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bearish Regime Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// === DATA SOURCES & NaN GUARD ===
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)

timeseries source = (src == "close") ? price.close
    : (src == "open") ? price.open
    : (src == "high") ? price.high
    : (src == "low") ? price.low
    : (src == "hl2") ? (price.high + price.low) / 2.0
    : (src == "hlc3") ? (price.high + price.low + price.close) / 3.0
    : (price.open + price.high + price.low + price.close) / 4.0

if (isnan(source[0]) || isnan(price.high[0]) || isnan(price.low[0])) {
    return
}

// === EMA COMPUTATION ===
var n = math.max(1, math.min(10, numEMAs))

timeseries e1 = ema(source, baseLen)
timeseries e2 = ema(source, baseLen + lenStep)
timeseries e3 = ema(source, baseLen + lenStep * 2)
timeseries e4 = ema(source, baseLen + lenStep * 3)
timeseries e5 = ema(source, baseLen + lenStep * 4)
timeseries e6 = ema(source, baseLen + lenStep * 5)
timeseries e7 = ema(source, baseLen + lenStep * 6)
timeseries e8 = ema(source, baseLen + lenStep * 7)
timeseries e9 = ema(source, baseLen + lenStep * 8)
timeseries e10 = ema(source, baseLen + lenStep * 9)

// Store in array for iteration
timeseries emaVals[10] = [e1, e2, e3, e4, e5, e6, e7, e8, e9, e10]

// === PALETTE → 10 color strings ===
var rainbow = ["#26a69a","#42a5f5","#ab47bc","#ec407a","#ef5350","#ff7043","#ffa726","#ffee58","#9ccc65","#26c6da"]
var heat    = ["#fff5e6","#ffe0b2","#ffb74d","#ff9800","#fb8c00","#f57c00","#ef6c00","#e65100","#bf360c","#7f2704"]
var ocean   = ["#e0f7fa","#80deea","#26c6da","#00acc1","#0097a7","#00838f","#006064","#01579b","#0277bd","#0288d1"]
var sunset  = ["#fce4ec","#f8bbd0","#f48fb1","#f06292","#ec407a","#e91e63","#d81b60","#c2185b","#ad1457","#880e4f"]
var greyscale = ["#f5f5f5","#e0e0e0","#bdbdbd","#9e9e9e","#757575","#616161","#424242","#303030","#212121","#0d0d0d"]
var neon    = ["#00e5ff","#1de9b6","#76ff03","#ffea00","#ffc400","#ff9100","#ff3d00","#ff1744","#d500f9","#651fff"]

var paletteCols = (palette == "Rainbow") ? rainbow
    : (palette == "Heat") ? heat
    : (palette == "Ocean") ? ocean
    : (palette == "Sunset") ? sunset
    : (palette == "Greyscale") ? greyscale
    : (palette == "Neon") ? neon
    : rainbow

// === REGIME DETECTION ===
// Fast cluster = first half of EMAs; Slow cluster = second half
var halfN = math.max(1, math.floor(n / 2))

// Fast cluster average (shortest EMAs)
timeseries fastAvg = (emaVals[0] + emaVals[math.max(0, halfN - 1)]) / 2.0
// Slow cluster average (longest EMAs)
timeseries slowAvg = (emaVals[math.min(n - 1, halfN)] + emaVals[n - 1]) / 2.0

// Price relative to EMA cloud
var priceAboveAll = source > e1 && source > e2 && (n < 3 || source > e3) && (n < 4 || source > e4)
    && (n < 5 || source > e5) && (n < 6 || source > e6) && (n < 7 || source > e7)
    && (n < 8 || source > e8) && (n < 9 || source > e9) && (n < 10 || source > e10)

var priceBelowAll = source < e1 && source < e2 && (n < 3 || source < e3) && (n < 4 || source < e4)
    && (n < 5 || source < e5) && (n < 6 || source < e6) && (n < 7 || source < e7)
    && (n < 8 || source < e8) && (n < 9 || source < e9) && (n < 10 || source < e10)

// Fast above slow = bullish regime; fast below slow = bearish
var fastAboveSlow = fastAvg > slowAvg
var regimeBull = priceAboveAll && fastAboveSlow
var regimeBear = priceBelowAll && !fastAboveSlow
var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// === TREND STRENGTH (EMA spread normalized by ATR) ===
timeseries atr = sma(
    math.max(
        price.high - price.low,
        math.max(
            math.abs(price.high - price.close[1]),
            math.abs(price.low - price.close[1])
        )
    ),
    strengthLen
)
timeseries emaSpread = math.abs(fastAvg - slowAvg)
timeseries trendStrength = atr > 0 ? (emaSpread / atr) : 0

// === STATIC STATE: Crossover Tracking ===
static prevFastAvg = 0.0
static prevSlowAvg = 0.0
static crossUpBar = 0
static crossDnBar = 0

if (!isLiveUpdate) {
    if (prevFastAvg > 0 && prevSlowAvg > 0) {
        if (fastAvg > slowAvg && prevFastAvg <= prevSlowAvg) {
            crossUpBar = barCount
        }
        if (fastAvg < slowAvg && prevFastAvg >= prevSlowAvg) {
            crossDnBar = barCount
        }
    }
    prevFastAvg = fastAvg
    prevSlowAvg = slowAvg
}

// === EVENT FLAGS ===
var crossUpEvent = crossUpBar == barCount
var crossDnEvent = crossDnBar == barCount

// === PLOTS: EMA RIBBON FILL (full envelope) ===
if (showRibbon && n >= 2) {
    var ribbonColor = regimeBull ? opacity(bullColor, 20) : (regimeBear ? opacity(bearColor, 20) : opacity("#9e9e9e", 15))
    plotLine(
        value=[e1, e10],
        width=1,
        colors=[ribbonColor, ribbonColor],
        fill=ribbonColor,
        label=["Fast EMA", "Slow EMA"],
        desc=["Fastest EMA envelope edge", "Slowest EMA envelope edge"]
    )
}

// === PLOTS: FAST/SLOW CLUSTER FILL ===
if (showClusterFill && n >= 4) {
    var clusterTop = emaVals[halfN - 1]
    var clusterBot = emaVals[halfN]
    var clusterColor = regimeBull ? opacity(bullColor, 15) : (regimeBear ? opacity(bearColor, 15) : opacity("#9e9e9e", 10))
    plotLine(
        value=[clusterTop, clusterBot],
        width=1,
        colors=[clusterColor, clusterColor],
        fill=clusterColor,
        label=["Fast Cluster", "Slow Cluster"],
        desc=["Fast EMA cluster boundary (short-term sentiment)", "Slow EMA cluster boundary (long-term investor behavior)"]
    )
}

// === PLOTS: INDIVIDUAL EMA LINES ===
// EMA 1
if (n >= 1) {
    var c1 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[0]
    plotLine(
        value=e1,
        width=lineWidth,
        colors=[c1],
        label=["EMA " + baseLen],
        desc=["EMA(" + baseLen + ") — fastest EMA in ribbon"]
    )
}
// EMA 2
if (n >= 2) {
    var c2 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[1]
    plotLine(
        value=e2,
        width=lineWidth,
        colors=[c2],
        label=["EMA " + (baseLen + lenStep)],
        desc=["EMA(" + (baseLen + lenStep) + ")"]
    )
}
// EMA 3
if (n >= 3) {
    var c3 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[2]
    plotLine(
        value=e3,
        width=lineWidth,
        colors=[c3],
        label=["EMA " + (baseLen + lenStep * 2)],
        desc=["EMA(" + (baseLen + lenStep * 2) + ")"]
    )
}
// EMA 4
if (n >= 4) {
    var c4 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[3]
    plotLine(
        value=e4,
        width=lineWidth,
        colors=[c4],
        label=["EMA " + (baseLen + lenStep * 3)],
        desc=["EMA(" + (baseLen + lenStep * 3) + ")"]
    )
}
// EMA 5
if (n >= 5) {
    var c5 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[4]
    plotLine(
        value=e5,
        width=lineWidth,
        colors=[c5],
        label=["EMA " + (baseLen + lenStep * 4)],
        desc=["EMA(" + (baseLen + lenStep * 4) + ")"]
    )
}
// EMA 6
if (n >= 6) {
    var c6 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[5]
    plotLine(
        value=e6,
        width=lineWidth,
        colors=[c6],
        label=["EMA " + (baseLen + lenStep * 5)],
        desc=["EMA(" + (baseLen + lenStep * 5) + ")"]
    )
}
// EMA 7
if (n >= 7) {
    var c7 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[6]
    plotLine(
        value=e7,
        width=lineWidth,
        colors=[c7],
        label=["EMA " + (baseLen + lenStep * 6)],
        desc=["EMA(" + (baseLen + lenStep * 6) + ")"]
    )
}
// EMA 8
if (n >= 8) {
    var c8 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[7]
    plotLine(
        value=e8,
        width=lineWidth,
        colors=[c8],
        label=["EMA " + (baseLen + lenStep * 7)],
        desc=["EMA(" + (baseLen + lenStep * 7) + ")"]
    )
}
// EMA 9
if (n >= 9) {
    var c9 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[8]
    plotLine(
        value=e9,
        width=lineWidth,
        colors=[c9],
        label=["EMA " + (baseLen + lenStep * 8)],
        desc=["EMA(" + (baseLen + lenStep * 8) + ")"]
    )
}
// EMA 10
if (n >= 10) {
    var c10 = (palette == "Bull/Bear") ? (regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)) : paletteCols[9]
    plotLine(
        value=e10,
        width=lineWidth,
        colors=[c10],
        label=["EMA " + (baseLen + lenStep * 9)],
        desc=["EMA(" + (baseLen + lenStep * 9) + ") — slowest EMA in ribbon"]
    )
}

// === PLOTS: SOURCE PRICE LINE ===
if (showPriceLine) {
    plotLine(
        value=source,
        width=1,
        colors=["#ffffff40"],
        label=["Source (" + src + ")"],
        desc=["Selected price source for EMA calculation"]
    )
}

// === PLOTS: CROSSOVER MARKERS ===
if (showCrossMarkers && crossUpEvent) {
    plotShape(
        value=source,
        shape="triangleup",
        colorIndex=bullColor,
        width=6,
        label=["EMA Cross Up"],
        desc=["Fast EMA cluster crossed above slow EMA cluster — bullish trend change"]
    )
}
if (showCrossMarkers && crossDnEvent) {
    plotShape(
        value=source,
        shape="triangledown",
        colorIndex=bearColor,
        width=6,
        label=["EMA Cross Down"],
        desc=["Fast EMA cluster crossed below slow EMA cluster — bearish trend change"]
    )
}

// === PLOTS: TREND STRENGTH HISTOGRAM (offchart) ===
if (showTrendStrength) {
    var strengthColor = trendStrength > 2.0 ? (regimeBull ? bullColor : bearColor)
        : (trendStrength > 1.0 ? opacity(regimeBull ? bullColor : bearColor, 60) : "#9e9e9e40")
    plotBar(
        value=trendStrength,
        colors=[strengthColor],
        width=1,
        label=["Trend Strength"],
        desc=["EMA spread normalized by ATR. >2.0 = strong trend, <1.0 = weak/chop."]
    )
}

// === REGIME LABEL (last bar only) ===
if (isLastBar) {
    var regimeLabel = regimeBull ? "BULLISH REGIME" : (regimeBear ? "BEARISH REGIME" : "NEUTRAL / CHOP")
    var regimeLabelColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

    plotPriceLabel(
        price=source,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeLabelColor,
        size=10,
        fontWeight=700
    )
}

// === EMA SUMMARY TABLE (last bar only) ===
if (isLastBar) {
    var tsLabel = trendStrength > 2.0 ? "STRONG" : (trendStrength > 1.0 ? "MODERATE" : "WEAK")

    plotTable(
        data=[
            ["As You Wish EMA", n + " EMAs | " + palette],
            ["Regime", regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")],
            ["Fast Avg", fastAvg],
            ["Slow Avg", slowAvg],
            ["Trend Strength", trendStrength],
            ["Strength Label", tsLabel]
        ],
        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
    )
}