Pine Script Tutorial

Sep 7, 2018 · 7 min read

Trading strategies are one of the best ways to avoid behavioral biases and ensure consistent results.

Strategies employ indicators in an objective manner to determine entry, exit and/or trade management rules. They include the detailed use of indicators or, multiple indicators, to establish instances where trading activity will occur.

However any trading strategy need to be tested under varying market conditions to measure consistency and accuracy.

For ex- You have a brilliant strategy in mind that could give overall 70–80% profitability with minimal drawdown over a certain period.

It doesn’t mean that it will perform the same when the market conditions change- say from a trending to a non-trending period.

Full Back-testing in every possible scenario with proper risk management is the need to avoid situations of large drawdowns in an account.

In this article i will be covering the basics of strategy tester environment of Trading-view with few basic Moving Average strategies.

Tradingview has inbuilt pine scripting language where anybody, even free account holders, can develop their strategy and back test accordingly.

The language itself is very simple to understand and no rocket science study needed here.

Let’s get started with the most basic stuff first

1> 20 period Moving Average strategy:

Image for post
Image for post

Taking the example of bitcoin to test this strategy. Let’s see why we are taking the 20 SMA for formulating our strategy.

From the btcusd chart here, we can see, after a nice uptrend and consolidation around 8k level, price started to break down around july end period and it broke below the 20MA — giving sell signal.

Price consolidated for a long time near the 20MA before finally breaking above- giving buy signal and trending again.

Now lets see how to setup tradingview to build our own signal bot!

  • First step is to access the pine editor itself.
Image for post
Image for post
  • Then we need to create a strategy template- which will be used later, to code our strategy. Simple process again- click on new and create strategy script!
Image for post
Image for post
  • You will get a default sample code, we won’t be needing that, so select everything there and replace with the code given here:


SMA =input(10, minval=1)


plot(s, color=yellow,linewidth=2) // Plots the MA

buy= close>s

sell= close<s

ordersize=floor(strategy.equity/close) // To dynamically calculate the order size as the account equity increases or decreases.


strategy.close("long", when = sell )

Lets understand this simple code below:

  1. //@version=3 This is the version of pine that you will be working on, pine ver 3 has lot of improvement over the version 2.
  2. There are two types of scripts in Pine one for indicators and other for strategies. If you are building a strategy then you will have to use the strategy function, which specifies the script name and some other script properties. Like Overlay= true if you want to plot the results on the chart itself, else if you are building an indicator like any oscillators, then you might want to keep it as false.
  3. Next Line: input function with default value as 10 and min value as 1. Its output gets stored in “SMA” and passed as a parameter to the inbuilt pine function “sma()”.
  4. We define a variable “s” which will store the 10 period simple moving average of candle closings.
  5. Then next, we need to define — exactly when we want our strategy to make a buy call or a sell call. To do that we define buy and sell variables which will be later passed as parameters to the strategy.entry() and strategy.close() functions respectively. These functions are used to open/close positions.
  6. Our “buy” variable will give output as true, whenever the candle closing is above the 10 SMA ( value stored in “s”). Vice-versa for the “sell”
  7. Next we calculate our ordersize based on the capital that we have.
  8. Strategy.entry with parameters order id, strategy.long, ordersize and buy: Opens a long position with defined ordersize at our buy condition.
  9. Strategy.close with parameters order id and sell: Closes any open position with the specified “order id” at our sell condition.
  10. If you want to implement exit position via Take profit, SL, TL in addition to the strategy exit call then you need to add a line to the code above:

strategy.exit( "exit long", from_entry="long" , profit=p,loss=sl,trail_points=tl,trail_offset=os)

“long” will be the id of the position to close, p,sl, tl and os can be defined as input variables with some default values. They must be provided in ticks (minimum price movements)

  • Then the last step would be to save this strategy and add it onto your charts.
Image for post
Image for post

This simple strategy gives decent results, if its running over a long period of time.

Image for post
Image for post

Important things to check in any strategy that you backtest: Net profits, Percent profitable- i.e the percent of winning trades. Maximum drawdown, profit factor, Largest win/loss and list of trades( very important too! ) to check the strategy starting date, profits, position size tallying or not, as sometimes if we’re just seeing the net profits and profitability, we can easily get tricked into believing that this strategy is invincible, only to later find a bug in its working.

Image for post
Image for post

To change the period of SMA, you just need to access the settings (top-left in the pic above) and put any desired value as the period there and then you can see the changes in the figures.

Now let’s look at a Moving average crossover strategy

2> Moving average crossover strategy

Image for post
Image for post

Price crossovers are used to identify shifts in momentum and can be used as a basic entry or exit strategy.

A short period MA crossing below a larger period MA (10–20MA in this case) indicates that bears are in control, gaining momentum and a big move is around the corner.

Conversely, the shorter period MA crossing above the larger period signifies that the momentum has now shifted towards the bulls.

There’s nothing new here, still it’s amazing to see how well it works, specially if you use some trade filters to remove noisy signals generated during choppy movements.

Now the important part:

The pine script code for this strategy could be something like this:


strategy("MAcross_strategy", shorttitle="MAcross_strategy", overlay=true, initial_capital=100000)

SMA_Fast =input(10, minval=1) // To input period for 1st sma, default period set as 10

SMA_Slow =input(20, minval=1)

s1=sma(close,SMA_Fast) // sma values stored in s1 and s2 variables


plot(s1, color=yellow,linewidth=2) // Plots the MA

plot(s2, color=red,linewidth=2)

buy= crossover(s1,s2) // Define our buy/sell conditions, using pine inbuilt functions.

sell= crossunder(s1,s2)

ordersize=floor(strategy.equity/close) // To dynamically calculate the order size as the account equity increases or decreases.

strategy.entry("long",strategy.long,ordersize,when=buy) // Buys when buy condition met

strategy.close("long", when = sell ) // Closes position when sell condition met

Thats all, now you can go ahead and save then add it to the charts:

Image for post
Image for post

To see the effects from the strategy-tester tab.

Image for post
Image for post

To change the period of SMAs, same process- you need to access the settings (top-left in the pic above) and put any desired value as the period there and then you can see the changes in the figures.

Now suppose you don’t want to use SMA in your strategy and instead a different MA then just replace the sma() function that we had used in our code above with wma()/ema()/vwma() functions as per your preference, all other details remain the same!

Check my strategy below, to implement code snippets of time-period and other MAs like HMA, TEMA into your strategies.

These were two most basic strategies that could be implemented into pine.

In my next articles i will be covering an advanced strategy involving WMA, Heikin-Ashi candles and also providing code snippets of various oscillators like MACD, stoch, RSI , showing how to add them in any strategy to get better results.

The purpose of this article was to give an overall feel of the strategy tester environment in Tradingview and if you feel that it has done so then kindly hit the like, subscribe.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store