Moving Average EA Help

 

Hello,

I have only been learning to code with MQL4 for a couple of months and I am looking to write an EA which opens a trade when MA cross and closes the trade when they cross again. I need a helping hand as the EA won't seem to close the trade. Thank you.

 Here is my code: 

extern double    Lots=0.2;

extern int       StopLoss=20;

extern string    Ma1;

extern int       Ma1Period=6;

extern int       Ma1Shift=0;

extern int       Ma1Method=0;

extern string    Ma2;

extern int       Ma2Period=3;

extern int       Ma2Shift=0;

extern int       Ma2Method=0;

#define MAX_ORDERS 4 //This controls the total number of that can be placed at any one time.

void start() //This process repeats itself after every tick (change in price).

{

Ma1=iMA(Symbol(),PERIOD_M1,6,0,MODE_SMA,PRICE_TYPICAL,0); //Defining the moving average

Ma2=iMA(Symbol(),PERIOD_M1,3,0,MODE_SMA,PRICE_TYPICAL,0); //Defining the moving average

int ticketbuy, ticketsell;  

   {if(OrdersTotal()<MAX_ORDERS) //Total number of orders

      //Buy Criteria

      {

      if(Ma1<Ma2)

      {

      ticketbuy = OrderSend(Symbol(),OP_BUY,Lots,Ask,10,StopLoss,0,"test_1",0,0,Green);

      

      }

      // Sell Criteria

      else

      {

      ticketsell = OrderSend(Symbol(),OP_SELL,Lots,Bid,10,StopLoss,0,"test_1",0,0,Red);

      }

      

//The section below is with regards to closing a live trade

if(Ma1>Ma2)// Condition to close the trade

  {

  bool buyingresult;

  buyingresult = OrderClose(ticketbuy,Lots,Bid,10,Blue);

  }

if(Ma1<Ma2)// Condition to close the trade

  {

  bool buyingresult;

  buyingresult = OrderClose(ticketsell,Lots,Bid,10,Blue);

  }

}

}

}
 

Forum on trading, automated trading systems and testing trading strategies


Hello,

Please use the SRC button when you post code. Thank you.


This time, I edited it for you.


 

Just by looking at your code:

you can open several orders, so you could store their individual ticket numbers in an array in a global variable.

As you defined them local they get lost after  the next ea call (so the next tick)

Regards

Uwe

 

Sorry, I can understand condition if see cross, vs. condition for Buy above - simple M1 is over M2 ?! Where is condition for Sell??

You must be brave