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 _get_positions(): if mt5.positions_total() == 0: msg = "No Open Positions" else: msg = Trader.get_positions() message = PopupMessages(title="Open Positions", icon=QMessageBox.Information, text=msg, fontsize=15) message.popup()
def getPosition(symbolId=None): # return the current value of assets (not include balance or margin) #b3.getPosition( symbol_id) # return the current position in a given asset (symbol_id) #Examples: #b3.getPosition('PETR4') #pos=b3.getPosition('ITUB3') #pos['volume'] # position volume #pos['open'] # position open price #pos['time'] #position open time #pos['symbol'] # position symbol id #pos['price'] #current price of the asset # b3.getPosition(group='PETR*') # returns a list of positions that are part of the group #print("get position") if symbolId==None: return mt5.positions_total() else: return mt5.positions_get(symbol=symbolId)
def OnTick(): print("OnTick") if mt5.positions_total() == 0: n = rnd.random() if n > 0.5: print("Buy") point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).ask request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": OnLot(), "type": mt5.ORDER_TYPE_BUY, "price": price, "sl": price - SL * point, "tp": price + TP * point, "deviation": deviation, "magic": magic, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_FOK, } result = mt5.order_send(request) print("Error ", result.retcode) else: print("Sell") point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).bid request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": OnLot(), "type": mt5.ORDER_TYPE_SELL, "price": price, "sl": price + SL * point, "tp": price - TP * point, "deviation": deviation, "magic": magic, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_FOK, } result = mt5.order_send(request) print("Error ", result.retcode) return
def get_open(self): threading.Timer(3.0, self.get_open).start() Trader.no_positions = mt5.positions_total() if Trader.no_positions >= 1: self._view.openOrdersCombo.setEnabled(True) if self._view.openOrdersCombo.itemText(0) != "": self._view.openOrdersCombo.insertItem(0, "") new_tickets = Trader.get_open_tickets() current_tickets = [ self._view.openOrdersCombo.itemText(i) for i in range(self._view.openOrdersCombo.count()) ] if new_tickets != current_tickets: difference = list(set(new_tickets) - set(current_tickets)) if len(current_tickets) < len(new_tickets): for item in sorted(difference): # add item self._view.openOrdersCombo.addItem(str(item)) Trader.no_positions += len(difference) elif len(new_tickets) < len(current_tickets): difference = list(set(current_tickets) - set(new_tickets)) for item in difference: if item == "": continue # find index index = self._view.openOrdersCombo.findText(item) # remove item self._view.openOrdersCombo.removeItem(index) Trader.no_positions -= len(difference) elif Trader.no_positions == 0: current_tickets = [ self._view.openOrdersCombo.itemText(i) for i in range(self._view.openOrdersCombo.count()) ] for i in range(len(current_tickets)): self._view.openOrdersCombo.removeItem(i) self._view.openOrdersCombo.setEnabled(False)
def close_all(self): """Close all currently open positions, regardless of symbol and order type""" while mt5.positions_total(): pos = mt5.positions_get( )[0] # FIXME Im sure this could be better. Try not to use indexing position_id = mt5.TradePosition(pos).ticket symbol = mt5.TradePosition(pos).symbol order = mt5.TradePosition(pos).type if order == 0: # Buy price = mt5.symbol_info_tick(symbol).bid # TODO Check if deviation even needs to be in this request request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "position": position_id, "volume": mt5.TradePosition(pos).volume, "type": mt5.ORDER_TYPE_SELL, "price": price, "magic": self.magic, "comment": f"python close all {symbol}", } elif order == 1: # Sell price = mt5.symbol_info_tick(symbol).ask request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "position": position_id, "volume": mt5.TradePosition(pos).volume, "type": mt5.ORDER_TYPE_BUY, "price": price, "magic": self.magic, "comment": f"python close all {symbol}", } result = mt5.order_send(request) return "No Open Positions"
def getPosition( symbolId=None ): # return the current value of assets (it does not include balance or margin) #b3.getPosition( symbol_id) # return the current position in a given asset (symbol_id) #Examples: #b3.getPosition('PETR4') #pos=b3.getPosition('ITUB3') #pos['volume'] # position volume #pos['open'] # position open price #pos['time'] #position open time #pos['symbol'] # position symbol id #pos['price'] #current price of the asset # b3.getPosition(group='PETR*') # returns a list of positions that are part of the group #print("get position") if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return if symbolId == None: return mt5.positions_total() else: return mt5.positions_get(symbol=symbolId)
# shut down connection to the MetaTrader 5 terminal #mt5.shutdown() positions = 0 result_order_buy=None # Averigua si la última posición es de compra o de venta #def classify_positions(): # LÓGICA ESTRATEGIA #Esto se ejecuta hasta el infinito o hasta que el usuario cancela el programa, lo suyo sería mejorarlo con una función tipo OnTick() #last_tick=mt5.symbol_info_tick(symbol).time while 1>0: #declaraciones locales positions=mt5.positions_total() random_number=random.uniform(0,1) #abrimos largo if positions == 0: if random_number >0.5: #aquí tu estrategia open_buy() #abrimos corto if positions == 0: if random_number <0.5: #aquí tu estrategia open_sell() #cerramos posiciones if positions != 0: #cerramos largo
print('Account Logged In: ', isLoggedIn) while True: # requesting current market price current_price = mt.symbol_info_tick(symbol) print('time (UNIX): ', current_price.time) print('bid: ', current_price.bid, ',', 'ask: ', current_price.ask) # requesting OHLC Data for SMA calculation and saving them in a Pandas DataFrame # to calculate the SMA, we are using the close prices and calculate the average value (mean) sma = pd.DataFrame(mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M1, 0, sma_period))['close'].mean() print('sma: ', sma) # requesting number of open positions num_open_trades = mt.positions_total() print('current open positions: ', num_open_trades) try: # checking exposure of open trades open_trades = pd.DataFrame(list(mt.positions_get()), columns=mt.positions_get()[0]._asdict().keys()) long_trades = open_trades[open_trades['type'] == 0] short_trades = open_trades[open_trades['type'] == 1] print('open_trades', open_trades[['symbol', 'volume', 'type']]) except TypeError and IndexError: print('open trades: None') # trade logic buy if current_price.bid > sma:
#_______Making and viewing an ordered dictionary_______# if order == None: print(f"No Orders, error code={mt5.last_error()}") else: for i in range(len(order)): # Converting a namedtuple to an ordered dictionary. #._asdict() works with named tuple and not a ordinary tuple. k = order[i]._asdict() print('\n') for j in k: print(f"{j}: {k[j]}") #________Open positions________# openPos = mt5.positions_total() #returns total number of open positions print('\nno of open positions:', openPos) position = mt5.positions_get() """Returns info of open positions as a tuple of named tuples one can pass name of the asset to show all open psitions on that asset one can pass a ticket of a trade to see the status of that trade If nothing is passed, it returns info of all the open positions in MT5""" #________Printing all the values of a position as a dictionary___________# if position == None: print(f"No positions, error code={mt5.last_error()}") else: for i in range(len(position)): k = position[i]._asdict() #._asdict() works with named tuple and not a tuple.
order_total = mt5.orders_total() print("当前的下单总量 = ",order_total) # 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() # check the presence of active orders orders=mt5.positions_total() t_orders = mt5.orders_get() position = mt5.orders_get(symbol = "USDJPY") print("position ",position) print("t_orders ",t_orders) if orders>0: print("Total orders=",orders) else: print("Orders not found") # shut down connection to the MetaTrader 5 terminal