Summary: A practical guide to building an MQL4 script that exports MT4 trading history to CSV format, including custom date range selection and file output configuration.




Most MT4 users know you can right-click the "Account History" tab and save a report as HTML. But what if you need that data in CSV format for Excel analysis, custom reporting, or feeding into another system? The built-in "Save Report" function only gives you HTML. If you want clean CSV output, you have to build it yourself using MQL4's file functions.

I ran into this problem about a month ago when a client wanted to import their entire two-year trading history into a custom risk analysis dashboard they'd built in Python. The HTML report was too messy to parse reliably, and manually copy-pasting from the terminal wasn't an option with 800+ trades.

Step 1: Understand where MT4 actually lets you save files



Before writing any code, you need to know the file path rules. According to the MQL4 documentation, working files can only be saved in specific folders:

  • Terminal_folder\MQL4\Files\ - for general use

  • Terminal_folder\Tester\Files\ - for files used during testing

  • Terminal_folder\history\server_name\ - for history files (using FileOpenHistory)


  • The third option is the most interesting. The official MQL4 reference explains that FileOpenHistory() "can be useful to form own history data for a non-standard symbol and/or period". The file you create in the history folder "can be opened offline, no data pumping is needed to chart it."

    That's the key insight most people miss. You're not just saving data for external use - you're creating files that MT4 itself can recognize and display offline.

    Step 2: Build the script - the "FileOpen" approach



    The simplest approach is using the standard FileOpen() function. Here's a script I put together that exports all closed trades to a CSV file in the MQL4\Files folder:

    ``cpp
    //+------------------------------------------------------------------+
    //| ExportHistoryToCSV.mq4 |
    //| Script to export account history to CSV |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2025"
    #property link "https://www.fxear.com"
    #property version "1.00"
    #property strict

    //+------------------------------------------------------------------+
    //| Script program start function |
    //+------------------------------------------------------------------+
    void OnStart()
    {
    // Ask user for date range
    datetime fromDate = D'2024.01.01 00:00';
    datetime toDate = TimeCurrent();

    // Open file in MQL4\Files folder
    int fileHandle = FileOpen("AccountHistory.csv",
    FILE_WRITE|FILE_CSV|FILE_SHARE_READ,
    ',');

    if(fileHandle == INVALID_HANDLE)
    {
    Print("Failed to open file. Error: ", GetLastError());
    return;
    }

    // Write header
    FileWrite(fileHandle, "Ticket","Symbol","Type","Lots","OpenTime",
    "CloseTime","OpenPrice","ClosePrice","SL","TP",
    "Profit","Swap","Commission");

    // Loop through history
    int totalOrders = OrdersHistoryTotal();
    for(int i = totalOrders - 1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
    {
    // Skip if still open
    if(OrderCloseTime() == 0) continue;

    string orderType = (OrderType() == OP_BUY) ? "Buy" :
    (OrderType() == OP_SELL) ? "Sell" : "Other";

    FileWrite(fileHandle,
    OrderTicket(),
    OrderSymbol(),
    orderType,
    DoubleToString(OrderLots(), 2),
    TimeToString(OrderOpenTime(), TIME_DATE|TIME_SECONDS),
    TimeToString(OrderCloseTime(), TIME_DATE|TIME_SECONDS),
    DoubleToString(OrderOpenPrice(), Digits),
    DoubleToString(OrderClosePrice(), Digits),
    DoubleToString(OrderStopLoss(), Digits),
    DoubleToString(OrderTakeProfit(), Digits),
    DoubleToString(OrderProfit(), 2),
    DoubleToString(OrderSwap(), 2),
    DoubleToString(OrderCommission(), 2));
    }
    }

    FileClose(fileHandle);
    Print("Export complete. File saved to MQL4\\Files\\AccountHistory.csv");
    }
    `

    Step 3: The more powerful approach - FileOpenHistory for offline charts



    Here's where it gets interesting. If you want to save history data in a format that MT4 can actually use as an offline chart, you need FileOpenHistory(). The official MQL4 documentation shows this example:

    `cpp
    int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ);
    if(handle<1)
    {
    Print("Cannot open file USDX240.HST");
    return(false);
    }
    // work with file
    // ...
    FileClose(handle);
    `

    This opens a file in the
    history\server_name folder. The .HST format is binary - MT4's native history file format. If you write data in the correct structure, you can create an offline chart of any custom symbol.

    There's a catch that isn't in the docs: on Windows 11, I've noticed the permission model is tighter. If you try to write to
    history\server_name and get permission errors, check that your terminal isn't running in a restricted AppContainer context. Moving the terminal to a non-system folder (like C:\MT4) often fixes this.

    Step 4: Setting the custom period programmatically



    The manual approach is selecting "Custom Period" in the Account History tab. But you can also control what data is available by calling
    OrderSelect() with MODE_HISTORY and filtering by date in your script, just like I did in Step 2.

    One thing I wish someone had told me earlier: the
    OrdersHistoryTotal() function returns the currently loaded history based on what's visible in the terminal's Account History tab. If you haven't loaded a custom period in the UI, you might only get the last few months. So either pre-load the data via the UI, or use OrderSelect()` in a loop to pull everything the server has available.

    Step 5: The HTML report shortcut (if you just need quick data)



    If you're in a hurry and don't want to write code, the HTML report actually contains everything in a structured format:

  • Right-click in Account History

  • Select "Custom Period" and choose your dates

  • Right-click again and select "Save as Detailed Report"

  • Open the HTML file in a browser


  • At the bottom of the report, you'll see key metrics like Gross Profit, Net Profit, Profit Factor, Drawdown percentages, and a balance equity graph. If you just need numbers for a quick analysis, this works fine.

    But if you need the raw trade-by-trade data in a clean format for programming, the script approach is the only way to go.

    Reference: MQL4 Documentation – FileOpenHistory (docs.mql4.com), MQL4 Book – File Operations (book.mql4.com), MetaTrader 4 Help – Account History Reports (help.metaquotes.net).

    This article is originally published on FXEAR.com, original content, reproduction without authorization is prohibited.