[MQL4 Coding Help] Overwrite .xml file periodically

Hello,

I am fetching news from http://nfs.faireconomy.media/ff_calendar_thisweek.xml and it save the file inside terminal/MQL4\Files as FFCPing(Symbol)-ffcal_week_this.xml (eg, FFCPingGBPUSD-ffcal_week_this.xml). I have added a code to check this file every 2 hours and overwrite it to new version.

Code:

int OnInit()
  {
//--- get today time
   TimeOfDay=(int)TimeLocal()%86400;
   Midnight=TimeLocal()-TimeOfDay;
//--- set xml file name ffcal_week_this (fixed name)
   xmlFileName=INAME+"-ffcal_week_this.xml";
//--- checks the existence of the file.
   if(!FileIsExist(xmlFileName))
     {
      xmlDownload();
      xmlRead();
     }
//--- else just read it
   else
      xmlRead();
//--- get last modification time
   xmlModifed=(datetime)FileGetInteger(xmlFileName,FILE_MODIFY_DATE,false);
//--- check for updates
   if(!FileIsExist(xmlFileName))
     {
      if(xmlModifed<TimeLocal()-(2*3600))
        {
         Print(INAME+": xml file is out of date");
         xmlUpdate();
        }
      //--- set timer to update old xml file every x hours

      EventSetTimer(2*3600);
     }
   assignVal=true;
  return(INIT_SUCCEEDED);
}

void OnTimer()
  {
//---
   assignVal=true;
   Print(INAME+": xml file is out of date");
   xmlUpdate();
//---
  }


void xmlDownload()
  {
   Sleep(3000);
//---
   ResetLastError();
  

   string cookie=NULL, headers;
   string reqheaders="User-Agent: Mozilla/4.0\r\n";
   char post[],result[];
   int res;
   string url="http://nfs.faireconomy.media/ff_calendar_thisweek.xml";
   ResetLastError();
   int timeout=5000;
   res=WebRequest("GET",url,reqheaders,timeout,post,result,headers);
   if(res==-1)
     {
      Print("Error in WebRequest. Error code  =",GetLastError());
      //--- Perhaps the URL is not listed, display a message about the necessity to add the address
      MessageBox("Add the address '"+url+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
     }
   else
     {
      //--- Load successfully
      PrintFormat("The file has been successfully loaded, File size =%d bytes.",ArraySize(result));
      //--- Save the data to a file
      int filehandle=FileOpen(xmlFileName,FILE_WRITE|FILE_BIN);
      //--- Checking errors
      if(filehandle!=INVALID_HANDLE)
        {
         //--- Save the contents of the result[] array to a file
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- Close the file
         FileClose(filehandle);
        }
      else
         Print("Error in FileOpen. Error code=",GetLastError());
     }
//---
  }

Error: It not overwriting automatically. I have to delete the file manually and than this code create new .xml file. How to fix this?. How to make this overwrite existing file automatically?

What does xmlupdate do? Seems that’s what doesn’t work, but I don’t see the code

void xmlUpdate()
  {
   Sleep(3000);
//--- do not download on saturday
   if(TimeDayOfWeek(Midnight)==6)
      return;
   else
     {
      Print(INAME+": check for updates...");
      Print(INAME+": delete old file");
      FileDelete(xmlFileName);
      xmlDownload();
      xmlRead();
      xmlModifed=(datetime)FileGetInteger(xmlFileName,FILE_MODIFY_DATE,false);
      PrintFormat(INAME+": updated successfully! last modified: %s",(string)xmlModifed);
     }
//---
  }

This is xmlupdate

BTW, if the file exists before you start, the timer event doesn’t run. Is that your problem?

Edit. The timer never runs. It shouldn’t be in the if statement.

Maybe the last if statement oninit is reversed logic?

I really do not understand what make Timer not run. (2*3600) it should be updating XML file every 2 hours.

I want Every 2 hours :

  1. Delete old XML file
  2. Create new XML file
  3. Read new XML file

I am getting :

  1. Download XML file when installation of EA on chart
  2. Read XML file

Really hard to reply on a phone, but you have an if statement that says if the file doesn’t exist to download and create it. Immediately afterwards you have another I’d statement that says if the file doesn’t exist to check if it’s 2 hours old and then still within that statement you create the timer. That if statement will never get entered because you created the file Immediately before checking that it doesn’t exist

To ensure that the file is overwritten each time, you need to use the FILE_WRITE flag with the FileOpen function. However, if the file already exists, you should first delete it before creating a new one. This can be done using the FileDelete function. Your implementation of the timer appears to be correct. However, if it is not triggering as expected, it could be due to the condition in the OnInit() function. The checks for the file’s existence and its last modification time should be separate. Also, the timer should be set regardless of whether the file exists. Before downloading the new XML file, use FileDelete to remove the old one if it exists. After deleting the old file, your existing xmlDownload() function should handle creating the new file. Then, you can read the file as needed. Although I’m very new to this coding world, I believe this should work:
int OnInit() {
//— get today time
TimeOfDay = (int)TimeLocal() % 86400;
Midnight = TimeLocal() - TimeOfDay;
//— set xml file name ffcal_week_this (fixed name)
xmlFileName = INAME + “-ffcal_week_this.xml”;

//--- check for updates and read file
if (FileIsExist(xmlFileName)) {
    xmlModifed = (datetime)FileGetInteger(xmlFileName, FILE_MODIFY_DATE, false);
    if (xmlModifed < TimeLocal() - (2 * 3600)) {
        Print(INAME + ": xml file is out of date");
        xmlUpdate();
    } else {
        xmlRead();
    }
} else {
    xmlDownload();
    xmlRead();
}

//--- set timer to update old xml file every 2 hours
EventSetTimer(2 * 3600);

return(INIT_SUCCEEDED);

}

void OnTimer() {
//—
Print(INAME + “: Updating xml file”);
xmlUpdate();
//—
}

void xmlUpdate() {
// Delete old file if it exists
if (FileIsExist(xmlFileName)) {
FileDelete(xmlFileName);
}
// Download and read new file
xmlDownload();
xmlRead();
}

void xmlDownload() {
Sleep(3000);
//—
ResetLastError();

string cookie = NULL, headers;
string reqheaders = "User-Agent: Mozilla/4.0\r\n";
char post[], result[];
int res;
string url = "http://nfs.faireconomy.media/ff_calendar_thisweek.xml";
ResetLastError();
int timeout = 5000;
res = WebRequest("GET", url, reqheaders, timeout, post, result, headers);
if (res == -1) {
    Print("Error in WebRequest. Error code =", GetLastError());
    MessageBox("Add the address '" + url + "' in the list of allowed URLs on tab 'Expert Advisors'", "Error", MB_ICONINFORMATION);
} else {
    PrintFormat("The file has been successfully loaded, File size = %d bytes.", ArraySize(result));
    int filehandle = FileOpen(xmlFileName, FILE_WRITE | FILE_BIN);
    if (filehandle != INVALID_HANDLE) {
        FileWriteArray(filehandle, result, 0, ArraySize(result));
        FileClose(filehandle);
    } else {
        Print("Error in FileOpen. Error code =", GetLastError());
    }
}
//---

}

// Include your xmlRead function and any other relevant code

1 Like