Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Supertrend v4.0 with EMA Filter – Tradingview Pinescript Code

4 min read

A Supertrend with EMA filter strategy takes Supertrend buy signals only when price is also above the 200-period EMA, and exits when the candle closes below Supertrend. The filter skips many counter-trend entries, which cuts the number of trades, the trading cost and the drawdown compared with plain Supertrend signals. Below are the rules, the 2017 to 2022 Nifty 15-minute backtest, the original Pine Script code and an updated Pine Script v6 version.

Supertrend with a simple EMA Filter can improve the performance of the signals during a strong trending market and reduces the number of trades as well which in turn reduces the trading cost + unwanted losing trades. i.e overall drawdown reduces and improves the Sharpe ratio compared to the regular supertrend long/short signals.

Key takeaways
  • Buy when the candle closes above Supertrend and above the 200 EMA; exit when it closes below Supertrend.
  • Long only, 15-minute Nifty chart, Supertrend factor 3 and ATR length 10, no optimisation.
  • Backtest (Jan 2017 to Oct 2022, 50 units): net profit ₹5,73,533, max drawdown 7.16%, profit factor 1.78, 45.35% winners over 419 trades.
  • The EMA filter does not fix sideways markets; Supertrend still whipsaws when price chops around the EMA.
  • An updated Pine Script v6 version with an EMA length input and an optional short side is included.

Strategy Rules

Buy – if candle closes above supertrend and price above 200 EMA on closing basis
Exit Buy – if price of the candle closes below supertrend.

OpenAlgo Desktop: algo trading on your own computer

WINDOWS, MAC AND LINUX

OpenAlgo Desktop: algo trading on your own computer

Install, sign in, connect your broker and trade. No server to set up and no Python to install.

  • Same API and screens as OpenAlgo web
  • Strategy module, charting and scalping terminals
  • Keys stay encrypted on your machine

In other words, the Supertrend with EMA filter only takes trades when two trend filters agree: the short-term Supertrend direction and the long-term 200 EMA.

Strategy Parameters

EMA Filter used: 200 EMA

Strategy Type: Long Only

Recommended Timeframe: 15min

Symbol Backtested: Nifty Futures

Backtesting Period : Jan 2017 – 29th Nov 2022 – Till to date

Supertrend Default Parameters: Multiplier- 3 and ATR Length – 10

Optimization : No

Position Size : 1 lot (50 shares)

Notes on the setup, from the strategy properties screenshot above: the test ran on the NSE:NIFTY 15-minute chart with an order size of 50 units (one Nifty lot at the time), initial capital of ₹2,00,000, 0.02% commission and no slippage. The Nifty lot size has changed since; it is 65 for contracts from January 2026 (NSE lot size revision), so scale the rupee figures if you trade one lot today.

Backtest Results

Supertrend V4.0 – Nifty Futures 15min Charts

During the sideways markets, it behaves like supertrend, creating noisy signals. However, the overall performance of the super trend improves with reduced drawdown

Equity Curve per lot

Absolute Drawdown per lot

Backtesting Metrics

Key figures from the performance summary:

MetricValue
Net profit₹5,73,533 (286.77%)
Buy and hold return (same period)₹2,16,166 (108.08%)
Max drawdown₹46,163 (7.16%)
Profit factor1.776
Sharpe ratio / Sortino ratio0.498 / 1.191
Closed trades419 (190 winners, 229 losers)
Percent profitable45.35%
Average trade₹1,368.81
Commission paid₹1,04,907
Figures from the TradingView Strategy Tester screenshot above (2017-01-01 to 2022-10-30).

Two things stand out. Fewer than half the trades win, so the profit comes from letting the trending trades run. And commission paid is about 18% of net profit, which is why reducing the number of trades with a filter matters so much.

Tradingview Pinescript Code – Supertrend V4.0

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © algostudio
// Coded by Rajandran R (Founder - Marketcalls and Creator - OpenAlgo)

//@version=5
strategy("Supertrend with EMA as Filter", overlay=true)


//input controls
factor = input.float(2,"Factor",1.0,10.0,0.5)
length = input.int(10,"ATR Length",1,100,1)

[supertrend,direction] = ta.supertrend(factor,length)

ema200 = ta.ema(close,200)

plot(ema200,"EMA 200",color.yellow,linewidth = 2)

//direction variables contains series of +1 and -1
//supertrend variable contains the supertrend line

longEntry = direction == -1 and close > ema200
longExit =  direction == 1 and direction[1] == -1

shortEntry = direction == 1 and close < ema200
shortExit = direction == -1 and direction[1] == 1

supcolor = direction == -1 ? color.green : color.red 

plot(supertrend,"Supertrend",supcolor,linewidth = 2)

if(longEntry)
    strategy.entry("BUY",strategy.long,comment="BUY")
if(longExit)
    strategy.close("BUY",comment="BUY EXIT")
// if(shortEntry)
//     strategy.entry("SHORT",strategy.short,comment="SHORT")
// if(shortExit)
//     strategy.close("SHORT",comment="SHORT EXIT")

How the code works

  • ta.supertrend(factor, length) returns the Supertrend line and a direction series that is -1 in an uptrend and +1 in a downtrend.
  • longEntry needs an uptrend (direction == -1) and a close above the 200 EMA.
  • longExit fires on the bar where direction flips from -1 to +1.
  • The short-side rules are written but commented out, which keeps the strategy long only.
  • Note that the factor input in this code defaults to 2, while the backtest above used 3. Set Factor to 3 in the indicator settings to reproduce the results.

Updated version (2026): Supertrend with EMA Filter in Pine Script v6

Pine Script v6 was released in December 2024 and older scripts keep working (TradingView blog). This v6 version keeps the same logic, sets the factor default to 3 to match the backtest, adds an input for the EMA length and makes the short side a switch instead of commented-out code:

//@version=6
strategy("Supertrend with EMA Filter (v6)", overlay=true, initial_capital=200000)

// Inputs
factor     = input.float(3.0, "Factor", minval=1.0, maxval=10.0, step=0.5)
atrLength  = input.int(10, "ATR Length", minval=1, maxval=100)
emaLength  = input.int(200, "EMA Filter Length", minval=1)
allowShort = input.bool(false, "Allow Short Trades")

// Supertrend: direction is -1 in an uptrend and +1 in a downtrend
[supertrend, direction] = ta.supertrend(factor, atrLength)
emaFilter = ta.ema(close, emaLength)

longEntry  = direction < 0 and close > emaFilter
longExit   = direction > 0 and direction[1] < 0
shortEntry = direction > 0 and close < emaFilter
shortExit  = direction < 0 and direction[1] > 0

plot(emaFilter, "EMA Filter", color.yellow, 2)
plot(supertrend, "Supertrend", direction < 0 ? color.green : color.red, 2)

if longEntry
    strategy.entry("BUY", strategy.long, comment="BUY")
if longExit
    strategy.close("BUY", comment="BUY EXIT")
if allowShort and shortEntry
    strategy.entry("SHORT", strategy.short, comment="SHORT")
if allowShort and shortExit
    strategy.close("SHORT", comment="SHORT EXIT")

Strategy Tester settings such as order size, commission and slippage can be set in the strategy’s Properties tab, so you can match your broker charges and the current lot size.

How to Add the Strategy to TradingView

  1. Open a Nifty or Nifty futures chart on the 15-minute timeframe.
  2. Open the Pine Editor, paste the code and click “Add to chart”.
  3. Open the strategy settings and confirm Factor 3, ATR Length 10 and EMA 200.
  4. In Properties, set order size, commission and slippage to match your trading.
  5. Review the Strategy Tester, then test on other liquid symbols before trusting the results.

Limitations and Ideas to Test

  • In sideways markets around the 200 EMA, Supertrend still gives frequent losing signals.
  • The backtest has no slippage; real fills on 15-minute signals will be worse.
  • Results are for one symbol and one parameter set. Test a grid of factors and ATR lengths out of sample; the VectorBT Supertrend grid optimisation tutorial shows how to do that quickly in Python.
  • Try a volatility or time-of-day filter, or compare with HalfTrend, a smoother alternative to Supertrend.

For the base indicator, see Supertrend indicator in Pine Script, and for Amibroker users the Supertrend V4.0 AFL code.

Frequently Asked Questions

What is the best EMA to use with Supertrend?

The 200 EMA used here is a common long-term trend filter. Shorter EMAs such as 50 react faster but filter fewer trades; test the length on your symbol and timeframe.

What are the default Supertrend settings?

This strategy was tested with factor 3 and ATR length 10, the most widely used combination. The original code defaults the factor to 2, so change it to 3 to match the backtest.

Does the EMA filter improve Supertrend?

In this Nifty 15-minute test it reduced the number of trades and kept drawdown to 7.16%, but it does not remove whipsaws in sideways markets.

Can I use this strategy for short selling?

Yes. Uncomment the short entry and exit lines in the original code, or switch on “Allow Short Trades” in the v6 version. Backtest the short side separately before using it.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

2 Replies to “Supertrend v4.0 with EMA Filter – Tradingview Pinescript Code”

  1. I have downloaded the nakshatra system for nifty and modified it. It is giving vey good calmar ratio for 6 months but the problem is i don’t have reliable data source for historical data. It would be great if you would share your data with us as you have shared many code. If it is not possible to share your data, please share the nakshatra system for tradingview where we can buy the data and test the code also. Thanks.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More