The Moving Average Convergence Divergence (MACD) is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price. It’s widely used in technical analysis to identify bullish or bearish momentum. In this article, we’ll delve into the ta.macd()
function in Pine Script version 5, exploring its syntax, parameters, and how to utilize it in your trading scripts.
Syntax and Parameters
The ta.macd()
function in Pine Script version 5 returns the MACD line, the signal line, and the histogram, which are key components of the MACD indicator. The syntax for ta.macd()
is as follows:
[macdLine, signalLine, macdHist] = ta.macd(source, fastLength, slowLength, signalSmoothing)
Where:
source
is the price or any other series you want to apply the MACD to (usually close price).fastLength
is the length of the fast moving average.slowLength
is the length of the slow moving average.signalSmoothing
is the length of the signal smoothing.
Example
Let’s create a basic MACD indicator script using ta.macd()
:
//@version=5 indicator("My MACD Indicator", overlay=false) priceSource = close fastMA = 12 slowMA = 26 signalSmooth = 9 [myMacdLine, mySignalLine, myMacdHist] = ta.macd(priceSource, fastMA, slowMA, signalSmooth) plot(myMacdLine, title="MACD Line", color=color.blue) plot(mySignalLine, title="Signal Line", color=color.red) plot(myMacdHist, title="Histogram", color=color.green, style=plot.style_histogram)

In this example:
priceSource
is set to the closing price of the security.fastMA
,slowMA
, andsignalSmooth
are set to typical values of 12, 26, and 9, respectively.myMacdLine
,mySignalLine
, andmyMacdHist
are plotted on the chart, each with a distinct color for easy differentiation.
Walkthrough of the Example
- Initialization: We begin by declaring the version of Pine Script and setting the indicator’s properties with
indicator()
. - Parameter Definition:
priceSource
,fastMA
,slowMA
, andsignalSmooth
variables are defined, holding the values for the source price and MACD calculation parameters. - MACD Calculation: The
ta.macd()
function calculates the MACD line, signal line, and histogram based on the provided parameters. - Plotting: Each component of the MACD is plotted on the chart using the
plot()
function. The histogram is plotted as a histogram usingstyle=plot.style_histogram
.
Key Features and Takeaways
- Function Usability:
ta.macd()
simplifies the process of adding a MACD indicator to your script, requiring only the source series and MACD parameters. - Syntax and Application: Understanding the function’s parameters and their impact on the indicator is crucial for effective implementation.
- Customization: This function allows for extensive customization of the MACD indicator, enabling users to experiment with different lengths for the moving averages and signal smoothing.