63 lines
1.6 KiB
Python
63 lines
1.6 KiB
Python
|
|
# Copyright 2025, MetaQuotes Ltd.
|
||
|
|
# https://www.mql5.com/en/users/johnhlomohang/
|
||
|
|
|
||
|
|
from datetime import datetime
|
||
|
|
import MetaTrader5 as mt5
|
||
|
|
import pandas as pd
|
||
|
|
import pytz
|
||
|
|
|
||
|
|
# Display MetaTrader5 package information
|
||
|
|
print("MetaTrader5 package author:", mt5.__author__)
|
||
|
|
print("MetaTrader5 package version:", mt5.__version__)
|
||
|
|
|
||
|
|
# Pandas display settings
|
||
|
|
pd.set_option('display.max_columns', 500)
|
||
|
|
pd.set_option('display.width', 1500)
|
||
|
|
|
||
|
|
# Initialize MT5 connection
|
||
|
|
if not mt5.initialize():
|
||
|
|
print("initialize() failed, error code =", mt5.last_error())
|
||
|
|
quit()
|
||
|
|
|
||
|
|
# Define symbol
|
||
|
|
symbol = "XAUUSD.m"
|
||
|
|
|
||
|
|
# Ensure the symbol is available
|
||
|
|
if not mt5.symbol_select(symbol, True):
|
||
|
|
print("Failed to select symbol:", symbol)
|
||
|
|
mt5.shutdown()
|
||
|
|
quit()
|
||
|
|
|
||
|
|
# Set timezone to UTC
|
||
|
|
timezone = pytz.timezone("Etc/UTC")
|
||
|
|
|
||
|
|
# Define date range
|
||
|
|
utc_from = datetime(2026, 1, 1, tzinfo=timezone)
|
||
|
|
utc_to = datetime(2026, 4, 1, tzinfo=timezone)
|
||
|
|
|
||
|
|
# Get historical rates
|
||
|
|
rates = mt5.copy_rates_range(symbol, mt5.TIMEFRAME_H1, utc_from, utc_to)
|
||
|
|
|
||
|
|
# Shutdown MT5 connection
|
||
|
|
mt5.shutdown()
|
||
|
|
|
||
|
|
# Validate data
|
||
|
|
if rates is None or len(rates) == 0:
|
||
|
|
print("No data retrieved. Check symbol or date range.")
|
||
|
|
else:
|
||
|
|
|
||
|
|
print("First 10 bars:")
|
||
|
|
for rate in rates[:10]:
|
||
|
|
print(rate)
|
||
|
|
|
||
|
|
# Convert to DataFrame
|
||
|
|
rates_frame = pd.DataFrame(rates)
|
||
|
|
|
||
|
|
# Convert time
|
||
|
|
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
|
||
|
|
|
||
|
|
# Save to CSV
|
||
|
|
filename = "XAUUSD_H1.csv"
|
||
|
|
rates_frame.to_csv(filename, index=False)
|
||
|
|
|
||
|
|
print("\nData saved to:", filename)
|