Tutorial

200 EMA Trend Filter in Pine Script: Add It to Any Entry

Add a 200 EMA trend filter to a Pine Script v6 strategy, tighten it with a slope check and buffer, and compare the runs fairly in TradingView.

•11 min read

You have an entry rule that fires often and loses often. Maybe it is an RSI dip, maybe a breakout. You open the Strategy Tester and notice that the losing trades cluster in one kind of market: the entries that buy a dip while price keeps sliding, or sell a bounce while price keeps climbing. Someone on a forum says the fix is a 200 EMA trend filter. Add one line, only take longs above it. It sounds too simple, and in code it genuinely is simple. The interesting part is everything the one line does to your results, and the three or four ways it quietly goes wrong.

This post builds the filter properly in Pine Script v6. We start with what the 200 EMA actually measures, then add it to an existing entry rule, then tighten it with a slope check and a buffer, then move it to a higher timeframe without repainting. Along the way we cover how to compare before and after fairly, because a filter that improves one number while halving your trade count is not automatically an improvement.

What a 200 EMA measures, and what it does not

An exponential moving average with a length of 200 is a weighted average of the last 200 closes, where recent bars count more than old ones. On a daily chart that is roughly 200 trading days of memory. On a 1 hour chart it is about eight days of continuous crypto trading. The length is the same, but the story it tells is not, which is the first thing to keep in mind: "the 200 EMA" has no fixed meaning until you say which timeframe it lives on.

What the line gives you is a cheap, smooth reference for direction. When price closes above it, the recent weighted average of closes is below the current price, so the market has been drifting up. When price closes below it, the opposite. That is all. It does not tell you that the trend will continue, that a pullback to the line will hold, or that the move is strong. It is a description of the recent past, delayed by design.

That delay is the price of smoothness. An EMA reacts later than price, so a trend filter built on it will always be a little late to turn on at the start of a move and a little late to turn off at the end. Readers who care about this sort of thing will recognise it as a property of the tool, not a flaw to engineer away. If you want the mechanics of how SMA, EMA, RMA and WMA differ in how fast they react, Pine Script Moving Average Types covers it.

The way to think about the filter is as a gate on an entry you already have, not as an entry in its own right. It answers one question: is this the kind of market where my entry rule is allowed to act? Everything below follows from treating it that way.

The simplest version: one condition on an existing entry

Here is a complete strategy. The entry rule is deliberately plain: a long when RSI crosses back up through 30, a short when it crosses back down through 70. The filter is a single toggle, so you can run the same script with the gate on and off and compare.

pine
//@version=6
strategy("RSI Entry With 200 EMA Filter", overlay=true,
     default_qty_type=strategy.percent_of_equity, default_qty_value=10,
     commission_type=strategy.commission.percent, commission_value=0.1)

emaLen    = input.int(200, "Trend EMA length", minval=2)
useFilter = input.bool(true, "Use trend filter")
rsiLen    = input.int(14, "RSI length", minval=2)

trendEma = ta.ema(close, emaLen)
rsiValue = ta.rsi(close, rsiLen)

uptrend   = close > trendEma
downtrend = close < trendEma

longOk  = not useFilter or uptrend
shortOk = not useFilter or downtrend

longEntry  = ta.crossover(rsiValue, 30) and longOk
shortEntry = ta.crossunder(rsiValue, 70) and shortOk

if longEntry
    strategy.entry("Long", strategy.long)
if shortEntry
    strategy.entry("Short", strategy.short)

if ta.crossover(rsiValue, 50)
    strategy.close("Short")
if ta.crossunder(rsiValue, 50)
    strategy.close("Long")

plot(trendEma, "Trend EMA", color=color.orange, linewidth=2)

Read the filter in three lines: uptrend, longOk, and the and longOk on the entry. The toggle is written as not useFilter or uptrend so that when the filter is off the gate is always open. That small pattern, a boolean input that makes a condition always true, is worth reusing for every filter you add later, because it lets you switch one idea on and off without editing logic.

Two details are easy to miss. First, the filter uses close on the current bar, and in a strategy that is evaluated at bar close by default, so the comparison is made on a finished value. Second, the exits are not filtered. If you are long and price drops under the EMA, the RSI exit still handles the trade. Whether the filter should also force an exit is a design choice, and we come back to it in the pitfalls section.

Compare before and after the right way

Run the script twice, once with useFilter on and once off, in the Strategy Tester on the same symbol, timeframe, and date range. Then look past net profit. The questions that matter are about what changed.

Look at the trade count first. A 200 EMA gate removes every trade that goes against the trend, so expect fewer trades, often a lot fewer. If a filter takes you from 400 trades to 60, the comparison between the two runs is no longer between equals: the smaller sample is far noisier, and a good-looking result on 60 trades says much less than the same result on 400. The Strategy Tester metrics guide explains what to read once you have enough trades to read anything.

Then look at maximum drawdown and the longest losing stretch, not just the headline. A trend filter's usual contribution is that it keeps the strategy out of the market during long one-directional moves against it, which shows up in the drawdown before it shows up in profit. If the drawdown did not move, the filter is probably not doing what you think. Maximum Drawdown: How to Measure Risk in a Backtest goes into the measurement.

Finally, change the EMA length and watch what happens. If 200 works and 180 and 220 both fall apart, you have not found a property of the market, you have found a coincidence on this data. A robust idea degrades gracefully when you nudge a parameter. A fragile one falls off a cliff.

This is a coding and testing exercise. A backtest describes what the rule would have done on past data under the assumptions you set, including commission, and it promises nothing about what happens next.

Tighten it: a slope check and a buffer

Price being above the 200 EMA is a loose test. In a sideways market price crosses the line back and forth, and each cross flips the gate. The strategy then takes entries in a range that the filter was supposed to protect against. Two refinements address this directly.

The first is a slope check. Instead of asking only where price is relative to the line, ask which way the line itself is moving. If the EMA is rising, the longer-run drift is up. If it is flat or falling, long entries are not welcome even when price pokes above it.

The second is a buffer. Require price to be a small percentage beyond the line before the gate opens, so that a hairline cross does not count. The buffer turns the single line into a band with a dead zone in the middle where neither side is allowed.

pine
//@version=6
strategy("RSI Entry With Slope and Buffer Filter", overlay=true,
     default_qty_type=strategy.percent_of_equity, default_qty_value=10,
     commission_type=strategy.commission.percent, commission_value=0.1)

emaLen      = input.int(200, "Trend EMA length", minval=2)
slopeBars   = input.int(10, "Slope lookback (bars)", minval=1)
bufferPct   = input.float(0.5, "Buffer (%)", minval=0.0, step=0.1)
rsiLen      = input.int(14, "RSI length", minval=2)

trendEma = ta.ema(close, emaLen)
rsiValue = ta.rsi(close, rsiLen)

emaRising  = trendEma > trendEma[slopeBars]
emaFalling = trendEma < trendEma[slopeBars]

upperBand = trendEma * (1 + bufferPct / 100)
lowerBand = trendEma * (1 - bufferPct / 100)

longOk  = close > upperBand and emaRising
shortOk = close < lowerBand and emaFalling

if ta.crossover(rsiValue, 30) and longOk
    strategy.entry("Long", strategy.long)
if ta.crossunder(rsiValue, 70) and shortOk
    strategy.entry("Short", strategy.short)

if ta.crossover(rsiValue, 50)
    strategy.close("Short")
if ta.crossunder(rsiValue, 50)
    strategy.close("Long")

plot(trendEma, "Trend EMA", color=color.orange, linewidth=2)
plot(upperBand, "Upper band", color=color.new(color.green, 60))
plot(lowerBand, "Lower band", color=color.new(color.red, 60))
bgcolor(longOk ? color.new(color.green, 92) : shortOk ? color.new(color.red, 92) : na)

The background color is not decoration. It shows you, bar by bar, when each side of the gate is open, which makes the filter inspectable. When a trade fires or does not fire, you can look at the chart and see whether the gate was open at that moment. Most filter bugs are visible in about ten seconds once the gate is painted.

Notice what each refinement costs. The slope check adds lag, because the EMA has to bend before the gate opens. The buffer cuts trades near the line, including some good ones. Neither is free, and neither is better by default. Treat both as inputs you vary, and keep the version that behaves sensibly across a range of settings, not the one that looks best at a single setting.

Run the filter on a higher timeframe

A 200 EMA on a 15 minute chart is a short-memory line. Many people want the opinion of a longer view: take 15 minute entries only when the daily trend agrees. That means pulling the daily EMA onto the 15 minute chart with request.security, and this is where indicators most often start to lie.

The trap is that a daily EMA computed on a 15 minute chart changes all day, because today's daily bar is still forming. On a live chart the value moves with every tick, and in a backtest it uses the final close of the day on bars that occurred hours earlier. The strategy then trades with information it could not have had.

The standard repaint-safe pattern asks for the previous completed daily bar and turns lookahead on only for that lagged value.

pine
//@version=6
strategy("RSI Entry With Daily 200 EMA Filter", overlay=true,
     default_qty_type=strategy.percent_of_equity, default_qty_value=10,
     commission_type=strategy.commission.percent, commission_value=0.1)

htf    = input.timeframe("D", "Filter timeframe")
emaLen = input.int(200, "Trend EMA length", minval=2)
rsiLen = input.int(14, "RSI length", minval=2)

htfEma   = request.security(syminfo.tickerid, htf, ta.ema(close, emaLen)[1],
     lookahead=barmerge.lookahead_on)
htfClose = request.security(syminfo.tickerid, htf, close[1],
     lookahead=barmerge.lookahead_on)

rsiValue = ta.rsi(close, rsiLen)

longOk  = htfClose > htfEma
shortOk = htfClose < htfEma

if ta.crossover(rsiValue, 30) and longOk
    strategy.entry("Long", strategy.long)
if ta.crossunder(rsiValue, 70) and shortOk
    strategy.entry("Short", strategy.short)

if ta.crossover(rsiValue, 50)
    strategy.close("Short")
if ta.crossunder(rsiValue, 50)
    strategy.close("Long")

plot(htfEma, "Daily EMA", color=color.orange, linewidth=2)

Both requests use [1] inside the call and lookahead=barmerge.lookahead_on. The [1] makes the value the previous closed higher-timeframe bar. Turning lookahead on then just lets that settled value appear on every intraday bar of the current day without waiting. The filter is a day behind on purpose, and that is what makes it honest. Multi-Timeframe Analysis in Pine Script Without Repainting explains why this works and when the other combinations do not.

See the filter run before you trust it

A filter is easy to write and easy to get subtly wrong, so watch it work. In PineScripter you can describe the change in plain English, something like "add a 200 EMA trend filter to the long entry, with an input to turn it off", and the AI edits only the lines that change, so the rest of a long script stays as you wrote it. The Code Changes view shows exactly which lines moved. Every script is checked for compile errors the way TradingView checks it before you see it.

Then run it on the built-in chart. PineScripter runs your script on real market data from 308 crypto spot markets, across 14 timeframes and up to 5,000 bars, and draws the plots so you can see the EMA, the bands, and the gate coloring without pasting anything into TradingView first. Use bar replay to step one bar at a time through a moment where the filter should have blocked an entry, and confirm that it did. You can ask the AI about any bar to find out why a condition was true or false there.

One boundary matters here. PineScripter does not simulate trades or report returns. The before and after comparison in the previous section happens in TradingView's Strategy Tester after you paste the script in. PineScripter is where you write the filter and check that it behaves; TradingView is where you measure what it does to the numbers.

Common pitfalls

The most common mistake is filtering entries but not thinking about exits. If you only take longs above the EMA but never exit when price falls through it, the trade can sit in a position the filter would no longer allow you to open. Decide on purpose. Some strategies are fine with the original exit; others should close when the gate shuts.

The second is applying a 200 EMA on a chart with fewer than 200 bars of history. The EMA needs time to settle, and the early values are unreliable. If your date range starts close to the first available bar, the first stretch of trades is being filtered by a line that is not yet meaningful. Start your test later, or give it warm-up bars.

The third is hunting for the best length. Running every value from 50 to 300 and picking the winner is fitting the filter to the history. The honest check is the neighbours: does the result hold when the length changes by 10 percent? The article on walk-forward testing shows a structured way to split the data so the choice is not made on the same bars you judge it on.

The fourth is asking a trend filter to do the job of the entry. The EMA gate says nothing about when to enter, and it does nothing in a market that trends one way and then reverses sharply. It trims a category of trade. It does not make the remaining trades good.

Last, remember that a filter changes what the strategy is. If you have already read moving average crossover strategies or built an RSI strategy, adding a trend gate produces a different system with its own trade count, its own drawdown, and its own parameters to validate. Treat the filtered version as a new strategy, not a patch.

Where to go from here

A 200 EMA filter is a good first lesson in how a single condition reshapes a strategy: fewer trades, different drawdowns, new places to hide a bug. Build the plain version, add the toggle, compare the runs, then try the slope, the buffer, and the higher timeframe one at a time so you know which change did what. If you would rather describe the change than edit the code by hand, PineScripter writes it as Pine Script v6, checks it compiles, and shows you the line-by-line diff, and you keep the code. Paste it into TradingView and run it in the Strategy Tester to see what it does on your market.

Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.

Describe your indicator in plain English and get Pine Script that compiles →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.