Problem writing a file

 

I want to save the deals of my optimizations in different files.

To do this I wrote the following code.

This works perfectly in test mode. But it doesn't work during optimization.

Does anyone know how to do it correctly?

Thank you very much !!


#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;
int handler;
//+------------------------------------------------------------------+
int passes = 0;
double EP=0;
//+------------------------------------------------------------------+
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());      
   }
}

//+------------------------------------------------------------------+
void SaveDeals()
{
   datetime end=TimeCurrent();     
   datetime start=0;              
   HistorySelect(start,end); 
   int dealsTotal    = HistoryDealsTotal();
   
   handler = FileOpen("./" + (string)passes + ".csv", FILE_CSV|FILE_READ|FILE_WRITE|FILE_ANSI|FILE_COMMON,'\t',CP_UTF8);     

   for(int i=0; i<dealsTotal; i++)
   {
         deal.SelectByIndex(i);
      
         FileWrite
         (
            handler,";",
            deal.Symbol(),";",
            deal.Magic(),";",            
            deal.Time(),";", 
            deal.Type(),";", 
            deal.Volume(),";",            
            deal.Commission(),";",
            deal.Swap(),";",
            deal.Profit()                       
         );   
   }
   
   FileClose(handler);
}
//+------------------------------------------------------------------+

double OnTester()
{   
   EP = TesterStatistics(STAT_EXPECTED_PAYOFF);
   
   if(EP>1) SaveDeals();
      
   passes++;      
   return EP;
}
//+------------------------------------------------------------------+

   
Files:
Reason: