You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MT4导出OHLC至CSV文件异常求助:仅存2位小数且漏存品种

Fixing MT4 OHLC Export Indicator Issues: Full Precision & All Symbols

Hey there! I’ve tinkered with tons of MT4 export scripts over the years, so let’s fix those two annoying problems you’re dealing with—first the truncated decimal places, then getting data for all your symbols instead of just one.

Let’s Break Down the Problems & Solutions

1. CSV Only Saves 2 Decimal Places

Most default export scripts hardcode Fixed(2) for price formatting, which ignores that different symbols use different decimal counts (e.g., EUR/USD uses 5, USD/JPY uses 2, crypto pairs might use even more). The fix is to use MT4’s built-in _Digits variable, which automatically pulls the correct decimal count for each symbol.

2. Can’t Export All Symbols

The original script probably only targets the symbol of the current chart. We’ll add a loop that iterates through every symbol in your MarketWatch list, pulls its OHLC data, and exports it to separate CSV files (one per symbol, for clarity).

Corrected Full Code

Save this as a MT4 Script (not an indicator) named ExportAllOHLC.mq4:

//+------------------------------------------------------------------+
//|                                                  ExportAllOHLC.mq4 |
//|                        Copyright 2024, MetaQuotes Software Corp. |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Software Corp."
#property version   "1.00"
#property strict

// Customizable inputs for flexibility
input ENUM_TIMEFRAMES Timeframe = PERIOD_H1;
input int StartBar = 0; // 0 = most recent bar
input int BarsToExport = 1000; // Number of bars to grab per symbol

//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
{
   // Get total symbols in MarketWatch
   int totalSymbols = SymbolsTotal(false);
   if(totalSymbols == 0)
   {
      Print("No symbols found in MarketWatch!");
      return;
   }

   // Loop through every symbol in MarketWatch
   for(int symIndex = 0; symIndex < totalSymbols; symIndex++)
   {
      string symbol = SymbolName(symIndex, false);
      // Select the symbol to access its data
      if(!SymbolSelect(symbol, true))
      {
         Print("Couldn't select symbol: ", symbol);
         continue;
      }

      // Create unique filename for each symbol
      string filename = "MQL4/Files/OHLC_" + symbol + "_" + TimeframeToString(Timeframe) + ".csv";
      int fileHandle = FileOpen(filename, FILE_CSV|FILE_WRITE, ";");
      if(fileHandle == INVALID_HANDLE)
      {
         Print("Failed to open file: ", filename, " Error code: ", GetLastError());
         continue;
      }

      // Write CSV header row
      FileWrite(fileHandle, "Date", "Time", "Open", "High", "Low", "Close", "Volume");

      // Calculate valid bar range to avoid out-of-bounds errors
      int endBar = Bars - StartBar - 1;
      int startBarIndex = endBar - BarsToExport + 1;
      if(startBarIndex < 0) startBarIndex = 0;

      // Pull and write OHLC data with full precision
      for(int i = startBarIndex; i <= endBar; i++)
      {
         datetime barTime = iTime(symbol, Timeframe, i);
         // Use _Digits to match the symbol's native decimal precision
         double open = iOpen(symbol, Timeframe, i);
         double high = iHigh(symbol, Timeframe, i);
         double low = iLow(symbol, Timeframe, i);
         double close = iClose(symbol, Timeframe, i);
         long volume = iVolume(symbol, Timeframe, i);

         // Format date/time for readability
         string date = TimeToStr(barTime, TIME_DATE);
         string time = TimeToStr(barTime, TIME_TIME);

         // Write row with correct decimal places
         FileWrite(fileHandle, date, time, 
                   DoubleToString(open, _Digits), 
                   DoubleToString(high, _Digits), 
                   DoubleToString(low, _Digits), 
                   DoubleToString(close, _Digits), 
                   volume);
      }

      // Clean up: close the file
      FileClose(fileHandle);
      Print("Exported ", BarsToExport, " bars for ", symbol, " to ", filename);
   }

   Print("Export finished! Check your MQL4/Files folder for all CSV files.");
}
//+------------------------------------------------------------------+

Key Changes Explained

  • Decimal Precision Fix: Replaced hardcoded decimal formatting with DoubleToString(price, _Digits), where _Digits is MT4’s native variable that matches each symbol’s correct decimal count. No more truncated prices!
  • All Symbols Export: Added a loop using SymbolsTotal() and SymbolName() to iterate through every symbol in your MarketWatch. Each symbol gets its own CSV file (e.g., OHLC_EURUSD_H1.csv).
  • User-Friendly Inputs: Added configurable settings for timeframe, starting bar, and number of bars to export—so you don’t have to edit code to adjust these.
  • Error Handling: Added checks for file access failures and symbol selection issues, so you’ll get clear feedback if something goes wrong.

How to Use

  1. Open MT4, go to Tools > MetaQuotes Language Editor.
  2. Create a new Script, paste the code above, and save it as ExportAllOHLC.
  3. Go back to MT4, drag the script onto any chart (it doesn’t matter which one—the script loops through all symbols).
  4. A window will pop up where you can set your preferred timeframe, start bar, and number of bars to export.
  5. Click OK and wait for the export to finish (check the Experts tab for progress updates).
  6. Find your CSV files in the MQL4/Files folder (access this via File > Open Data Folder in MT4).

内容的提问来源于stack exchange,提问作者I. Я. Newb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:41:15