Help with FileWrite to csv

 

Hello, I would like my indicator to save all ohlc values to csv file once loaded and then do not save anything more until manual reload of the indicator. This is what I did:

int handle = FileOpen("export.csv",FILE_READ|FILE_WRITE|FILE_CSV);

int OnInit(void)
  {

   if(handle>0)
     {
      FileSeek(handle,0,SEEK_SET);
      FileWrite(handle,"Date","Hour:Minute","Open","High","Low","Close");
     }


// Set number of significant digits (precision)
   IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
   ObjectsDeleteAll(0,IntegerToString(tf));
// Set Indicator buffers

   SetIndexBuffer(0, buff_dev, INDICATOR_DATA);
   SetIndexBuffer(1, buff_dev2, I
NDICATOR_DATA);
   SetIndexBuffer(2, buff_lowerdev, INDICATOR_DATA);
//Set indicator style

   SetIndexStyle(0,DRAW_LINE,0,2,clr1H);
   SetIndexStyle(1,DRAW_LINE,dev_ln,1,clrGold);
   SetIndexStyle(2,DRAW_LINE,dev_ln,1,clr1H);


   return INIT_SUCCEEDED;  // Successful initialisation of indicator
  };

// Calculation event handler
int OnCalculate(
   const int      rates_total,
   const int      prev_calculated,
   const datetime &time[],
   const double   &open[],
   const double   &high[],
   const double   &low[],
   const double   &close[],
   const long     &tick_volume[],
   const long     &volume[],
   const int      &spread[]
)
  {
// Define maximum index for the buffer array

   int lookback = 1000;
// Replacing loop function with the one you pointed out
   for(int iBar = Bars-1-MathMax(lookback, prev_calculated); iBar >= 0; --iBar)
     {
       ...
       ...
        
      if( iBar != 0)
        {
         FileSeek(handle,0,SEEK_END);
         FileWrite(handle,TimeToString(Time[iBar],TIME_DATE),TimeToString(Time[iBar],TIME_MINUTES),Open[iBar],High[iBar],Low[iBar],Close[iBar]);
        }
      else FileClose(handle);



     }

   return rates_total-1; // Recalculate current bar next tick.
// Return value of prev_calculated for next call
  };

Can someone help me identifying what I did wrong? Thank's.