Tradingview rsi script

Tradingview rsi script DEFAULT
//@version=4 //// Pine Script v4// @author BigBitsIO// Script Library: study(title, shorttitle, overlay, format, precision)// study(shorttitle = "Smoothed RSI", title="Smoothed RSI", overlay=false) // Improved with HMA, DEMA and TEMA and source options for MAs// MA#Period is a variable used to store the indicator lookback period. In this case, from the input.// input - = input(14, title="RSI Period")RSIType = input(title="RSI Type", defval="RSI", options=["RSI"])RSISource = input(title="RSI Source", type=input.source, defval=close)RSIResolution = input(title="RSI Resolution", defval="00 Current", options=["00 Current", "01 1m", "02 3m", "03 5m", "04 15m", "05 30m", "06 45m", "07 1h", "08 2h", "09 3h", "10 4h", "11 1D", "12 1W", "13 1M"])RSIVisible = input(title="RSI Visible", type=input.bool, defval=true) // Will automatically hide crossBovers containing this MASmoothedPeriod = input(17, title="Smoothed Period")SmoothedType = input(title="Smoothed Type", defval="DEMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA", "VWMA"])SmoothedVisible = input(title="Smoothed Visible", type=input.bool, defval=true) // Will automatically hide crossBovers containing this MASmoothedHistPeriod = input(8, title="Smoothed Histogram Period")SmoothedHistType = input(title="Smoothed Histogram Type", defval="DEMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA", "VWMA"])SmoothedHistVisible = input(title="Smoothed Histogram Visible", type=input.bool, defval=true)OS = input(25, title="Oversold Level", maxval=100, minval=1, step=1)OB = input(75, title="Overbought Level", maxval=100, minval=1, step=1)// MA# is a variable used to store the actual moving average value.// if statements - MA functions - (must search for appropriate MA)// custom functions in pine -, OSCSource, OSCPeriod) => if OSCType == "RSI" rsi(OSCSource, OSCPeriod)ma(MAType, MASource, MAPeriod) => if MAType == "SMA" sma(MASource, MAPeriod) else if MAType == "EMA" ema(MASource, MAPeriod) else if MAType == "WMA" wma(MASource, MAPeriod) else if MAType == "RMA" rma(MASource, MAPeriod) else if MAType == "HMA" wma(2*wma(MASource, MAPeriod/2)-wma(MASource, MAPeriod), round(sqrt(MAPeriod))) else if MAType == "DEMA" e = ema(MASource, MAPeriod) 2 * e - ema(e, MAPeriod) else if MAType == "TEMA" e = ema(MASource, MAPeriod) 3 * (e - ema(e, MAPeriod)) + ema(ema(e, MAPeriod), MAPeriod) else if MAType == "VWMA" vwma(MASource, MAPeriod)res(MAResolution) => if MAResolution == "00 Current" timeframe.period else if MAResolution == "01 1m" "1" else if MAResolution == "02 3m" "3" else if MAResolution == "03 5m" "5" else if MAResolution == "04 15m" "15" else if MAResolution == "05 30m" "30" else if MAResolution == "06 45m" "45" else if MAResolution == "07 1h" "60" else if MAResolution == "08 2h" "120" else if MAResolution == "09 3h" "180" else if MAResolution == "10 4h" "240" else if MAResolution == "11 1D" "1D" else if MAResolution == "12 1W" "1W" else if MAResolution == "13 1M" "1M"cid(Current, Past, TwoBack) => if Current > Past and Past < TwoBack "Up" else if Current < Past and Past > TwoBack "Down" else "None"RSI = security(syminfo.tickerid, res(RSIResolution), osc(RSIType, RSISource, RSIPeriod)) Smoothed = ma(SmoothedType, RSI, SmoothedPeriod)// plot - This will draw the information on the chart// plot - ? RSI : na,, linewidth=1, title="RSI")plot(SmoothedVisible ? Smoothed : na,, linewidth=1, title="Smoothed")Hist = RSI - Smoothedplot(Hist, title="Histogram", style=plot.style_columns, color=(Hist>=0 ? :, transp=25 )SmoothedHist = ma(SmoothedHistType, Hist, SmoothedHistPeriod)plot(SmoothedHistVisible ? SmoothedHist : na, title="Smoothed Histogram", style=plot.style_line, color=color.yellow, transp=25 )SmoothedChange = cid(Smoothed, Smoothed[1], Smoothed[2])plotshape("Up" == SmoothedChange ? -15 : na, style=shape.arrowup,, location=location.absolute, editable=false)plotshape("Down" == SmoothedChange ? 15 : na, style=shape.arrowdown,, location=location.absolute, editable=false)OBl = hline(OB, title="Overbought",, linewidth=1, editable=false)OSl = hline(OS, title="Oversold",, linewidth=1, editable=false)//Midpoint = hline(((OB + OS) / 2), title="Midpoint",, linewidth=1)Max = hline(100, title="Max",, linewidth=0, editable=false)Min = hline(0, title="Min",, linewidth=0, editable=false)//fill(OSl, OBl,, OSl, title="Oversold Area",, transp=90)fill(OBl, Max, title="Overbought Area",, transp=90)

Bundle multiple RSI indicatores in one tradingview panel

08 Mar 2018

Reading time ~2 minutes


The web portal Tradingview is a very sophisticated tool, to display for example trends in stock or cryptocurrency prices and and to analyze the future performance with the help of a wide variety of indicators. However, the amount of displayable indicators is tied to the license type and is also limited by the space on the screen. For both reasons, it seemed reasonable to me to combine the important oscillators “RSI” and “stochastic RSI” into one indicator panel. One possibility is using scripting.

Do you know Pine?

For this TradingView provides its own scripting language and a built-in script editor. This scripting allows the user to customize the display of the technical indicators and other functions. For more information, see PINE SCRIPT LANGUAGE REFERENCE MANUAL or Pine Script Tutorial .

The indicators

The calculation and presentation of the indicators and are similar, which makes them good candidates for grouping on a panel.

The is an indicator that reacts to changes in market prices with upward and downward movements and makes it easier to estimate the strength of the current market. For example, a value of 70 or more is considered to be overbought and signals a potential price decline, while a value of 30 or less is over-sold, indicating a potential price increase. Further details can be found here: The Relative Strength Index (RSI).


threshold values for the above-mentioned signals are more than 80 or less than 20, more information can be found here: Stochastic oscillators.

stochastic RSI

The scripting solution

The following pine script calculates both indicators and combines them into one view:

It can be copied directly into the pine editor in the tradingview chart page and added to the current chart view with :

pine editor

The result is a new panel that looks like this:

combined (stochastic) RSI

  1. Dividers instagram
  2. Serato.virtual dj
  3. 2010 sprinter 2500
  4. 2006 odyssey mpg
  5. Elasticsearch output

Trading System design -Creating Your Strategy with Tradingview’s Pine Script – Part 1

As promised, in this article, we will go through the steps to create a custom strategy, from the initial idea to the implementation of signals, stops, and targets.

The skeleton of a trading Strategy

To create a strategy programmatically is relatively simple. We need to define the Parameters and the trade rules first, followed by the position sizing algorithm, the entry commands, and the stop-loss and take-profit settings.

Visualizing the idea

Human beings are visual. We may think our trading idea is fantastic, but translating it into code may not be straightforward. It is much easier to detect the errors if we see our rules depicted on a chart.

With the parameter declarations and trade rules, we can create an indicator first, so we can see how it appears. After we are happy with the visual 

The idea

For our example, we will use a simple yet quite exciting indicator called Stochastic RSI, which applies the Stochastic study to the RSI values. This operation smoothes the RSI, and it reveals much better the turning points on mean-reverting markets, such as in Forex. Let’s see how it behaves as a naked strategy.

Diving into the process

First, you need to open an account with Tradingview. Once we are in, we create a new layout.

Then we open the Pine Editor.

It appears in the bottom left of your layout. Click on it… and it shows with a basic skeleton code.

The Stochastic RSI code.

As said, to create the Stochastic RSI indicator, we will make the RSI and then apply the stochastic algorithm to it.

1 study(title="Stochastic-RSI", format=format.price, overlay = false)

This first line declares the code to be a study, called Stochastic-RSI.  

format = format.price is used for selecting the formatting of output as prices in the study function.

Overlay = false means we desire the RSI lines to appear in a separate section. If it were a moving average to be plotted with the prices, overlay should be set to true.

RSIlength = input(14, "RSI-Length", minval=1)

We define the RSI length as an input parameter called RSI-Length.

src = input(close, title="RSI Source")

The variable src will collect the input values on every bar. The default is the bar close, but it may be modified by other values such as (o+c)/2.

myrsi = rsi(src, RSIlength)

This line creates the variable myrsi that stores the time series of the rsi.

This completes the calculation of the RSI. 

smooth_K = input(3, "K", minval=1)smooth_D = input(3, "D", minval=1)

These two lines create the smoothing values of the stochastic %K and %D. Since it comes from input, they can be changed at will.

Stochlength = input(14, "Stochastic Length", minval=1)

This code defined the variable lengthStoch, computed from the input parameter.

k = sma(stoch(rsi1, rsi1, rsi1, Stochlength), smooth_K)d = sma(k, smooth_D)

These two lines completes the calculation of the stochastic rsi.

plot(k, "K", color=color.white) - Plot a white k line plot(d, "D", - Plot a red d line.

To end this study, we will plot the overbought and oversold limits of 80 and 20, filling the mid-band with a distinctive color.

t0 = hline(80, "Upper Band", color=color.maroon)t1 = hline(20, "Lower Band", color=color.maroon)fill(t0, t1, color=color.purple, transp=80, title="Background")

The complete code ends as:


// This source code is subject to the terms of // the Mozilla Public License 2.0 at // © forex-academy //@version=4 study(title="Stochastic-RSI", format=format.price, overlay = false) RSIlength = input(14, "RSI-Length", minval=1) src = input(close, title="RSI Source") myrsi = rsi(src, RSIlength) smooth_K = input(3, "K", minval=1) smooth_D = input(3, "D", minval=1) Stochlength = input(14, "Stochastic Length", minval=1) k = sma(stoch(myrsi, myrsi, myrsi, Stochlength), smooth_K) d = sma(k, smooth_D) plot(k, "K", color=color.white) plot(d, "D", t0 = hline(80, "Upper Band", color=color.maroon) t1 = hline(20, "Lower Band", color=color.maroon) fill(t0, t1, color=color.teal, transp=80, title="Background")

This code is shown in our layout as

Stay tuned for the second part of this article, where we will evolve the Stochastic RSI into a viable strategy.


I love math, data science, and, also, financial markets. I love to write about system analysis, money management, risk, and math for traders. I hold a degree in Telecommunications Engineering by Univ. Autónoma de Madrid, and a Master in Business Administration and Marketing by Univ. de A Coruña.
Simple Backtest with Tradingview/Pine script

Pine Script (TradingView) – A Step-by-step Guide

Last Updated on January 11, 2021

Table of Contents

  1. What is Pine script?
  2. Why should I use Pine script?
  3. Why shouldn’t I use Pine script?
  4. What are the alternatives to using Pine script?
  5. How do I get started with Pine script?
  6. How to retrieve the price of Apple in Pine script?
  7. How to retrieve the SMA(20) of Apple in Pine script?
  8. How to backtest a moving average cross strategy with Pine Script?
  9. How to set take profits and stop losses?
  10. How to fire a trade on Apple when Google moves 5%?
  11. How to modify our scripts without coding?
  12. How to Plot with Pine script?
  13. How can I create a custom indicator with Pine script?
  14. Final Thoughts
Logo of TradingView and Pine Script

What is the Pine script?

Pine script is a programming language created by TradingView to backtest trading strategies and create custom indicators.

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.

Pine script code can be created within Pine editor which is a part of TradingView’s online charting platform.

Why should I use Pine script?

Built-in Data – This is a big one. Testing strategies or creating indicators in other languages involves sourcing your own data.

Not only does that mean you have to find a place to grab your data from, but you’ll also then have to format it in a certain way and this whole process can be time-consuming.

TradingView has a plethora of data available at your fingertips, ready to access with as little as one line of code. 

Easy to Learn – Pine script syntax is readable and simpler than other programming languages. 

Also, you don’t have to spend much time on error checking and handling as TradingView takes care of most of that for you.

Extensive user base and library – TradingView users have the option to publish their indicators and strategies to the TradingView library.

Having access to open source code is a great way to learn from other programmers. Also, in some cases, someone else may have already written the code for what you’re after.

» Quantopian has shut down. An alternative to consider is QuantConnect.

QuantConnect is a browser-based backtesting and algo trading platform.

Link: QuantConnect – A Complete Guide

Content Highlights:

  • Create strategies based on alpha factors such as sentiment, crypto, corporate actions and macro data (data provided by QuantConnect).
  • Backtest and trade a wide array of asset classes and industries ETFs (data provided by QuantConnect).
  • License strategies to hedge fund (while you keep the IP) via QuantConnect’s Alpha Stream.

Why shouldn’t I use Pine script?

The main reason why you wouldn’t want to use Pine script is that you’re limited to the TradingView universe.

Here are some specific limitations –

Data – If TradingView does not offer the data you’re after, you’re out of luck.

Granted, TradingView has a very comprehensive database of data feeds. But if your strategy involves trading obscure markets, price data may not be available.

This extends outside of price data. Some strategies involve economic or statistical data. TradingView does offer some data (mainly Quandl data) in this category but it is limited at this time.

If you use alternative data in your strategy, it’s probably easier to use another programming language that offers more flexibility.

External libraries – Pine script is not appropriate if you’re looking to leverage external libraries to do things like Machine learning.

There are better alternatives if your strategy relies on using data science or other third-party libraries.

What are the alternatives to using Pine script?

TD Ameritrade’s thinkorswim – this platform has a lot of similarities to Pine Script. 

It utilizes a proprietary language called thinkScript and stores price data in arrays in a similar to way to Pine script.

Data is built-in and the platform is geared towards creating custom indicators and strategies.

Ninjatrader – This platform also uses a proprietary language which is called Ninjascript. The language is not completely proprietary as it is based on C#.

Ninjatrader has a bit more flexibility as it allows you to connect to custom data feeds.

If you’re already familiar with C#, C, or C++, this might be a viable alternative.

How do I get started with Pine script?

Getting started with Pine script is really simple, there is nothing to download or install. 

If you already have an account with TradingView, simply head over to their page.

If you don’t have an account, navigate to From there you will see a sign in box in the upper right-hand corner.

There are several one-click options to sign up, or use the traditional email/password method.

Having an account allows you to save your scripts to the TradingView cloud, and provides the ability to add custom indicators to your charts.

Once signed up, launch the charting platform either by clicking on chart in the menu or by navigating to

A first look at Pine editor

Pine editor is where we will be creating our code. To launch it, click on Pine Editor on the very bottom of your screen.

A screen should pop up that looks like the image below. 

In Pine script, you will either be creating an indicator or a strategy. We will discuss the differences extensively in this article. 

If you’re following along, the screen you’re looking at now is the default starting script to create an indicator.

Let’s run through it line by line.

The first line is simply a comment. Comments in Pine script start with two forward slashes.

The second line is also a comment, it is auto-populated with your TradingView user name.

On the fourth line, you might assume we have yet another comment. However, this line is a bit different.

This is known as a compiler directive. It lets the compiler know which version of Pine script we want to use.

You can forego the first two comment lines if you want, but the compiler directive is required in all scripts.

Line 5 is a declaration. This is where you specify if you are creating an indicator which is also known as a study.

The alternative is to create a strategy, but we will start with the study. 

The second part of Line 5, in quotation marks, is the name that we will assign for this particular study. The default is My Script.

Line 6 contains the plot command. As you may have guessed, this tells TradingView to plot a specific variable.

In this case, the variable will get plotted. This is a built-in variable that contains the closing price of the latest bar.

Let’s hit Add to Chart on the upper right of the Pine editor.

You will be prompted to save the script.

Once saved, your chart should have a new window that contains a plot of the closing prices from your main chart.

This window is called the data window. In the image above, this is the line chart that is drawn in blue.

Note that the data window shows “My Script” in the upper left-hand corner. This pulls whatever is entered into Line 5 of our code where we declared a name for the study.

And there you have it, our first study and we didn’t even need to write any code!

How to retrieve the price of Apple?

In our first example, we plotted the closing price. Pine script will automatically do that for whichever chart you have open.

In this case, we had am hourly chart of Bitcoin open.

But what if you want to get data for another asset? Let’s go through an example where we grab the price of Apple even though we don’t have its chart open.

Every script will start with a few lines where we set the compiler directive. We also indicate if it’s a study or strategy that we are creating, and assign a name.

In this case, we are creating a study. The name for this study is price of Apple.

Next, we have to tell Pine script that we are interested in an asset other than what is currently displayed on the chart.

To do this, we can use the security() function.

A nice feature of Pine script is that help is always easily available if you’re working with syntax you haven’t worked with before.

For example, we can hover over our function and it will show a brief description.

For more detailed information, you can launch a help window. To do this, hit CTRL while clicking on the function on a PC. Or, on a Mac, press CMD while clicking on the function.

The help function clarifies the syntax and even has helpful examples.

We’ve used syntax similar to the example in the above code snippet. The first value in the security function is the ticker symbol which is AAPL. 

Then we set the time frame to daily. And lastly, we told Pine script we are interested in the closing price.

We can save the return of the function to a variable.

Now the apple_price variable will contain the latest daily close of Apple’s stock.

Studies created in Pine script need to have at least one output, otherwise it the script will generate a compiler error.

Let’s plot our variable so that it satisfies the Pine script rule about having an output.

After saving and adding to chart, this is what our screen looks like.

We now have Apple’s daily closing price plotted in the data window while the main window is showing a candlestick chart of Microsoft.

Full Code:

How to retrieve the SMA(20) of Apple?

Now that we can access Apple’s stock price, let’s go through an example of retrieving a simple moving average. 

The same process can be used to apply any indicator.

We will start with our basic declarations and use the security function we created in our last example.

If you’re not looking to get the 20 SMA specifically for AAPL, you can skip the security definition and just use the built-in variable.

This will grab the closing price for whichever security you have showing in your main chart window.

There is a helper function for the SMA indicator built-in to Pine script. To access it, we simply use the sma() function.

The first parameter we need to pass in is the price value. In this case, we are using the closing price for Apple that we have stored in our variable.

The second parameter is the length of the SMA. We are looking for a 20 period SMA.

Lastly, we will assign the SMA data to a separate variable and then plot it.

The simple moving average for Apple is now plotted to our data window.

Moving averages are typically plotted on the main chart. We can achieve that with a slight modification in our code.

By adding in into the study declaration, we can plot our data directly into the main charting window as opposed to the data window.

Full Code:

How to backtest a moving average cross strategy with Pine Script?

We’ve gone over indicators, or otherwise known as a study. Let’s take a look at strategies in Pine script.

In the next example, we will create a moving average cross over strategy with a few additional parameters. We will then backtest the strategy within TradingView.

To create a strategy, we swap out the study declaration with a strategy declaration.

The first thing we will want to do is create two moving averages and assign the data to variables. 

We will also create an RSI indicator that will be used to confirm our entries and exits.

This strategy will be run on the main chart so we don’t need to use the security() function here.

Next, we want to specify our crossover conditions. Fortunately, TradingView has a built-in function for that already, so we don’t need to code it manually.

We have two conditions, the first one is when the short SMA, the 10-period, crosses above the longer 30-period SMA.

The second condition is the opposite as we’ve used the crossunder function as opposed to crossover.

Both these conditions are saved to variables. So when the crossover or crossunder occurs, these variables will get updated to True which is a Boolean value.

We can use an if statement to check if the condition is changed to True, and then execute a trade based if that is the case.

The built-in function is used to enter trades. Here are the parameters that are passed into the function.

  1. long” – this is a trade ID. We won’t be using it in this example. But, if you plan to close or cancel a trade, it can be done with this ID.
  2. strategy.long – this is a built-in variable that tells Pine script that we want to get long.
  3. 100 – the number of shares we want to trade
  4. when = rsi > 50 – this is an additional parameter that tells pine script to only execute the trade if the RSI is higher than 50.

The syntax for our short entries will follow a very similar format.

Since we are running a strategy, we don’t have to plot anything or specify an output. 

But we will do so anyway. It would be nice to see the SMA’s on the chart so that we can confirm that trades took place when they should have.

If we save and add to chart, the strategy will run and automatically open the Strategy Tester window which will display some important stats.

This is what our screen looks like.

By default, a new tab opens showing the overview stats for the strategy. You can click through the Performance Summary or List of Trades to see other statistics.

The strategy will run on the time frame that is displayed on your chart. 

You can easily cycle through different time frames using the time frame options in the menu at the top of the screen. The strategy will auto-update based on the new time frame chosen.

Full Code:

How to set take profits and stop losses?

In our last example, the trade execution was determined by moving average crossovers and crossunders.

We will build on this script and set specific stop losses and take profits. We can use the Average True Range (ATR) to calculate the levels for these.

The ATR indicator calculates the average movement over the last number of specified bars. This is a good way to account for changes in volatility.

We have already declared several indicators, we will add the ATR indicator to the list.

Under our trade conditions, we can make the necessary calculations for our stop loss and take profit.

In the code above, we calculated the stop loss by taking the low of the bar at the time of entry and subtracting the average true range multiplied by two.

So if the stock moves on average $5 per bar, we are setting our take profit $10 below the low.

A similar calculation is done for the take profit.

Lastly, we specify the exit condition using the strategy.exit() function. Here are the parameters that were passed through.

  1. exit” – this is the trade ID for exiting out of the trade.
  2. long” – this is the ID that we previously set when we entered the trade. This will let Pine script know which position we are trying to exit.
  3. stop=stopLoss – we are specifying that the level contained in the stopLoss variable should be used as a stop order to exit the trade.
  4. limit=takeProfit = we are specifying that the level contained in the takeProfit variable should be used a limit order to exit the trade.

The syntax for our short condition is similar although some of the calculations are slightly different.

The rest of the script remains unchanged from the prior example. Let’s run it and see how our strategy did.

Our exits are working and being plotted on our main chart along with the long and short entries.

Full Code:

How to fire a trade on Apple when Google moves 5%?

We’ve seen that the security function can be used to display data for stocks not shown on the screen. 

We will use it to create a strategy that will execute a trade in Apple if Google moves more than 5%.

This is a mean reversion strategy, so if Google rallies by more than 5%, we will short Apple. If Google falls by more than 5% then we can buy Apple.

The first thing we will do is store Google’s daily open and closing price into a variable.

We can then perform a calculation to determine the percentage price change.

The variable now holds the calculation. So for example, if Google opened at $100 and rallied 5% to close at $105, the variable would be 105/100 which is 1.05.

But if Google opened at $100, and declined 5% to close at $95, the variable would read 95/100 which is 0.95.

So we know that if Google declined 5% or more, the variable would be 0.95 or less, and we want to get long. Here is the syntax to do that.

And the syntax to get short if Google rallies more than 5%.

You might notice that we have not mentioned Apple’s stock price in the code. All we need to do is open an AAPL chart and it will automatically know to execute the trades in Apple.

Lastly, we will plot the variable in the data window. It’s not necessary, but nice to see and we can confirm that the trades are being executed as they should.

And here are the results of our strategy.

Only four trades as 5% movements are rare. We’d probably need to see a lot more trades than that to determine if its a good strategy.

It did seem to have done a good job picking out that low in March!

Full Code:

How to modify our scripts without coding?

A cool feature about Pine script is that we can create custom inputs to easily change the parameters of our strategies and indicators.

Take a look at the standard ATR indicator offered in Tradingivew. Note how easy it is to modify the length and even the colors via the Style tab.

We can achieve the same for the studies and strategies created in Pine script by using the input() function.

Here is an example of the input function that will allow the user to customize the percent change from the last strategy example.

Let’s go through the parameters that are passed through the input() function.

  1. title – this is where we specify the text that the user sees when trying to change the value of that particular parameter.
  2. type – we have to let TradingView know what kind of value to accept. Since the user could be entering a number such as 4.2, we’ve used float.
  3. defval – this is the default value. 

If you’re not sure which values to use for the type, you can always use the auto-complete function to see what is available. 

Simply type part of the syntax and then press CTRL + spacebar on a PC or CMD + spacebar on a Mac.

We’ve can now get values from the user. But they will be inputting a value such as 5(%). We need to convert this to 1.05 for our if statements.

And we need to change our if statements to look at our newly created variables based on user input rather than the previous hard coded values.

To access the input options, click on the gear icon next to the name of your strategy in the data window.

Custom values can now be set for the percentage change used in the strategy.

There is also a Properties window that will allow you to set custom options for other parts of the strategy.

And a Style window to customize plotting options.

Full Code:

How to Plot with Pine script?

So far we’ve used the standard plot() function to plot certain things to the screen. Pine script has several other commands that we can use for our output and we will go through a few of them.

Plotting Forex market hours

Knowing when the markets open and close is something to be mindful of. This can be quite tough to figure out for Forex traders.

Forex trades 24 hours a day and 5 days a week. Different markets around the world open and close during the day which impacts currency volatility. 

Let’s program a study that will tell us with a quick glance at the chart when the markets are expected to be the busiest.

Most Forex traders are paying attention to the London and New York sessions. We will start by specifying the time for these sessions.

We’ve used the time() function here to create a period. In the parameters, we are using 0700 UTC for the start time of the London session and 1500 UTC for the end time.

The variable will now contain the bar time if the bar falls in between that period. Otherwise, it will show a NaN (not a value).

We can use an if statement to see to check the output of the variable.

In the code above, we are using a built-in function called na(). What this does is check whether the variable has a NaN value or not.

if the variable returns Nan, it means the bar is outside of London trading hours.

In this event, a variable called will be assigned the integer 1. Otherwise, the variable will be set at 0.

Lastly, we plot the newly created variable.

Here is what our chart looks like after saving and adding this study to the chart.

That doesn’t look too good. It is correctly showing when the London market is open, but plotting those values has made our candlesticks illegible.

We could plot it in the data window so that the candles are easier to see, but it still would not be easy to visualize the market open and close.

Also, the code doesn’t look too good.

Let’s start by using a one-line if statement to clean up our code a bit. 

This code performs the same function as the if statement before. We don’t need to use the variable in this case. Let’s break down the syntax.

This part is checking to see if the variable contains a NaN value.

The question mark here is short form for an if/else statement.

What follows the question mark is the important part. There are two numbers here separated by a colon. The number before the colon, 1 in this case, is what should be returned in the event the if statement is true.

The number after the colon, 0 in this case, gets returned when the if statement returns false.

We can then take the entire syntax and wrap it in a plot function, saving the effort of storing it to a variable first.

So now we’ve cleaned up the if statement into a one-line piece of code.

To make the chart easier to read, we can plot a different background color if the London market is open.

To do this, we swap the plot() function with the bgcolor() function. This allows us to change the background color.

Also, we will specify a color for when the market is open.

Our chart is starting to look a lot better!

The last thing we will do is add code to see if the New York market is open, and set the background to green if it is.

You’ll notice that there are three colors on the chart below. 

That’s because there is an overlap between the London and New York sessions, this is usually the most volatile time of the day.

Now we can easily see the sessions and quickly pick out things like the high set in European trading or the low that printed during the overlap.

Full Code:

Plotting Annotations

There are several options to print annotations. As an example, you can use the hline() function to draw a horizontal level across the chart.

There is a plotchar() function that allows you to plot ASCII characters on your chart. This is often used to plot a note either on top or on the bottom of the price bar.

Another common plotting function is plotshape() which allows you to plot various shapes. This one is quite popular as a lot of people use it to plot arrows on the top or bottom of bars to show buy or sell signals.

For a complete list of the various annotations available, check out the Annotations overview in the Pine script user manual.

How can I create a custom indicator in Pine script?

We are going to create a multi time frame indicator.

This is based on a scalping strategy that I used when I first started trading. It is a mean reversion strategy that works well during the early Asian session in the Forex markets when things are generally quiet.

The strategy uses Bollinger Bands on a 5-minute chart and RSI on a 1-minute chart.

The idea is to look for rsi divergence on a 1-minute chart when the price reaches the upper or lower Bollinger band on a 5-minute chart.

A potential target is the midline of the 5-minute Bollinger band or the lower line of a 1-minute Bollinger band.

The above image is an example of the strategy. The Forex sessions indicator that we used in a previous example was used here to show when the Asian session is open.

This strategy works best in the first half of the session, after that the risk of a breakout or directional move tends to increase.

When I traded this strategy, I had to keep two charts open, a 1-minute and a 5-minute chart.

But the example above shows the 5-minute Bollinger bands drawn directly on a 1-minute chart. We will create this indicator in Pine script.

We start by declaring a name for the script and indicating it is a study. A shorter title can be added as well, this is the name that will be shown on the charts.

Next, we set some user inputs. We can duplicate most of the inputs from the regular Bollinger band indicator (as shown in the image above) for our custom indicator.

 We can create the Bollinger band indicator from a built-in helper function. 

There are three values returned from this function. The lower, mid, and upper band. These are saved individually to variables.

The values should be calculated on a different time frame. We can use the security() function to point to the time frame chosen by the user. 

This is stored in the tf variable created by the earlier user input.

The ticker symbol remains the same, so we’ve used which will return whichever ticker is being displayed on the main chart.

And that does it, all that’s left is to plot the new indicator.

We can now see Bollinger bands from a 5-minute chart displayed on a 1-minute chart.

The inputs allow for easy customization of Bollinger band parameters and allows this indicator to work with any time frame combination.

Full Code:

Final Thoughts

If you’ve been following along with the examples, you will have a good idea of what Pine script is capable of doing.

Overall, there is a lot you can do with Pine script, even though it has certain limitations. It’s possible to code up a strategy really quickly once you get the hang of things.

From there, it’s always an option to take that logic and program it into another language if you want to build on it and leverage third-party libraries.

The plotting functions are great, and the ability to make custom indicators is really useful for both manual traders and automated systems.

The comprehensive statistics offered for strategies is also a big plus point for Pine script.

TradingView has several resources if you want to take your Pine script coding skills a step further.

Some help functions have already been discussed in this article. In addition to that, there is also a help option from within Pine editor.

Here are a few other resources – 

  1. Quickstart Guide – This gives an example of a study and breaks the script down line by line.
  2. Pine Script v4 User Manual – A detailed manual for Pine script.
  3. TradingView Blog – Announcements of new features which often contain sample code
  4. TradingView Scripts Library – A library of open source Pine script studies and strategies.

The last option on the list is a great resource as often another trader might have already coded the study or strategy you are after.

It is also a good resource to draw ideas from to build your own indicators or strategies.

If you’d like to try out some of the examples, a one-click download of all the code is available on GitHub. Simply click the green button and choose download zip. The code will be in text files which can be copied over to Tradingview’s Pine editor.


Script tradingview rsi

RSI Pine script Strategy

Strategy Premise

The Relative Strength Index (RSI). Is a momentum oscillator that measures the speed and change of price movements. The RSI oscillates between zero and 100. Increasing Rsi shows increasing bullish momentum. Decreasing Rsi shows increasing bearish momentum. We take RSI upper bound as 70 to indicate bullish momentum and the RSI lower bound as 30 to indicate bearish momentum.

Strategy Logic

Long Entry: When RSI goes below 20, send LE.

 Long Exit: Either when SL or Target is hit. If SL/TGT is not hit and RSI goes above 70, send LX and SE

Short Entry: When RSI goes above 70, send SE

Short Exit: Either when SL or Target is hit. If SL/TGT is not hit and RSI goes below 20, send SX and LE

RSI Strategy Parameters for TradingView Charts

Rsi Length(Mandatory): This is the number of bars used to calculated rsi Ex: 14 previous 14 candles are used to calculate RSI

Oversold(Mandatory): This is used to specify oversold of RSI

Overbought(Mandatory): This is used to specify overbought of RSI

Quantity: This is used to specify the trade quantity 

Custom Stop Loss in Points: Movement in chart price against the momentum which will trigger exit

Custom Target in Points: Movement in chart price against the momentum which will trigger exit


TradingView Settings

STEP 1: Download The Pine Script Algo here

STEP 2: Open desired Chart in trading View with normal Candlestick, Select desired timeframe of the chart, Go to the pine editor section, remove the default code, paste the downloaded code, save the file and to chart. 

 STEP  3: Once Strategy is applied to the chart, click on settings to optimize parameters for your own trading.


Setting Up Alert

Before setting up an alert make sure that You have selected the desired script, timeframe, strategy settings, API bridge is configured and running. Click in settings add alert and paste {{strategy.order.comment}} in message box.

Important: do not change any settings during live trading. 

NOTE: The pinescript works both with webhook alerts (TV Pro plan) and normal popup alerts (TV free plan).

That’s all, you are ready to trade with RSI Pine script Strategy.

How to code RSI - PineScript TradingView Code-along Tutorial

Relative Strength Index (RSI)


The Relative Strength Index (RSI) is a well versed momentum based oscillator which is used to measure the speed (velocity) as well as the change (magnitude) of directional price movements. Essentially RSI, when graphed, provides a visual mean to monitor both the current, as well as historical, strength and weakness of a particular market. The strength or weakness is based on closing prices over the duration of a specified trading period creating a reliable metric of price and momentum changes. Given the popularity of cash settled instruments (stock indexes) and leveraged financial products (the entire field of derivatives); RSI has proven to be a viable indicator of price movements.


J.Welles Wilder Jr. is the creator of the Relative Strength Index. A former Navy mechanic, Wilder would later go on to a career as a mechanical engineer. After a few years of trading commodities, Wilder focused his efforts on the study of technical analysis. In 1978 he published New Concepts in Technical Trading Systems. This work featured the debut of his new momentum oscillator, the Relative Strength Index, better known as RSI.

Over the years, RSI has remained quite popular and is now seen as one of the core, essential tools used by technical analysts the world over. Some practitioners of RSI have gone on to further build upon the work of Wilder. One rather notable example is James Cardwell who used RSI for trend confirmation.


RSI = 100 – 100/ (1 + RS) RS = Average Gain of n days UP / Average Loss of n days DOWN

For a practical example, the built-in Pine Script function rsi(), could be replicated in long form as follows.

change = change(close) gain = change >= 0 ? change : 0.0 loss = change < 0 ? (-1) * change : 0.0 avgGain = rma(gain, 14) avgLoss = rma(loss, 14) rs = avgGain / avgLoss rsi = 100 - (100 / (1 + rs))

"rsi", above, is exactly equal to rsi(close, 14).

The basics

As previously mentioned, RSI is a momentum based oscillator. What this means is that as an oscillator, this indicator operates within a band or a set range of numbers or parameters. Specifically, RSI operates between a scale of 0 and 100. The closer RSI is to 0, the weaker the momentum is for price movements. The opposite is also true. An RSI closer to 100 indicates a period of stronger momentum.

- 14 days is likely the most popular period, however traders have been known to use a wide variety of numbers of days.

What to look for


Wilder believed that when prices rose very rapidly and therefore momentum was high enough, that the underlying financial instrument/commodity would have to eventually be considered overbought and a selling opportunity was possibly at hand. Likewise, when prices dropped rapidly and therefore momentum was low enough, the financial instrument would at some point be considered oversold presenting a possible buying opportunity.

There are set number ranges within RSI that Wilder consider useful and noteworthy in this regard. According to Wilder, any number above 70 should be considered overbought and any number below 30 should be considered oversold.

An RSI between 30 and 70 was to be considered neutral and an RSI around 50 signified “no trend”.

Some traders believe that Wilder’s overbought/oversold ranges are too wide and choose to alter those ranges. For example, someone might consider any number above 80 as overbought and anything below 20 as oversold. This is entirely at the trader’s discretion.



RSI Divergence occurs when there is a difference between what the price action is indicating and what RSI is indicating. These differences can be interpreted as an impending reversal. Specifically there are two types of divergences, bearish and bullish.

Bullish RSI Divergence – When price makes a new low but RSI makes a higher low.

Bearish RSI Divergence – When price makes a new high but RSI makes a lower high.

Wilder believed that Bearish Divergence creates a selling opportunity while Bullish Divergence creates a buying opportunity.


Failure Swings

Failure swings are another occurrence which Wilder believed increased the likelihood of a price reversal. One thing to keep in mind about failure swings is that they are completely independent of price and rely solely on RSI. Failure swings consist of four “steps” and are considered to be either Bullish (buying opportunity) or Bearish (selling opportunity).

Bullish Failure Swing
  1. RSI drops below 30 (considered oversold).
  2. RSI bounces back above 30.
  3. RSI pulls back but remains above 30 (remains above oversold)
  4. RSI breaks out above its previous high.
Bearish Failure Swing
  1. RSI rises above 70 (considered overbought)
  2. RSI drops back below 70
  3. RSI rises slightly but remains below 70 (remains below overbought)
  4. RSI drops lower than its previous low.

Cardwell’s trend confirmations

Of course no one indicator is a magic bullet and almost nothing can be taken simply at face value. Andrew Cardwell, who was mentioned earlier, was one of those students who took Wilder’s RSI interpretations and built upon them. Cardwell’s work with RSI led to RSI being a great tool not just for anticipating reversals but also for confirming trends.


Cardwell made keen observations while studying Wilder’s ideas of divergence. Cardwell believed that:

  • Bullish Divergence only occurs in a Bearish Trend.
  • Bearish Divergence only occurs in an Bullish Trend.
  • Both Bullish and Bearish Divergence usually cause a brief price correction and not an actual trend reversal.


What this means is that essentially Divergence should be used as a way to confirm trends and not necessarily anticipate reversals.


Cardwell also discovered what are referred to as Positive and Negative Reversals. Positive and Negative Reversals are basically the opposite of Divergence.

  • Positive Reversal occurs when price makes a higher low while RSI makes a lower low. Price proceeds to rise. Positive Reversals only occur in Bullish Trends.
  • Negative Reversal occurs when price makes a lower high while RSI makes a higher high. Price proceeds to fall. Negative Reversals only occur in Bearish Trends.

Positive and Negative Reversals can be boiled down to cases where price outperformed momentum. And because Positive and Negative Reversals only occur in their specified trends, they can be used as yet another tool for trend confirmation.



For more than four decades the Relative Strength Index (RSI) has been an extremely valuable tool for almost any serious technical analyst. Wilder’s work with momentum laid the groundwork for future chartists and analysts to dive in deeper to further explore the implications of his RSI modeling and its correlation with underlying price movements. As such, RSI is simply one of the best tools or indicators in a trader’s arsenal of market metrics to develop most any trading methodology. Only the novice will take one look at RSI and assume which direction the market will be heading next based off of one number. Wilder believed that a bullish divergence was a sign that the market would soon be on the rise, while Cardwell believed that such a divergence was merely a slight price correction on the continued road of a downward trend. As with any indicator, a trader should take the time to research and experiment with the indicator before relying on it as a sole source of information for any trading decision. When used in proper its perspective, RSI has proven to be a core indicator and reliable metric of price, velocity and depth of market.



The time period to be used in calculating the RSI. 14 days is the default.


Determines what data from each bar will be used in calculations. Close is the default.



Can toggle the visibility of the RSI as well as the visibility of a price line showing the actual current price of the RSI. Can also select the RSI's color, line thickness and line style.

Upper Band

Can toggle the visibility of the Upper Band as well as sets the boundary, on the scale of 1-100, for the Upper Band (70 is the default). the Upper Band's color, line thickness and line style can also be determined.

Lower Band

Can toggle the visibility of the Lower Band as well as sets the boundary, on the scale of 1-100, for the Lower Band (30 is the default). the Lower Band's color, line thickness and line style can also be determined.


Toggles the visibility of a Background color within the RSI's boundaries. Can also change the Color itself as well as the opacity.


Sets the number of decimal places to be left on the indicator's value before rounding up. The higher this number, the more decimal points will be on the indicator's value.


You will also like:


44 45 46 47 48