EA Coding

 

It's probably staring me in the face but could someone point me to a resource where I can learn to create an EA myself?

Thanks in advance.....

 
Suggestions on learning MQL
https://www.mql5.com/en/forum/224425
Suggestions on learning MQL
Suggestions on learning MQL
  • 2018.01.11
  • www.mql5.com
Hello fellow coders/traders...
 
Sergey Golubev:
Suggestions on learning MQL
https://www.mql5.com/en/forum/224425
Thanks, will check it out :-)
 
what is the best way to learn coding if i dont have any background on it?
 
Hello!
I have to ask, is there no differens if I code in mql4 or mql5 anymore? ie I intend to learn but am unsure of where to start. Do I read in reference for mql4 so from build 600 it should be the same?.. Do I understand correctly, is it the same but with two names?

Confused
Johan
 

Hello Everyone,

I am new to MQL4 and have just started learning how to code in MQ4. After a couple of weeks' try I have tried to modify an existing EA on the web. It works, but it does not follow the logic I have tried to incorporate, which is: if MACD has peaked, place a SELL order; if MACD has bottomed, place a BUY order. Close the SELL order when MACD has bottomed, and then place a BUY order in the opposite direction. Close the BUY order when MACD has peaked, and then place SELL order in the opposite direction. I am using the open of the next bar to place the BUY/SELL order. Unfortunately, the EA does not do this, though it runs OK. Can someone be kind enough to have a look at it and provide some suggestions? The code is given below. Thanks much.

------------------

input double Risk = 2.0;    //percent of account bal at risk

input int TrailingStop = 195;       

input int StopLoss = 95;

input int TakeProfit=100;

input int MACD_Fast_Period = 7;

input int MACD_Slow_Period = 26;

input int MACD_Signal_Period = 15;

input int Slippage=3;



extern int Magic = 20170905;

extern ENUM_APPLIED_PRICE MACD_Price = PRICE_CLOSE;



extern bool EachTickMode = False;

//extern bool DirectionLong = True;



//------------------------

int BarCount;

int Current;

bool TickCheck = False;



//+------------------------------------------------------------------+

//| expert initialization function                                   |

//+------------------------------------------------------------------+

int init() {

   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;

   return(0);

}

//+------------------------------------------------------------------+

//| expert deinitialization function                                 |

//+------------------------------------------------------------------+

int deinit() {

   return(0);

}

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int start()

{

   double macd0, macd1, macd2, macd3, macd4, macd5;

   double order_sl=0, order_tp=0;

   int ticket=0, total;

 //----------------------------------------  

   

   // Initial data checks.

   if (Bars < 100)

   {

      Print("Less than 100 bars.");

      return(0);

   }

  //---to simplify the coding and speed up access data are put into internal variables

   macd0 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 0);

   macd1 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 1);

   macd2 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 2);

   macd3 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 3);

   macd4 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 4);

   macd5 =iMACD(Symbol(), Period(), MACD_Fast_Period, MACD_Slow_Period, MACD_Signal_Period, MACD_Price, MODE_MAIN, 5);

 //----------------------------------------  

   

   total = OrdersTotal();

   double Lots=getLots(Risk);

   int count = 0;

   for (int i = 0; i < total; i++)

   {

      if (OrderSelect(i, SELECT_BY_POS) == false) continue;

      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic) && ((OrderType() == OP_BUY) || (OrderType() == OP_SELL))) count++;

   }         

   // No open positions.

//+------------------------------------------------------------------+

//|                     Entry Conditions                             |

//+------------------------------------------------------------------+

   if (count == 0)

   {

      // Check for long position (BUY) possibility.

       if((macd2>macd1 && macd0>macd1)||(macd3>macd1 && macd2==macd1 && macd0>macd1)||      //If MACD has bottomed

          (macd4>macd1 && macd3==macd1 && macd2==macd1 && macd0>macd1)||

          (macd5>macd1 && macd4==macd1 && macd3==macd1 && macd2==macd1 && macd0>macd1))

        {

          if ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))

         {

         if (StopLoss > 0) order_sl = Ask - StopLoss * Point;

         order_tp = Ask + TakeProfit * Point;

         ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, order_sl, order_tp, "MACD Mfd1", Magic, 0, clrGreen);

         if (ticket > 0) Print("BUY order opened: ", OrderOpenPrice());

         else Print("Error opening BUY order: ", GetLastError()); 

         RefreshRates();

         }

         return(0); 

      }

      // Check for short position (SELL) possibility.

      //if ((MacdCurrent > 0) && (MacdCurrent < SignalCurrent) && (MacdPrevious > SignalPrevious) && 

      if((macd2<macd1 && macd0<macd1)||(macd3<macd1 && macd2==macd1 && macd0<macd1)||                    //If MACD has topped

        (macd4<macd1 && macd3==macd1 && macd2==macd1 && macd0<macd1)||

        (macd5<macd1 && macd4==macd1 && macd3==macd1 && macd2==macd1 && macd0<macd1)) 

        {

         if ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))

         {

         if (StopLoss > 0) order_sl = Bid + StopLoss * Point;

         order_tp = Bid - TakeProfit * Point;

         ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, order_sl, order_tp, "MACD Mfd1", Magic, 0, clrRed);

         if (ticket > 0)Print("SELL order opened: ", OrderOpenPrice());

         else Print("Error opening SELL order: ", GetLastError());

         RefreshRates();

         }

         return(0); 

      }

   }

//+------------------------------------------------------------------+

//|                     Exit Conditions                             |

//+------------------------------------------------------------------+

   for (int i = total; i >= 0; i--)

   {

      if (OrderSelect(i, SELECT_BY_POS) == false) continue;

      if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == Magic))

      {

         if (OrderType() == OP_BUY)

         {

            // Should it be closed?

         if((macd2<macd1 && macd0<macd1)||(macd3<macd1 && macd2==macd1 && macd0<macd1)||                    //If MACD has topped

           (macd4<macd1 && macd3==macd1 && macd2==macd1 && macd0<macd1)||

           (macd5<macd1 && macd4==macd1 && macd3==macd1 && macd2==macd1 && macd0<macd1)) 

           {

               if ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))

               {

               if (!OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, clrViolet)) Print("Error closing BUY order: ", GetLastError());

               //RefreshRates();

               //new block added for continuos buying & selling, and never being out of market------------------

               ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, order_sl, order_tp, "MACD Mfd1", Magic, 0, clrRed);

               if (ticket > 0) Print("SELL order opened: ", OrderOpenPrice());

               else Print("Error opening SELL order: ", GetLastError()); 

               //end of new block -------------------------------------------------------------------------------

               RefreshRates();

               }

               return(0);

            }

            // Trailing stop.

            if (TrailingStop > 0)

            {

                if (Bid - OrderOpenPrice() > Point * TrailingStop)

               {

                  if (OrderStopLoss() < Bid - Point * TrailingStop)

                  {

                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0))

                        Print("Error applying trailing stop: ", GetLastError());

                     return(0);

                  }

               }

            } 

         }

         else if (OrderType() == OP_SELL)

         {

            // Should it be closed?

              if((macd2>macd1 && macd0>macd1)||(macd3>macd1 && macd2==macd1 && macd0>macd1)||      //If MACD has bottomed

                 (macd4>macd1 && macd3==macd1 && macd2==macd1 && macd0>macd1)||

                 (macd5>macd1 && macd4==macd1 && macd3==macd1 && macd2==macd1 && macd0>macd1))

               {

               if ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))

               {

               if (!OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrViolet)) Print("Error closing SELL order: ", GetLastError());

               

               //new block added for continuos buying & selling, and never being out of market------------------

               ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, Slippage, order_sl, order_tp, "MACD Sample", Magic, 0, clrGreen);

               if (ticket > 0)Print("BUY order opened: ", OrderOpenPrice());

               else Print("Error opening BUY order: ", GetLastError());

               //end of new block -------------------------------------------------------------------------------

               RefreshRates();

               }

               return(0);

            }

            // Trailing stop.

            if (TrailingStop > 0)  

               {                 

               RefreshRates();

               if (OrderOpenPrice() - Ask > Point * TrailingStop)

               {

                  if ((OrderStopLoss() > Ask + Point * TrailingStop) || (OrderStopLoss() == 0))

                  {

                     if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + Point * TrailingStop, OrderTakeProfit(), 0))

                        Print("Error applying trailing stop: ", GetLastError());

                     return(0);

                  }

               }

            } 

         }

      }

   }

   return(0);

}

//+------------------------------------------------------------------+

double getLots(double risk)

   {

   double acctBal, margin, MaxPermitLotSizePerTrade, lotincrement,lotDigits, numLots;

   acctBal=AccountFreeMargin();  //

   margin=MarketInfo(Symbol(),MODE_MARGINREQUIRED);   //

   MaxPermitLotSizePerTrade=MarketInfo(Symbol(), MODE_MAXLOT); //

   lotincrement=MarketInfo(Symbol(), MODE_LOTSTEP);

   

   if (lotincrement==0.01) lotDigits=2;

   else lotDigits=1;

   numLots=NormalizeDouble((acctBal*risk)/(margin*100),lotDigits);     //

   return(numLots);

   }

//+------------------------------------------------------------------+

I have also attached the chart it creates during the Strategy Test run.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sam

 
sam malone:

Hello Everyone,

I am new to MQL4 and have just started learning how to code in MQ4. After a couple of weeks' try I have tried to modify an existing EA on the web. It works, but it does not follow the logic I have tried to incorporate, which is: if MACD has peaked, place a SELL order; if MACD has bottomed, place a BUY order. Close the SELL order when MACD has bottomed, and then place a BUY order in the opposite direction. Close the BUY order when MACD has peaked, and then place SELL order in the opposite direction. I am using the open of the next bar to place the BUY/SELL order. Unfortunately, the EA does not do this, though it runs OK. Can someone be kind enough to have a look at it and provide some suggestions? The code is given below. Thanks much.

------------------

//+------------------------------------------------------------------+

I have also attached the chart it creates during the Strategy Test run.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sam

Do not double post.

I have deleted your other duplicate post.

Please use the code button ( or Alt + S) when pasting code. I have edited your post this time

 
Keith Watford:

Do not double post.

I have deleted your other duplicate post.

Please use the code button ( or Alt + S) when pasting code. I have edited your post this time

My thanks and apologies, Keith. I appreciate your edit. This was my first time posting to this forum, and did not know which would be the best thread to post. It is good to know that posting in any thread is visible to the members of all other threads.
 
#define m  20050611
//----
extern int tp = 100;
extern int distance = 60;  
//----
datetime lastt; 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int kol_buy()
  {
   int kol_ob = 0;
//----
   for(int i = 0; i < OrdersTotal(); i++)
     {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) 
           break;
       //----
       if(OrderType() == OP_BUY)  
           kol_ob++;
     }
   return(kol_ob);
  }    
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int kol_sell()
  {
   int kol_os = 0;
//----
   for(int i = 0; i < OrdersTotal(); i++)
     {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) 
           break;
       //----
       if(OrderType() == OP_SELL)  
           kol_os++;
     }
   return(kol_os);
  }  
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   int slip, i, ii, tic, total, kk, gle;
   double lotsi = 0.0;
   bool sob = false, sos = false, scb = false, scs = false;
   int kb, kb_max = 0;
   kb = kol_buy() + 1;
   double M_ob[11][8];
   ArrayResize(M_ob,kb);
   int ks = 0, ks_max = 0;
   ks = kol_sell() + 1;
   double M_os[11][8];
   ArrayResize(M_os,ks);
   ArrayInitialize(M_ob, 0.0);
   int kbi = 0;
//----
   for(i = 0; i < OrdersTotal(); i++)
     {
       if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) 
           break;
       //----
       if(OrderSymbol() == Symbol() && OrderType() == OP_BUY)
         {
           kbi++;
           M_ob[kbi][0] = OrderTicket();
           M_ob[kbi][1] = OrderOpenPrice();
           M_ob[kbi][2] = OrderLots();
           M_ob[kbi][3] = OrderType();
           M_ob[kbi][4] = OrderMagicNumber();
           M_ob[kbi][5] = OrderStopLoss();
           M_ob[kbi][6] = OrderTakeProfit();
           M_ob[kbi][7] = OrderProfit();
           

         }
     } 
   M_ob[0][0] = kb; 
   double max_lot_b = 0.0;
//----
   for(i = 1; i < kb; i++)
       if(M_ob[i][2] > max_lot_b)
         {
           max_lot_b = M_ob[i][2];
           kb_max = i;
         }
   double buy_lev_min = M_ob[kb_max][1];   
   ArrayInitialize(M_os,0.0);
   int ksi = 0;
//----
   for(i = 0; i < OrdersTotal(); i++)
     {
       if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) 
           break;
       //----
       if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
         {
           ksi++;
           M_os[ksi][0] = OrderTicket();
           M_os[ksi][1] = OrderOpenPrice();
           M_os[ksi][2] = OrderLots();
           M_os[ksi][3] = OrderType();
           M_os[ksi][4] = OrderMagicNumber();
           M_os[ksi][5] = OrderStopLoss();
           M_os[ksi][6] = OrderTakeProfit();
           M_os[ksi][7] = OrderProfit();
  
         }
     } 
   M_os[0][0] = ks; 
   double max_lot_s = 0.0;
//----
   for(i = 1;i < ks; i++)
       if(M_os[i][2] > max_lot_s)
         {
           max_lot_s = M_os[i][2];
           ks_max = i;
         }
   double sell_lev_max = M_os[ks_max][1];    
//----
   if(Bars < 100 || IsTradeAllowed() == false) 
       return(0); 
   sob = (kol_buy() < 1 || buy_lev_min + distance*Point < Ask) && 
          AccountFreeMargin() > AccountBalance()*0.5;
   sos = (kol_sell() < 1 || sell_lev_max - distance*Point > Bid) &&
          AccountFreeMargin() > AccountBalance()*0.5;
//----
   if(M_ob[kb_max][2] > 0.0)
       scb = M_ob[kb_max][7] / (M_ob[kb_max][2]*10) > tp;

       
  //----
   if(M_os[ks_max][2] > 0.0)
       scs = M_os[ks_max][7] / (M_os[ks_max][2]*10) > tp;
   
        
  
   kk = 0;
   ii = 0;
//----
   if(scb)
     {
       while(kol_buy() > 0 && kk < 3)
         {
           for(i = 1; i <= kb; i++)
             {
               ii = M_ob[i][0];
               //----
               if(!OrderClose(ii,M_ob[i][2],Bid,slip,White)) 
                 {
                   gle = GetLastError();
                   kk++;
                   Print("Îøèáêà ¹", gle, " ïðè close buy ", kk);
                   Sleep(6000);
                   RefreshRates();  
                 }
             }
           kk++;
         }
     }
   kk = 0;  
   ii = 0; 
//----
   if(scs)
     {
       while(kol_sell() > 0 && kk < 3)
         {
           for(i = 1; i <= ks; i++)
             {
               ii = M_os[i][0];
               //----
               if(!OrderClose(ii,M_os[i][2], Ask, slip, White))
                 {
                   gle = GetLastError();
                   kk++;
                   Print("Îøèáêà ¹", gle, " ïðè close sell ", kk);
                   Sleep(6000);
                   RefreshRates();  
                 }
             }
           kk++;
         }
     }
   kk = 0; 
   tic = -1;  
//----
   if(sob) 
     {
       if(max_lot_b == 0.0)
           lotsi = 0.01;
       else 
           lotsi = 2.0*max_lot_b;
       //----
       while(tic == -1 && kk < 3)
         {
           tic = OrderSend(Symbol(), OP_BUY, lotsi, Ask, slip, 0, Ask + (tp + 25)*Point,  
                           " ", m, 0);
           Print("tic_buy=", tic);
           //----
           if(tic==-1)
             {
               gle = GetLastError();
               kk++;               
               Print("Îøèáêà ¹", gle, " ïðè buy ", kk);
               Sleep(6000);
               RefreshRates();   
             }
         }   
       lastt = CurTime();
       return;
     }
   tic = -1;
   kk = 0;  
//----
   if(sos) 
     {
       if(max_lot_s == 0.0)
           lotsi = 0.01;
       else 
           lotsi = 2.0*max_lot_s;
       //----
       while(tic == -1 && kk < 3)
         {
           tic = OrderSend(Symbol(), OP_SELL, lotsi, Bid, slip, 0, Bid - (tp + 25)*Point,
                           " ", m, 0);
           Print("tic_sell=", tic);
           //----
           if(tic == -1)
             {
               gle = GetLastError();
               kk++;               
               Print("Îøèáêà ¹", gle, " ïðè sell ", kk);
               Sleep(6000);
               RefreshRates();   
             }
          }
       lastt = CurTime();
       return;
     }        
  }
//+------------------------------------------------------------------+   

any body add in sl and 

max buy order and max sell order code

thanks

 
paulinayat:

Do not double post.

I have deleted your other duplicate post.