Solid opening/closing functions

 

Hello,

   I am trying to come-up with solid functions for opening and closing orders.

   Here is the routine for closing I am currently using:


   The main issue is I often get error 129, and the routine exits leaving my position open. I won't post the opening function, but it is very similar and suffers from the same type of problem.


take care,

lee


   

while(1==2)                                  // Order closing cycle
                  {
                      //Print("Attempt to open current open price:",  + price + " sl:" + sl + " tp:" + tp);
                       ticket=OrderSend(Symbol(), orderType, LOTS, price, SLIPPAGE, stop_loss, take_profit, notes, 0, 0, arrow_color);
                           //-------------------------------------------------------------------------- 8 --
                           if (ticket >= 0)                            // Got it! :)
                             {
                              //Print ("Opene: ", ticket);
                              break;                                 // Exit closing cycle
                             }
                           //-------------------------------------------------------------------------- 9 --
                           int Error=GetLastError();                 // Failed :(
                           //Print ("Error: ", Error);
                           switch(Error)                             // Overcomable errors
                             {
                              case 129:Print("Invalid Price");
                                 break;
                              case 135:Print("The price has changed. Retrying..");
                                 RefreshRates();                     // Update data
                                 continue;                           // At the next iteration
                              case 136:Print("No prices. Waiting for a new tick..");
                                 while(RefreshRates()==false)        // To the new tick
                                    Sleep(1);                        // Cycle sleep
                                 continue;                           // At the next iteration
                              case 146:Print("Trading subsystem is busy. Retrying..");
                                 Sleep(500);                         // Simple solution
                                 RefreshRates();                     // Update data
                                 continue;                           // At the next iteration
                             }
                           switch(Error)                             // Critical errors
                           {
                              case 2 : Print("Common error.");
                                 break;                              // Exit 'switch'
                              case 5 : Print("Old version of the client terminal.");
                                 break;                              // Exit 'switch'
                              case 64: Print("Account is blocked.");
                                 break;                              // Exit 'switch'
                              case 133:Print("Trading is prohibited");
                                 break;                              // Exit 'switch'
                              default: Print("Occurred error ",Error);//Other alternatives   
                           }
                           break;                                    // Exit closing cycle
                  }
 
Read yourself your code and then tell us where in the code trades get closed...
 
deVries:
Read yourself your code and then tell us where in the code trades get closed...

Hello,


 It is attempting to close with this line:

 

ticket=OrderSend(Symbol(), orderType, LOTS, price, SLIPPAGE, stop_loss, take_profit, notes, 0, 0, arrow_color);

 

 Then, as you can see, it loops while it figures out what to do with the response.


The issue is that this line:


case 129:Print("Invalid Price");
                                 break;


 Breaks out of the loop and the order is never closed.

 So, my question is 'Is there a better way to be closing orders so that this particular error can be overcome?'.


  I'm not sure if trying to close again immediately is a good idea as it could result in a bunch of error code's 146.


take care,

lee

 

It might be the language is hard to understand but the command you think is for closing the trade is doing opposite

OrderSend is a command for trying to open a new trade. Closing trades you do with OrderClose(........);


OrderClose


OrderDelete

 

Click the links for more info 


 
deVries:

It might be the language is hard to understand but the command you think is for closing the trade is doing opposite

OrderSend is a command for trying to open a new trade. Closing trades you do with OrderClose(........);

 


YOu know, you are right. Sorry, I copy and pasted the wrong code. Here is correct code. As you can see, it is basically the same, and the issue is the same.



while(true)                                  // Order closing cycle
                                      {
                                         //Print("Attempt to close order: ");
                                                   //bool omAns=;
                                                   //-------------------------------------------------------------------------- 8 --
                                                   //OrderClose(        int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
                                                   if (OrderClose(OrderTicket(), OrderLots(), price, SLIPPAGE, Blue)==true)                            // Got it! :)
                                                     {
                                                      //Print ("Oreder Closed ");
                                                      break;                                 // Exit closing cycle
                                                     }
                                                   //-------------------------------------------------------------------------- 9 --
                                                   int ocError=GetLastError();                 // Failed :(
                                                   switch(ocError)                             // Overcomable errors
                                                     {
                                                      case 129:Print("!!!!!!!!!!!!!!!  Invalid price !!!!!!!!!!!!!!!!!");
                                                             break;
                                                      case 135:Print("The price has changed. Retrying..");
                                                             RefreshRates();                     // Update data
                                                             continue;                           // At the next iteration
                                                      case 136:Print("No prices. Waiting for a new tick..");
                                                             while(RefreshRates()==false)        // To the new tick
                                                                    Sleep(1);                        // Cycle sleep
                                                             continue;  
                                                             case 138: Print("Requote error:");
                                                                 RefreshRates();        // To the new tick
                                                                    Sleep(1);
                                                                    continue;                   // At the next iteration
                                                      case 146:Print("Trading subsystem is busy. Retrying..");
                                                             Sleep(500);                         // Simple solution
                                                             RefreshRates();                     // Update data
                                                             continue;                           // At the next iteration
                                                     }
                                                   switch(ocError)                             // Critical errors
                                                   {
                                                      case 2 : Print("Common error.");
                                                             break;                              // Exit 'switch'
                                                      case 5 : Print("Old version of the client terminal.");
                                                             break;                              // Exit 'switch'
                                                      case 64: Print("Account is blocked.");
                                                             break;                              // Exit 'switch'
                                                      case 133:Print("Trading is prohibited");
                                                             break;                              // Exit 'switch'
                                                      default: Print("Occurred error ",ocError);//Other alternatives   
                                                   }
                                                   break;                                    // Exit closing cycle
                                
                         
                                      }
 
kleelof:

YOu know, you are right. Sorry, I copy and pasted the wrong code. Here is correct code. As you can see, it is basically the same, and the issue is the same.


What is the value of   price   ?  where does it's value come from ?  how do you determine if you are closing a Buy or a Sell and adjust  price  accordingly ?  Please show your code for this.

Also,  retrying is not always the correct course of action,  for example:

 

ERR_TRADE_DISABLED133Trade is disabled. All attempts to trade must be stopped.

 

You must not retry,  you must stop. 

And . . .

ERR_NO_CONNECTION6No connection to the trade server. It is necessary to make sure that connection has not been broken (for example, using the IsConnected function) and repeat the attempt after a certain period of time (over 5 seconds).

 

. . .  you must wait before retrying.

 
RaptorUK:


What is the value of   price   ?  where does it's value come from ?  how do you determine if you are closing a Buy or a Sell and adjust  price  accordingly ?  Please show your code for this.

Also,  retrying is not always the correct course of action,  for example:

 

ERR_TRADE_DISABLED133Trade is disabled. All attempts to trade must be stopped.

 

You must not retry,  you must stop. 

And . . .

ERR_NO_CONNECTION6No connection to the trade server. It is necessary to make sure that connection has not been broken (for example, using the IsConnected function) and repeat the attempt after a certain period of time (over 5 seconds).

 

. . .  you must wait before retrying.

 


 Hello,


   The values are being calculated before this part of the function.


   95% Of the time the order closes with no problem, so I believe the values are fine. But the other 5% or so of the time I get this error 129. This is the main error I want to deal with.


   I understand that sometimes the prices may move too quickly, and that is fine. However, I would like to figure out when I do get this error 129, the best way to go about attempting to close again.

  One thing; for slippage I use the value of 2. I think changing it to a higher value could help cut down on the number of error 129's, but still, there will always be the chance the value is not high enough and I will be in the same situation.

take care,

lee

 

Hello,


   I just had an idea;


   What if I do a 1-3 second pause, recalculate price and let it try to close again. Do you think something like this might work?


lee

 
kleelof:


  One thing; for slippage I use the value of 2. I think changing it to a higher value could help cut down on the number of error 129's, but still, there will always be the chance the value is not high enough and I will be in the same situation.

Why not just use OrderClosePrice() instead of  price  ?

Read all of this thread for more info:  https://www.mql5.com/en/forum/143495 

 
kleelof:  One thing; for slippage I use the value of 2.
That's only 2/10 a pip on a 5 digit broker. EA's must adjust TP, SL, AND slippage
//++++ These are adjusted for 5 digit brokers.
int      pips2points;                  // slippage  3 pips  3=points 30=points
double   pips2dbl;                     // Stoploss 15 pips  0.0015   0.00150
int      Digits.pips;                  // DoubleToStr(dbl/pips2dbl, Digits.pips)
int      init(){                                            OptInitialization();
    if(Digits % 2 == 1){   // DE30=1/JPY=3/EURUSD=5 forum.mql4.com/43064#515262
            pips2dbl = Point*10;    pips2points = 10;    Digits.pips = 1;
   } else { pips2dbl = Point;       pips2points =  1;    Digits.pips = 0;     }
   // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
//---- These are adjusted for 5 digit brokers.
   //{On ECN brokers you must open first and THEN set stops
   // int      ticket = OrderSend(..., 0,0,...)
   // if(ticket < 0)
   //    Alert("OrderSend failed: ", GetLastError());
   // else  if(!OrderSelect(ticket, SELECT_BY_TICKET))
   //    Alert("OrderSelect failed: ", GetLastError());
   // else  if(!OrderModify(OrderTicket(), OrderOpenPrice(), SL, TP, 0))
   //    Alert("OrderModify failed: ", GetLastError());
   //}
But your problem is most likely not using OrderClosePrice() or not checking OrderSelect() return value
 
WHRoeder:
That's only 2/10 a pip on a 5 digit broker. EA's must adjust TP, SL, AND slippageBut your problem is most likely not using OrderClosePrice() or not checking OrderSelect() return value

Hello,



    Thanks guys. I will replace my current values with OrderClosePrice() and see what happens.


    Just out of curiosity, when you manually place or close an order, and it comes back with a requotes, what is the actual error value that was returned by the server?


take care,

lee