Automated MACD Divergence Forex Trading Strategy

May 11, 2021

The MACD is a simple and effective momentum indicator. Here’s how you can save screen time by programming a MACD divergence strategy for the GBPJPY!

You can download the strategy below from the Free Strategies section.

The Moving Average Convergence/Divergence (MACD) is a household name in the world of technical trading.

Developed by Gerald Appel in the 1970s, it measures momentum by plotting the difference between two exponential moving averages (EMA).

MACD Calculations

I’ll use MT4’s default MACD from here on out. It consists of two lines: The main line and the signal line.

The MACD main line is simply the difference between a 12 and 26-period EMA, and is plotted as a histogram in this version of the MACD.

Notice that the main line crosses under 0 when the 12-period EMA crosses under the 26-period EMA.

The MACD signal line is a 9-period simple moving average of the main line.

Sometimes, you see a different version of the MACD, where the difference between the MACD main line and signal line (not the 12 and 26-period EMAs) is plotted as a histogram.

This version is shown below, using the same prices above.

I actually prefer this second version of the MACD, and you can download it here. Nonetheless, I’ll stick with MT4’s default MACD for the rest of this post.

How is the MACD Used?

The MACD is primarily used to detect short-term momentum.

When there is an upside move, the 12-period EMA reacts faster than the 26-period EMA. This causes the two EMAs to diverge, and the MACD main line increases.

The MACD is great at visually quantifying the momentum of these moves.

Here’s how you can use the MACD to generate entry signals.

1. Zero Line Crossover

This is similar to an EMA crossover.

When the MACD main line crosses above zero, momentum is bullish, and a long trade can be opened.

Conversely, short trades can be opened when the main line crosses below zero.

You can use the signal line instead of the main line if you prefer a slower but more reliable signal.

2. Signal Line Crossover

Long trades are opened when the main line crosses above the signal line, while shorts are opened when the main line crosses below the signal line.

Unlike the zero line crossover, the signal line crossover takes momentum into consideration, making it more reliable in general. 

Both the zero line and signal line crossovers have been backtested extensively, so let’s try something different here.

MACD Momentum Divergence

Momentum divergence occurs when price and momentum move in opposite directions.

There are two types of divergence: Regular and hidden.

1. Regular Divergence

A regular divergence indicates momentum leaving the trend, signalling a possible trend reversal.

During a downtrend, a regular bullish divergence occurs when prices make a lower low, but the MACD makes a higher low. 

During an uptrend, a regular bearish divergence occurs when price makes a higher high, but the MACD makes a lower high. 

2. Hidden Divergence

A hidden divergence indicates momentum entering the trend, signalling a possible trend continuation.

During an uptrend, a hidden bullish divergence occurs when price makes a higher low, but the MACD makes a lower low.

During a downtrend, a hidden bearish divergence occurs when price makes a lower high, but the MACD makes a higher high.

Unfortunately, momentum divergences are relatively uncommon and can be tricky to detect. Real price action is never as clean as the textbook diagrams above. The chart below shows a bullish hidden divergence between prices and the MACD main line.

Can we automate a MACD divergence strategy to cut down our screen time?

Let’s give it a shot!

Programming MACD Divergence

Since I mostly trade trend following strategies, I’ll focus on using hidden divergences to predict trend continuation.

I want to trade in the direction of the long-term trend, and use the MACD to time my entries.

The challenge lies in programming the swing highs/lows that form the basis of divergence. How do you algorithmically define a swing?

You’ll face the following questions when programming a swing high:

  • How many bars should be on either side of the highest bar?
  • Must the bars be in stairstep fashion, i.e. steadily increasing then steadily decreasing?

It’s easy to end up with a whole bunch of rules when attempting to program a swing. yell 

To keep the strategy simple, I’ll consider divergence to be present whenever price and momentum move in opposite directions. The presence of a swing will not be relevant. 

I’ll use the following simplified logic for price and the MACD main line.

A bullish hidden divergence is present when:

  • Price – The most recent low is above the highest low of the previous 10 periods
  • MACD – The most recent MACD value is below the lowest MACD value of the previous 10 periods

A bearish hidden divergence is present when:

  • Price – The most recent high is below the lowest high of the previous 10 periods
  • MACD – The most recent MACD value is above the highest MACD value of the previous 10 periods

As clear as mud? Here’s an illustration for bullish hidden divergence:

And here’s bearish hidden divergence:

Now that the MACD divergence criteria have been settled, I’ll start programming the strategy in AlgoWizard. Here’s the long side:

  1. The Indicator Highest function returns the highest price/indicator value over the lookback period. Indicator Lowest returns the lowest value.
  2. 0‘ means the highest value will be returned. Using ‘1’ will return the second highest value, and so on. 
  3. DivergencePeriod is the lookback period, and will be set to 10. Using anything below 5 will likely produce a large number of false entries.
  4. The bar shift [2] refers to the second most recently completed bar. The 10-bar lookback period starts from this bar. If you mistakenly set a bar shift of [1] here, this condition will never be satisfied because the left-hand side uses the most recently completed bar.

And likewise for the short side:

Adding a Long-term Trend Filter

From my experience, using the MACD in isolation will generate tons of false entries.

I’ll add a simple trend filter to counter this.

The strategy will only go long when price closes above the 20-period EMA, and the 20-period EMA is above the 50-period EMA.

Likewise, shorts will require price to close below the 20-period EMA, and the 20-period EMA must be below the 50-period EMA.

Here’s a long entry:

A few clicks in AlgoWizard and the trend filter is all set:

Trade Management

Most of the trend following strategies in this blog only use a trailing stop for trade management.

Such minimalism is intentional because I want to ride the trend until it reverses.

Of course, the flip side is that I may lose a chunk of open profits if the market reverses sharply.

Other trade management methods may be preferable if you want to minimize your time in the market. I’ll experiment with the following for this strategy:

  1. 70-pip catastrophic stop loss
  2. 30-pip breakeven stop loss
  3. 150-bar time stop (about 3 days on the M30 timeframe)
  4. Exit trades at Friday 3pm (New York time)

Backtesting the MACD Divergence Strategy

Momentum divergences don’t occur that often, so I’ll max out my backtest period to about 17.5 years.

We’ve a healthy sample of 825 trades here. There is some stagnation towards the end of the backtest, but it’s fair to say the strategy has a long-term edge.

You may obtain better results with some careful parameter optimizations, or by trading on a different market.

Wrapping Up

So there you have it! An automated MACD divergence strategy that helps you ride the trends without investing too much screen time.

I hope I’ve demonstrated that automated divergence trading is certainly possible; the main challenge is translating the divergence patterns into programmable logic.

You can refine the strategy by programming in the actual swing highs and lows. I think this will improve the win rate, at the expense of trading frequency. Hidden divergences seem to be far more subtle and uncommon than regular divergences.

If the MACD is not your thing, you can trade divergences using other momentum indicators like the RSI and CCI.

As usual, feel free to download the divergence strategy if you’d like to give it a go!

Powered By

Development Platform

Forex VPS

FXVM Forex VPS

Popular Posts

No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.

Make your money work for you!

Get promotions, trading ideas and strategy development tips delivered to your inbox!

Comments

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Trading Strategies

Forex Trading With Volume – Does It Work?

Forex Trading With Volume – Does It Work?

Volume is seldom discussed in forex trading. But as a stock trader would tell you, volume provides insights into the underlying market sentiment. Here I’ll demonstrate the use of two simple volume filters to improve entry reliability.

What Is the Kaufman Adaptive Moving Average?

What Is the Kaufman Adaptive Moving Average?

The Kaufman Adaptive Moving Average is a unique indicator that automatically adapts to the market’s noise. Here I explain its inner workings and show you how to build a trend following strategy around it.

Awesome Oscillator Forex Trend Strategy

Awesome Oscillator Forex Trend Strategy

The Awesome Oscillator is one of Bill Williams’ fine creations. It is a simple yet effective momentum indicator that can be a valuable addition to your strategy. Here we’ll use it together with a moving average to fine-tune our trend following entries.

Dual CCI Indicator Forex Trend Strategy

Dual CCI Indicator Forex Trend Strategy

The Commodity Channel Index (CCI) is an underrated momentum indicator that is often overshadowed by the RSI and MACD. I’ll show you how to build a simple trend following strategy using a pair of CCI indicators!

What is Fixed Ratio Money Management?

What is Fixed Ratio Money Management?

Have you heard of fixed ratio money management? How does it compare to the popular fixed fractional approach? Here I’ll explain how fixed ratio works, and see how it stacks up against fixed fractional money management.

What Is the Kaufman Efficiency Ratio?

What Is the Kaufman Efficiency Ratio?

Avoiding false breakouts is a common goal among trend traders. The Kaufman Efficiency Ratio provides a simple method of quantifying a market’s noise, helping traders focus on the smoothest trends. Let’s add the efficiency ratio to a simple trend following strategy and see whether its performance improves.

What Is the QQE Indicator?

What Is the QQE Indicator?

The QQE is a mysterious indicator that sometimes pops up in trading forums. Does it deserve a place alongside the more traditional momentum indicators like the RSI and CCI? Let’s add it to a trend following strategy to find out!

Do Bollinger Bands + Candlestick Patterns Work?

Do Bollinger Bands + Candlestick Patterns Work?

Bollinger Bands are great at detecting overbought and oversold conditions. Let’s use them to develop a countertrend strategy, and then refine our entries using limit entries and candlestick patterns.

How Good Are The Bollinger Bands’ Trailing Stops?

How Good Are The Bollinger Bands’ Trailing Stops?

Trailing stop losses are a popular feature in many trend following systems. Bollinger Bands, the ever-popular technical indicator among retail traders, actually contain two inbuilt trailing stops. Are these any good? Let’s find out!

Bollinger Bands vs. Keltner Channels

Bollinger Bands vs. Keltner Channels

Bollinger Bands are ubiquitous in the trading world, but there’s less discussion about their lesser-known cousin, the Keltner Channels. Do these perform as well as the Bollinger Bands? Let’s compare them over a broad range of input parameters.

Strategy Development

How to Select the Best Trading Strategy Entry

How to Select the Best Trading Strategy Entry

With an abundance of technical indicators available, selecting your strategy’s entry conditions can be overwhelming. This post will illustrate a method to graphically compare the profitability of different entries.

Live Trading

No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.

Make your money work for you!

Make your money work for you!

 

Get trading ideas and strategy development tips delivered to your inbox!

Thanks for subscribing!

Pin It on Pinterest

Share This