MACD in Algorithmic Trading: Calculations, Strategies, and MQL4 Example

The Moving Average Convergence Divergence (MACD) is a popular indicator in algorithmic trading that combines trend-following and momentum analysis. By comparing two moving averages of different lengths, MACD helps identify shifts in momentum, signalling potential trend reversals. In this article, we’ll discuss the MACD’s components, how it’s calculated, and how to use it in trading algorithms. We’ll also provide a practical MQL4 example of a MACD-based trading strategy.

What is the MACD Indicator?

MACD is a momentum indicator that tracks the relationship between two moving averages—typically a 12-period EMA (fast) and a 26-period EMA (slow). MACD oscillates around a zero line, helping traders identify bullish or bearish momentum.

MACD Components:

  1. MACD Line: The difference between the 12-period EMA and the 26-period EMA.
  2. Signal Line: A 9-period EMA of the MACD line, which acts as a trigger for buy and sell signals.
  3. MACD Histogram: Represents the difference between the MACD line and the signal line, visually indicating the momentum’s strength.

How MACD is Calculated

1. Calculate the MACD Line:

MACD Line

2. Calculate the Signal Line:

Signal Line

3. Calculate the MACD Histogram:

MACD Histogram

Applications of MACD in Trading Algorithms

1. MACD Crossover Strategy:

  • Buy when the MACD line crosses above the signal line, indicating a potential upward momentum shift.
  • Sell when the MACD line crosses below the signal line, signalling potential bearish momentum.

2. Zero Line Cross:

  • A cross above the zero line is often seen as a bullish signal, while a cross below indicates a bearish trend.

3. Divergence:

  • MACD divergence occurs when the price is making higher highs but MACD is making lower highs (or vice versa), indicating a potential trend reversal.

MACD Crossover Strategy Example in MQL4

The following MQL4 example demonstrates a MACD crossover strategy, where a buy signal is generated when the MACD line crosses above the signal line, and a sell signal is triggered when it crosses below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// MACD Crossover Strategy in MQL4
input int FastEMAPeriod = 12;         // Period for fast EMA
input int SlowEMAPeriod = 26;         // Period for slow EMA
input int SignalPeriod = 9;           // Period for signal line
input double LotSize = 0.1;           // Lot size for orders
 
// Global variables to track trade status
bool buyTradeOpen = false;
bool sellTradeOpen = false;
 
void OnTick() {
   double macdLine = iMACD(NULL, 0, FastEMAPeriod, SlowEMAPeriod, SignalPeriod, PRICE_CLOSE, MODE_MAIN, 0);
   double signalLine = iMACD(NULL, 0, FastEMAPeriod, SlowEMAPeriod, SignalPeriod, PRICE_CLOSE, MODE_SIGNAL, 0);
 
   // Buy signal: MACD line crosses above Signal line
   if (macdLine > signalLine && !buyTradeOpen) {
       if (sellTradeOpen) CloseSell();
       OpenBuy();
   }
   // Sell signal: MACD line crosses below Signal line
   else if (macdLine < signalLine && !sellTradeOpen) { if (buyTradeOpen) CloseBuy(); OpenSell(); } } // Function to open a buy position void OpenBuy() { int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, 0, 0, "MACD Buy", 0, 0, clrGreen); if (ticket > 0) {
       buyTradeOpen = true;
       sellTradeOpen = false;
       Print("Buy order opened.");
   } else {
       Print("Error opening buy order: ", GetLastError());
   }
}
 
// Function to open a sell position
void OpenSell() {
   int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, 0, 0, "MACD Sell", 0, 0, clrRed);
   if (ticket > 0) {
       sellTradeOpen = true;
       buyTradeOpen = false;
       Print("Sell order opened.");
   } else {
       Print("Error opening sell order: ", GetLastError());
   }
}
 
// Function to close any open buy position
void CloseBuy() {
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
       if (OrderSelect(i, SELECT_BY_POS) && OrderType() == OP_BUY) {
           OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrGreen);
           buyTradeOpen = false;
           Print("Buy order closed.");
       }
   }
}
 
// Function to close any open sell position
void CloseSell() {
   for (int i = OrdersTotal() - 1; i >= 0; i--) {
       if (OrderSelect(i, SELECT_BY_POS) && OrderType() == OP_SELL) {
           OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrRed);
           sellTradeOpen = false;
           Print("Sell order closed.");
       }
   }
}

Explanation of the MACD Strategy

1. Parameters:

  • FastEMAPeriod and SlowEMAPeriod define the periods for the fast and slow EMAs.
  • SignalPeriod sets the period for the signal line.
  • LotSize controls the trade size for each position.

2. Trade Execution:

  • A buy signal is generated when the MACD line crosses above the signal line, suggesting an upward trend.
  • A sell signal is generated when the MACD line crosses below the signal line, indicating downward momentum.

3. Functions:

  • OpenBuy() and OpenSell() initiate trades based on MACD crossover signals.
  • CloseBuy() and CloseSell() close trades when an opposite signal appears.

This MACD-based strategy is effective for capturing trend shifts, making it ideal for trend-following traders who want to automate entries and exits based on momentum changes.

Tips for Optimising MACD Strategies

  1. Experiment with MACD Periods: Different asset classes may respond better to alternative settings, so test different EMA and signal line periods to find the best fit.
  2. Combine with Volume Indicators: Adding a volume filter can help confirm momentum, reducing the likelihood of false signals.
  3. Adjust Risk Parameters: Use the MACD histogram’s strength to adjust position sizing, entering larger trades when momentum is stronger.

Conclusion

The MACD is a powerful tool in trend-following and momentum-based trading strategies, offering insights into trend direction and strength. With a versatile range of applications, the MACD is widely used in algorithmic trading systems. By understanding its calculation and using it in strategies, traders can identify key opportunities to enter and exit trades. In the next article, we’ll discuss Bollinger Bands and Volatility Trading, exploring how this popular volatility indicator can be used in algo trading.