4.1 Built-in Functions
In this lesson, we will explore Pinescript functions, which are an essential part of creating custom indicators and strategies. Pinescript offers a variety of built-in functions that perform specific tasks or calculations. These functions can be utilized to simplify your code and make it more efficient.
Some common built-in functions in Pinescript include:
- ta.sma(): Calculates the Simple Moving Average.
- ta.ema(): Calculates the Exponential Moving Average.
- ta.rsi(): Calculates the Relative Strength Index.
To use a built-in function, you simply need to call the function by its name and provide the required arguments. For example, to calculate a 14-day RSI, you would write:
rsi = ta.rsi(close, 14)
4.2 Custom Functions
In addition to built-in functions, Pinescript allows you to create your own custom functions. Custom functions can be useful when you need to perform a specific calculation or operation multiple times within your script.
To create a custom function, use the f_function_name() syntax, followed by the function's code block.
Here's an example of a custom function that calculates the difference between two moving averages:
f_moving_average_diff(src, length1, length2) =>
ma1 = ta.sma(src, length1)
ma2 = ta.sma(src, length2)
diff = ma1 - ma2
To call a custom function, simply use the function name and provide the necessary arguments. For example:
moving_average_diff = f_moving_average_diff(close, 14, 28)
4.3 Function Arguments and Return Values
Functions in Pinescript can accept input through arguments and return values as output. When defining a custom function, you can specify the arguments it requires within the parentheses following the function name. In our custom moving average difference function, we defined three arguments: src, length1, and length2.
To return a value from a function, use the return keyword followed by the value or variable you want to return. In our example, we returned the diff variable, which contains the difference between the two moving averages.
That's it for Lesson 4! You should now have a good understanding of Pinescript functions and how to create and use them. In the next lesson, we'll learn how to draw on the chart using Pinescript.