def Generator(curr="GBPUSD", period=14): Done = True rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2) c = 0 open_list = [] high_list = [] low_list = [] close_list = [] while Done: lasttick = mt5.symbol_info_tick(curr) bid, ask = round(lasttick.bid, 5), round(lasttick.ask, 5) mid = round((bid + ask) / 2, 5) c += 1 check = rates[1][0] #rates = mt5.copy_rates_from_pos("GBPUSD", mt5.TIMEFRAME_M1, 0, 1) while check == rates[1][0]: rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2) open, high, low, close, tickvol, spread = rates[0][1], rates[0][ 2], rates[0][3], rates[0][4], rates[0][5], rates[0][6] open_list.append(open) high_list.append(high) low_list.append(low) close_list.append(close) #if c>period: cci = CCI(high_list, low_list, close_list, period) if len(cci) == 0: cci = np.append(cci, 0) rsi = RSI(pd.Series(close_list), period) yield np.array( [bid, ask, mid, round(rsi.values[-1], 5), cci[-1] / 100])
def dollarizer(asset, dollarpair, tframe, period): mt5.symbol_select(dollarpair) time.sleep(2) asset_rates = pd.DataFrame( mt5.copy_rates_from_pos( asset, tframe, 0, period)).drop(columns=['spread', 'real_volume', 'tick_volume']) dollar_rates = pd.DataFrame( mt5.copy_rates_from_pos( dollarpair, tframe, 0, period)).drop(columns=['spread', 'real_volume', 'tick_volume']) asset_rates['time'] = pd.to_datetime(asset_rates['time'], unit='s') dollar_rates['time'] = pd.to_datetime(dollar_rates['time'], unit='s') asset_rates.set_index(keys=['time'], inplace=True) dollar_rates.set_index(keys=['time'], inplace=True) if dollarpair[3:6] == 'USD': # quoted in dollar dollarised_asset = asset_rates[[ 'open', 'high', 'low', 'close' ]] * dollar_rates[['open', 'high', 'low', 'close']] else: # based in dollar dollarised_asset = asset_rates[[ 'open', 'high', 'low', 'close' ]] / dollar_rates[['open', 'high', 'low', 'close']] dollarised_asset.rename(columns={'high': 'low', 'low': 'high'}) # dollarised_asset['vol'] = (asset_rates['tick_volume'] + dollar_rates['tick_volume']) / 2 dollarised_asset.dropa() return dollarised_asset
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 _generator(filename,curr='GBPUSD',period=14, header=False, split=0.8, mode='train',spread=.005): df = pd.read_csv(filename) if "Name" in df: df.drop('Name',axis=1,inplace=True) _stock = Sdf.retype(df.copy()) _stock.get('cci_14') _stock.get('rsi_14') _stock.get('dx_14') _stock = _stock.dropna(how='any') min_max_scaler = preprocessing.MinMaxScaler((-1, 1)) np_scaled = min_max_scaler.fit_transform(_stock[['rsi_14', 'cci_14','dx_14','volume']]) df_normalized = pd.DataFrame(np_scaled) df_normalized.columns = ['rsi_14', 'cci_14','dx_14','volume'] df_normalized['bid'] = _stock['close'].values df_normalized['ask'] = df_normalized['bid'] + spread df_normalized['mid'] = (df_normalized['bid'] + df_normalized['ask'])/2 split_len=int(split*len(df_normalized)) if(mode=='train'): raw_data = df_normalized[['ask','bid','mid','rsi_14','cci_14','dx_14','volume']].iloc[:split_len,:] elif mode=='test': raw_data = df_normalized[['ask', 'bid', 'mid', 'rsi_14', 'cci_14','dx_14','volume']].iloc[split_len:,:] if mode=='trade': if not mt5.initialize(): print("initialize() failed, error code =",mt5.last_error()) quit() Done=True collect = pd.DataFrame(mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 10)) c=0 open_list=collect['open'].values high_list=collect['high'].values low_list=collect['low'].values close_list=collect['close'].values rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2) while Done: lasttick=mt5.symbol_info_tick(curr) bid, ask = round(lasttick.bid,5), round(lasttick.ask,5) mid = round((bid + ask)/2,5) check = rates[1][0] #rates = mt5.copy_rates_from_pos("GBPUSD", mt5.TIMEFRAME_M1, 0, 1) while check==rates[1][0]: rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2) open, high, low, close, tickvol, spread = rates[0][1], rates[0][2], rates[0][3], rates[0][4], rates[0][5], rates[0][6] open_list = np.append(open_list, open) high_list = np.append(high_list,high) low_list = np.append(low_list, low) close_list = np.append(close_list,close) ADX = adx(high_list, low_list, close_list, period) cci = CCI(high_list, low_list, close_list, period) rsi = RSI(pd.Series(close_list), period) yield np.array([bid, ask, mid, round(rsi.values[-1],5), cci[-1]/100, ADX[-1]/100, tickvol]) c+=1 else: for index, row in raw_data.iterrows(): yield row.to_numpy()
def synthesize(symbol1, symbol2, periods): """Takes 2 MT5 currency symbols with common USD and returns a DataFrame of OCHLV of the price of first symbol denominated in second symbol. note: Requires both the assets to have USD in common, ie. either denomination or base.""" # Asset on which the pricing will be based. base_asset = pd.DataFrame( mt5.copy_rates_from_pos(symbol1, mt5.TIMEFRAME_H1, 1, period)) # Asset to quote the base in, generally a currency. quote_asset = pd.DataFrame( mt5.copy_rates_from_pos(symbol2, mt5.TIMEFRAME_H1, 1, period)) # converting timestamps to Datetime-index. base_asset['time'] = pd.to_datetime(base_asset['time'], unit='s') quote_asset['time'] = pd.to_datetime(quote_asset['time'], unit='s') baseAsset_quote = mt5.symbol_info(symbol1).currency_profit if symbol1[0:3] == 'USD': # Dollar based ie. USDJPY, USDCHF... if symbol2[3:6] == 'USD': basequote = (1 / base_asset[['open', 'high', 'low', 'close']]) * ( 1 / quote_asset[['open', 'high', 'low', 'close']]) basequote.rename(columns={ 'high': 'low', 'low': 'high' }, inplace=True) else: # basequote = quote_asset[['open', 'high', 'low', 'close']] / base_asset[['open', 'high', 'low', 'close']] basequote = (1 / base_asset[['open', 'high', 'low', 'close']] ) * quote_asset[['open', 'high', 'low', 'close']] basequote.rename(columns={ 'high': 'low', 'low': 'high' }, inplace=True) elif symbol1[ 3: 6] == 'USD' or baseAsset_quote == 'USD': # Dollar quoted ie. EURUSD, SnP500... if symbol2[3:6] == 'USD': basequote = base_asset[[ 'open', 'high', 'low', 'close' ]] / quote_asset[['open', 'high', 'low', 'close']] # basequote.rename(columns={'high':'low', 'low':'high'}, inplace=True) else: basequote = base_asset[[ 'open', 'high', 'low', 'close' ]] * quote_asset[['open', 'high', 'low', 'close']] # averaging volume. basequote['vol'] = ( (base_asset['tick_volume'] + quote_asset['tick_volume']) / 2) basequote.set_index(keys=[base_asset['time']], inplace=True) return basequote
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 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 get_datas(currency, timeframe, nb_bars): # Get forex datas eurusd_M5 = mt5.copy_rates_from_pos(currency, timeframe, 1, nb_bars) pd_eurusd = pd.DataFrame(eurusd_M5) # Get indicators # CCI pd_eurusd["CCI_M5"] = talib.CCI(pd_eurusd["high"], pd_eurusd["low"], pd_eurusd["close"], timeperiod=14) # Relative Strength Index pd_eurusd["RSI_M5"] = talib.RSI(pd_eurusd["close"], timeperiod=14) # Remove first empty lines of M30 for i in range(0, 7): if pd_eurusd["time"].iloc[0] % 1800 == 0: break else: pd_eurusd = pd_eurusd.drop([i]) # Adjust M30 open, high, low, close values pd_eurusd["open_M30"], pd_eurusd["high_M30"], pd_eurusd[ "low_M30"], pd_eurusd["close_M30"] = M30create(pd_eurusd, nb_bars=len(pd_eurusd)) # Test fractal *** signalperiod = 15, signalsmaperiod = 30 pd_eurusd["CustFractSignal"], pd_eurusd[ "CustFractSignalSMA"] = fractal_ind(pd_eurusd, nb_bars=len(pd_eurusd)) return pd_eurusd
def processo(self): plt.ion() while True: rates = mt5.copy_rates_from_pos(self.mercado, self.time_frame, 0, self.time_range) rates_frame = pd.DataFrame(rates) rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') self.time_list = [] self.open_list = [] self.close_list = [] self.grafico_contruction(rates_frame) self.n = str(self.time_list[-1]).replace('-', ' ').replace(':', ' ') self.timer_att_fibolines_4min() self.plot_fibo() plt.pause(0.00001) plt.clf() print(Grafico.close_list)
def mt5_ohlc_request(symbol, timeframe, num_candles=70): ''' Get a formatted df from MT5 ''' # A request to MT5 can occasionally fail. Retry a few times to connect # and a few more times to receive data for _ in range(2): if mt5.initialize(login=mt5_login, server=mt5_server, password=mt5_pass): for _ in range(5): rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, num_candles) if rates is not None: if len(rates) > 0: df = pd.DataFrame(rates) df = _format_mt5_data(df) return df print(f'\n ~~~ Request to MT5 failed. [{symbol} {timeframe}] ~~~') return # If init failed pause before retry time.sleep(0.1) print("MT5 initialize() failed, error code =", mt5.last_error())
def get_candles(self, timeframe, count=100): """Get bars from the MetaTrader5 terminal starting from the current one. Args: timeframe (str): M1/M2/M3/M4/M5/M6/M10/M12/M15/M20/M30/H1/H2/H3/H4/H6/H8/H12/D1/W1/MN1 count (int, optional): Specify the number of bars to retrieve. Defaults to 100. """ offset = self.__calc_offset() result = [] candles = mt5.copy_rates_from_pos(self.symbol, self.timeframe[timeframe], 0, count) for candle in candles: timestamp = (datetime.fromtimestamp(candle[0]) - timedelta(hours=offset)).isoformat() row = { 'timestamp': timestamp, 'open': candle[1], 'high': candle[2], 'low': candle[3], 'close': candle[4], 'volume': candle[5], 'spread': candle[6] } result.append(row) return result
def acquireWithDic(self, timeframe:Timeframe, size=99999): d = mt5.copy_rates_from_pos(self.stock, timeframe.constant , 0, size) data = self.convert2Array(d) array = self.toDicArray(data) dic = {} dic['name'] = self.stock dic['timeframe'] = timeframe.symbol dic['length'] = len(data) dic['data'] = array return dic
def scrapeWithDic(self, timeframe, size=99999): d = mt5.copy_rates_from_pos(self.stock, setting.timeframeConstant(timeframe) , 0, size) data = self.convert2Array(d) array = self.toDicArray(data) dic = {} dic['name'] = self.stock dic['timeframe'] = timeframe dic['length'] = len(data) dic['data'] = array return dic
def per_change(symbol, tframe, period): mt5.symbol_select(symbol) for i in range(2): rateFrame = pd.DataFrame( mt5.copy_rates_from_pos(symbol, tframe, 0, period)) time.sleep(1 / 2) # pcnt_change = (float(rateFrame.tail(1)['close']) - float(rateFrame.head(1)['close'])) / float(rateFrame.tail(1)['close']) * 100 pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) / rateFrame.iloc[(period - 1), 4]) * 100 return pcnt_change
def simulador(self): days = self.months * 20 for i in range(0, days): self.valor_inicial = 0 self.tempos = [] self.stop = 0 self.take = 0 self.lines = False self.first_looping = 1 self.registro_tempo = 0 self.key_fibo = 0 self.ponto = self.ponto_inicial while self.ponto >= self.ponto_final: # get 10 GBPUSD D1 bars from the current day rates = mt5.copy_rates_from_pos(self.mercado, self.time_frame, self.ponto, self.time_range) self.ponto -= 1 # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') self.time_list = [] self.open_list = [] self.close_list = [] self.high_list = [] self.low_list = [] # Montagem e atualização do gráfico self.grafico_simulador(rates_frame) self.media_movel(rates_frame) # str do tempo self.n = str(self.time_list[-1]).replace('-', ' ').replace( ':', ' ') # Atualização dos valores das linhas de Fibonacci self.timer_att_fibolines_4min() # Plotagem das linhas de Fibonacci self.plot_fibo() plt.pause(.0001) plt.clf()
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 per_change(symbol, tframe, period): mt5.symbol_select(symbol) for i in range(2): rateFrame = pd.DataFrame(mt5.copy_rates_from_pos(symbol, tframe, 1, period)) time.sleep(1/2) # pcnt_change = (float(rateFrame.tail(1)['close']) - float(rateFrame.head(1)['close'])) / float(rateFrame.tail(1)['close']) * 100 pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) / rateFrame.iloc[(period - 1), 4]) * 100 if symbol[3:6] == 'USD': # Dollar Quoted pairs. return pcnt_change else: # Dollar Based pairs. return - (pcnt_change)
def plotter(): # getting the selections selection = assetListBox.curselection()[0] asset = asset_dict[assetListBox.get(selection)] currency = denomination_dict[opMenuVar.get()] periods = periodEntryVar.get() if currency is None: # No currency is selected. synthetic_asset = pd.DataFrame( mt5.copy_rates_from_pos( asset, mt5.TIMEFRAME_H1, 1, periods)).drop(columns=['spread', 'real_volume']) synthetic_asset['time'] = pd.to_datetime(synthetic_asset['time'], unit='s') synthetic_asset.set_index(keys=['time'], inplace=True) else: # Cross-currency is selected synthetic_asset = synthesize(asset, currency, periods) synthetic_asset.dropna(inplace=True) # Calculaating Simple Moving averages synthetic_asset['SMA 1'] = synthetic_asset['close'].rolling( sma1boxVar.get()).mean() synthetic_asset['SMA 2'] = synthetic_asset['close'].rolling( sma2boxVar.get()).mean() # Calculating Standard-deviation. synthetic_asset['pct_change'] = synthetic_asset['close'].pct_change() * 100 synthetic_asset['std-dev'] = synthetic_asset['pct_change'].ewm( stddevVar.get()).std() candle_stick_data = fplt.PandasDataSource( synthetic_asset[['open', 'close', 'high', 'low']]) ax, ax2 = fplt.create_plot(title=f'{asset}/{currency}', rows=2) candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax) # Plotting SMAs sma1 = fplt.plot(synthetic_asset['SMA 1'], legend=f'{sma1boxVar.get()} SMA', ax=ax) sma2 = fplt.plot(synthetic_asset['SMA 2'], legend=f'{sma2boxVar.get()} SMA', ax=ax) # Plotting Std-dev stdDevPlot = fplt.plot(synthetic_asset['std-dev'], legend=f'Std Dev {stddevVar.get()}', ax=ax2) fplt.add_text(pos=(synthetic_asset.index[-1], synthetic_asset['std-dev'].iloc[-1]), s=f"{synthetic_asset['std-dev'].iloc[-1].round(3)}", ax=ax2) fplt.show()
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_current_bars(symbol, timeframe, count): """ :param symbols: str :param timeframe: str, '1H' :param count: int :return: df """ timeframe = timeModel.get_txt2timeframe(timeframe) rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count) # 0 means the current bar rates_frame = pd.DataFrame(rates, dtype=float) rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') rates_frame = rates_frame.set_index('time') return rates_frame
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 per_change(symbol, tframe, period): mt5.symbol_select(symbol) for i in range(2): rateFrame = pd.DataFrame( mt5.copy_rates_from_pos( symbol, tframe, 0, period)).drop(columns=['spread', 'real_volume', 'tick_volume']) time.sleep(1 / 2) # ((current close - previous open)/previous close) * 100 pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) / rateFrame.iloc[(period - 1), 4]) * 100 # return pcnt_change return pcnt_change.__round__(3)
def getData(numBefore, timePeriod, signal, timeDict): # Match the mt5 trading time zone (UMT+3) # timezone = pytz.timezone("Etc/GMT-3") # endDate = dt.now() # The most recent time # fmt = '%Y-%m-%d %H:%M:%S' # endDate = dt.strptime(a.strftime(fmt), fmt) # timeBefore = (int(timePeriod) * numBefore)*60 # In seconds # delta = datetime.timedelta(seconds=timeBefore) # startDate = endDate - delta rates = mt5.copy_rates_from_pos(signal, timeDict[timePeriod], 0, numBefore) ratesDf = pd.DataFrame(rates) return ratesDf
def __init__(self, symbol, time_frame, start_pos, period): self.time = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['time'] self.open = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['open'] self.high = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['high'] self.low = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['low'] self.close = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['close'] self.tick_volume = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['tick_volume'] self.spread = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['spread'] self.real_volume = Mt5.copy_rates_from_pos(symbol, time_frame, start_pos, period)['real_volume']
def per_change(symbol, tframe, period): mt5.symbol_select(symbol) denomination = mt5.symbol_info(symbol).currency_profit if denomination != 'USD': rateFrame = dollarizer(symbol, dollarPair(denomination), tframe, period) for i in range(2): rateFrame = pd.DataFrame( mt5.copy_rates_from_pos( symbol, tframe, 0, period)).drop(columns=['spread', 'real_volume', 'tick_volume']) time.sleep(1 / 2) # ((current close - previous open)/previous close) * 100 pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) / rateFrame.iloc[(period - 1), 4]) * 100 return pcnt_change.__round__(3)
def get_stock_by_bars(stocks, bars, timeframe): """ get prices for N number os periods """ data = None for i, stock in enumerate(stocks): # get prices from MT5 rates = mt5.copy_rates_from_pos(stock, timeframe, 0, bars) rates_frame = pd.DataFrame(rates) # convert timestamp rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') # creates a new dataframe with all each stock rates_frame['stock'] = stock if i == 0: data = rates_frame else: data = data.append(rates_frame) return data
def test(): # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() print('Version:', mt5.version()) #dji = mt5.copy_rates_range('US30Cash', mt5.TIMEFRAME_M30, Now() - DeltaDay(2), Now()) #print(dji) # request 1000 ticks from EURAUD euraud_ticks = mt5.copy_ticks_from("US30Cash", datetime(2020,4,17,23), 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(2020,1,27,13), datetime(2020,1,28,13), mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(2020,1,28,13), 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(2020,1,27,13), datetime(2020,1,28,13)) #print(eurusd_rates) # shut down connection to MetaTrader 5 mt5.shutdown() return
def update_info(curr_pair): global X_train, X_test, y_train, y_test, X_lately, df COIN_rates = mt5.copy_rates_from_pos(curr_pair, mt5.TIMEFRAME_M1, 0, 240) df = pd.DataFrame(COIN_rates) try: df.set_index('time', drop=True, inplace=True) df.drop(['spread', 'real_volume', 'open'], axis=1, inplace=True) except: pass forecast_col = 'close' forecast_out = 60 df['label'] = df[forecast_col].shift(-forecast_out) X = np.array(df.drop(['label'], 1)) X = preprocessing.scale(X) X_lately = X[-forecast_out:] y = np.array(df['label']) X_train, X_test, y_train, y_test = model_selection.train_test_split( X, y, test_size=0.3) return X_train, X_test, y_train, y_test, X_lately, df
print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version()) start_date=datetime(2021,1,27,10) end_date=datetime(2021,1,27,11) # request 1000 ticks from EURAUD #datetime(year,month,day,hour) euraud_ticks = mt5.copy_ticks_from("EURAUD", start_date, 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 audusd_ticks = mt5.copy_ticks_range("AUDUSD", start_date, end_date, mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1,start_date, 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, start_date, end_date) # shut down connection to MetaTrader 5 mt5.shutdown() #DATA print('euraud_ticks(', len(euraud_ticks), ')') for val in euraud_ticks[:10]: print(val) print('audusd_ticks(', len(audusd_ticks), ')') for val in audusd_ticks[:10]: print(val) print('eurusd_rates(', len(eurusd_rates), ')') for val in eurusd_rates[:10]: print(val)
import mplfinance as mpf # from matplotlib.dates import num2date # Initializing MT5 connection import MetaTrader5 as mt5 # mt5.WaitForTerminal() #%% mt5.initialize() print(mt5.terminal_info()) print(mt5.version()) Num_velas = 1000 # Copying data to pandas data frame stockdata = pd.DataFrame() rates = mt5.copy_rates_from_pos("EURUSD", 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.asfreq(freq='T') rates_frame.columns = [ 'time', 'Open', 'High', 'Low', 'Close', 'tick_volume', 'spread', 'real_volume' ] mpf.plot(rates_frame, type='candle') #%%