TradingView has become one of the most widely used platforms among traders, thanks to its powerful charting tools, real-time data, and native scripting language—Pine Script. This flexible language allows traders to create custom indicators, automate trading strategies, and conduct robust backtests directly on the platform.
In this guide, we’ll walk through how to build and backtest a Donchian Channels and Exponential Moving Average (EMA) strategy using Pine Script. Whether you're new to algorithmic trading or looking to refine your coding skills, this step-by-step tutorial will help you understand the core logic, implementation, and optimization of a rule-based strategy in TradingView.
The strategy we're exploring combines momentum signals from Donchian Channels with a trend filter from the 200-period EMA, focusing on long entries only. We'll implement it from scratch, explain each component, and show how to visualize and test performance.
Understanding the Strategy Logic
The DC/EMA Strategy follows a clear set of rules designed to capture strong upward breakouts while avoiding counter-trend trades:
- Entry (Long): On the daily timeframe, go long when the price crosses above the upper Donchian band and the closing price is above the 200-period EMA.
- Exit: Close the long position when the price drops below the lower Donchian band.
- Trade Execution: Entries and exits are triggered intraday using stop orders—no need to wait for candle closure.
This approach ensures timely execution by placing stop orders just beyond the Donchian bands, enhancing responsiveness compared to close-based entries.
👉 Discover how to code high-performance trading strategies with real-time execution
Setting Up the TradingView Environment
To begin, open TradingView and search for your desired asset—in this case, the BOTZ ETF. Set the chart timeframe to daily.
Next, locate the built-in ChannelBreakOutStrategy by searching for it in the Indicators panel. Apply it to your chart. This pre-built script gives us a foundation for Donchian-based entries.
Adjust the following inputs:
- Length: Set to
3(using a 3-day Donchian Channel). - Order Size: Choose
100%equity to enable full compounding during backtesting.
While this gets us started, we need to customize the strategy using Pine Script to add EMA filtering and long-only logic.
Customizing the Pine Script Code
Click the “Source Code” button next to the strategy name on your chart. Then, duplicate the script and rename it to something meaningful like "DC/EMA Strategy".
Now let’s enhance the code step by step.
Step 1: Plotting the Donchian Channels
Add visual clarity by plotting the upper and lower bands:
plot(upBound, color=color.green, linewidth=1, title="Upper Band")
plot(downBound, color=color.red, linewidth=1, title="Lower Band")These lines draw the Donchian Channels directly on price, making it easy to see breakout levels.
Step 2: Adding the EMA Filter
Insert this code below the downBound definition:
emaLength = input.int(title="EMA Length", minval=1, maxval=1000, defval=200)
emaFilter = ta.ema(close, emaLength)Then add:
plot(emaFilter, color=color.blue, linewidth=1, title="EMA Filter")This introduces a customizable EMA (default 200) that acts as a trend filter. Only when price is above this line will long entries be considered.
Step 3: Enabling Long-Only Mode
Add a toggle for directional bias:
longOnly = input.bool(title="Long Only", defval=true)This input appears in the strategy settings and lets users disable short trades entirely.
Step 4: Updating Trade Logic
Replace the existing entry/exit logic with the following:
if (close > emaFilter)
if (not na(close[length]))
strategy.entry("ChBrkLE", strategy.long, stop=upBound + syminfo.mintick, comment="ChBrkLE")
if (strategy.position_size > 0)
strategy.exit("Exit Long", "ChBrkLE", stop=downBound - syminfo.mintick)
if (close < emaFilter) and (longOnly == false)
if (not na(close[length]))
strategy.entry("ChBrkSE", strategy.short, stop=downBound - syminfo.mintick, comment="ChBrkSE")
if (strategy.position_size < 0)
strategy.exit("Exit Short", "ChBrkSE", stop=upBound + syminfo.mintick)This logic ensures:
- Long trades only activate when price is above EMA200.
- Short trades are disabled if "Long Only" is checked.
- Stop orders are placed one tick beyond Donchian levels for immediate execution.
Final Pine Script Code
Here’s the complete script ready for use:
//@version=5
strategy("DC/EMA Strategy", overlay=true)
length = input.int(title="Length", minval=1, maxval=1000, defval=3)
upBound = ta.highest(high, length)
downBound = ta.lowest(low, length)
emaLength = input.int(title="EMA Length", minval=1, maxval=1000, defval=200)
emaFilter = ta.ema(close, emaLength)
longOnly = input.bool(title="Long Only", defval=true)
if (close > emaFilter)
if (not na(close[length]))
strategy.entry("ChBrkLE", strategy.long, stop=upBound + syminfo.mintick, comment="ChBrkLE")
if (strategy.position_size > 0)
strategy.exit("Exit Long", "ChBrkLE", stop=downBound - syminfo.mintick)
if (close < emaFilter) and (longOnly == false)
if (not na(close[length]))
strategy.entry("ChBrkSE", strategy.short, stop=downBound - syminfo.mintick, comment="ChBrkSE")
if (strategy.position_size < 0)
strategy.exit("Exit Short", "ChBrkSE", stop=upBound + syminfo.mintick)
plot(upBound, color=color.green, linewidth=1, title="Upper Band")
plot(downBound, color=color.red, linewidth=1, title="Lower Band")
plot(emaFilter, color=color.blue, linewidth=1, title="EMA Filter")After saving and clicking “Add to Chart,” you’ll see all components overlaid: Donchian bands in green/red and EMA in blue. Trade signals will appear as arrows on the chart.
👉 Learn how to refine your strategy with advanced risk management techniques
Backtesting Results and Optimization
Once applied, use TradingView’s Strategy Tester to view equity performance. You can adjust:
- Donchian period (
Length) - EMA length
- Asset and timeframe
Testing multiple parameter combinations helps assess strategy robustness—a key part of avoiding overfitting.
For example:
- A shorter Donchian period increases sensitivity but may generate more false breakouts.
- A longer EMA smooths trend filtering but could delay entries.
Vary inputs systematically and analyze metrics like win rate, profit factor, and maximum drawdown to find optimal settings.
Frequently Asked Questions (FAQ)
What is Pine Script used for?
Pine Script is TradingView’s domain-specific language used to create custom technical indicators, alerts, and automated trading strategies. It enables real-time data analysis and backtesting without needing external tools.
Can I backtest strategies on any asset?
Yes. As long as historical price data is available on TradingView for an asset—stocks, ETFs, forex pairs, or cryptocurrencies—you can apply and test your Pine Script strategy across different instruments.
How does syminfo.mintick improve trade execution?
syminfo.mintick represents the smallest possible price increment for a given asset. Using it in stop orders ensures entries trigger immediately upon breaking the Donchian band, avoiding missed opportunities due to rounding or lag.
Is this strategy suitable for live trading?
While backtests provide insights, live markets involve slippage, liquidity issues, and emotional factors. Always paper-trade first and validate performance across multiple market conditions before going live.
Why use a 200-period EMA as a filter?
The 200-period EMA is widely recognized as a benchmark for long-term trend direction. It helps filter out countertrend breakouts, increasing the probability of successful trades in trending markets.
How can I make my strategy more robust?
Avoid curve-fitting by testing across different timeframes and assets. Use walk-forward analysis and out-of-sample testing. Focus on consistent performance rather than peak returns.
👉 Start building your own edge in the market with powerful tools and insights
By mastering Pine Script fundamentals like conditional logic, plotting visuals, and order execution, you gain full control over your trading systems. The DC/EMA Strategy demonstrated here serves as a practical template—you can adapt it with additional filters (RSI, volume) or apply it to other assets like crypto or commodities.
Whether you're aiming for systematic trading or deeper market understanding, coding strategies in Pine Script is a valuable skill that bridges analysis and action.