Download MetaTrader 5

Help coding delete pending after Buy or Sell Execute

To add comments, please log in or register
We have launched Spanish and Portuguese versions of the website. Try them!
ctripp
21
ctripp 2016.06.18 21:44 

I am a new coder in MQL4.  

I am working on an EA that will delete all pending orders after a single pending BuyStop or SellStop order is executed and changed to a Buy or Sell.

My results are mixed, it seems it is working if the Sell Stop is executed to a Sell, the Buy Stop is deleted.
However, if a Buy Stop is executed into a Buy, the Sell Stop seems to continue until the close all orders time at which time it is finally closed.

I cant find what I am doing wrong so that the Buy Stop to Buy execution will delete the existing Sell Stop.
Also it seems that the Close All Orders is only working with Pending Orders and not ALL orders. 

Here is a screen shot of what is happening.

 

 Trade Window Illustration

 

Here is the code I am using:

      bool t = checkchanneltime();
      if(OrdersTotal()==0 && t==true && DayOfWeek()>0)//Do only if No orders placed, it is inside the channel time, and it is not Sunday(0)
      {
        switch(Minute())// look for channels every 15 minutes
        {
            case 0: 
            channelchecker();
            break;
            case 15: 
            channelchecker();
            break;
            case 30: 
            channelchecker();
            break;
            case 45: 
            channelchecker();
            break;
            default:
            break;
         } 
       }                       
     
      if(Hour()==closeAllOrdersTime)
      {
         deletepending();
         closeall();
      }
      
      for (int i = OrdersTotal()-1; i > 0; i--)// This code is supposed to check if any Pending have become buy or sell orders, and if so, delete all pending. 
      {
         if ( OrderSelect(i,SELECT_BY_POS,MODE_TRADES) )
         {
            if (OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
            deletepending();
            }
         }
      }
   }

 And the deletependings and closeall() functions:

void deletepending()
{
   Alert("Deleting Pending");
   for(int w=0; w<OrdersTotal(); w++)
   {
      if(OrderSelect(w, SELECT_BY_POS,MODE_TRADES)==true)
      {
         if(OrderType()==OP_BUYSTOP||OrderType()==OP_SELLSTOP)
         {
            bool result=false;
            result=OrderDelete(OrderTicket());
         }
      }
   }
   
}
        
void closeall()
{

   Alert("Closing ALL");
   for(int i=1; i<OrdersTotal(); i++)
   {
      if(OrderSelect(i-1, SELECT_BY_POS, MODE_TRADES)==true)
      {
         if(OrderMagicNumber()==magic)
         {
            int j=0;
            while(j!=5)
               {
                  bool result=false;
                  result=OrderClose(OrderTicket(),OrderLots(),Bid,3,Pink);
                  PlaySound("news.wav");
                  j++;
               }
         }
      }
    }
   orderFlag = true;
} 

 

 Any help would be greatly appreciated.

Thank you. 

ctripp
21
ctripp 2016.06.18 21:52  
Sorry in the Image where is says Take Profit, it should actuallly say Closed by Stop Loss.
Fernando Carreiro
2352
Fernando Carreiro 2016.06.18 22:17  

Why do most users insist on using Pending Orders in EA's. Pending Orders are for manual trades executed by humans which cannot be in front of the screen 24/5.

EAs on the other hand can and do work 24/5, so use Market Orders instead and you will not have to worry about updating or closing opposite pending orders.

In your EA, just keep track of 2 variables for your buy and sell prices and when the bid price crosses those thresholds, open a Market Order and clear the two variables! And that is all there is to it!

The added advantage is that you can track and compensate for spread before opening a Market Order while you cannot do that so easily with Pending Orders.

ctripp
21
ctripp 2016.06.18 22:47  

Yours is a different, and arguably better approach, although it doesn't really answer the question, WHY this happening.  

I can experiment with your approach, however I would need to rework some things in order to still visually show me where my channels and windows started and ended in the chart.  Call that lazy coding or whatever, but at the moment, as a beginner, this was the only way I thought to do it and allow me, 'the human', to be able to see all the actions in the chart data step by step as it happened in the Tester.  If I rework it with a bunch of object placements I think I could do this as well, although that we be another learning curve for me.

So your simple answer is, I am just doing it wrong.  

If placing Pending Orders are really just for manual trades executed by humans then why is it included in MQL4 at all?

Fernando Carreiro
2352
Fernando Carreiro 2016.06.18 23:59  
ctripp:

Yours is a different, and arguably better approach, although it doesn't really answer the question, WHY this happening.  

I can experiment with your approach, however I would need to rework some things in order to still visually show me where my channels and windows started and ended in the chart.  Call that lazy coding or whatever, but at the moment, as a beginner, this was the only way I thought to do it and allow me, 'the human', to be able to see all the actions in the chart data step by step as it happened in the Tester.  If I rework it with a bunch of object placements I think I could do this as well, although that we be another learning curve for me.

So your simple answer is, I am just doing it wrong.  

If placing Pending Orders are really just for manual trades executed by humans then why is it included in MQL4 at all?

EAs can also be used for aiding and supporting with manual trading and thus need to be able to allow Pending Orders to be used. However, for EAs that work fully automatically for 24/5, there is absolutely no advantage in using pending orders and there are in fact disadvantages. Regarding your code, here are my suggestions:

  • Your loops for Deleting/Closing are in the wrong order. When doing this, you should count backwards and not forwards.
  • When closing a Market Order use the OrderClosePrice() because Buy and Sell orders close at different prices, which the OrderClosePrice() correctly reflects (Buy Orders open at Ask and close at Bid, while Sell Orders open at Bid and close at Ask).
  • Always check both the Magic Number and the Symbol so that EA "plays well with others" and does not interfere with other EAs  (or itself on other charts) or manual trading.
  • When Checking for the Pending Orders that have changed into Market Orders, exit the loop, otherwise it will no longer index correctly with orders being deleted in between.
  • Also, OrderClose() only closes Market Orders (it does not delete Pending Orders). So you have to call both the "CloseMarketOrders()" (see below) and the "DeletePendingOrders()" (see below) or combine the functionality for both (see function "CloseDeleteAllOrders()" below).
  • There are actually several other "bugs" and bad practices in your code, but for now, I concentrated only on the issues you reported. We can address them at a later stage.

Please note that the following code was not tested as it was written specifically to answer your query:

void CheckMarketDeletePending()
{
   for( int i = OrdersTotal() - 1; i >= 0; i-- )
   {
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         if( ( OrderMagicNumber() == MyMagicNumber ) && ( OrderSymbol() == _Symbol ) )
         {
            if( ( OrderType() == OP_BUY ) || ( OrderType() == OP_SELL ) )
            {
               DeletePendingOrders();
               break;
            }
         }
      }
   }
}

void DeletePendingOrders()
{
   for( int i = OrdersTotal() - 1; i >= 0; i-- )
   {
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         if( ( OrderMagicNumber() == MyMagicNumber ) && ( OrderSymbol() == _Symbol ) )
         {
            if( ( OrderType() != OP_BUY ) && ( OrderType() != OP_SELL ) )
            {
               if( !OrderDelete( OrderTicket() ) )
               {
                  // Delete failed (need to deal with situation)
                  // Check Error Codes
               }
            }
         }
      }
   }
}
        
void CloseMarketOrders()
{
   for( int i = OrdersTotal() - 1; i >= 0; i-- )
   {
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         if( ( OrderMagicNumber() == MyMagicNumber ) && ( OrderSymbol() == _Symbol ) )
         {
            if( ( OrderType() == OP_BUY ) || ( OrderType() == OP_SELL ) )
            {
               if( !OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), MySlippagePoints ) )
               {
                  // Close failed (need to deal with situation)
                  // Check Error Codes
               }
            }
         }
      }
   }
}

void CloseDeleteAllOrders()
{
   for( int i = OrdersTotal() - 1; i >= 0; i-- )
   {
      if( OrderSelect( i, SELECT_BY_POS, MODE_TRADES ) )
      {
         if( ( OrderMagicNumber() == MyMagicNumber ) && ( OrderSymbol() == _Symbol ) )
         {
            if( ( OrderType() == OP_BUY ) || ( OrderType() == OP_SELL ) )
            {
               if( !OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), MySlippagePoints ) )
               {
                  // Close failed (need to deal with situation)
                  // Check Error Codes
               }
            }
            else
            {
               if( !OrderDelete( OrderTicket() ) )
               {
                  // Delete failed (need to deal with situation)
                  // Check Error Codes
               }
            }
         }
      }
   }
}
ctripp
21
ctripp 2016.06.19 01:34  

Thank you very much.  This is a more detailed explanation than I was expecting.  I appreciate the tutorial!

-CTripp 

Alain Verleyen
Moderator
30725
Alain Verleyen 2016.06.19 12:43  
FMIC:

Why do most users insist on using Pending Orders in EA's. Pending Orders are for manual trades executed by humans which cannot be in front of the screen 24/5.

Why ?

Pending orders are useful in EA too, if used appropriately. In the example of this topic, it's maybe easier to monitor the price and place market order, but that doesn't mean you can made a general rule that pending orders are for manual trading and useless in EA.

However, for EAs that work fully automatically for 24/5, there is absolutely no advantage in using pending orders and there are in fact disadvantages.

Please explain the disadvantages ?

There is some advantages :

  • A pending order is placed at server side, in volatile market that can mean your order will be executed while your EA is not yet notified about the price changed.
  • It's easier and clearer to code (not always), for example if you want to place a grid while opening a market order.
  • Limit orders are executed at the request price or better, you don't have such guarantee with a market order.
whroeder1
14480
whroeder1 2016.06.19 14:17  

Agree with FMIC.

  1. In the presence of multiple orders (one EA multiple charts, multiple EA's, manual trading) you must count down when closing/deleting/modifying in a position loop. Get in the habit of always counting down. Loops and Closing or Deleting Orders - MQL4 forum
  2. No filtering on your OrderSelect loop means your code is incompatible with every EA (including itself on other charts and manual trading.) Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 forum
Fernando Carreiro
2352
Fernando Carreiro 2016.06.19 15:11  
angevoyageur:

Why ?

Pending orders are useful in EA too, if used appropriately. In the example of this topic, it's maybe easier to monitor the price and place market order, but that doesn't mean you can made a general rule that pending orders are for manual trading and useless in EA.

Please explain the disadvantages ?

There is some advantages :

  • A pending order is placed at server side, in volatile market that can mean your order will be executed while your EA is not yet notified about the price changed.
  • It's easier and clearer to code (not always), for example if you want to place a grid while opening a market order.
  • Limit orders are executed at the request price or better, you don't have such guarantee with a market order.
  • A pending order is placed at server side, in volatile market that can mean your order will be executed while your EA is not yet notified about the price changed.
I disagree! In volatile markets, the spread can widen very quickly and a Pending Order can be triggered (and slip greatly) when you really don't want it to. Under normal network latency conditions, the use of Market Orders is a much better choice.

Normally, users set the trigger prices based on BID (and not ASK), because that is what is available in history data and indicators. However, some Pending orders, like BUY_STOP, get triggered at ASK prices, so one has to compensate the open price with the spread (especially for short-term trading), so as to properly match the BID Price conditions and one cannot correctly predict the spread for it when placing the pending order. Trying to compensate for it while prices are developing close to the Open price, means that the EA has to constantly send Order Modifications to adjust the Open Price, causing unnecessary traffic with the broker and excessive log file clutter. In an even worse case, the pending order my need to be deleted and when conditions improve, recreated again, and this also causes excessive traffic, but may even not be possible due to STOP-LEVEL and FREEZE-LEVEL conditions.

In my opinion, the best way to handle the scenario I just described, is a three-step process, where first a Market Order is placed when entry conditions are met but without any stops, and then taking into account the real open price (due to slippage), set the Stop-Loss and Take-Profit accordingly (but with a certain safety offset if necessary). The real Stop-Loss and Take-Profit are then set in the EA (by manually closing the order at the exit conditions), so as to compensate for the ASK price closure of SELL orders because we cannot predict the Spread when a Stop is to be triggered if that price is based on BID prices of an indicator or history data. If however, that level of complexity is not needed, then a two-step process with real Stop-Loss and Take-Profit is used (without the safety offset).
  • It's easier and clearer to code (not always), for example if you want to place a grid while opening a market order.
Again, I disagree! Given the complexities I just described in the previous point, Market Orders will inherently always be more code efficient and in my opinion, be clearer in a properly coded EA. Even for Grids, you can easily do it and manage it much more efficiently with Market orders. I know because I coded several complex Grid strategies back in 2012 using only Market Orders, before I realised that mathematically, Grid Hedging based strategies are doomed to fail, and never coded one again.
  • Limit orders are executed at the request price or better, you don't have such guarantee with a market order.

Sorry to say this, but that is definitely incorrect! If you monitor Pending order execution (on a real live account), you will see that it suffers both positive and negative slippage just like Market Orders do. In the strategy tester however, Pending Orders always get falsely triggered at the "perfect" price, which is just not what happens in real live trading. This is also one of the many reason why so many pending-order back-tests give such "great" results, only to be shattered in real live trading. Even though Market Orders in the Strategy Tester still don't suffer real slippage, they do portray a more realistic price opening than Pending Orders do. Stop-Loss and Take-Profit are also triggered at the false "Perfect" prices in the Strategy Tester, but if the EA code is able to use "Virtual" stops during back-tests (while still using real stops on live), it will also provide a more realistic result.

There is only one real advantage of Pending Orders in EAs, and that is in the case of great Network latency or even system failure, where the pending order will still be triggered even though the EA is unable to properly communicate. However, this is only acceptable during long-term or medium-term trading. In short-term trading, especially at fast time-frames and scalping, it is actually safer to not have an order triggered at all, because if you do have network issues, you will not be able to monitor and manage the open order promptly which can lead to losses. In such short-term trading scenarios, even if a Pending Order already has a Take-Profit and Stop-Loss associated, which will allow it to be handled by the server without much EA intervention, it can still suffer slippage during volatility periods that will not be able to be compensated for if the EA is not able to track it, and in these cases it is better to be safer than sorry.

Please note that the all the above points and arguments I gave, are based both on logic as well as real-life experience of my own EAs that I have coded and used over the years. In the beginning (back in 2011) I wrote several EAs with Pending Orders and soon realised these disadvantages when they went "live". I have since then always coded using Market Orders and have never looked back on that decision.

Alain Verleyen
Moderator
30725
Alain Verleyen 2016.06.19 19:42  
FMIC:

I will let you quiet with all your certainties. It's not about disagree or agree, it's about facts, and the facts are there is no reason to say that "pending order are for manual trades" in all cases and all situations. It seems an habit for some coders here to think in black and white, but the real world is just grey.

All the best.

Fernando Carreiro
2352
Fernando Carreiro 2016.06.20 07:31  
angevoyageur:

I will let you quiet with all your certainties. It's not about disagree or agree, it's about facts, and the facts are there is no reason to say that "pending order are for manual trades" in all cases and all situations. It seems an habit for some coders here to think in black and white, but the real world is just grey.

All the best.

Everyone is free to do as they see as best serving their trading (manual or with EA). We are both expressing our opinions based on facts that suit our point-of-view. If you follow the forum and look at all my posts, you will see that this is the first time that I have expressed my opinion about the disadvantages of using Pending Orders in EA's in general. However, I have not been the only one to do so. There is at least one other on this forum, that I know of, that has expressed a similar opinion, but I have never discussed it with him.

Outside, of this forum, I know of a few others that share the same point-of-view as myself, but the vast majority of coders are in favour of using Pending Orders in EA's. Even though, we are a minority, that does not automatically "brand" us as incorrect. As an example of this "minority" vs "majority", is the fact that most of the world drive on the right-hand side of the road. However taking into account that most of the population is "right-handed" (and "right-eyed"), the most appropriate would be to drive on the left-hand side of the road. Yet, only a few countries do that (they are in the minority).

12
To add comments, please log in or register