Perfected FlowScript
ewfwert
Ewfwert Trend-Momentum System — Perfected Edition is indexed as 335_ewfwert.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.3 KB
Lines
531
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
EMA Cross Up
line 434:9
Trigger
(showShapes) && (crossUp)
Value
fastMA
Deps
crossUp:var, showShapes:input
EMA Cross Down
line 444:9
Trigger
(showShapes) && (crossDown)
Value
fastMA
Deps
crossDown:var, showShapes:input
Comp Cross Up
line 454:9
Trigger
(showShapes) && (compCrossUp)
Value
composite
Deps
compCrossUp:var, showShapes:input
Comp Cross Down
line 464:9
Trigger
(showShapes) && (compCrossDown)
Value
composite
Deps
compCrossDown:var, showShapes:input
Extreme Bull
line 474:9
Trigger
(showShapes) && (extremeBull)
Value
composite
Deps
extremeBull:var, showShapes:input
Extreme Bear
line 484:9
Trigger
(showShapes) && (extremeBear)
Value
composite
Deps
extremeBear:var, showShapes:input
335_ewfwert.flowscript
source path: kscripts/perfected/335_ewfwert.flowscript · sha256:5d07d886240c59ad8f2c4189c65ab26ddeed3694a2f128a5cb4212fa963d7c5a
//@version=2
// ============================================================================
// Ewfwert Trend-Momentum System — Perfected Edition
// Author: TestingTY (@TestingTY) | Enhanced by kScript Perfection Engineer
// Tags: CORE, ADVANCED, #trend, #momentum, #regime, #ema, #multifactor
//
// Production-quality dual-EMA trend-momentum system with multi-factor scoring,
// regime detection, color-coded visualization, shape markers, and session
// state tracking. Transforms a basic EMA crossover scaffold into a robust
// trend-momentum composite with volatility-adjusted signal quality.
//
// Research papers underpinning this design:
// 1. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
// Markets": introduced the Efficiency Ratio (ER) and KAMA, the
// foundational concepts for adaptive trend measurement. ER = Change /
// Volatility, ranging from 0 (no direction) to 1 (perfect trend).
// 2. Manasa & Reddy (2025), "Trend Analysis by Weighted and Exponential
// Moving Average": comparative study showing EMA offers superior
// stability to WMA for trend detection, while fast EMAs reduce lag.
// 3. Brock, Lakonishok & LeBaron (1992), "Simple Technical Trading Rules and
// the Stochastic Properties of Stock Returns": comprehensive 90-year study
// validating MA crossover profitability. Buy signals followed by positive
// returns, sell by negative.
// 4. Hurst, Ooi & Pedersen (2014), "A Century of Evidence on Trend-Following
// Investing": time-series momentum profitable since 1880 across nearly all
// asset classes. Validates EMA-based trend following as a robust strategy.
// 5. Zakamulin (2023), "Optimal Trend-Following with Transaction Costs":
// optimal trend-following strategies resemble simple MA crossover rules,
// theoretically justifying the fast/slow EMA architecture.
// 6. Jegadeesh & Titman (1993), "Returns to Buying Winners and Selling
// Losers": momentum as a premier cross-sectional anomaly. The momentum
// component of this composite captures the same persistent return effect.
// ============================================================================
define(
title="Ewfwert Trend-Momentum System — Perfected Edition",
position="onchart",
axis=false
)
// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------
// --- EMA Settings ---
var fastLen = input(
name="fastLen",
type="number",
defaultValue=9,
label="Fast EMA Length",
constraints={min: 2, max: 100, step: 1},
group="EMA Settings"
)
var slowLen = input(
name="slowLen",
type="number",
defaultValue=21,
label="Slow EMA Length",
constraints={min: 5, max: 200, step: 1},
group="EMA Settings"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="EMA Settings"
)
// --- Momentum Component ---
var momLen = input(
name="momLen",
type="number",
defaultValue=10,
label="Momentum Lookback",
constraints={min: 2, max: 50, step: 1},
group="Momentum"
)
var momWeight = input(
name="momWeight",
type="number",
defaultValue=0.30,
label="Momentum Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Momentum"
)
// --- Volatility Component ---
var volLen = input(
name="volLen",
type="number",
defaultValue=14,
label="Volatility Lookback",
constraints={min: 5, max: 50, step: 1},
group="Volatility"
)
var volWeight = input(
name="volWeight",
type="number",
defaultValue=0.20,
label="Volatility Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Volatility"
)
// --- Trend Weight ---
var trendWeight = input(
name="trendWeight",
type="number",
defaultValue=0.50,
label="Trend Weight",
constraints={min: 0.0, max: 1.0, step: 0.05},
group="Trend"
)
// --- Display ---
var showFast = input(
name="showFast",
type="boolean",
defaultValue=true,
label="Show Fast EMA",
group="Display"
)
var showSlow = input(
name="showSlow",
type="boolean",
defaultValue=true,
label="Show Slow EMA",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Score",
group="Display"
)
var showSignal = input(
name="showSignal",
type="boolean",
defaultValue=true,
label="Show Signal Line",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Momentum Histogram",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show EMA Fill",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Alert Shapes",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Regime Table",
group="Display"
)
// --- Colors ---
var fastColor = input(
name="fastColor",
type="color",
defaultValue="#26a69a",
label="Fast EMA Color",
group="Colors"
)
var slowColor = input(
name="slowColor",
type="color",
defaultValue="#ef5350",
label="Slow EMA Color",
group="Colors"
)
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#00e676",
label="Bull Color",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ff5252",
label="Bear Color",
group="Colors"
)
// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0])) {
return
}
// -----------------------------------------------------------------------------
// 3. EMA TREND COMPONENT
// -----------------------------------------------------------------------------
timeseries fastMA = ema(px, fastLen)
timeseries slowMA = ema(px, slowLen)
timeseries diff = fastMA - slowMA
// Normalize trend by ATR for cross-instrument comparability
timeseries atrV = atr(period=volLen)
timeseries trendScore = atrV > 0 ? diff / atrV : 0.0
trendScore = math.max(-3.0, math.min(3.0, trendScore))
// -----------------------------------------------------------------------------
// 4. MOMENTUM COMPONENT
// -----------------------------------------------------------------------------
// Rate-of-change momentum normalized by volatility
timeseries momRaw = px - px[momLen]
timeseries momScore = atrV > 0 ? momRaw / atrV : 0.0
momScore = math.max(-3.0, math.min(3.0, momScore))
// -----------------------------------------------------------------------------
// 5. VOLATILITY REGIME COMPONENT
// -----------------------------------------------------------------------------
// Expansion/contraction signal: short-term vs medium-term ATR ratio
timeseries atrShort = atr(period=5)
timeseries atrLong = atr(period=volLen)
timeseries volRatio = atrLong > 0 ? atrShort / atrLong : 1.0
timeseries volScore = volRatio > 1.5 ? 1.0 : (volRatio < 0.7 ? -1.0 : 0.0)
// -----------------------------------------------------------------------------
// 6. MULTI-FACTOR COMPOSITE SCORING
// -----------------------------------------------------------------------------
// Weighted combination of trend, momentum, and volatility regime.
// Produces a composite score normalized to a -100..+100 oscillator.
timeseries weightSum = trendWeight + momWeight + volWeight
timeseries compositeRaw = weightSum > 0 ?
(trendWeight * trendScore + momWeight * momScore + volWeight * volScore) / weightSum :
0.0
// Scale to -100..+100 and smooth
timeseries composite = ema(compositeRaw * 33.333, smoothLen)
// Signal line for crossover detection
timeseries signal = sma(composite, 9)
// Momentum histogram
timeseries hist = composite - signal
// -----------------------------------------------------------------------------
// 7. REGIME DETECTION
// -----------------------------------------------------------------------------
// Four-regime classification based on composite and signal:
// Strong Bull: composite > signal AND composite > 20
// Weak Bull: composite > signal AND composite <= 20
// Strong Bear: composite < signal AND composite < -20
// Weak Bear: composite < signal AND composite >= -20
var regimeStrongBull = composite > signal && composite > 20
var regimeWeakBull = composite > signal && composite <= 20
var regimeStrongBear = composite < signal && composite < -20
var regimeWeakBear = composite < signal && composite >= -20
var regimeColor = regimeStrongBull ? bullColor :
(regimeWeakBull ? transparency(bullColor, 50) :
(regimeStrongBear ? bearColor : transparency(bearColor, 50)))
// Trend direction for EMA coloring
var trendBull = fastMA > slowMA
var trendBear = fastMA < slowMA
// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
// Session-level persistence for regime transitions, extremes, and signal counts.
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighComposite = -999999.0
static sessionLowComposite = 999999.0
static lastBarIndex = 0
static bullSignalCount = 0
static bearSignalCount = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (composite > sessionHighComposite) {
sessionHighComposite = composite
}
if (composite < sessionLowComposite) {
sessionLowComposite = composite
}
var currentRegime = regimeStrongBull ? 2 : (regimeWeakBull ? 1 : (regimeStrongBear ? -2 : -1))
if (lastRegime != currentRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
if (crossover(fastMA, slowMA)) {
bullSignalCount = bullSignalCount + 1
}
if (crossunder(fastMA, slowMA)) {
bearSignalCount = bearSignalCount + 1
}
}
// -----------------------------------------------------------------------------
// 9. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// EMA crossovers
var crossUp = crossover(fastMA, slowMA)
var crossDown = crossunder(fastMA, slowMA)
// Composite signal crossovers
var compCrossUp = composite > signal && !isnan(composite[1]) && composite[1] <= signal[1]
var compCrossDown = composite < signal && !isnan(composite[1]) && composite[1] >= signal[1]
// Extreme conditions
var extremeBull = composite > 50 && !isnan(composite[1]) && composite[1] <= 50
var extremeBear = composite < -50 && !isnan(composite[1]) && composite[1] >= -50
// -----------------------------------------------------------------------------
// 10. PLOTTING
// -----------------------------------------------------------------------------
// --- EMA Lines (trend-colored) ---
if (showFast) {
plotLine(
value=fastMA,
width=2,
colors=[trendBull ? fastColor : transparency(fastColor, 40)],
label=["Fast EMA"],
desc=["Fast EMA (" + fastLen + ") — trend-colored"]
)
}
if (showSlow) {
plotLine(
value=slowMA,
width=2,
colors=[trendBear ? slowColor : transparency(slowColor, 40)],
label=["Slow EMA"],
desc=["Slow EMA (" + slowLen + ") — trend-colored"]
)
}
// --- EMA Fill ---
if (showFill) {
var emaBull = fastMA > slowMA
plotLine(
value=[fastMA, slowMA],
width=1,
colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
colorIndex=emaBull ? 0 : 1,
fill=true,
label=["Fast EMA", "Slow EMA"],
desc=["Fill between fast and slow EMA"]
)
}
// --- Composite Score (regime-colored) ---
if (showComposite) {
plotLine(
value=composite,
width=2,
colors=[regimeColor],
label=["Composite Score"],
desc=["Multi-factor trend-momentum composite (-100 to +100)"]
)
}
// --- Signal Line ---
if (showSignal) {
plotLine(
value=signal,
width=1,
colors=["#ffffff"],
label=["Signal"],
desc=["9-period SMA of composite score"]
)
}
// --- Composite/Signal Fill ---
if (showFill && showComposite && showSignal) {
var compFillBull = composite > signal
plotLine(
value=[composite, signal],
width=1,
colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
colorIndex=compFillBull ? 0 : 1,
fill=true,
label=["Composite", "Signal"],
desc=["Fill between composite and signal"]
)
}
// --- Momentum Histogram (color-coded) ---
if (showHistogram) {
var histBull = hist >= 0
var histStrong = math.abs(hist) > 10
plotBar(
value=hist,
colors=[
histStrong ? bullColor : transparency(bullColor, 60),
histStrong ? bearColor : transparency(bearColor, 60)
],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Momentum"],
desc=["Histogram of composite minus signal"]
)
}
// --- Alert Shapes ---
if (showShapes) {
if (crossUp) {
plotShape(
value=fastMA,
shape="triangleup",
color=bullColor,
width=3,
label=["EMA Cross Up"],
desc=["Fast EMA crossed above slow EMA — bullish trend start"]
)
}
if (crossDown) {
plotShape(
value=fastMA,
shape="triangledown",
color=bearColor,
width=3,
label=["EMA Cross Down"],
desc=["Fast EMA crossed below slow EMA — bearish trend start"]
)
}
if (compCrossUp) {
plotShape(
value=composite,
shape="circle",
color=bullColor,
width=2,
label=["Comp Cross Up"],
desc=["Composite score crossed above signal — momentum shift"]
)
}
if (compCrossDown) {
plotShape(
value=composite,
shape="circle",
color=bearColor,
width=2,
label=["Comp Cross Down"],
desc=["Composite score crossed below signal — momentum fade"]
)
}
if (extremeBull) {
plotShape(
value=composite,
shape="diamond",
color="#ff1744",
width=3,
label=["Extreme Bull"],
desc=["Extreme bullish composite score (>50) — exhaustion risk"]
)
}
if (extremeBear) {
plotShape(
value=composite,
shape="diamond",
color="#00e676",
width=3,
label=["Extreme Bear"],
desc=["Extreme bearish composite score (<-50) — reversal potential"]
)
}
}
// -----------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regimeStrongBull ? "STRONG BULL" :
(regimeWeakBull ? "WEAK BULL" :
(regimeStrongBear ? "STRONG BEAR" : "WEAK BEAR"))
var regimeTextColor = regimeStrongBull ? bullColor :
(regimeWeakBull ? transparency(bullColor, 70) :
(regimeStrongBear ? bearColor : transparency(bearColor, 70)))
plotTable(
data=[
["Ewfwert System", regimeText],
["Composite", composite[0]],
["Signal", signal[0]],
["Momentum", hist[0]],
["Fast EMA", fastMA[0]],
["Slow EMA", slowMA[0]],
["Bull Signals", bullSignalCount],
["Bear Signals", bearSignalCount],
["Regime Changes", regimeChangeCount]
],
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
)
}