def login(self): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() authorized = mt5.login(self.account, password=self.password) if not authorized: print("failed to connect at account #{}, error code: {}".format( self.account, mt5.last_error()))
def connect(account=None, passw=None, mt5path=None): #if not se.connect(): #print(“Error on connection”, se.last_error()) #exit(): if account is None and passw is None: if mt5path is None: res = mt5.initialize() else: res = mt5.initialize(mt5path) else: account = int(account) if mt5path is None: res = mt5.initialize(login=account, password=passw) else: res = mt5.initialize(mt5path, login=account, password=passw) global ac, path, datapath, commonDatapath, company, platform, connected if res != True: if account is None: print('Error trying to connect to last account!!', ' Error code:', mt5.last_error()) else: print('Error trying to connect to account: ', account, ' Error code:', mt5.last_error()) return False info = mt5.account_info() if info.margin_so_mode != mt5.ACCOUNT_MARGIN_MODE_RETAIL_NETTING: print( "It is NOT netting, but the stock exchange should be netting trade mode!! Error!!" ) # B3 is also Netting!! return False #elif info.margin_so_mode ==mt5.ACCOUNT_MARGIN_MODE_RETAIL_HEDGING: # print("It is hedding, not netting") #else: # print("It is something elese!!") #if info.margin_so_mode ==mt5.ACCOUNT_MARGIN_MODE_RETAIL_NETTING: # print("It is netting, not hedding") # se is Netting!! #elif info.margin_so_mode ==mt5.ACCOUNT_MARGIN_MODE_RETAIL_HEDGING: # print("It is hedding, not netting") #else: # print("It is something elese!!") if res: ac = mt5.terminal_info() path = ac.path datapath = ac.data_path commonDatapath = ac.commondata_path company = ac.company platform = ac.name connected = True return res
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 send_transaction(ticker, volume, type): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() if type == 'sell': type = mt5.ORDER_TYPE_SELL elif type == 'buy': type = mt5.ORDER_TYPE_BUY request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": ticker, "volume": volume, 'type': type, "type_time": mt5.ORDER_TIME_GTC } result = mt5.order_send(request) if result is not None: return result.comment else: return
def DataRequest(ticker, rates, plot): print("establish connection to MetaTrader 5 terminal...") if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() # request rates from ticker tickerRates = mt5.copy_rates_from(ticker, mt5.TIMEFRAME_M1, datetime.now(), rates) #print those values print("Number of rates returned: " + str(len(tickerRates))) #create dataframe from rates and handle datetime as string for interpolation on pyplot tickerFrame = pd.DataFrame(tickerRates) tickerFrame['time'] = pd.to_datetime(tickerFrame['time'], unit='s') tickerFrame['time'] = tickerFrame['time'].astype(str) if (plot): plt.plot(tickerFrame['time'], tickerFrame['close'], 'b-', label='close') plt.show() return tickerFrame
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 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 open_buy(): global result_order_buy # establish connection to the MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =",mt5.last_error()) quit() # prepare the buy request structure symbol_info = mt5.symbol_info(symbol) if symbol_info is None: print(symbol, "not found, can not call order_check()") 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() price = mt5.symbol_info_tick(symbol).ask request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_BUY, "price": price, "sl": price - sl_buy * point, "tp": price + tp_buy * point, "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(" buy opened position with POSITION_TICKET={}".format(result.order)) result_order_buy=result.order return(result_order_buy)
def build_in_memory_database(pairs: list, initial_period='1s', days=60, _from=None) -> dict: ''' Use threading to get all data into memory. Structured into a dict with the name of a pair as the key and the value being a dataframe of 1 second periods. ''' if not mt5.initialize( login=mt5_login, server="ICMarkets-Demo", password=mt5_pass): print("initialize() failed, error code =", mt5.last_error()) quit() # Create this timestamp outside of loop so it doesn't change. _to = datetime.now() if _from is None: _from = _to - pd.Timedelta(f'{days} day') with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for pair in pairs: futures.append( executor.submit(_request_ticks_and_resample, pair=pair, period=initial_period, _from=_from, _to=_to)) database = {} for future in concurrent.futures.as_completed(futures): data = future.result() database[data[0]] = data[1] # unpack name of pair and dataframe # confirmed working return database
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 get_ticks(self, symbol, from_date, to_date): """ Gets OHLC price data for the specified symbol. :param symbol: The name of the symbol to get the price data for. :param from_date: Date from when to retrieve data :param to_date: Date where to receive data to :return: Tick data for symbol as dataframe """ ticks_dataframe = None # Get ticks from MT5 ticks = MetaTrader5.copy_ticks_range(symbol, from_date, to_date, MetaTrader5.COPY_TICKS_ALL) # If ticks is None, there was an error if ticks is None: error = MetaTrader5.last_error() self.__log.error(f"Error retrieving ticks for {symbol}: {error}") else: self.__log.debug(f"{len(ticks)} ticks retrieved for {symbol}.") # Create dataframe from data and convert time in seconds to datetime format try: ticks_dataframe = pd.DataFrame(ticks) ticks_dataframe['time'] = pd.to_datetime( ticks_dataframe['time'], unit='s') except RecursionError: self.__log.warning("Error converting ticks to dataframe.") return ticks_dataframe
def checkOrder(req): global inbacktest if inbacktest: #print('Esta em backtest. bts=')#, bts) return backtest.get_balance(bts) #else: # print('NAO esta em backtest') if req is None: return False result = mt5.order_check(req) #print('result=',result, 'req=',req) if result is None: # error setLastError(mt5.last_error()) return False d = result._asdict() #margin - Margem requerida para a operação de negociação # margin_free - Margem livre que sobrará após a execução da operação de negociação # balance - Valor de saldo após a execução da operação de negociação #for k in d.keys(): # print('{} = {}',k,d[k]) if isSellOrder(req): if req['volume'] > get_shares( req['symbol']): #bloqueia ordem a descoberto return False else: return True if d['balance'] >= 0: # checa se não ficaria negativo com a execução return True else: setLastError( 'Trade would make the balance negative! Therefore, it does not check!' ) return False
def f_be_de_parte1(param_data): # Filtrado de operaciones ganadoras (operaciones ancla) param_data['capital_acm'] = param_data['profit_acm'] + 100000 ganadoras = param_data[param_data.Profit > 0] ganadoras = ganadoras.reset_index(drop=True) ganadoras["Ratio"] = (ganadoras["Profit"] / abs(ganadoras["profit_acm"])) df_anclas = ganadoras.loc[:, [ 'close_time', "open_time", 'Type', "Symbol", 'Profit', "profit_acm", "capital_acm", "Ratio", "Time", "Time.1", "Price", "Volume" ]] df_anclas = df_anclas.reset_index(drop=True) # Criterio de selección de operaciones abiertas por cada ancla ocurrencias = [] file_list = [] for x in df_anclas.index: df = param_data[ (param_data.open_time <= df_anclas["close_time"][x]) & (param_data.close_time > df_anclas["close_time"][x] )].loc[:, ['Type', 'Symbol', 'Volume', 'Profit', "Price", "pips"]] df['close_time_ancla'] = pd.Timestamp(df_anclas['close_time'][x]) file_list.append(df) ocurrencias.append(len(df)) all_df = pd.concat(file_list, ignore_index=True) # Descarga de precios para cada operación abierta float_price = [] if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() for i in range(len(all_df)): utc_from = datetime(all_df['close_time_ancla'][i].year, all_df['close_time_ancla'][i].month, all_df['close_time_ancla'][i].day) utc_to = utc_from + timedelta(1) symbol = all_df['Symbol'][i] ticks = mt5.copy_ticks_range(symbol, utc_from, utc_to, mt5.COPY_TICKS_ALL) ticks_frame = pd.DataFrame(ticks) ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') tick_time = next(x for x in ticks_frame['time'] if x >= all_df['close_time_ancla'][i]) price = ticks_frame.loc[ticks_frame['time'] == tick_time] if all_df["Type"][i] == "buy": price = price["bid"].mean() else: price = price["ask"].mean() float_price.append(price) float_prices = pd.DataFrame(columns=['float_price'], data=float_price) all_df = all_df.join(float_prices) all_df = f_columnas_pips_v2(all_df) all_df["float_P&L"] = (all_df["Profit"] / all_df["pips"]) * all_df["float_pips"] all_df = all_df[all_df['float_P&L'] < 0].reset_index(drop=True) return all_df, df_anclas
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 get_rates_range(self): rates = mt5.copy_rates_range(self.currency_pair_name, self.timeframe, self.datetime_from, self.datetime_to) if rates != None: return rates else: raise RuntimeError('copy_rates_range() failed. error code =', mt5.last_error())
def getLastError(): global lastErrorText if lastErrorText == None or lastErrorText == "": return mt5.last_error() else: aux = lastErrorText lastErrorText = None return aux
def getOrders(): # returns a dataframe with all active orders orders = mt5.orders_get() if orders == None or len(orders) == 0: print("No orders, error code={}".format(mt5.last_error())) return None else: print("Total orders:", len(orders)) df = pd.DataFrame(list(orders), columns=orders[0]._asdict().keys()) return df
def connect(account): account = int(account) mt5.initialize() authorized = mt5.login(account) if authorized: print("Connected: Connecting to MT5 Client") else: print("Failed to connect at account #{}, error code: {}".format( account, mt5.last_error()))
def Initialization(account, password, timeout): mt5.initialize() # Connection with mt5 via socket authorized = mt5.login(account, password, timeout=timeout) if authorized == True: print("Initialization Finished") if authorized == False: print("Initialization Failed: Here is the error code:", mt5.last_error()) return True
def get_positions(ticker): if not mt5.initialize(**LOGIN_DATA): print("initialize() failed, error code =", mt5.last_error()) quit() positions = mt5.positions_get(symbol=ticker) if (positions is None) or (len(positions) == 0): return None else: positions = pd.DataFrame(list(positions), columns=positions[0]._asdict().keys()) return positions
def get_orders(): if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() orders = mt5.orders_get() print(orders) if orders is None: return None else: orders = pd.DataFrame(list(orders), columns=orders[0]._asdict().keys()) return orders
def init(): with open('symbols.txt') as file: symbols = json.load(file) if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() print('Loading symbols...') return symbols
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 login(self): print(Fore.BLUE+'\nlogging in...') if mt5.login(self.acc_no,password = self.password,server = self.default_server): print(Fore.GREEN+'logged in successfully into acc:',self.acc_no,'on server:',self.default_server) print(Style.RESET_ALL) print(Back.GREEN+'ACCOUNT INFORMATION') print(Style.RESET_ALL) for k,v in mt5.account_info()._asdict().items(): print('{:>50}'.format(k),v) else:print(Fore.RED+'log in failure with error:', mt5.last_error()) print('\n')
def connect_account(account): """Login to MetaTrader5 account using API.""" account = int(account) mt5.initialize() authorized = mt5.login(account) if authorized: print('Connected: Connecting to MT5 Client') else: print( 'Failed to connect at account #{}, error code: {}'.format( account, mt5.last_error(), ), )
def run(ticker): #print(ticker) if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() info = mt5.symbol_info(ticker) if ticker not in USA_STOCKS: df_1min = get_candles( ticker, 'mt5.TIMEFRAME_M1', 5000).loc[:, ['open', 'high', 'low', 'close', 'volume']] else: # Получаем с яху, потому что с МТ5 с 15 минутным лагом df_1min = get_american_candles( ticker, '3d', '1m').loc[:, ['open', 'high', 'low', 'close', 'volume']] df_5min = df_1min.resample('5Min').agg(AGG_DICT) df_hour = df_1min.resample('60Min').agg(AGG_DICT) df_day = df_1min.resample('1D').agg(AGG_DICT) rsi = RSI() df_1min = rsi.get_value_df(df_1min) df_5min = rsi.get_value_df(df_5min) signal = check_trade_conditions(ticker, df_day, df_hour, df_5min, df_1min) if signal is not None: signal_is_sent = check_signal_is_sent(ticker) position = get_positions(ticker) if (not signal_is_sent) and (position is None): acceptable_PERC_loss = (open_close_5min_dif_mean[ticker] + open_close_5min_dif_std[ticker]) last_close = df_5min.close[-1] trade_size = calculate_trade_size(ticker, acceptable_PERC_loss, last_close) contract_size = info.trade_contract_size min_volume = info.volume_min trade_size = round(trade_size / contract_size / min_volume) trade_size = trade_size * min_volume direction = 'sell' if signal == 'sell' else 'buy' send_message(ticker + ' ' + direction + ' ' + str(trade_size)) print(send_transaction(ticker, trade_size, direction)) cur_time = datetime.now().time() print(cur_time, ticker, direction, trade_size) set_signal_is_sent_flag(ticker)
def connect(self, account_id: int): """connect to the specific MT5 account Args: account_id (int):the MT5 account you want to connect to """ mt5.initialize() authorized = mt5.login(account_id) if authorized: print("Connected: Connecting to MT5 Client") else: print("Failed to connect at account #{}, error code: {}".format( account_id, mt5.last_error()))
def getOrders(): # returns a dataframe with all active orders if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return orders = mt5.orders_get() if orders == None or len(orders) == 0: print("No orders, error code={}".format(mt5.last_error())) return None else: print("Total orders:", len(orders)) df = pd.DataFrame(list(orders), columns=orders[0]._asdict().keys()) return df
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 __init__(self, login=50581877, server="Alpari-MT5-Demo", password="******"): self.login = login self.server = server self.password = password self.terminal = mt5 print("MetaTrader5 package author: ", self.terminal.__author__) print("MetaTrader5 package version: ", self.terminal.__version__) if not self.terminal.initialize(login=self.login, server=self.server, password=self.password): print("initialize() failed, error code =", mt5.last_error()) quit() print(self.terminal.terminal_info()) print(self.terminal.version()) pass