Code snippet to calculate profit in MQL5 using OnTradeTransaction callback

 

Apologies for inappropriate formatting. If I attempt to format the code in code block, a big block shows up. If use HTML button on RHS, entire typed text disappears...

First of all, we need a global variable to hold the profit's calculation. 


In case you are tracking multiple EA's at once you may also need to use mutexes. 
double g_ProfitLoss = 0; 

It is always a good idea to initialize all the global variables in OnInit 

int OnInit()
{
// ... your custom code ... 
   g_ProfitLoss = 0; 
// ... your custom code ... 
}
void OnTradeTransaction(
   const MqlTradeTransaction &trans,
   const MqlTradeRequest &request,
   const MqlTradeResult &result
) {
   //--- if transaction is result of addition of the transaction in history
   if (trans.type == TRADE_TRANSACTION_DEAL_ADD)
   {
      long     deal_magic = 0;
      double   deal_profit       =0.0;
      string   deal_symbol       ="";
      ENUM_DEAL_ENTRY deal_entry = 0;

      if (HistoryDealSelect(trans.deal))
      {
         deal_entry   = HistoryDealGetInteger(trans.deal, DEAL_ENTRY  );
         deal_magic   = HistoryDealGetInteger(trans.deal, DEAL_MAGIC  );
         deal_profit  = HistoryDealGetDouble (trans.deal, DEAL_PROFIT );
         deal_symbol  = HistoryDealGetString (trans.deal, DEAL_SYMBOL );

         if ((deal_symbol == Symbol()) && (deal_magic == paramMagicNumber))
         {
            if (deal_entry == DEAL_ENTRY_OUT)
               g_ProfitLoss += deal_profit;
         }
      }
   }
} 

Any Comments / observation shedding light upon the flaw in logic invited.

Improperly formatted code edited by moderator.

 

Thank you!

it work for me

Thank you!

it work for me

 
cdjindia:

Apologies for inappropriate formatting. If I attempt to format the code in code block, a big block shows up. If use HTML button on RHS, entire typed text disappears...

First of all, we need a global variable to hold the profit's calculation. 


In case you are tracking multiple EA's at once you may also need to use mutexes. 

It is always a good idea to initialize all the global variables in OnInit 

Any Comments / observation shedding light upon the flaw in logic invited.

Very simple and helpful solution. Thank you for posting.