Skip to main content
On this page

How to Build a MACD Crossover Strategy in Pine Script

· 6 min read
Pineify Team
Pine Script and AI trading workflow research team

A MACD crossover strategy turns the relationship between the MACD and signal lines into explicit entry rules. The example below demonstrates that implementation in Pine Script v6. It is an educational baseline, not an optimized system or a report of measured returns.

MACD Indicator showing crossover signals on TradingView chart

Understand the three MACD series​

The MACD line is the difference between a fast and slow moving average. The signal line smooths the MACD line, and the histogram is MACD minus signal. In the usual EMA formulation, the familiar 12, 26, and 9 lengths are defaults to inspect, not universally best settings.

A crossover above the signal line means that the histogram has crossed above zero. It does not necessarily mean price will rise, nor does a shrinking histogram guarantee an imminent reversal. TradingView's MACD documentation explains the calculation and available indicator settings.

Pine's ta.macd() returns three series: the MACD line, signal line, and histogram. An indicator can plot them; a strategy additionally defines simulated orders.

Complete Pine v6 strategy​

This example enters long on an upward crossover and short on a downward crossover. Opposite entries reverse the position. It uses one unit per position, no pyramiding, and illustrative commission and slippage values so the testing assumptions are visible.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify
//@version=6
strategy("MACD Crossover Educational Baseline", overlay=false, initial_capital=10000, default_qty_type=strategy.fixed, default_qty_value=1, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.1, slippage=1)
fastLength = input.int(12, "Fast length", minval=1)
slowLength = input.int(26, "Slow length", minval=1)
signalLength = input.int(9, "Signal length", minval=1)
if fastLength >= slowLength
runtime.error("Fast length must be smaller than slow length.")
[macdLine, signalLine, histogram] = ta.macd(close, fastLength, slowLength, signalLength)
plot(macdLine, "MACD", color=color.blue)
plot(signalLine, "Signal", color=color.orange)
plot(histogram, "Histogram", color=histogram >= 0 ? color.green : color.red, style=plot.style_histogram)
hline(0, "Zero", color=color.gray)
crossUp = ta.crossover(macdLine, signalLine)
crossDown = ta.crossunder(macdLine, signalLine)
if crossUp and barstate.isconfirmed
strategy.entry("Long", strategy.long)
if crossDown and barstate.isconfirmed
strategy.entry("Short", strategy.short)

The 0.1% commission is an assumed percentage charge per order, and slippage is one minimum tick. Replace these assumptions with values appropriate to the instrument and execution process you intend to study. One unit has different economic meaning for a share, a futures contract, or another instrument; the example does not implement risk-based position sizing.

Read the order behavior correctly​

The strategy uses the default bar-close calculation behavior. A market order created after a signal is normally filled on the next available tick in the broker emulator, commonly the next bar's open in a historical test. The signal and fill can therefore appear on different bars.

An opposite strategy.entry() reverses the existing position rather than merely closing it. A reversal transaction includes the quantity needed to close the current position and establish the new one. The script has no independent stop-loss or take-profit orders; a position remains open until an opposite entry or the end of the available test data.

These choices are deliberately simple. Review TradingView's strategy documentation before changing order settings or interpreting the trade list as live fills.

Validate a backtest before comparing settings​

Start with a standard price chart. Record the exact exchange-qualified symbol, timeframe, test dates, chart type, capital, quantity, costs, and strategy properties. Compare several visible crossovers with the trade list to confirm the implementation before studying performance.

Then inspect drawdown, trade count, average trade, exposure, and the distribution of wins and losses. A low win rate can coexist with positive or negative returns; its meaning depends on payoff sizes and costs. This article does not supply a verified BTCUSD or other market backtest.

Shorter lengths generally react more quickly, while longer lengths smooth more history. Neither is automatically better for crypto or stocks. If you test many combinations, retain the search record and evaluate the chosen settings on data not used to select them. Adding RSI, volume, or a trend filter is a new hypothesis, not a guaranteed improvement.

Building and reviewing MACD in Pineify​

Pineify provides visual and AI-assisted workflows for creating scripts. Combining calculations into one script can reduce chart slots used, but it does not remove Pine's plotting, data-request, or runtime limits. Review the exported source and strategy properties as you would hand-written code.

Pineify visual Pine Script editor interface
MACD indicator built with Pineify visual editor
MACD crossover strategy backtest results showing buy and sell signals

The images illustrate editor and chart interfaces. They are not evidence of returns for the revised example above; no performance figures are attributed to them here. See the feature overview for the available editing workflow.

Frequently asked questions​

Is a bullish MACD crossover a guaranteed buy signal?

No. It identifies a relationship between smoothed price series. Whether using it as an entry rule has value depends on the complete strategy and testing assumptions.

Does this script trade a broker account?

No. It submits simulated orders to TradingView's broker emulator. Live execution requires a separately configured and tested route.

What are the best MACD settings for crypto?

No universal best setting is established here. Treat parameter choices as hypotheses and account for costs, selection bias, and different market conditions.

Does this strategy contain a stop loss?

No. It reverses on the opposite crossover. Add and independently verify explicit exits if your research specification requires them.