def cancel_all(self): """Cancels all pending orders regardless of symbol and order type""" while mt5.orders_get(): pos = mt5.orders_get()[ 0] # FIXME Again check if this can be done better without [0] position_id = mt5.TradeOrder(pos).ticket request = { "action": mt5.TRADE_ACTION_REMOVE, "order": position_id, "magic": self.magic } result = mt5.order_send(request) return "No Pending Orders"
def __init__(self, ticket): self.pending_orders = mt5.orders_get(ticket=ticket) self.symbol = self.pending_orders[0].symbol self.entry = self.pending_orders[0].price_open self.stop_loss = self.pending_orders[0].sl self.take_profit = self.pending_orders[0].tp self.comment = self.pending_orders[0].comment self.volume = self.pending_orders[0].volume_current
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 get_orders(self): """Get active order information Returns: list: Active orders """ orders = mt5.orders_get(symbol=self.symbol) result = [order._asdict() for order in orders] return result
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 get_orders(self): """Returns pending orders""" msg = "" for count, order in enumerate(mt5.orders_get(), 1): msg += f"Position {count} - {self.Orders(mt5.TradeOrder(order).type).name}\n" msg += f"Symbol : {self.symbol}\n" msg += f"Ticket : {mt5.TradeOrder(order).ticket}\n" msg += f"Volume : {mt5.TradeOrder(order).volume_initial} @ {self.Risk.risk}% Risk\n" msg += f"Open Price : {mt5.TradeOrder(order).price_open:.3f}\n" msg += f"TP : {mt5.TradeOrder(order).tp:.3f}\n" msg += f"SL : {mt5.TradeOrder(order).sl:.3f}\n" msg += "------------------------------\n" return msg
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 modify_order(self, ticket, open_price): """Modifies a currently pending order""" mt5.initialize() order = mt5.orders_get(ticket=ticket)[0] symbol = mt5.TradeOrder(order).symbol request = { "action": mt5.TRADE_ACTION_MODIFY, "order": ticket, "price": open_price, "sl": self.StopLoss.sl, "tp": self.TakeProfit.tp, "type_time": mt5.ORDER_TIME_GTC, "magic": self.magic, "comment": f"python modify {symbol}" } result = mt5.order_send(request)
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 # mt5.shutdown()
import pytz #____________Initializing Metatrader5____________# mt5.initialize() print(f"Module Author: {mt5.__author__}") print(f"MetaTrader5 module version: {mt5.__version__}") print(f"MT5 Terminal Build: {mt5.terminal_info().build}") #__________Pending Order operations_____________# # Returns total number of pending orders as int no_of_orders = mt5.orders_total() print('no of pending orders: {0}'.format(no_of_orders)) # Returns information of passed pending order as a tuple of named tuples, returns all orders if nothing passed. order = mt5.orders_get() print('\nOrder info: {0}'.format(order)) #_______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]}")
def trade(): """Check if Musk mentioned bitcoin and open a buy position if so""" what_musk_said = get_elons_tweet() # used to check if a position has already been placed positions = mt5.positions_get(symbol=CRYPTO) orders = mt5.orders_get(symbol=CRYPTO) symbol_info = mt5.symbol_info(CRYPTO) price = mt5.symbol_info_tick(CRYPTO).bid # perform logic check if any(keyword in what_musk_said for keyword in keywords): print(f'the madlad said it - buying some!') # prepare the trade request if not mt5.initialize(): raise RuntimeError( f'MT5 initialize() failed with error code {mt5.last_error()}') # check that there are no open positions or orders if len(positions) == 0 and len(orders) < 1: if symbol_info is None: print(f'{CRYPTO} not found, can not call order_check()') mt5.shutdown() # if the symbol is unavailable in MarketWatch, add it if not symbol_info.visible: print(f'{CRYPTO} is not visible, trying to switch on') if not mt5.symbol_select(CRYPTO, True): print('symbol_select({}}) failed, exit', CRYPTO) #this represents 5% Equity. Minimum order is 0.01 BTC. Increase equity share if retcode = 10014 lot = float(round(((equity / 5) / price), 2)) # define stop loss and take profit sl = price - (price * 5) / 100 tp = price + (price * 10) / 100 request = { 'action': mt5.TRADE_ACTION_DEAL, 'symbol': CRYPTO, 'volume': lot, 'type': mt5.ORDER_TYPE_BUY, 'price': price, 'sl': sl, 'tp': tp, 'magic': 66, 'comment': 'python-buy', 'type_time': mt5.ORDER_TIME_GTC, 'type_filling': mt5.ORDER_FILLING_IOC, } # send a trading request result = mt5.order_send(request) # check the execution result print(f'1. order_send(): by {CRYPTO} {lot} lots at {price}') if result.retcode != mt5.TRADE_RETCODE_DONE: print(f'2. order_send failed, retcode={result.retcode}') #print the order result - anything else than retcode=10009 is an error in the trading request. print(f'2. order_send done, {result}') print(f' opened position with POSITION_TICKET={result.order}') else: print( f'BUY signal detected, but {CRYPTO} has {len(positions)} active trade' ) else: print(f'He did not say it, he said: {what_musk_said}')
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))
comExposure = asset_class_exposure(comPositions) indexExposure = asset_class_exposure(indexPositions) equityExposure = asset_class_exposure(equityPositions) etfExposure = asset_class_exposure(etfPositions) bondExposure = asset_class_exposure(bondPositions) #Pushing exposures into spreadsheet portfolioSheet.cells(16, 'B').value = fxExposure portfolioSheet.cells(17, 'B').value = comExposure portfolioSheet.cells(18, 'B').value = indexExposure portfolioSheet.cells(19, 'B').value = equityExposure portfolioSheet.cells(20, 'B').value = etfExposure portfolioSheet.cells(21, 'B').value = bondExposure #_____________Orders Sheet___________________# allOrders = mt5.orders_get() tickets = set() for order in allOrders: tickets.add(order.ticket) tempVar2 = 11 + len(tickets) orderSheet.range('D11:S41').clear_contents() for i in range(11, tempVar2 + len(tickets)): for ticket in tickets: my_order = ca.Order(ticket) orderSheet.cells(i, 'D').value = my_order.position()
def trade(): """Determine if we should trade and if so, send requests to MT5.""" utc_from, utc_to = get_dates() candles = get_data() current_buy_price, current_sell_price = get_current_prices() # calculate the % difference between the current price and the close price of the previous candle difference = (candles['close'][-1] - candles['close'][-2]) / candles['close'][-2] * 100 # used to check if a position has already been placed positions = mt5.positions_get(symbol=CRYPTO) orders = mt5.orders_get(symbol=CRYPTO) symbol_info = mt5.symbol_info(CRYPTO) # perform logic check if difference > 3: print(f'dif 1: {CRYPTO}, {difference}') # Pause for 8 seconds to ensure the increase is sustained time.sleep(8) # calculate the difference once again candles = mt5.copy_rates_range(CRYPTO, mt5.TIMEFRAME_M10, utc_from, utc_to) difference = (candles['close'][-1] - candles['close'][-2]) / candles['close'][-2] * 100 if difference > 3: print(f'dif 2: {CRYPTO}, {difference}') price = mt5.symbol_info_tick(CRYPTO).bid print( f'{CRYPTO} is up {str(difference)}% in the last 5 minutes opening BUY position.' ) # prepare the trade request if not mt5.initialize(): raise RuntimeError( f'MT5 initialize() failed with error code {mt5.last_error()}' ) # check that there are no open positions or orders if len(positions) == 0 and len(orders) < 1: if symbol_info is None: print(f'{CRYPTO} not found, can not call order_check()') mt5.shutdown() # if the symbol is unavailable in MarketWatch, add it if not symbol_info.visible: print(f'{CRYPTO} is not visible, trying to switch on') if not mt5.symbol_select(CRYPTO, True): print('symbol_select({}}) failed, exit', CRYPTO) #this represents 5% Equity. Minimum order is 0.01 BTC. Increase equity share if retcode = 10014 lot = float(round(((equity / 20) / current_buy_price), 2)) # define stop loss and take profit sl = price - (price * 5) / 100 tp = price + (price * 8) / 100 request = { 'action': mt5.TRADE_ACTION_DEAL, 'symbol': CRYPTO, 'volume': lot, 'type': mt5.ORDER_TYPE_BUY, 'price': price, 'sl': sl, 'tp': tp, 'magic': 66, 'comment': 'python-buy', 'type_time': mt5.ORDER_TIME_GTC, 'type_filling': mt5.ORDER_FILLING_IOC, } # send a trading request result = mt5.order_send(request) # check the execution result print(f'1. order_send(): by {CRYPTO} {lot} lots at {price}') if result.retcode != mt5.TRADE_RETCODE_DONE: print(f'2. order_send failed, retcode={result.retcode}') #print the order result - anything else than retcode=10009 is an error in the trading request. print(f'2. order_send done, {result}') print( f' opened position with POSITION_TICKET={result.order}') else: print( f'BUY signal detected, but {CRYPTO} has {len(positions)} active trade' ) else: pass else: if orders or positions: print( 'Buying signal detected but there is already an active trade') else: print(f'difference is only: {str(difference)}% trying again...')
def job(): # 更新市场信息 for symbol_name in symbols: symbol_info_tick = mt5.symbol_info(symbol_name) market = {} print("symbol_info_tick ",symbol_info_tick); market["time"] = symbol_info_tick.time market["bid"] = symbol_info_tick.bid market["ask"] = symbol_info_tick.ask market["last"] = symbol_info_tick.last market["volume"] = symbol_info_tick.volume market["volume_real"] = symbol_info_tick.volume_real market["custome"] = symbol_info_tick.volume_real market["chart_mode"] = symbol_info_tick.chart_mode market["select"] = symbol_info_tick.select market["visible"] = symbol_info_tick.visible market["session_deals"] = symbol_info_tick.session_deals market["session_sell_orders"] = symbol_info_tick.session_sell_orders market["volumehigh"] = symbol_info_tick.volumehigh market["volumelow"] = symbol_info_tick.volumelow market["digits"] = symbol_info_tick.digits market["spread"] = symbol_info_tick.spread market["spread_float"] = symbol_info_tick.spread_float market["ticks_bookdepth"] = symbol_info_tick.ticks_bookdepth market["trade_calc_mode"] = symbol_info_tick.trade_calc_mode market["trade_mode"] = symbol_info_tick.trade_mode market["start_time"] = symbol_info_tick.start_time market["expiration_time"] = symbol_info_tick.expiration_time market["trade_stops_level"] = symbol_info_tick.trade_stops_level market["trade_freeze_level"] = symbol_info_tick.trade_freeze_level market["trade_exemode"] = symbol_info_tick.trade_exemode market["swap_mode"] = symbol_info_tick.swap_mode market["swap_rollover3days"] = symbol_info_tick.swap_rollover3days market["margin_hedged_use_leg"] = symbol_info_tick.margin_hedged_use_leg market["expiration_mode"] = symbol_info_tick.expiration_mode market["filling_mode"] = symbol_info_tick.filling_mode market["order_mode"] = symbol_info_tick.order_mode market["order_gtc_mode"] = symbol_info_tick.order_gtc_mode market["option_mode"] = symbol_info_tick.option_mode market["option_right"] = symbol_info_tick.option_right market["bid"] = symbol_info_tick.bid market["bidhigh"] = symbol_info_tick.bidhigh market["bidlow"] = symbol_info_tick.bidlow market["ask"] = symbol_info_tick.ask market["askhigh"] = symbol_info_tick.askhigh market["asklow"] = symbol_info_tick.asklow market["last"] = symbol_info_tick.last market["lasthigh"] = symbol_info_tick.lasthigh market["lastlow"] = symbol_info_tick.lastlow market["volume_real"] = symbol_info_tick.volume_real market["volumehigh_real"] = symbol_info_tick.volumehigh_real market["option_strike"] = symbol_info_tick.option_strike market["point"] = symbol_info_tick.point market["trade_tick_value"] = symbol_info_tick.trade_tick_value market["trade_tick_value_profit"] = symbol_info_tick.trade_tick_value_profit market["trade_tick_value_loss"] = symbol_info_tick.trade_tick_value_loss market["trade_tick_size"] = symbol_info_tick.trade_tick_size market["trade_contract_size"] = symbol_info_tick.trade_contract_size market["trade_accrued_interest"] = symbol_info_tick.trade_accrued_interest market["trade_face_value"] = symbol_info_tick.trade_face_value market["trade_liquidity_rate"] = symbol_info_tick.trade_liquidity_rate market["volume_min"] = symbol_info_tick.volume_min market["volume_max"] = symbol_info_tick.volume_max market["volume_step"] = symbol_info_tick.volume_step market["volume_limit"] = symbol_info_tick.volume_limit market["swap_long"] = symbol_info_tick.swap_long market["swap_short"] = symbol_info_tick.swap_short market["margin_initial"] = symbol_info_tick.margin_initial market["margin_maintenance"] = symbol_info_tick.margin_maintenance market["session_volume"] = symbol_info_tick.session_volume market["session_turnover"] = symbol_info_tick.session_turnover market["session_interest"] = symbol_info_tick.session_interest market["session_buy_orders_volume"] = symbol_info_tick.session_buy_orders_volume market["session_sell_orders_volume"] = symbol_info_tick.session_sell_orders_volume market["session_open"] = symbol_info_tick.session_open market["session_close"] = symbol_info_tick.session_close market["session_aw"] = symbol_info_tick.session_aw market["session_price_settlement"] = symbol_info_tick.session_price_settlement market["session_price_limit_min"] = symbol_info_tick.session_price_limit_min market["session_price_limit_max"] = symbol_info_tick.session_price_limit_max market["margin_hedged"] = symbol_info_tick.margin_hedged market["price_change"] = symbol_info_tick.price_change market["price_volatility"] = symbol_info_tick.price_volatility market["price_theoretical"] = symbol_info_tick.price_theoretical market["price_greeks_delta"] = symbol_info_tick.price_greeks_delta market["price_greeks_theta"] = symbol_info_tick.price_greeks_theta market["price_greeks_gamma"] = symbol_info_tick.price_greeks_gamma market["price_greeks_vega"] = symbol_info_tick.price_greeks_vega market["price_greeks_rho"] = symbol_info_tick.price_greeks_rho market["price_greeks_omega"] = symbol_info_tick.price_greeks_omega market["price_sensitivity"] = symbol_info_tick.price_sensitivity market["basis"] = symbol_info_tick.basis market["category"] = symbol_info_tick.category market["currency_base"] = symbol_info_tick.currency_base market["currency_profit"] = symbol_info_tick.currency_profit market["currency_margin"] = symbol_info_tick.currency_margin market["bank"] = symbol_info_tick.bank market["description"] = symbol_info_tick.description market["exchange"] = symbol_info_tick.exchange market["formula"] = symbol_info_tick.formula market["isin"] = symbol_info_tick.isin market["name"] = symbol_info_tick.name market["page"] = symbol_info_tick.page market["path"] = symbol_info_tick.path response = requests.post(server_url + "update_market/",json=market) json_response = response.json() print("json_response ",json_response ) position_get_no_param = mt5.positions_get() # 更新position order for trade_position in position_get_no_param: position = {} position["ticket"] = trade_position.ticket position["time"] = trade_position.time position["time_msc"] = trade_position.time_msc position["time_update"] = trade_position.time_update position["time_update_msc"] = trade_position.time_update_msc position["type"] = trade_position.type position["magic"] = trade_position.magic position["identifier"] = trade_position.identifier position["reason"] = trade_position.reason position["volume"] = trade_position.volume position["price_open"] = trade_position.price_open position["sl"] = trade_position.sl position["tp"] = trade_position.tp position["price_current"] = trade_position.price_current position["swap"] = trade_position.swap position["profit"] = trade_position.profit position["symbol"] = trade_position.symbol position["comment"] = trade_position.comment position["external_id"] = trade_position.external_id response = requests.post(server_url + "update_position_order/",json=position) json_response = response.json() print("position_response ",json_response ) # 更新 pending order pending_orders = mt5.orders_get() for pending_order in pending_orders: pending = {} pending["ticket"] = pending_order.ticket pending["time_setup"] = pending_order.time_setup pending["type"] = pending_order.type pending["state"] = pending_order.state pending["time_expiration"] = pending_order.time_expiration pending["time_done"] = pending_order.time_done pending["time_setup_msc"] = pending_order.time_setup_msc pending["time_done_msc"] = pending_order.time_done_msc pending["type_filling"] = pending_order.type_filling pending["type_time"] = pending_order.type_time pending["magic"] = pending_order.magic pending["reason"] = pending_order.reason pending["position_id"] = pending_order.position_id pending["position_by_id"] = pending_order.position_by_id pending["volume_initial"] = pending_order.volume_initial pending["volume_current"] = pending_order.volume_current pending["price_open"] = pending_order.price_open pending["sl"] = pending_order.sl pending["tp"] = pending_order.tp pending["price_current"] = pending_order.price_current pending["price_stoplimit"] = pending_order.price_stoplimit pending["symbol"] = pending_order.symbol pending["comment"] = pending_order.comment pending["external_id"] = pending_order.external_id response = requests.post(server_url + "update_pending_order/",json=pending) json_response = response.json() # 更新 deal order from_date = datetime(2020,11,30) deal_orders = mt5.history_deals_get(from_date, datetime.now()) for deal in deal_orders: deal_data = {} deal_data["ticket"] = deal.ticket deal_data["order"] = deal.order deal_data["time"] = deal.time deal_data["time_msc"] = deal.time_msc deal_data["type"] = deal.type deal_data["entry"] = deal.entry deal_data["magic"] = deal.magic deal_data["reason"] = deal.reason deal_data["position_id"] = deal.position_id deal_data["volume"] = deal.volume deal_data["price"] = deal.price deal_data["commission"] = deal.commission deal_data["swap"] = deal.swap deal_data["profit"] = deal.profit deal_data["fee"] = deal.fee deal_data["symbol"] = deal.symbol deal_data["comment"] = deal.comment deal_data["external_id"] = deal.external_id response = requests.post(server_url + "update_deal_order/",json=deal_data) json_response = response.json()
import MetaTrader5 as mt5 import datetime as dt import pytz #____________Initializing Metatrader5____________# mt5.initialize() print(f"Module Author: {mt5.__author__}") print(f"MetaTrader5 module version: {mt5.__version__}") print(f"MT5 Terminal Build: {mt5.terminal_info().build}") #__________Pending Order operations_____________# no_of_orders = mt5.orders_total( ) #changed #returns total number of pending orders print('no of pending orders: {0}'.format(no_of_orders)) order = mt5.orders_get( ) #returns information of passed pending order, returns all if nothing passed print('\nOrder info: {0}'.format(order)) #_______Making and viewing an orders dictionary_______# if order == None: print(f"No Orders, error code={mt5.last_error()}") else: for i in range(len(order)): k = order[i]._asdict( ) #._asdict() works with named tuple and not a tuple. print('\n') for j in k: print(f"{j}: {k[j]}") #____________Calculating required Margin_________________# margin = mt5.order_calc_margin(
if(rates99de[0]<rates99de[-1]): r99g ='FALLING' else: r99g ='RISING' if(rates7de[0]<rates7de[-1]): r7g = 'FALLING' else: r7g = 'RISING' if(rates25de[0]<rates25de[-1]): r25g = 'FALLING' else: r25g = 'RISING' orders=mt5.orders_get(symbol=pair) if orders is None: print("No orders on ETHUSD., error code={}".format(mt5.last_error())) else: print("Total orders on ETHUSD.:",len(orders)) for order in orders: print(order) print('bid ',ticks[0][1]) print('ask ',ticks[0][2]) print('###################################################################################################') #(len(orders)==0) if(killer>10): if((r25g == 'FALLING') and (r7g == 'RISING')):
def get_pending_tickets(): tickets = list() for order in mt5.orders_get(): tickets.append(str(order._asdict()['ticket'])) return tickets