Edgoro
Trend indicator

EMA crossover indicator: how it works, settings and Pine Script v6 code

How the EMA is calculated, why fast/slow EMA crosses are popular, which lengths traders use, and a free EMA crossover script with a trend filter.

What it measures

An exponential moving average (EMA) is an average of recent prices that gives more weight to the newest bars. An EMA crossover uses two of them: a fast one that follows price closely and a slow one that changes direction only when the trend does. When the fast EMA crosses above the slow EMA, recent prices have risen above the longer-term average; when it crosses below, the reverse.

It is one of the simplest trend-following tools, and because it is fully mechanical it is often the first idea traders turn into an indicator or a strategy.

The formula in words

  1. Pick a length N. The weight given to the newest price is 2 / (N + 1): about 0.095 for a 20-period EMA.
  2. Each new EMA value = weight × today's close + (1 − weight) × yesterday's EMA.
  3. Do this for a fast length (say 9) and a slow length (say 21).
  4. A bullish cross happens on the bar where the fast EMA closes above the slow EMA after being at or below it on the previous bar. A bearish cross is the mirror image.

Because every value depends on the previous one, an EMA needs some history to settle. Pine Script starts the series with a simple average of the first N bars.

How traders read it

  • Direction. Fast above slow describes an uptrend on that timeframe; fast below slow, a downtrend. The space between the two lines widens as the trend accelerates.
  • Crosses as entries. A cross is the moment the description changes. In clean trends it catches a good part of the move; in ranges it produces a series of small losses as the lines weave together.
  • A third, longer EMA as a filter. Many traders only take bullish crosses while price is above a 200-period EMA and bearish crosses below it. The script below includes that filter.
  • Pullbacks. In a trend, price often returns to the fast or slow EMA before continuing. Some traders use the EMAs as dynamic zones rather than using the cross at all.

Common settings

PairTypical use
9 / 21Short-term swings and intraday charts
20 / 50Swing trading on hourly to daily charts
50 / 200Long-term trend; the daily cross is often called the golden cross or death cross
200 aloneA trend filter for other signals

There is nothing special about these numbers beyond habit. If a strategy only works with a 17 / 43 pair and not with neighbouring values, it is probably fitted to noise; see backtesting mistakes that inflate results.

Pine Script v6 code

The complete, self-contained script is below. Copy it into a new indicator in TradingView's Pine Editor, or download the .pine file.

Pine Script v6
//@version=6
indicator("EMA crossover with trend filter", shorttitle = "EMA cross", overlay = true)

src      = input.source(close, "Source")
fastLen  = input.int(9, "Fast EMA", minval = 1)
slowLen  = input.int(21, "Slow EMA", minval = 2)
useTrend = input.bool(true, "Only signal in the direction of the trend EMA")
trendLen = input.int(200, "Trend EMA", minval = 2)

fast  = ta.ema(src, fastLen)
slow  = ta.ema(src, slowLen)
trend = ta.ema(src, trendLen)

crossUp   = ta.crossover(fast, slow)
crossDown = ta.crossunder(fast, slow)
longOk    = not useTrend or close > trend
shortOk   = not useTrend or close < trend

buySignal  = crossUp and longOk
sellSignal = crossDown and shortOk

fastPlot = plot(fast, "Fast EMA", color = color.new(color.teal, 0), linewidth = 2)
slowPlot = plot(slow, "Slow EMA", color = color.new(color.orange, 0), linewidth = 2)
plot(useTrend ? trend : na, "Trend EMA", color = color.new(color.gray, 0))
fill(fastPlot, slowPlot, color = fast > slow ? color.new(color.teal, 85) : color.new(color.orange, 85), title = "Cross fill")

plotshape(buySignal, "Bullish cross", shape.triangleup, location.belowbar, color.new(color.teal, 0), size = size.small)
plotshape(sellSignal, "Bearish cross", shape.triangledown, location.abovebar, color.new(color.orange, 0), size = size.small)

alertcondition(buySignal, "EMA bullish cross", "Fast EMA crossed above slow EMA on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sellSignal, "EMA bearish cross", "Fast EMA crossed below slow EMA on {{ticker}} ({{interval}}) at {{close}}")

The script plots the fast and slow EMAs with a shaded band between them, an optional 200-period trend EMA, and triangles on crosses that agree with the trend filter. Switch the filter off in the settings to see every cross.

This is an indicator: it marks signals and sends alerts, but it doesn't simulate trades. To backtest the same logic with stops, targets and costs, see how to build an EMA crossover strategy in Pine Script.

Add it to your chart

  1. Open any chart on TradingView and open the Pine Editor.
  2. Create a new indicator, delete the template code and paste the script.
  3. Click Save, then Add to chart. Change lengths and levels from the indicator's settings.

Stuck on an error? See how to add a Pine Script indicator to TradingView.

Pitfalls

  • Whipsaws in ranges. When price moves sideways the EMAs cross back and forth. A trend filter, a minimum distance between the lines, or an ADX threshold reduces the noise.
  • Lag. Crosses confirm after the turn. That's the price of filtering noise, and shorter lengths only trade lag for more false signals.
  • Optimising the lengths. It's easy to find a pair that fitted the past perfectly. Prefer round numbers and check that neighbouring values behave similarly.
  • Acting before the close. A cross on the live bar can undo itself. Use once-per-bar-close alerts and act on closed bars.

The script is an educational example: test it on your own markets before relying on it. Indicators describe the past; they don't predict the future. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Make it yours with Edgoro

Describe the change in plain English and Edgoro writes the Pine Script v6 for you, ready to paste. For example:

“Plot the 20 and 50 EMA, mark crosses only when the close is above the 200 EMA for longs and below it for shorts, and alert once per bar close.”

Build your EMA crossover indicator