struct to array to File on mql4

2.3k views Asked by At

the following MQL4 code arises an error :

#property version   "1.00"
#property strict

struct prices
{
    datetime          date; // date
    double            bid;  // bid price
    double            ask;  // ask price
};

prices arr[];
string path ;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{
   //---
    path = "script.log";
   //--- save data to array
    arr[0].date = TimeCurrent();
    arr[0].bid  = SymbolInfoDouble(Symbol(),SYMBOL_BID);
    arr[0].ask  = SymbolInfoDouble(Symbol(),SYMBOL_ASK);
   //--- show current data
   Print("Date = ",arr[0].date," Bid = ",arr[0].bid," Ask = ",arr[0].ask);
   //--- increase the counter
   //--- if the array is filled, write data to the file and zero it out
   WriteData(1);
}
//+------------------------------------------------------------------+
//| Write n elements of the array to file                            |
//+------------------------------------------------------------------+
void WriteData(const int n)
{
    //--- open the file
    ResetLastError();
    int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN|FILE_COMMON);
    if(handle!=INVALID_HANDLE)
      {
       //--- write array data to the end of the file
       FileSeek(handle,0,SEEK_END);
       FileWriteArray(handle,arr,0,n);
       //--- close the file
       FileClose(handle);
      }
    else
       Print("Failed to open the file, error ",GetLastError());
}
//+------------------------------------------------------------------+

the error is :

2015.06.17 15:39:25.561 array out of range in 'Struct2Array.mq4' (28,8)

And the line 28 is the following : arr[0].date = TimeCurrent();

Any idea where's the mistake ?

Thanks in advance /koul.

1

There are 1 answers

0
jlee88my On BEST ANSWER

You need to do either one of these:

  1. Fix the array size when you declare it.

    prices arr[0];

  2. Or, in OnStart(), resize it with:

    ArrayResize( arr, 0 )