Tradingview Pine Script Beginner Tutorial:
Tradingview is fast becoming one of the most popular charting tools in the industry. With its’ easy to use drawing tools, indicators and social network integration, traders have a complete set of tools to perform technical analysis and share ideas. In addition to this, Tradingview have also developed their own scripting language that allows traders to create custom indicators and develop strategies.
Before I go into the code, first things first. If you have not already, I suggest you sign up for an account at the Tradingview website. Once you have an account you will be able to save your scripts.
When I started to take a look at Tradingview for backtesting one thing that immediately struck me is how simple the platform is. This makes it an excellent choice for us backtest rookies to get started. Not only is the pine script language quite simple to understand, Tradingview also make accessing help information a breeze.
For example:
- Mouse over functions for help. Provides access short form help information.
- Builtin version control. Every time you hit the save button, Tradingview saves the script as a new version. This makes life very easy if you accidentally go too far off track and need to revert.
- CTL + Click to see detailed documentation (option + click for Mac users). One nice thing about the popup help window is that you can still type in the script pane behind it. No need to constantly open and close the help screen as you work through input parameters of a function.
Gallery (click on an image to enlarge it)
One negative I noticed (at the time of writing) is that I could not find an option to print strings to the output console. This can make debugging a little tricky. Especially in instances where you want to check the value of a certain variable.
The Platform
If you are completely new to trading view, it would be helpful to go over where everything is and how to access the pine script code editor.
First load up a chart:
- Open Tradingview (Use this affiliate link if you want to be kind – http://tradingview.go2cloud.org/SHpH)
- Click on chart on the home page
- If this is the first time you have used the charting feature, you will be taken to a chart. If not, you will get a drop down menu with an “unnamed” chart template. If that applies to you, click on that.

- The pine editor pops up from the bottom of the page. Click on the pine editor tab.
When creating a strategy, do not start from the default pine script page. This template is intended for indicators. You can get a better template for strategies. The default indicator template looks like this:

As you can see it is a bit spartan. To get a strategy based template, click on “New –> Blank strategy script“. This will provide a basic template to get you up and running.

This will give you a code template that looks like this:

You can see this actually gives you everything you need to run a script:
- The strategy is initialized
- A trigger to go long is provided
- A trigger to go short is provided
If you want, you can go ahead and press the “Add to Chart” button and consider yourself done. However, if you want to go just a little further and make some edits, keep reading on.
The Strategy
This strategy we are going to implement follows the same rules as in the Backtrader: First Script. I have done this for consistency and so that those still deciding which platform to select for backtesting can have an apples to apples introduction comparison. It is a super simple long only strategy that aims to stay on the right side of a long bull market in equities.
Entry
- Long Entry when RSI < 30
Exit
- Long Exit when RSI > 70
Trade Management and Position Sizing
- No trade management shall be implemented. No scaling in / out. Just simple buying and selling with a single open position at a time.
- Position size wise, we will keep things simple and keep the Tradingview default which is to buy and sell 1 contract.
Indicator Settings
- Period = 21
- We will use a longer look back period than the default 14. In theory this should result in less false signals and price should have to come down / rise much further before it is considered overbought / over sold.
The Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//@version=3 strategy("Simple RSI", overlay=true, initial_capital=10000, currency='USD') fromYear = year > 2014 toYear = year < 2016 longCondition = rsi(close, 21) < 30 if (longCondition and fromYear and toYear) strategy.entry("Long 1", strategy.long) closeCondition = rsi(close, 21) > 70 if (closeCondition) strategy.close("Long 1") |
Look how short and sweet that code is! If you compare this to the Backtrader: First Script, you will appreciate just how much easier it is to get up and running! What you give up in features and control, you get back in simplicity and time.
If you compare it to the blank strategy template shown above, you might notice the following changes:
- The short entry has been converted to a close function so that we do not go short (in accordance with the strategy rules)
- The SMA crossover functions have been changed to check whether an RSI indicator is above or below a certain level.
- The if statement for the long condition has been extended.
First lets take a little look at the Initialization of the strategy and talk about another really nice feature. There are very few mandatory parameters needed when setting up the strategy. In fact, only the title is required and this is so the strategy can be saved. All of the strategy parameters can be edited visually via a form in the strategies tab. Pretty nice right? Well it gets better, the parameters can be adjusted here at anytime and the results in the performance summary automatically update as you make the changes.
During the initialization of the strategy, I added some optional parameters:
1 |
strategy("Simple RSI", overlay=true, initial_capital=10000, currency='USD') |
These option parameters (initial_capital and currency) set the default values you will see when pressing the configuration button in the strategy tester panel:

Note in the above image the values for Initial Capital and Base Currency.
Another change I made, was to create some variables that are used to assess whether the year is above or below a particular number. I did this as I prefer to focus on particular periods of time when back testing so that a long profitable run does not mask a period of serious under performance. It is a personal preference. I would not like to sit through years of under performance even if a strategy works over 30 years! 😃
1 2 |
fromYear = year > 2014 toYear = year < 2016 |
What is happening here?
Each time a new candle is made, a check is done to see if the year is greater than 2014 or less than 2016. If it is, the Boolean value “true” is saved to the fromYear and toYear variables. This can then be used in the IF statement to check whether we can consider opening a trade:
1 2 |
longCondition = rsi(close, 21) < 30 if (longCondition and fromYear and toYear) |
We are checking to see IF the the RSI is below 30 AND the date is after 2014 AND the date is before 2016.
The closing of the strategy is more simple. It just waits to see if we are above 70 and closes it.
Using this code on Tradingview
Copy the code then click here to open up a chart window on Tradingview. Paste it into the pine script editor, Now you can click on the add to chart button in order to start the test and see visually where the strategy bought and sold.
Don’t forget to click save, so you can come back to the strategy later! You can apply this strategy to any instrument. All loaded strategies appear in the strategies tab on the bottom pane of the charting area. To load strategies, you can select “open” from the pine editor tab.
The results
Time for the grand results……..A net profit of $10.56! Not so impressive, but that is not the point. We are now setup and backtesting on Tradingview!

Have a play around with the code, change the indicators, change the strategy parameters and get used to the platform. I hope this post helps in getting you started!
[…] 6 – Tradingview: First Script […]
[…] 7 – Tradingview: First Script […]
[…] 7 – Tradingview: First Script […]
[…] 9 – Tradingview: First Script […]
Hello,
This is the given message:
Add to Chart operation failed, reason: line 8: mismatched input ‘strategy.entry’ expecting ‘end of line without line continuation’.
Waiting for your answer back (interesting topic).
Hi Matteo,
Thanks for pointing it out! It seems some white space was removed when copying and pasting.
I have updated the example script.
Appreciated.
This is awesome… if this were sold as a book on amazon I’d buy it.
Thanks for the great post!
I love TradingView’s performance stats in the strategy tester, but i don’t understand half of them. Can you add a post on what these stats mean and how to use them to determine the performance of your strategy?
That is a great idea for a post. Thanks for the suggestion.
I will add it to the “Todo” list.
Hay mate, love you work. trying to implement it into trading view, i ge the code into the pine editor and then save, apply to chart etc but never get any results from is. i see the indicator on the chart where i can edit the settings etc. not sure why im not getting the info out of it? help
Hi Shaun – Thanks for the nice feedback.
Can you post a link to your chart? You can generate a chart screenshot by clicking on the camera icon in the bottom right corner. It will be easier to visualize what you mean by seeing the indicator but no info.
I suspect it is probably your chart setup preferences in Tradingview.
Here is an example of a link to an image.
https://www.tradingview.com/x/Rs5fxTXE/
What a wonderful work. I’m a trader, but I know nothing about programming. I want to build up a strategy like “if the price stays 10% away from a moving average I’ll long, or I’ll short, and I’ll close the position when the price hits the moving average again or with a 10% stop loss. How would you do that? I’m trying to figure out, but I can’t do it. Thanks
Hi Igor,
I am a bit late to the party but I have noted this request for a future post.
Igor, if you figure that out PLEASE LET ME KNOW AS I WANT TO DO THE SAME AND I CANT!!!
Hi Lucio!
See my reply to Igor – Since there it appears to be in demand, I may consider this strategy for a future post.
been trying for weeks to do something similar with no luck. i shall keep trying but coding isnt my strong point
I tried entering this script and it returned no data. Why?
Hey Jason
Are you testing on daily data? The script only tests a specific range between 2014 and 2016.
To make this more clear, make sure you have set your candles to Daily candles or greater.
This is at the top of the screen, directly to the right of the symbol / pair on the left.
Directly above the chart, and the chart information that has the o, h, l, and c stuff.
This is NOT the 1D 5D 1M thing at the bottom of the chart, above the pine editor, that just effects the view, not the candles.
Hello Rookie1,
I need your help to code something similar to this. I like to have this parameters you gave:
longCondition = rsi(close, 21) 70
if (closeCondition)
strategy.close(“Long 1”)
This codes enters a position when the market is leaving the RSI 70-30 zone, but I want the trade to enter a position when the market is entering the 70-30 RSI zone. So not when is getting out of the RSI 70-30 zone but when is getting in the RSI 70-30 zone.
Also, when in the closing condition, the order closes in the RSI 70 zone and I need a “or” condition for closing in 15pips TP. Also I want to have a SL command at 10 pips.
Could you help me?
Agustin A.
Thank you so much for your sharing. Very very helpful!!!
Can we code conditions (RSI) satisfying two time frames .Eg. crossing 70 in both tome frames and exit after 4 bars reenter again the condition meets
hi sir . A small addition
1. since the from year is greater than 2014 and less than 2016 , does that mean it will only check for long trades in 2015. If yes , could we have just used fromYear = = 2015 ?
Thank you so much for this!
Could you possibly show how I could add on another indicator?
I would like to see this script execute along with the MACD indicator at the same time.
Is this possible?
Appreciate all you’ve done and any feedback you can provide.
This is what I have so far but I get syntax error on line 27 input (2 lines above last line in script)
strategy(“Simple RSI and MACD”, overlay=true, initial_capital=10000, currency=’USD’)
fromYear = year > 2017
toYear = year < 2019
// Create inputs
fastLen = input(title="Fast Length", type=integer, defval=12)
slowLen = input(title="Slow Length", type=integer, defval=26)
sigLen = input(title="Signal Length", type=integer, defval=9)
// Get MACD values
[macdLine, signalLine, _] = macd(close, fastLen, slowLen, sigLen)
// Plot MACD values and line
plot(series=macdLine, color=#6495ED, linewidth=2)
plot(series=signalLine, color=orange, linewidth=2)
hline(price=0)
longCondition = (rsi(close, 21) 70) and (crossunder(macdLine, signalLine))
if (shortCondition)
strategy.close (“Long 1”)
Hello all,
Has anyone used a strategy(not study) to fire alert messages programatically containing {{strategy.order.action}} or {{strategy.order.contracts}} dynamic values using the {{strategy.order.alert_message}} ? I have used and it works.
However, the challenge is to pass the actual values instead of text. Am able to use the {{strategy.order.alert_message}} to pass the static message(does not return the actual values, just the text!) to the Message Box, while the above dynamic values does not get passed.
Here is the code, am using:
message_long_entry = input(“[{“E”:”EXCH”,”IT”:”SBIN”,”Q”:”{{strategy.order.contracts}}”,”OT”:”MARKET”,”P”:”MIS”,”TT”:”{{strategy.order.action}}”,”VL”:”DAY”,”AT”:”BROKER”}]”)
strategy.entry(“long”, strategy.long, when=longsubcondition, alert_message = message_long_entry)
Any pointers or guidance is much much appreciated from the experts and professionals.