Ejemplo n.º 1
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)
Ejemplo n.º 2
0
def dollarizer(asset, dollarpair, tframe, period):

    mt5.symbol_select(dollarpair)
    time.sleep(2)

    asset_rates = pd.DataFrame(
        mt5.copy_rates_from_pos(
            asset, tframe, 0,
            period)).drop(columns=['spread', 'real_volume', 'tick_volume'])
    dollar_rates = pd.DataFrame(
        mt5.copy_rates_from_pos(
            dollarpair, tframe, 0,
            period)).drop(columns=['spread', 'real_volume', 'tick_volume'])

    asset_rates['time'] = pd.to_datetime(asset_rates['time'], unit='s')
    dollar_rates['time'] = pd.to_datetime(dollar_rates['time'], unit='s')

    asset_rates.set_index(keys=['time'], inplace=True)
    dollar_rates.set_index(keys=['time'], inplace=True)

    if dollarpair[3:6] == 'USD':  # quoted in dollar
        dollarised_asset = asset_rates[[
            'open', 'high', 'low', 'close'
        ]] * dollar_rates[['open', 'high', 'low', 'close']]

    else:  # based in dollar
        dollarised_asset = asset_rates[[
            'open', 'high', 'low', 'close'
        ]] / dollar_rates[['open', 'high', 'low', 'close']]
        dollarised_asset.rename(columns={'high': 'low', 'low': 'high'})

    # dollarised_asset['vol'] = (asset_rates['tick_volume'] + dollar_rates['tick_volume']) / 2
    dollarised_asset.dropa()
    return dollarised_asset
Ejemplo n.º 3
0
def per_change(symbol, tframe, period):
    mt5.symbol_select(symbol)
    for i in range(2):
        rateFrame = pd.DataFrame(
            mt5.copy_rates_from_pos(symbol, tframe, 0, period))
        time.sleep(1 / 2)

    # pcnt_change = (float(rateFrame.tail(1)['close']) - float(rateFrame.head(1)['close'])) / float(rateFrame.tail(1)['close']) * 100
    pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) /
                   rateFrame.iloc[(period - 1), 4]) * 100
    return pcnt_change
Ejemplo n.º 4
0
def fxAdjust(exposure, pair):
    """Adjusts non-USD exposure into USD"""

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

    return adjustedExpo
Ejemplo n.º 5
0
def per_change(symbol, tframe, period):
    mt5.symbol_select(symbol)
    for i in range(2):
        rateFrame = pd.DataFrame(mt5.copy_rates_from_pos(symbol, tframe, 1, period))
        time.sleep(1/2)

    # pcnt_change = (float(rateFrame.tail(1)['close']) - float(rateFrame.head(1)['close'])) / float(rateFrame.tail(1)['close']) * 100
    pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) / rateFrame.iloc[(period - 1), 4]) * 100
    if symbol[3:6] == 'USD':      # Dollar Quoted pairs. 
        return pcnt_change
    else:                         # Dollar Based pairs.
        return - (pcnt_change)
Ejemplo n.º 6
0
def per_change(symbol, tframe, period):
    mt5.symbol_select(symbol)
    for i in range(2):
        rateFrame = pd.DataFrame(
            mt5.copy_rates_from_pos(
                symbol, tframe, 0,
                period)).drop(columns=['spread', 'real_volume', 'tick_volume'])
        time.sleep(1 / 2)

    # ((current close - previous open)/previous close) * 100
    pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) /
                   rateFrame.iloc[(period - 1), 4]) * 100

    # return pcnt_change
    return pcnt_change.__round__(3)
Ejemplo n.º 7
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
Ejemplo n.º 8
0
def open_buy():
    global result_order_buy
    # establish connection to the MetaTrader 5 terminal
    if not mt5.initialize():
        print("initialize() failed, error code =",mt5.last_error())
        quit()

    # prepare the buy request structure
    symbol_info = mt5.symbol_info(symbol)
    if symbol_info is None:
        print(symbol, "not found, can not call order_check()")
        mt5.shutdown()
        quit()

    # if the symbol is unavailable in MarketWatch, add it
    if not symbol_info.visible:
        print(symbol, "is not visible, trying to switch on")
        if not mt5.symbol_select(symbol,True):
            print("symbol_select({}}) failed, exit",symbol)
            mt5.shutdown()
            quit()
    price = mt5.symbol_info_tick(symbol).ask
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": mt5.ORDER_TYPE_BUY,
        "price": price,
        "sl": price - sl_buy * point,
        "tp": price + tp_buy * point,
        "deviation": deviation,
        "magic": 234000,
        "comment": "python script open",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_FOK,
    }

    # send a trading request
    result = mt5.order_send(request)

    # check the execution result
    print("1. order_send(): by {} {} lots at {} with deviation={} points".format(symbol,lot,price,deviation))
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print("2. order_send failed, retcode={}".format(result.retcode))
        # request the result as a dictionary and display it element by element
        result_dict=result._asdict()
        for field in result_dict.keys():
            print("   {}={}".format(field,result_dict[field]))
            # if this is a trading request structure, display it element by element as well
            if field=="request":
                traderequest_dict=result_dict[field]._asdict()
                for tradereq_filed in traderequest_dict:
                    print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
        print("shutdown() and quit")
        mt5.shutdown()
        quit()
    print("2. order_send done, ", result)
    print("   buy opened position with POSITION_TICKET={}".format(result.order))
    result_order_buy=result.order
    return(result_order_buy)
Ejemplo n.º 9
0
Archivo: bot.py Proyecto: slape/python
def open_position(
    pair, order_type,
    size, tp_distance=None,
    stop_distance=None,
):
    """Open a position."""
    symbol_info = mt5.symbol_info(pair)

    if symbol_info is None:
        print(pair, 'not found')
        return

    if not symbol_info.visible:
        print(pair, 'is not visible, trying to switch on')
        if not mt5.symbol_select(pair, True):
            print('symbol_select({}}) failed, exit', pair)
            return
    print(pair, 'found!')

    point = symbol_info.point
    # volume_step = symbol_info.volume_step

    if(order_type == 'BUY'):
        order = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(pair).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(pair).bid
        if(stop_distance):
            sl = price + (stop_distance * point)
        if(tp_distance):
            tp = price - (tp_distance * point)

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

    result = mt5.order_send(request)
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print('Failed to send order :(')
    else:
        print('Order successfully placed!')
Ejemplo n.º 10
0
def per_change(symbol, tframe, period):
    mt5.symbol_select(symbol)

    denomination = mt5.symbol_info(symbol).currency_profit
    if denomination != 'USD':
        rateFrame = dollarizer(symbol, dollarPair(denomination), tframe,
                               period)
    for i in range(2):
        rateFrame = pd.DataFrame(
            mt5.copy_rates_from_pos(
                symbol, tframe, 0,
                period)).drop(columns=['spread', 'real_volume', 'tick_volume'])
        time.sleep(1 / 2)

    # ((current close - previous open)/previous close) * 100
    pcnt_change = ((rateFrame.iloc[(period - 1), 4] - rateFrame.iloc[0, 1]) /
                   rateFrame.iloc[(period - 1), 4]) * 100

    return pcnt_change.__round__(3)
def test():
    """ Executes the swap calculation function,
        on the press of button and makes the
        required changes to the GUI variables."""

    selection = assetList.curselection()[0]
    symbol = assetList.get(selection)
    mt5.symbol_select(symbol)
    volume = float(volEntryVar.get())
    try:
        entryPrice = float(priceEntryVar.get())
    except ValueError:  # if entry price is not entered.
        entryPrice = float(mt5.symbol_info_tick(symbol).ask)

    exposure = volume * entryPrice

    long, short = swap(symbol, volume, exposure)
    sLongVar.set(long)
    sShortVar.set(short)
Ejemplo n.º 12
0
def buyOrder(symbolId, volume, price=None, sl=None, tp=None):  # Buying !!
    #b=b3.buy(symbol_id,volume, price, sl, tp ))
    #if b3.checkorder(b):
    #    if b3.send(b): #buying
    #	print('order sent to B3')
    #    else:
    #	print('Error : ',b3.getLastError())
    #else:
    #    print('Error : ',b3.getLastError())
    if not connected:
        print(
            "In order to use this function, you must be connected to B3. Use function connect()"
        )
        return
    symbol_info = mt5.symbol_info(symbolId)
    #print("symbol=",symbolId," info=",symbol_info)
    if symbol_info is None:
        setLastError(symbolId + " not found, can not create buy order")
        return None


# se o símbolo não estiver disponível no MarketWatch, adicionamo-lo
    if not symbol_info.visible:
        #print(symbolId, "is not visible, trying to switch on")
        if not mt5.symbol_select(symbolId, True):
            setLastError("symbol_select({}}) failed! symbol=" + symbolId)
            return None
    point = mt5.symbol_info(symbolId).point
    deviation = 20

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbolId,
        "volume": float(volume),
        "type": mt5.ORDER_TYPE_BUY,
        "deviation": deviation,
        "magic": random.randrange(100, 100000),
        "comment": "order by mt5b3",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_RETURN,
    }
    if price == None:  # order a mercado
        request['action'] = mt5.TRADE_ACTION_DEAL
        request['type'] = mt5.ORDER_TYPE_BUY
        request['price'] = mt5.symbol_info_tick(symbolId).ask
    else:  # order limitada
        request['action'] = mt5.TRADE_ACTION_PENDING
        request['type'] = mt5.ORDER_TYPE_BUY_LIMIT
        request['price'] = float(price)
    if sl != None:
        request["sl"] = sl
    if tp != None:
        request["tp"] = tp

    return request
Ejemplo n.º 13
0
def open_position(pair,
                  order_type,
                  size,
                  tp_distance=None,
                  stop_distance=None):
    symbol_info = mt5.symbol_info(pair)
    if symbol_info is None:
        print(f"{pair} not found")
        return
    if not symbol_info.visible:
        print(f"{pair} is not visible, trying to switch on")
        if not mt5.symbol_select(pair, True):
            print(f"symbol_select({pair}) failed, exit")
            return
    print(f"{pair} found!")
    point = symbol_info.point
    volume_step = symbol_info.volume_step

    if (order_type == "BUY"):
        order = mt5.ORDER_TYPE_BUY
        price = mt5.symbol_info_tick(pair).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(pair).bid
        if (stop_distance):
            sl = price + (stop_distance * point)
        if (tp_distance):
            tp = price - (tp_distance * point)

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

    result = mt5.order_send(request)

    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print("Failed to send order :(")
    else:
        print("Order successfully placed!")
Ejemplo n.º 14
0
 def Check(self, lot, symbol):
     symbol_info = mt5.symbol_info(symbol)
     if symbol_info is None:
         print(symbol, "not found.")
         mt5.shutdown()
         quit()   
     # if the symbol is unavailable in MarketWatch, add it
     if not symbol_info.visible:
         print(symbol, "is not visible, trying to switch on")
         if not mt5.symbol_select(symbol,True):
             print("symbol_select({}}) failed, exit",symbol)
             mt5.shutdown()
             quit()
Ejemplo n.º 15
0
def is_market_open(asset='B3SA3'):
    if not connected:
        print(
            "In order to use this function, you must be connected to the Stock Exchange. Use function connect()"
        )
        return
    # si=mt5.symbol_info(asset)
    # if si!=None:
    #      if si.trade_mode==mt5.SYMBOL_TRADE_MODE_FULL: # it does not work in XP/B3 (always True)
    #          return True
    #      else:
    #          return False
    #  return False
    mt5.symbol_select(
        asset)  # it makes sure that the symbol is present in Market Watch View
    t_secs = mt5.symbol_info_tick(asset).time  # time in seconds
    now_dt = datetime.now(etctz) + timedelta(hours=-3)
    last_tick_dt = datetime.fromtimestamp(t_secs, etctz)
    #print(last_tick_dt)
    #print(now_dt)
    if now_dt > last_tick_dt + timedelta(seconds=60):
        return False
    else:
        return True
Ejemplo n.º 16
0
def getSymbolData(symbol):
    selected = mt5.symbol_select(symbol, True)
    if not selected:
        print("Failed to select " + symbol)
        mt5.shutdown()
        quit()

    symbolInfoDictionarie = mt5.symbol_info_tick(symbol)._asdict()

    symbolInfoDictionarie['time'] = convertTimeStampToDate(
        symbolInfoDictionarie['time'])
    data = json.dumps(symbolInfoDictionarie, indent=4, sort_keys=True)
    print(data)
    return data

    mt5.shutdown()
Ejemplo n.º 17
0
def sellOrder(symbolId, volume, price=None, sl=None, tp=None):  # Selling !!
    symbol_info = mt5.symbol_info(symbolId)
    #print("symbol=",symbolId," info=",symbol_info)
    if symbol_info is None:
        setLastError(symbolId + " not found, can not create buy order")
        return None


# se o símbolo não estiver disponível no MarketWatch, adicionamo-lo
    if not symbol_info.visible:
        #print(symbolId, "is not visible, trying to switch on")
        if not mt5.symbol_select(symbolId, True):
            setLastError("symbol_select({}}) failed! symbol=" + symbolId)
            return None
    point = mt5.symbol_info(symbolId).point
    deviation = 20
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbolId,
        "volume": float(volume),
        "type": mt5.ORDER_TYPE_SELL,
        "deviation": deviation,
        "magic": random.randrange(100, 100000),
        "comment": "order by mt5b3",
        "type_time": mt5.ORDER_TIME_DAY,
        "type_filling": mt5.ORDER_FILLING_FOK,
    }

    if price == None:  # order a mercado
        request['action'] = mt5.TRADE_ACTION_DEAL
        request['type'] = mt5.ORDER_TYPE_SELL
        request['price'] = mt5.symbol_info_tick(symbolId).ask
    else:  # order limitada
        request['action'] = mt5.TRADE_ACTION_PENDING
        request['type'] = mt5.ORDER_TYPE_SELL_LIMIT
        request['price'] = float(price)

    if sl != None:
        request["sl"] = sl

    if tp != None:
        request["tp"] = tp

    return request
Ejemplo n.º 18
0
    def prepare_symbol(self):
        # Prepare the symbol to open positions
        symbol_info = Mt5.symbol_info(self.symbol)
        if symbol_info is None:
            print(f'It was not possible to find {self.symbol}')
            Mt5.shutdown()
            print('Turned off')
            quit()

        if not symbol_info.visible:
            print(
                f'The {self.symbol} is not visible, needed to be switched on.')
            if not Mt5.symbol_select(self.symbol, True):
                print(
                    f'The expert advisor {self.expert_name} failed in select the symbol {self.symbol}, turning off.'
                )
                Mt5.shutdown()
                print('Turned off')
                quit()
Ejemplo n.º 19
0
    def step(self, action, trade=False):
        """Take an action (buy/sell/hold) and computes the immediate reward.

        Args:
            action (numpy.array): Action to be taken, one-hot encoded.

        Returns:
            tuple:
                - observation (numpy.array): Agent's observation of the current environment.
                - reward (float) : Amount of reward returned after previous action.
                - done (bool): Whether the episode has ended, in which case further step() calls will return undefined results.
                - info (dict): Contains auxiliary diagnostic information (helpful for debugging, and sometimes learning).

        """

        self._action = action
        self._iteration += 1
        done = False
        info = {}
        if all(self._position != self._positions['flat']):
            reward = -self._time_fee
        self._current_pnl = 0
        # establish connection to the MetaTrader 5 terminal
        if not mt5.initialize():
            print("initialize() failed, error code =", mt5.last_error())
            quit()

        # prepare the buy request structure
        symbol = "GBPUSD"
        symbol_info = mt5.symbol_info(symbol)
        if symbol_info is None:
            print(symbol, "not found, can not call order_check()")
            mt5.shutdown()
            quit()

        # if the symbol is unavailable in MarketWatch, add it
        if not symbol_info.visible:
            print(symbol, "is not visible, trying to switch on")
            if not mt5.symbol_select(symbol, True):
                print("symbol_select({}}) failed, exit", symbol)
                mt5.shutdown()
                quit()
        #-------------------
        instant_pnl = 0
        reward = -self._time_fee
        if all(action == self._actions['buy']):
            reward -= self._trading_fee
            if all(self._position == self._positions['flat']):
                self._position = self._positions['long']
                if trade:
                    lot = 0.1
                    point = mt5.symbol_info(symbol).point
                    price = mt5.symbol_info_tick(symbol).ask
                    deviation = 20
                    request = {
                        "action": mt5.TRADE_ACTION_DEAL,
                        "symbol": symbol,
                        "volume": lot,
                        "type": mt5.ORDER_TYPE_BUY,
                        "price": price,
                        "deviation": deviation,
                        "magic": 234000,
                        "comment": "python script open",
                        "type_time": mt5.ORDER_TIME_GTC,
                        "type_filling": 1,
                    }
                    # send a trading request
                    result = mt5.order_send(request)
                    # check the execution result
                    print(
                        "1. order_send(): by {} {} lots at {} with deviation={} points"
                        .format(symbol, lot, price, deviation))
                    if result.retcode != mt5.TRADE_RETCODE_DONE:
                        print("2. order_send failed, retcode={}".format(
                            result.retcode))
                        # request the result as a dictionary and display it element by element
                        result_dict = result._asdict()
                        for field in result_dict.keys():
                            print("   {}={}".format(field, result_dict[field]))
                            # if this is a trading request structure, display it element by element as well
                            if field == "request":
                                traderequest_dict = result_dict[field]._asdict(
                                )
                                for tradereq_filed in traderequest_dict:
                                    print("       traderequest: {}={}".format(
                                        tradereq_filed,
                                        traderequest_dict[tradereq_filed]))

                    print("2. order_send done, ", result)
                    print("   opened position with POSITION_TICKET={}".format(
                        result.order))
                self._entry_price = self._price = self._tick_buy
                self.Buy_render = True
            elif all(self._position == self._positions['short']):
                self._exit_price = self._exit_price = self._tick_sell
                instant_pnl = round(self._entry_price, 5) - round(
                    self._exit_price, 5)
                self._position = self._positions['flat']
                self._entry_price = 0
                if trade:
                    position_id = result.order
                    price = mt5.symbol_info_tick(symbol).bid
                    deviation = 20
                    request = {
                        "action": mt5.TRADE_ACTION_DEAL,
                        "symbol": symbol,
                        "volume": lot,
                        "type": mt5.ORDER_TYPE_BUY,
                        "position": position_id,
                        "price": price,
                        "deviation": deviation,
                        "magic": 234000,
                        "comment": "python script close",
                        "type_time": mt5.ORDER_TIME_GTC,
                        "type_filling": 1,
                    }
                    # send a trading request
                    result = mt5.order_send(request)
                    # check the execution result
                    print(
                        "3. close position #{}: sell {} {} lots at {} with deviation={} points"
                        .format(position_id, symbol, lot, price, deviation))
                    if result.retcode != mt5.TRADE_RETCODE_DONE:
                        print("4. order_send failed, retcode={}".format(
                            result.retcode))
                        print("   result", result)
                    else:
                        print("4. position #{} closed, {}".format(
                            position_id, result))
                        # request the result as a dictionary and display it element by element
                        result_dict = result._asdict()
                        for field in result_dict.keys():
                            print("   {}={}".format(field, result_dict[field]))
                            # if this is a trading request structure, display it element by element as well
                            if field == "request":
                                traderequest_dict = result_dict[field]._asdict(
                                )
                                for tradereq_filed in traderequest_dict:
                                    print("       traderequest: {}={}".format(
                                        tradereq_filed,
                                        traderequest_dict[tradereq_filed]))
                                    positions = mt5.positions_get(
                                        symbol="GBPUSD")
                    if positions == None:
                        print("No positions on GBPUSD, error code={}".format(
                            mt5.last_error()))
                    elif len(positions) > 0:
                        print("Total positions on GBPUSD =", len(positions))
                        # display all open positions
                        for position in positions:
                            print(position)

                    # get the list of positions on symbols whose names contain "*USD*"
                    usd_positions = mt5.positions_get(group="*USD*")
                    if usd_positions == None:
                        print(
                            "No positions with group=\"*USD*\", error code={}".
                            format(mt5.last_error()))
                    elif len(usd_positions) > 0:
                        print("positions_get(group=\"*USD*\")={}".format(
                            len(usd_positions)))
                        # display these positions as a table using pandas.DataFrame
                        df = pd.DataFrame(
                            list(usd_positions),
                            columns=usd_positions[0]._asdict().keys())
                        df['time'] = pd.to_datetime(df['time'], unit='s')
                        df.drop([
                            'time_update', 'time_msc', 'time_update_msc',
                            'external_id'
                        ],
                                axis=1,
                                inplace=True)
                        #print(df)
                        instant_pnl = df['profit'][-1]

                # self.Buy_render = True
                if (instant_pnl > 0):
                    self.TP_render = True
                else:
                    self.SL_render = True

        elif all(action == self._actions['sell']):
            reward -= self._trading_fee
            if all(self._position == self._positions['flat']):
                self._position = self._positions['short']
                self._entry_price = self._price = self._tick_sell
                self.Sell_render = True
                if trade:
                    lot = 0.1
                    point = mt5.symbol_info(symbol).point
                    price = mt5.symbol_info_tick(symbol).ask
                    deviation = 20
                    request = {
                        "action": mt5.TRADE_ACTION_DEAL,
                        "symbol": symbol,
                        "volume": lot,
                        "type": mt5.ORDER_TYPE_SELL,
                        "price": price,
                        "deviation": deviation,
                        "magic": 234000,
                        "comment": "python script open",
                        "type_time": mt5.ORDER_TIME_GTC,
                        "type_filling": 1
                    }
                    # send a trading request
                    result = mt5.order_send(request)
                    # check the execution result
                    print(
                        "1. order_send(): by {} {} lots at {} with deviation={} points"
                        .format(symbol, lot, price, deviation))
                    if result.retcode != mt5.TRADE_RETCODE_DONE:
                        print("2. order_send failed, retcode={}".format(
                            result.retcode))
                        # request the result as a dictionary and display it element by element
                        result_dict = result._asdict()
                        for field in result_dict.keys():
                            print("   {}={}".format(field, result_dict[field]))
                            # if this is a trading request structure, display it element by element as well
                            if field == "request":
                                traderequest_dict = result_dict[field]._asdict(
                                )
                                for tradereq_filed in traderequest_dict:
                                    print("       traderequest: {}={}".format(
                                        tradereq_filed,
                                        traderequest_dict[tradereq_filed]))

                    print("2. order_send done, ", result)
                    print("   opened position with POSITION_TICKET={}".format(
                        result.order))

            elif all(self._position == self._positions['long']):
                self._exit_price = self._tick_buy
                instant_pnl = round(self._exit_price, 5) - round(
                    self._entry_price, 5)
                self._position = self._positions['flat']
                self._entry_price = 0
                if trade:
                    position_id = result.order
                    price = mt5.symbol_info_tick(symbol).bid
                    deviation = 20
                    request = {
                        "action": mt5.TRADE_ACTION_DEAL,
                        "symbol": symbol,
                        "volume": lot,
                        "type": mt5.ORDER_TYPE_SELL,
                        "position": position_id,
                        "price": price,
                        "deviation": deviation,
                        "magic": 234000,
                        "comment": "python script close",
                        "type_time": mt5.ORDER_TIME_GTC,
                        "type_filling": 1,
                    }
                    # send a trading request
                    result = mt5.order_send(request)
                    # check the execution result
                    print(
                        "3. close position #{}: sell {} {} lots at {} with deviation={} points"
                        .format(position_id, symbol, lot, price, deviation))
                    if result.retcode != mt5.TRADE_RETCODE_DONE:
                        print("4. order_send failed, retcode={}".format(
                            result.retcode))
                        print("   result", result)
                    else:
                        print("4. position #{} closed, {}".format(
                            position_id, result))
                        # request the result as a dictionary and display it element by element
                        result_dict = result._asdict()
                        for field in result_dict.keys():
                            print("   {}={}".format(field, result_dict[field]))
                            # if this is a trading request structure, display it element by element as well
                            if field == "request":
                                traderequest_dict = result_dict[field]._asdict(
                                )
                                for tradereq_filed in traderequest_dict:
                                    print("       traderequest: {}={}".format(
                                        tradereq_filed,
                                        traderequest_dict[tradereq_filed]))

                    # shut down connection to the MetaTrader 5 terminal
                    positions = mt5.positions_get(symbol="GBPUSD")
                    if positions == None:
                        print("No positions on GBPUSD, error code={}".format(
                            mt5.last_error()))
                    elif len(positions) > 0:
                        print("Total positions on GBPUSD =", len(positions))
                        # display all open positions
                        for position in positions:
                            print(position)

                    # get the list of positions on symbols whose names contain "*USD*"
                    usd_positions = mt5.positions_get(group="*USD*")
                    if usd_positions == None:
                        print(
                            "No positions with group=\"*USD*\", error code={}".
                            format(mt5.last_error()))
                    elif len(usd_positions) > 0:
                        print("positions_get(group=\"*USD*\")={}".format(
                            len(usd_positions)))
                        # display these positions as a table using pandas.DataFrame
                        df = pd.DataFrame(
                            list(usd_positions),
                            columns=usd_positions[0]._asdict().keys())
                        df['time'] = pd.to_datetime(df['time'], unit='s')
                        df.drop([
                            'time_update', 'time_msc', 'time_update_msc',
                            'external_id'
                        ],
                                axis=1,
                                inplace=True)
                        #print(df)
                        instant_pnl = df['profit'][-1]
                # self.Sell_render = True

                if (instant_pnl > 0):
                    self.TP_render = True
                else:
                    self.SL_render = True

        else:
            self.Buy_render = self.Sell_render = False
            self.TP_render = self.SL_render = False
        usd_positions = mt5.positions_get(group="*USD*")

        reward += instant_pnl * 1000
        self._total_pnl += instant_pnl * 10000
        self._total_reward += reward

        try:
            self._prices_history.append(next(self._data_generator))
            self._tick_sell, self._tick_buy, self.tick_mid, self.tick_rsi_14, self.tick_cci_14= \
            self._prices_history[-1][:5]
        except StopIteration:
            done = True
            info['status'] = 'No more data.'

        # Game over logic
        if self._iteration >= self._episode_length:
            done = True
            info['status'] = 'Time out.'
        if reward <= self._max_lost:
            done = True
            info['status'] = 'Bankrupted.'
        if self._closed_plot:
            info['status'] = 'Closed plot'

        observation = self._get_observation()

        return observation, reward, done, info
Ejemplo n.º 20
0
def get_closed(trade, symbol='EURUSD', side='long', lot=0.01, magic=102):
    # establish connection to the MetaTrader 5 terminal
    if not mt5.initialize():
        print("initialize() failed, error code =", mt5.last_error())
        quit()
    # prepare the buy request structure
    symbol_info = mt5.symbol_info(symbol)
    if symbol_info is None:
        print(symbol, "not found, can not call order_check()")
        mt5.shutdown()
        quit()
    # if the symbol is unavailable in MarketWatch, add it
    if not symbol_info.visible:
        print(symbol, "is not visible, trying to switch on")
        if not mt5.symbol_select(symbol, True):
            print("symbol_select({}}) failed, exit", symbol)
            mt5.shutdown()
            quit()
    # create a close request
    ask = mt5.symbol_info_tick(symbol).ask
    bid = mt5.symbol_info_tick(symbol).bid
    if side == 'short':
        price = ask
        type_side = mt5.ORDER_TYPE_BUY
    elif side == 'long':
        price = bid
        type_side = mt5.ORDER_TYPE_SELL
    deviation = 20
    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": lot,
        "type": type_side,
        "position": trade,
        "price": price,
        "deviation": deviation,
        "magic": 234000,
        "comment": "python script close",
        "type_time": mt5.ORDER_TIME_GTC,
        #"type_filling": mt5.ORDER_FILLING_RETURN,
    }
    # send a trading request
    result = mt5.order_send(request)
    # check the execution result
    #print("3. close position #{}: sell {} {} lots at {} with deviation={} points".format(trade,symbol,lot,price,deviation));
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        print("4. order_send failed, retcode={}".format(result.retcode))
        #print("   result",result)
    else:
        #print("4. position #{} closed, {}".format(trade,result))
        # request the result as a dictionary and display it element by element
        result_dict = result._asdict()
        # for field in result_dict.keys():
        #     #print("   {}={}".format(field,result_dict[field]))
        #     # if this is a trading request structure, display it element by element as well
        #     if field=="request":
        #         traderequest_dict=result_dict[field]._asdict()
        #         for tradereq_filed in traderequest_dict:
        #             #print("       traderequest: {}={}".format(tradereq_filed,traderequest_dict[tradereq_filed]))
    # shut down connection to the MetaTrader 5 terminal
    mt5.shutdown()
def trade():
    """Check if Musk mentioned bitcoin and open a buy position if so"""
    what_musk_said = get_elons_tweet()

    # used to check if a position has already been placed
    positions = mt5.positions_get(symbol=CRYPTO)
    orders = mt5.orders_get(symbol=CRYPTO)
    symbol_info = mt5.symbol_info(CRYPTO)
    price = mt5.symbol_info_tick(CRYPTO).bid

    # perform logic check
    if any(keyword in what_musk_said for keyword in keywords):
        print(f'the madlad said it - buying some!')

        # prepare the trade request
        if not mt5.initialize():
            raise RuntimeError(
                f'MT5 initialize() failed with error code {mt5.last_error()}')

        # check that there are no open positions or orders
        if len(positions) == 0 and len(orders) < 1:
            if symbol_info is None:
                print(f'{CRYPTO} not found, can not call order_check()')
                mt5.shutdown()

            # if the symbol is unavailable in MarketWatch, add it
            if not symbol_info.visible:
                print(f'{CRYPTO} is not visible, trying to switch on')
                if not mt5.symbol_select(CRYPTO, True):
                    print('symbol_select({}}) failed, exit', CRYPTO)

            #this represents 5% Equity. Minimum order is 0.01 BTC. Increase equity share if retcode = 10014
            lot = float(round(((equity / 5) / price), 2))

            # define stop loss and take profit
            sl = price - (price * 5) / 100
            tp = price + (price * 10) / 100
            request = {
                'action': mt5.TRADE_ACTION_DEAL,
                'symbol': CRYPTO,
                'volume': lot,
                'type': mt5.ORDER_TYPE_BUY,
                'price': price,
                'sl': sl,
                'tp': tp,
                'magic': 66,
                'comment': 'python-buy',
                'type_time': mt5.ORDER_TIME_GTC,
                'type_filling': mt5.ORDER_FILLING_IOC,
            }

            # send a trading request
            result = mt5.order_send(request)

            # check the execution result
            print(f'1. order_send(): by {CRYPTO} {lot} lots at {price}')

            if result.retcode != mt5.TRADE_RETCODE_DONE:
                print(f'2. order_send failed, retcode={result.retcode}')

            #print the order result - anything else than retcode=10009 is an error in the trading request.
            print(f'2. order_send done, {result}')
            print(f'   opened position with POSITION_TICKET={result.order}')

        else:
            print(
                f'BUY signal detected, but {CRYPTO} has {len(positions)} active trade'
            )

    else:
        print(f'He did not say it, he said: {what_musk_said}')
Ejemplo n.º 22
0
# get account currency
account_currency = mt5.account_info().currency
print("Account сurrency:", account_currency)

# 准备请求结构
symbol = "USDJPY"
symbol_info = mt5.symbol_info(symbol)
if symbol_info is None:
    print(symbol, "not found, can not call order_check()")
    mt5.shutdown()
    quit()

# 如果市场报价中没有此交易品种,请添加
if not symbol_info.visible:
    print(symbol, "is not visible, trying to switch on")
    if not mt5.symbol_select(symbol, True):
        print("symbol_select({}}) failed, exit", symbol)
        mt5.shutdown()
        quit()

# prepare the request
point = mt5.symbol_info(symbol).point
request = {
    "action": mt5.TRADE_ACTION_DEAL,
    "symbol": symbol,
    "volume": 1.0,
    "type": mt5.ORDER_TYPE_BUY,
    "price": mt5.symbol_info_tick(symbol).ask,
    "sl": mt5.symbol_info_tick(symbol).ask - 100 * point,
    "tp": mt5.symbol_info_tick(symbol).ask + 100 * point,
    "deviation": 10,
Ejemplo n.º 23
0
 def select_symbol(self):
     Mt5.symbol_select(self.symbol, True)
Ejemplo n.º 24
0
import MetaTrader5 as mt5
import pandas as pd

# 显示有关MetaTrader 5程序包的数据
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)
print()
# 建立与MetaTrader 5程序端的连接
if not mt5.initialize(
        login=25115284, server="MetaQuotes-Demo", password="******"):
    print("initialize() failed, error code =", mt5.last_error())
    quit()

# 尝试在市场报价中启用显示EURCAD
selected = mt5.symbol_select("EURCAD", True)
if not selected:
    print("Failed to select EURCAD, error code =", mt5.last_error())
# 其他:
# symbol_info = mt5.symbol_info("EURCAD")
# print(symbol_info)
# print("EURCAD: currency_base =", symbol_info.currency_base, "  currency_profit =", symbol_info.currency_profit,
#       "  currency_margin =", symbol_info.currency_margin)
# print()
#
# # get symbol properties in the form of a dictionary
# print("Show symbol_info()._asdict():")
# symbol_info_dict = symbol_info._asdict()
# for prop in symbol_info_dict:
#     print("  {}={}".format(prop, symbol_info_dict[prop]))
# print()
#
Ejemplo n.º 25
0
# All stocks trading < $100
import MetaTrader5 as mt5
import pandas as pd

mt5.initialize()

all_assets = mt5.symbols_get()

stocks = list()
small = list()

for asset in all_assets:
    if "Stock" in asset.path:
        stocks.append(asset.name)

for stock in stocks:
    if 'ETF' in mt5.symbol_info(stock).path:
        stocks.remove(stock)
# print(stocks)

for stock in stocks:
    mt5.symbol_select(stock)
    if mt5.symbol_info_tick(stock).ask <= 100:
        small.append(stock)

print(small)
print(len(small))
mt5.shutdown()
Ejemplo n.º 26
0
def trade():
    """Determine if we should trade and if so, send requests to MT5."""
    utc_from, utc_to = get_dates()
    candles = get_data()
    current_buy_price, current_sell_price = get_current_prices()

    # calculate the % difference between the current price and the close price of the previous candle
    difference = (candles['close'][-1] -
                  candles['close'][-2]) / candles['close'][-2] * 100

    # used to check if a position has already been placed
    positions = mt5.positions_get(symbol=CRYPTO)
    orders = mt5.orders_get(symbol=CRYPTO)
    symbol_info = mt5.symbol_info(CRYPTO)

    # perform logic check
    if difference > 3:
        print(f'dif 1: {CRYPTO}, {difference}')
        # Pause for 8 seconds to ensure the increase is sustained
        time.sleep(8)

        # calculate the difference once again
        candles = mt5.copy_rates_range(CRYPTO, mt5.TIMEFRAME_M10, utc_from,
                                       utc_to)
        difference = (candles['close'][-1] -
                      candles['close'][-2]) / candles['close'][-2] * 100
        if difference > 3:
            print(f'dif 2: {CRYPTO}, {difference}')
            price = mt5.symbol_info_tick(CRYPTO).bid
            print(
                f'{CRYPTO} is up {str(difference)}% in the last 5 minutes opening BUY position.'
            )

            # prepare the trade request
            if not mt5.initialize():
                raise RuntimeError(
                    f'MT5 initialize() failed with error code {mt5.last_error()}'
                )

            # check that there are no open positions or orders
            if len(positions) == 0 and len(orders) < 1:
                if symbol_info is None:
                    print(f'{CRYPTO} not found, can not call order_check()')
                    mt5.shutdown()
                    # if the symbol is unavailable in MarketWatch, add it
                if not symbol_info.visible:
                    print(f'{CRYPTO} is not visible, trying to switch on')
                    if not mt5.symbol_select(CRYPTO, True):
                        print('symbol_select({}}) failed, exit', CRYPTO)

                #this represents 5% Equity. Minimum order is 0.01 BTC. Increase equity share if retcode = 10014
                lot = float(round(((equity / 20) / current_buy_price), 2))
                # define stop loss and take profit
                sl = price - (price * 5) / 100
                tp = price + (price * 8) / 100
                request = {
                    'action': mt5.TRADE_ACTION_DEAL,
                    'symbol': CRYPTO,
                    'volume': lot,
                    'type': mt5.ORDER_TYPE_BUY,
                    'price': price,
                    'sl': sl,
                    'tp': tp,
                    'magic': 66,
                    'comment': 'python-buy',
                    'type_time': mt5.ORDER_TIME_GTC,
                    'type_filling': mt5.ORDER_FILLING_IOC,
                }

                # send a trading request
                result = mt5.order_send(request)

                # check the execution result
                print(f'1. order_send(): by {CRYPTO} {lot} lots at {price}')

                if result.retcode != mt5.TRADE_RETCODE_DONE:
                    print(f'2. order_send failed, retcode={result.retcode}')

                #print the order result - anything else than retcode=10009 is an error in the trading request.
                print(f'2. order_send done, {result}')
                print(
                    f'   opened position with POSITION_TICKET={result.order}')

            else:
                print(
                    f'BUY signal detected, but {CRYPTO} has {len(positions)} active trade'
                )

        else:
            pass

    else:
        if orders or positions:
            print(
                'Buying signal detected but there is already an active trade')
        else:
            print(f'difference is only: {str(difference)}% trying again...')
Ejemplo n.º 27
0
def insertion(symbol):
    mt5.symbol_select(symbol, True)
Ejemplo n.º 28
0
    print("initialize() failed")
    quit()

symbol_1 = 'EURUSD'
symbol_2 = 'GBPUSD'

symbol_1_info = mt5.symbol_info(symbol_1)
symbol_2_info = mt5.symbol_info(symbol_2)
if symbol_1_info and symbol_2_info is None:
    print(symbol_1, 'and', symbol_2, "not found, can not call order_check()")
    mt5.shutdown()
    quit()

if not symbol_1_info.visible and symbol_2_info.visible:
    print(symbol_1, 'and', symbol_2, "is not visible, trying to switch on")
    if not mt5.symbol_select(symbol_1, True) and mt5.symbol_select(
            symbol_2, True):
        print("symbol_select({}}) failed, exit", symbol_1)
        print("symbol_select({}}) failed, exit", symbol_2)
        mt5.shutdown()
        quit()

timezone = pytz.timezone("Etc/UTC")
utc_from = datetime(2017, 7, 25, tzinfo=timezone)
utc_to = datetime(2018, 7, 25, tzinfo=timezone)

rates_eur = mt5.copy_rates_range(symbol_1, mt5.TIMEFRAME_D1, utc_from, utc_to)
rates_gbp = mt5.copy_rates_range(symbol_2, mt5.TIMEFRAME_D1, utc_from, utc_to)

rates_eur_frame = pd.DataFrame(rates_eur)
rates_eur_frame['time'] = pd.to_datetime(rates_eur_frame['time'], unit='s')
Ejemplo n.º 29
0
def synthesize(symbol1, symbol2, period):
    """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."""

    mt5.symbol_select(symbol1)
    mt5.symbol_select(symbol2)
    time.sleep(2)

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

    # 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')

    base_asset.set_index(keys=['time'], inplace=True)
    quote_asset.set_index(keys=['time'], inplace=True)

    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']]

    else:
        dollarisedAsset = dollarizer(symbol1, dollarPair(baseAsset_quote),
                                     period)

        if symbol2[3:6] == 'USD':
            basequote = dollarisedAsset[[
                'open', 'high', 'low', 'close'
            ]] / quote_asset[['open', 'high', 'low', 'close']]
        else:
            basequote = dollarisedAsset[[
                'open', 'high', 'low', 'close'
            ]] * quote_asset[['open', 'high', 'low', 'close']]

    return basequote
Ejemplo n.º 30
0
import random
import FinalCode.Orders as Orders

account = 820585
password = "******"

if not mt5.initialize():
    print(mt5.last_error())
    raise ValueError("Error! Did not initialise")
if not mt5.login(account, password=password):
    print(mt5.last_error())
    raise ValueError("Error! Did not login")

symbols = {"EURGBP": [], "GBPUSD": [], "EURUSD": []}

mt5.symbol_select("EURGBP", True)
mt5.symbol_select("GBPUSD", True)
mt5.symbol_select("EURUSD", True)


def algorithm():
    return {
        "EURGBP": [random.randint(2), [True, False][random.randint(2)]],
        "GBPUSD": [random.randint(2), [True, False][random.randint(2)]],
        "EURUSD": [random.randint(2), [True, False][random.randint(2)]]
    }


items = algorithm()
for symbol in items:
    if items[symbol][0] == 0: