How to Delete All Orders in MQL4?

This article provides a comprehensive guide on how to delete all orders in MQL4, covering essential concepts, practical code examples, and best practices for order management in MetaTrader 4.

Understanding Order Management in MQL4

The Role of Orders in MetaTrader 4

Orders are the core element of trading in MetaTrader 4. They represent instructions to buy or sell a financial instrument at a specified price. Managing these orders effectively is crucial for any automated trading system or manual trader using MQL4.

Order Types and Their Significance (Market, Pending)

  • Market Orders: Executed immediately at the current market price.
  • Pending Orders: Placed to be executed when the price reaches a specific level. Common types include:
    • Buy Stop
    • Sell Stop
    • Buy Limit
    • *Sell Limit

Understanding the difference is essential for tailoring your order deletion logic.

Essential MQL4 Functions for Order Handling (OrderSelect, OrderClose, OrderDelete)

The following functions are fundamental for order management:

  • OrderSelect(): Selects an order from the order pool based on its index or ticket number. It’s essential to select an order before performing any operation on it.
  • OrderClose(): Closes a market order or partially closes a pending order. It requires parameters such as the ticket number, lots, and price.
  • OrderDelete(): Deletes a pending order. Market orders cannot be deleted with OrderDelete; instead, they must be closed using OrderClose.

Methods for Deleting Orders in MQL4

Deleting Single Orders by Ticket Number

Deleting a single order using its ticket number is straightforward. First, select the order using OrderSelect and then use OrderClose (for market orders) or OrderDelete (for pending orders).

Deleting Orders Based on Order Type

You might need to delete orders based on their type (e.g., only pending orders). This requires iterating through all open orders and checking the OrderType() property.

Deleting Pending Orders (Buy Stop, Sell Stop, Buy Limit, Sell Limit)

Deleting only pending orders involves filtering orders based on OrderType() and then using OrderDelete() on the selected orders.

Implementing the ‘Delete All Orders’ Function

The function to delete all orders requires careful consideration of order types and error handling.

Iterating Through Open Orders

Use a loop that iterates from OrdersTotal() - 1 down to 0. This is because deleting an order changes the indices of subsequent orders.

Checking Order Properties Before Deletion (Symbol, Magic Number)

Before deleting an order, it’s often necessary to check its properties like OrderSymbol() (to delete orders only for the current symbol) and OrderMagicNumber() (to delete orders associated with a specific Expert Advisor).

Executing Order Deletion Using OrderClose or OrderDelete

Use OrderClose() for market orders and OrderDelete() for pending orders. Ensure you provide the correct parameters for each function.

Handling Errors During Order Deletion

Check the return values of OrderClose() and OrderDelete() to ensure the operation was successful. Use GetLastError() to get specific error codes and implement appropriate error handling.

Practical Code Examples and Considerations

Example Script: Deleting All Pending Orders for the Current Symbol

void DeleteAllPendingOrders() {
  for (int i = OrdersTotal() - 1; i >= 0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderSymbol() == Symbol() && OrderType() > OP_SELL) {
        if (!OrderDelete(OrderTicket())) {
          Print("Error deleting order #", OrderTicket(), ": ", GetLastError());
        }
      }
    }
  }
}

Example Script: Deleting All Orders with a Specific Magic Number

void DeleteOrdersByMagicNumber(int magic) {
  for (int i = OrdersTotal() - 1; i >= 0; i--) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
      if (OrderMagicNumber() == magic) {
        if (OrderType() > OP_SELL) {
          if (!OrderDelete(OrderTicket())) {
            Print("Error deleting order #", OrderTicket(), ": ", GetLastError());
          }
        } else {
          if (!OrderClose(OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_CLOSEPRICE), Slippage, Green)) {
            Print("Error closing order #", OrderTicket(), ": ", GetLastError());
          }
        }
      }
    }
  }
}

Important Considerations for Live Trading (Slippage, Confirmation)

  • Slippage: When closing market orders, slippage can occur, meaning the actual execution price may differ from the requested price. Account for this by setting an appropriate slippage value.
  • Confirmation: Consider implementing a confirmation mechanism to prevent accidental deletion of orders, especially in live trading environments.

Best Practices and Advanced Techniques

Using OrderSend Function with Specific Lots, Stop Loss and Take Profit

The OrderSend function is used to place new orders with parameters like lot size, stop loss, and take profit levels. While not directly related to deleting orders, understanding it is crucial for overall order management.

Implementing Order Modification Logic (OrderModify)

OrderModify allows you to change the properties of an existing order, such as stop loss, take profit, or price. It is an alternative to deleting and recreating orders when only minor adjustments are needed.

Event Handling for Order Deletion Events

MQL4 doesn’t natively support events for order deletion. You need to periodically check for order changes if you require real-time detection of order deletion. In MQL5, the OnTradeTransaction function allows you to respond to trading events, including order placement, modification, and deletion. This provides a more robust and event-driven approach to order management.


Leave a Reply