How to Handle Deal Entry and Exit in MQL5?

Mastering deal entry and exit handling in MQL5 is crucial for developing robust and reliable trading algorithms. Deals represent the actual execution of orders and reflect the history of completed trades. Understanding how to accurately identify and analyze these deals is essential for precise backtesting, performance analysis, and advanced trading strategy implementation.

Understanding Deals vs. Orders vs. Positions

It’s important to differentiate between deals, orders, and positions. An order is a request to the broker to execute a trade. A deal is the actual execution of that order (or part of it). A position represents the net open exposure in a particular instrument. Multiple deals can contribute to a single position, and a single order can result in multiple deals (especially with partial fills).

Importance of Accurate Deal Handling

Incorrect deal handling can lead to inaccurate profit calculations, flawed backtesting results, and ultimately, poor trading decisions. Precisely identifying entry and exit points allows for correct calculation of profit/loss, risk-reward ratios, and other vital performance metrics.

Overview of Deal Properties in MQL5

Deals in MQL5 have a rich set of properties, accessible through various functions. These properties include the entry and exit reasons, timestamps, prices, volumes, associated order tickets, magic numbers, and comments. Leveraging these properties is key to effective deal analysis.

Identifying Deal Entry Points

Identifying deal entry points involves iterating through the trade history and filtering deals based on their DEAL_ENTRY property.

Using HistoryDealsTotal() and HistoryDealGetTicket()

These functions are fundamental for accessing historical deal data. HistoryDealsTotal() returns the total number of deals in the account history, while HistoryDealGetTicket() retrieves the ticket number of a deal at a specific index.

int totalDeals = HistoryDealsTotal();
for (int i = 0; i < totalDeals; i++)
{
   long ticket = HistoryDealGetTicket(i);
   if (ticket > 0)
   {
      // Process the deal with the given ticket
   }
}

Accessing Deal Properties with DealGetString(), DealGetInteger(), and DealGetDouble()

Once you have a deal ticket, you can access its properties using these functions. DealGetString() retrieves string properties (e.g., symbol, comment), DealGetInteger() retrieves integer properties (e.g., entry type, magic number), and DealGetDouble() retrieves double-precision floating-point properties (e.g., price, volume).

Filtering Deals Based on Entry Reason (DEAL_ENTRY)

The DEAL_ENTRY property is crucial for distinguishing entry deals from exit deals. Possible values include:

  • DEAL_ENTRY_IN – Entry deal
  • DEAL_ENTRY_OUT – Exit deal
  • DEAL_ENTRY_INOUT – Reversal deal (both entry and exit in one)
  • DEAL_ENTRY_NONE – No entry type

Examples of Identifying Entry Deals

long ticket = HistoryDealGetTicket(i);
if (ticket > 0)
{
   long entryType = DealGetInteger(ticket, DEAL_ENTRY);
   if (entryType == DEAL_ENTRY_IN)
   {
      double price = DealGetDouble(ticket, DEAL_PRICE);
      datetime time = (datetime)DealGetInteger(ticket, DEAL_TIME);
      // Process entry deal data (price, time, etc.)
      PrintFormat("Entry Deal: Ticket=%d, Time=%s, Price=%.5f", ticket, TimeToString(time), price);
   }
}

Identifying Deal Exit Points

Identifying deal exit points is similar to identifying entry points, but with a focus on DEAL_ENTRY_OUT.

Distinguishing Exit Deals from Entry Deals

Use the DEAL_ENTRY property to filter out entry deals, ensuring that you’re only analyzing exit transactions.

Filtering Deals Based on Exit Reason (DEAL_ENTRY)

Focus on deals where DealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_OUT.

Analyzing Exit Prices and Times

The exit price and time provide crucial information about the effectiveness of your trading strategy. Compare these values to the entry prices and times to calculate profit/loss and determine the duration of the trade.

Practical Scenarios: Identifying Stop Loss and Take Profit Exits

You can further refine your analysis by examining the DEAL_REASON property, which indicates the reason for the deal execution. Common reasons include:

  • DEAL_REASON_SL – Stop Loss
  • DEAL_REASON_TP – Take Profit
  • DEAL_REASON_MARKET – Market Execution (manual closure or by EA logic)
  • DEAL_REASON_EXPERT – Executed by an Expert Advisor
long dealReason = DealGetInteger(ticket, DEAL_REASON);
if (dealReason == DEAL_REASON_SL)
{
   Print("Stop Loss Exit");
}
else if (dealReason == DEAL_REASON_TP)
{
   Print("Take Profit Exit");
}

Working with Deal Properties: Practical Examples

Calculating Profit/Loss Based on Entry and Exit Deals

To calculate the profit or loss for a trade, you need to identify the corresponding entry and exit deals. The formula varies depending on the trade type (buy or sell).

double profit = DealGetDouble(exitTicket, DEAL_PROFIT);
PrintFormat("Profit/Loss: %.2f", profit);

Determining Deal Duration

The deal duration is the time elapsed between the entry and exit deals. This can be calculated by subtracting the entry time from the exit time.

datetime entryTime = (datetime)DealGetInteger(entryTicket, DEAL_TIME);
datetime exitTime = (datetime)DealGetInteger(exitTicket, DEAL_TIME);
int durationSeconds = exitTime - entryTime;
PrintFormat("Deal Duration: %d seconds", durationSeconds);

Identifying the Order Associated with a Deal

The DEAL_ORDER property links a deal to the order that initiated it. This is useful for tracing the origin of a deal and understanding the order parameters (e.g., stop loss, take profit).

long orderTicket = DealGetInteger(ticket, DEAL_ORDER);
PrintFormat("Associated Order Ticket: %d", orderTicket);

Analyzing Deal Context (Magic Number, Comment)

The magic number and comment associated with a deal provide valuable context about the trading strategy or Expert Advisor that generated the trade. These properties can be used to filter deals and analyze the performance of specific strategies.

long magicNumber = DealGetInteger(ticket, DEAL_MAGIC);
string comment = DealGetString(ticket, DEAL_COMMENT);
PrintFormat("Magic Number: %d, Comment: %s", magicNumber, comment);

Advanced Techniques and Considerations

Handling Partial Deal Closures

When an order is partially filled or closed in multiple steps, you’ll have multiple deals associated with a single position. You’ll need to aggregate the deal information to get a complete picture of the trade.

Dealing with Multiple Entry/Exit Points for a Single Position

Strategies like averaging in or scaling out can result in multiple entry and exit points for a single position. Your code needs to be able to handle these scenarios correctly, potentially by grouping deals based on a common identifier (e.g., the initial order ticket).

Error Handling and Data Validation

Always include error handling to gracefully manage unexpected situations, such as invalid deal tickets or missing deal properties. Validate the data retrieved from deal properties to ensure its consistency and accuracy.

Optimizing Deal Data Retrieval for Performance

Accessing historical deal data can be time-consuming, especially when dealing with large datasets. Optimize your code by minimizing the number of function calls and caching frequently accessed data. Consider using asynchronous operations for data retrieval to avoid blocking the main trading thread.

The differences between MQL4 and MQL5 are significant when it comes to dealing with history. MQL4 relies heavily on iterating through closed orders, while MQL5 offers more granular access to deal history with specific deal properties. MQL5’s object-oriented approach and its event handling capabilities greatly simplify complex trading strategy implementations and make deal analysis more robust.


Leave a Reply