Close Orders with MQL4 Using OrderClose

OrderClose() is a function in the MQL4 language used to close orders, in this guide you can see how it works.

In other guides, we saw how to open new market orders and how to scan the account for open orders. To close the cycle, we also need to learn how to close orders with the function OrderClose().

At this point, the order could be a winner, loser or breakeven, but we only want to see how to close the order using MQL4 code.

MQL4 OrderClose() Function

OrderClose() is the MQL4 function that allows you to close open market orders entirely or partially. This function requires a few parameters — you can see them in the following specification:

bool OrderClose( 
        int     ticket,             //ticket 
        double  lots,               //volume 
        double  price,              //close price 
        int     slippage,           //slippage 
        color   arrow_color=clrNONE //color 
);
 

The parameters expected are (bold are the required ones):

  • ticket to specify the ticket number that identifies which order to close.
  • lots is the size in lots to close. For example if order #1234 is a BUY order of 1 lot of EUR/USD, you can close the entire position, specifying 1 lot. Or you can close it partially, for example 0.6 lots; the remaining 0.4 lots will remain open.
  • price is the closing price. Must be the current Bid price for closing a BUY order or the current Ask price for closing a SELL order.
  • slippage is the allowed difference between the requested close price and the one actually on the broker's side.
  • arrow_color is the color of the arrow to draw on the chart at the time/price of the closed order.

Close Orders Using MQL4 OrderClose()

We can now apply what we learned in other articles about MQL4 coding to close orders.

Usually orders are closed manually or during the process of order management of an EA.

In our example we will scan for orders and close all of them. With some more advanced coding, you will be able to be more selective and choose which orders to close, but for the moment we will keep it simple.

Most of the information necessary to close an order can be retrieved easily by selecting the order. This is why the scan for the orders is so useful.

When you use the OrderSelect() function, many details about the order can be retrieved with native MQL4 functions, in particular:

  • OrderTicket() returns the ticket number of the order.
  • OrderLots() returns the position size of the order.

The above are the strictly necessary properties, however, there are more functions to retrieve even more details about the order. You will learn about them in other guides.

The function CloseOrder() is of type boolean. It returns true if the order is successfully closed and false if the order is not closed due to some error.

Close Orders Using MQL4 OrderClose() Example

We can see an example of script that closes all of the open market orders.

#property copyright "EarnForex.com"
#property link      "https://www.earnforex.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 order, 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 the order.
      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 correctly, 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 use a delay if the execution is too fast. Sleep() will wait X milliseconds before proceeding with the code.
      // Sleep(300);
   }
   // If the loop finishes, it means there are no more open orders for the trading account.
   return(TotalClose);
}

void OnStart()
{
   Print("How many orders have been closed? ",CloseOpenOrders());
}
 

If we run the script in any chart, it will close all the orders, not limited to the currency pair in the chart:

Before:

Before Running OrderClose Script on Entire Account

After:

After Running OrderClose Script on Entire Account

Applying Your Knowledge of MQL4 OrderClose() Function

Applying more filters we could restrict the selection of the orders and close only specific ones.

With this guide, you learned how to close an order with MQL4 language. You can now do some experiment and test it yourself.

I remember when I first started to learn MQL coding, even though I knew a lot about coding, many of the concept were still unclear.

The best way to learn MQL4 coding is by looking at the well-commented code of existing expert advisors or indicators and by attempting to modify them to your liking.

You can save hours of research and coding by downloading our MT4 Expert Advisor Template, which contains some professional code. You can use it to build your own EA!


If you want to get news of the most recent updates to our guides or anything else related to Forex trading, you can subscribe to our monthly newsletter.

© 2005–2021

EarnForex.com

Design — Mart Studio

Forex trading bears intrinsic risks of loss. You must understand that Forex trading, while potentially profitable, can make you lose your money. Never trade with the money that you cannot afford to lose! Trading with leverage can wipe your account even faster.

CFDs are leveraged products and as such loses may be more than the initial invested capital. Trading in CFDs carry a high level of risk thus may not be appropriate for all investors.