How to save correctly all deals into a csv file?

 

I want to save some histories of the optimizations in a CSV file. But sometimes not all deals are written to the file correctly.

For example, maybe one pass had 2000 trades and only 3500 deals were written in the file.

Or sometimes some of the data in a row is missing.

I don't know what is happening exactly.

Is my code wrong?

The OnTester() event flushes the memory before the data is written to the file? Any ideas for this not to happen?


Below is a test code;


///--------------------------------------------------------------------------------
#ifndef CSV_H
#define CSV_H
///--------------------------------------------------------------------------------
class CSV
{
   string fileName;
   int handle;
   
public:

   void CSV()
   {
      fileName="Deals "+MQLInfoString(MQL_PROGRAM_NAME)+"_"+EnumToString(Period())+"_"+_Symbol+".csv"; // Form the file name
   }

   bool Open()
   {
      handle=FileOpen(fileName,FILE_READ|FILE_WRITE|FILE_CSV|FILE_COMMON|FILE_SHARE_WRITE|FILE_SHARE_READ,'\t',CP_UTF8); // Open the file
      if(handle) return true;
      return false;
   }
   
   bool Exist()
   {
      return FileIsExist(fileName,FILE_COMMON); 
   }
  
   void MoveToEOF() // Move the cursor to the file end
   {
      FileSeek(handle,0,SEEK_END); // Move the cursor to the file end
   }
   
   void Write(string pBuffer)
   {
      FileWrite(handle,pBuffer); // Write the message
   }
   
   void Close()
   {
      FileClose(handle); // Close the file
   }
   
   void Update(string pBuffer)
   {  
      if(!Open())  return;
      if(!Exist())  return;
      MoveToEOF();
      Write(pBuffer);
      Close();   
   }
   
   string GetHistoyDeals()
   {
      datetime end=TimeCurrent();     
      datetime start=0;              
      HistorySelect(start,end); 
      int dealsTotal = HistoryDealsTotal();
      
      if(dealsTotal==0) return "";  
      
      string history;
      
       for(short i=0; i<dealsTotal; i++)
       {   
         
         ulong deal_ticket =    HistoryDealGetTicket(i);        
           
         
         if(deal_ticket!=0)
         {       
            string order_ticket    = (string)HistoryDealGetInteger(deal_ticket, DEAL_ORDER);
            string position_ticket = (string)HistoryDealGetInteger(deal_ticket, DEAL_POSITION_ID);
            string time            = (string)HistoryDealGetInteger(deal_ticket, DEAL_TIME);
            string type            = (string)HistoryDealGetInteger(deal_ticket, DEAL_TYPE);
            string entry           = (string)HistoryDealGetInteger(deal_ticket, DEAL_ENTRY);            
            string symbol          = (string)HistoryDealGetString(deal_ticket, DEAL_SYMBOL);          
            string volume          = (string)HistoryDealGetDouble(deal_ticket, DEAL_VOLUME);
            string price           = (string)HistoryDealGetDouble(deal_ticket, DEAL_PRICE);
            string profit          = (string)HistoryDealGetDouble(deal_ticket, DEAL_PROFIT);
            string swap            = (string)HistoryDealGetDouble(deal_ticket, DEAL_SWAP);
            string commission      = (string)HistoryDealGetDouble(deal_ticket, DEAL_COMMISSION);
            string magic           = (string)HistoryDealGetInteger(deal_ticket, DEAL_MAGIC);
            string reason          = (string)HistoryDealGetInteger(deal_ticket, DEAL_REASON); 
            
            
            
            history +=             
            order_ticket      +"\t"+
            position_ticket   +"\t"+
            time              +"\t"+
            type              +"\t"+
            entry             +"\t"+                 
            symbol            +"\t"+          
            volume            +"\t"+
            price             +"\t"+
            profit            +"\t"+
            swap              +"\t"+
            commission        +"\t"+
            magic             +"\t"+
            reason            ;
         }      
         
       } 
       
       return str;  
   }

};
///---------------------------------------------------------------------------------
#endif
///---------------------------------------------------------------------------------




//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\DealInfo.mqh>
//+------------------------------------------------------------------+
CTrade cTrade;
CSymbolInfo cSymbol;
CPositionInfo cPositionInfo;    
CDealInfo deal;
int magicNumber = 1;
input double TP = 1000;
input double SL = 1000;
//+------------------------------------------------------------------+
void OnInit()
{
   cTrade.SetExpertMagicNumber(magicNumber);
}
//+------------------------------------------------------------------+
void OnTick()
{   
   bool isTrading = cPositionInfo.SelectByMagic(Symbol(), magicNumber);   

   if(!isTrading)   
   {      
      if(cTrade.Buy(0.01,Symbol(), cSymbol.Ask(), cSymbol.Ask()-SL*cSymbol.Point(), cSymbol.Ask()+TP*cSymbol.Point()))      
         printf("Position open");      
      else      
         printf("Position open FAILL: %i",  cTrade.ResultRetcode()); 
      
   }
   
   if(isTrading)
   {
     if(cTrade.PositionClose(cPositionInfo.Ticket()) && cTrade.ResultRetcode()==TRADE_RETCODE_DONE)     
         printf("Position close");     
     else     
         printf("Position close FAILL: %i",  cTrade.ResultRetcode());      
   }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+ 
CSV csv;   
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
double OnTester()
{          
   string history = csv.GetHistoyDeals();
   csv.Update(history); 
   return (MQLInfoInteger(MQL_OPTIMIZATION) == 1 ? TesterStatistics(STAT_EXPECTED_PAYOFF) : 0);
}
///---------------------------------------------------------------------------------
///---------------------------------------------------------------------------------

Thank you so much!!

Reason: