One of the most useful functions in Pine Script is array.avg, which calculates the average of an array’s elements. In this comprehensive guide, we will cover the essential aspects of this function, including its syntax, usage, and application in various scenarios.
Introduction to Arrays in Pine Script
Before diving into the array.avg
function, it is crucial to understand the concept of arrays in Pine Script. Arrays are data structures that store multiple values, allowing for easier data manipulation and storage. They are particularly useful in Pine Script for storing and managing historical price data, indicator values, and other essential information for technical analysis.
In Pine Script, arrays can be created using the array.new_*()
function, where the asterisk (*) is replaced by the data type of the array’s elements. For example, you can create an array of floats using the array.new_float()
function.
Understanding the array.avg Function
The array.avg
function is used to calculate the average of an array’s elements. It is especially useful when dealing with price data, as it allows you to compute the mean of a specific range of values, which can then be used to create various technical indicators.
Syntax
The syntax for the array.avg
function is as follows:
array.avg(id)
Parameters
id
: The input array for which the average value is to be calculated. The array must contain elements of either the integer or float data type.
Return Value
The function returns a float value representing the average of the input array’s elements.
Practical Applications of array.avg
Now that we have a fundamental understanding of the array.avg
function, let’s explore two practical examples that demonstrate its usage.
Example 1: Simple Moving Average
A simple moving average (SMA) is a widely used technical indicator that calculates the average price of a security over a specified period. The SMA smooths out price data, making it easier to identify trends and patterns.
Here’s how to create a simple moving average using the array.avg
function in Pine Script:
//@version=5 indicator('Simple Moving Average (SMA)', shorttitle='SMA', overlay=true) length = input.int(14, minval=1, title='Length') src = close // Initialize array prices = array.new_float(0) // Populate array with the desired number of price values for i = 0 to math.min(length - 1, bar_index) by 1 array.unshift(prices, src[i]) // Calculate the simple moving average sma = array.avg(prices) // Plot the result label newLable = na if barstate.islast newLable := label.new(x=bar_index, y=close, style=label.style_label_left, color=#E6E6FA, textcolor=color.black, size=size.large, text="Absolute Price Difference = " + str.tostring(sma )) label.delete(newLable[1])
In this example, we begin by defining the length and source of the simple moving average. Then, we initialize an array of floats called prices
. We populate the prices
array with the desired number of price values using a **for
**loop. Next, we calculate the simple moving average using the **array.avg
**function and store the result in the **sma
**variable. Finally, we plot the SMA on the chart.
Here’s a line-by-line explanation of the example code:
- Define the script version and create a study with an overlay.
- Set the input for the length of the SMA.
- Define the source of the price data (in this case, the closing price).
- Initialize an empty float array called
prices
. - Use a
for
loop to populate theprices
array with the desired number of price values. - Calculate the average of the
prices
array using thearray.avg
function and assign the result to thesma
variable. - Plot the SMA on the chart inside the label
Example 2: Weighted Moving Average with Custom Weights
A weighted moving average (WMA) assigns more importance to recent data points, giving them more weight in the calculation. In this example, we will create a WMA using the array.avg
function in Pine Script, along with custom weights for each price value. This will demonstrate a more sophisticated application of the array.avg
function.
//@version=5 indicator('Weighted Moving Average (WMA) with Custom Weights', shorttitle='Custom WMA', overlay=true) length = input.int(14, minval=1, title='Length') src = close // Initialize arrays prices = array.new_float(0) weights = array.new_float(0) // Populate arrays with the desired number of price values and custom weights sum_weights = 0.0 for i = 0 to math.min(length - 1, bar_index) by 1 weight = (i + 1) * 2 sum_weights += weight array.unshift(prices, src[i] * weight) array.unshift(weights, weight) // Calculate the weighted moving average wma = array.avg(prices) / (sum_weights / length) // Plot the result plot(wma, title='Custom WMA', color=color.new(color.green, 0), linewidth=2)
In this example, we begin by defining the length and source of the weighted moving average. Then, we initialize two arrays of floats called prices
and weights
. We use a for
loop to populate both arrays with the desired number of price values and custom weights, while also calculating the sum of the weights. Next, we calculate the weighted moving average using the array.avg
function, incorporating the custom weights, and store the result in the wma
variable. Finally, we plot the WMA on the chart.
Here’s a line-by-line explanation of the example code:
- Define the script version and create a study with an overlay.
- Set the input for the length of the WMA.
- Define the source of the price data (in this case, the closing price).
- Initialize two empty float arrays called
prices
andweights
. - Use a
for
loop to populate theprices
andweights
arrays with the desired number of price values and custom weights, while also calculating the sum of the weights. - Calculate the weighted moving average by dividing the average of the weighted
prices
array by the average of the weights and assign the result to thewma
variable. - Plot the WMA on the chart with a green color and a linewidth of 2.
Conclusion
The array.avg
function in Pine Script is a versatile and powerful tool for calculating the average value of an array’s elements. By understanding its syntax, parameters, and practical applications, you can leverage this function to create various technical indicators, such as simple and cumulative moving averages, to aid in your trading decisions.
With this comprehensive guide, you should now have a solid understanding of the array.avg
function and its usage in Pine Script. By applying these concepts and examples, you can create custom technical indicators to improve your trading strategies and gain valuable insights into market trends and patterns.