Building and Back-Testing Algorithms in TradingView with PineScript (2024)

Building and Back-Testing Algorithms in TradingView with PineScript (3)

TradingView has one of the best charting tools and is used globally very widely. The best part of this platform is the ability to code your own plugin (or choose from the wide range of available plugins).

The Pine Script is the programming language, we use to create the charting plugin. In this tutorial, you will learn how to create a charting plugin with a simple strategy, and then we will code it to backtest the data on any chart and any timeframe.

The beuty of TradingView is, with just a few clicks, you can test your trading algorithm hypothesis in multiple stocks and multiple time frames, and come up with the best possible and most profitable combination for trading/investing.

We will understand things in the following order:

  1. Understand the Algorithm
  2. Pine Script Basics for our Algorithm
  3. Creating a new TradingView Plugin
  4. Improvising the Algorithm Logics
  5. Analyzing and Back-testing Data
  6. Optimizing for Maximum Profits
  7. Conclusion

We will start with a simple algorithm with one of the popular technical indicators Average Directional Index (ADX). Once you understand how it is being created, you can think of using it with any other indicator.

Simply saying, this indicator consists of three things, ADX which shows the total strength of the dominant player, Plus DI (PDI) which shows the strength/dominance of Buyers, and Minus (or Negative) DI (MDI) which shows the strength of sellers.

Building and Back-Testing Algorithms in TradingView with PineScript (4)

Now the conditions for the Algorithm are:

  1. In the previous candle, the ADX line should be below both PDI and MDI
  2. For Buy condition, on the current candle PDI should be above the MDI and ADX line should be crossing upwards on the MDI
  3. For Sell condition, on the current candle, MDI should be above the PDI and ADX line should be crossing upwards on MDI
  4. The first cross with PDI (will happen mostly) or MDI (a few times) after the entry should be our exit strategy to exit the trade.

To make it more clear, look at the above image. There are at least two times the ADX line moved significantly higher, but it is only the second time when ADX crossed from the bottom. Or in another word, previously ADX was below both PDI and MDI before giving an entry signal.

// Keep it customizable
len = input(14, minval=1, title="DI Length")
lensig = input(14, title="ADX Smoothing", minval=1, maxval=50)
// Get ADX, PDI and MDI values
[plus, minus, adx] = dmi(len, lensig)
// Showing on Graph
plot(adx, color=color.black, title="ADX")
plot(plus, color=color.green, title="PDI")
plot(minus, color=color.red, title="MDI")

As you can see in our code, we have divided the code into three parts. The first part which uses input() function is used for variable data which a user can change from the plugin interface on TradingView.

The lines starting with // are comments and not actual code. They are just there for better readability.

The ADX indicator requires two settings, the first length of the smoothening length. We keep 14 for them both by default, but you can experiment with them in the 5th section — Optimizing the algorithm.

In the second logic, we are getting actual values of ADX, PDI, and MDI from a built-in function dmi(). These values will be stored in variables adx, diplus and diminus.

In Pine Script, variables sometimes are series by default. For example adx, plus and minus are series and by default holds value for current or last candle. If you need value of previous candles, you can use them like adx[1], adx[2], and so on.

And in the third logic, we are using plot() the function, which actually draws the graph on the plugin screen.

Creating a new plugin is easy. Go to your Pinescript Chart page and then hit refresh. When a page is loaded, you need to click Pine Editor at the bottom. It will show you an empty template with two ‘coding’ lines written.

Building and Back-Testing Algorithms in TradingView with PineScript (5)

There are two most important things we need to keep at the top of every plugin. First is //@version=4 a line and second is either study() function or strategy() function. Pine Script has evolved over years, and the latest version is 4 and we keep it mentioned to use newer features.

The difference between a study and a strategy in TradingView is that study is just for showing graphs, however, strategy has more functions that are used for order entry, exit, and such conditions.

The strategy has a few more options in the TradingView, giving us additional reporting on how a strategy of buying/selling is performing. We will look into strategy in the Improvising section.

A study() or strategy() the function requires at least a name, which is shown at multiple places. For now, you can have something like: study(title="Directional Movement Index", shorttitle="DMI").

Important Conditions

We will code important conditions and we will keep them stored in some variables. Have a look at the code:

// Previous to current candle, adx should be lowest
adxWasBelow = adx[1] < plus[1] and adx[1] < minus[1]
// Rule 2
diPositive = plus > minus
diNegative = not diPositive
// Rule 3
inBuyZone = adx >= minus and adx <= plus
inSellZone = adx >= plus and adx <= minus
// Condition when Rule 2 and Rule 3 are matching
buyCond = diPositive and inBuyZone
sellCond = diNegative and inSellZone

Visual Hints

The first improvement we would do is getting a visual hint of an entry and an exit on the graph itself. There are many ways to do that, but I would like something simple as filling a background color.

As long as we are in the BUY condition, we will paint the region between PDI and MDI with green color, and for SELL with red color.

// Have a variables assigned to plotted graph
p = plot(plus, color=color.green, title="+DI")
m = plot(minus, color=color.red, title="-DI")
// Choose color based on condition
fillColor = buyCond ? color.green : (sellCond ? color.red : na)
// Fill the color
fill(p, m, color = fillColor)

You can understand the above code from the comments, except for fillColor, if you are new to programming. It simply says:

If BUY condition is met, use green color, otherwise, if SELL condition is met use red color. If neither condition is met, don’t use any color.

Building and Back-Testing Algorithms in TradingView with PineScript (6)

From the above image, all the places where it showed colors may be correct, but for us, the only correct trades are those for which our ALL conditions are met.

And the reason why incorrect trades are appearing is we have not yet included the first condition of ADX, which basically says, ADX should be below both PDI and MDI before starting the entry, and should cross above.

Since this condition is only checked on the first entry position, we have to change the logic to support it in Pine Script. Have a look at these changes:

// New Conditions
noTradeZone = (adx < plus and adx < minus) or (adx > plus and adx > minus)
adxJustCrossed = cross(adx, plus) or cross(adx, minus)
// At the very beginning
var traded = false
// All three conditions met
if (adxWasBelow and (sellCond or buyCond))
traded := true
// Continue until exit condition
if (traded and not traded[1] and not adxJustCrossed)
traded := true
// Reset Condition
if noTradeZone
traded := false
// Finally Fill in only if its valid one
fill(p, m, color = traded ? fillColor : na)

You might want to read the above code twice, but basically what we did above is created a new variable traded which will be trueonly when ALL algorithmic conditions are met, and will continue to be true until there is an exit condition.

We had to do this much because our algorithmic condition “ADX should be below both PDI and MDI before the entry” is required to be true only for the first candle.

As mentioned earlier, to see the statistics, we need to convert our study into strategy like this:

// study(title="Directional Movement Index", shorttitle="DMI") strategy(title="DMI Strategy", shorttitle="DMIStrat")

Further, we will need to add strategy conditions to enter and exit the trades. For these, we will need to make use of strategy.entry() and strategy.close() functions.

// Trade Conditions
enterLong = traded and buyCond
exitLong = not traded
enterShort = traded and sellCond
exitShort = not traded
// Strategize LONG conditions
strategy.entry("long", true, 1, when = enterLong)
strategy.close("long", when = exitLong)
// Strategize SHORT conditions
strategy.entry("short", true, 1, when = enterShort)
strategy.close("short", when = exitShort)
Building and Back-Testing Algorithms in TradingView with PineScript (7)

Now, let us analyze the outputs. I ran the plugin data on NSE Nifty Future scrip in 1 minute and 5 minutes. In 1 minute the net profit was 1.92% after 353 trades in which trade was profitable 51.57% times.

Now, I just changed the timeframe to 5 minutes, and now I can see the net profit jumped to 87.08% and that too in 289 trades, with 53.29% profitability.

Building and Back-Testing Algorithms in TradingView with PineScript (8)

The point I am trying to make it here, even if the algorithm is the same, by just changing the time frame, a loss-making strategy in one time frame can become hugely profitable in another time frame.

To optimize the performance of the strategy we can do the following things:

  1. Switch to different time frames
  2. Use only BUY strategy or SELL strategy
  3. Change the scrip (stock / index)
  4. Change the quantity
  5. Change the input parameters

The list is long and you can optimize the performance by many trials and errors. For example, switching to 5 minutes got 87% profitability. I improved it further by some experimentation with input parameters.

Building and Back-Testing Algorithms in TradingView with PineScript (9)

With the new changes, I increased net profit to 93.22% and profitability percent also increased to 54.61%, and similar to the profit factor. Now you know which timeframe you should use on what scrip, to be more profitable.

When we are looking for a profitable strategy, it makes a lot of sense to first back-test it. To do so, TradingView and PineScript are some of the best options around.

Every day, the internet is filled with so many strategies and methods that claim to be profitable, but betting your money on just assumptions is not the proper way.

I would suggest everybody write the back-testable strategy and test its profitability concerning scrips, time-frames and optimal settings, and so on.

I hope that the above tutorial will inspire you to create your own plugin and test your assumption before you bet your money on it. If you have any questions, please leave a comment.

Building and Back-Testing Algorithms in TradingView with PineScript (2024)
Top Articles
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6234

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.