Hands-On Guide: Building an Automated Trade Journal and CSV Exporter in
Keeping a meticulous trading journal is one of the most important habits of a successful systematic trader. However, manually writing down every entry, exit, profit, and loss in a spreadsheet is tedious and prone to human error. By writing a custom MQL5 function that automatically logs closed trade history directly into a structured CSV file, you can maintain a flawless performance journal effortlessly.
In this hands-on tutorial, we will build a trade-logging script that tracks and exports closed order history in MetaTrader 5.
---------------------------------------------------
1. Why Automated Trade Journaling Matters
Automated logging ensures:
• Every single backtest or live execution is permanently recorded with exact timestamps.
• You can easily import your CSV file into Microsoft Excel or Python pandas to analyze win rates, maximum drawdown, and profit factors offline.
• You eliminate the emotional blind spots that come with manual record-keeping.
---------------------------------------------------
2. Complete MQL5 Trade Journal Exporter Code
Open your Expert Advisor or create a new script in MetaEditor (F4) and add the following journaling function:
#include <Trade\Trade.mqh>
input string JournalFileName = "MQL5_Trade_Journal.csv";
void ExportClosedTradesToCSV()
{
// Select all historical deals
if(!HistorySelect(0, TimeCurrent()))
{
Print("Failed to select history.");
return;
}
int totalDeals = HistoryDealsTotal();
// Open file for writing (FILE_WRITE | FILE_CSV | FILE_ANSI)
int fileHandle = FileOpen(JournalFileName, FILE_WRITE|FILE_CSV|FILE_ANSI, ",");
if(fileHandle == INVALID_HANDLE)
{
Print("Error opening journal file for writing. Error code: ", GetLastError());
return;
}
// Write CSV Header
FileWrite(fileHandle, "DealTicket", "OrderTicket", "Time", "Symbol", "Type", "Volume", "Price", "Profit", "Commission");
// Loop through historical deals
for(int i = 0; i < totalDeals; i++)
{
ulong dealTicket = HistoryDealGetTicket(i);
if(dealTicket > 0)
{
long order = HistoryDealGetInteger(dealTicket, DEAL_ORDER);
string symbol = HistoryDealGetString(dealTicket, DEAL_SYMBOL);
long type = HistoryDealGetInteger(dealTicket, DEAL_TYPE);
double volume = HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
double price = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);
double comm = HistoryDealGetDouble(dealTicket, DEAL_COMMISSION);
datetime time = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);
// Only log entry/exit trade deals (excluding balance adjustments)
if(type == DEAL_TYPE_BUY || type == DEAL_TYPE_SELL)
{
string typeStr = (type == DEAL_TYPE_BUY) ? "BUY" : "SELL";
string timeStr = TimeToString(time, TIME_DATE|TIME_MINUTES|TIME_SECONDS);
FileWrite(fileHandle, dealTicket, order, timeStr, symbol, typeStr, volume, price, profit, comm);
}
}
}
FileClose(fileHandle);
Print("Trade journal successfully exported to ", JournalFileName);
}
---------------------------------------------------
3. Triggering the Journal on Deinitialization
You can call your export function inside the `OnDeinit()` event so your journal updates automatically every time your EA or script finishes running:
void OnDeinit(const int reason)
{
// Export all closed trades to CSV upon termination
ExportClosedTradesToCSV();
Print("Trade Journal Exporter Deinitialized.");
}
---------------------------------------------------
4. Locating Your Journal File
1. Press F7 in MetaEditor to compile your code (ensure 0 errors).
2. In MetaTrader 5, click **File** > **Open Data Folder**.
3. Navigate to `MQL5\Files` to find your generated `MQL5_Trade_Journal.csv` spreadsheet ready for analysis!
---------------------------------------------------
Final Thoughts
Automating your trade journal bridges the gap between raw execution and data-driven optimization. With 20 technical guides published, you now possess a complete, production-ready laboratory framework!
Stay tuned for more advanced tech labs as our platform continues to expand!
Comments
Post a Comment