import MetaTrader5 as mt5
import pandas as pd
from datetime import datetime
import pytz
import os

def fetch_history_to_csv(symbol="XAUUSD", timeframe=mt5.TIMEFRAME_M5, days=60):
    if not mt5.initialize():
        print("initialize() failed")
        mt5.shutdown()
        return None
        
    utc_to = datetime.now(pytz.timezone("Etc/UTC"))
    bars_to_fetch = days * 300 
    
    rates = mt5.copy_rates_from(symbol, timeframe, utc_to, bars_to_fetch)
    mt5.shutdown()
    
    if rates is None or len(rates) == 0:
        print(f"Failed to fetch data for {symbol}")
        return None
        
    df = pd.DataFrame(rates)
    df['time'] = pd.to_datetime(df['time'], unit='s')
    df.set_index('time', inplace=True)
    df.rename(columns={'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'tick_volume': 'Volume'}, inplace=True)
    
    os.makedirs("data/offline", exist_ok=True)
    filename = f"data/offline/mt5_{symbol}_{days}d_m5.csv"
    df.to_csv(filename)
    print(f"MT5 data exported to: {filename} ({len(df)} bars)")
    return filename

if __name__ == "__main__":
    fetch_history_to_csv()
