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

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

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

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

Forex Weekend Gaps: Can You Exploit Them?

Forex Weekend Gaps: Can You Exploit Them?

Have you noticed that forex weekend gaps usually reverse within 3 days? Here I’ll program a mean reversion strategy to exploit gaps over the last 18 years!

Money Flow Index: An Improved RSI?

Money Flow Index: An Improved RSI?

The Money Flow Index is sometimes called the volume-weighted RSI. Can it outperform the RSI in this trend following strategy?

Automated Bollinger Bands Squeeze Forex Strategy

Automated Bollinger Bands Squeeze Forex Strategy

StrategyQuant’s BBWR indicator is the perfect tool to detect a Bollinger Bands squeeze. Here I explain how it’s calculated, and use it to program a breakout strategy for the AUDJPY!

Should You Use the Kelly Criterion for Forex Trading?

Should You Use the Kelly Criterion for Forex Trading?

The Kelly criterion is a famous mathematical formula that attempts to maximize your long-term capital growth. In this post, I’ll apply it to a EURUSD breakout strategy and explain some of its potential shortcomings when applied to forex trading.

Can a Trading Pause Improve Your Trend Following Results?

Can a Trading Pause Improve Your Trend Following Results?

A temporary trading pause can improve your win rate if you’re trend following a volatile market. Here I’ll program a trading pause into a simple breakout strategy, and test its effectiveness on the Widow Maker – the GBPJPY.

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!

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.

Ichimoku Trend Following Strategy

Ichimoku Trend Following Strategy

Like candlesticks, the Ichimoku indicator is a fine Japanese creation. Here I’ll explain how the Ichimoku is plotted, and use it to build a trend following strategy for the USDJPY.

Strategy Development

Do You Know Your System Quality Number?

Do You Know Your System Quality Number?

The System Quality Number measures the profitability & consistency of your trading system. Here’s how to calculate your SQN and use it to improve your trading!

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.

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.

Which MT4 Backtest Report Metrics Should You Use?

Which MT4 Backtest Report Metrics Should You Use?

Understanding your backtest report is an essential part of being a successful strategy developer. Here I explain what the numbers mean, and how you can make use of each metric during strategy development.

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.

How Many Trades Should Your Backtest Have?

How Many Trades Should Your Backtest Have?

We all want a large sample of trades in our backtests, but practical limitations such as data availability often get in the way. Here I’ll explain why 30 trades is insufficient, and how you can use standard error to quantify the uncertainty arising from a small sample size.

Build a Diversified Portfolio With QuantAnalyzer

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.

Strategy Optimization Using MT4

Strategy Optimization Using MT4

How do you improve your trading strategy in MT4? This post will show you how to optimize the entry and exit parameters for a moving average crossover strategy. Finally, an intraday time filter will be added to help avoid false breakouts.

Debugging & Backtesting Using MT4

Debugging & Backtesting Using MT4

With a fresh algorithm at your fingertips, how do you verify that it has been programmed correctly? This guide will show you how to use Metatrader 4’s visual backtester to debug and backtest your strategy.

Create Your Trading Algorithm in 15 Minutes (FREE)

Create Your Trading Algorithm in 15 Minutes (FREE)

Converting your trading idea into an algorithm is the first step towards reaping the benefits of automated trading. This guide will cover the creation of a simple moving average crossover algorithm, without any actual programming.

What Is Drawdown in Trading?

What Is Drawdown in Trading?

Are you getting a comprehensive assessment of your strategy’s downside? This post will discuss several methods to measure drawdowns, helping you build and select strategies that better suit your risk appetite.

Live Trading

What’s the Best Time to Trade Forex?

What’s the Best Time to Trade Forex?

The forex markets are open 24/5, but not all hours are created equal. Here I dissect my broker data to determine the best time to trade forex.

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.

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.

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.

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