How to Close Orders with MQL4 Code

In earlier articles we noticed how to open new market orders and the way to scan the account for open orders, to shut the cycle we additionally want to find out how to shut orders with the perform OrderClose() . At this level the order might be a winner, loser or breakeven however we solely need to see how to shut the order utilizing MQL4 code. OrderClose()  is the MQL4 perform that permits you to shut open market orders completely or partially. This perform requires a couple of parameters, we are able to see them within the following specification.

The parameters anticipated are (daring the required):

We can apply what we discovered in how to Open Orders and Scan open Orders to shut orders, often orders are closed manually or through the technique of Order Management of an EA. In our instance we’ll scan for order and shut all of them, with some extra superior coding it is possible for you to to grow to be extra selective and select what orders to shut however for the second we’ll maintain it easy. Most of the knowledge vital to shut an order may be retrieved simply choosing the order, that is why the scan of the orders is so helpful. When you employ the OrderChoose()  perform many particulars in regards to the order may be retrieved with native MQL4 capabilities, specifically:

The above are the strictly vital nonetheless there are extra capabilities to retrieve much more particulars about an order, we’ll see them in another article. The perform CloseOrder()  is of sort boolean and returns true if the order is efficiently closed, false if the order is just not closed for some error. We can see an instance of script that closes all of the open market orders
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#property copyright "Luca Spinello"

#property link      "https://mql4tradingautomation.com"

#property version   "1.00"
#property strict
#property show_inputs
//Allowed Slippage
extern double Slippage=3;
//We declare a function CloseOpenOrders of type int and we want to return
//the number of orders that are closed
int CloseOpenOrders(){
   int TotalClose=0;  //We want to count how many orders have been closed
  
   //Normalization of the slippage
   if(Digits==3 || Digits==5){
      Slippage=Slippage*10;
   }
  
   //We scan all the orders backwards, this is required as if we start from the first we will have problems with the counters and the loop
   for( int i=OrdersTotal()1;i>=0;i) {
      
      //We select the order of index i selecting by position and from the pool of market/pending trades
      //If the selection is successful we try to close it
      if(OrderSelect( i, SELECT_BY_POS, MODE_TRADES )){
      
         //We define the close price, which depends on the type of order
         //We retrieve the price for the instrument of the order using MarketInfo(OrderSymbol(),MODE_BID) or MODE_ASK
         //And we normalize the price found
         double ClosePrice;
         RefreshRates();
         if(OrderType()==OP_BUY) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),Digits);
         if(OrderType()==OP_SELL) ClosePrice=NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),Digits);
        
         //If the order is closed correcly we increment the counter of closed orders
         //If the order fails to be closed we print the error
         if(OrderClose(OrderTicket(),OrderLots(),ClosePrice,Slippage,CLR_NONE)){
            TotalClose++;
         }
         else{
            Print(“Order failed to close with error – “,GetLastError());
         }
      }
      //If the OrderSelect() fails we return the cause
      else{
         Print(“Failed to select the order – “,GetLastError());
      }  
      
      //We can have a delay if the execution is too fast, Sleep will wait x milliseconds before proceed with the code
      //Sleep(300);
   }
   //If the loop finishes it means there were no more open orders for that pair
   return(TotalClose);
}
void OnStart()
{
   Print(“How many orders have been closed ? “,CloseOpenOrders());
If we run the script in any chart it’s going to shut all of the orders, not restricted to the forex pair within the chartHow to Close Orders with MQL4 CodeHow to Close Orders with MQL4 CodeApplying extra filters we may limit the choice of the orders and shut solely particular ones. With this text you discovered how to shut an order with MQL4 language, do some experiment and check it your self. I keep in mind once I first began to study MQL coding,

though I had some information of coding many idea have been nonetheless unclear. To pace up your studying course of I might suggest to observe a fast MQL course that will provide you with the basics you want to create purposeful Trading Robot.

You can take a look at the next two course, Udemy typically has gross sales on to make the programs much more reasonably priced, and should you subscribe to my e-newsletter (prime and backside of the web page) I’ll let you recognize when this occurs.

MQL4 Programming for Traders: Build Robust Trading Robots!

Black Algo Trading: Build Your Trading Robot

Please depart a remark if in case you have any suggestions or doubt and keep in mind to like us on Social Media!

If you need to save hours of analysis and coding and also you need to see some skilled code test this out! You can use it to construct your individual EA!

How to Close Orders with MQL4 Code

Leave a Reply

Your email address will not be published. Required fields are marked *