OrderSend / OrderClose Issue

 

Hello everyone!
I've researched for days, including here, using the term "ordersend/orderclose not working". There are lots of questions/answers but I still cannot figure it out.
I appreciate your help.

I'm attaching 2 of the many attempts I've tried, with notes on the behavior of each of them...

#property strict

input string  iNote_1 = " --== EA Settings ==-- ";
input double  iLot    = 0.01;   //Lot
input int     iMagic  = 201159//Mag

double sma_5;   //magenta
double sma_16;  //cyan
double sma_25;  //orange
double sma_50;  //dash white
double rsi;

int ticket;

datetime gBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      sma_5  = iMA (_Symbol,_Period,5,0,MODE_SMA,PRICE_OPEN,0);   //magenta
      sma_16 = iMA (_Symbol,_Period,16,0,MODE_SMA,PRICE_OPEN,0);  //cyan
      sma_25 = iMA (_Symbol,_Period,25,0,MODE_SMA,PRICE_OPEN,0);  //orange
      sma_50 = iMA (_Symbol,_Period,50,0,MODE_SMA,PRICE_OPEN,0);  //dash white 

      rsi = iRSI(_Symbol,_Period,7,PRICE_CLOSE,0);

      // new local variable to hold the current open time of bar zero
      datetime rightBarTime = iTime(_Symbol, _Period, 0);
      // check if bar zero has the same open time as the global variable
      if(rightBarTime != gBarTime){
         // set the global variable to be the time of bar zero
         gBarTime = rightBarTime;
         // call on bar function
         OnBar();
      }
  }

void OnBar()
{ 
    // placing BUY
    if(OrdersTotal() == 0){
        if(rsi < 25)  
          if((sma_5 < sma_16) && (sma_16 < sma_25))
             ticket = OrderSend(Symbol(),OP_BUY,iLot,Ask,3,0,0,NULL,iMagic,0,clrGreen);

    // placing SELL 
        if(rsi > 75)  
          if((sma_5 > sma_16) && (sma_16 > sma_25))
             ticket = OrderSend(Symbol(),OP_SELL,iLot,Bid,3,0,0,NULL,iMagic,0,clrRed);
    }     
    // closing BUY //
    if(OrdersTotal() >= 1){
      if((sma_5 < sma_16) && (sma_16 > sma_25))
       if(OrderType()== OP_BUY)
          OrderClose(ticket,iLot,Bid,3,clrWhite); 
      
    // closing SELL
      if((sma_5 < sma_50) && (sma_16 < sma_50) && (sma_5 > sma_16))
       if(OrderType()== OP_SELL)
          OrderClose(ticket,iLot,Ask,3,clrMagenta); 

    }
}


When backtesting with the above code and...
(a) setting Positions to Long & Short, it places a single SELL but never closes it.
     The Journal shows OrderClose error 138 = MT4 platform has missed your quoted price for executing an order.

(b) setting Positions to Short Only, has same behavior as above.

(c) setting Positions to Long Only, it operates correctly opening and closing BUY orders as expected.

As such I recoded to the following,

#property strict

input string  iNote_1 = " --== EA Settings ==-- ";
input double  iLot    = 0.01;   //Lot
input int     iMagic  = 201159; //Mag

double sma_5;   //magenta
double sma_16;  //cyan
double sma_25;  //orange
double sma_50;  //dash white

int ticket;
int order;

datetime gBarTime;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      sma_5  = iMA (_Symbol,_Period,5,0,MODE_SMA,PRICE_OPEN,0);   //magenta
      sma_16 = iMA (_Symbol,_Period,16,0,MODE_SMA,PRICE_OPEN,0);  //cyan
      sma_25 = iMA (_Symbol,_Period,25,0,MODE_SMA,PRICE_OPEN,0);  //orange
      sma_50 = iMA (_Symbol,_Period,50,0,MODE_SMA,PRICE_OPEN,0);  //dash white 

/*    // new local variable to hold the current open time of bar zero
      datetime rightBarTime = iTime(_Symbol, _Period, 0);
      // check if bar zero has the same open time as the global variable
      if(rightBarTime != gBarTime)
      {
         // set the global variable to be the time of bar zero
         gBarTime = rightBarTime;
      }
      if(gBarTime == rightBarTime){
*/
      if(OrdersTotal() == 0){
        // placing BUY
        if((sma_5 < sma_16) && (sma_16 < sma_25))
           ticket = OrderSend(Symbol(),OP_BUY,iLot,Ask,3,0,0,NULL,iMagic,0,clrGreen);
         
        // placing SELL    
        if((sma_5 > sma_16) && (sma_16 > sma_25))
           ticket = OrderSend(Symbol(),OP_SELL,iLot,Bid,3,0,0,NULL,iMagic,0,clrRed);
      }      

      // closing orders
      if(OrdersTotal() >= 1)
         ClosingOrders();
  }

void ClosingOrders()
 { 
    // closing BUY
      if((sma_5 < sma_16) && (sma_16 > sma_25))
        if(OrderType()== OP_BUY)
         if(OrderMagicNumber() == iMagic)        
           if(OrderSymbol()== Symbol())
              order = OrderClose(ticket,iLot,Bid,3,clrWhite); 
      
    // closing SELL
      if((sma_5 < sma_50) && (sma_16 < sma_50) && (sma_5 > sma_16))
        if(OrderType()== OP_SELL)
         if(OrderMagicNumber() == iMagic)        
           if(OrderSymbol()== Symbol())
              order = OrderClose(ticket,iLot,Ask,3,clrMagenta); 
 }

When backtesting with the above code...
(a) when Positions is set to Long & Short it places and closes "n" SELL orders in the same candle and Journal shows OrderSend error 134.

(b) when Positions is set to Long Only it places a single BUY but never closes it. Journal shows OrderSend error 4111.
.

 

Mosamba: I've researched for days, including here, using the term "ordersend/orderclose not working". There are lots of questions/answers but I still cannot figure it out. I appreciate your help. I'm attaching 2 of the many attempts I've tried, with notes on the behavior of each of them...

When backtesting with the above code and...
(a) setting Positions to Long & Short, it places a single SELL but never closes it.  The Journal shows OrderClose error 138 = MT4 platform has missed your quoted price for executing an order.

(b) setting Positions to Short Only, has same behavior as above.

(c) setting Positions to Long Only, it operates correctly opening and closing BUY orders as expected.

As such I recoded to the following,

When backtesting with the above code...
(a) when Positions is set to Long & Short it places and closes "n" SELL orders in the same candle and Journal shows OrderSend error 134.

(b) when Positions is set to Long Only it places a single BUY but never closes it. Journal shows OrderSend error 4111.

Runtime Errors - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL4 Reference

134

ERR_NOT_ENOUGH_MONEY

Not enough money

138

ERR_REQUOTE

Requote

4111

ERR_SHORTS_NOT_ALLOWED

Shorts are not allowed. Check the Expert Advisor properties

Error 134: You are not properly calculating your volume based on your stop-loss risk and free margin.

Error 138: A re-quote occurred because the account/symbol is using Instant Execution Policy and the deviation/slippage setting is too low or the market price slipped too much and needs to be reevaluated.

Error 4111: Is because you disabled shorts/sells or because the symbol does not support them.

I would offer you links to previous posts of mine referencing these points (as they are common problems for newbies), the but the site's search function is currently not functioning properly. So I will leave the search to you to do, once the site is functioning properly again.

Runtime Errors - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL4 Reference
Runtime Errors - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL4 Reference
  • docs.mql4.com
Runtime Errors - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL4 Reference
 
       if(OrderType()== OP_SELL)
MT4: You can not use any Trade Functions until you first select an order.
 
Fernando Carreiro #:

Runtime Errors - Codes of Errors and Warnings - Constants, Enumerations and Structures - MQL4 Reference

134

ERR_NOT_ENOUGH_MONEY

Not enough money

138

ERR_REQUOTE

Requote

4111

ERR_SHORTS_NOT_ALLOWED

Shorts are not allowed. Check the Expert Advisor properties

Error 134: You are not properly calculating your volume based on your stop-loss risk and free margin.

Error 138: A re-quote occurred because the account/symbol is using Instant Execution Policy and the deviation/slippage setting is to low or the market price slipped too much and needs to be reevaluated.

Error 4111: Is because you disabled shorts/sells or because the symbol does not support them.

I would offer you links to previous posts of mine referencing these points (as they are common problems for newbies), the but the site's search function is currently not functioning properly. So I will leave the search to you to do, once the site is functioning properly again.

Hi Fernando. Thanks so much for your time! The problem was actually the 138 (slippage). Previously, I did check the Journal messages, and had done a research about 138 and on all samples I found none of them had slippage  set above 3 so I set mine to 10 and still no solution. After your answer I decided to go radical and changed slippage to 30, 50 and 100. Only with 100 it did work, so from 100 up my coding to open and close orders is finally working - which brings me to think how accurate back testing is in MT4, because I don't think that in a real account this level of slippage will ever be required - but anyway, for this stage of learning, it's fine and now I may  focus on the strategy itself. Cheers!  
 
William Roeder #:
MT4: You can not use any Trade Functions until you first select an order.
Thanks for the hint William!!!
 
Mosamba #: Hi Fernando. Thanks so much for your time! The problem was actually the 138 (slippage). Previously, I did check the Journal messages, and had done a research about 138 and on all samples I found none of them had slippage  set above 3 so I set mine to 10 and still no solution. After your answer I decided to go radical and changed slippage to 30, 50 and 100. Only with 100 it did work, so from 100 up my coding to open and close orders is finally working - which brings me to think how accurate back testing is in MT4, because I don't think that in a real account this level of slippage will ever be required - but anyway, for this stage of learning, it's fine and now I may  focus on the strategy itself. Cheers!  

100 points = 10 pips.

In live trading there can actually be slippage of any size. For example, during high volatility of news events, slippage on Forex can easily be in the range of 100 pips = 1000 points.

 
void ClosingOrders()
 { 
    
// for loop {
	/// orderselect 	
        if(OrderType()< 1)
	if(OrderType () == OP_BUY)
        if(OrderMagicNumber() == iMagic) <---- not needed
        if(OrderSymbol()== Symbol())
	if(sma_5 < sma_16 
	&& sma_16 > sma_25) 
          { order = OrderClose(ticket,iLot,Bid,3,clrWhite); } <--- instead of ticket (which i use to do) put OrderClose(OrderTicket(),OrderLots(),OrderOpenPrice(),0,0). 
       ////  i know it shows a warning when you dont emphasize on the ordersend, but that is a very minor issue because OrderSelect will select the order for you. 
      
    // closing SELL
      else{ if(sma_5 < sma_50  //// using the else if command, you do not have to specify if its AN OP_SELL, ea will recognize what to close if you have 2 types of positions
		&& (sma_16 < sma_50
		 && (sma_5 > sma_16)
              		order = OrderClose(ticket,iLot,Ask,3,clrMagenta); }
	}
 }

This should be working after you do a a for loop and then select the order. I take out the magic number because it is not needed UNLESS, you actually have a compiling problem and the ea cannot find your orders and also because you are really using only one pair. Putting them all into one loop will help this function very well since there is only one output (much easier for the ea to flick through the inputted signals). Read the code carefully, the logic will make sense once you understand the code and what the new commands return.

 
Fernando Carreiro #:

100 points = 10 pips.

In live trading there can actually be slippage of any size. For example, during high volatility of news events, slippage on Forex can easily be in the range of 100 pips = 1000 points.

Thanks very much for clarifying this. Could I then assume that the best practice would be to always set slippage to 0 and in this case the EA would handle volatility automatically?
 
Adj007 #:

This should be working after you do a a for loop and then select the order. I take out the magic number because it is not needed UNLESS, you actually have a compiling problem and the ea cannot find your orders and also because you are really using only one pair. Putting them all into one loop will help this function very well since there is only one output (much easier for the ea to flick through the inputted signals). Read the code carefully, the logic will make sense once you understand the code and what the new commands return.

Thanks very much for having edited my code...for a newbie it makes this much easier! Just one question - on your first "if" shouldn't it be "(OrdersTotal > 0) ?
 
Mosamba #: Thanks very much for clarifying this. Could I then assume that the best practice would be to always set slippage to 0 and in this case the EA would handle volatility automatically?

That depends on your strategy. Surely if the entry price is too far away it could potentially invalidate one or two of your entry rules, right?

 
Fernando Carreiro #:

That depends on your strategy. Surely if the entry price is too far away it could potentially invalidate one or two of your entry rules, right?

Got it. But because I'm only now starting to set the strategy I'll keep it in mind. Thanks!
Reason: