def __exit__(self, exc_type, exc_val, exc_tb): """ Закрываем подключение. """ mt5.shutdown() if exc_val: raise ()
def getHistoricalData(self, symbol): print(Fore.YELLOW + 'Getting Historical data on symbol:', symbol) # create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset ticks = None try: ticks = mt5.copy_rates_range(symbol, mt5.TIMEFRAME_M10, self.start_date, self.to_date) print(Fore.BLUE + "Ticks received:", len(ticks)) # shut down connection to the MetaTrader 5 terminal except TypeError: print(Fore.RED + 'failed to get data on symbol:', symbol, 'with error:', mt5.last_error()) print(Style.RESET_ALL) os.system('taskkill /f /im terminal64.exe') exit() mt5.shutdown() # display data on each tick on a new line print("Display obtained ticks 'as is'") #count = 0 #for tick in ticks: # count+=1 # print(tick) # if count >= 10: # break # create DataFrame out of the obtained data ticks_frame = pd.DataFrame(ticks) # convert time in seconds into the datetime format ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') # display data print("\nDisplay dataframe with ticks") print(ticks_frame.head, ticks_frame.shape) print(ticks_frame.info()) return ticks_frame
def historyData(Symbol): mt5.initialize(server="ForexClub-MT5 Demo Server", login=500063649, password="******") # print(mt5.terminal_info()) # print(mt5.version()) listSymbols = mt5.symbols_get() # [x.name for x in listSymbols] # Symbol=np.random.choice(FXmajor, 1)[0] print(Symbol) pointValue = mt5.symbol_info(Symbol).point # mt5.Buy("EURUSD", 0.1,price=11395,ticket=9) Num_velas = 1000 # Copying data to pandas data frame # rates = mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas) rates = mt5.copy_rates_range(Symbol, mt5.TIMEFRAME_H1, datetime(2021, 1, 10), datetime.now()) # rates = mt5.copy_rates_range("ES", mt5.TIMEFRAME_D1, datetime(2019, 1, 15), datetime(2019, 1, 25)) # rates = mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas) # Deinitializing MT5 connection mt5.shutdown() # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame.index = pd.to_datetime(rates_frame['time'], unit='s') rates_frame.columns = [ 'time', 'Open', 'High', 'Low', 'Close', 'tick_volume', 'spread', 'real_volume' ] return rates_frame
def __init__(self): if not mt5.initialize(): print("initialize() failed") mt5.shutdown() exit(1) else: print("initialize ok")
def get_data(self): mt5.initialize() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset utc_from = dt(self.date_from.year, self.date_from.month, self.date_from.day, 00, 00, tzinfo=timezone) utc_to = dt(self.date_to.year, self.date_to.month, self.date_to.day, 23, 59, tzinfo=timezone) if self.time_frame == 0: data_values = mt5.copy_ticks_range(self.currency_type, utc_from, utc_to, mt5.COPY_TICKS_ALL) else: data_values = mt5.copy_rates_range(self.currency_type, self.time_frame, utc_from, utc_to) print(self.currency_type, " Data Points received: ", len(data_values)) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() data_frame = pd.DataFrame(data_values) # print(ticks_frame) return data_frame
def __init__(self, stock): self.stock = stock if not mt5.initialize(): print("initialize() failed") mt5.shutdown() #print('Version: ', mt5.version()) pass
def connect_server(): # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() else: print("MetaTrader Connected")
def convert_csv(timeframe=mt5.TIMEFRAME_D1, bars=1000): def load_data(symbol): try: ticker = pd.DataFrame( mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_D1, 0, bars))['close'].rename(index=symbol) print(f'Symbol {symbol} Bars {BARS} ok') except RuntimeError: print(f'ERRO NO SYMBOL "{symbol}"') mt5.shutdown() quit() return ticker tickers_close = [load_data(symbol) for symbol in symbols] symbol_one = pd.DataFrame( mt5.copy_rates_from_pos(symbols[0], timeframe, 0, bars)) time_tickers = pd.to_datetime(symbol_one['time'], unit='s') mt5.shutdown() df = pd.DataFrame(tickers_close).T df['TIME'] = time_tickers df.set_index('TIME', inplace=True) df.to_csv( f'{str(datetime.now().replace(microsecond=0)).replace(":", "-")}.csv') print( f'From {str(time_tickers.iloc[0]).split(" ")[0]} to {str(time_tickers.iloc[-1]).split(" ")[0]}' )
def load_stocks_1h(stock_name, load_from_datetime, ema_periods=(20, 50, 200)): ''' Loads hourly stock data. :param stock_name: The symbol code, e.g. AUDUSD :param load_from_datetime: This should be a datetime value e.g. dt.datetime.strptime("07/02/2020 15:00:00", "%d/%m/%Y %H:%M:%S") :param ema_periods: A tuple indicating the periods for which EMA should be calculated. :return: Returns a dictionary indexed by time. Each index is then a further dictionary see {dictionary}.keys() for more details ''' mt5.initialize() stock_data = mt5.copy_rates_range(stock_name, mt5.TIMEFRAME_H1, load_from_datetime, dt.datetime.now()) dataset = {} for datapoint in stock_data: dataset[dt.datetime.utcfromtimestamp(datapoint[0])] = { "OPEN": datapoint[1], "HIGH": datapoint[2], "LOW": datapoint[3], "CLOSE": datapoint[4], "VOLUME": datapoint[5], "SPREAD": datapoint[6] } mt5.shutdown() for period in ema_periods: dataset = exponential_moving_average(dataset, period) return dataset
def init_mt5(): if not mt5.initialize( path=path, login=mt5_account, password=mt5_password, server=mt5_server): print("initialize() failed, error code =", mt5.last_error()) mt5.shutdown()
def RequestData(SymbolName, run_time, Day): # 连接到MetaTrader 5 if not mt5.initialize(login=3335660, server="Exness-MT5Real",password="******"): print("initialize() failed") # 请求连接状态和参数 #print(mt5.terminal_info()) # 获取有关MetaTrader 5版本的数据 #print(mt5.version()) try: if run_time == 'H1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_H1, 0, Day) # 通过多种方式获取不同交易品种的柱形图 elif run_time == 'H4': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_H4, 0, Day) elif run_time == 'D1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_D1, 0, Day) elif run_time == 'W1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_W1, 0, Day) except Exception as e: log.error("生成K线图时,获取MT5数据失败........."+str(e)) # 断开与MetaTrader 5的连接 mt5.shutdown() #DATA #print(rates) #PLOT # 从所获得的数据创建DataFrame ticks_frame = pd.DataFrame(rates) ticks_frame=ticks_frame.drop(ticks_frame.index[1]) # 将时间(以秒为单位)转换为日期时间格式 ticks_frame['time']=pd.to_datetime(ticks_frame['time'], unit='s') return ticks_frame
def get_data_mt5(symbol='EURUSD', bars=500, to=0, timeframe='H1'): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() concatenation = 'mt5.TIMEFRAME_' + timeframe evaluated = eval(concatenation) rates = mt5.copy_rates_from_pos(symbol, evaluated, 0, bars) mt5.shutdown() df = pd.DataFrame(rates) df.time = pd.to_datetime(df.time, unit='s') df = df.set_index('time') df['symbol'] = symbol df = df.rename( columns={ 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close', 'tick_volume': 'Volume' }) df = df[[ 'symbol', 'Open', 'High', 'Low', 'Close', 'Volume', 'spread', 'real_volume' ]] return (df)
def __enter__(self): """ Открываем подключение к терминалу """ # подключимся к MetaTrader 5 if not mt5.initialize(path=self.path, server=self.server, login=self.login, password=self.password): print("initialize() failed") mt5.shutdown()
def wrapped(self, *args, **kwargs): if not mt5.initialize(path=self.path, server=self.server, login=self.login, password=self.password): print("initialize() failed") mt5.shutdown() return fn(self, *args, **kwargs) mt5.shutdown()
def __init__(self,symbol:str): # conecte-se ao MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # consultamos o estado e os parâmetros de conexão print(mt5.terminal_info()) # obtemos informações sobre a versão do MetaTrader 5 print(mt5.version()) self.symbol = symbol
def initialize(self): if not Mt5.initialize(): print( 'Initialization failed, check internet connection. You must have Meta Trader 5 installed.' ) Mt5.shutdown() else: print(f'You are running the {self.expert_name} expert advisor,' f' version {self.version}, on symbol {self.symbol}.')
def startTrade(symbol, lot, price, tradeType): deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": tradeType, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_FOK, } # send a trading request result = mt5.order_send(request) # check the execution result print( "1. order_send(): by {} {} lots at {} with deviation={} points".format( symbol, lot, price, deviation)) if result.retcode != mt5.TRADE_RETCODE_DONE: print("2. order_send failed, retcode={}".format(result.retcode)) # request the result as a dictionary and display it element by element result_dict = result._asdict() for field in result_dict.keys(): print(" {}={}".format(field, result_dict[field])) # if this is a trading request structure, display it element by element as well if field == "request": traderequest_dict = result_dict[field]._asdict() for tradereq_filed in traderequest_dict: print(" traderequest: {}={}".format( tradereq_filed, traderequest_dict[tradereq_filed])) print("shutdown() and quit") mt5.shutdown() quit() print("2. order_send done, ", result) print(" opened position with POSITION_TICKET={}".format(result.order)) time.sleep(2) return result
def get_candles(ticker, timeframe, n_candles): """ Establishes connection with the terminal, parses prices, as is, shuts down the connection """ if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() rates = mt5.copy_rates_from_pos(ticker, eval(timeframe), 0, n_candles) mt5.shutdown() return rates
def data_collection(timeframe, n): if not mt5.initialize(): print('failed to connect') quit() timeframe_dict = { 'H1':mt5.TIMEFRAME_H1, 'D1':mt5.TIMEFRAME_D1, 'W1':mt5.TIMEFRAME_W1 } currs = ['EUR', 'GBP', 'AUD', 'NZD', 'USD', 'CAD', 'CHF', 'JPY'] ohlc_dict = {} for curr_no, curr1 in enumerate(currs): for curr2 in currs[curr_no+1:]: curr_pair = curr1 + curr2 #Get candles from the past 3 weeks (exclusive of current week) time_now = pd.Timestamp.now(tz='Etc/UTC') #four_wks_ago = time_now - dt.timedelta(weeks=3) #day_of_wk = dt.timedelta(days=four_wks_ago.isoweekday()%7) #past_4_wks = dt.date(four_wks_ago.year, four_wks_ago.month, four_wks_ago.day) - day_of_wk #ohlc_arr = mt5.copy_rates_range(curr_pair, timeframe_dict[timeframe], # pd.to_datetime(past_4_wks), time_now) ohlc_arr = mt5.copy_rates_from(curr_pair, timeframe_dict[timeframe], time_now, n) column_names = { 'open':'Open', 'high':'High', 'low':'Low', 'close':'Close' } try: ohlc_df = pd.DataFrame(ohlc_arr) ohlc_df.index = pd.to_datetime(ohlc_df.iloc[:, 0], unit='s') ohlc_df = ohlc_df.drop(columns=['time']) ohlc_df = ohlc_df.rename(columns=column_names) ohlc_dict[curr_pair+'_ohlc_df'] = ohlc_df except: print('ERROR OCCURRED IN: ', curr_pair) mt5.shutdown() return ohlc_dict
def load_data(symbol): try: ticker = pd.DataFrame( mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_D1, 0, bars))['close'].rename(index=symbol) print(f'Symbol {symbol} Bars {BARS} ok') except RuntimeError: print(f'ERRO NO SYMBOL "{symbol}"') mt5.shutdown() quit() return ticker
def get_rates_from_date(initials, start_date, end_date, show_last=False): mt5.initialize() values = mt5.copy_rates_range( initials, mt5.TIMEFRAME_M1, start_date, end_date ) mt5.shutdown() return values if show_last else values[:-1]
def getDataFromMetatrader(currency="EURUSD", timeframe=mt5.TIMEFRAME_H1, fromdate=datetime.now(), count=70000): if not mt5.initialize(): print("initialize() failed") mt5.shutdown() eurusd_rates = mt5.copy_rates_from(currency, timeframe, fromdate, count) mt5.shutdown() df = pd.DataFrame(data=eurusd_rates) df['time'] = pd.to_datetime(df['time'], unit='s') return df
def Check(self, lot, symbol): symbol_info = mt5.symbol_info(symbol) if symbol_info is None: print(symbol, "not found.") mt5.shutdown() quit() # if the symbol is unavailable in MarketWatch, add it if not symbol_info.visible: print(symbol, "is not visible, trying to switch on") if not mt5.symbol_select(symbol,True): print("symbol_select({}}) failed, exit",symbol) mt5.shutdown() quit()
def get_candles(ticker, timeframe, n_candles): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() rates = mt5.copy_rates_from_pos(ticker, eval(timeframe), 0, n_candles) mt5.shutdown() rates_frame = pd.DataFrame(rates) # Sets timezone to Moscow time just for convinience rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') rates_frame.set_index('time', inplace=True) rates_frame.index = rates_frame.index.tz_localize(tz='Etc/UTC') rates_frame.index = rates_frame.index.tz_convert('Europe/Moscow') rates_frame.rename(columns=COL_NAMES, inplace=True) return rates_frame
def test0(): if not mt5.initialize(): print("initialize() failed") mt5.shutdown() print('Version:', mt5.version()) t1 = TimeUtility.xmTime(2020, 9, 18, 15, 12) t0 = t1 - TimeUtility.deltaMinute(5) values = mt5.copy_rates_range("US30Cash", mt5.TIMEFRAME_M1, t0, t1) for value in values: t = pd.to_datetime(value[0], unit='s') naive_time = t.to_pydatetime() print(t, naive_time, TimeUtility.toXm(naive_time), value) mt5.shutdown() pass
def getSymbolData(symbol): selected = mt5.symbol_select(symbol, True) if not selected: print("Failed to select " + symbol) mt5.shutdown() quit() symbolInfoDictionarie = mt5.symbol_info_tick(symbol)._asdict() symbolInfoDictionarie['time'] = convertTimeStampToDate( symbolInfoDictionarie['time']) data = json.dumps(symbolInfoDictionarie, indent=4, sort_keys=True) print(data) return data mt5.shutdown()
def login(self): # display data on the MetaTrader 5 package #print("MetaTrader5 package author: ", mt5.__author__) #print("MetaTrader5 package version: ", mt5.__version__) # establish connection to the MetaTrader 5 terminal if not mt5.initialize(self.PATH): print("initialize() failed, error code =", mt5.last_error()) quit() authorized = mt5.login(self.login_id, password=self.password) if not authorized: print('LOGIN FAILED!!!') mt5.shutdown() quit() else: print("Login with account: ", str(self.login_id), " successfull!")
def __init__(self, buyingCurrency, sellingCurrency, timeFrame, lotSize, cycleTime): logging.basicConfig(format='%(asctime)s,%(levelname)s,%(message)s', datefmt='%m/%d/%Y,%H:%M:%S') self.timeFrame = timeFrame self.logger = logging.getLogger('TraderLog') self.logger.setLevel(logging.DEBUG) self.advisorsList = list() if not mt5.initialize(): logger.error("initialize() failed, error code =" + mt5.last_error()[2]) mt5.shutdown() raise Exception(errorMsg) # request connection status and parameters print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version())
def test0(): if not mt5.initialize(): print("initialize() failed") mt5.shutdown() print('Version:', mt5.version()) t1 = nowXm() t0 = t1 - deltaMinute(5) values = mt5.copy_rates_range("US30Cash", mt5.TIMEFRAME_M1, t0, t1) for value in values: t = pd.to_datetime(value[0], unit='s') pytime = t.to_pydatetime() print(t, pytime, toXm(pytime), value) mt5.shutdown() pass
def __init__(self): # Connect to MetaTrader5. Opens if not already open. # Logger self.__log = logging.getLogger(__name__) # Open MT5 and log error if it could not open if not MetaTrader5.initialize(): self.__log.error("initialize() failed") MetaTrader5.shutdown() # Print connection status self.__log.debug(MetaTrader5.terminal_info()) # Print data on MetaTrader 5 version self.__log.debug(MetaTrader5.version())