Having issues trying to print the trades history

 

So, i have made this code to print the list of all trades made in the backtest.
But it does't print anything, there is trades (i did't shared the strategy code, but there is roughly 40 trades executed in the backtest).

Could someone please help me fix my code ?


//+------------------------------------------------------------------+
//|                                              YourExpertAdvisor.mq5|
//|                        Copyright 2024, Your Name                  |
//|                                       http://www.yourwebsite.com |
//+------------------------------------------------------------------+
#property strict

#include <Trade/Trade.mqh>
CTrade Trade_Obj;


int MagicNumber = 1586641;


string symbol = "NDX";
ENUM_TIMEFRAMES period = PERIOD_M15; // 15 minutes == +108 000

// Structure pour stocker les informations des trades clôturés
struct ClosedTradeInfo
  {
   int barIndex;
   double profit;
  };

// Déclaration d'un tableau dynamique pour stocker les informations des trades clôturés
ClosedTradeInfo closedTrades[];


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
        // Some code here

}


//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   PrintClosedTrades();
}


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   CheckClosedTrades();   
}

//+-----------------------------------------------------------------    




//+------------------------------------------------------------------+
//| Check closed trades and store details                            |
//+------------------------------------------------------------------+
void CheckClosedTrades()
  {
   int total = HistoryOrdersTotal();
   for(int i = 0; i < total; i++)
     {
      if (OrderSelect(i))
        {
         if (OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_SELL || OrderGetInteger(ORDER_TYPE) == ORDER_TYPE_BUY) // Vérifier que c'est un trade de marché (BUY ou SELL)
           {
            ENUM_ORDER_TYPE OrderType;
            OrderType = OrderGetInteger(ORDER_TYPE);
            
            ClosedTradeInfo tradeInfo;
            tradeInfo.barIndex = iBarShift(NULL, 0, OrderGetInteger(ORDER_TIME_DONE));
            
            double profit = 0.0;
            OrderCalcProfit(OrderType, symbol, OrderGetDouble(ORDER_VOLUME_CURRENT), OrderGetDouble(ORDER_PRICE_OPEN), OrderGetDouble(ORDER_PRICE_CURRENT), profit);
            tradeInfo.profit = profit;
            
            ArrayResize(closedTrades, ArraySize(closedTrades) + 1);
            closedTrades[ArraySize(closedTrades) - 1] = tradeInfo;
           }
        }
     }
  }



//+------------------------------------------------------------------+
//| Print closed trades information                                  |
//+------------------------------------------------------------------+
void PrintClosedTrades()
{
   printf("---- Printing Trades History... ----");
  
   for (int i = 0; i < ArraySize(closedTrades); i++)
   {
      printf("____");
      printf("Trade " + IntegerToString(i + 1) + ": Bar Index = " + IntegerToString(closedTrades[i].barIndex) + " | Profit = " + DoubleToString(closedTrades[i].profit));
   }
}
//+------------------------------------------------------------------+
 

You are iterating orders and that will not help you to detect closed trades. To detect closed trades you should iterate over deals that are DEAL_OUT.

Check documentation for HistoryDealsTotal, HistoryDealGetTicket, HistoryDealGetInteger, HistoryDealGetDouble, ...

 

Hi

As mentioned, –int mt5 you need to use deals to get the historical positions. Also, I think that iBarShift does not work properly on mt5. Use something like this instead:

HistorySelect(0, TimeCurrent());
   for (int i = HistoryDealsTotal()-1; i >= 0; i--)
   {
      ulong ticket=HistoryDealGetTicket(i);
      if(HistoryDealGetInteger(ticket,DEAL_ENTRY)==DEAL_ENTRY_OUT){
      if (HistoryDealGetInteger(DEAL_TYPE) == DEAL_TYPE_SELL || HistoryDealGetInteger(DEAL_TYPE) == ORDER_TYPE_BUY) // Vérifier que c'est un trade de marché (BUY ou SELL)
           {
           ClosedTradeInfo tradeInfo;
            tradeInfo.barIndex = iBarShiftFixed(NULL, 0, OrderGetInteger(ORDER_TIME_DONE));
            
         double  profit = HistoryDealGetDouble(ticket, DEAL_PROFIT)+HistoryDealGetDouble(ticket, DEAL_SWAP)+HistoryDealGetDouble(ticket, DEAL_COMMISSION)*2;
         tradeInfo.profit = profit;

         ArrayResize(closedTrades, ArraySize(closedTrades) + 1);
         closedTrades[ArraySize(closedTrades) - 1] = tradeInfo;
           }
      
   }
   int iBarShiftFixed(string symbol,
                  int tf,
                  datetime time,
                  bool exact=false)
  {
   if(time<0) return(-1);
   ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
   datetime Arr[],time1;
   CopyTime(symbol,timeframe,0,1,Arr);
   time1=Arr[0];
   if(CopyTime(symbol,timeframe,time,time1,Arr)>0)
     {
      if(ArraySize(Arr)>2) return(ArraySize(Arr)-1);
      if(time<time1) return(1);
      else return(0);
     }
   else return(-1);
  }

Have a nice weekend

 

Thanks ! It make way more sense ! But there is 2 errors with the iBarShiftFixed function, and i don't know how to fix them, it seem that the TFMigrate function does't exist, maybe it changed name or you forgot to provide it ? Could you please help me fix it ?


'TFMigrate' - undeclared identifier
'tf' - some operator expected



 
Marzena Maria Szmit #:

Hi

As mentioned, –int mt5 you need to use deals to get the historical positions. Also, I think that iBarShift does not work properly on mt5. Use something like this instead:

Have a nice weekend

Can you please help me with the errors i mentioned in my last message ?

 
int OnInit()
  {
   if(HistorySelect(0, TimeCurrent()))
     {
      int total = HistoryDealsTotal();
      for(int i = 0; i < total; i++)
        {
         ulong dealTicket = HistoryDealGetTicket(i);
         if(HistoryDealGetInteger(dealTicket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
         {
            ulong position_ticket = HistoryDealGetInteger(dealTicket, DEAL_POSITION_ID);
            PrintClosedTradeInfo(position_ticket);
            HistorySelect(0, TimeCurrent());
         }
        }
     }
   return(INIT_SUCCEEDED);
  }
  
void PrintClosedTradeInfo(ulong ticket)
{
   if(HistorySelectByPosition(ticket)==true)
   {
      int deals_total = HistoryDealsTotal();
      //in deal
      ulong in_deal_ticket=HistoryDealGetTicket(0);
      datetime in_deal_time = (datetime)HistoryDealGetInteger(in_deal_ticket, DEAL_TIME);
      //out deal
      ulong out_deal_ticket=HistoryDealGetTicket(deals_total-1);
      datetime out_deal_time = (datetime)HistoryDealGetInteger(out_deal_ticket, DEAL_TIME);
      double pnl = HistoryDealGetDouble(out_deal_ticket, DEAL_PROFIT);
      Print("Trade entered at: ", TimeToString(in_deal_time, TIME_SECONDS),
            ", Trade Exited at: ", TimeToString(out_deal_time, TIME_SECONDS),
            ", PnL: ", DoubleToString(pnl, 2));
   }
}
 
Yashar Seyyedin #:

This is not what i need