A Simple Start
In this article, I will explain some of the basic functions of Pine Script by creating a Moving Averages crossover strategy. If you follow along step by step, you too can make your own trend script!
So, what do you need for this script to work? For a simple script, you only need a couple of things, but there are some basics. To get started, go to a chart in TradingView and click “Pine Editor” at the bottom of your screen.
You will now see a notepad-like editor, which we will use to create scripts. The first thing you will notice is the important line of
//@version=3. This is critical and is needed to communicate that you will be using version 3 of Pine Script. Be sure to always start with this line.
There are two types of scripts within Pine Script, namely study and strategy. The main difference between them, is that you can create alerts under a study and you can backtest your script under strategy. Why TradingView split these functionalities is one of the great mystery’s of our time, but that is just the way it is.
In the example script loaded, the third line says
plot(close). This means the script will plot a line of the current close data point of the instrument you apply it to. If you are used to looking at candlesticks, you know that they stand for the Open, High, Low and Close (OHLC) of a period. This means that a
plot(low), would plot a line of the lows of every period that you have selected, such as the Daily, 4 Hours, 1 Hour etcetera. Selecting the data you for you script to calculate with is arguably one of the harder parts of algorithmic scripting, but I’ll be sure to dedicate one article to it in the series.
Setting up your strategy
So, let’s take a closer look at the
strategy() function and replace the
study() function in the editor.
Looks messy, but setting this up the right way will help make your backtest results a lot more reliable. Once you have your strategy running, you can find most of these settings in the configuration menu of your strategy.
And this is how that looks as code:
And this is what that means:
- Sets title and short title to “A Simple Start – Strategy [CP]”
- Sets overlay to ‘true’ so that the script will be overlayed on the price, instead of a separate pane. Useful for Moving Averages, not so much for
a RSIor OBV script.
- Sets starting capital to test with to 50.000 USD. You want this to be a high number. If you are testing your script on Bitcoin, for example, it will have trouble testing it at the time $BTC was at $20.000 a piece. You can always see what trouble that causes by setting this lower.
- Pyramiding gives you the ability to layer buy orders with a designated percentage of your stash. Not needed in Moving Averages crossovers, so 0.
- Sets commission type to percentage and value at 0.075%. Specifically for trading on
Binance. If you have a bag of $BNB, the commission/trading fees are 0.075% (discount of 0.025%).
- Disables intra-bar strategy and order calculation. These are two settings that are best turned off, as they will mess with your backtest results greatly.
- Sets the quantity value to 100%. So you will be trading with your entire stash from long to short, which is a great way to see the effectiveness of your strategy, specifically on Moving Averages crossovers.
This might seem like a lot take in, but don’t underestimate the importance of setting the scope of your strategy.
Coding the strategy
Now that we’ve defined the scope, we can continue creating two Moving Averages, a fast one and a slow one. For this script, we will use the Simple Moving Average. So let’s take a look at how Pine Script calculates the SMA.
To calculate we need a source and a length. The source is data that the calculation uses and for this example we will use the close data point. The length is the number of periods (bars) the calculation uses. The higher the length, the slower the Moving Average responds. So we will be using a small number for the Fast MA and a greater length for the Slow MA. After defining that MA’s we will use the plot function to draw them on your screen.
This is how that looks as code in your editor:
As you can see,
So, now the inputs of my SMA’s are dynamic and that makes testing a lot easier. To zoom in on the
input() function, you can see that in the case of lengthFastMA, we set the default value to 5, the type to integer, which means it is a whole number and gave it a title so we can recognize it easily in the menu later on.
As you can see i also added some commentary to different parts of the code. This makes it easier to read if you want to share your code with others or for yourself when your scripts run into the hundreds of lines.
Now that we’ve got dynamic SMA’s, there are just two steps left.
- Defining the conditions that would signal a long/buy or short/sell signal.
Conditions are basically rules. X is a bigger than Y for example, which
x > y
Fortunately, Pine Script has a built-in function to detect crossovers, crossunders or just crosses. Let’s take a look at what information they need.
It looks like it needs to check two variables, ‘x’ and ‘y’, which we will replace with the Fast MA and the Slow MA. If it detects that this happened it will return a signal to us, namely a boolean, which is a datatype that can only consist of ‘true’ or ‘false’. So what we want to define is the following:
- Long/Buy signal: The Fast MA crosses over the Slow MA
- Short/Sell signal: The Fast MA crosses under the Slow MA
This is how that looks as code:
Now we are left with the final part of the script.
Based on the conditions we just set with the
crossunder() function we need the last bit of code to execute the strategy when the conditions are met. This is done with the
strategy.entry() function. Let’s take a closer look.
Once again, a lot of options and when you want to continue building scripts and they become more complex, you will definitely need to go down that rabbit hole. For our purpose, we only need to give it a name and trigger it when the conditions we set earlier, are met. We do this with the following code:
If you look at the latest addition of code it reads as following:
- When the Fast MA crosses over the Slow MA, enter a Long position with the ID “MA Cross – Long”
- When the Fast MA crosses under the Slow MA, enter a Short position with the ID “MA Cross – Short”
The last thing that you need to do is hit the Save button, and when it’s done compiling you can hit “Add to Chart” and you’ll see the SMA’s appearing on your screen. You can now hit the cogwheel button to change the periods of your SMA’s and under “Strategy Tester” you’ll see the results of your strategy change instantly!
This was the start of the series and I hope you this has made starting with scripting easier. If you have any feedback, do let me know!
It also wouldn’t hurt to study the Pine Script Language Reference Manual, so you can get up to date on al the functions, variables and operators used by Pine Script.
FYI: I have an advanced script with multiple MA’s and other filters you can use for free, you can find it here!
This post was initially posted on Medium and reposted with Coinpocalypse’s approval. Minor changes have been made to improve readability or fix spelling errors. You can read the original post here.