You're reading...
EA development, MQL5

MQL5: Get P&L of last closed trade

A quick script illustrating how to get the P&L of the last closed trade with MQL5.


void OnStart(){

   //time interval of the trade history needed
   datetime timeEnd = TimeTradeServer(); //calculated server time (TimeCurrent() may not suffice for multi-currency logic)
   datetime timeStart = timeEnd - PeriodSeconds(PERIOD_D1); //use smaller period if logic does not need to look back so far as 1 day

   //cache trade history for the selected time interval
   HistorySelect(timeStart, timeEnd);

   //get number of deals between time_start and time_end
   int numberOfDeals = HistoryDealsTotal();

   //get ticket of last deal in the cached trade history
   ulong dealTicket = HistoryDealGetTicket(numberOfDeals - 1); //index starts from 0 so we need to minus 1 to get the last deal

   //print information
   if(dealTicket > 0){ //if a history deal has been successfully selected
      Print("P&L of last deal: ", HistoryDealGetDouble(dealTicket, DEAL_PROFIT));
   }
   else Print("Error obtaining last deal, error #", GetLastError());
}
   

 

Advertisement

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Archives

Visitors

Flag Counter
%d bloggers like this: