Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (2024)

Here is a Tradingview Pine Script Strategy.

TradingView is a popular tool with many traders due to its vast array of tools and features. TradingView uses its native code language, Pine Script, to implement indicators and backtest trading strategies.

In this article, we’ll go through some basics of using Pine Script in backtesting by going through a step-by-step process. Follow this process, and you will be able to successfully backtest using Pine Script.

As an example, we will be showing these steps using a Donchian Channels / EMA strategy we developed in our article on Robotics and AI Trading Strategies (BOTZ ETF Backtest). This strategy uses the Donchian Channels and Exponential Moving Average indicators.

Table of contents:

Tradingview Pine Script Strategy

Here are the trading rules of the strategy we will be implementing in Pine Script:

  • On the daily timeframe, when the price crosses above the upper band of the Donchian Channels, and the price is above the EMA line, we go long (buy) immediately.
  • On the daily timeframe, when the price crosses below the lower band of the Donchian Channels, we close our position (sell) immediately.

This means that we are using the daily timeframe, but trades are entered or exited immediately when the price crosses the Donchian Channels band during the day. We do not wait for the daily close. We achieve this by placing stop orders one tick outside the DC band.

We are using the following variables in this tutorial:

Trading Rules – Tradingview Pine Script Strategy

THIS SECTION IS FOR MEMBERS ONLY. _________________Click Here To Get A Trial Access Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (1)Click Here To Get Access To Trading Rules

We’ll call this combination of variables the ‘DC/EMA Strategy’.

You can easily achieve variables 1 and 2 by searching the BOTZ ETF in TradingView and setting the timeframe to daily. In this tutorial, we will focus on the last three variables, starting with number 3: how to add a strategy to our chart.

Donchian Channel / EMA Strategy in TradingView

We begin by applying one of TradingView’s pre-made strategies.

The Donchian Channels strategy is available under the name ‘ChannelBreakOutStrategy’:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (2)
Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (3)

We adjust the ‘Length’ input to 3 in the input interface:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (4)

Further, we set ‘Order size’ to 100% of equity, to give us fully compounded end results:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (5)

This takes care of our basic Donchian Channels strategy, without any need to interact with Pine Script directly. Let’s move on to variables 4 and 5.

Donchian Channels/EMA Trading Rules in Pine Script

The premade ChannelBreakOutStrategy on TradingView lacks some of the features needed to make this strategy work according to the above trading logic. We’ll need to add these in Pine Script. Fortunately, this is a relatively easy operation and a great opportunity for learning some basics of Pine Script editing.

We will need to add three things in Pine Script to make this work. These are:

  • Chart visualization (plotting) for the Donchian Channels.
  • EMA200 filter
  • ‘Long only’ filter

Modifying source code in Pine Script

In order to modify the ChannelBreakoutStrategy, we start by clicking the ‘Source code’ button next to the strategy in the chart:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (6)

We then make a copy of the current script by pressing the ChannelBreakOutStrategy itself and giving the new script a fitting name:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (7)

With this out of the way, we are ready to start editing the code.

Plotting the Donchian Channels

Copy/paste the following Pine Script code snippet at the bottom of the coding window, and click ‘Save’.

plot(upBound, color=color.green, linewidth=1, title="Upper Band")plot(downBound, color=color.red, linewidth=1, title="Lower Band")

This makes sure our Donchian Channels are plotted onto the chart.

Filtering trades with an Exponential Moving Average

Copy/paste the following Pine Script code snippet right below the ‘downBound = ta.lowest(low, length)’ line:

emaLength = input.int(title="EMA Length", minval=1, maxval=1000, defval=200)emaFilter = ta.ema(close, emaLength)

Then add the following snippet at the bottom of the script:

plot(emaFilter, color=color.blue, linewidth=1, title="EMA Filter")

Then click ‘Save’. This defines our Exponential Moving Average (EMA) indicator, with a default value of 200 that can be changed in the input interface and adding plotting for the EMA.

Long trades only

Copy/paste the following Pine Script code snippet right below the ‘emaFilter = ta.ema(close, emaLength)’ line, and click ‘Save’:

longOnly = input.bool(title="Long Only", defval=true)

This makes sure the script only places long trades in backtesting. This option can be disabled in the input interface.

Changing the trade logic

The following code snippet should be copied and used to replace the remaining piece of code, starting with the ‘if (not na(close[length]))’ line, and ending with the ‘//plot(strategy.equity, title=”equity”, color=color.red, linewidth=2, style=plot.style_areabr)’ line (do not replace the plotting for the Donchian Channels and EMA we added earlier):

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)

Click “Save”.

This defines our new trade logic, making use of the EMA and Long Only variables we added earlier. The top half defines long trades, and the bottom half defines theoretical short trades, if we choose to disable the Long Only filter.

You might also notice how the script uses ‘syminfo.mintick’ to define the smallest possible price movement beyond the upper or lower DC bands as the entry and exit conditions.

Adding Pine Script to the chart

You should now have the following script before you in Pine Editor:

//@version=5strategy("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")

You may of course simply copy/paste this entire script without going through the above steps. However, we encourage you to do the work, as this will enhance your understanding of Pine Script.

In order to see the results, click ‘Add to chart’. Minimizing the Strategy Tester panel for the moment, you will now be able to see the Donchian Channels (green and red lines), the EMA200 (blue line), as well as where orders are generated:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (8)

Before you consider applying this in live trading, ensure that you understand how the trading logic works in relation to what is going on in this chart.

BOTZ Donchian Channel Strategy Backtest Equity Curve

We can now view the equity curve for the BOTZ DC/EMA Strategy we just created, using DC3 and EMA200 as inputs.

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (9)

We won’t be discussing the results here, as this is the subject of another article, and our focus here is to learn about the uses of Pine Script.

The important thing for now is that you are able to vary the inputs for all variables in the input interface, and see the backtesting results for yourself:

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (10)

Trying various combinations, along with viewing the backtesting results for each combination, enables you to do the trading optimization involved in testing the robustness of your strategy.

Tradingview Pine Script Strategy (Rules And Backtest) - Quantified Trading Strategies (2024)
Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 6665

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.