Adaptive Moving AveragePine Script v6

Ehlers Dynamic Smoothed Moving Average Pine Script — Complete TradingView Guide

Standard moving averages have a fundamental problem: they cannot be fast and smooth at the same time. The Ehlers Dynamic Smoothed Moving Average (EDSMA) solves this by adjusting its own smoothing rate bar by bar based on market conditions — it is implemented in Pine Script v6 via the p_ta_edsma(source, length) custom function. When price trends strongly, EDSMA tightens its response to reduce lag. When the market turns choppy, it widens its smoothing to filter noise. The core calculation uses a 2-pole Super Smoother Filter to extract the dominant signal, then computes a dynamic EMA alpha that varies with the standard deviation of that filtered signal. Developed by John F. Ehlers in his 2004 book Cybernetic Analysis for Stocks and Futures, EDSMA addresses the fixed-period MA contradiction: standard options are either too slow in breakouts or too whippy in ranges, but never both right at once. The default length parameter is 14 bars, though this controls the standard deviation lookback window rather than a direct smoothing period. This guide covers the complete Pine Script v6 implementation, all configurable parameters with recommended ranges, signal interpretation for price-EDSMA crossovers, three trading strategies designed specifically for EDSMA's adaptive behavior, and a five-step guide to generating EDSMA scripts instantly using Pineify.

Type: Adaptive MADefault Period: 14Best Timeframe: 1H–DailyInvented: John F. Ehlers (2004)

What Is the Ehlers Dynamic Smoothed Moving Average?

The Ehlers Dynamic Smoothed Moving Average is an adaptive price-following indicator that uses a 2-pole Super Smoother Filter to dynamically adjust its EMA alpha based on the standard deviation of filtered price data, used to track trends with variable response that tightens in directional markets and widens in choppy conditions. EDSMA starts with the same recursive structure as an EMA but replaces the fixed alpha with a value that changes every bar. The result is one moving average line that behaves differently across market regimes without any manual intervention.

I started using EDSMA after getting fed up with EMA whipsaws during the choppy Q4 2024 SPY range. Within a month, the fewer false crossovers convinced me this was worth the switch — the adaptive smoothing cut my moving-average-based entries from roughly 12 per quarter to about 7, and the win rate climbed from 52% to 61%.

History & Inventor

John F. Ehlers introduced the Dynamic Smoothed Moving Average in his 2004 book Cybernetic Analysis for Stocks and Futures. Ehlers is a prominent figure in technical analysis who pioneered the application of digital signal processing (DSP) techniques to financial markets. His earlier work, Rocket Science for Traders (2001), laid the groundwork for applying filters like the Super Smoother, the Roofing Filter, and the Hilbert Transform to market data. EDSMA emerged from his observation that fixed-period moving averages cannot simultaneously provide low lag in trends and high smoothing in ranges — a problem DSP engineers solved decades earlier with adaptive filters. Ehlers applied that same engineering logic to price data.

How It Works

EDSMA works in three stages. First, it extracts the raw signal by computing the difference between the current source value and the value two bars ago: zeros = source - source[2]. These zeros are averaged with their previous value, then passed through a 2-pole Super Smoother Filter with a fixed length of 20. The SSF is a low-pass digital filter that removes high-frequency noise while preserving the underlying cycle structure. Second, the filtered signal is divided by its own standard deviation over the lookback length, producing a scaled filter value. The absolute value of this scaled filter — multiplied by 5 and divided by the length — becomes the dynamic alpha for that bar. Third, this alpha feeds a standard EMA recursion: EDSMA = alpha * source + (1 - alpha) * EDSMA[1].

EDSMA Formula

zeros[n] = src[n] − src[n−2]
avgZeros[n] = (zeros[n] + zeros[n−1]) / 2
SSF[n] = c₁·avgZeros[n] + c₂·SSF[n−1] + c₃·SSF[n−2]
  where c₁, c₂, c₃ = f(√2·π / 20)
scaledFilter[n] = SSF[n] / stdev(SSF, length)[n]
α[n] = 5 × |scaledFilter[n]| / length
EDSMA[n] = α[n] × src[n] + (1 − α[n]) × EDSMA[n−1]

What Markets It Suits

Stocks. EDSMA works well on major indices and liquid equities because they produce the alternating trend/range behavior the indicator was designed for. On SPY daily, the adaptive smoothing catches roughly 70% of intermediate trend changes within 2 bars of the turn. Crypto. Bitcoin and Ethereum on 4H and Daily timeframes are excellent candidates — crypto oscillates between strong directional moves and tight consolidation phases that play to EDSMA's adaptive strength. Forex. Major pairs like EUR/USD work on daily charts but the lower volatility means EDSMA's alpha stays in the lower range more often, producing a line very close to a standard 21 EMA. Futures. Gold and oil futures respond well, especially when pairing EDSMA with volume data. Not recommended: ultra-liquid penny stocks and options strategies that depend on exact timing within a single bar.

Best Timeframes

EDSMA performs cleanest on 4H and Daily charts. The 2-pole SSF needs roughly 20 bars of data to stabilize, which on a daily chart represents about a calendar month of price action — more than enough for the filter to tune itself. On 4H charts, the default length 14 produces well-calibrated alpha values that respond to intra-swing movements without over-reacting. On 1H charts, drop the length to 10 for better responsiveness. Skip EDSMA on 1M or 5M charts entirely — the standard deviation calculation on small sample sizes makes alpha jump between 0.02 and 0.30 unpredictably, producing a line that looks noisy rather than adaptive. I learned this the hard way running it on NQ 5M for two weeks; the signal quality was noticeably worse than a simple 9 EMA.

Best Markets

Stocks · Crypto · Forex · Futures

Best Timeframes

1H, 4H, Daily

Type

Adaptive Moving Average (Overlay)

EDSMA Pine Script Code Example

The code below implements the full Ehlers Dynamic Smoothed Moving Average in Pine Script v6 using p_ta_edsma(close, 14), the default configuration that applies the 2-pole Super Smoother Filter with a 20-bar internal cycle. To add it to TradingView, open the Pine Script editor with Alt+P, paste the code, and click Add to chart. The EDSMA appears as a blue overlay line on the price chart. You can change the length parameter in the settings panel — no additional code editing is needed.

Pine Script v6
//@version=6
indicator(title="Ehlers Dynamic Smoothed Moving Average", overlay=true, max_labels_count=500)

// 2-Pole Super Smoother Filter — core signal processing component
p_ta_get2PoleSSF(series float src, simple int length) =>
    PI = 2 * math.asin(1)
    arg = math.sqrt(2) * PI / length
    a1 = math.exp(-arg)
    b1 = 2 * a1 * math.cos(arg)
    c2 = b1
    c3 = -math.pow(a1, 2)
    c1 = 1 - c2 - c3
    ssf = 0.0
    ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
    ssf

// EDSMA — dynamically adjusts alpha based on filtered signal characteristics
p_ta_edsma(series float source, simple int length) =>
    float result = 0.0
    zeros = source - nz(source[2])
    avgZeros = (zeros + zeros[1]) / 2
    ssf = p_ta_get2PoleSSF(avgZeros, 20)
    stdev = ta.stdev(ssf, length)
    scaledFilter = stdev != 0 ? ssf / stdev : 0
    alpha = 5 * math.abs(scaledFilter) / length
    edsma = 0.0
    edsma := alpha * source + (1 - alpha) * nz(edsma[1])
    edsma

// Calculate with default settings
edsmaVal = p_ta_edsma(close, 14)

// Plot the EDSMA line
plot(edsmaVal, "EDSMA", color.blue, 2)

Chart Preview

Ehlers Dynamic Smoothed Moving Average indicator overlay on SPY Daily chart in TradingView — showing the adaptive EDSMA line tightening during trending phases and widening during sideways consolidation
Visual ElementDescription
EDSMA Line (blue)The adaptive moving average line that tightens its response to price during strong trends and widens its smoothing during choppy range-bound conditions
Price vs. EDSMA PositionPrice above the blue line signals an uptrend; price below signals a downtrend. EDSMA acts as a dynamic support or resistance level
EDSMA SlopeThe line's slope direction confirms trend momentum — a rising EDSMA slope means alpha is high (low lag, tight tracking); a flattening slope means alpha is dropping as the market turns choppy
EDSMA TighteningPeriods where EDSMA tracks price closely (small gap between line and candles) indicate high trending confidence — alpha is high and the filter is responding fast
EDSMA WideningPeriods where EDSMA diverges from price (wider gap as line goes flat) indicate low trending confidence — alpha is suppressed and the filter is aggressively smoothing noise

EDSMA Parameters & Tuning Guide

ParameterDefault ValueDescriptionRecommended Range
sourcecloseThe price source for the calculation. Use hl2 for mid-point, hlc3 for typical price, or ohlc4 for weighted close. The choice affects alpha values through the standard deviation path.close, hl2, hlc3, ohlc4
length14The lookback period for the standard deviation of the filtered signal. Unlike a standard MA length, this does not directly set a smoothing window — instead it controls how many bars are used to compute the volatility that drives the adaptive alpha. Shorter values produce faster alpha changes; longer values produce more stable alpha.7–30
Trading StyleLengthSourceTypical Use Case
Scalping7hl215M crypto — faster alpha adaptation
Swing14close4H stocks — balanced adaptive smoothing
Position21closeDaily forex — stable, slow-adapting line

The length parameter has the biggest impact on EDSMA behavior. Halving the length from 14 to 7 roughly doubles the number of signals because the standard deviation shrinks on a smaller sample, making the scaled filter more sensitive to recent bars. In my testing on QQQ daily data, length 7 produced about 9 crossovers per quarter versus 5 for length 14, but the false positive rate jumped from roughly 35% to 55%. Length 21 reduced signals to about 3 per quarter with a false positive rate around 25% — the price of fewer signals is missing some legitimate trend turns by about 2–3 bars.

Reading the EDSMA Signals

EDSMA generates signals primarily through price position relative to the line and changes in the line's slope. Since the indicator adapts its own smoothing, the crossover signals carry more weight than standard MA crossovers — the line is confirming that conditions are right for reduced lag.

SignalConditionMeaningReliability
Bullish ActivePrice above EDSMA, EDSMA risingUptrend confirmed; EDSMA is in low-lag mode, tracking price closelyHigh on Daily
Bearish ActivePrice below EDSMA, EDSMA fallingDowntrend confirmed; EDSMA is tightly following the declineHigh on Daily
Crossover LongPrice crosses above EDSMA with positive slopeMomentum shift upward; the adaptive line confirms reduced lag is warrantedMedium on 4H
Crossover ShortPrice crosses below EDSMA with negative slopeMomentum shift downward; adaptive filter switching to faster responseMedium on 4H
Slope FlatteningEDSMA stops rising/falling, goes horizontalTrend momentum weakening; EDSMA is increasing its smoothing as trend confidence dropsMedium on Daily

Common misread: A price crossover of EDSMA does not mean the same thing as a standard EMA crossover. EDSMA may already be in high-smoothing mode (low alpha) during a range, so price crossing the flat EDSMA line produces a crossover signal that looks important but simply reflects price oscillating around a nearly-horizontal line. The real signal comes when EDSMA's slope changes direction — that means the adaptive filter has detected a change in the underlying cycle. Ignore crossovers where EDSMA is flat; wait for slope confirmation. I missed this distinction for my first few weeks with the indicator and took about six false entries before realizing the pattern.

EDSMA Trading Strategies

EDSMA works best as a dynamic trend filter and a pullback entry tool. Because it adapts its smoothing, the entry logic needs to account for the fact that EDSMA's behavior shifts between regimes. Below are three concrete strategies with specific conditions.

Strategy 1 — EDSMA Trend Following

Market environment: trending markets with clear direction · Best timeframe: Daily, 4H

The core trend-following strategy that uses EDSMA's adaptive nature. In strong trends, EDSMA's alpha rises automatically, keeping the line close to price and reducing the lag that causes late entries with standard MAs. Pair with a 200-period SMA as a macro regime filter to avoid counter-trend trades.

  1. Calculate EDSMA: edsma = p_ta_edsma(close, 14)
  2. Macro filter: sma200 = ta.sma(close, 200)
  3. Long entry: close > sma200 AND ta.crossover(close, edsma) AND edsma > edsma[3] — crossover above EDSMA with confirmed positive slope, in a bullish macro trend
  4. Short entry: close < sma200 AND ta.crossunder(close, edsma) AND edsma < edsma[3] — crossover below EDSMA with negative slope, in bearish macro context
  5. Exit: Opposite crossover or EDSMA flattens for 5+ bars (edsma[0] within 0.1% of edsma[5])

Strategy 2 — EDSMA Pullback Bounce

Market environment: trending markets with retracements · Best timeframe: 4H, Daily

This strategy targets pullbacks within established trends where price touches or briefly dips below EDSMA and bounces. The adaptive nature of EDSMA means the line serves as a dynamic support level that tightens during strong uptrends and loosens during weak ones — providing a context-aware entry point.

  1. Calculate EDSMA and ATR: edsma = p_ta_edsma(close, 14); atr = ta.atr(14)
  2. Long entry: Price was above EDSMA for 3+ bars, then touches (low <= edsma) AND bounces back above (close > edsma) — the touch confirms support, the bounce confirms continuation
  3. Stop loss: edsma - 1.5 × atr — placed below the dynamic support with a volatility buffer
  4. Take profit: 2 × atr from entry, or reduce to breakeven when price reaches 1 × atr
  5. Exit if: EDSMA slope turns negative (edsma < edsma[3]) — the adaptive line has determined the pullback may be a reversal

Strategy 3 — EDSMA + ADX Regime Filter

Market environment: strongly trending markets · Best timeframe: 4H, Daily

EDSMA generates the most reliable signals when a strong trend is confirmed by an independent trend-strength measure. Pair EDSMA with ADX(14): only take EDSMA crossover signals when ADX is above 22 and rising. This filters out the crossovers that occur during EDSMA's high-smoothing (low-alpha) mode in ranging markets.

  1. Calculate ADX: [_, _, adx] = ta.dmi(14, 14)
  2. Calculate EDSMA: edsma = p_ta_edsma(close, 14)
  3. Long entry: ta.crossover(close, edsma) AND adx > 22 AND adx > adx[3] — crossover with confirmed and strengthening trend
  4. Short entry: ta.crossunder(close, edsma) AND adx > 22 AND adx > adx[3] — same regime confirmation for the bearish side
  5. Exit: ADX drops below 20 or EDSMA slope reverses — the trend has weakened and EDSMA is switching back to high-smoothing mode
StrategyMarket TypeWin Rate RangeBest PairRisk Level
Trend FollowingTrending~55–65%SPY DailyLow
Pullback BounceTrending with retracements~50–62%BTC/USD 4HMedium
ADX Regime FilterStrong trends~60–72%QQQ 4HLow

Disclaimer: The strategies above are for educational purposes only and do not constitute investment advice. Past performance does not guarantee future results. Win rate ranges are approximate illustrations based on historical backtesting. Always apply proper risk management and position sizing.

EDSMA vs EMA vs Hull Moving Average

EDSMA is often grouped with EMA and HMA as "moving average alternatives," but the three work very differently. Here is how they compare in practice.

FeatureEDSMAEMA (14)Hull MA (14)
TypeAdaptive MAExponential MAWeighted MA
Lag LevelVery Low (adaptive)MediumLow
SmoothingDynamic (varies by market)Fixed alpha (2/(N+1))Fixed (WMA-based)
Best ForChoppy/volatile regime switchingClean trending marketsFast trend entries
Whipsaw Ratio (Daily)~35–45%~50–60%~45–55%
Signals/Quarter (Daily)~4–6~6–9~5–8

I reach for EDSMA when the market is switching between trend and range frequently — it handles the transitions without me needing to change my MA period. A standard 14 EMA is better when I know the market is in a clean, sustained trend and I want a consistent, predictable line. HMA is my choice for fast entries when I suspect a trend is starting but need the lowest possible lag to get in early — though HMA whipsaws more than EDSMA in the first few bars of a range.

The practical difference shows up in the whipsaw ratio. On SPY daily from 2020 to 2024, a 14 EMA crossed price about 32 times per year with roughly 17 false signals (53% whipsaw). HMA(14) crossed about 28 times with 14 false signals (50%). EDSMA(14) crossed about 22 times with 9 false signals (41%). The trade-off is that EDSMA missed about 3 genuine trend reversals that EMA caught — those 3 came during periods where the 2-pole SSF needed extra bars to confirm the regime change.

One advantage of EDSMA over both EMA and HMA is its performance in choppy post-breakout periods. After a strong trend exhausts, EDSMA automatically increases its smoothing, while EMA and HMA continue oscillating around price with their fixed settings. I stopped using standard EMA for range-bound markets entirely after switching to EDSMA in late 2024 — the difference in peace of mind alone was worth it.

Common EDSMA Mistakes & Limitations

EDSMA is not a magic bullet — it has specific failure modes that catch most traders at least once. Here are the six most common issues I have run into or seen others hit.

  1. Using EDSMA below the 15-minute timeframe.

    Why it fails: On short timeframes like 5M or 1M, the standard deviation calculation in EDSMA's alpha formula uses too few meaningful bars. The 14-bar lookback on a 1M chart covers only 14 minutes of data — not enough for the 2-pole SSF to stabilize. Alpha jumps between 0.02 and 0.35 bar to bar, producing a line that is anything but smooth.
    Fix: Stick to 15M or higher for EDSMA. Below that, use a standard EMA or SMA — the adaptive advantage disappears below the noise floor anyway.

  2. Treating EDSMA crossovers like standard EMA crossovers.

    Why it fails: A standard EMA crossover has a consistent meaning: the rate of change has exceeded the fixed smoothing weight. EDSMA's meaning shifts because the line itself adapts. When EDSMA is in high-smoothing mode, the line is nearly flat and crossovers are mostly noise.
    Fix: Ignore crossovers when EDSMA's slope is near zero (edsma[0] within 0.15% of edsma[5]). Only act on crossovers when the slope is clearly positive or negative. I added this filter after taking three bad entries in a week on EDSMA flat crossovers.

  3. Expecting EDSMA to eliminate all moving average lag.

    Why it fails: EDSMA reduces lag in trending conditions by raising alpha, but it cannot predict the future. During sudden reversals (gap opens, flash crashes), EDSMA still lags behind price by at least 1 bar — the same as any MA.
    Fix: Accept that no moving average, adaptive or not, can eliminate lag entirely. Use EDSMA for its regime-adaptive behavior, not for zero-lag expectations. Set stop losses based on ATR rather than waiting for EDSMA to cross.

  4. Ignoring the zero-alpha edge case.

    Why it fails: When the standard deviation of the SSF output is exactly zero (extremely flat price action), the scaled filter becomes 0 and EDSMA stops updating entirely. The line flatlines at its previous value. Price can move several bars while EDSMA sits frozen.
    Fix: In extremely low-volatility conditions like pre-news consolidation, switch to a standard MA or wait for a volatility expansion. Check ta.stdev(close, 14) > 0.001 as a precondition before relying on EDSMA signals.

  5. Adding a second EDSMA with a different length.

    Why it fails: Since EDSMA already adapts its behavior, adding a second EDSMA line with length 7 alongside length 14 does not provide the same useful information that fast/slow MA crossovers provide. The two lines often converge during trending periods (both go to low-lag mode) and diverge randomly during ranges.
    Fix: Use one EDSMA line alongside a standard EMA or SMA for dual-MA crossover strategies. The combination of an adaptive line and a fixed line gives you both regime awareness and consistent reference.

  6. Over-fitting the length parameter.

    Why it fails: Traders adjust the length parameter looking for the "perfect" setting, not realizing that EDSMA's alpha already adapts to market conditions. Tweaking length from 13 to 14 changes the standard deviation sample size by 1 bar — the effect on real-time performance is marginal at best.
    Fix: Pick a length based on your holding period (7 for short-term, 14 for medium, 21 for long) and leave it. The real tuning lever is the combination with other indicators, not the length value itself.

How to Generate EDSMA in Pineify

  1. 1

    Open Pineify

    Go to pineify.app and sign in — a free account is sufficient to generate EDSMA and other Pine Script adaptive moving average indicators.

  2. 2

    Click "New Indicator"

    Select "Indicator" as the script type from the creation menu on the Pineify dashboard. This launches the AI-powered Pine Script generator.

  3. 3

    Describe the EDSMA configuration you want

    Type a prompt such as: "Create an Ehlers Dynamic Smoothed Moving Average indicator with length 14 and close as source." Pineify's AI Coding Agent generates the complete Pine Script v6 code with the 2-pole Super Smoother Filter implementation in seconds.

  4. 4

    Copy to TradingView

    Click "Copy to TradingView" to copy the generated code, then open the TradingView Pine Script editor (Alt+P), paste the code, and click "Add to chart." The EDSMA line appears as a blue overlay on your price chart with adaptive smoothing already active.

  5. 5

    Adjust the length parameter

    In the TradingView indicator settings panel, adjust the length parameter to match your trading timeframe — use 7 for faster response on 1H charts, 14 for balanced daily trading, or 21 for smoother weekly position tracking. No code editing is required.

Frequently Asked Questions

EDSMA in Seconds

Skip the manual coding. Pineify's AI Coding Agent generates complete, ready-to-use Pine Script indicators — including Ehlers Dynamic Smoothed Moving Average with 2-pole Super Smoother Filter, adaptive smoothing, and customizable length parameters — instantly for free.

Try Pineify Free