def Macro_Calculator(symbol, y, m, d, h1, m1, s1, h2, m2, s2): mt5.initialize() Score = np.zeros(30) Date = np.zeros(30, datetime.date) Macro_10 = np.zeros(30) adate = datetime.date(y, m, d) for j in range(0, 30): orlist = OR_Calculator(symbol, y, m, d, h1, m1, s1, h2, m2, s2) if orlist == None: adate = Time_Shift(y, m, d, symbol) y = adate[0] m = adate[1] d = adate[2] continue if Score_Calculator(symbol, y, m, d, h1, m1, s1, h2, m2, s2) == None: adate = Time_Shift(y, m, d, symbol) y = adate[0] m = adate[1] d = adate[2] continue Score[j] = Score_Calculator(symbol, y, m, d, h1, m1, s1, h2, m2, s2)[0] Date[j] = datetime.datetime(y, m, d).date() adate = Time_Shift(y, m, d, symbol) y = adate[0] m = adate[1] d = adate[2] for k in range(0, len(Score)): if k < 20: Macro_10[k] = (sum(Score[k:k + 6])) else: Macro_10[k] = None MACROs = pd.DataFrame({'Date': Date, 'Score': Score, 'Macro': Macro_10}) return MACROs
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 historyData(Symbol): mt5.initialize(server="ForexClub-MT5 Demo Server", login=500063649, password="******") # print(mt5.terminal_info()) # print(mt5.version()) listSymbols = mt5.symbols_get() # [x.name for x in listSymbols] # Symbol=np.random.choice(FXmajor, 1)[0] print(Symbol) pointValue = mt5.symbol_info(Symbol).point # mt5.Buy("EURUSD", 0.1,price=11395,ticket=9) Num_velas = 1000 # Copying data to pandas data frame # rates = mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas) rates = mt5.copy_rates_range(Symbol, mt5.TIMEFRAME_H1, datetime(2021, 1, 10), datetime.now()) # rates = mt5.copy_rates_range("ES", mt5.TIMEFRAME_D1, datetime(2019, 1, 15), datetime(2019, 1, 25)) # rates = mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas) # Deinitializing MT5 connection mt5.shutdown() # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) # convert time in seconds into the datetime format rates_frame.index = pd.to_datetime(rates_frame['time'], unit='s') rates_frame.columns = [ 'time', 'Open', 'High', 'Low', 'Close', 'tick_volume', 'spread', 'real_volume' ] return rates_frame
def get_data(self): mt5.initialize() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' objects in UTC time zone to avoid the implementation of a local time zone offset utc_from = dt(self.date_from.year, self.date_from.month, self.date_from.day, 00, 00, tzinfo=timezone) utc_to = dt(self.date_to.year, self.date_to.month, self.date_to.day, 23, 59, tzinfo=timezone) if self.time_frame == 0: data_values = mt5.copy_ticks_range(self.currency_type, utc_from, utc_to, mt5.COPY_TICKS_ALL) else: data_values = mt5.copy_rates_range(self.currency_type, self.time_frame, utc_from, utc_to) print(self.currency_type, " Data Points received: ", len(data_values)) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() data_frame = pd.DataFrame(data_values) # print(ticks_frame) return data_frame
def ATR_Calculator(y, m, d, symbol): mt5.initialize() # set time zone to UTC timezone = pytz.timezone("Etc/UTC") # create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset utc_from = datetime.datetime(y, m, d, tzinfo=timezone) # get 11 bars of any symbol that you want in 1D timeframe starting from given time in format of y=Year,m=Month,d=Day rates = mt5.copy_rates_from(symbol, mt5.TIMEFRAME_D1, utc_from, 32) # create DataFrame out of the obtained data rates_frame = pd.DataFrame(rates) DaysOn = len(rates_frame) # convert time in seconds into the datetime format rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s') # if you need to see the data print rates_frame. Otherwise let it be as a comment # print(rates_frame) # create the TR as an array with specified length if DaysOn < 3: return None else: TR = np.zeros(DaysOn - 2) # start to fill the TR for i in range(1, DaysOn - 1): TR[i - 1] = max(rates_frame['high'][i], rates_frame['close'][i - 1]) - min( rates_frame['low'][i], rates_frame['close'][i - 1]) # now make the ATR dictionary ATR = sum(TR[-10:-1]) / 10 ATR = {'time': rates_frame["time"].iloc[-1], 'ATR': ATR} return ATR
def main(): Mt5.initialize() Mt5.login(settings.METATRADE.LOGIN, password=settings.METATRADE.PASSWORD, server=settings.METATRADE.SERVER) for currency in models.Currency.objects.all().iterator( ): # type: models.Currency print(currency) name = f"{currency.first}{currency.second}".upper() latest = models.Bar.objects.filter( currency=currency).latest("time_marker__time_marker") latest_datetime = datetime.combine(latest.time_marker.time_marker, datetime.min.time()) date_to = datetime.utcnow() - timedelta(days=1) items = Mt5.copy_rates_range(name, Mt5.TIMEFRAME_D1, latest_datetime, date_to) if items is None: continue for item in items: close = item["close"] high = item["high"] low = item["low"] t = datetime.utcfromtimestamp(item["time"]).date() if t.weekday() in {6, 5}: continue time_marker = TimeMarker.objects.get_or_create(time_marker=t)[0] print(currency, time_marker) Bar.objects.update_or_create(currency=currency, time_marker=time_marker, defaults={ "close": close, "high": high, "low": low })
def load_stocks_1h(stock_name, load_from_datetime, ema_periods=(20, 50, 200)): ''' Loads hourly stock data. :param stock_name: The symbol code, e.g. AUDUSD :param load_from_datetime: This should be a datetime value e.g. dt.datetime.strptime("07/02/2020 15:00:00", "%d/%m/%Y %H:%M:%S") :param ema_periods: A tuple indicating the periods for which EMA should be calculated. :return: Returns a dictionary indexed by time. Each index is then a further dictionary see {dictionary}.keys() for more details ''' mt5.initialize() stock_data = mt5.copy_rates_range(stock_name, mt5.TIMEFRAME_H1, load_from_datetime, dt.datetime.now()) dataset = {} for datapoint in stock_data: dataset[dt.datetime.utcfromtimestamp(datapoint[0])] = { "OPEN": datapoint[1], "HIGH": datapoint[2], "LOW": datapoint[3], "CLOSE": datapoint[4], "VOLUME": datapoint[5], "SPREAD": datapoint[6] } mt5.shutdown() for period in ema_periods: dataset = exponential_moving_average(dataset, period) return dataset
def f_pip_size(param_ins): try: mt5.initialize(login=41671538, server='MetaQuotes-Demo',password='******') pip_size = int(0.1/mt5.symbol_info(param_ins)._asdict().get('trade_tick_size')) return pip_size except: return print('Ticker no válido')
def connect(self): account = int(self.account_id) mt5.initialize() try: self.authorized = mt5.login(self.account_id) except not self.authorized: print( f"Failed to connect at account #{account}, error code: {mt5.last_error()}" )
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 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 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 get_rates_from_date(initials, start_date, end_date, show_last=False): mt5.initialize() values = mt5.copy_rates_range( initials, mt5.TIMEFRAME_M1, start_date, end_date ) mt5.shutdown() return values if show_last else values[:-1]
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 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 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 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 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 connect_server(): # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() else: print("MetaTrader Connected")
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 init_mofid(): global mofid, mofid_path mofid_path = None mofid = False possible = [ "C:/Program Files/MofidTrader/terminal64.exe", "C:/Program Files/MofidTrader/terminal.exe", "C:/Program Files/MetaTrader 5/terminal64.exe", "C:/Program Files/MetaTrader 5/terminal.exe" ] for pos in possible: if os.path.isfile(pos): mofid_path = pos break if mofid_path is None: raise SaamError("COULD NOT FIND MOFID-TRADER / META-TRADER 5") if config["mofid_server"] is None: config["mofid_server"] = "MofidSecurities-Server" save_config() if config["mofid_login"] is None or config["mofid_pass"] is None: return mofid mofid = mt5.initialize(mofid_path, login=config["mofid_login"], password=config["mofid_pass"], server=config["mofid_server"]) return mofid
def __init__(self, stock): self.stock = stock if not mt5.initialize(): print("initialize() failed") mt5.shutdown() #print('Version: ', mt5.version()) pass
def __init__(self): if not mt5.initialize(): print("initialize() failed") mt5.shutdown() exit(1) else: print("initialize ok")
def main(): Mt5.initialize() Mt5.login(settings.METATRADE.LOGIN, password=settings.METATRADE.PASSWORD, server=settings.METATRADE.SERVER) for deal in models.Deal.objects.filter(status__id=1, first__time_marker__time_marker=datetime(2020, 8, 20)): # type: models.Deal result = deal.first if result.is_open(): deal.close_first() for result in first_models.Result.objects.filter(status__id=1, first__time_marker__time_marker=datetime(2020, 8, 20)): # type: first_models.Result if models.Deal.objects.filter(result=result).exist(): continue order = result.order if order.time_marker == result.time_marker: models.Deal.open_first(result=result)
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 RequestData(SymbolName, run_time, Day): # 连接到MetaTrader 5 if not mt5.initialize(login=3335660, server="Exness-MT5Real",password="******"): print("initialize() failed") # 请求连接状态和参数 #print(mt5.terminal_info()) # 获取有关MetaTrader 5版本的数据 #print(mt5.version()) try: if run_time == 'H1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_H1, 0, Day) # 通过多种方式获取不同交易品种的柱形图 elif run_time == 'H4': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_H4, 0, Day) elif run_time == 'D1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_D1, 0, Day) elif run_time == 'W1': rates = mt5.copy_rates_from_pos(SymbolName, mt5.TIMEFRAME_W1, 0, Day) except Exception as e: log.error("生成K线图时,获取MT5数据失败........."+str(e)) # 断开与MetaTrader 5的连接 mt5.shutdown() #DATA #print(rates) #PLOT # 从所获得的数据创建DataFrame ticks_frame = pd.DataFrame(rates) ticks_frame=ticks_frame.drop(ticks_frame.index[1]) # 将时间(以秒为单位)转换为日期时间格式 ticks_frame['time']=pd.to_datetime(ticks_frame['time'], unit='s') return ticks_frame
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_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 ini(count_wins, count_losses, curr_pair): print( f"\ncurrent score is: {count_wins} wins, {count_losses} losses. Win percentage over total = {round(count_wins/(count_wins+count_losses+0.0000001),2)}" ) if not mt5.initialize(): print("initialize() failed") pickle_my_pickles(count_wins, count_losses, curr_pair)
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