How To Download FOREX Data From MetaTrader5 | Algorithmic Trading With Python For Beginners

import datetime
import pytz
import pandas as pd
import MetaTrader5 as mt5
import numpy as np
frame_M15 = mt5.TIMEFRAME_M15 # 15-minute time
frameframe_M30 = mt5.TIMEFRAME_M30 # 30-minute time frame
frame_H1 = mt5.TIMEFRAME_H1 # Hourly time frame
frame_H4 = mt5.TIMEFRAME_H4 # 4-hour time frame
frame_D1 = mt5.TIMEFRAME_D1 # Daily time frame
frame_W1 = mt5.TIMEFRAME_W1 # Weekly time frame
frame_M1 = mt5.TIMEFRAME_MN1 # Monthly time frame
assets = ['EURUSD', 'USDCHF', 'GBPUSD', 'USDCAD', 'BTCUSD','ETHUSD' 'XAUUSD', 'XAGUSD', 'SP500m', 'UK100']
def get_quotes(time_frame, year=2024, month=1, day=1, asset="EURUSD"):
    if not mt5.initialize():
        print("initialize() failed, error code =", mt5.last_error())
        quit()

    timezone = pytz.timezone("America/New_York")

# America/New_York
# Europe/London
# Europe/Paris
# Asia/Tokyo
# Australia/Sydney


    time_from = datetime.datetime(year, month, day, tzinfo=timezone)
    time_to = datetime.datetime.now(timezone) + datetime.timedelta(days=1)

    print(f"Fetching data for {asset} from {time_from} to {time_to} with timeframe {time_frame}")

    rates = mt5.copy_rates_range(asset, time_frame, time_from, time_to)

    if rates is None:
        print(f"No data for {asset} in the specified range.")
        return None

    rates_frame = pd.DataFrame(rates)
    return rates_frame
def mass_import(asset_index, time_frame):
    asset = assets[asset_index]
    data = get_quotes(frame_D1 if time_frame == 'D1' else frame_H1, 2024, 6, 12, asset=asset)

    if data is None or data.empty:
        print(f"No data returned for {asset} on {time_frame} timeframe.")
        return None

    print(f"Data for {asset} on {time_frame} timeframe:\n", data.head())
    data_values = data.iloc[:, 1:5].values.round(decimals=5)
    return data_values
# Fetch data for ETHUSD on the Daily time frame
my_data = mass_import(1, 'D1')

if my_data is not None:
    print("Fetched Data:\n", my_data)
else:
    print("No data fetched.")