Divergence and Convergence Automated Trading Strategy

divergence vs convergence in forex trading
The short URL of the present article is: https://netbizint.com.au/div-conv-ea

Automating a trading strategy that identifies divergence and convergence is a complex task, as it requires the code to identify and compare swing highs and lows on both the price chart and an indicator.

To provide you with a functional and robust solution, I have developed two Expert Advisors (EAs)—one for MetaTrader 4 (MQL4) and one for MetaTrader 5 (MQL5).

These EAs implement a comprehensive trading strategy based on the principles we’ve discussed. Instead of attempting to programmatically draw trendlines to find divergence (which can be unreliable in code), this strategy uses a more mechanical and robust approach: it uses a MACD crossover as the primary entry signal and then uses the Relative Strength Index (RSI) and the Average Directional Index (ADX) as powerful filters.

This multi-indicator approach effectively captures the spirit of divergence and convergence trading:

  • Convergence (Agreement): A trade is only taken when the price action (signaled by the MACD crossover) and momentum (confirmed by the RSI and ADX) are in agreement. This confirms the trend’s strength.,,
  • Divergence (Disagreement): The strategy automatically filters out trades where there is a disagreement. For example, if a bullish MACD crossover occurs but the RSI is below 50 (indicating bearish momentum), no trade is taken. This is an implicit way of avoiding trades during periods of momentum divergence.,

Below are the complete codes for both platforms, along with instructions on how to use them.


MetaTrader 4 (MQL4) Expert Advisor Code

This EA is designed for the MT4 platform. It identifies potential trend reversals and continuations using a MACD crossover, confirmed by RSI and ADX filters, and includes built-in risk management.,,

How to Use the MQL4 Code:

  1. Open MetaEditor: In your MT4 platform, press F4 or go to Tools > MetaQuotes Language Editor.
  2. Create New EA: In MetaEditor, click File > New. In the wizard, select Expert Advisor (template) and click Next.
  3. Name the EA: Call it DivergenceConvergenceStrategy_MT4 and click Finish.
  4. Paste Code: Delete the template code and paste the MQL4 code below into the file.
  5. Compile: Click the Compile button. If there are no errors, you can close MetaEditor.
  6. Attach to Chart: In MT4, find the EA in the “Navigator” window. Drag it onto your desired chart (e.g., EUR/USD, H4).
  7. Enable AutoTrading: Ensure the “AutoTrading” button at the top of MT4 is enabled.

<!– end list –>

Code snippet

//+------------------------------------------------------------------+
//| DivergenceConvergenceStrategy_MT4.mq4 |
//| Copyright 2025, Award-Winning Writer |
//| |
//| This EA trades based on MACD crossovers, confirmed by RSI and ADX. |
//| It captures the principles of convergence by ensuring momentum |
//| and trend strength align before entering a trade. |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Award-Winning Writer"
#property link      "https://example.com"
#property version   "1.00"
#property strict

//--- EA Inputs (User-Configurable Settings)
//--- Indicator Settings
input int    MACD_Fast_EMA   = 12;     // Fast EMA for MACD
input int    MACD_Slow_EMA   = 26;     // Slow EMA for MACD
input int    MACD_Signal_SMA = 9;      // Signal line for MACD
input int    RSI_Period      = 14;     // Period for RSI
input int    ADX_Period      = 14;     // Period for ADX

//--- Filter Levels
input double RSI_Center_Line = 50.0;   // RSI must be above/below this level
input double ADX_Trend_Level = 25.0;   // ADX must be above this level to confirm a trend

//--- Risk Management Settings
input double Lots            = 0.01;   // Fixed lot size for trades
input double RiskRewardRatio = 2.0;    // Take Profit = Risk * Ratio

//--- Trade Management Settings
input int MagicNumber = 67890;  // Unique ID for trades from this EA
input int Slippage    = 3;      // Allowed slippage in points

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
   Print("Divergence Convergence Strategy Initialized.");
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function (main trading logic) |
//+------------------------------------------------------------------+
void OnTick()
{
   //--- Check if a new bar has started to avoid multiple trades per bar
   static datetime lastBarTime = 0;
   if(lastBarTime == Time)
      return;
   lastBarTime = Time;

   //--- Check if a trade is already open for this symbol
   if(IsTradeOpen())
      return;

   //--- Get indicator values for the last two closed bars (shift = 1 and 2)
   //--- We use shift=1 to ensure the signal is based on a completed candle
   
   // MACD Crossover Check
   double macd_main_1 = iMACD(NULL, 0, MACD_Fast_EMA, MACD_Slow_EMA, MACD_Signal_SMA, PRICE_CLOSE, MODE_MAIN, 1);
   double macd_signal_1 = iMACD(NULL, 0, MACD_Fast_EMA, MACD_Slow_EMA, MACD_Signal_SMA, PRICE_CLOSE, MODE_SIGNAL, 1);
   double macd_main_2 = iMACD(NULL, 0, MACD_Fast_EMA, MACD_Slow_EMA, MACD_Signal_SMA, PRICE_CLOSE, MODE_MAIN, 2);
   double macd_signal_2 = iMACD(NULL, 0, MACD_Fast_EMA, MACD_Slow_EMA, MACD_Signal_SMA, PRICE_CLOSE, MODE_SIGNAL, 2);

   // Confirmation Indicators
   double rsi_1 = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 1);
   double adx_1 = iADX(NULL, 0, ADX_Period, PRICE_CLOSE, MODE_MAIN, 1);
   
   //--- Define Entry Conditions ---
   
   // Bullish Conditions
   bool bullish_crossover = (macd_main_2 < macd_signal_2) && (macd_main_1 > macd_signal_1);
   bool bullish_rsi_confirm = (rsi_1 > RSI_Center_Line);
   bool trend_strong_confirm = (adx_1 > ADX_Trend_Level);

   // Bearish Conditions
   bool bearish_crossover = (macd_main_2 > macd_signal_2) && (macd_main_1 < macd_signal_1);
   bool bearish_rsi_confirm = (rsi_1 < RSI_Center_Line);
   // trend_strong_confirm is the same for both directions

   //--- Execute Trades ---
   
   // Check for BUY signal (Convergence of Bullish Signals)
   if(bullish_crossover && bullish_rsi_confirm && trend_strong_confirm)
   {
      double stop_loss_price = Low; // Stop below recent swing low
      double risk_pips = (Ask - stop_loss_price) / _Point;
      double take_profit_price = NormalizeDouble(Ask + (risk_pips * RiskRewardRatio * _Point), _Digits);
      
      OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, stop_loss_price, take_profit_price, "DivConv_Buy", MagicNumber, 0, clrGreen);
   }
   // Check for SELL signal (Convergence of Bearish Signals)
   else if(bearish_crossover && bearish_rsi_confirm && trend_strong_confirm)
   {
      double stop_loss_price = High; // Stop above recent swing high
      double risk_pips = (stop_loss_price - Bid) / _Point;
      double take_profit_price = NormalizeDouble(Bid - (risk_pips * RiskRewardRatio * _Point), _Digits);
      
      OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, stop_loss_price, take_profit_price, "DivConv_Sell", MagicNumber, 0, clrRed);
   }
}

//+------------------------------------------------------------------+
//| Helper function to check for open trades |
//+------------------------------------------------------------------+
bool IsTradeOpen()
{
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
         {
            return(true); // Found an open trade for this EA on this symbol
         }
      }
   }
   return(false);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   Print("Divergence Convergence Strategy Deinitialized.");
}
//+------------------------------------------------------------------+

MetaTrader 5 (MQL5) Expert Advisor Code

This EA is the modern equivalent for the MT5 platform. It uses the same core logic but is built with the updated MQL5 language and trading functions.

How to Use the MQL5 Code:

  1. Open MetaEditor: In your MT5 platform, press F4 or go to Tools > MetaQuotes Language Editor.
  2. Create New EA: In MetaEditor, click File > New. In the wizard, select Expert Advisor (template) and click Next.
  3. Name the EA: Call it DivergenceConvergenceStrategy_MT5 and click Finish.
  4. Paste Code: Delete the template code and paste the MQL5 code below into the file.
  5. Compile: Click the Compile button. If there are no errors, you can close MetaEditor.
  6. Attach to Chart: In MT5, find the EA in the “Navigator” window. Drag it onto your desired chart.
  7. Enable Algo Trading: Ensure the “Algo Trading” button at the top of MT5 is enabled.

<!– end list –>

Code snippet

//+------------------------------------------------------------------+
//| DivergenceConvergenceStrategy_MT5.mq5 |
//| Copyright 2025, Award-Winning Writer |
//| |
//| This EA trades based on MACD crossovers, confirmed by RSI and ADX. |
//| It captures the principles of convergence by ensuring momentum |
//| and trend strength align before entering a trade. |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Award-Winning Writer"
#property link      "https://example.com"
#property version   "1.00"

#include <Trade\Trade.mqh>

//--- EA Inputs (User-Configurable Settings)
//--- Indicator Settings
input int    MACD_Fast_EMA   = 12;     // Fast EMA for MACD
input int    MACD_Slow_EMA   = 26;     // Slow EMA for MACD
input int    MACD_Signal_SMA = 9;      // Signal line for MACD
input int    RSI_Period      = 14;     // Period for RSI
input int    ADX_Period      = 14;     // Period for ADX

//--- Filter Levels
input double RSI_Center_Line = 50.0;   // RSI must be above/below this level
input double ADX_Trend_Level = 25.0;   // ADX must be above this level to confirm a trend

//--- Risk Management Settings
input double Lots            = 0.01;   // Fixed lot size for trades
input double RiskRewardRatio = 2.0;    // Take Profit = Risk * Ratio

//--- Trade Management Settings
input ulong MagicNumber = 67890;  // Unique ID for trades from this EA
input int   Slippage    = 30;     // Allowed slippage in points

//--- Global variables and objects
CTrade trade;
int macd_handle;
int rsi_handle;
int adx_handle;

//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
   //--- Set up trade object
   trade.SetExpertMagicNumber(MagicNumber);
   trade.SetDeviationInPoints(Slippage);
   
   //--- Create indicator handles
   macd_handle = iMACD(_Symbol, _Period, MACD_Fast_EMA, MACD_Slow_EMA, MACD_Signal_SMA, PRICE_CLOSE);
   rsi_handle = iRSI(_Symbol, _Period, RSI_Period, PRICE_CLOSE);
   adx_handle = iADX(_Symbol, _Period, ADX_Period);
   
   if(macd_handle == INVALID_HANDLE |
| rsi_handle == INVALID_HANDLE |
| adx_handle == INVALID_HANDLE)
   {
      Print("Error creating indicator handles");
      return(INIT_FAILED);
   }
   
   Print("Divergence Convergence Strategy Initialized.");
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function (main trading logic) |
//+------------------------------------------------------------------+
void OnTick()
{
   //--- Check if a new bar has started
   static datetime lastBarTime = 0;
   if(TimeCurrent() == lastBarTime)
      return;
   lastBarTime = TimeCurrent();

   //--- Check if a trade is already open for this symbol
   if(PositionSelect(_Symbol))
      return;

   //--- Get indicator values
   double macd_main_buffer, macd_signal_buffer;
   double rsi_buffer;
   double adx_buffer;

   if(CopyBuffer(macd_handle, 0, 1, 2, macd_main_buffer) < 2 ||
      CopyBuffer(macd_handle, 1, 1, 2, macd_signal_buffer) < 2 ||
      CopyBuffer(rsi_handle, 0, 1, 1, rsi_buffer) < 1 ||
      CopyBuffer(adx_handle, 0, 1, 1, adx_buffer) < 1)
   {
      Print("Error copying indicator buffers");
      return;
   }
   
   double macd_main_1 = macd_main_buffer;
   double macd_signal_1 = macd_signal_buffer;
   double macd_main_2 = macd_main_buffer[1];
   double macd_signal_2 = macd_signal_buffer[1];
   
   double rsi_1 = rsi_buffer;
   double adx_1 = adx_buffer;

   //--- Define Entry Conditions ---
   
   // Bullish Conditions
   bool bullish_crossover = (macd_main_2 < macd_signal_2) && (macd_main_1 > macd_signal_1);
   bool bullish_rsi_confirm = (rsi_1 > RSI_Center_Line);
   bool trend_strong_confirm = (adx_1 > ADX_Trend_Level);

   // Bearish Conditions
   bool bearish_crossover = (macd_main_2 > macd_signal_2) && (macd_main_1 < macd_signal_1);
   bool bearish_rsi_confirm = (rsi_1 < RSI_Center_Line);
   // trend_strong_confirm is the same for both directions

   //--- Execute Trades ---
   
   // Check for BUY signal (Convergence of Bullish Signals)
   if(bullish_crossover && bullish_rsi_confirm && trend_strong_confirm)
   {
      MqlRates rates[2];
      if(CopyRates(_Symbol, _Period, 1, 10, rates) < 10) return;
      
      double low_prices[2];
      for(int i=0; i<10; i++) low_prices[i] = rates[i].low;
      int lowest_index = ArrayMinimum(low_prices, 0, 10);
      
      double stop_loss_price = rates[lowest_index].low;
      double risk = SymbolInfoDouble(_Symbol, SYMBOL_ASK) - stop_loss_price;
      double take_profit_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + (risk * RiskRewardRatio);
      
      trade.Buy(Lots, _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_ASK), stop_loss_price, take_profit_price, "DivConv_Buy");
   }
   // Check for SELL signal (Convergence of Bearish Signals)
   else if(bearish_crossover && bearish_rsi_confirm && trend_strong_confirm)
   {
      MqlRates rates[2];
      if(CopyRates(_Symbol, _Period, 1, 10, rates) < 10) return;

      double high_prices[2];
      for(int i=0; i<10; i++) high_prices[i] = rates[i].high;
      int highest_index = ArrayMaximum(high_prices, 0, 10);

      double stop_loss_price = rates[highest_index].high;
      double risk = stop_loss_price - SymbolInfoDouble(_Symbol, SYMBOL_BID);
      double take_profit_price = SymbolInfoDouble(_Symbol, SYMBOL_BID) - (risk * RiskRewardRatio);
      
      trade.Sell(Lots, _Symbol, SymbolInfoDouble(_Symbol, SYMBOL_BID), stop_loss_price, take_profit_price, "DivConv_Sell");
   }
}

//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   //--- Release indicator handles
   IndicatorRelease(macd_handle);
   IndicatorRelease(rsi_handle);
   IndicatorRelease(adx_handle);
   Print("Divergence Convergence Strategy Deinitialized.");
}
//+------------------------------------------------------------------+

Important Considerations for Automated Trading

  • Backtesting is Crucial: Before using this EA with real money, you must test it thoroughly in the MetaTrader Strategy Tester. Test it on different currency pairs and timeframes to see how it performs under various market conditions.
  • Risk Management: The provided code uses a fixed lot size. For more advanced risk management, you could modify the code to calculate the lot size based on a percentage of your account equity.
  • No Strategy is Perfect: This strategy is designed to filter out many low-quality signals, but no automated system is foolproof. It will perform best in trending markets and may experience losses during choppy, sideways conditions.
  • Divergence is a Concept: This code mechanizes the principles of divergence and convergence. True divergence often requires a discretionary eye to spot nuances on a chart. This EA provides a disciplined, rule-based way to trade the momentum shifts that divergence and convergence represent.,

Disclaimer: This code is provided for educational purposes only and is not financial advice. Trading forex and other financial markets involves substantial risk, and past performance is not indicative of future results. Always conduct your own thorough backtesting and risk assessment before deploying any automated trading strategy with real capital. Sources and related content

District of Columbia | Largest Ever Seizure of Funds Related to Crypto Confidence Scams

Source icon

justice.gov/usao-dc/pr/largest-ever-seizure-funds-related-crypto-confidence-scams

District of Columbia | Largest Ever Seizure of Funds Related to Crypto Confidence Scams

Source icon

justice.gov/usao-dc/pr/largest-ever-seizure-funds-related-crypto-confidence-scams

Avoid Scams: Investment Fraud and Pig Butchering – Secret Service

Source icon

secretservice.gov/investi

Tags:

No responses yet

Leave a Reply

Latest Comments

No comments to show.