Detecting the last profit/loss in transaction history reliably for a given magic number

 

Hi all,

I'm trying to detect the last profit/loss in the transaction history (which I think I've got right), but something unexpected is happening, hopefully someone will have an idea.

Here's the snippet:

void OnTradeTransaction(
   const MqlTradeTransaction&    trans,
   const MqlTradeRequest&        request,
   const MqlTradeResult&         result
   ) {
   
   CDealInfo      m_deal; 

   if(trans.type == TRADE_TRANSACTION_DEAL_ADD) {
      ResetLastError();
      if (HistoryDealSelect(trans.deal))
         m_deal.Ticket(trans.deal);
      else
         return;

      if (m_deal.DealType() == DEAL_TYPE_BUY || m_deal.DealType() == DEAL_TYPE_SELL) {
         if (m_deal.Entry() == DEAL_ENTRY_OUT) {
            if (m_deal.Profit() < 0 && m_deal.Magic() == EAMagic) {
               // set global var
               var = 1; // <-- this works reliably
               Print("Trade loss");
            }
            else if (m_deal.Profit() > 0 && m_deal.Magic() == EAMagic) {
               // set global var
               var = 0; // <-- *** execution is reaching this point at unexpected times zapping my var ***
               Print("Trade profit");
            }
         }
      }
   }
}

I've tried using the debugger to step through the code to figure out what is happening, but I'm not making much headway. Setting the var = 1 when a trade loses works perfectly. Conversely, when a trade ends in profit, the var = 0, which is fine, BUT, that line is being hit at unexpected times and I cannot figure out why. Probably something fundamental I'm missing in the way orders/deals/history/etc are processed.

All I'm trying to do basically is set a variable to be used in subsequent buy/sell trades when a trade ends in a loss.

Any guidance would be appreciated.

Thanks


Update: changed initial condition to TRADE_TRANSACTION_DEAL_ADD... I must have fiddled before posting this question.

Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
Documentation on MQL5: Constants, Enumerations and Structures / Environment State / Symbol Properties
  • www.mql5.com
Symbol Properties - Environment State - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
Ignore this question. I figured out the EA is using pending orders, which changes the logic.