Failed to open the CSV file for writing! Error code: 5002

 

Hi guys, I've been getting this error on my expert advisor when writing to csv file. Below is my code.

input double CommissionPerLot = 5.0; // Commission per lot parameter

//+------------------------------------------------------------------+
//| Expert Advisor initialization function                           |
//+------------------------------------------------------------------+
int OnInit()
{
   // Get the total number of available symbols
   int totalSymbols = SymbolsTotal(false);

   // Get the broker name
   string brokerName = AccountInfoString(ACCOUNT_COMPANY);

   // Create the filename with the broker name
   string fileName = "CommissionCheck_" + brokerName + ".csv";

   // Check if the file already exists
   if (FileIsExist(fileName))
   {
      // Delete the existing file
      if (!FileDelete(fileName))
      {
         PrintFormat("Failed to delete existing file '%s'! Error code: %d", fileName, GetLastError());
         return INIT_FAILED;
      }
   }

   // Open the CSV file for writing
   int fileHandle = FileOpen(fileName, FILE_CSV | FILE_WRITE, '\t');
   if (fileHandle == INVALID_HANDLE)
   {
      PrintFormat("Failed to open the CSV file for writing! Error code: %d", GetLastError());
      return INIT_FAILED;
   }

   // Write the table header
   FileWrite(fileHandle, "Symbol\tTick Size\tTick Value\tContract Size\tCurrent Price\tSpread\tTick Value in Dollars\tMCC (Points)\tMCC (Dollars)\tCom1\tCom2\tCom3\tCom4\tCom5\tCom6\tCom7\tCom8\tCom9\tCom10\tRemark");

   // Iterate through each symbol
   for (int i = 0; i < totalSymbols; i++)
   {
      // Print progress information
      Print("Processing symbol ", i+1, " of ", totalSymbols);

      // Retrieve the symbol at the current index
      string symbol = SymbolName(i, false);

      // Check if trading is allowed for the symbol
      if (SymbolInfoInteger(symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_DISABLED)
         continue;

      // Retrieve the tick size, tick value, and contract size of the symbol
      double tickSize = SymbolInfoDouble(symbol, SYMBOL_POINT);
      double tickValue = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_VALUE);
      double contractSize = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);

      // Declare an array to store the rates
      MqlRates rates[];

      // Calculate the total number of rates for the symbol
      int totalRates = Bars(symbol, PERIOD_CURRENT);

      // Check if there are rates available
      if (totalRates <= 0)
      {
         PrintFormat("No rates available for symbol %s! Error code: %d", symbol, GetLastError());
         continue;
      }

      // Copy the rates into the array
      int copiedRates = CopyRates(symbol, PERIOD_CURRENT, 0, totalRates, rates);

      // Check if the rates were copied successfully
      if (copiedRates <= 0)
      {
         PrintFormat("Failed to copy rates for symbol %s! Error code: %d", symbol, GetLastError());
         continue;
      }

      // Retrieve the close price of the latest rate
      double currentPrice = rates[copiedRates - 1].close;

      // Retrieve the spread in points
      int spreadPoints = SymbolInfoInteger(symbol, SYMBOL_SPREAD);

      // Convert the spread from points to the actual price level
      double spread = spreadPoints * SymbolInfoDouble(symbol, SYMBOL_POINT);

      // Convert the tick value to dollars based on the current price
      double tickValueInDollars = tickValue * tickSize * currentPrice;

      // Calculate the number of movements in points required to cover the commission using lot size 1
      int movementsToCoverCommissionPoints = 0;
      if (tickValue != 0.0)
      {
         movementsToCoverCommissionPoints = (int)(CommissionPerLot / tickValue);
      }
      else
      {
         movementsToCoverCommissionPoints = INT_MAX;
      }

      // Calculate the dollar amount required to cover the commission using lot size 1
      double movementsToCoverCommissionDollars = movementsToCoverCommissionPoints * tickValueInDollars;

      // Prepare the data row
      string rowData = symbol + "\t" +
         DoubleToString(tickSize) + "\t" +
         DoubleToString(tickValue) + "\t" +
         DoubleToString(contractSize) + "\t" +
         DoubleToString(currentPrice) + "\t" +
         DoubleToString(spread) + "\t" +
         DoubleToString(tickValueInDollars) + "\t" +
         IntegerToString(movementsToCoverCommissionPoints) + "\t" +
         DoubleToString(movementsToCoverCommissionDollars) + "\t";

      for (int com = 1; com <= 10; com++)
      {
         double commissionValue = com;
         string comRemark;
         if (tickValueInDollars > commissionValue)
            comRemark = "CAN!";
         else
            comRemark = "CAN'T";

         rowData += comRemark + "\t";
      }

      // Determine if the commission can be covered
      string remark;
      if (tickValueInDollars > CommissionPerLot)
         remark = "CAN!";
      else
         remark = "CAN'T";

      rowData += remark;

      // Write the data row to the CSV file
      if (!FileWrite(fileHandle, rowData))
      {
         PrintFormat("Failed to write data for symbol %s! Error code: %d", symbol, GetLastError());
      }
   }

   // Close the CSV file
   FileClose(fileHandle);

   return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert Advisor start function                                     |
//+------------------------------------------------------------------+
void OnTick()
{
   // Place your trading logic here
}
 

Please search before you post ... https://www.mql5.com/en/search#!keyword=Error%205002&module=mql5_module_forum

ERR_WRONG_FILENAME

5002

Invalid file name

Check your filename (and in your case broker name) for any invalid characters that are not allowed, such as colon ":", etc.

Your topic has been moved to the section: Expert Advisors and Automated Trading — In the future, please consider which section is most appropriate for your query.

 

The code used to work, and all of a sudden started printing that error.

Any assistance would be appreciated



Fernando Carreiro #:

Please search before you post ... https://www.mql5.com/en/search#!keyword=Error%205002&module=mql5_module_forum

ERR_WRONG_FILENAME

5002

Invalid file name

Check your filename (and in your case broker name) for any invalid characters that are not allowed, such as colon ":", etc.

Your topic has been moved to the section: Expert Advisors and Automated Trading — In the future, please consider which section is most appropriate for your query.

 
futuristly #: The code used to work, and all of a sudden started printing that error. Any assistance would be appreciated

Follow up as suggested ...

  • "Check your filename (and in your case broker name) for any invalid characters that are not allowed, such as colon ":", etc."

    Did you do that? Did you print out the file name to the log file and verify it?

  • "Please search before you post".

    Did you do that? Did you read the other threads for possible similarities and clues?

Also, does the file perhaps already exist? Is it perhaps "locked" because it is open in another application?