def placeOrder(symbol_name, order_type, pipsprof=50, pipsloss=50, lot=0.1): order = None sl = None tp = None point = mt5.symbol_info(symbol_name).point price = mt5.symbol_info_tick(symbol_name).ask if order_type == 'buy': order = mt5.ORDER_TYPE_BUY sl = price - pipsloss * point # pips down tp = price + pipsprof * point # pips up elif order_type == 'sell': order = mt5.ORDER_TYPE_SELL sl = price + pipsloss * point # pips up tp = price - pipsprof * point # pips down else: print("Wrong order type passed into place order function") exit() # Exit the file deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol_name, "volume": lot, "type": order, "price": price, "sl": sl, # "tp": tp, "deviation": deviation, # "magic": 234000, "comment": f"Placing order on {symbol_name}", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC #mt5.ORDER_FILLING_FOK#mt5.ORDER_FILLING_RETURN } result = mt5.order_send(request) if result.retcode != mt5.TRADE_RETCODE_DONE: print(mt5.last_error()) return False else: return True
def get_order_close(): print(" closing position #{}".format(result.order)) #time.sleep(2) # create a close request position_id = result.order price = mt5.symbol_info_tick(symbol).bid deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_SELL, "position": position_id, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script close", "type_time": mt5.ORDER_TIME_GTC, #"type_filling": mt5.ORDER_FILLING_RETURN, } # send a trading request result = mt5.order_send(request) # check the execution result print( "3. close position #{}: sell {} {} lots at {} with deviation={} points" .format(position_id, symbol, lot, price, deviation)) if result.retcode != mt5.TRADE_RETCODE_DONE: print("4. order_send failed, retcode={}".format(result.retcode)) print(" result", result) else: print("4. position #{} closed, {}".format(position_id, result)) # 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])) # shut down connection to the MetaTrader 5 terminal mt5.shutdown()
def test(): """ Executes the swap calculation function, on the press of button and makes the required changes to the GUI variables.""" selection = assetList.curselection()[0] symbol = assetList.get(selection) mt5.symbol_select(symbol) volume = float(volEntryVar.get()) try: entryPrice = float(priceEntryVar.get()) except ValueError: # if entry price is not entered. entryPrice = float(mt5.symbol_info_tick(symbol).ask) exposure = volume * entryPrice long, short = swap(symbol, volume, exposure) sLongVar.set(long) sShortVar.set(short)
def get_malgo(self, name, margin_level, profit, exchange_rate, new_exchange_rate, symbol): #volume = __open_positon[0][9] #swap = __open_positon[0][14] #stop_loss = __open_positon[0][11] #stop_loss = __open_positon[0][12] select_time = self.get_local_time(mt.symbol_info_tick("EURUSD")[0]) self.trade_positions = [{ "Account Name": name, "Margin Level": round(margin_level, 2), "Symbol": symbol, "exchnage rate": exchange_rate, "Current Exchange Rate": new_exchange_rate, "Profit": profit, "Local Time": select_time }]
def sell(stock_name, volume): """ Buy stock. Note, you must login with mt5.login(accountNo, password) prior to this For this function to work, you must also enable autotrading by pressing the "Algo trading" button :param stock_name: The symbol code :param volume: Volume in lots. E.g. 0.01 is 1k dollars in GBPUSD :return: class Order """ symbol_info = mt5.symbol_info(stock_name) if symbol_info is None or not symbol_info.visible: return False request = { "action": mt5.TRADE_ACTION_DEAL, "type": mt5.ORDER_TYPE_SELL, "symbol": stock_name, "volume": volume, "price": mt5.symbol_info_tick(stock_name).ask } return Order(mt5.order_send(request), request)
def open_sell_position(self, comment=''): point = Mt5.symbol_info(self.symbol).point price = Mt5.symbol_info_tick(self.symbol).bid request = { "action": Mt5.TRADE_ACTION_DEAL, "symbol": self.symbol, "volume": self.lot, "type": Mt5.ORDER_TYPE_SELL, "price": price, "sl": price + self.emergency_stop_loss * point, "tp": price - self.emergency_take_profit * point, "deviation": 5, "magic": self.magic_number, "comment": comment, "type_time": Mt5.ORDER_TIME_GTC, "type_filling": Mt5.ORDER_FILLING_RETURN, } result = Mt5.order_send(request) self.request_result(price, result)
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 Buy(self, lot, symbol): trade.Check(lot, symbol) point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).ask deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_BUY, "price": price, "sl": price - 100 * point, "tp": price + 100 * point, "deviation": deviation, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_RETURN, } # 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() else: self.orders[symbol] = result.order return
def isMarketOpen(asset='B3SA3'): if not connected: print( "In order to use this function, you must be connected to B3. Use function connect()" ) return # si=mt5.symbol_info(asset) # if si!=None: # if si.trade_mode==mt5.SYMBOL_TRADE_MODE_FULL: # it does not work in XP/B3 (always True) # return True # else: # return False # return False t_secs = mt5.symbol_info_tick(asset).time # time in seconds now_dt = datetime.now(etctz) + timedelta(hours=-3) last_tick_dt = datetime.fromtimestamp(t_secs, etctz) #print(last_tick_dt) #print(now_dt) if now_dt > last_tick_dt + timedelta(seconds=60): return False else: return True
def make_request(volume, direction, deviation, symbol, magic): if direction == 'long': order_type = mt5.ORDER_TYPE_BUY elif direction == 'short': order_type = mt5.ORDER_TYPE_SELL else: print('Invalid order type') request = { 'action': mt5.TRADE_ACTION_DEAL, 'symbol': symbol, 'volume': volume, 'type': order_type, 'price': mt5.symbol_info_tick(symbol).ask, 'deviation': deviation, 'magic': magic, 'comment': 'Order type: ' + direction, 'type_time': mt5.ORDER_TIME_GTC, 'type_filling': mt5.ORDER_FILLING_FOK } return mt5.order_send(request)
def open_buy_position(self, comment=""): point = Mt5.symbol_info(self.symbol).point price = Mt5.symbol_info_tick(self.symbol).ask self.ticket = (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0) request = { "action": Mt5.TRADE_ACTION_DEAL, "symbol": self.symbol, "volume": self.lot, "type": Mt5.ORDER_TYPE_BUY, "price": price, "sl": price - self.emergency_stop_loss * point, "tp": price + self.emergency_take_profit * point, "deviation": 5, "magic": self.magic_number, "comment": str(comment), "type_time": Mt5.ORDER_TIME_GTC, "type_filling": Mt5.ORDER_FILLING_RETURN, "position": (Mt5.positions_get()[0].ticket if len(Mt5.positions_get()) == 1 else 0) } result = Mt5.order_send(request) self.request_result(price, result)
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 set_order_type(self): symbol = Trader.symbol if self._view.orderTypeComboBox.currentText() == "Buy": Trader.OrderType.order_type = mt5.ORDER_TYPE_BUY self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).bid) if self._view.orderTypeComboBox.currentText() == "Sell": Trader.OrderType.order_type = mt5.ORDER_TYPE_SELL self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).ask) if self._view.orderTypeComboBox.currentText() == "Buy Limit": Trader.OrderType.order_type = mt5.ORDER_TYPE_BUY_LIMIT self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).bid) if self._view.orderTypeComboBox.currentText() == "Sell Limit": Trader.OrderType.order_type = mt5.ORDER_TYPE_SELL_LIMIT self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).ask) if self._view.orderTypeComboBox.currentText() == "Buy Stop": Trader.OrderType.order_type = mt5.ORDER_TYPE_BUY_STOP self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).bid) if self._view.orderTypeComboBox.currentText() == "Sell Stop": Trader.OrderType.order_type = mt5.ORDER_TYPE_SELL_STOP self._view.priceSpinBox.setValue(mt5.symbol_info_tick(symbol).ask)
# All stocks trading < $100 import MetaTrader5 as mt5 import pandas as pd mt5.initialize() all_assets = mt5.symbols_get() stocks = list() small = list() for asset in all_assets: if "Stock" in asset.path: stocks.append(asset.name) for stock in stocks: if 'ETF' in mt5.symbol_info(stock).path: stocks.remove(stock) # print(stocks) for stock in stocks: mt5.symbol_select(stock) if mt5.symbol_info_tick(stock).ask <= 100: small.append(stock) print(small) print(len(small)) mt5.shutdown()
def compra_init(key_value, file, close_list_value, open_list_value, n_value, stop_gain_value, stop_lose_value, mercado_value, lote_value, sim_value, facebook_value): # Metatrader5 command key_f = key_value valor_inicial_f = mt5.symbol_info_tick(mercado_value).ask pontos_f = mt5.symbol_info(mercado_value).point # Simulation process if sim_value: print( f"|Processo de COMPRA iniciado|\n - VALOR DE ENTRADA = {valor_inicial_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) print("-" * 12) # Real Trade process else: request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": mercado_value, "volume": lote_value, "type": mt5.ORDER_TYPE_BUY, "price": valor_inicial_f, "sl": stop_lose_value - 40 * pontos_f, "tp": stop_gain_value + 40 * pontos_f, "deviation": 20, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } mt5.order_send(request) # Facebook message trade alert if facebook_value: msg.mensagem( f"|Processo de COMPRA iniciado|\n - VALOR DE ENTRADA = {valor_inicial_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) msg.mensagem("-" * 12) print( f"|Processo de COMPRA iniciado|\n - VALOR DE ENTRADA = {valor_inicial_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) print("-" * 12) stop_lines_f = True registro_tempo_f = n_value plt.savefig(file) return key_f, stop_lines_f, valor_inicial_f, registro_tempo_f
def compra_perda(key_value, file, file_hist, close_list_value, open_list_value, time_list_value, n_value, tabela_value, valor_inicial_value, mercado_value, lote_value, lote_price, sim_value, facebook_value): # Metatrader5 command key_f = 0 valor_atual_f = mt5.symbol_info_tick(mercado_value).ask resultado_f = valor_inicial_value - valor_atual_f # Simulation process if sim_value: lucro = resultado_f * lote_price * lote_value * 0.78 tabela_value[1] += 1 print( f"|PERDA: Processo de COMPRA|\n - FECHAMENTO = {close_list_value[-1]}\n - RESULTADO = {resultado_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) print(f'PERDA: {lucro}') print(f'LUCRO: {tabela_value[0]}; PERDA: {tabela_value[1]}') print("-" * 12) print(f"QUANTIA = {mt5.account_info()._asdict()['balance']}") print("-" * 12) # Real Trade process else: request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": mercado_value, "volume": lote_value, "type": mt5.ORDER_TYPE_BUY, "price": valor_atual_f, "deviation": 20, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } mt5.order_send(request) lucro = resultado_f * lote_price * lote_value * 0.78 tempo = time_list_value[-1] df_dados = pd.DataFrame({ 'key': [key_value], 'Lucro': [lucro], 'Data': [tempo], 'Boolean': [sim_value] }) with open(file_hist, 'a') as f: df_dados.to_csv(f, header=False, index=False) tabela_value[1] += 1 # Facebook message trade alert if facebook_value: msg.mensagem( f"|PERDA: Processo de COMPRA|\n - FECHAMENTO = {close_list_value[-1]}\n - RESULTADO = {resultado_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) msg.mensagem(f'PERDA: {lucro}') msg.mensagem(f'LUCRO: {tabela_value[0]}; PERDA: {tabela_value[1]}') msg.mensagem("-" * 12) msg.mensagem( f"QUANTIA = {mt5.account_info()._asdict()['balance']}") msg.mensagem("-" * 12) print( f"|PERDA: Processo de COMPRA|\n - FECHAMENTO = {close_list_value[-1]}\n - RESULTADO = {resultado_f}\n " f"- KEY = {key_f};\n - open_list[-1] = {open_list_value[-1]};\n - open_list[-2] = {open_list_value[-2]};\n " f"- close_list[-1] = {close_list_value[-1]};\n - close_list[-2] = {close_list_value[-2]}" ) print(f'PERDA: {lucro}') print(f'LUCRO: {tabela_value[0]}; PERDA: {tabela_value[1]}') print("-" * 12) print(f"QUANTIA = {mt5.account_info()._asdict()['balance']}") print("-" * 12) stop_lines_f = False registro_tempo_f = n_value plt.savefig(file) return key_f, stop_lines_f, registro_tempo_f, tabela_value
def get_order(symbol='EURUSD', side='long', lot=0.01, sl=100, tp=100, magic=101): # 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() point = mt5.symbol_info(symbol).point ask = mt5.symbol_info_tick(symbol).ask bid = mt5.symbol_info_tick(symbol).bid if side == 'long': price = ask stop_loss = price - sl * point take_profit = price + tp * point type_side = mt5.ORDER_TYPE_BUY elif side == 'short': price = bid stop_loss = price + sl * point take_profit = price - tp * point type_side = mt5.ORDER_TYPE_SELL deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": type_side, "price": price, "sl": stop_loss, "tp": take_profit, "deviation": deviation, "magic": magic, "comment": "python script open", "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("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(" opened position with POSITION_TICKET={}".format(result.order)) return result.order
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}')
timeframe = mt5.TIMEFRAME_H6 array = 10 lot = 50.0 deviation = 20 signal = '' prevSignal = '' orders = 0 while True: signal = '' #print(prevSignal) highMA = periodHigh(pair, 10, timeframe, array) lowMA = periodLow(pair, 10, timeframe, array) ask = mt5.symbol_info_tick(pair).ask #BUY bid = mt5.symbol_info_tick(pair).bid #SELL point = mt5.symbol_info(pair).point price = 0 tradeType = 0 #print('symbol: ',pair) #print('bid: ', bid, 'ask: ', ask) #print('speread: ', ask-bid) #print('BUY: ',(ask-lowMA[-1])/(highMA[-1]-lowMA[-1])) #print('SELL: ',(bid-lowMA[-1])/(highMA[-1]-lowMA[-1])) #print('########################################') if (orders == 0):
def monitor(jb,vf,im,i,hh,d,to_whatsapp): t = 'done' if d == 1 and len(hh) >0: tickett=hh[2] tt=ft.positions_get(ticket=tickett) trade=tt[0][15] if trade <=-2.5 and vf== 0: ft.Close(im,ticket=tickett) hy=ft.Sell(im,0.04) client.messages.create(body='Close the Buy loss in '+im+' , I advise you Sell' ,from_=from_whatsapp,to=to_whatsapp) while True: if (ft.positions_get(hy[2]))[0][15] >= 10: ft.Close(im,ticket=hy[2]) break elif (ft.positions_get(hy[2]))[0][15]<=-2.5: ft.Close(im,ticket=hy[2]) break return t elif trade<=-2.5 and vf== 1: ft.Close(im,ticket=tickett) hy=ft.Buy(im,0.04) client.messages.create(body='Close the Sell loss in '+im+' , I advise you Buy' ,from_=from_whatsapp,to=to_whatsapp) while True: if (ft.positions_get(hy[2]))[0][15] >= 10: ft.Close(im,ticket=hy[2]) break elif (ft.positions_get(hy[2]))[0][15]<=-2.5: ft.Close(im,ticket=hy[2]) break return t elif trade >= 50 and vf == 0: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbb[2] >= (jbg[2]): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif trade >=50 and vf==1: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbb[1] <= (jbg[1]): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 50>trade>=20 and vf==0: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbb[2] > (jbg[2]+0.00005): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 50>trade>=20 and vf==1: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbg[1] > (jbb[1]-0.00005): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 20>trade>=10 and vf==0: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbb[2] > (jbg[2]+0.000075): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 20>trade>=10 and vf==1: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbg[1] > (jbb[1]-0.000075): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 10>trade>=2 and vf==0: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbb[2] > (jbg[2]+0.00010): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif 10>trade>=2 and vf==1: jbb=ft.symbol_info_tick(im) time.sleep(2) jbg=ft.symbol_info_tick(im) if jbg[1] > (jbb[1]-0.00010): ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif trade<=-2.5: ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t elif trade>=10: ft.Close(im,ticket=tickett) client.messages.create(body='Close the profit in '+im ,from_=from_whatsapp,to=to_whatsapp) return t else: return 'not' elif d ==0 and len(hh)<=0: print('no trade done at the moment') return t else: print('Error occured in getting ticket') return 'not'
and fibo_list[4] > close_list[-2] >= fibo_list[5]) ) and close_list[-1] > fibo_list[5] + 0.20 * (fibo_list[4] - fibo_list[5]): stop_gain = fibo_list[3] - 0.20 * (fibo_list[3] - fibo_list[4]) stop_lose = fibo_list[1] - 0.2 * (fibo_list[6] - fibo_list[1]) key, stop_lines, valor_inicial, registro_tempo = met.compra_init( 1, f'/Users/vychi/Desktop/graficos/{file_entrada}/{time}', close_list, open_list, time, stop_gain, stop_lose, mercado, lote_value_corr, sim, facebook) if stop_lines: plt.axhline(stop_gain, color='green', linewidth=0.5) plt.axhline(stop_lose, color='red', linewidth=0.5) if key == 1 and mt5.symbol_info_tick(mercado).bid >= stop_gain: key, stop_lines, registro_tempo, tabela = met.venda_lucro( 1, f'/Users/vychi/Desktop/graficos/{file_saida}/{time}', f'/Users/vychi/Desktop/graficos/Dados/historico_{mercado}.csv', close_list, open_list, time_list, time, tabela, valor_inicial, mercado, lote_value_corr, lote_peso, sim, facebook) fibo_list, curve = graf.fibonacci(open_list, close_list) if key == 1 and mt5.symbol_info_tick(mercado).bid <= stop_lose: key, stop_lines, registro_tempo, tabela = met.venda_perda( 1, f'/Users/vychi/Desktop/graficos/{file_saida}/{time}', f'/Users/vychi/Desktop/graficos/Dados/historico_{mercado}.csv', close_list, open_list, time_list, time, tabela, valor_inicial, mercado, lote_value_corr, lote_peso, sim, facebook)
def step(self, action, trade=False): """Take an action (buy/sell/hold) and computes the immediate reward. Args: action (numpy.array): Action to be taken, one-hot encoded. Returns: tuple: - observation (numpy.array): Agent's observation of the current environment. - reward (float) : Amount of reward returned after previous action. - done (bool): Whether the episode has ended, in which case further step() calls will return undefined results. - info (dict): Contains auxiliary diagnostic information (helpful for debugging, and sometimes learning). """ self._action = action self._iteration += 1 done = False info = {} if all(self._position != self._positions['flat']): reward = -self._time_fee self._current_pnl = 0 # 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 = "GBPUSD" 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() #------------------- instant_pnl = 0 reward = -self._time_fee if all(action == self._actions['buy']): reward -= self._trading_fee if all(self._position == self._positions['flat']): self._position = self._positions['long'] if trade: lot = 0.1 point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).ask deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_BUY, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": 1, } # 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("2. order_send done, ", result) print(" opened position with POSITION_TICKET={}".format( result.order)) self._entry_price = self._price = self._tick_buy self.Buy_render = True elif all(self._position == self._positions['short']): self._exit_price = self._exit_price = self._tick_sell instant_pnl = round(self._entry_price, 5) - round( self._exit_price, 5) self._position = self._positions['flat'] self._entry_price = 0 if trade: position_id = result.order price = mt5.symbol_info_tick(symbol).bid deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_BUY, "position": position_id, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script close", "type_time": mt5.ORDER_TIME_GTC, "type_filling": 1, } # send a trading request result = mt5.order_send(request) # check the execution result print( "3. close position #{}: sell {} {} lots at {} with deviation={} points" .format(position_id, symbol, lot, price, deviation)) if result.retcode != mt5.TRADE_RETCODE_DONE: print("4. order_send failed, retcode={}".format( result.retcode)) print(" result", result) else: print("4. position #{} closed, {}".format( position_id, result)) # 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])) positions = mt5.positions_get( symbol="GBPUSD") if positions == None: print("No positions on GBPUSD, error code={}".format( mt5.last_error())) elif len(positions) > 0: print("Total positions on GBPUSD =", len(positions)) # display all open positions for position in positions: print(position) # get the list of positions on symbols whose names contain "*USD*" usd_positions = mt5.positions_get(group="*USD*") if usd_positions == None: print( "No positions with group=\"*USD*\", error code={}". format(mt5.last_error())) elif len(usd_positions) > 0: print("positions_get(group=\"*USD*\")={}".format( len(usd_positions))) # display these positions as a table using pandas.DataFrame df = pd.DataFrame( list(usd_positions), columns=usd_positions[0]._asdict().keys()) df['time'] = pd.to_datetime(df['time'], unit='s') df.drop([ 'time_update', 'time_msc', 'time_update_msc', 'external_id' ], axis=1, inplace=True) #print(df) instant_pnl = df['profit'][-1] # self.Buy_render = True if (instant_pnl > 0): self.TP_render = True else: self.SL_render = True elif all(action == self._actions['sell']): reward -= self._trading_fee if all(self._position == self._positions['flat']): self._position = self._positions['short'] self._entry_price = self._price = self._tick_sell self.Sell_render = True if trade: lot = 0.1 point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).ask deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_SELL, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": 1 } # 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("2. order_send done, ", result) print(" opened position with POSITION_TICKET={}".format( result.order)) elif all(self._position == self._positions['long']): self._exit_price = self._tick_buy instant_pnl = round(self._exit_price, 5) - round( self._entry_price, 5) self._position = self._positions['flat'] self._entry_price = 0 if trade: position_id = result.order price = mt5.symbol_info_tick(symbol).bid deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_SELL, "position": position_id, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script close", "type_time": mt5.ORDER_TIME_GTC, "type_filling": 1, } # send a trading request result = mt5.order_send(request) # check the execution result print( "3. close position #{}: sell {} {} lots at {} with deviation={} points" .format(position_id, symbol, lot, price, deviation)) if result.retcode != mt5.TRADE_RETCODE_DONE: print("4. order_send failed, retcode={}".format( result.retcode)) print(" result", result) else: print("4. position #{} closed, {}".format( position_id, result)) # 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])) # shut down connection to the MetaTrader 5 terminal positions = mt5.positions_get(symbol="GBPUSD") if positions == None: print("No positions on GBPUSD, error code={}".format( mt5.last_error())) elif len(positions) > 0: print("Total positions on GBPUSD =", len(positions)) # display all open positions for position in positions: print(position) # get the list of positions on symbols whose names contain "*USD*" usd_positions = mt5.positions_get(group="*USD*") if usd_positions == None: print( "No positions with group=\"*USD*\", error code={}". format(mt5.last_error())) elif len(usd_positions) > 0: print("positions_get(group=\"*USD*\")={}".format( len(usd_positions))) # display these positions as a table using pandas.DataFrame df = pd.DataFrame( list(usd_positions), columns=usd_positions[0]._asdict().keys()) df['time'] = pd.to_datetime(df['time'], unit='s') df.drop([ 'time_update', 'time_msc', 'time_update_msc', 'external_id' ], axis=1, inplace=True) #print(df) instant_pnl = df['profit'][-1] # self.Sell_render = True if (instant_pnl > 0): self.TP_render = True else: self.SL_render = True else: self.Buy_render = self.Sell_render = False self.TP_render = self.SL_render = False usd_positions = mt5.positions_get(group="*USD*") reward += instant_pnl * 1000 self._total_pnl += instant_pnl * 10000 self._total_reward += reward try: self._prices_history.append(next(self._data_generator)) self._tick_sell, self._tick_buy, self.tick_mid, self.tick_rsi_14, self.tick_cci_14= \ self._prices_history[-1][:5] except StopIteration: done = True info['status'] = 'No more data.' # Game over logic if self._iteration >= self._episode_length: done = True info['status'] = 'Time out.' if reward <= self._max_lost: done = True info['status'] = 'Bankrupted.' if self._closed_plot: info['status'] = 'Closed plot' observation = self._get_observation() return observation, reward, done, info
def ticker(self, symbol): ticker = mt5.symbol_info_tick(symbol) logger.debug(ticker, extra={'type': "update"}) return (ticker.bid, ticker.ask, ticker.time_msc)
""" .symbol_select(s) takes a symbol as string and a boolean and adds the symbol in the market watch if boolean is True and removes the symbol from the market watch if boolean set to False. While retriving price data from selected symbol, pause the program for a few seconds as it takes time to download price data due to network lag""" import MetaTrader5 as mt5 import time mt5.initialize() aset_list = ['EURUSD', 'USDZAR', 'EURNOK', 'EURCHF'] def insertion(symbol): mt5.symbol_select(symbol, True) for asset in aset_list: tick = mt5.symbol_info_tick(asset) if tick == None: insertion(asset) time.sleep(5) # pausing program tick = mt5.symbol_info_tick(asset) print(tick)
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() lot = 1.0 point = mt5.symbol_info(symbol).point price = mt5.symbol_info_tick(symbol).ask deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": mt5.ORDER_TYPE_BUY, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script open", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_FOK, } # send a trading request
def get_current_prices(): """Return current buy and sell prices.""" current_buy_price = mt5.symbol_info_tick("BTCUSD")[2] current_sell_price = mt5.symbol_info_tick("BTCUSD")[1] return current_buy_price, current_sell_price
# 如果市场报价中没有此交易品种,请添加 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() # prepare the request point = mt5.symbol_info(symbol).point request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": 1.0, "type": mt5.ORDER_TYPE_BUY, "price": mt5.symbol_info_tick(symbol).ask, "sl": mt5.symbol_info_tick(symbol).ask - 100 * point, "tp": mt5.symbol_info_tick(symbol).ask + 100 * point, "deviation": 10, "magic": 234000, "comment": "python script", "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_RETURN, } # 执行检查并显示结果'按原状' result = mt5.order_check(request) print(result); # request the result as a dictionary and display it element by element result_dict = result._asdict() for field in result_dict.keys():
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 getTerminalTime(): currTick = mt5.symbol_info_tick("AUDUSD")._asdict() currTime = currTick[ 'time'] # Just need the most recent time on the M1 timeframe return currTime
def get_closed(trade, symbol='EURUSD', side='long', lot=0.01, magic=102): # 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() # create a close request ask = mt5.symbol_info_tick(symbol).ask bid = mt5.symbol_info_tick(symbol).bid if side == 'short': price = ask type_side = mt5.ORDER_TYPE_BUY elif side == 'long': price = bid type_side = mt5.ORDER_TYPE_SELL deviation = 20 request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": lot, "type": type_side, "position": trade, "price": price, "deviation": deviation, "magic": 234000, "comment": "python script close", "type_time": mt5.ORDER_TIME_GTC, #"type_filling": mt5.ORDER_FILLING_RETURN, } # send a trading request result = mt5.order_send(request) # check the execution result #print("3. close position #{}: sell {} {} lots at {} with deviation={} points".format(trade,symbol,lot,price,deviation)); if result.retcode != mt5.TRADE_RETCODE_DONE: print("4. order_send failed, retcode={}".format(result.retcode)) #print(" result",result) else: #print("4. position #{} closed, {}".format(trade,result)) # 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])) # shut down connection to the MetaTrader 5 terminal mt5.shutdown()