Trend FollowingPine Script v6

Dual Moving Average Pine Script — Complete TradingView Guide

The Dual Moving Average indicator in Pine Script plots two moving averages — a fast MA and a slow MA — on the same price chart and generates automatic crossover buy and sell signals using Pine Script v6's built-in ta.crossover() and ta.crossunder() functions. The default configuration uses a 9-period EMA (fast) and a 21-period EMA (slow) on the close price, displayed as green and red overlay lines. When the fast MA crosses above the slow MA, a bullish trend shift is signalled; when it crosses below, a bearish shift is signalled. The indicator supports 11 MA types — SMA, EMA, HMA, WMA, RMA, VWMA, and more — making it adaptable to any trading style from intraday scalping to long-term position trading. This guide covers the complete Pine Script v6 implementation, all configurable parameters, three concrete trading strategies, and step-by-step instructions for generating it instantly with Pineify.

What Is the Dual Moving Average Indicator?

The Dual Moving Average is a trend-following overlay indicator that plots two MAs of different lengths and signals trend direction changes when the faster MA crosses the slower MA. The concept of using two moving averages to identify trend shifts has been a cornerstone of technical analysis since Richard Donchian popularised moving average crossover systems in the 1960s and 1970s. The two-MA crossover became mainstream after the publication of the "Golden Cross" and "Death Cross" patterns — terms coined to describe the 50-day SMA crossing above or below the 200-day SMA on daily stock charts.

In Pine Script v6, the Dual Moving Average indicator is built on two calls to a flexible p_ta_ma(source, length, ma_type) helper function that dispatches to the appropriate built-in MA function (ta.ema, ta.sma, ta.hma, etc.) based on the selected type. The crossover logic uses ta.crossover(fast_ma, slow_ma) — which returns true on the bar where fast MA closes above slow MA — and ta.crossunder(fast_ma, slow_ma) for the reverse.

Core formula: For EMA (the default MA type), each value is calculated as EMA[t] = α × price[t] + (1 − α) × EMA[t−1], where the smoothing factor α = 2 / (length + 1). A fast EMA(9) has α ≈ 0.20, giving 20% weight to the latest price; a slow EMA(21) has α ≈ 0.09, giving 9% weight. The fast MA reacts to price changes in approximately 3–5 bars; the slow MA takes approximately 7–10 bars to reflect a similar move.

The Dual Moving Average works across all liquid asset classes — stocks, crypto, forex, and futures — and on all timeframes. The most effective timeframes are 15-minute and 1-hour charts for day trading, 4-hour and Daily charts for swing trading, and Daily and Weekly charts for position trading. The indicator produces more reliable signals in trending markets (ADX above 20) and generates excessive false signals (whipsaws) in low-volatility, sideways-ranging markets.

Best Markets

Stocks · Crypto · Forex · Futures

Best Timeframes

15m, 1H, 4H, Daily

Overlay

Yes — plots directly on price chart

Dual Moving Average Pine Script Code

The code below plots a 9-period EMA (green) and a 21-period EMA (red) as overlay lines on the TradingView price chart, and computes crossover signals for use in alerts or strategies. To add it to TradingView: copy the code, open the Pine Script editor with Alt+P, paste it in, and click Add to chart. Change the 9 and 21 values or swap "EMA" for any supported MA type to customise the indicator.

Pine Script v6
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
indicator(title="Dual Moving Average", overlay=true, max_labels_count=500)

// Dual Moving Average crossover: fast EMA(9) and slow EMA(21) on close
p_ta_ma(series float source, simple int length, simple string ma_type) =>
    switch ma_type
        "SMA"  => ta.sma(source, length)
        "EMA"  => ta.ema(source, length)
        "HMA"  => ta.hma(source, length)
        "WMA"  => ta.wma(source, length)
        "RMA"  => ta.rma(source, length)
        "VWMA" => ta.vwma(source, length)

p_ta_ma_crossover(series float source, simple int fast_length, simple int slow_length, simple string ma_type) =>
    fast_ma     = p_ta_ma(source, fast_length, ma_type)
    slow_ma     = p_ta_ma(source, slow_length, ma_type)
    is_cross_up   = ta.crossover(fast_ma, slow_ma)
    is_cross_down = ta.crossunder(fast_ma, slow_ma)
    [fast_ma, slow_ma, is_cross_up, is_cross_down]

[p_ind_1_fastMa, p_ind_1_slowMa, p_ind_1_crossUp, p_ind_1_crossDown] =
    p_ta_ma_crossover(close, 9, 21, "EMA")

// Plot fast MA (green) and slow MA (red)
plot(p_ind_1_fastMa, "Dual MA - Fast", color.rgb(76, 175, 80, 0), 1)
plot(p_ind_1_slowMa, "Dual MA - Slow", color.rgb(242, 54, 69, 0), 1)

Chart Preview

Dual Moving Average indicator Pine Script code example in TradingView — EMA 9/21 crossover plotted as overlay

Parameters

ParameterDefault ValueDescriptionRecommended Range
sourcecloseThe price series both MAs are calculated from. close is standard; some traders use hlc3 (typical price) for noise reduction.close, open, high, low, hlc3, ohlc4
fast_length9Period of the faster moving average. Smaller values react more quickly to price changes and generate more signals.5–50 bars
slow_length21Period of the slower moving average. Must be greater than fast_length. Larger values produce fewer, higher-quality signals.10–200 bars
ma_type"EMA"The type of moving average applied to both fast and slow lines. Supports SMA, EMA, HMA, WMA, RMA, VWMA, VAR, WWMA, ZLEMA, TSF.EMA (trending) · SMA (noisy markets) · HMA (fast response)

Tuning Guide by Trading Style

  • Scalping (1m–5m charts): fast 5 / slow 13 EMA — very reactive, best on high-liquidity assets like BTC or EUR/USD
  • Intraday day trading (15m–1H charts): fast 9 / slow 21 EMA (default) — balances signal frequency with reliability
  • Swing trading (4H–Daily charts): fast 20 / slow 50 EMA or SMA — fewer but higher-conviction crossovers
  • Position trading (Daily–Weekly charts): fast 50 / slow 200 SMA — the "Golden Cross / Death Cross" watched by institutional traders globally

Trading Strategies Using the Dual Moving Average

The Dual Moving Average is most effective as a trend-direction filter and entry trigger in trending markets. Below are three concrete strategies with specific, numbered entry and exit conditions.

Strategy 1 — EMA 9/21 Momentum Crossover

Market environment: trending markets · Best timeframe: 1H, 4H

The 9/21 EMA crossover is a classic short-to-medium-term trend entry. Pair it with ta.rsi(close, 14) above 50 to confirm bullish momentum before entering long positions.

  1. Calculate EMA(9) and EMA(21) on close using the Dual MA code above
  2. Long entry: ta.crossover(ema9, ema21) fires AND RSI(14) is above 50
  3. Short entry: ta.crossunder(ema9, ema21) fires AND RSI(14) is below 50
  4. Stop loss: place 1 ATR(14) below the entry candle low (long) or above the high (short)
  5. Take profit: exit when the opposite crossover fires, or at 2× the stop-loss distance

Strategy 2 — Golden Cross / Death Cross (50/200 SMA)

Market environment: long-term bull and bear cycles · Best timeframe: Daily

The 50-day / 200-day SMA crossover — the "Golden Cross" on the upside and "Death Cross" on the downside — is one of the most watched signals by institutional investors in equity markets. Pair with ta.adx(14) above 20 to confirm a genuine trend before acting.

  1. Set Dual MA to SMA, fast_length = 50, slow_length = 200 on the Daily chart
  2. Golden Cross (buy): SMA(50) crosses above SMA(200) AND ADX(14) > 20
  3. Death Cross (sell/short): SMA(50) crosses below SMA(200) AND ADX(14) > 20
  4. Hold the position as long as the 50-day SMA remains on the correct side of the 200-day SMA
  5. Risk management: use a 5–10% trailing stop on individual stock positions to protect gains in extended uptrends

Strategy 3 — Dual MA Pullback Entry (Trend Continuation)

Market environment: established uptrend · Best timeframe: 4H, Daily

Rather than chasing crossover signals at the moment of the cross, wait for price to pull back to the fast MA after a bullish crossover. This reduces entry risk and improves the reward-to-risk ratio. Combine with ta.stoch(close, high, low, 14) below 30 to confirm the pullback is oversold.

  1. Wait for the bullish crossover: ta.crossover(fast_ma, slow_ma) has fired within the last 10 bars
  2. Entry trigger: close pulls back to within 0.5% of the fast MA AND Stochastic(14) crosses above 20
  3. Confirm both MAs are still in upward slope: fast_ma > fast_ma[1] AND slow_ma > slow_ma[1]
  4. Stop loss: below the slow MA
  5. Target: minimum 1.5× the stop distance; trail stop to break-even after 1× is reached

Disclaimer: The strategies above are for educational purposes only and do not constitute investment advice. Past performance does not guarantee future results. Always apply proper risk management and position sizing.

How to Generate the Dual Moving Average in Pineify

  1. 1

    Open Pineify

    Go to pineify.app and sign in — a free account gives you full access to the AI Coding Agent for indicator generation.

  2. 2

    Click "New Indicator"

    Select "Indicator" as the script type from the creation menu to start a new Pine Script v6 project.

  3. 3

    Describe your Dual MA configuration

    Type a prompt such as: "Plot a 9-period EMA and a 21-period EMA on the price chart, and generate a crossover signal." Pineify's AI Coding Agent writes the complete Pine Script v6 code in seconds — including crossover logic, plot colours, and alert conditions.

  4. 4

    Copy the generated code to TradingView

    Click "Copy to TradingView" to copy the code, then paste it into the TradingView Pine Script editor (Alt+P) and click "Add to chart." Both MA lines appear immediately as overlays on your price chart.

  5. 5

    Adjust periods and MA type in indicator settings

    In the TradingView indicator settings panel, change the fast and slow periods or swap the MA type (SMA, EMA, HMA, WMA) to match your trading style — no manual code editing required.

Frequently Asked Questions

Related Pine Script Indicators

Build Your Dual Moving Average in Seconds

Skip the manual coding. Pineify's AI Coding Agent generates complete, ready-to-use Pine Script indicators — including Dual MA crossover strategies with alerts — instantly for free.

Try Pineify Free