MQL5 FileOpen Guide: Reading & Writing CSV Files in MetaTrader 5
Comprehensive guide to MQL5 FileOpen for CSV files. Learn how to combine FILE_READ, FILE_WRITE, FILE_CSV, and FILE_COMMON flags, format custom delimiters, and stream trade records safely.
What this MQL5 guide covers
FileOpen returns an integer file handle on success or INVALID_HANDLE (-1) on error.
MQL5 restricts file access to the terminal sandbox (MQL5\Files) unless FILE_COMMON is specified to access the shared OS directory.
Combining FILE_CSV with FILE_READ and FILE_WRITE requires explicit delimiter specification (e.g. comma ',' or semicolon ';').
Always enclose file operations in resource protection blocks and invoke FileClose(handle) to flush disk buffers and prevent file locking.
FileOpen Function Signature and Bitmask Flags
MQL5 provides low-level file input/output through the FileOpen function. It opens files in text, binary, or delimited CSV mode, controlling access permissions and sharing policies.
| Flag | Value Type | Purpose |
|---|---|---|
| FILE_READ | Open flag | Opens file for reading input data |
| FILE_WRITE | Open flag | Opens file for writing (creates or overwrites existing file) |
| FILE_CSV | Format flag | Specifies comma/delimited text file where FileWrite inserts delimiters automatically |
| FILE_ANSI | Encoding flag | Encodes strings as 1-byte ANSI characters (recommended for external tools/Python) |
| FILE_COMMON | Location flag | Directs path to shared Common\Files directory across all MT5 terminals |
| FILE_SHARE_READ | Sharing flag | Allows other applications or EAs to read the file simultaneously |
Terminal Sandbox vs FILE_COMMON Directory
For security reasons, MetaTrader 5 isolates file operations within dedicated directory sandboxes. Without FILE_COMMON, files are written to [Terminal Data Folder]\MQL5\Files. Other terminal instances cannot access this folder.
Adding FILE_COMMON directs the file to C:\Users\[User]\AppData\Roaming\MetaQuotes\Terminal\Common\Files. This shared folder enables seamless communication between multiple EAs, Python data analysis pipelines, and external charting tools.
- Local Sandbox: FileOpen("log.csv", FILE_WRITE | FILE_CSV); -> MQL5\Files\log.csv
- Shared Directory: FileOpen("log.csv", FILE_WRITE | FILE_CSV | FILE_COMMON); -> Common\Files\log.csv
- Subdirectories: You can specify relative subfolders such as "Data\\EURUSD.csv".
Reading CSV Records Row by Row
When reading a CSV file opened with FILE_CSV, each call to FileReadString(handle) reads the next token up to the delimiter or newline.
Looping while !FileIsEnding(handle) enables parsing complete multi-column tables into MQL5 structs or arrays.
Implementation details & mechanics
Core implementation pattern
To log trading activity or export trade history to CSV: call FileOpen with FILE_WRITE | FILE_CSV | FILE_ANSI | FILE_COMMON. Write a header row using FileWrite(handle, "Ticket", "Symbol", "Type", "Volume", "Price", "Time"). When a trade executes, append the trade metrics with FileWrite.
Error handling & safety rules
Always verify if the file handle is valid before performing I/O: if(handle == INVALID_HANDLE) log GetLastError(). Once read or write loops terminate, unconditionally invoke FileClose(handle) so the operating system commits buffered data to disk.
MQL5 Code Implementation Code
//+------------------------------------------------------------------+
//| FileOpenCSVGuide.mq5 |
//| Copyright 2026, Pineify Guides Series |
//| https://pineify.app |
//+------------------------------------------------------------------+
#property copyright "Pineify Guides Series"
#property link "https://pineify.app/mql5/fileopen-csv-guide"
#property version "1.00"
#property script_show_inputs
//--- Input parameters
input string InpFileName = "pineify_trades.csv"; // CSV File Name
input bool InpUseCommonFolder = true; // Use Shared Common\Files Folder
//+------------------------------------------------------------------+
//| Function: Write trade records to CSV |
//+------------------------------------------------------------------+
bool WriteTradeLogCSV(const string filename, bool useCommon)
{
int flags = FILE_WRITE | FILE_CSV | FILE_ANSI;
if(useCommon)
flags |= FILE_COMMON;
// Open file for writing with comma ',' delimiter
int fileHandle = FileOpen(filename, flags, ',');
if(fileHandle == INVALID_HANDLE)
{
PrintFormat("Failed to open file %s for writing. Error: %d", filename, GetLastError());
return false;
}
// 1. Write Header Row
FileWrite(fileHandle, "Timestamp", "Symbol", "Action", "Lots", "Price", "Comment");
// 2. Write Data Rows
FileWrite(fileHandle,
TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS),
_Symbol,
"BUY",
0.10,
SymbolInfoDouble(_Symbol, SYMBOL_ASK),
"Initial Entry");
FileWrite(fileHandle,
TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS),
_Symbol,
"MODIFY_SL",
0.10,
SymbolInfoDouble(_Symbol, SYMBOL_BID),
"Trailing Stop Step");
// 3. Close File Handle
FileClose(fileHandle);
PrintFormat("Successfully wrote CSV records to %s", filename);
return true;
}
//+------------------------------------------------------------------+
//| Function: Read and parse CSV file records |
//+------------------------------------------------------------------+
bool ReadTradeLogCSV(const string filename, bool useCommon)
{
int flags = FILE_READ | FILE_CSV | FILE_ANSI;
if(useCommon)
flags |= FILE_COMMON;
int fileHandle = FileOpen(filename, flags, ',');
if(fileHandle == INVALID_HANDLE)
{
PrintFormat("Failed to open file %s for reading. Error: %d", filename, GetLastError());
return false;
}
Print("--- Reading CSV Data ---");
int lineNum = 0;
// Loop until end of file
while(!FileIsEnding(fileHandle))
{
// Read each column token
string col1 = FileReadString(fileHandle);
if(FileIsEnding(fileHandle) && col1 == "")
break;
string col2 = FileReadString(fileHandle);
string col3 = FileReadString(fileHandle);
string col4 = FileReadString(fileHandle);
string col5 = FileReadString(fileHandle);
string col6 = FileReadString(fileHandle);
lineNum++;
PrintFormat("Row %d: [%s] | Symbol: %s | Action: %s | Lots: %s | Price: %s | Note: %s",
lineNum, col1, col2, col3, col4, col5, col6);
}
FileClose(fileHandle);
PrintFormat("Finished reading %d rows from %s", lineNum, filename);
return true;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// Demo: Write sample records, then read them back
if(WriteTradeLogCSV(InpFileName, InpUseCommonFolder))
{
ReadTradeLogCSV(InpFileName, InpUseCommonFolder);
}
}
Copy this code into MetaEditor, save it in your MQL5 folder (Experts, Scripts, or Include), and compile with F7.
Generate custom MQL5 code with Pineify AI
Describe the trade execution, indicator calculations, risk management, or data processing logic you need. Pineify produces clean, typed MQL5 source code ready to compile in MetaEditor.
Frequently Asked Questions
Related MQL5 pages
Technical references
Risk and testing note
Past performance is not indicative of future results. Backtest statistics are based on historical data and do not guarantee future profits. Trading involves significant risk of loss. This content is for educational purposes only and does not constitute financial advice.