OrderModify Error 130 on pending orders

 

Hi all,

I got the error "OrderModify error 130" but I do not why I got this error since I have all required check on take profit and stop loss before to call the function orderModify.

Below is my code:

int openPosition(int cmd, double volume,double priceDistance=0, double sl=0,double tp=0)
{
     double marginFree      = AccountFreeMargin(); // Allow some slack
     double marginPerLot    = MarketInfo( Symbol(), MODE_MARGINREQUIRED );
     double stoplevel       = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;  //minimum stop loss/ take profit level, in points or pending order
     double freezelevel     = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point;
     
     //number of digit for min lot
     double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
     double minLot=MarketInfo(Symbol(),MODE_MINLOT);
     int lotDigit=2;
     
     if(minLot==0.1)
      lotDigit=1;
     else if(minLot==1)
      lotDigit=0;
      
     double size =volume;
      

      size=NormalizeDouble(size,lotDigit);
      string description; 
      size=MathMax(minLot,size);
      size=MathMin(maxLot,size);
      if(!CheckVolumeValue(size,description))
      {
           lastErrorMessage="Volume is not correct";
           lastDateErrorMessage=TimeCurrent();
           Print("Error opening order for size ",size," : ",description);
           return -1;
      }
      
      //Pending order needs to be translated for checks
      int cmd_bis=(cmd<2)?cmd:cmd-4;

      //-- if there is not enough money 
      if(AccountFreeMarginCheck(Symbol(),cmd_bis,size)<0)
        {
         string oper=(cmd==OP_BUY)? "Buy":"Sell";
         lastErrorMessage="#"+IntegerToString(GetLastError())+" not enough money";
         lastDateErrorMessage=TimeCurrent();
         return(-1);
        }

      
   RefreshRates();
   //format price
   double openPrice=0;
   double closePrice=0; //it is only used to calculate the stop limits (tp and sl)
   
   if(cmd==OP_BUYSTOP)
   {  
      openPrice=Ask+MathMax(MathMax(priceDistance,stoplevel),freezelevel);
      closePrice=openPrice;
   }
   else if(cmd==OP_SELLSTOP) 
   {  
      openPrice=Bid-MathMax(MathMax(priceDistance,stoplevel),freezelevel);
      closePrice=openPrice;
   }

   //format stop loss and take profit
   //--- check stop orders for buying
   if(cmd==OP_BUYSTOP)
     {
      tp_distance = (tp - closePrice)/Point;
      sl_distance = (closePrice - sl)/Point;
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=closePrice+(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=closePrice-(stoplevel+1*Point);
     }
   //--- check stop orders for selling
   else if(cmd==OP_SELLSTOP)
     {
      tp_distance = (closePrice - tp)/Point;
      sl_distance = (sl - closePrice)/Point;
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=closePrice-(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=closePrice+(stoplevel+1*Point);
     }

     int lastTicketNumber=OrderSend(Symbol(),cmd, size,NormalizeDouble(openPrice,Digits),3,0,0,"Test",12345,0,White);
 
     if(lastTicketNumber>0)
     {
         if(!OrderSelect(lastTicketNumber,SELECT_BY_TICKET,MODE_TRADES))
         {
            lastErrorMessage="#"+IntegerToString(GetLastError())+" position not found";
            lastDateErrorMessage=TimeCurrent();
            return lastTicketNumber;
         }
         
         if(sl>0 || tp>0)
         {
            //bool res=OrderModify(lastTicketNumber,OrderOpenPrice(),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
            bool res=OrderModify(lastTicketNumber,NormalizeDouble(openPrice,Digits),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);

            if(!res)
            {
               lastErrorMessage="#"+IntegerToString(GetLastError())+" can not modify order";
               lastDateErrorMessage=TimeCurrent();
               Print("Error #",GetLastError()," Cmd:",cmd," Order :",OrderType()," Price:",OrderOpenPrice()," SL:",NormalizeDouble(sl,Digits)," TP:",NormalizeDouble(tp,Digits));
               Print("Error initial price: ",NormalizeDouble(openPrice,Digits));
            }
         }
         
         
         return lastTicketNumber;
     }
     else
     {
        error_code=GetLastError();
        switch(error_code)                                  
        {                                            
         case ERR_TRADE_NOT_ALLOWED : 
            lastErrorMessage="#"+IntegerToString(error_code)+" Trade is not allowed";
            break; //4109 Trade is not allowed.
         case ERR_INVALID_STOPS: 
            lastErrorMessage="#"+IntegerToString(error_code)+" Invalid stop";
            break; //130 invalid stop
         default: 
            lastErrorMessage="#"+IntegerToString(error_code)+" Error opening order";
        }
        lastDateErrorMessage=TimeCurrent();
     }
    return 0;
}
Basic Principles - Trading Operations - MetaTrader 5 Help
Basic Principles - Trading Operations - MetaTrader 5 Help
  • www.metatrader5.com
is an instruction given to a broker to buy or sell a financial instrument. There are two main types of orders: Market and Pending. In addition, there are special Take Profit and Stop Loss levels. is the commercial exchange (buying or selling) of a financial security. Buying is executed at the demand price (Ask), and Sell is performed at the...
 
Dorian Baranes:

Hi all,

I got the error "OrderModify error 130" but I do not why I got this error since I have all required check on take profit and stop loss before to call the function orderModify.

Below is my code:


int openOrder(int cmd, double volume,double priceDistance=0, double sl=0,double tp=0)
{
     double marginFree      = AccountFreeMargin(); // Allow some slack
     double marginPerLot    = MarketInfo( Symbol(), MODE_MARGINREQUIRED );
     double stoplevel       = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;  //minimum stop loss/ take profit level, in points or pending order
     double freezelevel     = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point;
    
     //number of digit for min lot
     double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
     double minLot=MarketInfo(Symbol(),MODE_MINLOT);
     int lotDigit=2;
    
     if(minLot==0.1)
      lotDigit=1;
     else if(minLot==1)
      lotDigit=0;
     
     double size =volume;
     

      size=NormalizeDouble(size,lotDigit);
      string description;
      size=MathMax(minLot,size);
      size=MathMin(maxLot,size);
      if(!CheckVolumeValue(size,description))
      {
           lastErrorMessage="Volume is not correct";
           lastDateErrorMessage=TimeCurrent();
           Print("Error opening order for size ",size," : ",description);
           return -1;
      }
     
      //Pending order needs to be translated for checks
      int cmd_bis=(cmd<2)?cmd:cmd-4;

      //-- if there is not enough money
      if(AccountFreeMarginCheck(Symbol(),cmd_bis,size)<0)
        {
         string oper=(cmd==OP_BUY)? "Buy":"Sell";
         lastErrorMessage="#"+IntegerToString(GetLastError())+" not enough money";
         lastDateErrorMessage=TimeCurrent();
         return(-1);
        }

     
   RefreshRates();
   //format price
   double openPrice=0;
   double closePrice=0; //it is only used to calculate the stop limits (tp and sl)
  
   if(cmd==OP_BUYSTOP)
   { 
      openPrice=Ask+MathMax(MathMax(priceDistance,stoplevel),freezelevel);
      closePrice=openPrice;
   }
   else if(cmd==OP_SELLSTOP)
   { 
      openPrice=Bid-MathMax(MathMax(priceDistance,stoplevel),freezelevel);
      closePrice=openPrice;
   }

   //format stop loss and take profit
   //--- check stop orders for buying
   if(cmd==OP_BUYSTOP)
     {
      tp_distance = (tp - closePrice)/Point;
      sl_distance = (closePrice - sl)/Point;
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=closePrice+(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=closePrice-(stoplevel+1*Point);
     }
   //--- check stop orders for selling
   else if(cmd==OP_SELLSTOP)
     {
      tp_distance = (closePrice - tp)/Point;
      sl_distance = (sl - closePrice)/Point;
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=closePrice-(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=closePrice+(stoplevel+1*Point);
     }

     int lastTicketNumber=OrderSend(Symbol(),cmd, size,NormalizeDouble(openPrice,Digits),3,0,0,"Test",12345,0,White);
 
     if(lastTicketNumber>0)
     {
         if(!OrderSelect(lastTicketNumber,SELECT_BY_TICKET,MODE_TRADES))
         {
            lastErrorMessage="#"+IntegerToString(GetLastError())+" position not found";
            lastDateErrorMessage=TimeCurrent();
            return lastTicketNumber;
         }
        
         if(sl>0 || tp>0)
         {
            //bool res=OrderModify(lastTicketNumber,OrderOpenPrice(),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
            bool res=OrderModify(lastTicketNumber,NormalizeDouble(openPrice,Digits),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);

            if(!res)
            {
               lastErrorMessage="#"+IntegerToString(GetLastError())+" can not modify order";
               lastDateErrorMessage=TimeCurrent();
               Print("Error #",GetLastError()," Cmd:",cmd," Order :",OrderType()," Price:",OrderOpenPrice()," SL:",NormalizeDouble(sl,Digits)," TP:",NormalizeDouble(tp,Digits));
               Print("Error initial price: ",NormalizeDouble(openPrice,Digits));
            }
         }
        
        
         return lastTicketNumber;
     }
     else
     {
        error_code=GetLastError();
        switch(error_code)                                 
        {                                           
         case ERR_TRADE_NOT_ALLOWED :
            lastErrorMessage="#"+IntegerToString(error_code)+" Trade is not allowed";
            break; //4109 Trade is not allowed.
         case ERR_INVALID_STOPS:
            lastErrorMessage="#"+IntegerToString(error_code)+" Invalid stop";
            break; //130 invalid stop
         default:
            lastErrorMessage="#"+IntegerToString(error_code)+" Error opening order";
        }
        lastDateErrorMessage=TimeCurrent();
     }
    return 0;
}

FreezeLevel Limitation (Freezing Distance).

Market orders can not be closed if the StopLoss and TakeProfit values violate the FreezLevel parameter requirements.
StopLoss or TakeProfit orders can not be modified if StopLoss or TakeProfit values violate the StopLevel parameter requirements.
Pending orders can not be deleted or modified if the declared open price violates the FreezeLevel parameter requirements.


I think because of that red.

chaiya

 
  1. When you post code please use the SRC button! Please edit your post.
              General rules and best pratices of the Forum. - General - MQL5 programming forum

  2. MathMax(MathMax(priceDistance,stoplevel),freezelevel);
    These can be simplified
    template <typename T>
    T        MathMax(T a, T b, T c){ return MathMax(a, MathMax(b, c) );  }
    :
    MathMax(priceDistance,stoplevel,freezelevel);

  3.      double stoplevel       = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;    // 0.00030
         double freezelevel     = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point;
    
          tp_distance = (tp - closePrice)/Point;                                // 30
          sl_distance = (closePrice - sl)/Point;
          if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=closePrice+(stoplevel+1*Point);
                                         30       <=  0.00030
    Problem with your checking.

  4. Don't think, Use the debugger or print out your variables, including _LastError and find out why.

  5. size=NormalizeDouble(size,lotDigit);
    
    NormalizeDouble(openPrice,Digits),3,0,0,"Test",12345,0,White);
     
    OrderModify(lastTicketNumber,NormalizeDouble(openPrice,Digits),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
    
    Do NOT use NormalizeDouble, EVER. For ANY Reason. It's a kludge, don't use it. It's use is always wrong

 
whroeder1:
  1. When you post code please use the SRC button! Please edit your post.
              General rules and best pratices of the Forum. - General - MQL5 programming forum

  2. These can be simplified

  3. Problem with your checking.

  4. Don't think, Use the debugger or print out your variables, including _LastError and find out why.

  5. Do NOT use NormalizeDouble, EVER. For ANY Reason. It's a kludge, don't use it. It's use is always wrong

Hi,

Thanks for your feedbacks. I have done the following update. Can you let me know if it is correct.

string lastErrorMessage="";
datetime lastDateErrorMessage;
int error_code;
double tp_distance;
double sl_distance;

int openPosition(int cmd, double volume,double priceDistance=0, double sl=0,double tp=0)
{
     double marginFree      = AccountFreeMargin(); // Allow some slack
     double marginPerLot    = MarketInfo( Symbol(), MODE_MARGINREQUIRED );
     double stoplevel       = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;  //minimum stop loss/ take profit level, in points or pending order
     double freezelevel     = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point;
     
     //number of digit for min lot
     double maxLot = MarketInfo(Symbol(), MODE_MAXLOT);
     double minLot=MarketInfo(Symbol(),MODE_MINLOT);

     double size=NormalizeLots(volume);
      
      
      string description; 
      size=MathMax(minLot,size);
      size=MathMin(maxLot,size);
      if(!CheckVolumeValue(size,description))
      {
           lastErrorMessage="Volume is not correct";
           lastDateErrorMessage=TimeCurrent();
           Print("Error opening order for size ",size," : ",description);
           return -1;
      }
      
      //Pending order needs to be translated for checks
      int cmd_bis=(cmd<2)?cmd:cmd-4;

      //-- if there is not enough money 
      if(AccountFreeMarginCheck(Symbol(),cmd_bis,size)<0)
        {
         string oper=(cmd==OP_BUY)? "Buy":"Sell";
         lastErrorMessage="#"+IntegerToString(GetLastError())+" not enough money";
         lastDateErrorMessage=TimeCurrent();
         return(-1);
        }

      
   RefreshRates();
   //format price
   double openPrice=0;

   
   if(cmd==OP_BUYSTOP)  
      openPrice=Ask+MathMax(MathMax(priceDistance,stoplevel),freezelevel);
   else if(cmd==OP_SELLSTOP) 
      openPrice=Bid-MathMax(MathMax(priceDistance,stoplevel),freezelevel);

   //format stop loss and take profit
   //--- check stop orders for buying
   if(cmd==OP_BUYSTOP)
     {
      tp_distance = (tp - openPrice);
      sl_distance = (openPrice - sl);
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=openPrice+(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=openPrice-(stoplevel+1*Point);
     }
   //--- check stop orders for selling
   else if(cmd==OP_SELLSTOP)
     {
      tp_distance = (openPrice - tp);
      sl_distance = (sl - openPrice);
      if(tp!=0 && tp_distance>0 && tp_distance<=stoplevel) tp=openPrice-(stoplevel+1*Point);
      if(sl!=0 && sl_distance>0 && sl_distance<=stoplevel) sl=openPrice+(stoplevel+1*Point);
     }

     int lastTicketNumber=OrderSend(Symbol(),cmd, size,NormalizePrice(openPrice),3,0,0,"Test",12345,0,White);
 
     if(lastTicketNumber>0)
     {
         if(!OrderSelect(lastTicketNumber,SELECT_BY_TICKET,MODE_TRADES))
         {
            lastErrorMessage="#"+IntegerToString(GetLastError())+" position not found";
            lastDateErrorMessage=TimeCurrent();
            return lastTicketNumber;
         }
         
         if(sl>0 || tp>0)
         {
            //bool res=OrderModify(lastTicketNumber,OrderOpenPrice(),NormalizeDouble(sl,Digits),NormalizeDouble(tp,Digits),0,White);
            bool res=OrderModify(lastTicketNumber,openPrice,NormalizePrice(sl),NormalizePrice(tp),0,White);

            if(!res)
            {
               lastErrorMessage="#"+IntegerToString(GetLastError())+" can not modify order";
               lastDateErrorMessage=TimeCurrent();
               Print("Error #",GetLastError()," Cmd:",cmd," Order :",OrderType()," Price:",OrderOpenPrice()," SL:",NormalizeDouble(sl,Digits)," TP:",NormalizeDouble(tp,Digits));
               Print("Error initial price: ",NormalizeDouble(openPrice,Digits));
            }
         }
          
         return lastTicketNumber;
     }
     else
     {
        error_code=GetLastError();
        switch(error_code)                                  
        {                                            
         case ERR_TRADE_NOT_ALLOWED : 
            lastErrorMessage="#"+IntegerToString(error_code)+" Trade is not allowed";
            break; //4109 Trade is not allowed.
         case ERR_INVALID_STOPS: 
            lastErrorMessage="#"+IntegerToString(error_code)+" Invalid stop";
            break; //130 invalid stop
         default: 
            lastErrorMessage="#"+IntegerToString(error_code)+" Error opening order";
        }
        lastDateErrorMessage=TimeCurrent();
     }
    return 0;
}

double NormalizeLots(double lots, string pair="")
{
    if (pair == "") pair = Symbol();
    double  lotStep     = MarketInfo(pair, MODE_LOTSTEP),
            minLot      = MarketInfo(pair, MODE_MINLOT);
    lots            = MathRound(lots/lotStep) * lotStep;
    if (lots < minLot) lots = minLot;    // or minLot
    return(lots);
}

double NormalizePrice(double p, string pair="")
{

    if (pair == "") pair = Symbol();
    double ts = MarketInfo(pair, MODE_TICKSIZE);
    return( MathRound(p/ts) * ts );
}