If you're looking to quickly access the details of your last closed trade in MetaTrader 5, you're in the right place! This guide will walk you through a straightforward code snippet that retrieves this information without the hassle of loops.
Getting Started
- First, you might want to create a variable to set the current day's start time, although this step isn't strictly necessary.
- It’s also a good idea to create additional variables to help with chart output, which can be useful in other parts of your code.
- By placing this code inside the OnTick(); function, you can display results for every tick. Alternatively, you can set it to run once per bar.
Code Example
// Variables string DayStart = "00:00"; // Day Start Time double LastClosed_Profit; // Last Closed trade profit string TradeSymbol, TradeType; // Expert Initializing -------------------- int OnInit() { return(INIT_SUCCEEDED); } // Expert DeInitializing ------------------- void OnDeinit(const int reason) { } // Expert OnTick -------------------------- void OnTick() { // Check for last closed trade. CheckLastClosed(); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ void CheckLastClosed() { datetime HistoryTime = StringToTime(DayStart); // History from "Day beginning to current time" if(HistorySelect(HistoryTime,TimeCurrent)) { int Total = HistoryDealsTotal(); // Get the last deal ticket number and select it for further work. ulong Ticket = HistoryDealGetTicket(Total -1); // Retrieve the necessary data. LastClosed_Profit = NormalizeDouble(HistoryDealGetDouble(Ticket,DEAL_PROFIT),2); TradeSymbol = HistoryOrderGetString(Ticket,ORDER_SYMBOL); // Identify a sell trade. if(HistoryDealGetInteger(Ticket,DEAL_TYPE) == DEAL_TYPE_BUY) { TradeType = "Sell Trade"; } // Identify a buy trade if(HistoryDealGetInteger(Ticket,DEAL_TYPE) == DEAL_TYPE_SELL) { TradeType = "Buy Trade"; } // Output to chart. Comment("\n","Deals Total - : ", Total, "\n","Last Deal Ticket - : ", Ticket, "\n", "Last Closed Profit -: ", LastClosed_Profit, "\n", "Last Trade was -: ", TradeType); } } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+
You can also retrieve the entire trading history from the very start of your account using the HistorySelect(); function like this:
// Get entire history HistorySelect(0,TimeCurrent());
Comments 0