Example #1
0
def open_position(symbol,
                  order_type,
                  volume,
                  tp_distance=None,
                  stop_distance=None):
    symbol_info = mt5.symbol_info(symbol)
    sl, tp, order, price = None, None, None, None

    if symbol_info is None:
        print(f"{symbol} is not found")
        return

    if not symbol_info.visible:
        print(f"{symbol} is not visible, trying to switch on")
        if not mt5.symbol_select(symbol, True):
            print(f"symbol_select for {symbol} is failed, exiting")
            return
    print(f"{symbol} found")

    point = symbol_info.point

    if order_type == "BUY":
        order = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
        if stop_distance:
            sl = price - (stop_distance * point)
        if tp_distance:
            tp = price + (tp_distance * point)

    if order_type == "SELL":
        order = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
        if stop_distance:
            sl = price + (stop_distance * point)
        if tp_distance:
            tp = price - (tp_distance * point)

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": float(volume),
        "type": order,
        "price": price,
        "sl": sl,
        "tp": tp,
        "magic": 234000,
        "comment": "",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC
    }

    result = None
    try:
        result = mt5.order_send(request)
    except result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
        print("Unable to send order")
        return

    print(f"{symbol} Order sent")
    return result.retcode
    def minutes_counter_after_trade(self, symbol, count_until):
        if len(Mt5.positions_get(symbol=symbol)) == 1:
            self.__recent_trade = True

        if len(Mt5.positions_get(symbol=symbol)) != 1 and self.__recent_trade:
            if not self.__allow_to_count:
                self.__allow_to_count = True
                self.__allowed_to_trade = False
                self.__recent_trade = False

        if datetime.now(
        ).second == 0 and self.__counter_flag and self.__allow_to_count:
            print(
                f"Your Expert Advisor will be allowed to trade in {count_until-self.__minutes_counter} minutes."
            )
            self.__minutes_counter += 1
            self.__counter_flag = False

        if datetime.now().second == 59:
            self.__counter_flag = True

        if self.__minutes_counter == count_until:
            print(f"Your Expert Advisor is allowed to trade.\n")
            self.__minutes_counter = 0
            self.__counter_flag = True
            self.__allow_to_count = False
            self.__allowed_to_trade = True

        return self.__allowed_to_trade
Example #3
0
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')
Example #4
0
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
Example #5
0
def close_trade(request, result, deviation):
    symbol = request['symbol']

    if request['type'] == mt5.ORDER_TYPE_BUY:
        trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    elif request['type'] == mt5.ORDER_TYPE_SELL:
        trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask

    position_id = result.order
    lot = request['volume']

    close_request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": trade_type,
        "position": position_id,
        "price": price,
        "deviation": deviation,
        "magic": 234000,
        "comment": "python request end",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }

    result = mt5.order_send(close_request)
Example #6
0
def open_trade(action, symbol, lot, sl, tp, deviation):

    if action == 'buy':
        trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask

    elif action == 'sell':
        trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
        tp *= -1
        sl *= -1

    point = mt5.symbol_info(symbol).point

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": trade_type,
        "price": price,
        "sl": price - sl * point,
        "tp": price + tp * point,
        "deviation": deviation,
        "magic": 234000,
        "comment": "python request",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }

    result = mt5.order_send(request)
    return result, request
Example #7
0
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)
Example #8
0
def per_change(symbol, delta):
    """Returns the percentage change in the price of asset in the given 
    time-delta from the latest price in the terminal."""

    mt5.symbol_select(symbol)

    # latest tick data.
    now_tick = mt5.symbol_info_tick(symbol)
    now_ask = now_tick.ask  # latest ask price.
    now_time = now_tick.time  # latest time of tick

    # setting past-time adjusting with delta.
    past_time = dt.datetime.fromtimestamp(now_time - delta)

    # Getting past tick
    past_tick = mt5.copy_ticks_from(symbol, past_time, 1, mt5.COPY_TICKS_INFO)
    past_ask = past_tick[0][2]  # getting past ask.

    # calculating percentage change.
    per_chng = ((now_ask - past_ask) / past_ask) * 100

    if symbol[3:6] == 'USD':
        return per_chng
    else:
        return -(per_chng)
Example #9
0
def close_trade(action, buy_request, result, deviation):
    '''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
    '''
    # create a close request
    symbol = buy_request['symbol']
    if action == 'buy':
        trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
    elif action == 'sell':
        trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    position_id = result.order
    lot = buy_request['volume']

    close_request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": mt5.ORDER_TYPE_SELL,
        "position": position_id,
        "price": price,
        "deviation": deviation,
        "magic": ea_magic_number,
        "comment": "python script close",
        "type_time": mt5.ORDER_TIME_GTC,  # good till cancelled
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    # send a close request
    result = mt5.order_send(close_request)
Example #10
0
def check(n, count_wins, count_losses, j, curr_pair):
    if n > 0:
        txt = "buy"
    else:
        txt = "sell"
    while True:
        spread = round(
            mt5.symbol_info(curr_pair).ask - mt5.symbol_info(curr_pair).bid, 7)
        print("\r",
              txt,
              ", current profit: ",
              mt5.account_info().profit,
              ", spread: ",
              round(spread * 10, 4),
              flush=True)
        if mt5.account_info().profit > 0.02:
            count_wins += 1
            win(count_wins, count_losses, curr_pair)
            break
        elif mt5.account_info().profit <= -0.1:
            count_losses += 1
            loss(count_wins, count_losses, curr_pair)
            break
        else:
            pass
        k = (1 + j) * 30
        print("checking price in: ", k, " seconds.")
        time.sleep(k)
    return count_wins, count_losses
Example #11
0
def getBars(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
Example #12
0
def convert_csv(timeframe=mt5.TIMEFRAME_D1, bars=1000):
    def load_data(symbol):
        try:
            ticker = pd.DataFrame(
                mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_D1, 0,
                                        bars))['close'].rename(index=symbol)
            print(f'Symbol {symbol} Bars {BARS} ok')

        except RuntimeError:
            print(f'ERRO NO SYMBOL "{symbol}"')
            mt5.shutdown()
            quit()

        return ticker

    tickers_close = [load_data(symbol) for symbol in symbols]

    symbol_one = pd.DataFrame(
        mt5.copy_rates_from_pos(symbols[0], timeframe, 0, bars))
    time_tickers = pd.to_datetime(symbol_one['time'], unit='s')

    mt5.shutdown()

    df = pd.DataFrame(tickers_close).T

    df['TIME'] = time_tickers
    df.set_index('TIME', inplace=True)

    df.to_csv(
        f'{str(datetime.now().replace(microsecond=0)).replace(":", "-")}.csv')

    print(
        f'From {str(time_tickers.iloc[0]).split(" ")[0]} to {str(time_tickers.iloc[-1]).split(" ")[0]}'
    )
Example #13
0
    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
Example #14
0
File: bot.py Project: slape/python
def close_position(deal_id):
    open_positions = get_positions()
    open_positions = open_positions[open_positions['ticket'] == deal_id]
    order_type = open_positions['type'][0]
    symbol = open_positions['symbol'][0]
    volume = open_positions['volume'][0]

    if(order_type == mt5.ORDER_TYPE_BUY):
        order_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    else:
        order_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask

    close_request = {
        'action': mt5.TRADE_ACTION_DEAL,
        'symbol': symbol,
        'volume': float(volume),
        'type': order_type,
        'position': deal_id,
        'price': price,
        'magic': 234000,
        'comment': 'Close trade',
        'type_time': mt5.ORDER_TIME_GTC,
        'type_filling': mt5.ORDER_FILLING_IOC,
    }

    result = mt5.order_send(close_request)

    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print('Failed to close order :(')
    else:
        print('Order successfully closed!')
Example #15
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)
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
Example #17
0
def Generator(curr="GBPUSD", period=14):
    Done = True
    rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2)
    c = 0
    open_list = []
    high_list = []
    low_list = []
    close_list = []
    while Done:
        lasttick = mt5.symbol_info_tick(curr)
        bid, ask = round(lasttick.bid, 5), round(lasttick.ask, 5)
        mid = round((bid + ask) / 2, 5)
        c += 1
        check = rates[1][0]
        #rates = mt5.copy_rates_from_pos("GBPUSD", mt5.TIMEFRAME_M1, 0, 1)
        while check == rates[1][0]:
            rates = mt5.copy_rates_from_pos(curr, mt5.TIMEFRAME_M1, 0, 2)
        open, high, low, close, tickvol, spread = rates[0][1], rates[0][
            2], rates[0][3], rates[0][4], rates[0][5], rates[0][6]
        open_list.append(open)
        high_list.append(high)
        low_list.append(low)
        close_list.append(close)
        #if c>period:
        cci = CCI(high_list, low_list, close_list, period)
        if len(cci) == 0:
            cci = np.append(cci, 0)
        rsi = RSI(pd.Series(close_list), period)
        yield np.array(
            [bid, ask, mid,
             round(rsi.values[-1], 5), cci[-1] / 100])
Example #18
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
Example #19
0
def open_trade(action, symbol, lot, sl_points, tp_points, deviation):
    '''https://www.mql5.com/en/docs/integration/python_metatrader5/mt5ordersend_py
    '''
    # prepare the buy request structure
    symbol_info = get_info(symbol)

    if action == 'buy':
        trade_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask
    elif action == 'sell':
        trade_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    point = mt5.symbol_info(symbol).point

    buy_request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": trade_type,
        "price": price,
        "sl": price - sl_points * point,
        "tp": price + tp_points * point,
        "deviation": deviation,
        "magic": ea_magic_number,
        "comment": "sent by python",
        "type_time": mt5.ORDER_TIME_GTC,  # good till cancelled
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    # send a trading request
    result = mt5.order_send(buy_request)
    return result, buy_request
Example #20
0
def close_position(deal_id):
    open_positions = positions_get()
    open_positions = open_positions[open_positions["ticket"] == deal_id]
    order_type = open_positions["type"][0]
    symbol = open_positions["symbol"][0]
    volume = open_positions["volume"][0]
    if (order_type == mt5.ORDER_TYPE_BUY):
        order_type = mt5.ORDER_TYPE_SELL
        price = mt5.symbol_info_tick(symbol).bid
    else:
        order_type = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(symbol).ask

    close_request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": float(volume),
        "type": order_type,
        "position": deal_id,
        "price": price,
        "magic": 234000,
        "comment": "Close trade",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC,
    }

    result = mt5.order_send(close_request)

    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print("Failed to close order :(")
    else:
        print("Order successfully closed!")
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
Example #22
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 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

    return x
Example #23
0
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
Example #24
0
 def __enter__(self):
     """
     Открываем подключение к терминалу
     """
     # подключимся к MetaTrader 5
     if not mt5.initialize(path=self.path, server=self.server, login=self.login, password=self.password):
         print("initialize() failed")
         mt5.shutdown()
Example #25
0
 def get_rates_range(self):
     rates = mt5.copy_rates_range(self.currency_pair_name, self.timeframe,
                                  self.datetime_from, self.datetime_to)
     if rates != None:
         return rates
     else:
         raise RuntimeError('copy_rates_range() failed. error code =',
                            mt5.last_error())
Example #26
0
def closeingPrice(name):
    info = mt5.symbol_info_tick(name)
    if info is None:
        insertion(name)
        time.sleep(0.5)
        info = mt5.symbol_info_tick(name)
        return info.ask
    return info.ask
Example #27
0
def synthesize(symbol1, symbol2, periods):
    """Takes 2 MT5 currency symbols with common USD and returns a DataFrame of OCHLV
    of the price of first symbol denominated in second symbol.
    
    note: Requires both the assets to have USD in common, ie. either denomination
    or base."""

    # Asset on which the pricing will be based.
    base_asset = pd.DataFrame(
        mt5.copy_rates_from_pos(symbol1, mt5.TIMEFRAME_H1, 1, period))
    # Asset to quote the base in, generally a currency.
    quote_asset = pd.DataFrame(
        mt5.copy_rates_from_pos(symbol2, mt5.TIMEFRAME_H1, 1, period))

    # converting timestamps to Datetime-index.
    base_asset['time'] = pd.to_datetime(base_asset['time'], unit='s')
    quote_asset['time'] = pd.to_datetime(quote_asset['time'], unit='s')

    baseAsset_quote = mt5.symbol_info(symbol1).currency_profit

    if symbol1[0:3] == 'USD':  # Dollar based ie. USDJPY, USDCHF...
        if symbol2[3:6] == 'USD':
            basequote = (1 / base_asset[['open', 'high', 'low', 'close']]) * (
                1 / quote_asset[['open', 'high', 'low', 'close']])
            basequote.rename(columns={
                'high': 'low',
                'low': 'high'
            },
                             inplace=True)
        else:
            # basequote = quote_asset[['open', 'high', 'low', 'close']] / base_asset[['open', 'high', 'low', 'close']]
            basequote = (1 / base_asset[['open', 'high', 'low', 'close']]
                         ) * quote_asset[['open', 'high', 'low', 'close']]
            basequote.rename(columns={
                'high': 'low',
                'low': 'high'
            },
                             inplace=True)

    elif symbol1[
            3:
            6] == 'USD' or baseAsset_quote == 'USD':  # Dollar quoted ie. EURUSD, SnP500...
        if symbol2[3:6] == 'USD':
            basequote = base_asset[[
                'open', 'high', 'low', 'close'
            ]] / quote_asset[['open', 'high', 'low', 'close']]
            # basequote.rename(columns={'high':'low', 'low':'high'}, inplace=True)
        else:
            basequote = base_asset[[
                'open', 'high', 'low', 'close'
            ]] * quote_asset[['open', 'high', 'low', 'close']]

    # averaging volume.
    basequote['vol'] = (
        (base_asset['tick_volume'] + quote_asset['tick_volume']) / 2)
    basequote.set_index(keys=[base_asset['time']], inplace=True)

    return basequote
Example #28
0
def getOrders():  # returns a dataframe with all active orders
    orders = mt5.orders_get()
    if orders == None or len(orders) == 0:
        print("No orders, error code={}".format(mt5.last_error()))
        return None
    else:
        print("Total orders:", len(orders))
        df = pd.DataFrame(list(orders), columns=orders[0]._asdict().keys())
        return df
Example #29
0
    def _fxAdjust(exposure, pair):
        """Converts the passed exposure in USD"""

        if pair[0:3] == 'USD':
            adjustedExpo = exposure / mt5.symbol_info_tick(pair).ask
        else:
            adjustedExpo = exposure * mt5.symbol_info_tick(pair).ask

        return adjustedExpo
Example #30
0
 def get_prices(self):
     symbol = Trader.symbol
     bid = mt5.symbol_info_tick(symbol).bid
     ask = mt5.symbol_info_tick(symbol).ask
     spread = round(abs(ask - bid) * 1000)
     threading.Timer(1.0, self.get_prices).start()
     self._view.askPriceDisplay.setText(f"{ask:.3f}")
     self._view.bidPriceDisplay.setText(f"{bid:.3f}")
     self._view.spreadDisplay.setText(f"{spread}")