Comprehensive Guide to Accessing and Analyzing Historical Orders and Deals in MetaTrader 5 with Python

Watch on YouTube: History Orders & Deals in MetaTrader 5 with Python (Part 1, Part 2, Part 3)

MetaTrader 5 (MT5) provides powerful tools to access historical trading data, which is crucial for analyzing past performance, fine-tuning strategies, and debugging algorithmic trading systems. Four key functions in this area are history_orders_total, history_orders_get, history_deals_total, and history_deals_get. This post will guide you through these functions and how to use them effectively with Python.

1. Counting Historical Orders (history_orders_total)

The history_orders_total function returns the total number of historical orders available in the account’s history. Historical orders encompass all orders that have been executed, canceled, or expired within a specified time frame and exclude any currently active orders. The function takes two arguments to specify the start date and end date.

*you may need to use the pytz module to prevent local time adjustments, as demonstrated in the Price Data chapter!

Example

import MetaTrader5 as mt5
# Initialize connection to MT5 (use your demo account credentials)
if not mt5.initialize(login=52021XXX, server="XXX-Demo", password="G3wt9SY&4wXXXX"):
    print("Failed to connect to MetaTrader 5, error code:", mt5.last_error())
    quit()
# get the number of orders in history
from datetime import datetime
from_date=datetime(2025,1,1)
to_date=datetime.now()
total_orders = mt5.history_orders_total(from_date, to_date)
print(f"Total historical orders: {total_orders}")

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

2. Retrieving Historical Orders (history_orders_get)

The history_orders_get function retrieves detailed information about historical orders. The function can accept a single parameter (either a ticket or position), but in most cases, you’ll want to analyze your orders within a specific time range.

Example

from datetime import datetime, timedelta
# Define the time range (last 7 days)
to_time = datetime.now()
from_time = to_time - timedelta(days=7)
# Retrieve historical orders
orders = mt5.history_orders_get(from_time, to_time)
if orders is None:
    print("Failed to retrieve historical orders, error code:", mt5.last_error())
else:
    print(f"Retrieved {len(orders)} historical orders:")
    for order in orders:
        print(order)  # Each order with detailed attributes

3. Counting Historical Deals (history_deals_total)

The history_deals_total function returns the total number of historical deals executed in the account. Deals refer to the actual trades that have been executed, as opposed to orders, which may or may not result in a trade. The function takes two arguments to specify the start date and end date.

Example

# Get the total number of historical deals
from datetime import datetime
from_date=datetime(2025,1,1)
to_date=datetime.now()
total_deals = mt5.history_deals_total(from_date, to_date)
print(f"Total historical deals: {total_deals}")

4. Retrieving Historical Deals (history_deals_get)

The history_deals_get function retrieves detailed information about historical deals. Similarly to history_orders_get, the function can accept a single parameter (either a ticket or position), but in most cases, you’ll want to track your deals within a specific time range. Deals include information such as the traded symbol, volume, execution price, and resulting profit.

Example

from datetime import datetime
from_date=datetime(2025,1,1)
to_date=datetime.now()
deals = mt5.history_deals_get(from_date, to_date)
if deals is None:
    print("Failed to retrieve historical deals, error code:", mt5.last_error())
else:
    print(f"Retrieved {len(deals)} historical deals:")
    for deal in deals:
        print(deal)  # Each deal with detailed attributes

Key Differences Between Orders and Deals

  • Orders:
    • Represent requests to trade, such as Buy or Sell orders.
    • Can be pending, executed, canceled, or expired.
  • Deals:
    • Represent the actual trades executed in the market as a result of orders placed.
    • Include execution details like price, volume, and resulting profit.

Conclusion

The historical orders and deals functions are essential for gaining insights into your trading activity and refining your strategies in MetaTrader 5. By utilizing these tools, you can analyze past trades, troubleshoot issues, and make informed, data-driven decisions to enhance your algorithmic trading performance.

In the next post, we’ll begin creating our first trading bot using MT5 and Python.

Next: MA Crossover Bot

Previous: Positions