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)

FAQs

Is Pinescript good for backtesting? ›

Backtesting is a highly valuable tool for traders, and Pine Script can be used to perform it effectively. It's like having the power of time travel, but specifically designed for trading!

How do you back test trading strategy in TradingView? ›

Open a Chart: Visit TradingView and open the desired chart of the financial instrument you wish to backtest. Bar Replay Tool: On the top-right side of the chart, find the Bar Replay icon. Setting Start Point: Move the cursor to where you wish to start your backtest and click to set the starting point.

How difficult is the pine Script? ›

Compared to other programming languages, Pine Script is a lightweight script, designed to interact with TradingView in as few lines as possible. Many users compare it to Python, but traders experienced with any programming language should have an easy time learning Pine Script.

How long does it take to learn Pinescript? ›

You could theoretically learn Pine Script in a day and you don't need to look anywhere else.

How much backtesting is enough? ›

When you are backtesting a strategy on a higher timeframe, you will have to go back 6 to 12 months. Ideally, you want to end up with 30 to 50 trades in your backtest to get a meaningful sample size. Anything below 30 trades does not have enough explanatory power.

What is the most used strategy in TradingView? ›

The trading system is a trend-following strategy based on two moving averages (MA) and Parabolic SAR (PSAR) indicators. How it works: The strategy uses two moving averages: a fast MA and a slow MA. It checks for a bullish trend when the fast MA is above the slow MA and the current price is above the fast MA.

How do you get deep backtesting on TradingView? ›

How does Deep Backtesting work?
  1. Add a strategy to the chart.
  2. Make sure all settings are correct.
  3. Switch to the Deep Backtesting mode.
  4. Select the time interval on which you want to calculate and generate the report.

What is the best way to backtest a trading strategy? ›

How to backtest a trading strategy
  1. Define the strategy parameters.
  2. Specify which financial market​ and chart timeframe​ the strategy will be tested on. ...
  3. Begin looking for trades based on the strategy, market and chart timeframe specified. ...
  4. Analyse price charts for entry and exit signals.

Does TradingView have a strategy tester? ›

How can I analyze strategy results? When you add a strategy to the chart, additional information will appear in the Strategy Tester tab and can show you a report of your strategies results.

What are the limitations of pine scripts? ›

Scripts can contain up to 1,000 variables in each of its scopes. Pine scripts always contain one global scope, represented by non-indented code, and they may contain zero or more local scopes.

Can a pine script execute trades? ›

Pine Script™ strategies simulate the execution of trades on historical and real-time data to facilitate the backtesting and forward testing of trading systems.

Who uses Pine script? ›

Traders can use Pine Script to develop and backtest their trading strategies directly on the TradingView platform. By coding their strategies in Pine Script, traders can automate their buy and sell signals based on predefined criteria, such as price movements, volume patterns, and technical signals.

Is learning pine script worth it? ›

Pinescript was the first coding language I learned and the only coding language I am actually proficient in. However, it has helped me better understand and get a grasp on other languages like Python, and even languages that I have used before such as R.

What language is PineScript based on? ›

Pine script was designed to be lightweight, and in most cases, you can achieve your objectives with fewer lines of code compared to other programming languages. It is not based on any particular language, but if you've used Python, you'll tend to pick it up quickly and notice similarities.

What is the pine script strategy? ›

A strategy is a Pine script that can send, modify and cancel buy/sell orders. Strategies allow you to perform backtesting (emulation of a strategy trading on historical data) and forwardtesting (emulation of a strategy trading on real-time data) according to your algorithms.

What is the best programming language for backtesting? ›

A compiled language (such as C++) is often useful if the backtesting parameter dimensions are large. Remember that it is necessary to be wary of such systems if that is the case!

What is the best library for backtesting? ›

VectorBT: fastest backtesting library

The fastest python library for backtesting trading strategies is VectorBT. Even though it is a vector-based engine, VectorBT has the advantage of incorporating recursive features, such as trailing stop losses, which are commonly unavailable on these backtesters.

Which software is best for backtesting trading strategies? ›

Best Backtesting Software for Traders
  • TrendSpider: Best No-code Backtesting & Pattern Recognition.
  • Trade Ideas: Best Blackbox AI Backtesting & Auto-trading.
  • Tradingview: Best Backtesting & Auto-trading Globally.
  • MetaStock: Best Chart Backtesting & Forecasting.
  • Tradestation: Great Backtesting For Tradestation Clients.

Top Articles
Hard life? Wouldn’t you rather be Wealthy?
15 Rarest and Most Valuable 2 Dollar Bills Worth Money
Moon Stone Pokemon Heart Gold
Yogabella Babysitter
Coffman Memorial Union | U of M Bookstores
BULLETIN OF ANIMAL HEALTH AND PRODUCTION IN AFRICA
Washington Poe en Tilly Bradshaw 1 - Brandoffer, M.W. Craven | 9789024594917 | Boeken | bol
Costco Gas Foster City
Spoilers: Impact 1000 Taping Results For 9/14/2023 - PWMania - Wrestling News
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
3S Bivy Cover 2D Gen
Pay Boot Barn Credit Card
Craigslist West Valley
Rural King Credit Card Minimum Credit Score
Little Caesars 92Nd And Pecos
Betaalbaar naar The Big Apple: 9 x tips voor New York City
Knock At The Cabin Showtimes Near Alamo Drafthouse Raleigh
SN100C, An Australia Trademark of Nihon Superior Co., Ltd.. Application Number: 2480607 :: Trademark Elite Trademarks
How Taraswrld Leaks Exposed the Dark Side of TikTok Fame
Craigslist Panama City Beach Fl Pets
Mynahealthcare Login
Bfsfcu Truecar
Reserve A Room Ucla
Mobile crane from the Netherlands, used mobile crane for sale from the Netherlands
*!Good Night (2024) 𝙵ull𝙼ovie Downl𝚘ad Fr𝚎e 1080𝚙, 720𝚙, 480𝚙 H𝙳 HI𝙽DI Dub𝚋ed Fil𝙼yz𝚒lla Isaidub
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
Christmas Days Away
Datingscout Wantmatures
The Hoplite Revolution and the Rise of the Polis
Craigslist Car For Sale By Owner
Bimar Produkte Test & Vergleich 09/2024 » GUT bis SEHR GUT
Geology - Grand Canyon National Park (U.S. National Park Service)
Cbs Fantasy Mlb
Cox Outage in Bentonville, Arkansas
WorldAccount | Data Protection
Restored Republic May 14 2023
How Many Dogs Can You Have in Idaho | GetJerry.com
Man Stuff Idaho
Who Is Responsible for Writing Obituaries After Death? | Pottstown Funeral Home & Crematory
Kent And Pelczar Obituaries
Is Ameriprise A Pyramid Scheme
Atu Bookstore Ozark
Kjccc Sports
American Bully Puppies for Sale | Lancaster Puppies
Lesly Center Tiraj Rapid
A jovem que batizou lei após ser sequestrada por 'amigo virtual'
Food and Water Safety During Power Outages and Floods
Deshuesadero El Pulpo
Skyward Login Wylie Isd
Kenmore Coldspot Model 106 Light Bulb Replacement
O'reilly's Eastman Georgia
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.