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 get_ticks(self,start_day: int,end_day ,month: int,year: int): ''' Upload the data Parameters ---------- symbol : name symbol ticker day: corrent day upload month: corrent month upload year: corrent year upload Returns ------- base : pandas dataframe ''' # tratamento de exeção para dias não operaveis try: timezone = pytz.timezone("America/Sao_Paulo") # criamos o objeto datatime no fuso horário UTC para que não seja aplicado o deslocamento do fuso horário local utc_from = datetime(year, month, start_day, tzinfo=timezone) utc_to = datetime(year, month, end_day, tzinfo=timezone) # solicitamos ticks de um intervalo ticks_ = mt5.copy_ticks_range(self.symbol, utc_from, utc_to, mt5.COPY_TICKS_ALL) # Convertemos para pandas dataframe ticks_ = pd.DataFrame(ticks_) # transformar timestamp em segundos ticks_['time']=pd.to_datetime(ticks_['time'],unit='s') # ticks_.set_index('time',inplace=True) return ticks_ except ValueError: print("Dia não existe") return pd.DataFrame(columns=['valor'])
def get_ticks(self, symbol, from_date, to_date): """ Gets OHLC price data for the specified symbol. :param symbol: The name of the symbol to get the price data for. :param from_date: Date from when to retrieve data :param to_date: Date where to receive data to :return: Tick data for symbol as dataframe """ ticks_dataframe = None # Get ticks from MT5 ticks = MetaTrader5.copy_ticks_range(symbol, from_date, to_date, MetaTrader5.COPY_TICKS_ALL) # If ticks is None, there was an error if ticks is None: error = MetaTrader5.last_error() self.__log.error(f"Error retrieving ticks for {symbol}: {error}") else: self.__log.debug(f"{len(ticks)} ticks retrieved for {symbol}.") # Create dataframe from data and convert time in seconds to datetime format try: ticks_dataframe = pd.DataFrame(ticks) ticks_dataframe['time'] = pd.to_datetime( ticks_dataframe['time'], unit='s') except RecursionError: self.__log.warning("Error converting ticks to dataframe.") return ticks_dataframe
def f_be_de_parte1(param_data): # Filtrado de operaciones ganadoras (operaciones ancla) param_data['capital_acm'] = param_data['profit_acm'] + 100000 ganadoras = param_data[param_data.Profit > 0] ganadoras = ganadoras.reset_index(drop=True) ganadoras["Ratio"] = (ganadoras["Profit"] / abs(ganadoras["profit_acm"])) df_anclas = ganadoras.loc[:, [ 'close_time', "open_time", 'Type', "Symbol", 'Profit', "profit_acm", "capital_acm", "Ratio", "Time", "Time.1", "Price", "Volume" ]] df_anclas = df_anclas.reset_index(drop=True) # Criterio de selección de operaciones abiertas por cada ancla ocurrencias = [] file_list = [] for x in df_anclas.index: df = param_data[ (param_data.open_time <= df_anclas["close_time"][x]) & (param_data.close_time > df_anclas["close_time"][x] )].loc[:, ['Type', 'Symbol', 'Volume', 'Profit', "Price", "pips"]] df['close_time_ancla'] = pd.Timestamp(df_anclas['close_time'][x]) file_list.append(df) ocurrencias.append(len(df)) all_df = pd.concat(file_list, ignore_index=True) # Descarga de precios para cada operación abierta float_price = [] if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() for i in range(len(all_df)): utc_from = datetime(all_df['close_time_ancla'][i].year, all_df['close_time_ancla'][i].month, all_df['close_time_ancla'][i].day) utc_to = utc_from + timedelta(1) symbol = all_df['Symbol'][i] ticks = mt5.copy_ticks_range(symbol, utc_from, utc_to, mt5.COPY_TICKS_ALL) ticks_frame = pd.DataFrame(ticks) ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') tick_time = next(x for x in ticks_frame['time'] if x >= all_df['close_time_ancla'][i]) price = ticks_frame.loc[ticks_frame['time'] == tick_time] if all_df["Type"][i] == "buy": price = price["bid"].mean() else: price = price["ask"].mean() float_price.append(price) float_prices = pd.DataFrame(columns=['float_price'], data=float_price) all_df = all_df.join(float_prices) all_df = f_columnas_pips_v2(all_df) all_df["float_P&L"] = (all_df["Profit"] / all_df["pips"]) * all_df["float_pips"] all_df = all_df[all_df['float_P&L'] < 0].reset_index(drop=True) return all_df, df_anclas
def get_ticks_range(symbol, start, end, timezone): """ :param symbol: str, symbol :param start: tuple, (2019,1,1) :param end: tuple, (2020,1,1) :param count: :return: """ utc_from = timeModel.get_utc_time_from_broker(start, timezone) utc_to = timeModel.get_utc_time_from_broker(end, timezone) ticks = mt5.copy_ticks_range(symbol, utc_from, utc_to, mt5.COPY_TICKS_ALL) ticks_frame = pd.DataFrame( ticks ) # set to dataframe, several name of cols like, bid, ask, volume... ticks_frame['time'] = pd.to_datetime( ticks_frame['time'], unit='s') # transfer numeric time into second ticks_frame = ticks_frame.set_index('time') # set the index return ticks_frame
def _request_ticks_and_resample(pair, period, _from, _to) -> list: ''' Ticks will be resampled into 1 second bars. Returns a list with name of pair in index 0 and dataframe in index 1. ''' ticks = mt5.copy_ticks_range(pair, _from, _to, mt5.COPY_TICKS_ALL) df = pd.DataFrame(ticks) df = df.rename(columns={df.columns[0]: 'datetime'}) df.datetime = pd.to_datetime(df.datetime, unit='s') df.datetime = df.datetime - pd.Timedelta('5 hours') df = df.set_index(df.datetime, drop=True) # Save volume (count each tick) df.volume = 1 # To avoid spikes due to a widening spread get an average price df['price'] = (df.bid + df.ask) / 2 df = df[['price', 'volume']] open = df.price.resample(period).first() high = df.price.resample(period).max() low = df.price.resample(period).min() close = df.price.resample(period).last() volume = df.volume.resample(period).sum() resampled = pd.DataFrame({ 'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume }) # Check for nan volume rows and set to 0 resampled.volume.replace(np.nan, 0) # Any remaining nans should be forward filled resampled = resampled.fillna(method='ffill') # Return the name of pair along with the dataframe return [pair, resampled]
def OR_Calculator(symbol,y,m,d,h1,m1,s1,h2,m2,s2): #connect to Metatrader 5 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 OR_Start = datetime.datetime(y, m, d, h1, m1, s1, tzinfo=timezone) OR_Stop = datetime.datetime(y, m, d, h2, m2, s2, tzinfo=timezone) # request any symbol that you want and it's ticks within different Opening Ranges that you want ticks = mt5.copy_ticks_range(symbol , OR_Start, OR_Stop, mt5.COPY_TICKS_ALL) # in case that symbol has not been traded this day if len(ticks) == 0: return None # calculate the OR_high and OR_low ticks_frame = pd.DataFrame(ticks) ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') # find the start time which is the time that first trade is done #print(ticks_frame) start = 0 for i in range(0,len(ticks_frame)): if (ticks_frame["bid"][i] == ticks_frame["last"][i]) or (ticks_frame["ask"][i] == ticks_frame["last"][i]): ticks_frame = ticks_frame[i:] start = i break for j in range(start,len(ticks_frame)): timediff = ticks_frame["time"][j] - ticks_frame["time"][start] timediff = int(datetime.timedelta.total_seconds(timediff)) / 60 if timediff >= 15: ticks_frame = ticks_frame[:j] print(ticks_frame) stop = j break H = datetime.datetime.time(ticks_frame["time"].iloc[0]).hour M = datetime.datetime.time(ticks_frame["time"].iloc[0]).minute S = datetime.datetime.time(ticks_frame["time"].iloc[0]).second # find the OR_high and OR_low OR_high = max(ticks_frame["last"]) OR_low = min(ticks_frame["last"]) return [OR_high, OR_low, H, M, S]
def test(): # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() print('Version:', mt5.version()) #dji = mt5.copy_rates_range('US30Cash', mt5.TIMEFRAME_M30, Now() - DeltaDay(2), Now()) #print(dji) # request 1000 ticks from EURAUD euraud_ticks = mt5.copy_ticks_from("US30Cash", datetime(2020,4,17,23), 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(2020,1,27,13), datetime(2020,1,28,13), mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(2020,1,28,13), 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(2020,1,27,13), datetime(2020,1,28,13)) #print(eurusd_rates) # shut down connection to MetaTrader 5 mt5.shutdown() return
# connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # request connection status and parameters print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version()) # request ticks from GBPUSD gbpusd_ticks = mt5.copy_ticks_from("GBPUSD", datetime(2021, 1, 18, 13), 1, mt5.COPY_TICKS_ALL) # request ticks from GBPJPY within 2020.01.20 13:00 - 2020.03.18 13:00 gbpusdticks = mt5.copy_ticks_range("GBPUSD", datetime(2021, 1, 20, 13), datetime(now), mt5.COPY_TICKS_ALL) # get bars from different symbols in 3 different ways gbpusd_rates = mt5.copy_rates_from("GBPUSD", mt5.TIMEFRAME_M15, datetime(2020, 1, 20, 13), 1) gbpusd_rates = mt5.copy_rates_from_pos("GBPUSD", mt5.TIMEFRAME_M15, 0, 1) gbpusd_rates = mt5.copy_rates_range("GBPUSD", mt5.TIMEFRAME_M15, datetime(2020, 1, 20, 13), datetime(2020, 3, 18, 13)) # shut down connection to MetaTrader 5 mt5.shutdown() #data to be displayed in the terminal print('gbpusd_ticks(', len(gbpusd_ticks), ')') for val in gbpusd_ticks[:1]:
def acquireTicksRange(self, from_jst, to_jst): utc_from = TimeUtility.jst2seasonalAwaretime(from_jst) utc_to = TimeUtility.jst2seasonalAwaretime(to_jst) d = mt5.copy_ticks_range(self.stock, utc_from, utc_to, mt5.COPY_TICKS_ALL) data = self.convert2ArrayTick(d) return data
pd.set_option('display.width', 1500) # max table width to display # import pytz module for working with time zone import pytz # establish connection to MetaTrader 5 terminal if not mt5.initialize(): print("initialize() failed, error code =", mt5.last_error()) quit() # 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 = datetime(2020, 1, 10, tzinfo=timezone) utc_to = datetime(2020, 1, 11, tzinfo=timezone) # request AUDUSD ticks within 11.01.2020 - 11.01.2020 ticks = mt5.copy_ticks_range("AUDUSD", utc_from, utc_to, mt5.COPY_TICKS_ALL) print("Ticks received:", len(ticks)) # shut down connection to the MetaTrader 5 terminal mt5.shutdown() # display data on each tick on a new line print("Display obtained ticks 'as is'") count = 0 for tick in ticks: count += 1 print(tick) if count >= 10: break # create DataFrame out of the obtained data
# Weekend End Enable / Disable Code # if now.weekday() > 4: # mt5.shutdown() # print("Week End No Rates") # exit(0) # end december_month = 12 # request 1000 ticks from EURAUD euraud_ticks = mt5.copy_ticks_from("EURAUD", datetime(now.year, now.month, now.day, now.hour), 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 # if now.day > 1: # audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year, now.month, now.day-1, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) if now.weekday() == 0 and now.day == 1 and now.month > 1: audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year, now.month-1, now.day - 3, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) elif now.weekday() > 0 and now.day == 1 and now.month > 1: audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year, now.month - 1, now.day - 1, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) elif now.weekday() == 0 and now.day == 1 and now.month == 1: audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year-1, december_month, now.day - 3, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) elif now.weekday() > 0 and now.day == 1 and now.month == 1: audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year-1, december_month, now.day - 1, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) else: audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(now.year, now.month, now.day - 1, now.hour), datetime(now.year, now.month, now.day, now.hour), mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(now.year, now.month, now.day, now.hour), 1000)
def Score_Calculator(symbol,y,m,d,h1,m1,s1,h2,m2,s2): # from orlist find OR_high and OR_low orlist = OR_Calculator(symbol, y, m, d, h1, m1, s1, h2, m2, s2) H2 = int(orlist[2]) M2 = int(orlist[3]) S2 = int(orlist[4]) OR_high = orlist[0] OR_low = orlist[1] 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 Session_Start = datetime.datetime(y, m, d, H2, M2, S2, tzinfo=timezone) Session_Stop = datetime.datetime(y, m, d, h2, m2, s2, tzinfo=timezone) # request any symbol that you want and it's ticks within different Opening Ranges that you want ticks = mt5.copy_ticks_range(symbol , Session_Start, Session_Stop, mt5.COPY_TICKS_ALL) if len(ticks) == 0: return None # make the dataframe of ticks ticks_frame = pd.DataFrame(ticks) # convert time in seconds into the datetime format ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') # get the closing price LAST = ticks_frame["last"].iloc[-1] # get the ATR and make the A and C levels if ATR_Calculator(y, m, d, symbol) == None: return None else:atr = ATR_Calculator(y, m, d, symbol)["ATR"] A_up = OR_high + (atr)*0.1 A_down = OR_low - (atr)*0.1 C_up = OR_high + (atr)*0.15 C_down = OR_low - (atr)*0.15 i=0 checklist = [] if not OR_low == OR_high: while i < int(ticks_frame["time"].index[-1]): t = ticks_frame["time"][i] # iterate through ticks_frame if ticks_frame['last'][i] >= A_up: #print("A_Up!!!") # check if the price touched the A_up level for j in range(i+1,len(ticks_frame)): # for 8 minutes check if validation of A_up is confirmed timediff = ticks_frame["time"][j] - ticks_frame["time"][i] timediff = (datetime.timedelta.total_seconds(timediff)) / 60 if ticks_frame["last"][j] < OR_high and timediff < 8: # if price has returned below OR line, then call it A_up_fail checklist.append("A_up_fail") #print("in time {} and index {} A_up fail!".format(ticks_frame["time"][j], j)) i = j+1 # we should go on and check again for index i = j+1 break elif ticks_frame["last"][j] > OR_high and timediff >= 8: checklist.append("A_up_valid") #print("in time {} A_up Valid!".format(ticks_frame["time"][j])) for k in range(j+1, len(ticks_frame)): if ticks_frame["last"][k] < OR_high: checklist.append("A_up_stop") #print("in time {} Stop!".format(ticks_frame["time"][k])) i = k+1 break else: continue i = k+1 break else: continue i = j + 1 elif ticks_frame['last'][i] <= A_down: # check if the price touched the A_up level for m in range(i+1,len(ticks_frame)): # for 8 minutes check if validation of A_up is confirmed timediff = ticks_frame["time"][m] - ticks_frame["time"][i] timediff = (datetime.timedelta.total_seconds(timediff)) / 60 if ticks_frame["last"][m] > OR_low and timediff < 8: # if price has returned below OR line, then call it A_up_fail checklist.append("A_down_fail") #print("in time {} A_down fail!".format(ticks_frame["time"][m])) i = m+1 # we should go on and check again for index i = j+1 break elif ticks_frame["last"][m] < OR_low and timediff >= 8: checklist.append("A_down_valid") #print("in time {} A_down Valid!".format(ticks_frame["time"][m])) for n in range(m+1, len(ticks_frame)): if ticks_frame["last"][n] > OR_low: checklist.append("A_down_stop") #print("in time {} Stop!".format(ticks_frame["time"][n])) i = n+1 break else: continue i = n+1 break else: continue else: i = i+1 if i < len(ticks_frame): continue else: break #print(checklist) # calculate the score Score = 10000 checkset = sorted(set(checklist), key=checklist.index) if not OR_low == OR_high: if (OR_low < ticks_frame["last"].iloc[-1] < OR_high): if ("A_up_fail" in checklist) and len(set(checklist)) == 1: Score = -1 elif ("A_down_fail" in checklist) and len(set(checklist)) == 1: Score = 1 else: Score = 0 elif (ticks_frame["last"].iloc[-1] <= OR_low): if checkset == ["A_up_fail", "A_down_valid"] or checkset == ["A_up_fail"]: Score = -3 elif "A_up_valid" in checkset and "A_down_stop" not in checkset: Score = -4 else: Score = -2 elif (ticks_frame["last"].iloc[-1] >= OR_high): if checkset == ["A_down_fail", "A_up_valid"] or checkset == ["A_down_fail"]: Score = 3 elif "A_down_valid" in checkset and "A_up_stop" not in checkset: Score = 4 else: Score = 2 elif (OR_low == OR_high): timeshift = Time_Shift(y,m,d,symbol) Y = timeshift[0] M = timeshift[1] D = timeshift[2] OR_prev = OR_Calculator(symbol, Y, M, D, h1, m1, s1, h2, m2, s2) if OR_high > OR_prev[0]: if (ticks_frame["last"].iloc[-1] == OR_high): Score = 2 elif OR_high/ticks_frame["last"].iloc[-1] >= 1.09: Score = -4 elif (ticks_frame["last"].iloc[-1] < OR_high): Score = 0 if OR_low < OR_prev[1]: if (ticks_frame["last"].iloc[-1] == OR_low): Score = -2 elif ticks_frame["last"].iloc[-1]/OR_low >= 1.09: Score = 4 elif (ticks_frame["last"].iloc[-1] > OR_low): Score = 0 return [Score, checklist, OR_high , OR_low]
#____________Symbol info____________# # mt5.symbol_select('EURTRY', False) #puts/removes the entered symbol in the marketwatch eurinfo = mt5.symbol_info('EURUSD') #gives the information of the asset print(eurinfo) print('=' * 90, '\n') eurtick = mt5.symbol_info_tick('EURUSD') #gives the latest tick info print('tick info:', eurtick) print('=' * 90, '\n') #_______________retriving OHLC data______________# eurbar = mt5.copy_rates_from('EURUSD', mt5.TIMEFRAME_H1, tiem, 1) print('bars: ', eurbar, '\n') # for i in eurbar: # print(i) eurbar2 = mt5.copy_rates_range('EURUSD', mt5.TIMEFRAME_H1, tiem, tiem2) print('bars range: ', eurbar2, '\n') eurbar3 = mt5.copy_rates_from_pos('EURUSD', mt5.TIMEFRAME_H1, 0, 3) print('bars from pos:', eurbar3, '\n') print('=' * 90, '\n') #__________________retriving ticks____________________# eurtic = mt5.copy_ticks_from('EURUSD', tiem, 3, mt5.COPY_TICKS_INFO) print('EURUSD Tic', eurtic, '\n') eurtic2 = mt5.copy_ticks_range('EURUSD', tiem, tiem2, mt5.TIMEFRAME_H1) print('EURUSD Tic range', eurtic2, '\n')
def f_be_de(param_data): param_data = param_data.loc[:, ('Symbol', 'Type', 'Volume', 'Price', 'Price.1', 'Profit', 'open_time', 'close_time', 'pips', 'profit_acm')] #Se seleccionan las operaciones anclas(aquellas con profit positivo) df_anclas = param_data[param_data['Profit'] > 0].reset_index( drop=True) #reiniciar contador de índices #Checar si hubo operaciones abiertas al cerrar un ancla ocurrencias = pd.concat([ param_data.iloc[j, :] for i in range(len(df_anclas)) for j in range(len(param_data)) if param_data['close_time'][j] > df_anclas['close_time'][i] and param_data['open_time'][j] < df_anclas['close_time'][i] ], 1).transpose() #Incluir la fecha de cierre de la operación ancla times_ancla = [ df_anclas.loc[i, ('close_time')] for i in range(len(df_anclas)) for j in range(len(param_data)) if param_data['close_time'][j] > df_anclas['close_time'][i] and param_data['open_time'][j] < df_anclas['close_time'][i] ] #Se añade la columna con los tiempos de cierre del ancla ocurrencias['close_ancla'] = times_ancla precio_flotante = [] for i in range(len(ocurrencias)): from_date = datetime(ocurrencias['close_ancla'].iloc[i].year, ocurrencias['close_ancla'].iloc[i].month, ocurrencias['close_ancla'].iloc[i].day) to_date = from_date + timedelta(1) sym = ocurrencias['Symbol'].iloc[i] ticks = mt5.copy_ticks_range(sym, from_date, to_date, mt5.COPY_TICKS_ALL) df_t = pd.DataFrame(ticks) df_t['time'] = pd.to_datetime(df_t['time'], unit='s') if ocurrencias['Type'].iloc[i] == 'buy': tipo = 'bid' else: tipo = 'ask' precio_flotante.append(df_t[f'{tipo}'][ df_t['time'] >= ocurrencias['close_ancla'].iloc[0]].iloc[0]) ocurrencias['precio_flotante'] = precio_flotante ocurrencias['pip_value'] = abs(ocurrencias['Profit'] / ocurrencias['Price'] - ocurrencias['Price.1']) #profit flotante, lo que ganas o pierdes en ese momento que cerró el ancla p_flotante = [ ocurrencias['pip_value'].iloc[i] * (ocurrencias['precio_flotante'].iloc[i] - ocurrencias['Price'].iloc[i]) if ocurrencias['Type'].iloc[i] == 'buy' else ocurrencias['pip_value'].iloc[i] * (ocurrencias['Price'].iloc[i] - ocurrencias['precio_flotante'].iloc[i]) for i in range(len(ocurrencias)) ] ocurrencias['profit_flotante'] = p_flotante ocurrencias = ocurrencias[ocurrencias['profit_flotante'] < 0].reset_index( drop=True) #Diccionario diccionario = {'ocurrencias': {'cantidad': len(ocurrencias)}} for i in range(len(ocurrencias)): ganadora = df_anclas[ocurrencias['close_ancla'].iloc[i] == df_anclas['close_time']] diccionario['ocurrencias'][f'ocurrencia_{i+1}'] = { 'timestamp': ocurrencias['close_ancla'].iloc[i], 'operaciones': { 'ganadoras': { 'instrumento': ganadora['Symbol'].iloc[0], 'volumen': ganadora['Volume'].iloc[0], 'sentido': ganadora['Type'].iloc[0], 'profit_ganadora': ganadora['Profit'].iloc[0] }, 'perdedoras': { 'instrumento': ocurrencias['Symbol'].iloc[i], 'volumen': ocurrencias['Volume'].iloc[i], 'sentido': ocurrencias['Type'].iloc[i], 'profit_perdedora': ocurrencias['profit_flotante'].iloc[i] } }, 'ratio_cp_profit_acm': abs(ocurrencias['profit_flotante'].iloc[i] / ganadora['profit_acm'].iloc[0]), 'ratio_cg_profit_acm': abs(ganadora['Profit'].iloc[0] / ganadora['profit_acm'].iloc[0]), 'ratio_cp_cg': abs(ocurrencias['profit_flotante'].iloc[i] / ganadora['Profit'].iloc[0]) } status_quo = 0 aversion_perdida = 0 for i in range(len(ocurrencias)): if diccionario['ocurrencias'][f'ocurrencia_{i+1}'][ 'ratio_cp_profit_acm'] < diccionario['ocurrencias'][ f'ocurrencia_{i+1}']['ratio_cg_profit_acm']: status_quo += 1 if diccionario['ocurrencias'][f'ocurrencia_{i+1}']['ratio_cp_cg'] > 2: aversion_perdida += 1 sensibilidad_decreciente = 0 if df_anclas['profit_acm'].iloc[-1] > df_anclas['profit_acm'].iloc[0]: sensibilidad_decreciente += 1 if df_anclas['Profit'].iloc[-1] > df_anclas['Profit'].iloc[ 0] and ocurrencias['profit_flotante'].iloc[-1] > ocurrencias[ 'profit_flotante'].iloc[0]: sensibilidad_decreciente += 1 if diccionario['ocurrencias'][f'ocurrencia_{len(ocurrencias)}'][ 'ratio_cp_cg'] > 2: sensibilidad_decreciente += 1 if sensibilidad_decreciente >= 2: final = 'Si' else: final = 'No' diccionario['resultados'] = { 'dataframe': pd.DataFrame({ 'ocurrencias': len(ocurrencias), 'status_quo': str(round(100 * status_quo / len(ocurrencias), 2)) + '%', 'aversion_perdida': str(round(100 * aversion_perdida / len(ocurrencias), 2)) + '%', 'sensibilidad_decreciente': [final] }) } diccionario2 = pd.DataFrame( { 'ocurrencias': len(ocurrencias), 'status_quo': str(round(100 * status_quo / len(ocurrencias), 2)) + '%', 'aversion_perdida': str(round(100 * aversion_perdida / len(ocurrencias), 2)) + '%', 'sensibilidad_decreciente': [final] }, columns=[ 'ocurrencias', 'status_quo', 'aversion_perdida', 'sensibilidad_decreciente' ]) return diccionario2
def get_ticks(self, symbol, utc_from, utc_to): ticks = mt5.copy_ticks_range(symbol, utc_from, utc_to, mt5.COPY_TICKS_ALL) ticks_df = pd.DataFrame(ticks) ticks_df["time"] = pd.to_datetime(ticks_df["time"], unit="s") return ticks_df
import MetaTrader5 as mt5 # conecte-se ao MetaTrader 5 if not mt5.initialize(login=25115284, server="MetaQuotes-Demo",password="******"): print("initialize() failed") mt5.shutdown() # consultamos o estado e os parâmetros de conexão print(mt5.terminal_info()) # obtemos informações sobre a versão do MetaTrader 5 print(mt5.version()) # solicitamos 1 000 ticks de EURAUD euraud_ticks = mt5.copy_ticks_from("EURAUD", datetime(2020,10,30,13), 1000, mt5.COPY_TICKS_ALL) # solicitamos ticks de AUDUSD no intervalo 2019.10.29 13:00 - 2019.10.30 13:00 audusd_ticks = mt5.copy_ticks_range("AUDUSD", datetime(2020,10,29,13), datetime(2020,10,30,13), mt5.COPY_TICKS_ALL) # obtemos barras de vários instrumentos de diferentes maneiras eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(2020,10,30,13), 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(2020,10,29,13), datetime(2020,10,30,13)) # concluímos a conexão ao MetaTrader 5 mt5.shutdown() #DATA print('euraud_ticks(', len(euraud_ticks), ')') for val in euraud_ticks[:10]: print(val) print('audusd_ticks(', len(audusd_ticks), ')') for val in audusd_ticks[:10]: print(val)
# 例 : (1580209200, 1.63412, 1.63437, 0., 0, 1580209200067, 130, 0.) from datetime import datetime euraud_ticks = mt5.copy_ticks_from("EURAUD", datetime(2020, 1, 28, 13), 1000, mt5.COPY_TICKS_ALL) print(len(euraud_ticks)) # 顯示所有交易品種 # for i in mt5.symbols_get(): # print(i.name) # 請求 2020/1/27 13:00 - 2020/1/28 13:00 之間的 AUDUSD 所有報價 import pytz timezone = pytz.timezone("Etc/UTC") time1 = datetime(2021, 1, 27, 15, tzinfo=timezone) time2 = datetime(2021, 1, 28, 9, tzinfo=timezone) audusd_ticks = mt5.copy_ticks_range("AUDUSD", time1, time2, mt5.COPY_TICKS_ALL) print(len(audusd_ticks)) audusd_ticks = mt5.copy_ticks_range("USDJPY", time1, time2, mt5.COPY_TICKS_ALL) print(len(audusd_ticks)) # 通過多種方式獲取不同交易品種的柱形圖 # Args : 交易品種, 時間週期, 開盤日期, 樣本數目 # 返回 時間, 開盤價, 最高價, 最低價, 收盤價, tick_volume, 點差, real_volume # 例 : (1578484800, 1.11382, 1.11385, 1.1111, 1.11199, 9354, 1, 0) eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1, datetime(2020, 1, 28, 13), 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M5, datetime(2020, 1, 27, 13), datetime(2020, 1, 28, 13)) a = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(2020, 1, 27, 13),
df_symbol_rates = pd.DataFrame(symbol_rates) df_symbol_rates['time'] = pd.to_datetime(df_symbol_rates['time'], unit='s') my_symbols_etf_rates[symbol] = df_symbol_rates # get ticks from - what are TICKS and how this data can be used? my_symbols_etf_ticks = {} for symbol in my_symbols_etf: symbol_ticks = mt5.copy_ticks_from(symbol, datetime(2020, 5, 18, 0), 100, mt5.COPY_TICKS_TRADE) df_symbol_ticks = pd.DataFrame(symbol_ticks) df_symbol_ticks['time'] = pd.to_datetime(df_symbol_ticks['time'], unit='s') my_symbols_etf_ticks[symbol] = df_symbol_ticks # copy ticks range function timezone = pytz.timezone("Etc/UTC") my_symbols_etf_ticks = {} for symbol in my_symbols_etf: symbol_ticks = mt5.copy_ticks_range( symbol, datetime(2020, 7, 14, 0, tzinfo=timezone), datetime(2020, 7, 17, 23, tzinfo=timezone), mt5.COPY_TICKS_ALL) df_symbol_ticks = pd.DataFrame(symbol_ticks) df_symbol_ticks['time'] = pd.to_datetime(df_symbol_ticks['time'], unit='s') my_symbols_etf_ticks[symbol] = df_symbol_ticks # get total number of active orders orders = mt5.orders_total() # get total number of open positions positions = mt5.positions_total() mt5.shutdown()
# connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # request connection status and parameters print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version()) # request 1000 ticks from EURAUD euraud_ticks = mt5.copy_ticks_from("ETHLTC.", datetime(2020, 1, 28, 13), 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 audusd_ticks = mt5.copy_ticks_range("BCHETH.", datetime(2020, 1, 27, 13), datetime(2020, 1, 28, 13), mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("ETHLTC.", mt5.TIMEFRAME_M1, datetime(2020, 1, 28, 13), 1000) eurgbp_rates = mt5.copy_rates_from_pos("BCHETH.", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("ETHEUR.", mt5.TIMEFRAME_M1, datetime(2020, 1, 27, 13), datetime(2020, 1, 28, 13)) # shut down connection to MetaTrader 5 mt5.shutdown() #DATA print('euraud_ticks(', len(euraud_ticks), ')')
from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import MetaTrader5 as mt5 # connect to MetaTrader 5 if not mt5.initialize(): print("initialize() failed") mt5.shutdown() # request connection status and parameters print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version()) # request ticks from EURRUB within range eurrub_ticks = mt5.copy_ticks_range("EURRUB", datetime(2020,10,27,13), datetime(2020,10,28,13), mt5.COPY_TICKS_ALL) # shut down connection to MetaTrader 5 mt5.shutdown() #DATA print('eurrub_ticks(', len(eurrub_ticks), ')') for val in eurrub_ticks[:10]: print(val) #PLOT # create DataFrame out of the obtained data ticks_frame = pd.DataFrame(eurrub_ticks) # convert time in seconds into the datetime format ticks_frame['time']=pd.to_datetime(ticks_frame['time'], unit='s') # display ticks on the chart
# request connection status and parameters print(mt5.terminal_info()) # get data on MetaTrader 5 version print(mt5.version()) start_date=datetime(2021,1,27,10) end_date=datetime(2021,1,27,11) # request 1000 ticks from EURAUD #datetime(year,month,day,hour) euraud_ticks = mt5.copy_ticks_from("EURAUD", start_date, 1000, mt5.COPY_TICKS_ALL) # request ticks from AUDUSD within 2019.04.01 13:00 - 2019.04.02 13:00 audusd_ticks = mt5.copy_ticks_range("AUDUSD", start_date, end_date, mt5.COPY_TICKS_ALL) # get bars from different symbols in a number of ways eurusd_rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_M1,start_date, 1000) eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000) eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, start_date, end_date) # shut down connection to MetaTrader 5 mt5.shutdown() #DATA print('euraud_ticks(', len(euraud_ticks), ')') for val in euraud_ticks[:10]: print(val) print('audusd_ticks(', len(audusd_ticks), ')') for val in audusd_ticks[:10]: print(val)
# 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.fromisoformat(startDateTime) startDateTimeStr = utc_from.strftime("%Y%m%d%H%M%S") #delta_time = datetime.timedelta(seconds=86399) delta_time = datetime.timedelta(days=1) try: while utc_from < datetime.datetime.now(datetime.timezone.utc): if utc_from.weekday() == 5 or utc_from.weekday() == 6: print('skipping:{}'.format( utc_from.strftime("%Y-%m-%d %H:%M:%S %A"))) utc_from = utc_from + delta_time continue ticks = mt5.copy_ticks_range(currencyPair, utc_from, utc_from + delta_time, mt5.COPY_TICKS_ALL) ticks_frame = pd.DataFrame(ticks) # convert time in seconds into the datetime format ticks_frame['time'] = pd.to_datetime(ticks_frame['time'], unit='s') #write fixed start and end points ticks_frame.iloc[0, ticks_frame.columns.get_loc('time')] = pd.Timestamp( utc_from.strftime('%Y-%m-%d %H:%M:%S')) endtime = datetime.datetime.combine(utc_from.date(), datetime.time(23, 59, 59)) ticks_frame.iloc[-1, ticks_frame.columns.get_loc('time')] = pd.Timestamp( endtime.strftime('%Y-%m-%d %H:%M:%S')) # drop duplicates ticks_frame = ticks_frame.drop_duplicates(subset=['time'])