Tradingview Pine Script Strategy
|

Tradingview Pine Script Strategy (Rules And Backtest)

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.

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 Access 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’:

How To Make A Successful Trading Strategy Using Pine Script on TradingView

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

How to backtest TradingView

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

How to backtest using Pine Script

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:

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

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=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")

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 strategy backtest

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. 

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:

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.

Similar Posts