File size: 1,235 Bytes
a6fae72 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import MetaTrader5 as mt5
import pandas as pd
from datetime import datetime
from pathlib import Path
# ====== Config ======
symbols = ['DXYm','EURUSDm','GBPUSDm','USDJPYm','USDCADm','XAUUSDm']
timeframe = mt5.TIMEFRAME_D1 # timeframe Day
num_bars = 3650 # จำนวนแท่งย้อนหลังที่จะดึง
output_dir = Path("Datasource")
output_dir.mkdir(exist_ok=True, parents=True)
# ====== Connect MT5 ======
if not mt5.initialize():
print("❌ MT5 Initialize failed")
mt5.shutdown()
exit()
# ====== Loop symbol ======
for symbol in symbols:
print(f"Fetching {symbol} ...")
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, num_bars)
if rates is None:
print(f"❌ Failed to get rates for {symbol}")
continue
# convert to DataFrame
df = pd.DataFrame(rates)
df['time'] = pd.to_datetime(df['time'], unit='s') # timestamp -> datetime
df = df[['time', 'open', 'high', 'low', 'close', 'tick_volume']]
# save to CSV
csv_path = output_dir / f"{symbol}.csv"
df.to_csv(csv_path, index=False)
print(f"✅ Saved {csv_path}")
# ====== Shutdown MT5 ======
mt5.shutdown()
print("All done!")
|