ea_DivergenceTrader_Ron_MT4_v05

Author: Ron Thompson
Profit factor:
0.78
Price Data Components
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself
Indicators Used
Moving average indicator
Miscellaneous
Uses files from the file systemIt writes information to fileIt issuies visual alerts to the screen
5 Views
0 Downloads
0 Favorites
ea_DivergenceTrader_Ron_MT4_v05
/*
+--------+
|Divergence Trader
+--------+
*/


// variables declared here are GLOBAL in scope

#property copyright "Ron Thompson"
#property link      "http://www.lightpatch.com/forex"

// user input
extern double Lots=0.1;               // how many lots to trade at a time 
extern int    Slippage=2;             // how many pips of slippage can you tolorate
extern int    Fast_Period=7;
extern int    Fast_Price = PRICE_OPEN;
extern int    Slow_Period=88;
extern int    Slow_Price = PRICE_OPEN;
extern double DVBuySell=0.0011;
extern double DVStayOut=0.0079;
extern double ProfitMade=0;           // how much money do you expect to make
extern double LossLimit=0;            // how much loss can you tolorate
extern double TrailStop=9999;         // trailing stop (999=no trailing stop)
extern int    PLBreakEven=9999;       // set break even when this many pips are made (999=off)
extern int    StartHour=0;            // your local time to start making trades
extern int    StopHour=24;            // your local time to stop making trades
extern int    BasketProfit=75;        // if equity reaches this level, close trades
extern int    BasketLoss=9999;        // if equity reaches this negative level, close trades
extern bool   FileData=false;

// naming and numbering
int      MagicNumber  = 200601182020; // allows multiple experts to trade on same account
string   TradeComment = "Divergence_00_";

// Bar handling
datetime bartime=0;                   // used to determine when a bar has moved
int      bartick=0;                   // number of times bars have moved
int      objtick=0;                   // used to draw objects on the chart
int      tickcount=0;

// Trade control
bool TradeAllowed=true;               // used to manage trades

// Min/Max tracking
double maxOrders;
double maxEquity;
double minEquity;
double CECount;
double CEProc;
double CEBuy;
double CESell;



//+-------------+
//| Custom init |
//|-------------+
// Called ONCE when EA is added to chart or recompiled

int init()
  {
   int    i;
   string o;
   
   //remove the old objects 
   for(i=0; i<Bars; i++) 
     {
      o=DoubleToStr(i,0);
      ObjectDelete("myx"+o);
      ObjectDelete("myz"+o);
     }
   objtick=0;

   ObjectDelete("Cmmt");
   ObjectCreate("Cmmt", OBJ_TEXT, 0, Time[20], High[20]+(5*Point()));
   ObjectSetText("Cmmt","Divergence=0.0020",10,"Arial",White);

   Print("Init happened ",CurTime());
   Comment(" ");
  }

//+----------------+
//| Custom DE-init |
//+----------------+
// Called ONCE when EA is removed from chart

int deinit()
  {
   int    i;
   string o;
   //remove the old objects 
   
   for(i=0; i<Bars; i++) 
     {
      o=DoubleToStr(i,0);
      ObjectDelete("myx"+o);
      ObjectDelete("myz"+o);
     }
   objtick=0;
   
   Print("MAX number of orders ",maxOrders);
   Print("MAX equity           ",maxEquity);
   Print("MIN equity           ",minEquity);
   Print("Close Everything     ",CECount);
   Print("Close Proc           ",CEProc);
   Print("Proc Buy             ",CEBuy);
   Print("Proc Sell            ",CESell);
      
   Print("DE-Init happened ",CurTime());
   Comment(" ");
  }


//+-----------+
//| Main      |
//+-----------+
// Called EACH TICK and each Bar[]

int start()
  {

   double p=Point();
   double spread=Ask-Bid;
   
   int      cnt=0;
   int      gle=0;
   int      OrdersPerSymbol=0;
   int      OrdersBUY=0;
   int      OrdersSELL=0;
   
   int      iFileHandle;
  
   // stoploss and takeprofit and close control
   double SL=0;
   double TP=0;
   double CurrentProfit=0;
   double CurrentBasket=0;
   
   // direction control
   bool BUYme=false;
   bool SELLme=false;
   
   // Trade stuff
   double diverge;
      

   // bar counting
   if(bartime!=Time[0]) 
     {
      bartime=Time[0];
      bartick++; 
      objtick++;
      TradeAllowed=true;
     }

   OrdersPerSymbol=0;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         OrdersPerSymbol++;
         if(OrderType()==OP_BUY) {OrdersBUY++;}
         if(OrderType()==OP_SELL){OrdersSELL++;}
        }
     }
   if(OrdersPerSymbol>maxOrders) maxOrders=OrdersPerSymbol;


   //+-----------------------------+
   //| Insert your indicator here  |
   //| And set either BUYme or     |
   //| SELLme true to place orders |
   //+-----------------------------+
   
   diverge=divergence(Fast_Period,Slow_Period,Fast_Price,Slow_Price,0);
   ObjectDelete("Cmmt");
   ObjectCreate("Cmmt", OBJ_TEXT, 0, Time[0], High[0]+(10*p));
   ObjectSetText("Cmmt","Divergence="+DoubleToStr(diverge,4),10,"Arial",White);
   if( diverge>=DVBuySell        && diverge<=DVStayOut )         BUYme=true;
   if( diverge<=(DVBuySell*(-1)) && diverge>=(DVStayOut*(-1)) ) SELLme=true;
   //if( diverge>=DVBuySell        ) BUYme=true;
   //if( diverge<=(DVBuySell*(-1)) ) SELLme=true;
   
   if(FileData)
     {
      tickcount++;
      iFileHandle = FileOpen("iDivergence", FILE_CSV|FILE_READ|FILE_WRITE, ",");
      FileSeek(iFileHandle, 0, SEEK_END);
      FileWrite(iFileHandle, bartick, " ", tickcount, " ", diverge);
      FileFlush(iFileHandle);
      FileClose(iFileHandle);
     }

   //+------------+
   //| End Insert |
   //+------------+

   //ENTRY LONG (buy, Ask) 
   if(TradeAllowed && BUYme)
      {
       //Ask(buy, long)
      if(LossLimit ==0) SL=0; else SL=Ask-((LossLimit+7)*Point() );
      if(ProfitMade==0) TP=0; else TP=Ask+((ProfitMade+7)*Point() );
      OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,SL,TP,TradeComment,MagicNumber,White);
      gle=GetLastError();
      if(gle==0)
        {
         Print("BUY  Ask=",Ask," bartick=",bartick);
         ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
         ObjectSetText("myx"+DoubleToStr(objtick,0),"B",15,"Arial",Red);
         bartick=0;
         TradeAllowed=false;
        }
         else 
        {
         Print("-----ERROR----- BUY  Ask=",Ask," error=",gle," bartick=",bartick);
        }
     }
        
   //ENTRY SHORT (sell, Bid)
   if(TradeAllowed && SELLme )
     {
      //Bid (sell, short)
      if(LossLimit ==0) SL=0; else SL=Bid+((LossLimit+7)*Point() );
      if(ProfitMade==0) TP=0; else TP=Bid-((ProfitMade+7)*Point() );
      OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,SL,TP,TradeComment,MagicNumber,Red);
      gle=GetLastError();
      if(gle==0)
        {
         Print("SELL Bid=",Bid," bartick=",bartick); 
         ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
         ObjectSetText("myx"+DoubleToStr(objtick,0),"S",15,"Arial",Red);
         bartick=0;
         TradeAllowed=false;
        }
         else 
        {
         Print("-----ERROR----- SELL Bid=",Bid," error=",gle," bartick=",bartick);
        }
     }

     

   //Basket profit or loss
   CurrentBasket=AccountEquity()-AccountBalance();
   
   if(CurrentBasket>maxEquity) maxEquity=CurrentBasket;
   if(CurrentBasket<minEquity) minEquity=CurrentBasket;
   
   // actual basket closure
   if( CurrentBasket>=BasketProfit || CurrentBasket<=(BasketLoss*(-1)) )
     {
      CloseEverything();
      CECount++;
     }

   // CLOSE order if profit target made
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
        {
        
         if(OrderType()==OP_BUY)
           {
            CurrentProfit=Bid-OrderOpenPrice() ;

            // modify for break even
            if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()>OrderStopLoss())
              {
               SL=OrderOpenPrice()+(spread*2);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("MODIFY BREAKEVEN BUY  Bid=",Bid," bartick=",bartick); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY BREAKEVEN BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }

            // modify for trailing stop
            if(CurrentProfit >= TrailStop*p )
              {
               SL=Bid-(TrailStop*p);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print ("MODIFY TRAILSTOP BUY  StopLoss=",SL,"  bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY TRAILSTOP BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }

            // did we make our desired BUY profit
            // or did we hit the BUY LossLimit
            if((ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p))  )
              {
               OrderClose(OrderTicket(),Lots,Bid,Slippage,White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("CLOSE BUY  Bid=",Bid," bartick=",bartick); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- CLOSE BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }
              
           } // if BUY


         if(OrderType()==OP_SELL)
           {

            CurrentProfit=OrderOpenPrice()-Ask;
            
            // modify for break even
            if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()<OrderStopLoss())
              {
               SL=OrderOpenPrice()-(spread*2);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("MODIFY BREAKEVEN SELL Ask=",Ask," bartick=",bartick);
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY BREAKEVEN SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
              }

            // modify for trailing stop
            if(CurrentProfit >= TrailStop*p)
              {
               SL=Ask+(TrailStop*p);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print ("MODIFY TRAILSTOP SELL StopLoss=",SL,"  bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY TRAILSTOP SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
              }

            // did we make our desired SELL profit?
            if( (ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p))  )
              {
               OrderClose(OrderTicket(),Lots,Ask,Slippage,Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("CLOSE SELL Ask=",Ask," bartick=",bartick);
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- CLOSE SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
                 
              }

           } //if SELL
           
        } // if(OrderSymbol)
        
     } // for

  } // start()



//+-----------------+
//| CloseEverything |
//+-----------------+
// Closes all OPEN and PENDING orders

int CloseEverything()
  {
   double myAsk;
   double myBid;
   int    myTkt;
   double myLot;
   int    myTyp;

   int i;
   bool result = false;
    
   for(i=OrdersTotal()-1;i>=0;i--)
     {
      OrderSelect(i, SELECT_BY_POS);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         myAsk=MarketInfo(OrderSymbol(),MODE_ASK);            
         myBid=MarketInfo(OrderSymbol(),MODE_BID);            
         myTkt=OrderTicket();
         myLot=OrderLots();
         myTyp=OrderType();
            
         switch( myTyp )
           {
            //Close opened long positions
            case OP_BUY      :result = OrderClose(myTkt, myLot, myBid, Slippage, Red);
            CEBuy++;
            break;
         
            //Close opened short positions
            case OP_SELL     :result = OrderClose(myTkt, myLot, myAsk, Slippage, Red);
            CESell++;
            break;

            //Close pending orders
            case OP_BUYLIMIT :
            case OP_BUYSTOP  :
            case OP_SELLLIMIT:
            case OP_SELLSTOP :result = OrderDelete( OrderTicket() );
           }
    
         if(result == false)
           {
            Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Sleep(3000);
           }  

         Sleep(1000);
         CEProc++;
        
        } //if
           
     } //for
  
  } // closeeverything




double divergence(int F_Period, int S_Period, int F_Price, int S_Price, int mypos)
  {

   int i;
   
   double maF1, maF2, maS1, maS2;
   double dv1, dv2;
   
   maF1=iMA(Symbol(),0,F_Period,0,MODE_SMA,F_Price,mypos);
   maS1=iMA(Symbol(),0,S_Period,0,MODE_SMA,S_Price,mypos);
   dv1=(maF1-maS1);

   maF2=iMA(Symbol(),0,F_Period,0,MODE_SMA,F_Price,mypos+1);
   maS2=iMA(Symbol(),0,S_Period,0,MODE_SMA,S_Price,mypos+1);
   dv2=((maF1-maS1)-(maF2-maS2));
     
   return(dv1-dv2);
   
  }




Profitability Reports

GBP/USD Jul 2025 - Sep 2025
1.40
Total Trades 1006
Won Trades 812
Lost trades 194
Win Rate 80.72 %
Expected payoff 5.60
Gross Profit 19579.90
Gross Loss -13942.30
Total Net Profit 5637.60
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
1.32
Total Trades 1129
Won Trades 843
Lost trades 286
Win Rate 74.67 %
Expected payoff 3.04
Gross Profit 14156.00
Gross Loss -10726.30
Total Net Profit 3429.70
-100%
-50%
0%
50%
100%
AUD/USD Jan 2025 - Jul 2025
1.32
Total Trades 2051
Won Trades 1441
Lost trades 610
Win Rate 70.26 %
Expected payoff 302.96
Gross Profit 2550974.10
Gross Loss -1929612.00
Total Net Profit 621362.10
-100%
-50%
0%
50%
100%
NZD/USD Jul 2025 - Sep 2025
1.18
Total Trades 1027
Won Trades 808
Lost trades 219
Win Rate 78.68 %
Expected payoff 2.95
Gross Profit 19981.20
Gross Loss -16946.70
Total Net Profit 3034.50
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
1.16
Total Trades 1077
Won Trades 840
Lost trades 237
Win Rate 77.99 %
Expected payoff 2.56
Gross Profit 19722.39
Gross Loss -16969.47
Total Net Profit 2752.92
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
1.15
Total Trades 1138
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff 2.26
Gross Profit 20296.60
Gross Loss -17724.90
Total Net Profit 2571.70
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
1.15
Total Trades 1191
Won Trades 904
Lost trades 287
Win Rate 75.90 %
Expected payoff 2.12
Gross Profit 19584.96
Gross Loss -17055.85
Total Net Profit 2529.11
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
1.03
Total Trades 999
Won Trades 681
Lost trades 318
Win Rate 68.17 %
Expected payoff 1.77
Gross Profit 52983.20
Gross Loss -51218.80
Total Net Profit 1764.40
-100%
-50%
0%
50%
100%
GBP/CAD Jan 2025 - Jul 2025
0.97
Total Trades 1865
Won Trades 1350
Lost trades 515
Win Rate 72.39 %
Expected payoff -0.66
Gross Profit 36094.12
Gross Loss -37333.07
Total Net Profit -1238.95
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.89
Total Trades 415
Won Trades 260
Lost trades 155
Win Rate 62.65 %
Expected payoff -1.93
Gross Profit 6789.06
Gross Loss -7590.81
Total Net Profit -801.75
-100%
-50%
0%
50%
100%
USD/CHF Jul 2025 - Sep 2025
0.86
Total Trades 965
Won Trades 667
Lost trades 298
Win Rate 69.12 %
Expected payoff -1.87
Gross Profit 11498.75
Gross Loss -13305.57
Total Net Profit -1806.82
-100%
-50%
0%
50%
100%
EUR/USD Jan 2025 - Jul 2025
0.83
Total Trades 791
Won Trades 468
Lost trades 323
Win Rate 59.17 %
Expected payoff -4.41
Gross Profit 17327.30
Gross Loss -20818.10
Total Net Profit -3490.80
-100%
-50%
0%
50%
100%
GBP/AUD Jul 2025 - Sep 2025
0.81
Total Trades 906
Won Trades 617
Lost trades 289
Win Rate 68.10 %
Expected payoff -5.08
Gross Profit 20167.66
Gross Loss -24768.83
Total Net Profit -4601.17
-100%
-50%
0%
50%
100%
USD/CHF Jul 2025 - Sep 2025
0.74
Total Trades 673
Won Trades 373
Lost trades 300
Win Rate 55.42 %
Expected payoff -5.95
Gross Profit 11580.48
Gross Loss -15585.45
Total Net Profit -4004.97
-100%
-50%
0%
50%
100%
USD/JPY Jul 2025 - Sep 2025
0.74
Total Trades 30
Won Trades 13
Lost trades 17
Win Rate 43.33 %
Expected payoff -11.03
Gross Profit 965.30
Gross Loss -1296.23
Total Net Profit -330.93
-100%
-50%
0%
50%
100%
AUD/USD Jul 2025 - Sep 2025
0.69
Total Trades 421
Won Trades 263
Lost trades 158
Win Rate 62.47 %
Expected payoff -9.54
Gross Profit 9008.40
Gross Loss -13025.90
Total Net Profit -4017.50
-100%
-50%
0%
50%
100%
GBP/AUD Jan 2025 - Jul 2025
0.60
Total Trades 330
Won Trades 181
Lost trades 149
Win Rate 54.85 %
Expected payoff -19.40
Gross Profit 9440.21
Gross Loss -15840.86
Total Net Profit -6400.65
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.58
Total Trades 193
Won Trades 79
Lost trades 114
Win Rate 40.93 %
Expected payoff -19.48
Gross Profit 5253.78
Gross Loss -9014.30
Total Net Profit -3760.52
-100%
-50%
0%
50%
100%
USD/CAD Jan 2025 - Jul 2025
0.44
Total Trades 248
Won Trades 117
Lost trades 131
Win Rate 47.18 %
Expected payoff -27.62
Gross Profit 5391.75
Gross Loss -12242.49
Total Net Profit -6850.74
-100%
-50%
0%
50%
100%
GBP/USD Jan 2025 - Jul 2025
0.43
Total Trades 69
Won Trades 30
Lost trades 39
Win Rate 43.48 %
Expected payoff -123.75
Gross Profit 6488.90
Gross Loss -15027.90
Total Net Profit -8539.00
-100%
-50%
0%
50%
100%
NZD/USD Jan 2025 - Jul 2025
0.42
Total Trades 347
Won Trades 149
Lost trades 198
Win Rate 42.94 %
Expected payoff -18.43
Gross Profit 4590.60
Gross Loss -10986.40
Total Net Profit -6395.80
-100%
-50%
0%
50%
100%
GBP/CAD Jul 2025 - Sep 2025
0.35
Total Trades 193
Won Trades 35
Lost trades 158
Win Rate 18.13 %
Expected payoff -26.95
Gross Profit 2812.46
Gross Loss -8013.76
Total Net Profit -5201.30
-100%
-50%
0%
50%
100%
USD/CAD Jul 2025 - Sep 2025
0.22
Total Trades 313
Won Trades 114
Lost trades 199
Win Rate 36.42 %
Expected payoff -16.95
Gross Profit 1481.90
Gross Loss -6786.08
Total Net Profit -5304.18
-100%
-50%
0%
50%
100%
GBP/USD Jul 2025 - Sep 2025
0.18
Total Trades 142
Won Trades 60
Lost trades 82
Win Rate 42.25 %
Expected payoff -24.26
Gross Profit 736.30
Gross Loss -4180.70
Total Net Profit -3444.40
-100%
-50%
0%
50%
100%
EUR/USD Jul 2025 - Sep 2025
0.00
Total Trades 170
Won Trades 103
Lost trades 67
Win Rate 60.59 %
Expected payoff -9928.67
Gross Profit 2848.70
Gross Loss -1690722.80
Total Net Profit -1687874.10
-100%
-50%
0%
50%
100%

Comments