check last profit - MQL5

 

I'm trying to use the following function to "see" if the last trade resulted in porfit or loss. The problem is: the function is returning "true" whether the profit is positive or not, that is, always returns true. I don't know if i'm using the wrong "get" functions or misunderstood how they work.


bool CalculateProfit()

{  
   datetime end = TimeCurrent();
   datetime start=end-5*PeriodSeconds(PERIOD_D1);
   HistorySelect(start,end);
   ulong ticket=  HistoryDealGetTicket(0);
   double profit = HistoryDealGetDouble(ticket,DEAL_PROFIT);  
   

if(profit > 0)
   {
      return true;
   }
     return false;     
}
 

Use the OnTradeTransaction - you need to catch the transaction - an exit from the market (DEAL_ENTRY_OUT):

//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
//--- get transaction type as enumeration value 
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      long     deal_entry        =0;
      string   deal_symbol       ="";
      long     deal_magic        =0;
      if(HistoryDealSelect(trans.deal))
        {
         deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);
         deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);
         deal_magic=HistoryDealGetInteger(trans.deal,DEAL_MAGIC);
        }
      else
         return;
      if(deal_symbol==Symbol() && deal_magic==m_magic)
         if(deal_entry==DEAL_ENTRY_OUT)
           {
            if(deal_profit>0)
              {
               ... profit > 0.0
              }
            else
              {
               ... profit < 0.0
              }
           }
     }
  }
 
Vladimir Karputov:

Use the OnTradeTransaction - you need to catch the transaction - an exit from the market (DEAL_ENTRY_OUT):


Thanks Vladimir, now the function is working perfectly (finally :D).
Reason: