Unexplainable Error 130 on Modify Order · · · – – – · · · - page 2

 
Duarte Silva:

Before making any modify order, I check if SL and TP are outside stoplevels: https://book.mql4.com/appendix/limits. This should be enough, yes?

Of course not enough you might as well try to set levels above or below actual Ask or Bid this would result in an immediate orderclose if the modification was accepted.

And you have to check the value of MODE_STOPLEVEL itself because it can be floating.

MODE_STOPLEVEL

14

Stop level in points

 

A zero value of MODE_STOPLEVEL means either absence of any restrictions on the minimal distance for Stop Loss/Take Profit or the fact that a trade server utilizes some external mechanisms for dynamic level control, which cannot be translated in the client terminal. In the second case, GetLastError() can return error 130, because MODE_STOPLEVEL is actually "floating" here.

Print it... it may reveal something to you.

Whats it gonna be ? takeprofit? or TakeProfitValue?

         StopLossValue = LastHighUpFractal + SLMargin;
         TakeProfitValue = PriceValue - 2 * (StopLossValue - PriceValue);  

These values need to be Normalized.

bool res=OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-Point*TrailingStop,Digits),OrderTakeProfit(),0,Blue); 
 
Duarte Silva:

Hi Marco,

Let me try to explain better: When I call my ModifyOrders functions, I have to specify the Order Type. Example:

I use string to specify the Ordertype, because I think its more intuitive,  but I could use integers like your suggestion in other forum topic. This isn't the problem...

Once the function ModifyOrders is called, it makes the search of the desire OrderType to change it. The search and order slection it works fine but the ModifyOrder instrution doesn't execute and gives error 130. On previous tests that I made the order was accepted with the same value: Price Value, SL and TP.

Since this error I have been trying to understand what is the error:

- Checking the stoplevels of pending orders:

 MarketStopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();

- Normalized values:

I have read in the link above that error 130 can have several causes and I trying to find out... 

 

 After some code changes the problems remains the same... I send in attachment the mql4 file.

 

I hope that i have explained better. Feel free to ask... 

Move the MarketStopLevel assignment from ModifyOrders() to OnInit().

double MarketStopLevel = 0.0;
//+------------------------------------------------------------------+
//| Inicialização do Expert Adviser                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Data/hora de abertura da última barra
   Lastbar=Time[1];

   Previous_Bars=Bars;////////////////////////////////////////////Atenção ao número de barras do histórico)
   Unchecked_Bars=0;
   Print("*** INICIALIZAÇÃO ***");
   Print("Nº de barras a ler: ",Previous_Bars);

   MarketStopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();
 
Ernst Van Der Merwe:

Move the MarketStopLevel assignment from ModifyOrders() to OnInit().

That's not a good idea as the STOPLEVEL can change...although not often.
 

Or do this...

   static double MarketStopLevel = 0.0;
   
   //Converte o tipo de ordem   
   if(sTypeOrder == "OP_BUY") OrderTypeNum = 0;
   else if(sTypeOrder == "OP_SELL") OrderTypeNum = 1;
   else if(sTypeOrder == "OP_BUYLIMIT") OrderTypeNum = 2;
   else if(sTypeOrder == "OP_SELLLIMIT")  OrderTypeNum = 3;  
   else if(sTypeOrder == "OP_BUYSTOP") OrderTypeNum = 4;
   else if(sTypeOrder == "OP_SELLSTOP")  OrderTypeNum = 5;  
   else OrderTypeNum = -1;
   
   Print("*** Função Modificação de ordens ***: Order Number = ", OrderTypeNum, " TypeOrder: ", sTypeOrder);
    
   for(PositionIndex = OrdersTotal()-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() == iMagicNum && OrderSymbol() == Symbol() && OrderType() == OrderTypeNum)
            {
            Print("Ordem seleccionada do tipo pretendido. Ticket: ", OrderTicket(), " Tipo:", OrderType(), " Price:", OrderOpenPrice(), " SL:", OrderStopLoss(), " TP:", OrderTakeProfit());
            if (sTypeOrder == "OP_BUY" || sTypeOrder == "OP_SELL")   // No caso das ordens abertas apenas alteramos o stop loss vindo do main
               {
               PriceValue = 0;
               TakeProfitValue = OrderTakeProfit();
               }
            //------------> Validação dos limites da ordem ----------------------------------> https://book.mql4.com/appendix/limits      https://forum.mql4.com/50603
            double minStop = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();
            MarketStopLevel = (minStop>0)?minStop:MarketStopLevel;
 
Marco vd Heijden:

Of course not enough you might as well try to set levels above or below actual Ask or Bid this would result in an immediate orderclose if the modification was accepted.

And you have to check the value of MODE_STOPLEVEL itself because it can be floating.

MODE_STOPLEVEL

14

Stop level in points

 

A zero value of MODE_STOPLEVEL means either absence of any restrictions on the minimal distance for Stop Loss/Take Profit or the fact that a trade server utilizes some external mechanisms for dynamic level control, which cannot be translated in the client terminal. In the second case, GetLastError() can return error 130, because MODE_STOPLEVEL is actually "floating" here.

Print it... it may reveal something to you.

Whats it gonna be ? takeprofit? or TakeProfitValue?

These values need to be Normalized.

I have implemented all the requirement limits before any modification order, have checked the MODE_STOPLEVEL and normalized the value that goes on the ModifyOrder, but the problem remains: ERROR 130... I'm going to make a comment to explaint the results...

About TakeProfit or TakeProfitValue, I have corrected to TakeProfit because the name of the variable may confuse. Thanks for the tip.

 
Ernst Van Der Merwe:

Or do this...

Ernst, despiste having checked the MODE_STOPLEVEL the problem remains...

void ModifyOrders(string sTypeOrder)
  {
   bool TradeConditionsOK = false;
   int CountOrders = 0, IndexSave = 0, OrderTypeNum = 0;
   static double MarketStopLevel = 0.0, MarketFreezeLevel = 0.0;
   
   //Converte o tipo de ordem   
   if(sTypeOrder == "OP_BUY") OrderTypeNum = 0;
   else if(sTypeOrder == "OP_SELL") OrderTypeNum = 1;
   else if(sTypeOrder == "OP_BUYLIMIT") OrderTypeNum = 2;
   else if(sTypeOrder == "OP_SELLLIMIT")  OrderTypeNum = 3;  
   else if(sTypeOrder == "OP_BUYSTOP") OrderTypeNum = 4;
   else if(sTypeOrder == "OP_SELLSTOP")  OrderTypeNum = 5;  
   else OrderTypeNum = -1;
   
   for(PositionIndex = OrdersTotal()-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() == iMagicNum && OrderSymbol() == Symbol() && OrderType() == OrderTypeNum)
            {
            //------------ Apenas altera os SL 
            Print("Ordem seleccionada do tipo pretendido. Ticket: ", OrderTicket(), " Tipo:", OrderType(), " Price:", OrderOpenPrice(), " SL:", OrderStopLoss(), " TP:", OrderTakeProfit());
            if (sTypeOrder == "OP_BUY" || sTypeOrder == "OP_SELL")
               {
               PriceValue = 0;
               TakeProfit = OrderTakeProfit();
               }
               
            //------------ Requirements and Limitations in Making Trades
            MarketStopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();
            MarketFreezeLevel = MarketInfo(Symbol(),MODE_FREEZELEVEL)*Point();
            
            if(MarketStopLevel > 0.0)//---- StopLevel Minimum Distance Limitation --- Requirements --- FreezeLevel Limitation).
              {
               if (OrderType() == OP_BUYSTOP)
                  {
                  if ((PriceValue - Ask >= MarketStopLevel) && (PriceValue - StopLoss >= MarketStopLevel) && (TakeProfit - PriceValue >= MarketStopLevel)
                     && PriceValue > Ask && (PriceValue - Ask > MarketFreezeLevel)) TradeConditionsOK = true;
                  else Print ("#ERRO: Limites Stop Level NOT OK.");
                  }
               if (OrderType() == OP_SELLSTOP)
                  {
                  if ((Bid - PriceValue >= MarketStopLevel) && (StopLoss - PriceValue >= MarketStopLevel) && (PriceValue - TakeProfit >= MarketStopLevel)
                     && PriceValue < Bid && (Bid - PriceValue > MarketFreezeLevel)) TradeConditionsOK = true;
                  else Print ("#ERRO: Limites Stop Level NOT OK.");
                  }
               if (OrderType() == OP_SELL)
                  {
                  if ((StopLoss - Ask>= MarketStopLevel) && (Ask - TakeProfit >= MarketStopLevel)
                     && (StopLoss - Ask > MarketFreezeLevel) && (Ask - TakeProfit > MarketFreezeLevel)) TradeConditionsOK = true;
                  else Print ("#ERRO: Limites Stop Level NOT OK.");
                  }
               if (OrderType() == OP_BUY)
                  {
                  if ((Bid - StopLoss >= MarketStopLevel) && (TakeProfit - Bid >= MarketStopLevel)
                     && (Bid - StopLoss > MarketFreezeLevel) && (TakeProfit - Bid > MarketFreezeLevel)) TradeConditionsOK = true;
                  else Print ("#ERRO: Limites Stop Level NOT OK.");
                  }
               if(TradeConditionsOK == true)
                 {
                  if(OrderModify(ticket,NormalizeDouble(PriceValue, Digits),NormalizeDouble(StopLoss, Digits),NormalizeDouble(TakeProfit, Digits),0,Green))
                    {
                     Print("Ordem de modificação bem sucedida.");
                    }
                  else Print("Erro: Ordem de modificação mal executada!!",GetLastError());
                  
                  TradeConditionsOK = false;
                  CountOrders = CountOrders + 1;
                 }
              }
            
            else Print ("Market Level igual a Zero: Possivel Erro 130 na ordem de modificação");
            
            Print ("Dados da modificação de ordens: PV: ", PriceValue, " SL: ", StopLoss, " TP: ", TakeProfit, " Ask: ", Ask, " Bid: ", Bid, " StopLevel: ", DoubleToString(MarketStopLevel, Digits), " Freeze Level: ", DoubleToString(MarketFreezeLevel, Digits));
            }
         }
     }
  }

 The error is the same: 130.

I have tried to increase and decrease a SL margin that I have in code and the result is the same! Trade requirements are fulfilled to proceed to ModifyOrder but still gives error... The log print values when "OP_BUYSTOP" modification orders goes are:

"Dados da modificação de ordens: PV: 1.2098 SL: 1.1795 TP: 1.2704 Ask: 1.19285 Bid: 1.1927 StopLevel: 0.00001 Freeze Level: 0.00000 "

Like I said to Marco, I have tried to increase and decrease the SL margin that I have in code to try not getting error 130 and the result isn't better. 

 

Can I ask someone to test the EA in attachmento in the year of 2006 on EURUSD to see if the result is  the same?

 

Yes it will still give error 130. The idea of my code is to use the previous value if the current one is zero.

double MarketStopLevel = 0.0;
//+------------------------------------------------------------------+
//| Inicialização do Expert Adviser                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Data/hora de abertura da última barra
   Lastbar=Time[1];

   Previous_Bars=Bars;////////////////////////////////////////////Atenção ao número de barras do histórico)
   Unchecked_Bars=0;
   Print("*** INICIALIZAÇÃO ***");
   Print("Nº de barras a ler: ",Previous_Bars);

   MarketStopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();


//---
void ModifyOrders(string sTypeOrder)
  {
   int CountOrders = 0, IndexSave = 0, OrderTypeNum = 0;
 
   if(sTypeOrder == "OP_BUY") OrderTypeNum = 0;
   else if(sTypeOrder == "OP_SELL") OrderTypeNum = 1;
   else if(sTypeOrder == "OP_BUYLIMIT") OrderTypeNum = 2;
   else if(sTypeOrder == "OP_SELLLIMIT")  OrderTypeNum = 3;  
   else if(sTypeOrder == "OP_BUYSTOP") OrderTypeNum = 4;
   else if(sTypeOrder == "OP_SELLSTOP")  OrderTypeNum = 5;  
   else OrderTypeNum = -1;

  for(PositionIndex = OrdersTotal()-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() == iMagicNum && OrderSymbol() == Symbol() && OrderType() == OrderTypeNum)
            {
            Print("Ordem seleccionada do tipo pretendido. Ticket: ", OrderTicket(), " Tipo:", OrderType(), " Price:", OrderOpenPrice(), " SL:", OrderStopLoss(), " TP:", OrderTakeProfit());
            if (sTypeOrder == "OP_BUY" || sTypeOrder == "OP_SELL")   // No caso das ordens abertas apenas alteramos o stop loss vindo do main
               {
               PriceValue = 0;
               TakeProfitValue = OrderTakeProfit();
               }
            //------------> Validação dos limites da ordem ----------------------------------> https://book.mql4.com/appendix/limits      https://forum.mql4.com/50603
            double minStop = MarketInfo(Symbol(),MODE_STOPLEVEL)*Point();
            MarketStopLevel = (minStop>0.0)?minStop:MarketStopLevel;
 
Duarte Silva:

Ernst, despiste having checked the MODE_STOPLEVEL the problem remains...

 The error is the same: 130.

I have tried to increase and decrease a SL margin that I have in code and the result is the same! Trade requirements are fulfilled to proceed to ModifyOrder but still gives error... The log print values when "OP_BUYSTOP" modification orders goes are:

"Dados da modificação de ordens: PV: 1.2098 SL: 1.1795 TP: 1.2704 Ask: 1.19285 Bid: 1.1927 StopLevel: 0.00001 Freeze Level: 0.00000 "

Like I said to Marco, I have tried to increase and decrease the SL margin that I have in code to try not getting error 130 and the result isn't better. 

 

Can I ask someone to test the EA in attachmento in the year of 2006 on EURUSD to see if the result is  the same?

This code was tested without any errors.

 
Ernst Van Der Merwe:

This code was tested without any errors.

Ernst, thank you for the help!

If you don't mind I would like to know how do you get there? It was the string conversion that doesn't work? The code has the same value: order index, SL values, type of order...

One more question: I was searching on the mql4 book for operand/expressions to understand the structure of the code that you have written:  "MarketStopLevel = (minStop>0.0)?minStop:MarketStopLevel;"

Can you give a link to read?

 
Duarte Silva:

Ernst, thank you for the help!

If you don't mind I would like to know how do you get there? It was the string conversion that doesn't work? The code has the same value: order index, SL values, type of order...

One more question: I was searching on the mql4 book for operand/expressions to understand the structure of the code that you have written:  "MarketStopLevel = (minStop>0.0)?minStop:MarketStopLevel;"

Can you give a link to read?

It wasn't the string conversion because:

Duarte Silva:

This isn't the problem...

Now you successfully hired Ernst for a couple of days to,

Marco vd Heijden:

Rewrite the whole thing the way it should be.


https://www.mql5.com/en/docs/basis/operators/ternary

Documentation on MQL5: Language Basics / Operators / Ternary Operator ?:
Documentation on MQL5: Language Basics / Operators / Ternary Operator ?:
  • www.mql5.com
Language Basics / Operators / Ternary Operator ?: - Reference on algorithmic/automated trading language for MetaTrader 5