Crossing MAs

 

Hello,

I am trying to achieve my first EA. The strategy is this: buy when the Moving Average 18 is under the MA9 and close when it is the contrary.

I can't find why the closing orders don't work...

I need your help! Thanks!

//+------------------------------------------------------------------+
//|                                                      MM9et18.mq4 |
//|                                                            Brice |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Brice"
#property link      ""

int ticket;
int achat = 0;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
   double MM9;
   double MM18;
   MM9=iMA(Symbol(),30,9,0,MODE_SMA,PRICE_CLOSE,0);
   MM18=iMA(Symbol(),30,18,0,MODE_SMA,PRICE_CLOSE,0);
   if(MM9>MM18 && achat==0)
   {
      ticket=OrderSend(Symbol(),OP_BUY,0.1,Ask,3,1,200,"My order #1",16384,0,Green);
      achat=1;  
      if(ticket<0)
      {
        Print("OrderSend failed with error #",GetLastError());
        return(0);
      }
      return(0);
   }
   if(MM18>MM9 && achat==1)
   {
      OrderClose(ticket,0.1,Bid,3,Red); 
      Alert(GetLastError());
      achat=0;
      return(0);
   }
   //----
   return(0);
  }
//+------------------------------------------------------------------+
Files:
mm9et18.mq4  2 kb
 

You need to loop through the order pool and select the order first...

https://book.mql4.com/trading/orderclose

https://docs.mql4.com/trading/OrderSelect


Also not, that in the book the for loop increments i looping through the orders. If you are closing, you need to count backwards...there are explanations on the site... I don't have a link handy...

V

Reason: