OrderClose error on three EMA crosses EA

 

Dear Forum,


I'm trying to program and test a simple base EMA program that buy and sell on the EMA crosses.

There is the problema that the program is not opening orders, is only trying to close orders,

I've reade the MQL4 references and tutorial for EA creation but till now I've not a clear idea of how to tell to close the first order or to close another order,

somebody can check which parts are not good into this program?

I want to open and close 1 position at time, not more, I see an error with orderclose.

Regards,

G.L.

This is the code:

//+------------------------------------------------------------------+
//|                                                          EMA.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

extern double Lots = 0.1;
  double EMA1;
  double EMA2;
  double EMA3;
  int ordiniaperti;
  int i;
  int total=0;
  int posizione=0;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
       EMA1 = iMA(NULL, 0, 9, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA2 = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA3 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i);     

      
       Print("Totale ordini aperti in questo momento "+total);
       Print("Prima del blocco degli orderclose if==1 or if>1"+total);
   //-----chiusura ordini -----------------------
      if((total==1) || (total>1)){
      Print("Dentro il blocco degli orderclose che controllano total" + total);
      if((EMA1<EMA2) && (EMA2>EMA3)){
      Print("EMA1 minore di EMA2 "+posizione);
      OrderClose(posizione,OrderLots(),Bid,3,Violet); // close position
      total=0;
      }
      if((EMA1>EMA2) && (EMA2<EMA3)){
      Print("EMA1 maggiore di EMA2 "+posizione);
      OrderClose(posizione,OrderLots(),Ask,3,Violet); // close position
      total=0;
      }
   }    
   //--------------------------------------------------
   
   //apertura ordini------------------------------------
 
      // no opened orders identified
      if(total==0){
      Print("total uguale a 0");
      if((EMA1>EMA2) && (EMA2>EMA3)){
      OrderSend(Symbol(), OP_BUY, Lots, Ask, 3,0,0, "EMA_CROSS", 12345, 0, Green);
      total=1;
      posizione=posizione+1;
      Print("Bought");
      }
      
      if((EMA1<EMA2) && (EMA1<EMA3)){
      OrderSend(Symbol(), OP_SELL, Lots, Bid, 3,0,0, "EMA_CROSS", 12345, 0, Red);
      total=1;
      posizione=posizione+1;
      Print("Sold");
      }
     }
//---- 
   return(0);
  }
// the end.
 
You can look for TWO MAs crossing. The problem is three or more may not cross on the same bar. So forget crosses, look for alignments.
double fastCurr = iMA(NULL, 0,  9, 0, MODE_EMA, PRICE_MEDIAN, i),
       medCurr  = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i),
       slowCurr = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i),
     
       fastPrev = iMA(NULL, 0,  9, 0, MODE_EMA, PRICE_MEDIAN, i+1),
       medPrev  = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i+1),
       slowPrev = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i+1);     

bool   isBuy  = fastCurr > medCurr && medCurr > slowCurr,
      wasBuy  = fastPrev > medPrev && medPrev > slowPrev;
if(isBuy){
   CloseAllOrders(OP_SELL);
   if(!wasBuy && MyOrdersTotal(OP_BUY) == 0) OpenOrder(OP_BUY);
}
 
   if((total==1) || (total>1)){
      Print("Dentro il blocco degli orderclose che controllano total" + total);
      if((EMA1<EMA2) && (EMA2>EMA3)){
      Print("EMA1 minore di EMA2 "+posizione);
      OrderClose(posizione,OrderLots(),Bid,3,Violet); // close position
      total=0;

if you wanna close a trade you have to select the right OrderTicket()

before you do the close you're not selecting the trade you wanna close...

posizione is not same as OrderTicket()....

make a loop checking trades of your account

find the trades with the right symbol and magicnumber and right ordertype

if the trade is the one to close then close and check if it succeed

 
giuseppeloddo:

Dear Forum,


I'm trying to program and test a simple base EMA program that buy and sell on the EMA crosses.

There is the problema that the program is not opening orders, is only trying to close orders,

I've reade the MQL4 references and tutorial for EA creation but till now I've not a clear idea of how to tell to close the first order or to close another order,

somebody can check which parts are not good into this program?

I want to open and close 1 position at time, not more, I see an error with orderclose.

You need to check your trading function return values, report errors and any relevant variables . . . What are Function return values ? How do I use them ?

As deVries said, where is your OrderSelect() ? read the documentation for OrderLots() <----- click this
 

Thank you for the link,

now with OrderLots and OrderSelect I start to understand why was opened only the first order and stop without any closing.

I'm modifying the EA


G.L.

 

Something into the ordersend is not working,

the backtesting is returning to me "ordersend error number 148"


this is the code:

//+------------------------------------------------------------------+
//|                                                          EMA.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

extern double Lots = 0.1;
  double EMA1;
  double EMA2;
  double EMA3;
  int i;
  int Ticket;
  int TicketNumber;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
       EMA1 = iMA(NULL, 0, 9, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA2 = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA3 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i);     

   //-----section for close the orders -----------------------
      

      if((EMA1<EMA2) && (EMA2>EMA3)){
      if(OrderSelect(TicketNumber,SELECT_BY_TICKET)){
      Ticket=OrderTicket(); 
      OrderClose(Ticket,OrderLots(),Bid,3,Violet); // close position
      TicketNumber=0;
      }
     
      Print("Bought closed");
      }
      if((EMA1>EMA2) && (EMA2<EMA3)){
      if(OrderSelect(TicketNumber,SELECT_BY_TICKET)){
      Ticket=OrderTicket();
      OrderClose(Ticket,OrderLots(),Ask,3,Violet); // close position
      Print("Sold closed");
      TicketNumber=0;
      }
      }
    
   //--------------------------------------------------
   
   //-----section for open the orders------------------------------------
      if(TicketNumber<1){
      
      if((EMA1>EMA2) && (EMA2>EMA3)){
      TicketNumber=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3,0,0, "EMA_CROSS", 12345, 0, Green);
      if( TicketNumber > 0 )
      {
      Print("Order placed # ", TicketNumber + " Bought");
      }
      else
      {
      Print("Order Send failed, error # ", GetLastError() );
      }
      }
      
      
      if((EMA1<EMA2) && (EMA1<EMA3)){
      TicketNumber=OrderSend(Symbol(), OP_SELL, Lots, Bid, 3,0,0, "EMA_CROSS", 12345, 0, Red);
      if( TicketNumber > 0 )
      {
      Print("Order placed # ", TicketNumber + " Sold");
      }
      else
      {
      Print("Order Send failed, error # ", GetLastError() );
      }
      }
      
      }
   return(0);
  }
// the end.

G.L.
 
giuseppeloddo:

Something into the ordersend is not working,

the backtesting is returning to me "ordersend error number 148"

  1. False
  2. Did you bother to look up the code?
 

See also https://www.mql5.com/en/forum/139654

take your time reading it and you will see how to use a loop

and select the right trade to handle

 

I've used the loop, infact now all the orders are closed correctly! Thank you for the helpfull tutorial.

Now I see that EA that is going only in one direction, it's only opening SELL orders till all the money ends,

I think that it's a problem about the EMA cross signal, the same EMA it's working for the indicator, but not for the trading system


//+------------------------------------------------------------------+
//|                                                          EMA.mq4 |
//|                        Copyright 2013, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

extern double Lots = 0.1;
  double EMA1;
  double EMA2;
  double EMA3;
  int i;
  int Ticket;
  int TicketNumber;
  int MagicNo = 12345;
  int PositionIndex;    //  <-- this variable is the index used for the loop
  int TotalNumberOfOrders;   //  <-- this variable will hold the number of orders currently in the Trade pool
  int Slippage= 3;
  int Counted_bars;                // Êîëè÷åñòâî ïðîñ÷èòàííûõ áàðîâ 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
 

//--------------------------------------------------------------------
   Counted_bars=IndicatorCounted(); // Êîëè÷åñòâî ïðîñ÷èòàííûõ áàðîâ 
   i=Bars-Counted_bars-1;           // Èíäåêñ ïåðâîãî íåïîñ÷èòàííîã
   while(i>=0)                      // Öèêë ïî íåïîñ÷èòàííûì áàðà
     {
       EMA1 = iMA(NULL, 0, 9, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA2 = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA3 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i);     
      i--;                          // Ðàñ÷¸ò èíäåêñà ñëåäóþùåãî áàðà
     }
   //-----section for close the orders -----------------------
      
      TotalNumberOfOrders = OrdersTotal();
      if((EMA1<EMA2) && (EMA2>EMA3)){
      TotalNumberOfOrders = OrdersTotal();    // <-- we store the number of Orders in the variable

      for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)  //  <-- for loop to loop through all Orders . .   COUNT DOWN TO ZERO !
      {
      if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) ) continue;   // <-- if the OrderSelect fails advance the loop to the next PositionIndex
   
      if( OrderMagicNumber() == MagicNo       // <-- does the Order's Magic Number match our EA's magic number ? 
      && OrderSymbol() == Symbol()         // <-- does the Order's Symbol match the Symbol our EA is working on ? 
      && ( OrderType() == OP_BUY           // <-- is the Order a Buy Order ? 
      ||   OrderType() == OP_SELL ) )      // <-- or is it a Sell Order ?
   
      if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) )               // <-- try to close the order
         Print("Order Close failed, order number: ", OrderTicket(), " Error: ", GetLastError() );  // <-- if the Order Close failed print some helpful information 
      
      } //  end of For loop
      }
      
      
      if((EMA1>EMA2) && (EMA2<EMA3)){
      TotalNumberOfOrders = OrdersTotal();    // <-- we store the number of Orders in the variable

      for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)  //  <-- for loop to loop through all Orders . .   COUNT DOWN TO ZERO !
      {
      if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) ) continue;   // <-- if the OrderSelect fails advance the loop to the next PositionIndex
   
      if( OrderMagicNumber() == MagicNo       // <-- does the Order's Magic Number match our EA's magic number ? 
        && OrderSymbol() == Symbol()         // <-- does the Order's Symbol match the Symbol our EA is working on ? 
        && ( OrderType() == OP_BUY           // <-- is the Order a Buy Order ? 
        ||   OrderType() == OP_SELL ) )      // <-- or is it a Sell Order ?
   
        if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) )               // <-- try to close the order
           Print("Order Close failed, order number: ", OrderTicket(), " Error: ", GetLastError() );  // <-- if the Order Close failed print some helpful information 
      
       } //  end of For loop
      }
    
   //--------------------------------------------------
      Print("Numero di ordini totali: "+TotalNumberOfOrders);
   //-----section for open the orders------------------------------------
   
      TotalNumberOfOrders = OrdersTotal();
      if(TotalNumberOfOrders==0){
      if((EMA1>EMA2) && (EMA2>EMA3))
         {
         TicketNumber=OrderSend(Symbol(), OP_BUY, Lots, Ask, 3,0,0, "EMA_CROSS", MagicNo, 0, Green);
         if( TicketNumber > 0 )
            {
            Print("Order placed # ", TicketNumber + " Bought");
            }
            else
            {
            Print("Order Send failed, error # ", GetLastError() );
            }
         }
      }
      
      TotalNumberOfOrders = OrdersTotal();
      if(TotalNumberOfOrders==0){
      if((EMA1<EMA2) && (EMA1<EMA3))
         {
         TicketNumber=OrderSend(Symbol(), OP_SELL, Lots, Bid, 3,0,0, "EMA_CROSS", MagicNo, 0, Red);
         if( TicketNumber > 0 )
            {
            Print("Order placed # ", TicketNumber + " Sold");
            }
            else
            {
            Print("Order Send failed, error # ", GetLastError() );
            }
         }
      }
      
   return(0);
  }
// the end.
 

You are opening a sell order with

if((EMA1<EMA2) && (EMA1<EMA3))

and it is possible that next tick, you will be closing it with

if((EMA1<EMA2) && (EMA2>EMA3))

as both these conditions can be true at the same time.

Also, it is normally best to check for MA crosses only when a new bar opens. This is because crosses up and down can happen many times during a single bar

 
   Counted_bars=IndicatorCounted(); // Êîëè÷åñòâî ïðîñ÷èòàííûõ áàðîâ 
   i=Bars-Counted_bars-1;           // Èíäåêñ ïåðâîãî íåïîñ÷èòàííîã
   while(i>=0)                      // Öèêë ïî íåïîñ÷èòàííûì áàðà
     {
       EMA1 = iMA(NULL, 0, 9, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA2 = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, i);
       EMA3 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, i);     
      i--;                          // Ðàñ÷¸ò èíäåêñà ñëåäóþùåãî áàðà
     }

every tick this is resulting in just one value for

       EMA1 = iMA(NULL, 0, 9, 0, MODE_EMA, PRICE_MEDIAN, 0);
       EMA2 = iMA(NULL, 0, 27, 0, MODE_EMA, PRICE_MEDIAN, 0);
       EMA3 = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_MEDIAN, 0);

don't use specific indicatorfunctions in your EA

so this while function is senseless i =0, or i =1, or i = 2, but it is not at same moment 0 1 2 ......whatever

TotalNumberOfOrders = OrdersTotal();   
      if((EMA1<EMA2) && (EMA2>EMA3))
          {
          TotalNumberOfOrders = OrdersTotal();    // <-- we store the number of Orders in the variable

why do you repeat TotalNumberOfOrders = OrdersTotal();

where can it become different if you think it can be there is just one trade closed by stoploss or takeprofit

then in that case wouldn't it be better to repeat it every line ... but we don't see that possibillity happens often it 's more unlikely

if the value can't have been changed normally then there is no sense for repeating

//

if you have condition

 if((EMA1<EMA2) && (EMA2>EMA3))

then what kind of trades do you wanna close ?? ........

then you do this ok

 for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)  //  <-- for loop to loop through all Orders . .   COUNT DOWN TO ZERO !
      {
      if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) ) continue;   // <-- if the OrderSelect fails advance the loop to the next PositionIndex

but what kind of orders have you select you gonna close .....

  if( OrderMagicNumber() == MagicNo       // <-- does the Order's Magic Number match our EA's magic number ? 
        && OrderSymbol() == Symbol()         // <-- does the Order's Symbol match the Symbol our EA is working on ? 
        && ( OrderType() == OP_BUY           // <-- is the Order a Buy Order ? 
        ||   OrderType() == OP_SELL ) )      // <-- or is it a Sell Order ?

if you wanna close buy trades then don't take buy or sell trades but take only the ordertype () needed to close

now it can be you close wrong trade and there is no message what kind of trade succeed in closing

the error handling for closetrade is correctly

then you repeat it all again... now for closing the other ordertype if it is still there...

//

orderopening before opening a trade make TicketNumber = 0; otherwise your checking if a new trade opend is senseless

and some other things i can suggest

Reason: