How to Get Trade History in MQL5?

Introduction to Trade History in MQL5

Importance of Trade History Analysis

Trade history is the bedrock of informed trading decisions. By analyzing past trades, you can identify patterns, evaluate strategy performance, and refine your trading approach. Comprehensive trade history analysis allows you to understand profitability, risk exposure, and the overall effectiveness of your trading system. This is crucial for continuous improvement and adapting to changing market conditions.

Overview of MQL5 Trade History Functions

MQL5 provides a robust set of functions for accessing and manipulating trade history. These functions allow you to retrieve trades within a specific date range, iterate through deals, and extract detailed information about each transaction. The primary functions include HistorySelect(), HistoryDealsTotal(), HistoryDealGetTicket(), and functions to get deal properties like HistoryDealGetDouble(), HistoryDealGetInteger(), and HistoryDealGetString(). These functions offer fine-grained control over how you access and process trade data. Unlike MQL4, MQL5 neatly separates orders, deals, and positions, offering more clarity and flexibility when analyzing trading activity.

Accessing Trade History Using HistorySelect()

Understanding HistorySelect() Parameters

The HistorySelect() function is the cornerstone of retrieving trade history in MQL5. It takes two parameters: the start date and the end date. These parameters define the period from which you want to retrieve trade data. Dates are specified as datetime values, representing the number of seconds since January 1, 1970. Successful execution of HistorySelect() populates the trade history accessible through other history functions.

Selecting Trades Within a Specific Date Range

To retrieve trades from a specific date range, you need to convert the dates into datetime format. For example, to retrieve all trades from January 1, 2023, to January 31, 2023, you would use the following code:

datetime start_date = StringToTime("2023.01.01 00:00");
datetime end_date = StringToTime("2023.01.31 23:59");

bool selected = HistorySelect(start_date, end_date);

if(selected)
  Print("Trade history selected successfully");
else
  Print("Failed to select trade history. Error code: ", GetLastError());

Practical Examples of HistorySelect() Usage

Here’s a more complete example demonstrating how to use HistorySelect() to retrieve trades from the last month:

datetime end_date = TimeCurrent();
datetime start_date = end_date - PeriodSeconds(PERIOD_MN1); // One month ago

bool selected = HistorySelect(start_date, end_date);

if(selected)
{
  int deals_total = HistoryDealsTotal();
  Print("Total deals in the last month: ", deals_total);
}
else
  Print("Failed to select trade history. Error code: ", GetLastError());

Iterating Through Trade History

Using HistoryDealsTotal() and HistoryDealGetTicket()

After successfully selecting the trade history, you can iterate through the deals using HistoryDealsTotal() to get the total number of deals and HistoryDealGetTicket() to retrieve the ticket number of each deal.

int deals_total = HistoryDealsTotal();

for(int i = 0; i < deals_total; i++)
{
  ulong ticket = HistoryDealGetTicket(i);
  if(ticket > 0)
  {
    // Process the deal with the given ticket
    Print("Deal Ticket: ", ticket);
  }
  else
  {
    Print("Error getting deal ticket at index ", i, ". Error code: ", GetLastError());
  }
}

Accessing Individual Deal Properties via HistoryDealGetDouble(), HistoryDealGetInteger(), HistoryDealGetString()

Once you have the deal ticket, you can access its properties using functions like HistoryDealGetDouble(), HistoryDealGetInteger(), and HistoryDealGetString(). These functions allow you to retrieve information such as the deal’s price, volume, type, and symbol.

double price = HistoryDealGetDouble(ticket, DEAL_PRICE);
long type = HistoryDealGetInteger(ticket, DEAL_TYPE);
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);

Print("Price: ", price, ", Type: ", type, ", Symbol: ", symbol);

Example: Calculating Total Profit from Trade History

Here’s an example of calculating the total profit from the selected trade history:

double total_profit = 0.0;

int deals_total = HistoryDealsTotal();

for(int i = 0; i < deals_total; i++)
{
  ulong ticket = HistoryDealGetTicket(i);
  if(ticket > 0)
  {
    double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
    total_profit += profit;
  }
}

Print("Total Profit: ", total_profit);

Filtering and Analyzing Trade History

Filtering Trades by Symbol, Magic Number, and Order Type

You can filter trades based on various criteria, such as symbol, magic number (used to identify trades opened by a specific EA), and order type. This allows you to isolate and analyze specific subsets of your trading activity.

string target_symbol = "EURUSD";
int target_magic_number = 12345;

int deals_total = HistoryDealsTotal();

for(int i = 0; i < deals_total; i++)
{
  ulong ticket = HistoryDealGetTicket(i);
  if(ticket > 0)
  {
    string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
    int magic_number = (int)HistoryDealGetInteger(ticket, DEAL_MAGIC);

    if(symbol == target_symbol && magic_number == target_magic_number)
    {
      // Process the deal for the specified symbol and magic number
      double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
      Print("Deal Ticket: ", ticket, ", Profit: ", profit);
    }
  }
}

Calculating Performance Metrics from Trade History Data

Trade history data can be used to calculate various performance metrics, such as win rate, average profit per trade, maximum drawdown, and profit factor. These metrics provide insights into the effectiveness of your trading strategies.

Using Arrays to Store and Process Trade Data

For more complex analysis, you can store trade data in arrays. This allows you to perform calculations and generate reports more efficiently. Dynamic arrays can be particularly useful when the number of trades is unknown beforehand.

Practical Applications and Examples

Creating a Simple Trade History Report

A simple trade history report can be generated by iterating through the deals and printing relevant information to the Experts log. This can include the ticket number, symbol, type, volume, price, and profit for each deal.

Developing a Custom Trade Analysis Tool

By leveraging the MQL5 trade history functions, you can develop custom tools for analyzing your trading performance. These tools can provide advanced features such as charting of profit and loss over time, calculation of risk-adjusted returns, and identification of trading patterns.

Debugging and Troubleshooting Trade History Access

If you encounter issues accessing trade history, check the return values of the MQL5 functions and use GetLastError() to retrieve error codes. Common issues include incorrect date ranges, invalid deal tickets, and insufficient history data. Ensuring that the correct symbol is selected in the strategy tester is also important for backtesting scenarios. Remember that trade history is only available for the account currently active in the terminal.


Leave a Reply