How to Access the Last Trade Result in MQL5?

Introduction to Last Trade Results in MQL5

In MQL5, accessing the last trade’s result is crucial for refining trading strategies, managing risk, and making informed decisions. Knowing the outcome of your previous trade allows your Expert Advisor (EA) to adapt dynamically, for example, by adjusting position sizes, modifying take-profit levels, or even altering the underlying trading logic.

Importance of accessing last trade results for trading strategies

  • Dynamic Strategy Adjustment: Allows EAs to react to market conditions and previous trade outcomes.
  • Risk Management: Enables the implementation of sophisticated risk management techniques based on previous trade performance.
  • Performance Analysis: Facilitates in-depth analysis of trading strategy effectiveness.

Overview of trade properties in MQL5

MQL5 provides comprehensive functions for accessing trade properties, allowing you to retrieve virtually any detail about a past trade. These properties include the trade’s ticket number, profit, volume, entry price, exit price, trade type (buy or sell), and more.

Methods for Accessing the Last Trade

There are several methods to access the last trade in MQL5. A common and efficient approach involves iterating through the trade history and identifying the most recent closed trade.

Using HistorySelect() to access trade history

Instead of OrderSelect(), MQL5 primarily utilizes history functions. To access the trade history, we use HistorySelect(). This function selects a date range from the account history.

bool HistorySelect(datetime start_time, datetime end_time);

Iterating through trade history

After selecting the relevant trade history, you can iterate through it using HistoryDealsTotal() and HistoryDealGetTicket() to find the last trade.

int totalDeals = HistoryDealsTotal();
long lastDealTicket = 0;

for (int i = totalDeals - 1; i >= 0; i--)
{
   long dealTicket = HistoryDealGetTicket(i);
   if (dealTicket > 0) {
      lastDealTicket = dealTicket;
      break; // Found the last deal, exit the loop
   }
}

if (lastDealTicket > 0)
{
   // Process the last trade using the deal ticket
   Print("Last Deal Ticket: ", lastDealTicket);
}
else
{
   Print("No deals found in history.");
}

Retrieving Specific Trade Properties

Once you have the ticket number of the last trade, you can use the HistoryDealGetString(), HistoryDealGetInteger(), and HistoryDealGetDouble() functions to retrieve specific properties.

Accessing trade properties with HistoryDealGetString(), HistoryDealGetInteger(), and HistoryDealGetDouble()

These functions allow you to access string, integer, and double-precision floating-point properties of the trade, respectively.

Common trade properties to retrieve (ticket number, profit, volume, etc.)

  • DEAL_TICKET: The unique identifier for the trade.
  • DEAL_PROFIT: The profit or loss of the trade.
  • DEAL_VOLUME: The volume of the trade.
  • DEAL_TIME: The timestamp of the trade.
  • DEAL_TYPE: The type of the trade (buy or sell).
  • DEAL_ENTRY: The entry type of the deal (in, out, inout).

Practical Examples and Code Snippets

Example 1: Retrieving the profit of the last closed trade

double GetLastTradeProfit()
{
   double lastTradeProfit = 0.0;
   int totalDeals = HistoryDealsTotal();

   for (int i = totalDeals - 1; i >= 0; i--)
   {
      long dealTicket = HistoryDealGetTicket(i);
      if (dealTicket > 0)
      {
         lastTradeProfit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
         break;
      }
   }

   return lastTradeProfit;
}

Example 2: Checking the trade direction (buy or sell) of the last order

enum ENUM_DEAL_TYPE GetLastTradeType()
{
   ENUM_DEAL_TYPE lastTradeType = WRONG_VALUE; // Default value indicating no trade found
   int totalDeals = HistoryDealsTotal();

   for (int i = totalDeals - 1; i >= 0; i--)
   {
      long dealTicket = HistoryDealGetTicket(i);
      if (dealTicket > 0)
      {
         lastTradeType = (ENUM_DEAL_TYPE)(int)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
         break;
      }
   }

   return lastTradeType;
}

Example 3: Getting the entry price of the last trade

This example is a little trickier, as the entry price is associated with the order, not the deal. Therefore, you’ll need the order ticket associated with the last deal.

double GetLastTradeEntryPrice()
{
    double lastTradeEntryPrice = 0.0;
    int totalDeals = HistoryDealsTotal();

    for (int i = totalDeals - 1; i >= 0; i--)
    {
        long dealTicket = HistoryDealGetTicket(i);
        if (dealTicket > 0)
        {
            long orderTicket = HistoryDealGetInteger(dealTicket, DEAL_ORDER);

            // Now you need to get the order properties
            if (orderTicket > 0) {
                if (HistoryOrderSelect(orderTicket)) {
                    lastTradeEntryPrice = HistoryOrderGetDouble(orderTicket, ORDER_PRICE_OPEN);
                    break;
                }
            }
        }
    }

    return lastTradeEntryPrice;
}

Error Handling and Considerations

Handling cases where no trades exist

Always check if the trade history contains any trades before attempting to access them. This prevents errors when the EA is first started or when no trades have been executed yet.

Understanding return values and error codes

Pay attention to the return values of the history functions. A return value of false often indicates an error. Use GetLastError() to retrieve the specific error code and handle it accordingly.

Performance considerations when accessing trade history

Accessing trade history repeatedly can impact performance, especially when dealing with large datasets. Cache frequently accessed data to minimize the number of history function calls. Use HistorySelect() wisely by specifying a reasonable date range.


Leave a Reply