A Comprehensive Guide to Managing Orders with MetaTrader 5 and Python

Watch on YouTube: Working with Orders in MT5 Using Python (Part 1, Part 2, Part 3)

MetaTrader 5 (MT5) offers robust functionality for algorithmic trading, enabling traders to automate trading strategies with precision. In this post, we’ll dive into three essential functions that every MT5 programmer should know: orders_total, orders_get, and order_send. These functions allow you to monitor, retrieve, and place orders programmatically, forming the backbone of any automated trading system.

1. Counting Active Orders (orders_total)

The orders_total function provides the total number of active orders in the trading account. Active orders refer to pending orders (e.g., Buy Limit, Sell Limit, Buy Stop, and Sell Stop) that are yet to be executed.

Usage

This function is useful for:

  • Monitoring how many pending orders are currently in place.
  • Ensuring your strategy adheres to specific constraints (e.g., a maximum number of open orders).

Example

# Get the total number of orders
import MetaTrader5 as mt5
# Initialize connection to MT5 (use your demo account credentials)
if not mt5.initialize(login=52021XXX, server="XXX-Demo", password="G3wt9SY&XXX"):
    print("Failed to connect to MetaTrader 5, error code:", mt5.last_error())
    quit()
total_orders = mt5.orders_total()
print(f"Total pending orders: {total_orders}")

This function returns an integer representing the number of active pending orders.

For the following examples, we will assume that the MetaTrader5 package has been imported and the connection has been successfully initialized.

2. Retrieving Details of Active Orders (orders_get)

The orders_get function retrieves detailed information about the active orders. Returns info in the form of a tuple structure (namedtuple) containing the attributes of a specific order.

Usage

This function is essential for:

  • Fetching specific details about pending orders, such as price, symbol, volume, or expiration.
  • Filtering orders based on custom criteria for advanced strategy logic.

Example

# Retrieve all pending orders
orders = mt5.orders_get()
if orders is None:
    print("Failed to retrieve the orders, error code:", mt5.last_error())
else:
    print(f"Retrieved {len(orders)} orders:")
    for order in orders:
        print(order)  # Each order is a dictionary with detailed attributes

Filtering Example

You can filter orders for a specific symbol. For example, you can retrieve symbols that include “EUR” in their names by using the asterisk symbol ("*EUR*").

orders = mt5.orders_get(group="*EUR*")
if orders:
    print(f"Pending orders for symbols containing EUR in their names: {len(orders)}")

3. Placing Orders (order_send)

The order_send function is used to place, modify, and delete orders. It’s a cornerstone function for executing trades programmatically. The function syntax is order_send(request). If you’re familiar with MQL5, you likely know how the MQLTradeRequest and MQLTradeResult structures function. These same structures are utilized when working with Python.

The request parameter represents MqlTradeRequest trading structure, defining the order instructions. The function’s execution result is stored in the MqlTradeResult structure, providing details about the success or failure of the order placement.

Usage

This function is used for:

  • Entering the market with Buy/Sell orders.
  • Placing pending orders, modifying and closing positions.
  • Automating trade execution based on strategy signals.

Example

request = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": "EURUSD",
"volume": 0.1,
"type": mt5.ORDER_TYPE_BUY,
"price": mt5.symbol_info_tick("EURUSD").ask,
"sl": 1.01,  # adjust according to current market prices
"tp": 1.05,  # adjust according to current market prices
"deviation": 10,
"magic": 101,
"comment": "python script open",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": mt5.ORDER_FILLING_IOC # check the Filling method in the symbols specs
} 
# send a trading request
result = mt5.order_send(request)
# check the execution result (retcode 10009 = TRADE_RETCODE_DONE)
print("Order_send result: Return_Code: {}, Open Price: {}, Volume: {}".format(result.retcode, result.price, result.volume));

When placing an order, ensure you specify the correct filling method in the request (type_filling). You can find this information by right-clicking on the symbol name in the MarketWatch and selecting “Specification.” In the example above, we used “type_filling”: mt5.ORDER_FILLING_IOC.

Modifying Orders

As previously mentioned, the order_send function can also be used to modify or delete existing orders (positions). In this example, we’ll take the Buy position we just opened (its ticket) and update its Take Profit (TP) price. Be sure to adjust the code as needed to align with current market conditions.

request = {
"action": mt5.TRADE_ACTION_SLTP,
"symbol": "EURUSD",
"sl": 1.01,
"tp": 1.0466,
"position": 888983450  # provide order (position) ticket number
} 
# send a trading request
result = mt5.order_send(request)
# check the execution result (retcode 10009 = TRADE_RETCODE_DONE)
print("Order_send result: Ret_Code: {}".format(result.retcode));

Similarly, you can utilize the request/result structures to cancel orders and close positions.

Conclusion

Understanding and effectively using orders_total, orders_get, and order_send are essential for developing robust automated trading strategies in MetaTrader 5. These functions give you full control over monitoring, retrieving, and placing orders, enabling precise implementation of even the most complex trading algorithms.

In the next post, we’ll explore how to retrieve position data. Stay tuned to level up your algorithmic trading skills with Python and MetaTrader 5!

Next: Positions

Previous: Price Data

Watch on YouTube: Working with Orders in MT5 Using Python (Part 1 / Part 2 / Part 3)