How to Close a Trade by Ticket in MQL5?

Closing trades is a fundamental operation in automated trading systems. While closing by symbol is common, closing by ticket offers a more precise and reliable method, especially in complex trading scenarios. This article delves into how to close trades by ticket in MQL5, providing a comprehensive guide for intermediate and senior MQL5 developers.

Understanding Trade Tickets in MQL5

In MQL5, each trade is assigned a unique identifier called a ticket. This ticket acts as a primary key for the trade, ensuring that you can specifically target a particular trade for modification or closure. Unlike relying on order indexes or other dynamic properties, the ticket remains constant for the trade’s lifetime.

Why Close Trades Using Tickets?

Closing trades by ticket is preferable for several reasons:

  • Precision: It eliminates ambiguity, particularly when multiple trades are open on the same symbol.
  • Reliability: It remains consistent even if the order of trades changes due to market events or other EA operations.
  • Efficiency: In complex EAs, it simplifies trade management by providing a direct reference to the trade you intend to close.

The OrderCloseByTicket Function

MQL5 provides the OrderCloseByTicket function for precisely this purpose.

Syntax and Parameters of OrderCloseByTicket

The syntax for the OrderCloseByTicket function is as follows:

bool OrderCloseByTicket(ulong ticket, double volume, double price, int slippage, color arrow_color=clrNONE);

Where:

  • ticket (ulong): The ticket number of the trade to be closed.
  • volume (double): The volume to close (can be less than the initial volume for partial closures).
  • price (double): The price at which to close the trade. Usually Ask for buy orders and Bid for sell orders. Using 0 allows the terminal to use the current market price.
  • slippage (int): The maximum allowable slippage in points.
  • arrow_color (color): The color of the arrow displayed on the chart (optional).

Return Values and Error Handling

The function returns true if the close order was successfully placed; otherwise, it returns false. In case of failure, GetLastError() will return an error code, which should be checked for robust error handling.

Implementing OrderCloseByTicket in MQL5

Let’s look at how to use the OrderCloseByTicket function in practice.

Retrieving the Ticket Number of a Trade

Before closing a trade by ticket, you need to retrieve the ticket number. This is typically done during the initial trade placement or by iterating through open trades.

ulong ticket = OrderGetTicket(i);

Where i is an index within the OrdersTotal() loop.

Building a Function to Close a Trade by Ticket

Encapsulating the OrderCloseByTicket call within a function improves code readability and reusability.

bool CloseTradeByTicket(ulong ticket, double volume, int slippage)
{
   double price;
   ENUM_ORDER_TYPE orderType;

   if(!OrderSelectByTicket(ticket)) {
       Print("OrderSelectByTicket failed, error code = ", GetLastError());
       return false;
   }

   orderType = (ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE);

   if (orderType == ORDER_TYPE_BUY) {
       price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
   } else {
       price = SymbolInfoDouble(Symbol(), SYMBOL_ASK);
   }

   bool result = OrderCloseByTicket(ticket, volume, price, slippage);

   if (!result) {
       Print("OrderCloseByTicket failed, error code = ", GetLastError());
       return false;
   }

   return true;
}

Example Code: Closing a Trade with Error Checking

Here’s an example of how to use the CloseTradeByTicket function, including proper error checking.

void OnTick()
{
   ulong myTicket = 12345; // Replace with the actual ticket number
   double volumeToClose = 0.01;
   int slippage = 3;

   if (CloseTradeByTicket(myTicket, volumeToClose, slippage))
   {
      Print("Trade with ticket ", myTicket, " closed successfully.");
   }
   else
   {
      Print("Failed to close trade with ticket ", myTicket);
   }
}

Advanced Considerations and Best Practices

Handling Partial Closures

OrderCloseByTicket allows you to close only a portion of a trade by specifying a volume less than the original order volume. Ensure the volume is within acceptable limits, and handle potential errors arising from minimum volume requirements.

Dealing with Trade Context Errors

Ensure that the trade context is valid before attempting to close a trade. This includes checking for internet connectivity, account status, and market conditions. Use functions like IsTradeAllowed() to verify the context.

Asynchronous Execution and Event Handling

In scenarios involving multiple trades or complex logic, consider using asynchronous execution and event handling to prevent blocking the main thread. This can be achieved using custom events and timers.

Conclusion

Summary of Closing Trades by Ticket

Closing trades by ticket in MQL5 provides a precise, reliable, and efficient way to manage your trading operations. By understanding the OrderCloseByTicket function, its parameters, and potential errors, you can build robust and sophisticated trading systems.

Further Resources and Learning


Leave a Reply