Problem Description
Solution
To save trade results to a text file (specifically a CSV file for easy analysis in Excel or Python), you need to use the MQL4 File functions.
The following solution is a robust script that iterates through your account's closed trade history and writes the details to a CSV file located in the MQL4/Files directory.
MQL4 Code to Save Trade History
//+------------------------------------------------------------------+
//| SaveTradeHistory.mq4 |
//| Copyright 2023, MetaQuotes |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, Quantitative Trading AI"
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property show_inputs
//--- Input Parameters
input string InpFileName = "TradeReport.csv"; // Name of the file to save
input string InpDelimiter = ","; // Delimiter for CSV (comma is standard)
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// 1. Open the file for writing
// FILE_CSV: Indicates we are working with a CSV format
// FILE_WRITE: Open for writing (will overwrite existing file)
// FILE_ANSI: Use ANSI encoding (standard for simple text files)
int fileHandle = FileOpen(InpFileName, FILE_CSV | FILE_WRITE | FILE_ANSI, InpDelimiter);
// Check if file opened successfully
if(fileHandle == INVALID_HANDLE)
{
Print("Error opening file: ", InpFileName, ". Error Code: ", GetLastError());
return;
}
// 2. Write the Header Row
FileWrite(fileHandle,
"Ticket",
"Symbol",
"Type",
"Lots",
"Open Time",
"Open Price",
"Close Time",
"Close Price",
"Commission",
"Swap",
"Profit",
"Comment",
"MagicNumber"
);
// 3. Iterate through Account History
int totalHistory = OrdersHistoryTotal();
Print("Processing ", totalHistory, " historical orders...");
for(int i = 0; i < totalHistory; i++)
{
// Select the order from history by index
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
{
// Optional: Filter out non-trading entries (like Balance deposits)
// if(OrderType() > OP_SELL) continue;
// Convert Order Type to readable string
string typeStr = GetOrderTypeString(OrderType());
// 4. Write the Order Data
FileWrite(fileHandle,
OrderTicket(),
OrderSymbol(),
typeStr,
DoubleToString(OrderLots(), 2),
TimeToStr(OrderOpenTime(), TIME_DATE | TIME_SECONDS),
DoubleToString(OrderOpenPrice(), 5),
TimeToStr(OrderCloseTime(), TIME_DATE | TIME_SECONDS),
DoubleToString(OrderClosePrice(), 5),
DoubleToString(OrderCommission(), 2),
DoubleToString(OrderSwap(), 2),
DoubleToString(OrderProfit(), 2),
OrderComment(),
OrderMagicNumber()
);
}
}
// 5. Close the file to save changes
FileClose(fileHandle);
Print("Successfully saved trade history to: MQL4/Files/", InpFileName);
}
//+------------------------------------------------------------------+
//| Helper function to convert integer order type to string |
//+------------------------------------------------------------------+
string GetOrderTypeString(int type)
{
switch(type)
{
case OP_BUY: return "BUY";
case OP_SELL: return "SELL";
case OP_BUYLIMIT: return "BUY LIMIT";
case OP_SELLLIMIT:return "SELL LIMIT";
case OP_BUYSTOP: return "BUY STOP";
case OP_SELLSTOP: return "SELL STOP";
case 6: return "BALANCE"; // Deposit/Withdrawal
default: return "UNKNOWN";
}
}
How to Use This Code
-
Create the Script:
- Open MetaEditor (F4 in MT4).
- Create a new Script (File -> New -> Script) and name it
SaveTradeHistory. - Paste the code above into the window.
- Click Compile (F7).
-
Run the Script:
- Go to the MT4 Terminal.
- Drag the
SaveTradeHistoryscript from the Navigator window onto any chart. - You can change the filename in the inputs window if desired.
-
Locate the File:
- Go to File -> Open Data Folder.
- Navigate to
MQL4 -> Files. - You will find
TradeReport.csvthere.
Key Implementation Details
FileOpen: This function creates the file. The flagFILE_CSVhandles the formatting automatically.FILE_WRITEoverwrites the file every time you run the script. If you want to append new trades to an existing file instead, useFILE_READ | FILE_WRITEand seek to the end of the file usingFileSeek.OrdersHistoryTotal&OrderSelect: We useMODE_HISTORYto access closed trades. If you wanted to save currently open positions, you would useMODE_TRADES.FileWrite: This function accepts multiple arguments and writes them to the file separated by the delimiter specified inFileOpen.- Data Formatting: Functions like
DoubleToStringandTimeToStrare used to ensure the data looks clean in the text file (e.g., ensuring prices have the correct number of decimal places).
Q&A
Q: Can I use this inside an Expert Advisor (EA) instead of a script?
A: Yes. You can place the logic inside the OnDeinit() function of your EA. This will save the report automatically when you remove the EA from the chart or when a backtest finishes.
Q: Why can't I find the file on my computer?
A: MT4 uses a "Sandbox" security model. It can only write files to the specific MQL4/Files folder inside your Data Folder. It cannot write to your Desktop or C: drive directly.
Q: How do I filter by Magic Number?
A: Inside the for loop, add a check after OrderSelect:
if(OrderMagicNumber() != MyMagicNumber) continue;