Problem Description
Solution
To achieve this in MQL4, you need to utilize the file system functions provided by the API. Note that for security reasons, MQL4 operates within a "sandbox." All file operations (creation, deletion, reading) are restricted to the terminal_data_folder\MQL4\Files directory.
Below is a complete script that performs the following actions:
- Creates a new folder (or verifies if it already exists).
- Scans that folder for specific file types (e.g.,
.logor.txt). - Checks the age of each file.
- Deletes files that are older than a specified number of days.
MQL4 Script: Create Folder and Clean Logs
Save this code as a Script (e.g., CleanLogs.mq4) in your MQL4/Scripts folder.
//+------------------------------------------------------------------+
//| CleanLogs.mq4 |
//| Copyright 2023, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property script_show_inputs
//--- Input Parameters
input string InpFolderName = "MyLogArchives"; // Name of the folder to create/clean
input string InpExtension = "log"; // File extension to target (e.g., log, txt, csv)
input int InpDaysOld = 30; // Delete files older than this many days
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// 1. Attempt to create the folder
// Note: This creates the folder inside MQL4\Files\
if(!FolderCreate(InpFolderName))
{
int err = GetLastError();
// Error 4119 means the folder already exists, which is fine for our purpose
if(err != 4119)
{
Print("Error creating folder '", InpFolderName, "'. Error Code: ", err);
return;
}
else
{
Print("Folder '", InpFolderName, "' already exists. Proceeding to cleanup.");
}
}
else
{
Print("Folder '", InpFolderName, "' created successfully.");
}
// 2. Define the search filter (e.g., MyLogArchives\*.log)
string search_path = InpFolderName + "\\*." + InpExtension;
string file_name;
// 3. Start searching for files in the folder
// 0 indicates searching in the local MQL4\Files folder
long search_handle = FileFindFirst(search_path, file_name, 0);
if(search_handle != INVALID_HANDLE)
{
int deleted_count = 0;
do
{
// Construct the full path for the file operations
string full_file_path = InpFolderName + "\\" + file_name;
// 4. Check if it is a file and not a directory
if(!FileIsExist(full_file_path)) continue; // Safety check
// Get the file creation date
long create_date = FileGetInteger(full_file_path, FILE_CREATE_DATE, false);
// Calculate the age of the file in seconds
long file_age_seconds = TimeCurrent() - create_date;
long threshold_seconds = InpDaysOld * 24 * 60 * 60;
// 5. Delete if older than threshold
if(file_age_seconds > threshold_seconds)
{
ResetLastError();
if(FileDelete(full_file_path))
{
Print("Deleted old file: ", file_name, " (Age: ", file_age_seconds/86400, " days)");
deleted_count++;
}
else
{
Print("Failed to delete: ", file_name, ". Error: ", GetLastError());
}
}
}
while(FileFindNext(search_handle, file_name)); // Find the next file
// 6. Always close the search handle
FileFindClose(search_handle);
Print("Cleanup complete. Total files deleted: ", deleted_count);
}
else
{
Print("No files found in '", InpFolderName, "' matching extension *.", InpExtension);
}
}
//+------------------------------------------------------------------+
Key Functions Explained
-
FolderCreate(string folder_name):- Creates a directory in
MQL4\Files. - If the folder already exists, it returns
falseandGetLastError()returns4119. The script handles this gracefully so it can proceed to clean an existing folder.
- Creates a directory in
-
FileFindFirst/FileFindNext/FileFindClose:- These are the standard iteration functions.
FileFindFirstinitializes the search based on a filter (e.g.,Folder\*.log).FileFindNextmoves to the next file in the list.FileFindClosereleases the memory handle used for searching. This is mandatory to prevent memory leaks.
-
FileGetInteger(..., FILE_CREATE_DATE):- Retrieves the timestamp of when the file was created.
- We compare this against
TimeCurrent()(the current server time) to determine the file's age.
-
FileDelete(string file_name):- Permanently removes the file from the directory.
How to Test
- Compile the code in MetaEditor.
- Open your MT4 Data Folder (
File->Open Data Folder). - Navigate to
MQL4\Files. - Manually create a folder named
MyLogArchivesand put some dummy.logfiles in it. - Drag the script onto a chart in MT4.
- Check the "Experts" tab in the Terminal window to see the logs of created folders and deleted files.
Q&A
Q: Can I delete files outside the MQL4\Files folder?
A: No. MQL4 runs in a sandbox environment. You cannot access C:\Windows or Desktop directly using standard MQL4 functions. You would need to use a DLL (Windows API) to access files outside the sandbox.
Q: What happens if InpDaysOld is set to 0?
A: The script will delete all files matching the extension in that folder, as every file will be considered "older" than 0 seconds (assuming they weren't created at the exact same millisecond the script ran).
Q: Does FolderCreate support subdirectories?
A: Yes. If you set InpFolderName to "Logs\\StrategyA", it will create the Logs folder and the StrategyA subfolder inside it.