Introduction to Retrieving Last Deal’s Profit in MQL5
Brief Overview of MQL5 and its Capabilities
MQL5, the programming language for MetaTrader 5, provides powerful tools for algorithmic trading. It allows developers to create Expert Advisors (EAs), custom indicators, and scripts to automate trading strategies. MQL5’s capabilities extend beyond simple order execution, offering access to historical data, real-time market information, and comprehensive trade management functions.
Importance of Accessing Deal Profit in Trading Strategies
Accessing the last deal’s profit is crucial for various trading strategies. It allows for dynamic risk management, performance tracking, and adaptive strategy adjustments. For instance, a strategy might adjust its position size based on the profit or loss of the previous trade. Moreover, analyzing the last deal’s outcome can provide insights into the strategy’s recent performance and inform decisions about its continued use or modification.
Article Objectives: Focusing on Practical Implementation
This article aims to provide a practical guide to retrieving the last deal’s profit in MQL5. We will cover the necessary functions, code implementation, and considerations for different account types. The goal is to equip you with the knowledge and code snippets to integrate this functionality into your own trading strategies.
Understanding Deal Properties in MQL5
Explanation of Deal Tickets and Their Significance
In MQL5, each deal is assigned a unique ticket number. This ticket acts as a primary key for identifying and accessing specific deal properties. Deal tickets are essential for retrieving information about individual trades from the account history.
Key Deal Properties Related to Profit: DEALPROFIT, DEALCOMMISSION, DEAL_SWAP
Several deal properties are relevant when calculating the overall profit of a trade:
DEAL_PROFIT: The actual profit or loss from the trade, excluding commission and swap.DEAL_COMMISSION: The commission charged for the trade.DEAL_SWAP: The swap charges (rollover interest) applied to the trade.
To get the net profit, you would typically sum DEAL_PROFIT, subtract DEAL_COMMISSION, and subtract DEAL_SWAP.
Using DealGetString, DealGetDouble, and DealGetInteger Functions
MQL5 provides functions to access deal properties based on their data type:
DealGetString(ulong ticket, ENUM_DEAL_PROPERTY_STRING prop_id, string& value): Retrieves string properties.DealGetDouble(ulong ticket, ENUM_DEAL_PROPERTY_DOUBLE prop_id, double& value): Retrieves double properties (like profit, commission, and swap).DealGetInteger(ulong ticket, ENUM_DEAL_PROPERTY_INTEGER prop_id, long& value): Retrieves integer properties.
For accessing profit-related properties, DealGetDouble is typically used. For retrieving the deal ticket, HistoryDealGetTicket is used, after the deal is identified via HistorySelect. Other helpful deal properties are DEAL_TIME (deal execution time) and DEAL_TYPE (deal type like buy or sell).
Methods to Identify and Access the Last Deal
Iterating Through History Deals Using HistorySelect and HistoryDealGetTicket
The primary method involves iterating through the account history using the HistorySelect function, which selects deals within a specified time range. After selecting the history, use HistoryDealGetTicket(int index) to get the ticket number of the deal at the specified index in the history. It is more efficient to select only today’s trades, as last deal should be among them.
Sorting Deals by Time (DEAL_TIME) to Find the Last One
Since the deal history is not guaranteed to be sorted by time, you need to manually sort it. You can store the deal tickets and their timestamps in an array and then sort the array by timestamp. The last element in the sorted array will represent the last deal. Another option is to iterate the HistoryDealsTotal() deals count and keep track of the most recent deal encountered. This is most likely better from a performance perspective.
Considerations for Different Account Types (Hedging vs. Netting)
Hedging accounts allow multiple positions for the same symbol in opposite directions. In this case, the ‘last deal’ might not directly correlate with the ‘last closed position’. You’ll need to filter by DEAL_ENTRY (entry type) property to ensure you’re considering closing deals (DEAL_ENTRY_OUT).
Netting accounts consolidate positions, so the last deal typically reflects the net position change. The DEAL_ENTRY property might be less critical in this scenario.
Code Implementation: Retrieving and Displaying Last Deal’s Profit
Step-by-Step Guide to Writing an MQL5 Script or EA
- Create a new MQL5 script or EA in MetaEditor.
- Include the necessary header files.
- Use
HistorySelectto select deals from the account history. - Iterate through the selected deals using a loop.
- Identify the last deal based on its timestamp.
- Retrieve the profit, commission, and swap values using
DealGetDouble. - Display the retrieved values using
PrintorCommentfunctions.
Code Snippets: HistorySelect, Looping, and Accessing Profit
Here’s a code snippet illustrating the key steps:
#property script_title "Last Deal Profit"
void OnStart()
{
datetime lastDealTime = 0;
ulong lastDealTicket = 0;
double lastDealProfit = 0;
double lastDealCommission = 0;
double lastDealSwap = 0;
// Select history for the current trading day
datetime today = TimeCurrent();
datetime startOfDay = StrToTime(TimeToString(today, TIME_DATE) + " 00:00:00");
bool historySelected = HistorySelect(startOfDay, today);
if(historySelected)
{
int dealsTotal = HistoryDealsTotal();
for(int i = 0; i < dealsTotal; i++)
{
ulong ticket = HistoryDealGetTicket(i);
datetime dealTime;
double dealProfit, dealCommission, dealSwap;
if(ticket > 0 &&
DealGetInteger(ticket, DEAL_TIME, dealTime) &&
DealGetDouble(ticket, DEAL_PROFIT, dealProfit) &&
DealGetDouble(ticket, DEAL_COMMISSION, dealCommission) &&
DealGetDouble(ticket, DEAL_SWAP, dealSwap))
{
if (dealTime >= lastDealTime)
{
lastDealTime = dealTime;
lastDealTicket = ticket;
lastDealProfit = dealProfit;
lastDealCommission = dealCommission;
lastDealSwap = dealSwap;
}
}
}
if(lastDealTicket > 0)
{
Print("Last Deal Ticket: ", lastDealTicket);
Print("Last Deal Profit: ", lastDealProfit);
Print("Last Deal Commission: ", lastDealCommission);
Print("Last Deal Swap: ", lastDealSwap);
Print("Last Deal time: ", TimeToString(lastDealTime));
} else {
Print("No deals found today.");
}
} else {
Print("HistorySelect failed: ", GetLastError());
}
}
Error Handling and Validation of Deal Properties
Always include error handling to ensure the code functions correctly. Check the return values of HistorySelect and DealGetDouble to handle potential errors. Also, validate the deal ticket before accessing its properties to prevent unexpected behavior. Implement checks to make sure ticket > 0 before calling DealGetDouble.
Example: Displaying Profit, Commission, and Swap of the Last Deal
The code snippet above already demonstrates how to display the profit, commission, and swap of the last deal using the Print function. These values can also be displayed on the chart using the Comment function or stored in global variables for use in other parts of your EA.
Practical Applications and Considerations
Using the Retrieved Profit for Strategy Optimization
The retrieved profit can be used to dynamically adjust parameters in your trading strategy. For example, you can increase the position size after a profitable trade or reduce it after a losing trade. This allows for adaptive risk management based on recent performance.
Potential Issues and Limitations (e.g., Deal History Availability)
- History Availability: The deal history might not be available for all time periods, especially on demo accounts or after account resets. Ensure that the required history is available before running your script or EA.
- Data Accuracy: While unlikely, ensure the integrity of data fetched using provided functions is handled. Use basic mathematical checks to avoid obvious anomalies.
- Time Zones: Account for potential time zone differences between the broker’s server time and your local time when selecting the deal history.
Advanced Techniques: Combining Last Deal Profit with Other Indicators
You can combine the last deal’s profit with other technical indicators to create more sophisticated trading strategies. For example, you can use the profit as a confirmation signal for a trend-following indicator. If the last trade was profitable and the indicator signals a buy, it might be a stronger indication to enter a long position.
Conclusion and Further Learning Resources
Retrieving the last deal’s profit in MQL5 is a valuable technique for developing adaptive and performance-driven trading strategies. This article has provided a comprehensive guide to accessing and utilizing this information.
For further learning, refer to the MQL5 Reference documentation, the MQL5 community forum, and online tutorials on MQL5 programming.