Help me calculate history profit

 

I want to calculate a history profit on OnDeInit event handler. This function only runs when backtesting the strategy. My code looks like this,

void CStrategy::OnDeInitEvent(string& SymbolArray[], int numberOfTradeableSymbols, TRADE_DIRECTION TradeDirection) {
   if(MQLInfoInteger(MQL_TESTER)) {
      for(int SymbolLoop=0; SymbolLoop < numberOfTradeableSymbols; SymbolLoop++) {
         string CurrentSymbol = SymbolArray[SymbolLoop];
         TesterTotalProfit[SymbolLoop] = HistoryProfit(CurrentSymbol, TradeDirection);
         Print(">>>>> Currency: ", CurrentSymbol, " ", EnumToString(TradeDirection), ", Total Profit = ", TesterTotalProfit[SymbolLoop]);
      }
   }
}

//+------------------------------------------------------------------+
// Calculate history profit ------------------------------------------------------------------------------------------+ //
double CStrategy::HistoryProfit(string symb, TRADE_DIRECTION TradeDirection) {
   double result = 0;

   if(HistorySelect(0, TimeCurrent())) {
      for(int i = HistoryDealsTotal() - 1; i >= 0; i--) {
         ulong Ticket = HistoryDealGetTicket(i);
         if(HistoryDealGetString(Ticket, DEAL_SYMBOL) == symb)
            if(HistoryDealGetInteger(Ticket, DEAL_MAGIC) == GlobalExpertID(symb, InpTradeTimeframe, InpMagicNumber)) {

               ENUM_DEAL_TYPE dealType = 0;
               if(TradeDirection == LONG_ONLY)
                  dealType = DEAL_TYPE_BUY;
               if(TradeDirection == SHORT_ONLY)
                  dealType = DEAL_TYPE_SELL;

               if(HistoryDealGetInteger(Ticket, DEAL_TYPE) == dealType) {
                  double  profit = HistoryDealGetDouble(Ticket, DEAL_PROFIT);
                  //Print("profit: ", profit);
                  double  swap   = HistoryDealGetDouble(Ticket, DEAL_SWAP);
                  //Print("swap: ", swap);
                  double  commission = HistoryDealGetDouble(Ticket, DEAL_COMMISSION);
                  //Print("commission: ", commission);
                  result +=  profit + swap + commission;
               }
            }
      }
   }
   return(result);
}

For some reason it returns 0 for all of the currency. Anyone knows where the problem is?

 

1. One thing I see here is you think deal type corresponds to position type. This is not true...

A position consists of two deals: (in deal and out deal).

2. The profit you are looking for is saved in out deal and not in deal.
 
I just delete the dealType variable and it still return 0
 
I found that the magic number filter is the culprit. I do print statement before and after magic number filter and it shows after magic number filter the profit always 0. Any clue why this happened?
 
Just fix the problem. Apparently when using CTrade to close a position, if we don't use SetExpertMagicNumber() function the deal that came out of it will be 0. After add SetExpertMagicNumber() when close position the deal will have the same magic number.