//+------------------------------------------------------------------+ //| OHLC_Export_Script.mq5 | //| Export all available OHLC bars to CSV | //| Output: MQL5\Files\__OHLC.csv | //+------------------------------------------------------------------+ #property strict #property script_show_inputs input string FileName = ""; // Output filename (empty = auto: Symbol_TF_OHLC.csv) void OnStart() { string sym = _Symbol; ENUM_TIMEFRAMES tf = _Period; if(TerminalInfoInteger(TERMINAL_CONNECTED) == 0) { Print("Terminal not connected to server. Cannot download."); return; } // Trigger download and wait for data sync Print("Requesting full history for ", sym, " ", EnumToString(tf), "..."); int prev = 0, cur = Bars(sym, tf); int retries = 0; while(cur < 10 || cur != prev) { prev = cur; Sleep(1000); cur = Bars(sym, tf); retries++; if(retries % 5 == 0) PrintFormat(" Downloaded %d bars so far...", cur); if(retries > 60) { Print("Timeout waiting for data. Exporting what's available."); break; } } if(cur <= 0) { Print("No bars available for ", sym); return; } PrintFormat("Total bars available: %d", cur); string fn = (FileName != "") ? FileName : sym + "_" + EnumToString(tf) + "_OHLC.csv"; int h = FileOpen(fn, FILE_WRITE|FILE_CSV|FILE_ANSI, ','); if(h == INVALID_HANDLE) { Print("Cannot create file: ", fn); return; } FileWrite(h, "Timestamp", "Open", "High", "Low", "Close", "TickVolume", "Spread"); MqlRates r[]; ArraySetAsSeries(r, true); int copied = 0, chunk = 5000; for(int start = 0; start < cur; start += chunk) { int toCopy = MathMin(chunk, cur - start); if(CopyRates(sym, tf, start, toCopy, r) <= 0) break; copied += toCopy; for(int i = 0; i < toCopy; i++) FileWrite(h, TimeToString(r[i].time, TIME_DATE|TIME_MINUTES|TIME_SECONDS), DoubleToString(r[i].open, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)), DoubleToString(r[i].high, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)), DoubleToString(r[i].low, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)), DoubleToString(r[i].close, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)), (long)r[i].tick_volume, (int)r[i].spread); } FileClose(h); PrintFormat("Exported %d bars to %s (MQL5\\Files\\%s)", copied, fn, fn); } //+------------------------------------------------------------------+