Tradingview: Creating Functions

It is time to add another feather to our pine script bow. In this post, we are going to take a look at creating functions and briefly discuss when might be a good time to use them. The post is aimed at the complete beginner and as such, the anatomy of a function will be explained in detail. If you have some programming background, this post might not be for you! Feel free to skip it.

What is a function and when should I use it?

A function is a section of pine script code that is grouped together and can be reused easily without re-writing everything again. This is because when we reuse the code, we just need to call the function again. Imagine you have 20 lines of code that are needed to make a complex calculation. If you want to make the calculation again later, instead of copying and pasting 20 lines of code, you can do it in 1 line by turning the code into a function and simply calling it.

We have actually been using many functions throughout all of the tutorials so far. You just may not have realized. Pine script has a lot of built-in functions that Tradingview’s developers created to make our lives easier. Let’s take a look at some examples:

  • plot(): We finish all of our indicator scripts by calling the plot()function. This function takes our final values and places them on the chart.
  • rsi(): A handy function used in the first script post. Having the ability to call this function rather than needing to search Wikipedia for the formula and then calculate the RSI ourselves made the first script a breeze.
  • input(): If you ever want to add changeable settings to a script, you will need to use the built-in input()function.

Function Jargon

If you are new to programming, there are some concepts and terms that need to be understood to make your life a little easier when reading the documentation.

Function annotations

Argument(s): An argument is an input to a function. We can use arguments to provide the function with something to process or to make changes to the calculation without needing to create another separate function. In other words, this allows the same code to be used for slightly different purposes. If you imagine you have a machine that can produce square blocks from a lump of wood, wouldn’t it be more useful and cost-effective to reuse the same machine to produce rectangular blocks too? You can probably visualize the machine would not need to be all that different to support this. Adding a new part or two and a lever select whether you want a square or rectangular blocks would be enough. Arguments are our levers that make our functions more useful.

Keyword Argument: A keyword argument is pretty much the same as an argument. The difference is that you specifically tell the function what the argument is for. Going back to the analogy above, imagine your machine has 4 levers and you are given instructions on a piece of paper telling you how to set them. It reads “adjust the levers to 5,7,2 and 10“.  You might decide to adjust the levers from left to right in the same order as the note. That is how arguments are given to a function. They are given in order from left to right.  The same instructions with keyword arguments might read “adjust the levers so that the brown lever=10, red lever=7, pink lever=5 and black lever=2“. This reduces the ambiguity and means you do not need to follow a set order. These are keyword arguments.

Return: When we call a function we usually want something to come out of it. Be it a result of a calculation or something else.  When we talk about returning, this means that a number, string (text) or list is returned from the function and stored in a variable.  E.g in x = sma(close,7)the SMA value is returned from the function and store inside the variable x .

Creating a function

When we create a function in pine script, we need to do the following

  • Give it a name: This can be anything you wish but it is recommended to use something which describes what the function does.
  • Declare the arguments: This is done in the same way you submit arguments and keyword arguments when calling a function. We simply write names for the arguments between the brackets. Then in the following code, we decide how to handle the data that is given to that variable.
    • Note: At the time of writing declaring keyword arguments in a function is not supported in pine script. (as far as I can tell)
  • Add the pine script function syntax =>at the end of the line: This lets the interpreter know you are declaring a function.
  • Indent the function’s code: All code for the function must now be indented so that the interpreter knows it is part of the function and can tell where the function ends. To indent you can hit tab on the keyboard or press the space bar 4 times.
  • Return something: This is the output of the function. I.e the result of the calculation (assuming you are making a calculation). In pine script, a variable or list of variables can be returned by writing them on the last line.

Practical example

Nothing cements the theory like a practical example. In this example, we will create a simple function that will return the followng built-in variables:Open highlowand closedepending on a string that is passed to it. This is useful when you create indicator or strategy and want to be able to change the price data that the indicator/strategy uses.  It is especially useful if you have multiple inputs in the script as you can use the same function multiple times.

Commentary

In the code above, we are simply passing a string to the function and using a ternary conditional operator (confused? click the link) to assign a value to x depending on whether the argumentstrmatches the strings in the function.  At the end, we return X.

Note that due to the long line needed, this example splits the line up into several lines using line continuation. You could write the statement as one long line if you wish. For more information see here:

https://www.tradingview.com/wiki/Lines_Wrapping. Line

Line wrapping can be a little tricky to get right with functions and may make a good candidate for a future beginners blog post.

Putting it all together (and adding another function)

The code below shows how to combine the function above with inputs and use them to create a dual HMA (Hull Moving Average) indicator.

Running the code above will allow you to add two HMA’s to a chart and select the input source for the calculation. You will note that the HMA calculation has also been made into a function.

Full credit for the HMA calculation needs to be attributed to Tradingview user Ricardo Santos for the HMA calculation.  (https://www.tradingview.com/u/RicardoSantos/). Visit his profile and give him some Tradingview reputation if you found this post useful.

Note: I have noticed that Tradingview can sometimes raise an error when the code is copied and pasted. If you see an error along the lines of expecting 'end of line without line continuation'then you should re-indent all of the indented lines.