Ejemplo n.º 1
0
def getBars(symbol, start, end=None, timeFrame=INTRADAY):
    # definimos o fuso horário como UTC
    #timezone = pytz.timezone("Etc/UTC")
    #print("timeFrame: ",timeFrame)
    #print("symbol: ",symbol)
    #print("start: ",start)
    #print("end: ",end)
    if not connected:
        print(
            "In order to use this function, you must be connected to B3. Use function connect()"
        )
        return
    if symbol == None or type(symbol) != str:
        return None
    else:
        symbol = symbol.upper()
    if timeFrame == DAILY:
        timeFrame = mt5.TIMEFRAME_D1
    elif timeFrame == INTRADAY:
        timeFrame = mt5.TIMEFRAME_M1
    else:
        timeFrame = mt5.TIMEFRAME_D1
    if end == None:
        end = datetime.now()
    if type(start).__name__ != 'datetime' and type(
            start).__name__ != 'Timestamp':
        if type(start).__name__ != 'int':
            print('Error, start should be a datetime or int, but it is ',
                  type(start).__name__)
            return None
        else:
            start_day = datetime.now()  #- timedelta(days=start)
            rates = mt5.copy_rates_from(symbol, timeFrame, start_day, start)
            # criamos a partir dos dados obtidos DataFrame
            rates_frame = pd.DataFrame(rates)
            if len(rates_frame) > 0:
                rates_frame['time'] = pd.to_datetime(rates_frame['time'],
                                                     unit='s')
            #print("rates", rates_frame)
            return rates_frame
    else:
        if type(end).__name__ == 'int':
            rates = mt5.copy_rates_from(symbol, timeFrame, start, end)
        else:
            rates = mt5.copy_rates_range(symbol, timeFrame, start, end)
    # criamos a partir dos dados obtidos DataFrame
        rates_frame = pd.DataFrame(rates)
        if len(rates_frame) > 0:
            rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
        #print("rates", rates_frame)
        return rates_frame
Ejemplo n.º 2
0
    def get_prices(self, event, timeframe, fromdate, numberofcandles):

        prices = pd.DataFrame()
        symbols = self.__companies['Ticker']
        tmp = {}

        for i in symbols:
            # try:

            tmp = mt5.copy_rates_from(i, timeframe, fromdate, numberofcandles)

            # if (i==symbols[0]):
            #     prices=pd.DataFrame()
            #     prices['time'] = pd.to_datetime(tmp['time'], unit='s')
            #     prices.rename({'time': 'Date'}, axis=1, inplace=True)
            #     prices.set_index('Date', inplace=True)
            # shutdown()
            # tmp = web.DataReader(i, self.__api, start_date, end_date)
            # print('Fetched prices for: '+i)
            # print(tmp.head())
            #
            # for col in tmp.columns:
            #     print(col)

            # except:
            #     print('Issue getting prices for: '+i)
            # else:
            prices[i] = tmp[event]

        return prices
Ejemplo n.º 3
0
    def copy(self, symbol, date_from, date_to=None, count=None, timeframe=mt5.TIMEFRAME_H1):
        """
        Args:
            symbol    (list)    : List of symbols
                Get all symbols : [i.name for i in mt5.symbols_get()]
            date_from (datetime): Date, the ticks are requested from
            date_to   (datetime): Date, up to which the ticks are requested
            count     (int)     : The length of the data (minutes)
            timeframe (int)     : Time timeframe of data sampling (mt5.TIMEFRAME)
                Form : mt5.TIMEFRAME_ + M(minute) / H(hour) / D(day) / W(week) / MN(month) + value
        """
        self.data = []
        self.date_from = date_from
        self.data_to   = date_to
        self.count     = count
        for i in range(len(symbol)):
            if count:
                data = mt5.copy_rates_from(symbol[i], timeframe, date_from, count).tolist()
            elif date_to:
                data = mt5.copy_rates_range(symbol[i], timeframe, date_from, date_to).tolist()
            else:
                print('Argument passed in error')
                return

            if data is None:
                print(f'{symbol[i]} data copy error, skip')
            else:
                self.data += [data]
        self.data = torch.FloatTensor(self.data).permute(1, 0, 2)
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
def get_bars(symbol, start, end=None, timeFrame=DAILY):
    # definimos o fuso horário como UTC
    #timezone = pytz.timezone("Etc/UTC")
    if symbol == None or type(symbol) != str:
        return None
    else:
        symbol = symbol.upper()
    if timeFrame == DAILY:
        timeFrame = mt5.TIMEFRAME_D1
    elif timeFrame == INTRADAY:
        timeFrame = mt5.TIMEFRAME_M1
    else:
        timeFrame = mt5.TIMEFRAME_D1
    if end == None:
        end = datetime.now()
    if type(start).__name__ != 'datetime':
        if type(start).__name__ != 'int':
            print(
                'Error, start should be a datetime from package datetime or int'
            )
        else:
            start_day = datetime.now()  #- timedelta(days=start)
            rates = mt5.copy_rates_from(symbol, timeFrame, start_day, start)
            # criamos a partir dos dados obtidos DataFrame
            rates_frame = pd.DataFrame(rates)
            if len(rates_frame) > 0:
                rates_frame['time'] = pd.to_datetime(rates_frame['time'],
                                                     unit='s')
            return rates_frame
    else:
        rates = mt5.copy_rates_range(symbol, timeFrame, start, end)
        # criamos a partir dos dados obtidos DataFrame
        rates_frame = pd.DataFrame(rates)
        rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
        return rates_frame
Ejemplo n.º 6
0
def getDailYBars(
        symbol,
        start,
        end=None):  # sao inclusas barras com  tempo de abertura <= end.
    # definimos o fuso horário como UTC
    #timezone = pytz.timezone("Etc/UTC")
    if not connected:
        print(
            "In order to use this function, you must be connected to B3. Use function connect()"
        )
        return
    if end == None:
        end = datetime.now()
    if type(start).__name__ != 'datetime':
        if type(start).__name__ != 'int':
            print(
                'Error, start should be a datetime from package datetime or int'
            )
        else:
            start_day = datetime.now()  #- timedelta(days=start)
            rates = mt5.copy_rates_from(symbol, mt5.TIMEFRAME_D1, start_day,
                                        start)
            # criamos a partir dos dados obtidos DataFrame
            rates_frame = pd.DataFrame(rates)
            rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
            return rates_frame
    else:
        rates = mt5.copy_rates_range(symbol, mt5.TIMEFRAME_D1, start, end)
        # criamos a partir dos dados obtidos DataFrame
        rates_frame = pd.DataFrame(rates)
        rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
        return rates_frame
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
 def get_profit(self):
     get_rates = None
     if self.base[:3].lower() != "usd":
         try:
             self.us_base = self.base[:3].upper() + "USD"
             get_rates = mt.copy_rates_from(self.us_base, mt.TIMEFRAME_M1,
                                            self.time, 10)
             if get_rates == None:
                 self.us_base = "USD" + self.base[:3].upper()
                 get_rates = mt.copy_rates_from(self.us_base,
                                                mt.TIMEFRAME_M1, self.time,
                                                10)
                 if get_rates == None:
                     self.bid = 1.0
                     self.ask = 1.0
         except Exception as e:
             print(self.base, self.us_base, e)
     """
     elif self.base[:3].lower() == "usd":
         try:
             self.us_base = self.base[3:6].upper() + "USD"
             get_rates = mt.copy_rates_from(self.us_base,
                 mt.TIMEFRAME_M1,self.time,10)
             if get_rates == None:
                 self.us_base = "USD" + self.base[3:6].upper()
                 get_rates = mt.copy_rates_from(self.us_base,
                     mt.TIMEFRAME_M1,self.time,10)
                 if get_rates == None:
                     self.bid = 1.0
                     self.ask = 1.0
         
         except Exception as e:
             print(self.base,self.us_base,e)
         """
     get_currency = round(self.exchange_rate_difference\
         * self.price_per_pip_change,8)
     bare_currency = get_currency * pow(10, abs(self.exponent))
     if get_rates != None:
         self.bid = get_rates[0][1]
         self.ask = get_rates[0][3]
         self.profit = round(bare_currency * self.ask, 2)
         self.profit = self.profit + self.swap
         round(self.profit, 2)
     else:
         self.profit = bare_currency + self.swap
         self.profit = round(self.profit, 2)
Ejemplo n.º 9
0
def data_collection(timeframe, n):
	
	if not mt5.initialize():
		print('failed to connect')
		quit()

	timeframe_dict = {
                      'H1':mt5.TIMEFRAME_H1, 
					  'D1':mt5.TIMEFRAME_D1, 
					  'W1':mt5.TIMEFRAME_W1
					 }

	currs = ['EUR', 'GBP', 'AUD', 'NZD',
             'USD', 'CAD', 'CHF', 'JPY']

	ohlc_dict = {}

	for curr_no, curr1 in enumerate(currs):
		for curr2 in currs[curr_no+1:]:
			curr_pair = curr1 + curr2

			#Get candles from the past 3 weeks (exclusive of current week)
			time_now = pd.Timestamp.now(tz='Etc/UTC')
			#four_wks_ago = time_now - dt.timedelta(weeks=3)
			#day_of_wk = dt.timedelta(days=four_wks_ago.isoweekday()%7)
			#past_4_wks = dt.date(four_wks_ago.year, four_wks_ago.month, four_wks_ago.day) - day_of_wk

			#ohlc_arr = mt5.copy_rates_range(curr_pair, timeframe_dict[timeframe], 
			#	                            pd.to_datetime(past_4_wks), time_now)
			ohlc_arr = mt5.copy_rates_from(curr_pair, timeframe_dict[timeframe], 
				                           time_now, n)

			column_names = {
			                'open':'Open',
			                'high':'High',
			                'low':'Low',
			                'close':'Close'
						   }

			try:
				ohlc_df = pd.DataFrame(ohlc_arr)
				ohlc_df.index = pd.to_datetime(ohlc_df.iloc[:, 0], unit='s')
				ohlc_df = ohlc_df.drop(columns=['time'])
				ohlc_df = ohlc_df.rename(columns=column_names)

				ohlc_dict[curr_pair+'_ohlc_df'] = ohlc_df

			except:
				print('ERROR OCCURRED IN: ', curr_pair)

	mt5.shutdown()

	return ohlc_dict
Ejemplo n.º 10
0
 def getDataFromMetatrader(currency="EURUSD",
                           timeframe=mt5.TIMEFRAME_H1,
                           fromdate=datetime.now(),
                           count=70000):
     if not mt5.initialize():
         print("initialize() failed")
         mt5.shutdown()
     eurusd_rates = mt5.copy_rates_from(currency, timeframe, fromdate,
                                        count)
     mt5.shutdown()
     df = pd.DataFrame(data=eurusd_rates)
     df['time'] = pd.to_datetime(df['time'], unit='s')
     return df
Ejemplo n.º 11
0
def get_prices_for_whole_period():
    now = datetime.now(timezone)
    rates_whole_period = mt5.copy_rates_from(EUR_USD, mt5.TIMEFRAME_H1, now,
                                             barsAmount)
    rates_frame = pandas.DataFrame(rates_whole_period)

    high_price = rates_frame[[HIGH]]
    low_price = rates_frame[[LOW]]
    bar_size = high_price[HIGH] - low_price[LOW]
    print(
        f'Максимальная свеча за весь период: {round(bar_size.max(), round_num)}'
    )
    print(
        f'Минимальная свеча за весь период: {round(bar_size.min(), round_num)}'
    )
Ejemplo n.º 12
0
def inicializa(Ativo, Ano,Mes,Dia,QtdeBar,TimeFrame):
    utc_tz = timezone("America/Recife") #timezone("UTC")
    try:
        #MT5Initialize()
        mt5.initialize()
        #MT5WaitForTerminal()
        mt5.wait()
        
        utc_from = datetime(Ano, Mes, Dia, tzinfo=utc_tz)        
        #ticksAtivo =  MT5CopyRatesFrom(Ativo, TimeFrame, utc_from, QtdeBar)
        barsAtivo =  mt5.copy_rates_from(Ativo, TimeFrame, utc_from, QtdeBar)       
        
        #MT5Shutdown()
        mt5.shutdown()
        return barsAtivo
    except Exception as e:
        raise e
Ejemplo n.º 13
0
def animate(i):
    ax1.clear()
    rates = mt5.copy_rates_from(pair, timeframe, datetime.now(), array)
    rates_frame = pd.DataFrame(rates)

    candlestick2_ohlc(ax1,
                      rates_frame['open'],
                      rates_frame['high'],
                      rates_frame['low'],
                      rates_frame['close'],
                      width=0.6)
    xdate = [datetime.fromtimestamp(i) for i in rates_frame['time']]

    ax1.xaxis.set_major_locator(ticker.MaxNLocator(6))

    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''

    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))

    fig.autofmt_xdate()
    fig.tight_layout()

    highMA = periodHigh(pair, 10, timeframe, array)
    lowMA = periodLow(pair, 10, timeframe, array)
    #rates7de = period(pair,7,timeframe,array)
    #rates25de = period(pair,25,timeframe,array)
    #rates99de = period(pair,99,timeframe,array)

    ax1.plot(lowMA)
    ax1.plot(highMA)
    #ax1.plot(rates99de)
    #ax1.plot(rates25de)
    #ax1.plot(rates7de)

    ask = mt5.symbol_info_tick(pair).ask  #BUY
    bid = mt5.symbol_info_tick(pair).bid  #SELL
    print('BUY: ', (ask - lowMA[-1]) / (highMA[-1] - lowMA[-1]))
    print('sell: ', (bid - lowMA[-1]) / (highMA[-1] - lowMA[-1]))
Ejemplo n.º 14
0
def period(pair, period, timeframe, array):

    ratesDE = collections.deque([0.0] * array)

    if not mt5.initialize():
        print("initialize() failed")
        mt5.shutdown()

    currentTime = datetime.now()

    rates = mt5.copy_rates_from(pair, timeframe, currentTime, period + array)

    for arr in range(array):
        calculated = 0
        for pos in range(period):
            calculated += rates[arr + pos][4]
        ratesDE.appendleft(calculated / period)
        ratesDE.pop()

    ratesDE.reverse()
    return ratesDE
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
def Time_Shift(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)
    # 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)
    # now shift the time to day before
    timeshift = rates_frame['time'].iloc[-2].date()
    timeshift = str(timeshift)
    timeshift = timeshift.split('-')
    Y = int(timeshift[0])
    M = int(timeshift[1])
    D = int(timeshift[2])
    return [Y, M, D]
Ejemplo n.º 17
0
ano = datetime.today().year
mes = datetime.today().month
dia = datetime.today().day

# definimos o fuso horário
timezone = pytz.timezone("Brazil/DeNoronha")
utc_from = datetime(ano, mes, dia, tzinfo=timezone)

# quantidade de pregões desde o dia inicial
range_time = 60  # em dias pois estou usando timeframe diário

print('Executando o programa...')
for ativo in ativos:
    try:
        # coletando as informações do MT5
        rates = mt5.copy_rates_from(ativo, mt5.TIMEFRAME_D1, utc_from,
                                    range_time)
        # transformando para dataframe
        rf = pd.DataFrame(rates)
        # transformando a coluna da data no formato datetime
        rf['time'] = pd.to_datetime(rf['time'], unit='s')
        # cálculo das médias móveis
        rf['MM4'] = rf['close'].rolling(4).mean()
        rf['MM17'] = rf['close'].rolling(17).mean()
        rf['MM55'] = rf['close'].rolling(55).mean()

        if (rf['MM4'][range_time - 1] < rf['MM17'][range_time - 2]) and (
                rf['MM4'][range_time - 1] >= rf['MM17'][range_time - 1]) and (
                    rf['MM17'][range_time - 1] >= rf['MM55'][range_time - 1]):
            new_row = {
                'Data': rf['time'][range_time],
                'Ativo': ativo,
Ejemplo n.º 18
0
Archivo: kkt.py Proyecto: xbobekf/MT5
# 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), ')')
for val in euraud_ticks[:10]:
    print(val)

print('audusd_ticks(', len(audusd_ticks), ')')
for val in audusd_ticks[:10]:
Ejemplo n.º 19
0
if not mt5.initialize(login=config_dict["user"], server="ModalMais-DMA4 - Beta", password=config_dict["password"]):
    print("initialize() failed, error code =", mt5.last_error())
    quit(1)

with open("tickers.json") as json_file:
    json_dict = json.loads(json_file.read())

string_to_timeframe = {"m1": mt5.TIMEFRAME_M1, "m2": mt5.TIMEFRAME_M2, "m3": mt5.TIMEFRAME_M3, "m4": mt5.TIMEFRAME_M4,
                       "m5": mt5.TIMEFRAME_M5, "m6": mt5.TIMEFRAME_M6, "m10": mt5.TIMEFRAME_M10,
                       "m12": mt5.TIMEFRAME_M12, "m15": mt5.TIMEFRAME_M15, "m20": mt5.TIMEFRAME_M20,
                       "m30": mt5.TIMEFRAME_M30, "h1": mt5.TIMEFRAME_H1, "h2": mt5.TIMEFRAME_H2, "h3": mt5.TIMEFRAME_H3,
                       "h4": mt5.TIMEFRAME_H4, "h6": mt5.TIMEFRAME_H6, "h8": mt5.TIMEFRAME_H8, "h12": mt5.TIMEFRAME_H12,
                       "d1": mt5.TIMEFRAME_D1, "w1": mt5.TIMEFRAME_W1, "mn1": mt5.TIMEFRAME_MN1}
timeframe = json_dict["timeframe"]
utc_from = datetime.now()
for ticker in tqdm(json_dict["tickers"]):
    try:
        rates = mt5.copy_rates_from(ticker, string_to_timeframe[timeframe], utc_from, 9999999)

        rates_frame = pd.DataFrame(rates)
        rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')
        rates_frame = rates_frame.set_index("time")
        rates_frame.to_csv(f"../data/{ticker}_{timeframe}.csv")
    except KeyError as e:
        print(f"Error type: {type(e)}")
        print("Try to set unlimited bars on mt5 platform.")
    except Exception as e:
        print(f"Error on ticker: {ticker}; error: {type(e)}{e}")

mt5.shutdown()
    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]:
    print(val)

print('gbpusd_rates(', len(gbpusd_rates), ')')
for val in gbpusd_rates[:1]:
Ejemplo n.º 21
0
pair = "ETHUSD."
array = [0.0] * 10

rates7de = collections.deque(array) 
rates25de = collections.deque(array) 
rates99de = collections.deque(array) 

# connect to MetaTrader 5
if not mt5.initialize():
    print("initialize() failed")
    mt5.shutdown()

while(True):
    signal = ''
    currentTime = datetime.now()
    rates7 = mt5.copy_rates_from(pair, timeframe, currentTime, 7)
    rates25 = mt5.copy_rates_from(pair, timeframe, currentTime, 25)
    rates99 = mt5.copy_rates_from(pair, timeframe, currentTime, 99)
    ticks = mt5.copy_ticks_from(pair, currentTime, 1, mt5.COPY_TICKS_ALL)
    
    calculated7 = 0
    for pos in rates7:
        calculated7+=pos[4]
    rates7de.appendleft(calculated7/7)
    rates7de.pop()
    print ('7:', rates7de)

    calculated25 = 0
    for pos in rates25:
        calculated25+=pos[4]
    rates25de.appendleft(calculated25/25)
Ejemplo n.º 22
0
# 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("USDJPYm", 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("GBPJPYm", 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("USDJPYm", mt5.TIMEFRAME_M1,
                                   datetime(2020, 1, 28, 13), 1000)
eurgbp_rates = mt5.copy_rates_from_pos("USDJPYm", mt5.TIMEFRAME_M1, 0, 1000)
eurcad_rates = mt5.copy_rates_range("USDJPYm", 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), ')')
for val in euraud_ticks[:10]:
    print(val)

print('audusd_ticks(', len(audusd_ticks), ')')
for val in audusd_ticks[:10]:
Ejemplo n.º 23
0
pd.set_option('display.max_columns', 500)  # number of columns to be displayed
pd.set_option('display.width', 1500)  # max table width to display
# 导入用于处理时区的pytz模块
import pytz

# 建立与MetaTrader 5程序端的连接
if not mt5.initialize():
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# 将时区设置为UTC
timezone = pytz.timezone("Etc/UTC")
# 以UTC时区创建'datetime'对象,以避免实现本地时区偏移
utc_from = datetime(2020, 1, 10, tzinfo=timezone)
# 在UTC时区,获取01.10.2020开始的10个EURUSD H4柱形图
rates = mt5.copy_rates_from("EURUSD", mt5.TIMEFRAME_H4, utc_from, 10)

# 断开与MetaTrader 5程序端的连接
mt5.shutdown()
# 在新行显示所获得数据的每个元素
print("Display obtained data 'as is'")
for rate in rates:
    print(rate)

# 从所获得的数据创建DataFrame
rates_frame = pd.DataFrame(rates)
# 将时间(以秒为单位)转换为日期时间格式
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')

# 显示数据
print("\nDisplay dataframe with data")
Ejemplo n.º 24
0
import MetaTrader5 as mt5
import sys
import pandas as pd

if (sys.argv[1] == None):
    pair = "ETHUSD."
else:
    pair = sys.argv[1]

if not mt5.initialize():
    print("initialize() failed")
    mt5.shutdown()

timeframe = mt5.TIMEFRAME_M1

quotes = mt5.copy_rates_from(pair, timeframe, datetime.now(), 100)
quotes = pd.DataFrame(quotes)
print(quotes)
fig, ax = plt.subplots()
candlestick2_ohlc(ax,
                  quotes['open'],
                  quotes['high'],
                  quotes['low'],
                  quotes['close'],
                  width=0.6)

xdate = [datetime.fromtimestamp(i) for i in quotes['time']]

ax.xaxis.set_major_locator(ticker.MaxNLocator(6))

Ejemplo n.º 25
0
                                        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)
eurgbp_rates = mt5.copy_rates_from_pos("EURGBP", mt5.TIMEFRAME_M1, 0, 1000)

if now.day == 1 and now.month > 1:
    eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(now.year, now.month-1, now.day - 1, now.hour),
                                        datetime(now.year, now.month, now.day, now.hour))
elif now.day == 1 and now.month == 1:
    eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(now.year-1, december_month, now.day - 1, now.hour),
                                        datetime(now.year, now.month, now.day, now.hour))
else:
    eurcad_rates = mt5.copy_rates_range("EURCAD", mt5.TIMEFRAME_M1, datetime(now.year, now.month, now.day - 1, now.hour),
                                        datetime(now.year, now.month, now.day, now.hour))

# shut down connection to MetaTrader 5
mt5.shutdown()
Ejemplo n.º 26
0
# 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)
 
print('eurusd_rates(', len(eurusd_rates), ')')
for val in eurusd_rates[:10]: print(val)
Ejemplo n.º 27
0
import pytz
import pandas as pd
import matplotlib.pyplot as plt

# initialize connections
mt5.initialize(
    path="C:\\Users\\silin\\AppData\\Roaming\\MetaTrader 5\\terminal64.exe",
    login=35146240,
    password="******")

# query for forex pair
timezone = pytz.timezone("Etc/UTC")
utc_from = datetime(2020, 1, 1,
                    tzinfo=timezone)  # create date time for the query

rates = mt5.copy_rates_from('EURUSD', mt5.TIMEFRAME_H4, datetime.today(),
                            10000)

# shutdown connections
mt5.shutdown()

##### work on the data #####
rates_frame = pd.DataFrame(rates)
rates_frame['time'] = pd.to_datetime(rates_frame['time'], unit='s')


##### Implement Order #####
def get_info(symbol):
    '''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5symbolinfo_py
    '''
    # get symbol properties
    info = mt5.symbol_info(symbol)
Ejemplo n.º 28
0
print(mt5.terminal_info())
# get data on MetaTrader 5 version
print(mt5.version())

# request 1000 ticks from EURAUD
euraud_ticks = mt5.copy_ticks_from("EURAUD", datetime(2020, 1, 28, 13), 1000,
                                   mt5.COPY_TICKS_ALL)
eurusd_ticks = mt5.copy_ticks_from("EURUSD", 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("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))

# 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]:
Ejemplo n.º 29
0
 def rates_Collection(symbol, timeframe, year, mon, day, num):
     timezone = pytz.timezone('Etc/UTC')
     utc_from = datetime(year, mon, day, tzinfo=timezone)
     rates = mt5.copy_rates_from(symbol, Operation.Period(timeframe),
                                 utc_from, num)
     return (rates)
Ejemplo n.º 30
0
import pandas as pd
import matplotlib.pyplot as plt
import time
from datetime import datetime
import MetaTrader5 as mt5
import ta
import sys
while True:
    
        
    nem=input('nemad ra vared konid : ')
    if not mt5.initialize():
        print("initialize() failed")
    period=50
    shakhes = mt5.copy_rates_from("شاخص کل6", mt5.TIMEFRAME_D1, datetime.now(), period)
    nemad = mt5.copy_rates_from(nem, mt5.TIMEFRAME_D1, datetime.now(), period)
    mt5.shutdown()
    df = pd.DataFrame(nemad)
    ds = pd.DataFrame(shakhes)
    print(nem,list(df.columns))
    df['time'] = pd.to_datetime(df['time'], unit='s')
    dfp = df["close"]
    dsp = ds["close"]