﻿//+------------------------------------------------------------------+
//|                                               WFE_CSV_Reader.mqh |
//|             CSV return series reader for WFE Validation Engine   |
//+------------------------------------------------------------------+
#ifndef WFE_CSV_READER_MQH
#define WFE_CSV_READER_MQH

//+------------------------------------------------------------------+
//| Read per-bar equity returns from a CSV file written by the EA    |
//| Expected format: BarIndex,DateTime,EquityReturn (with header)    |
//| Returns number of rows read, -1 on failure                       |
//+------------------------------------------------------------------+
int ReadReturnsFromCSV(const string filename, double &returns[])
  {
   int handle = FileOpen(filename, FILE_READ | FILE_CSV | FILE_ANSI | FILE_COMMON, ',');
   if(handle == INVALID_HANDLE)
     {
      Print("WFE_CSV_Reader: Cannot open '", filename, "'. Error=", GetLastError());
      Print("WFE_CSV_Reader: Ensure the file is in the MQL5/Files/ directory.");
      return(-1);
     }

   ArrayResize(returns, 0);
   int  row_count      = 0;
   bool header_skipped = false;

   while(!FileIsEnding(handle))
     {
      string col_index  = FileReadString(handle);
      string col_time   = FileReadString(handle);
      string col_return = FileReadString(handle);

      //--- Skip the header row (first column reads "BarIndex")
      if(!header_skipped)
        {
         header_skipped = true;
         if(col_index == "BarIndex")
            continue;
        }

      //--- Skip empty trailing rows
      if(StringLen(col_return) == 0)
         continue;

      double ret_val = StringToDouble(col_return);

      int idx = ArraySize(returns);
      ArrayResize(returns, idx + 1);
      returns[idx] = ret_val;

      row_count++;
     }

   FileClose(handle);

   Print("WFE_CSV_Reader: Read ", row_count, " return bars from '", filename, "'");

   if(row_count < 10)
      Print("WFE_CSV_Reader: WARNING — fewer than 10 rows read. ",
            "Check that the EA completed its backtest and wrote the file.");

   return(row_count);
  }

#endif // WFE_CSV_READER_MQH
//+------------------------------------------------------------------+