import MetaTrader5 as mt5
import pytz
from datetime import datetime
from op_forex.model.MT5Account import MT5AccountInfo
from tqz_extern.tqz_constant import SymbolType

# from tqz_extern.pandas_operator import pandas
import pandas


if not mt5.initialize(login=MT5AccountInfo.get_account_id(), server=MT5AccountInfo.get_account_server(), password=MT5AccountInfo.get_account_password()):
    print("initialize() failed, error code =", mt5.last_error())
    quit()

class MT5HistoryDataDump:
    timezone = pytz.timezone("Etc/UTC")

    utc_from = datetime(2014, 1, 1, tzinfo=timezone)
    utc_to = datetime(2024, 8, 4, hour=0, tzinfo=timezone)

    @classmethod
    def run(cls):
        all_symbols = MT5AccountInfo.get_symbols(symbol_type=SymbolType.STOCK_INDEX) + MT5AccountInfo.get_symbols(symbol_type=SymbolType.SPOTS) + MT5AccountInfo.get_symbols(symbol_type=SymbolType.FOREX) + MT5AccountInfo.get_symbols(symbol_type=SymbolType.CRYPTO)
        for single_symbol in all_symbols:
            for timeframe, mt5_timeframe in MT5AccountInfo.get_timeframe_map().items():
                his_bars = mt5.copy_rates_range(single_symbol, mt5_timeframe, cls.utc_from, cls.utc_to)
                his_bars_df = pandas.DataFrame(his_bars)
                his_bars_df['time'] = pandas.to_datetime(his_bars_df['time'], unit='s')

                his_bars_df.to_csv(
                    f'./his_data/{single_symbol}_{timeframe}.csv',
                    index=False
                )

        print('yes, is login.')
        mt5.shutdown()


if __name__ == '__main__':
    MT5HistoryDataDump.run()