Почему [ MetaTrader 4 ] не может записать/открыть файл в Windows 10 с помощью функции FileWrite()?

Я попытался реализовать решения из этого сообщения Не удается открыть файл в Ubuntu

Но безрезультатно. Я продолжаю получать сообщение об ошибке 5002. (не удалось открыть файл) после FileWrite()

Даже когда я пробую пример скрипта на https://docs.mql4.com/files/filewrite

Я получаю ту же ошибку. Я попытался запустить MetaTrader Terminal 4 в режиме администратора, но безрезультатно.
Кто-нибудь знает решение этой проблемы?

 #property version   "1.00"
 #property strict

 //--- show the window of input parameters when launching the script
 #property script_show_inputs

 //--- parameters for receiving data from the terminal
 input string             InpSymbolName    = "EURUSD";    // Сurrency pair
 input ENUM_TIMEFRAMES    InpSymbolPeriod  = PERIOD_H1;   // Time frame
 input int                InpFastEMAPeriod = 12;          // Fast EMA period
 input int                InpSlowEMAPeriod = 26;          // Slow EMA period
 input int                InpSignalPeriod  =  9;          // Difference averaging period
 input ENUM_APPLIED_PRICE InpAppliedPrice  = PRICE_CLOSE; // Price type

 //--- parameters for writing data to file
 input string             InpFileName      = "MACD.csv";  // File name
 input string             InpDirectoryName = "Data";      // Folder name
 //+------------------------------------------------------------------+
 //| Script program start function                                    |
 //+------------------------------------------------------------------+

 void OnStart()
 {
    bool     sign_buff[];                                 // signal array (true - buy, false - sell)
    datetime time_buff[];                                 // array of signals' appear time
    int      sign_size=0;                                 // signal array size
    double   macd_buff[];                                 // array of indicator values
    datetime date_buff[];                                 // array of indicator dates
    int      macd_size=0;                                 // size of indicator arrays

 //--- set indexing as time series
    ArraySetAsSeries( sign_buff, true );
    ArraySetAsSeries( time_buff, true );
    ArraySetAsSeries( macd_buff, true );
    ArraySetAsSeries( date_buff, true );

 //--- reset last error code
    ResetLastError();

 //--- copying the time from last 1000 bars
    int  copied = CopyTime( NULL, 0, 0, 1000, date_buff );
    if ( copied <= 0 )
    {    PrintFormat( "Failed to copy time values. Error code = %d", GetLastError() );`
         return;
      }

 //--- prepare macd_buff array
    ArrayResize( macd_buff, copied );

 //--- copy the values of main line of the iMACD indicator
    for ( int i = 0; i< copied; i++ )
    {     macd_buff[i] = iMACD( InpSymbolName, InpSymbolPeriod, InpFastEMAPeriod, InpSlowEMAPeriod, InpSignalPeriod, InpAppliedPrice, MODE_MAIN, i );
      }

 //--- get size
    macd_size = ArraySize( macd_buff );

 //--- analyze the data and save the indicator signals to the arrays
    ArrayResize( sign_buff, macd_size - 1 );
    ArrayResize( time_buff, macd_size - 1 );
    for ( int i = 1; i < macd_size; i++ )
    {   
        //--- buy signal
          if (  macd_buff[i-1] <  0
             && macd_buff[i]   >= 0 )
          {     
                sign_buff[sign_size] = true;
                time_buff[sign_size] = date_buff[i];
                sign_size++;
            }
        //--- sell signal
        if (  macd_buff[i-1] >  0
           && macd_buff[i]   <= 0 )
        {  
              sign_buff[sign_size] = false;
              time_buff[sign_size] = date_buff[i];
              sign_size++;
           }
      }

 //--- open the file for writing the indicator values (if the file is absent, it will be created automatically)
    ResetLastError();
    int file_handle = FileOpen( InpDirectoryName                    // aDirNAME
                              + "//"                                // aFileSystemTreeBranchSEPARATOR
                              + InpFileName,                        // aFileNAME
                                FILE_READ|FILE_WRITE|FILE_CSV       // fileIoMODE_FLAGs
                                );
    if (  file_handle != INVALID_HANDLE )
    {     
          PrintFormat( "%s file is available for writing", InpFileName );
          PrintFormat( "File path: %s\\Files\\",           TerminalInfoString( TERMINAL_DATA_PATH ) );

       //--- first, write the number of signals
          FileWrite( file_handle, sign_size );

       //--- write the time and values of signals to the file
          for ( int i = 0; i <  sign_size; i++ )
                FileWrite( file_handle, time_buff[i], sign_buff[i] );

       //--- close the file
          FileClose( file_handle );
          PrintFormat( "Data is written, %s file is closed", InpFileName );
      }
    else
          PrintFormat( "Failed to open %s file, Error code = %d", InpFileName, GetLastError() );
   }

person Maurice    schedule 19.06.2016    source источник
comment
Пожалуйста, опубликуйте соответствующий код.   -  person user3666197    schedule 19.06.2016
comment
со всем уважением, но... я никогда не заставляю генератор кода работать, пожалуйста, просто нажмите на ссылку.   -  person Maurice    schedule 20.06.2016


Ответы (1)


Альт. А)

алгоритм не проверяет наличие узла InpDirectoryName в файловой системе.

Альт. Б)

в случае, если альт. A) проходит, в aFilePATH + aFileNAME string следует использовать совместимый разделитель, т. е. == "\\", ( aFileSystemTreeBranchSEPARATOR см.: Справка для подробностей )
тогда
должно быть использовано fileIO происходить в \Terminal\Common\Files (в случае, если в параметре int open_flags был добавлен (использован) флаг битовой маски FILE_COMMON),
в противном случае
операции будут происходить в (под)-каталог локальной папки MetaTrader Terminal 4
== MQL4\Files (для живого ExpertAdvisor или режим работы Custom Indicator или Script )
или
== MQL4\Tester\Files (в случае использования ExpertAdvisor или Custom Indicatorвнутри системы обратного тестирования MT4 Strategy Tester).

person user3666197    schedule 20.06.2016