Divergences between an indicator and the price can be powerful signals for a trend change. This post will show you how to program an indicator to automatically detect and visualise a bullish and bearish divergence by using so called arrays.
What is a Bullish or Bearish Divergence?
A perfect example of a bullish divergence is shown on the chart below: While the EUR/USD made a new low (see highlights), the MACD below already made a higher low. So the new low in the price was not confirmed by the indicator. Both series diverge which means that there could be a trend change soon.
Programming a Bullish or Bearish Divergence using Arrays
Let`s have a look at the programming to see how this divergence has been found automatically.
- The first thing to notice is, that I use two arrays to store the needed information. They first have an undefined length, and areÂ re-dimensioned every time a new MACD cross occurs (lines 13 & 14).
- These two arrays will be used to store the local lows of the market and the MACD: Every time MACD crosses above its trigger, this information is written (line 12 & 16/17).
- If there are at least two bullish MACD crossings (line 18), we can check for a divergence. For this example, a divergence is defined as a lower price low and a higher MACD low.
- Line 19 & 20 show how easy it is to do this comparison of different values when using arrays. In the end these arrays contain all MACD and market lows on the chart. Element i will be the current low, i+1 the previous, i+2 the one before and so on…
- If a divergence is found, the indicator simply draws a symbol on the MACD to indicate a divergence (line 21). If you would like to make this a strategy and backtest the significance of divergences, you would place a buy or sell command instead of the drawsymbol command.
In this example we coded an indicator for bullish divergences. In order to detect bearish divergences too, you would have add more lines of code like 18-21 to do the logic.
Tradesignal® is a registered trademark of Tradesignal GmbH. Unauthorized use or misuse is strictly prohibited. Data by Thomson Reuters Eikon.