OrderClose error 138

 

May i know how should i fix this problem? i googled the error it says it can be fixed by adding RefreshRates() because the bid /ask values are outdated, i added the refresh function to my code but the same error still jumps out 

OrderClose error 138


 
cyxstudio:

May i know how should i fix this problem? i googled the error it says it can be fixed by adding RefreshRates() because the bid /ask values are outdated, i added the refresh function to my code but the same error still jumps out 

OrderClose error 138

Show your code. 

This is the actual error:

ERR_REQUOTE138The requested price has become out of date or bid and ask prices have been mixed up. The data can be refreshed without any delay using the RefreshRates function and make a retry. If the error does not disappear, all attempts to trade must be stopped, the program logic must be changed.
 
//+------------------------------------------------------------------+
//|                                       RSI_strategy_cyxstudio.mq4 |
//|                                  Copyright 2013, Tjipke de Vries |
//|                                     https://forum.mql4.com/53695/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"


extern int RSIPeriod        =  3;      //number of periods for RSI
extern double UpperBound    =  90;     //set upper bound value for RSI
extern double LowerBound    =  5;      //set lower bound value for RSI
extern int MASlowPeriod     = 200;
extern int MAFastPeriod     = 5;
extern double Lots  = 0.1;
extern double StopLoss      = 60;       //Set the stop loss level
extern double TakeProfit    = 120;       //Set the take profit level
extern double TrailingStop = 40;
//extra settings for OrderSend
extern int        MagicNumber = 54333;
extern string     CommentEA = "RSI strategy";
extern int        Slippage.Pips    = 3;


int    BUYS=1,SELLS=1;
//++++ These are adjusted for 5 digit brokers.
int     pips2points;      // slippage  3 pips    3=points    30=points
double  pips2dbl;         // Stoploss 15 pips    0.015      0.0150
int     Digits.pips;      // DoubleToStr(dbl/pips2dbl, Digits.pips)
//---
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----   
   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        
//----      

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
  Print("Account balance = ",AccountBalance());
  Print("Account number ", AccountCredit());
  Print("Account free margin = ",AccountFreeMargin());
//----
   int Ticket;
   double SL,TP;
   int Total;
   double MagicNo;
   double Slippage;
   
   double pAsk = MarketInfo(Symbol(), MODE_ASK);
   double pBid = MarketInfo(Symbol(), MODE_BID);
   double MA200 = iMA(NULL, 0, MASlowPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);  //200 day Moving Average   
   double MA5 = iMA(NULL, 0, MAFastPeriod, 0,MODE_SMA,PRICE_CLOSE, 0);      //  5 day Moving Average
   double CurrentRSI = iRSI (NULL, 1440, RSIPeriod,PRICE_CLOSE ,0);
  
   int Ticket2;
   int cnt;
   
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
   if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }


  
        
        
        if (OrdersTotal() == 0 ) {
        
        if (CurrentRSI < LowerBound && pAsk > MA200) {    //Condition to execute buy entry
  
        Ticket = OrderSend(Symbol(), OP_BUY, Lots, pAsk, 3, pBid - ( StopLoss * Point ), pAsk + ( TakeProfit * Point ), "Buy.", 111,0,Yellow)   ;       //execute buy order
   
    if(Ticket>0)
           {
            if(OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("BUY order opened : ",OrderOpenPrice());
            
           }
         if (Ticket < 0) {
         Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
   }
  
  }
  
  
 
  if (CurrentRSI > UpperBound && pBid < MA200) {     //Condition to execute sell entry
  
       Ticket2 = OrderSend(Symbol(), OP_SELL, Lots, pBid, 3, pAsk + ( StopLoss * Point ), pBid - ( TakeProfit * Point ), "Sell.",000, 0, Yellow)  ;     //execute sell order
       if(Ticket2>0)
           {
            if(OrderSelect(Ticket2,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("SELL order opened : ",OrderOpenPrice());
           
           }
         if (Ticket2<0) {
          Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      
   
   } 
   }
   
   if (OrdersTotal() > 0 ) {
   
   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

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 !
   {
   RefreshRates();
   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 ?
      RefreshRates();
   if (pAsk > MA5){      //condition to close long position
   RefreshRates();
    OrderClose(OrderTicket(),OrderLots(),pBid,3,Violet); // close long position
    RefreshRates();
   
   
   if(TrailingStop>0)  
              {                 
               if(pBid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<pBid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),pBid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
   
  }
   
   if(pBid < MA5){       //condition to close short position
   RefreshRates();
   OrderClose(OrderTicket(),OrderLots(),pAsk,3,Violet); // close short position
     RefreshRates();
   
   
   
  if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-pAsk)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(pAsk+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),pAsk+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
   }
   
      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
   
   
   }
  
   
   
   
   
   
        
        
           return(0);
}  
as u can see i added RefreshRates() everywhere but it still has problem closing the order
 
cyxstudio:
as u can see i added RefreshRates() everywhere but it still has problem closing the order

RefreshRates() won't help,  you aren't using PredfinedVariables  Bid or Ask . . .

Please explain this code . . .

   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 ?
      RefreshRates();
   if (pAsk > MA5){      //condition to close long position
   RefreshRates();
    OrderClose(OrderTicket(),OrderLots(),pBid,3,Violet); // close long position ??  how do you know this order is a Buy ?
    RefreshRates();

 Why aren't you checking the return value from your OrderClose() to see if it worked or failed ?  don't you want to know ?  why not report the error number if it has failed along with the Bid, Ask and any other relevant information at te time ? 

 Read and implement this:  What are Function return values ? How do I use them ?

 
  1. //++++ These are adjusted for 5 digit brokers.
    int     pips2points;      // slippage  3 pips    3=points    30=points
    double  pips2dbl;         // Stoploss 15 pips    0.015      0.0150
    // OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl   
    
    You included my code for 4/5 digit brokers. Why didn't you adjust slippage?
    Ticket = OrderSend(Symbol(), OP_BUY, Lots, pAsk, 3, pBid - ...
    // and
    OrderClose(OrderTicket(),OrderLots(),pBid,3,Violet); // close l...

  2. if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) ) 
    What is the value of Slippage?
 
 if (pAsk > MA5){      //condition to close long position

    Ticket3 = OrderClose(OrderTicket(),OrderLots(),pBid,3,Violet); // close long position
if(Ticket3 == true)
           {
            
               Print("Buy Order closed",OrderClosePrice());
           
           }
         if (Ticket3 == false) {
          Print("Error closing SELL order : ",GetLastError() ,ErrorDescription(GetLastError())); 
         return(0); 
        }
   
   
   if(TrailingStop>0)  
              {                 
               if(pBid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<pBid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),pBid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
   
  }
   
   if(pBid < MA5){       //condition to close short position
   
   Ticket4 = OrderClose(OrderTicket(),OrderLots(),pAsk,3,Violet); // close short position
     if(Ticket4 == true)
           {
            
               Print("Buy Order closed",OrderClosePrice());
           
           }
         if (Ticket4 == false) {
          Print("Error closing SELL order : " ,GetLastError(), ErrorDescription(GetLastError()) + pBid + pAsk); 
         return(0); 
        }
   
   

i added in the error description code along with the bid and ask price . this is what i get..."no error"

 

 

 
cyxstudio:

i added in the error description code along with the bid and ask price . this is what i get..."no error"

Yes,  because you don't understand how to use GetLastError() . . .  read the documentation and learn.   "The function returns the last occurred error, then the value of special last_error variable where the last error code is stored will be zeroized."
 
RaptorUK:

RefreshRates() won't help,  you aren't using PredfinedVariables  Bid or Ask . . .

Please explain this code . . .


I said please . . . .  can you explain it ?
 
RaptorUK:
I said please . . . .  can you explain it ?


its used to check if a position has been open and if the condition of closing it has been met.
 
RaptorUK:

RefreshRates() won't help,  you aren't using PredfinedVariables  Bid or Ask . . .

Please explain this code . . .

how do you know this order is a Buy ?

? ?

By the way,  if your if statement is true all it does is call RefreshRates() . . .  the following code will happen even if the order is a pending order or for a different symbol . . . you might want to look at that.

Reason: