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!

Want to develop a portfolio of automated trading strategies?

Supercharge your strategy development with StrategyQuant

Access 14-day FREE trial here!

Get up to USD 300 discount!

Strategies need improvement?

Use QuantAnalyzer’s powerful analysis tools

Try the FREE version here!

Get 20% Discount here!

FXVM Forex VPS
Follow Us

Popular Posts

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

read more

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.

read more

Build a Diversified Portfolio With QuantAnalyzer

The ability to efficiently trade a diversified portfolio of strategies is one of the biggest advantages of algorithmic trading. Here we will use QuantAnalyzer’s Portfolio Master to build a portfolio consisting of high performing, uncorrelated strategies.

read more

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!

read more

Hey there, Wayne here! I’m on a mission to develop robust algorithmic trading strategies for the forex markets. Trading Tact is where I share my trading methods and insights.

Follow Us
Have a Question?

Comments

0 Comments

Submit a Comment

Your email address will not be published.

Want to develop a portfolio of automated trading strategies?

Supercharge your strategy development with StrategyQuant

Access 14-day FREE trial here!

Get up to USD 300 discount!

Strategies need improvement?

Use QuantAnalyzer’s powerful analysis tools

Try the FREE version here!

Get 20% Discount here!

FXVM Forex VPS

Recent Posts

How to Find a Real Trading Guru

How to Find a Real Trading Guru

Every day I come across a trading guru offering educational content on the internet. Many of them speak of huge returns with minimal effort. Should these be trusted? Here’s some tips on how to separate the wheat from the chaff.

read more
How to Enjoy Stress-Free Trading

How to Enjoy Stress-Free Trading

Trading is a great way to make some additional income, but not if you’re constantly pulling your hair out. Here I offer 7 tips to help make your trading profitable and stress-free.

read more
How to Get a Realistic Backtest Spread

How to Get a Realistic Backtest Spread

Your choice of backtest spread can certainly make or break a strategy. This post will show you how to study the intraday spread variations of your market, and suggest several ways to avoid paying ridiculous spreads.

read more
Laguerre RSI Trend Following Strategy

Laguerre RSI Trend Following Strategy

The Laguerre RSI attempts to improve the responsiveness of the regular RSI, whilst keeping whipsaw trades to a minimum. Let’s see how well it detects short-term pullbacks for a trend following strategy!

read more
Do You Know Your Strategy’s Optimization Profile?

Do You Know Your Strategy’s Optimization Profile?

Your strategy’s optimization profile often reveals its robustness, helping you select strategies that will remain profitable in live trading. Here I explain why an optimization profile is important, and how you can easily obtain one using StrategyQuant’s optimizer.

read more
How to Use the Supertrend Indicator

How to Use the Supertrend Indicator

Despite its cool name, the Supertrend indicator often seems to slip under the radar. Here I explain how it’s calculated, and combine it with moving averages to produce a simple trend following strategy.

read more
How to Select the Best Forex VPS

How to Select the Best Forex VPS

A virtual private server (VPS) is a virtual computer that you can rent and access remotely. It provides a reliable platform on which to execute your forex strategies. This post will help you decide whether you need a VPS, and show you how to select an optimal VPS.

read more
Out-of-sample Testing Using Monte Carlo Simulations

Out-of-sample Testing Using Monte Carlo Simulations

Traders often use Monte Carlo simulations to estimate worst-case drawdowns, but did you know they can be used for out-of-sample testing too? This post demonstrates the use of StrategyQuant’s Monte Carlo simulator to randomize historical prices and strategy parameters, helping you select robust strategies for live trading.

read more

Hey there, Wayne here! I’m on a mission to develop robust algorithmic trading strategies for the forex markets. Trading Tact is where I share my trading methods and insights.

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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!

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