Select Page

# 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.

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:

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!

## 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!

## 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.

## 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.

## 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.

## 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?

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?

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!

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.

###### Have a Question?

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!

## 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!

## Dynamic Position Sizing: Is It Time to Go Big?

Should you increase your lot sizes for higher probability trades? Let’s code a dynamic position sizing scheme to capture more outsized wins!

## Pivot Points: A Reliable Support & Resistance Indicator

Pivot points are the perfect tool if you trade using support & resistance. Here’s how to develop an automated pivot points forex strategy!

## 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?

## Trade Slippage: How Can You Simulate and Minimize It?

Are you a victim of excessive trade slippage? Here’s how you can minimize slippage, and more realistically simulate it in your backtests!

## Edge Ratio: A Unique Way to Quantify Entry Profitability

Selecting a profitable entry is a critical step in strategy development. Here I’ll demonstrate how to use the Edge Ratio to maximize your profit potential.

## 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!

## 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!

## Automated Schaff Trend Cycle Forex Strategy

The Schaff Trend Cycle is a unique combination of the MACD and Stochastic indicators. Here’s how you can use it to improve your trend following results!

## 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.

## Forex Intermarket Correlations: How Do You Exploit Them?

Knowledge of intermarket correlations can improve your forex trading win rate. Here I explain three important types of correlations, and how you can use them to benefit your trading.

## 5 Forex Day Trading Challenges & How to Overcome Them

Forex day trading seems to have a particular appeal to new traders. Here I highlight five hidden challenges of day trading, and offer some suggestions on how to overcome them.

## 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.

## Can Partial Profit Taking Benefit Trend Followers?

Partial profit taking is a dilemma often faced by long-term trend followers. Could this benefit your overall strategy performance?

Let’s test!

## Using Maximum Adverse Excursion for Stop Loss Placement

A catastrophic stop loss is a vital risk management tool for many traders. Here I’ll show you how to optimize your stop loss distance using maximum adverse excursion.

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!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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

## Make your money work for you!

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