def check(n, count_wins, count_losses, j, curr_pair): if n > 0: txt = "buy" else: txt = "sell" while True: spread = round( mt5.symbol_info(curr_pair).ask - mt5.symbol_info(curr_pair).bid, 7) print("\r", txt, ", current profit: ", mt5.account_info().profit, ", spread: ", round(spread * 10, 4), flush=True) if mt5.account_info().profit > 0.02: count_wins += 1 win(count_wins, count_losses, curr_pair) break elif mt5.account_info().profit <= -0.1: count_losses += 1 loss(count_wins, count_losses, curr_pair) break else: pass k = (1 + j) * 30 print("checking price in: ", k, " seconds.") time.sleep(k) return count_wins, count_losses
def check(n, count_wins, count_losses): if n > 0: txt = "buy" else: txt = "sell" while True: spread = round( mt5.symbol_info("USDJPY").ask - mt5.symbol_info("USDJPY").bid, 7) print("\r", txt, ", current profit: ", mt5.account_info().profit, ", spread: ", round(spread * 10, 4), flush=True) if mt5.account_info().profit > 0.03: count_wins += 1 win(n, count_wins, count_losses) break elif mt5.account_info().profit < -0.21: count_losses += 1 loss(n, count_wins, count_losses) break else: pass time.sleep(0.2) return count_wins, count_losses
def __init__(self, magic, symbol): mt5.initialize() self.magic = magic self.symbol = symbol self.no_orders = mt5.orders_total() self.no_positions = mt5.positions_total() self.balance = mt5.account_info()._asdict()['balance'] self.leverage = mt5.account_info()._asdict()['leverage'] self.order_time = mt5.ORDER_TIME_GTC self.order_tt = None
def Login(self): if not mt5.initialize(login=self.username, server=self.server, password=self.password): print("initialize() failed, error code =", mt5.last_error()) quit() authorized = mt5.login(self.username, password=self.password) if authorized: account_info = mt5.account_info() if account_info != None: # convert the dictionary into DataFrame and print account_info_dict = mt5.account_info()._asdict() df=pd.DataFrame(list(account_info_dict.items()), columns=['property','value']) print(df) else: print("Failed to connect to trade account 25115284 with password=gqz0343lbdm, error code =", mt5.last_error()) quit()
def print_terminal_info(): # request connection status and parameters print(mt5.terminal_info()) # request account info print(mt5.account_info()) # get data on MetaTrader 5 version print(mt5.version())
def connect(account=None, passw=None): #if not b3.connect(): #print(“Error on connection”, b3.last_error()) #exit(): if account == None and passw == None: res = mt5.initialize() else: res = mt5.initialize(login=account, password=passw) global ac, path, datapath, commonDatapath, company, platform, connected info = mt5.account_info() if info.margin_so_mode != mt5.ACCOUNT_MARGIN_MODE_RETAIL_NETTING: print( "It is NOT netting, but B3 should be netting trade mode!! Error!!" ) # B3 is 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") # B3 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 __init__(self): __account, __open_positon = mt.account_info(), mt.positions_get() """leverage = __account[2] balance = __account[10] limit_orders = __account[3] equity = __account[13] margin = __account[14] margin_free = __account[15]""" profit = __account[12] margin_level = round(__account[16], 2) name = __account[24] if len(__open_positon) > 0: exchange_rate = __open_positon[0][10] new_exchange_rate = __open_positon[0][13] symbol = __open_positon[0][16] try: if len(__open_positon) > 0: self.get_malgo(name, margin_level, profit, exchange_rate, new_exchange_rate, symbol) self.get_ticks() else: self.get_ticks() except Exception as e: print(e)
def getFreeMargin(): if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return return mt5.account_info().margin_free
def get_account(self): """Get info on the current trading account. Returns: dict: Account information """ account_info = mt5.account_info()._asdict() return account_info
def get_balance(): global inbacktest if inbacktest: #print('Esta em backtest. bts=')#, bts) return backtest.get_balance(bts) #else: # print('NAO esta em backtest') return mt5.account_info().balance
def account_info(): if not connected: print( "In order to use this function, you must be connected to the Stock Exchange. Use function connect()" ) return account_info = mt5.account_info() return account_info
def calc_position_size(self, symbol): print(f"Calculation position size for: {symbol}") balance = mt5.account_info().balance pip_value = constants.get_pip_value(symbol, self.account_currency) # Lot size = (balance * risk) / pip value * stop loss lot_size = (float(balance) * (float(self.risk) / 100)) / (pip_value * self.stop_loss) lot_size = round(lot_size, 2) return lot_size
def __init__(self): self.info = mt5.account_info() #Info tuple self.name = self.info.name #Account holders name self.server = self.info.server #Server name self.profit = self.info.profit #Current P/L self.balance = self.info.balance #money before taking any position self.equity = self.info.equity #balance +- Profit/Loss self.margin = self.info.margin #Collatral paid to the broker self.free_margin = self.info.margin_free #Usable amount self.margin_level = f"{self.info.margin_level:.2f}%" #paid margin as a percentage of equity
def getAfforShares(assetId, money=None, price=None): if money == None: money = mt5.account_info().margin_free if price == None: close = mt5.symbol_info_tick(assetId).last else: close = price step = mt5.symbol_info(assetId).volume_step free = 0 while free * close < money: free = free + step return free - step
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 accountInfo(): #acc=se.accountInfo() # it returns a dictionary #acc['login'] # Account id #acc['balance'] # Account balance in the deposit currency # acc['equity'] # Account equity in the deposit currency #acc['margin'] #Account margin used in the deposit currency #acc['margin_free'] # Free margin of an account in the deposit currency #acc['assets'] # The current assets of an account # acc['name'] #Client name # acc['server'] # Trade server name # acc['currency'] # Account currency, BRL for Brazilian Real account_info = mt5.account_info() #print("account info") return account_info
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 accountInfo(): #acc=b3.accountInfo() # it returns a dictionary #acc['login'] # Account id #acc['balance'] # Account balance in the deposit currency # acc['equity'] # Account equity in the deposit currency #acc['margin'] #Account margin used in the deposit currency #acc['margin_free'] # Free margin of an account in the deposit currency #acc['assets'] # The current assets of an account # acc['name'] #Client name # acc['server'] # Trade server name # acc['currency'] # Account currency, BRL for Brazilian Real if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return account_info = mt5.account_info() #print("account info") return account_info
def _lot_size(risk, df, i, symbol): r''' Automatically set lot size based on desired risk %. Set the risk % as a decimal for the first arg. ''' symb_info = mt5.symbol_info(symbol) acc_info = mt5.account_info() # get the pip value (of 0.01 lot) pip_val = symb_info.trade_tick_value # get the distance from entry to sl in pips distance = abs(df.loc[i, 'entry'] - df.loc[i, 'sl']) distance /= symb_info.point * 10 # min loss loss_with_min_lot = distance * pip_val # Divide risk per trade by loss_with_min_lot risk_per_trade = risk * acc_info.equity lot_size = risk_per_trade // loss_with_min_lot return lot_size
def getAfforShares(assetId, money=None, price=None): if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return if money == None: money = mt5.account_info().balance if money <= 0: return 0.0 if price == None: close = mt5.symbol_info_tick(assetId).last else: close = price step = mt5.symbol_info(assetId).volume_step free = 0 while free * close < money: free = free + step return free - step
def pget_affor_shares(assetId, price, money=None, volumeStep=None): if not connected: print( "In order to use this function, you must be connected to the Stock Exchange. Use function connect()" ) return if money is None: money = mt5.account_info().balance if money <= 0: return 0.0 if price is None: close = mt5.symbol_info_tick(assetId).last else: close = price if volumeStep is None: step = get_volume_step(assetId) else: step = volumeStep free = 0 while free * close < money: free = free + step return free - step
def summary(send=True): """ returns a summary of your positions/performance (positions DataFrame, total spent, account info) :send: boolean, decides whether the info gets sent to telegram or not """ try: df = pd.DataFrame(list(mt5.positions_get()), columns=mt5.positions_get()[0]._asdict().keys()) df.drop(['time_update', 'time_msc', 'time_update_msc', 'external_id'], axis=1, inplace=True) df["proportion"] = df["volume"] / df["volume"].sum() img = img_portfolio(df["proportion"], df["symbol"]) conn = sqlite3.connect("../data/orders.db") c = conn.cursor() spent = c.execute("""SELECT SUM(total_price) FROM (SELECT price*volume AS total_price FROM open);""") for i in spent: total_spent = i[0] info = mt5.account_info() if send: send_image(image_file=img) text = f"Balanço: R${info.balance}\nEquity: R${info.equity}\nTotal investido: R${total_spent}" requests.post( f"https://api.telegram.org/bot{TELE_TOKEN}/sendMessage?chat_id={CHAT_ID}&text={text}" ) os.remove(img) return df, spent, info except Exception as e: print(e)
import MetaTrader5 as mt5 import threading import datetime from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QTime, QDateTime from PyQt5.QtWidgets import QMessageBox from PyQt5.QtGui import QFont UI = importlib.import_module("traderUI12") trade = importlib.import_module("spooksFX") # tradeCalc = importlib.import_module("Trading Tool") # TODO IF YOU CHANGE 'Trader' EVERYTHING NEEDS CHANGING Trader = trade.TradeSession(magic=916848650, symbol="GBPJPY") balance = mt5.account_info()._asdict()["balance"] leverage = mt5.account_info()._asdict()["leverage"] # Calc = tradeCalc.TradingTool(balance=balance, leverage=leverage) # TODO If you are doing high frequency trading / scalping, need to deal with re-quotes class PopupMessages: def __init__(self, title, icon, text, fontsize): self.font = QFont() self.font.setPointSize(fontsize) # 15 is a good size self.title = title self.icon = icon self.text = text
def getBalance(): return mt5.account_info().balance
def login(self, account, server, password): print("当前登录的账号 = ", account) account = mt5.login(account, server=server, password=password) self._account_info = mt5.account_info() print("当前登录的账号信息 = ", self._account_info)
mt5.initialize() # account number in the top left corner of the MT5 terminal window # the terminal database password is applied if connection data is set to be remembered account_number = 555 authorized = mt5.login(account_number) if authorized: print(f'connected to account #{account_number}') else: print( f'failed to connect at account #{account_number}, error code: {mt5.last_error()}' ) # store the equity of your account account_info = mt5.account_info() if account_info is None: raise RuntimeError('Could not load the account equity level.') else: equity = float(account_info[10]) #crypto sign and keywords CRYPTO = 'BTCUSD' keywords = ['Bitcoin', 'bitcoin', 'BITCOIN', 'btc', 'BTC'] #Get Technoking's latest tweet def get_elons_tweet(): """Get Elon's last tweet by user ID""" tweets = tweepy.Cursor(api.user_timeline, id="44196397",
while True: data = self.conn.recv(10000) self.cummdata += data.decode("utf-8") if not data: break self.conn.send(bytes(calcregr(self.cummdata), "utf-8")) return self.cummdata def __del__(self): self.sock.close() # Connecting to Trade Account, Throwing an error code if failed authorized = mt5.login(accout_number, password="******") if authorized: print(mt5.account_info()) # Trading Account Data else: print("Failed to connect to trade account, error code=", mt5.last_error) print(mt5.terminal_info()) print(mt5.version()) now = datetime.now( ) # Now specifically for the purpose of getting the data and placing the trades right now gbpusd_ticks = mt5.copy_ticks_from("GBPUSD", now, 1, mt5.COPY_TICKS_ALL) eurusd_ticks = mt5.copy_ticks_from("EURUSD", now, 1, mt5.COPY_TICKS_ALL) audusd_ticks = mt5.copy_ticks_from("AUDUSD", now, 1, mt5.COPY_TICKS_ALL) usdjpy_ticks = mt5.copy_ticks_from("USDJPY", now, 1, mt5.COPY_TICKS_ALL) start = input(
import MetaTrader5 as mt5 # display data on the MetaTrader 5 package print("MetaTrader5 package author: ", mt5.__author__) print("MetaTrader5 package version: ", mt5.__version__) # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() # get account currency account_currency = mt5.account_info().currency print("Account сurrency:", account_currency) # 准备请求结构 symbol = "USDJPY" symbol_info = mt5.symbol_info(symbol) if symbol_info is None: print(symbol, "not found, can not call order_check()") mt5.shutdown() quit() # 如果市场报价中没有此交易品种,请添加 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()
import MetaTrader5 as mt5 #____________Initializing Metatrader5____________# mt5.initialize() print(mt5.version(), '\n') print(mt5.terminal_info(), '\n') print(mt5.account_info(), '\n') order = mt5.orders_get() #getting all pending orders #____________Calculating required Margin_________________# margin = mt5.order_calc_margin( mt5.ORDER_TYPE_BUY, order[0].symbol, order[0].volume_initial, order[0].price_open) #returns required margin in account currency print('\nMargin requirement for buying {0} @ {1} is ${2}'.format( order[0].symbol, order[0].price_open, margin)) #____________Calculating Profit/loss_____________# volatility = float(input('Enter the desired volatility in percentage: ')) percentage = volatility * (order[0].price_open / 100) profit = mt5.order_calc_profit( mt5.ORDER_TYPE_BUY, order[0].symbol, order[0].volume_initial, order[0].price_open, (order[0].price_open + percentage)) #returns potential P/L in account currency print('\n Profit on {0} at {1} with {2}% volatility is ${3}'.format( order[0].symbol, order[0].price_open, volatility, profit))
def getFreeMargin(): return mt5.account_info().margin_free