Ejemplo n.º 1
0
def check(n, count_wins, count_losses):
    if n > 0:
        txt = "buy"
    else:
        txt = "sell"
    while True:
        spread = round(
            mt5.symbol_info("USDJPY").ask - mt5.symbol_info("USDJPY").bid, 7)
        print("\r",
              txt,
              ", current profit: ",
              mt5.account_info().profit,
              ", spread: ",
              round(spread * 10, 4),
              flush=True)
        if mt5.account_info().profit > 0.03:
            count_wins += 1
            win(n, count_wins, count_losses)
            break
        elif mt5.account_info().profit < -0.21:
            count_losses += 1
            loss(n, count_wins, count_losses)
            break
        else:
            pass
        time.sleep(0.2)
    return count_wins, count_losses
Ejemplo n.º 2
0
    def swap(self):
        """Returns the swap that you will pay or receive in USD after taking that position."""

        if self.symbol[-1:-5:-1] in ['ESYN', 'SAN.'
                                     ]:  #Calculaing swap for Shares and ETFs
            if self.position() == 'Long':
                swap_rate = mt5.symbol_info(self.symbol).swap_long
            elif self.position() == 'Short':
                swap_rate = mt5.symbol_info(self.symbol).swap_short

            swapPerDay = ((self.exposure() * swap_rate) / 100) / 365

            return swapPerDay

        else:  #Calculating swap for forex, commodities, index.
            if self.position() == 'Long':
                swap_rate = mt5.symbol_info(self.symbol).swap_long
            elif self.position() == 'Short':
                swap_rate = mt5.symbol_info(self.symbol).swap_short

            swapPerDay = swap_rate * self.volume

            if self.symbol[0:3] == 'USD':
                adjustedSwap = swapPerDay / mt5.symbol_info_tick(
                    self.symbol).ask
                return adjustedSwap
            elif self.symbol in list1:
                return self._fxAdjust(swapPerDay, list1[self.symbol])
            else:
                return swapPerDay
Ejemplo n.º 3
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
Ejemplo n.º 4
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.º 5
0
    def __init__(
        self,
        expert_name,
        version,
        symbol,
        magic_number,
        lot: float,
        stop_loss,  # It calls a functions that tries to close the deal, it is the stop you want.
        emergency_stop_loss,  # It set stop on chart as a protection
        # if something went wrong with the stop_loss.
        take_profit,  # The same of stop_loss but for profit.
        emergency_take_profit,  # The same of emergency_stop_loss but for gain
        start_time='9:15',  # It is the hour and minutes that the expert advisor are able to start to run.
        finishing_time='17:30',  # No new position can be opened after that time.
        ending_time='17:50',  # If there is a position opened it will be closed.
        fee=0.0,
    ):

        self.expert_name = expert_name
        self.version = version
        self.symbol = symbol
        self.magic_number = magic_number
        self.lot = lot
        self.stop_loss = stop_loss
        self.emergency_stop_loss = emergency_stop_loss
        self.take_profit = take_profit
        self.emergency_take_profit = emergency_take_profit
        self.start_time_hour, self.start_time_minutes = start_time.split(':')
        self.finishing_time_hour, self.finishing_time_minutes = finishing_time.split(
            ':')
        self.ending_time_hour, self.ending_time_minutes = ending_time.split(
            ':')
        self.fee = fee

        self.loss_deals = 0
        self.profit_deals = 0
        self.total_deals = 0
        self.balance = 0.0

        self.ticket = 0

        print('\nInitializing the basics.')
        self.initialize()
        self.select_symbol()
        self.prepare_symbol()
        self.sl_tp_steps = Mt5.symbol_info(
            self.symbol).trade_tick_size / Mt5.symbol_info(self.symbol).point
        print('Initialization successfully completed.')

        print()
        self.summary()
        print('Running')
        print()
Ejemplo n.º 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
Ejemplo n.º 7
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.º 8
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
Ejemplo n.º 9
0
def getSharesStep(assetId, money=None):
    if not connected:
        print(
            "In order to use this function, you must be connected to B3. Use function connect()"
        )
        return
    return mt5.symbol_info(assetId).volume_step
Ejemplo n.º 10
0
def vwap_reversion(symbol, period):
    """
    Implements a simple mean reversion using the vwap
    :symbol: the symbol of the instrument
    :period: how often you want to check the last vwap against the current price (in seconds)
    """
    print(f"reversion {symbol} started")
    # buy and sell buffers to store the orders
    buy_buf = []
    sell_buf = []

    while True:
        symbol_inf = mt5.symbol_info(symbol)
        mean = vwap(symbol)[0][-1]
        print(
            f"{symbol} mean: {mean}\nask: {symbol_inf.ask}\nask-mean: {symbol_inf.ask-mean}"
        )

        if symbol_inf.ask < 0.995 * mean:
            buy_buf.append(
                open_order(symbol, "buy", 10, symbol_inf.ask * 1.005))
            print(f"{symbol} bought")
        # elif symbol_inf.ask > 1.005 * mean:
        #     # sell_buf.append(open_order(symbol, "sell", 1))
        #     for i in buy_buf[::-1]:
        #         close_order(symbol, "sell", i.volume, i.order)
        #         sell_buf.append(buy_buf.pop())
        #         print(f"sold {symbol}: {i}")

        for i, j in enumerate(buy_buf):
            print(f"printing {symbol} buy buffer[{i}]:", j)

        time.sleep(period)
Ejemplo n.º 11
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.º 12
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')
Ejemplo n.º 13
0
def historyData(Symbol):
    mt5.initialize(server="ForexClub-MT5 Demo Server",
                   login=500063649,
                   password="******")
    # print(mt5.terminal_info())
    # print(mt5.version())
    listSymbols = mt5.symbols_get()
    # [x.name for x in listSymbols]
    # Symbol=np.random.choice(FXmajor, 1)[0]
    print(Symbol)
    pointValue = mt5.symbol_info(Symbol).point
    # mt5.Buy("EURUSD", 0.1,price=11395,ticket=9)
    Num_velas = 1000
    # Copying data to pandas data frame
    # rates =  mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas)
    rates = mt5.copy_rates_range(Symbol, mt5.TIMEFRAME_H1,
                                 datetime(2021, 1, 10), datetime.now())
    # rates =  mt5.copy_rates_range("ES", mt5.TIMEFRAME_D1, datetime(2019, 1, 15), datetime(2019, 1, 25))
    # rates =  mt5.copy_rates_from_pos(Symbol, mt5.TIMEFRAME_M1, 0, Num_velas)

    # Deinitializing MT5 connection
    mt5.shutdown()
    # create DataFrame out of the obtained data
    rates_frame = pd.DataFrame(rates)
    # convert time in seconds into the datetime format
    rates_frame.index = pd.to_datetime(rates_frame['time'], unit='s')

    rates_frame.columns = [
        'time', 'Open', 'High', 'Low', 'Close', 'tick_volume', 'spread',
        'real_volume'
    ]
    return rates_frame
Ejemplo n.º 14
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
Ejemplo n.º 15
0
def OnTick():
    print("OnTick")
    if mt5.positions_total() == 0:
        n = rnd.random()
        if n > 0.5:
            print("Buy")
            point = mt5.symbol_info(symbol).point
            price = mt5.symbol_info_tick(symbol).ask
            request = {
                "action": mt5.TRADE_ACTION_DEAL,
                "symbol": symbol,
                "volume": OnLot(),
                "type": mt5.ORDER_TYPE_BUY,
                "price": price,
                "sl": price - SL * point,
                "tp": price + TP * point,
                "deviation": deviation,
                "magic": magic,
                "comment": "python script open",
                "type_time": mt5.ORDER_TIME_GTC,
                "type_filling": mt5.ORDER_FILLING_FOK,
            }
            result = mt5.order_send(request)
            print("Error ", result.retcode)
        else:
            print("Sell")
            point = mt5.symbol_info(symbol).point
            price = mt5.symbol_info_tick(symbol).bid
            request = {
                "action": mt5.TRADE_ACTION_DEAL,
                "symbol": symbol,
                "volume": OnLot(),
                "type": mt5.ORDER_TYPE_SELL,
                "price": price,
                "sl": price + SL * point,
                "tp": price - TP * point,
                "deviation": deviation,
                "magic": magic,
                "comment": "python script open",
                "type_time": mt5.ORDER_TIME_GTC,
                "type_filling": mt5.ORDER_FILLING_FOK,
            }
            result = mt5.order_send(request)
            print("Error ", result.retcode)
    return
Ejemplo n.º 16
0
    def runner(self):
        """Returns an order request. Will automatically close 'pct_close' percent of all positions and set the stoploss
            to the opening price + 'sl_points'

            Will implement a ticket system to allow specification of a position"""
        for pos in mt5.positions_get():
            position_id = mt5.TradePosition(pos).ticket
            symbol = mt5.TradePosition(pos).symbol
            order = mt5.TradePosition(pos).type
            point = mt5.symbol_info(symbol).point
            price = mt5.TradePosition(pos).price_open
            bid = mt5.symbol_info_tick(symbol).bid
            ask = mt5.symbol_info_tick(symbol).ask
            current_price = mt5.TradePosition(pos).price_current
            pct_close = 80
            sl_points = 30
            tp_points = 500

            if order == 0:  # Buy
                new_sl = round(price + sl_points * point, 3)
                if current_price < new_sl:
                    print("Desired SL is under current price")
                else:
                    self.close_custom_pct(pct_close, ticket=position_id)
                    request = {
                        "action": mt5.TRADE_ACTION_SLTP,
                        "symbol": symbol,
                        "position": position_id,
                        "sl": new_sl,
                        "tp": round(ask + tp_points * point, 3),
                        "magic": self.magic,
                        "comment": f"python runner {symbol}"
                    }
            if order == 1:  # Sell
                new_sl = round(price - sl_points * point, 3)
                if current_price > new_sl:
                    print("Desired SL is over current price")
                else:
                    self.close_custom_pct(pct_close, ticket=position_id)
                    request = {
                        "action": mt5.TRADE_ACTION_SLTP,
                        "symbol": symbol,
                        "position": position_id,
                        "sl": new_sl,
                        "tp": round(bid - (tp_points * point), 3),
                        "magic": self.magic,
                        "comment": f"python runner {symbol}"
                    }

            try:
                result = mt5.order_send(request)
                self.order_error_check(result)
            except UnboundLocalError:
                print(f"Desired SL      : {new_sl}")
                print(
                    f"Current Price   : {mt5.TradePosition(pos).price_current}"
                )
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
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.º 19
0
    def get_symbol_info(self, symbol=None):
        """Get data on the specified financial instrument.

        Args:
            symbol (str, optional): Financial instrument name. Defaults to None.

        Returns:
            dict: Symbol information
        """
        instrument = symbol if symbol else self.symbol
        return mt5.symbol_info(instrument)._asdict()
Ejemplo n.º 20
0
def spread_is_ok(df, i, symbol):

    info = mt5.symbol_info(symbol)

    # Get the spread in pips rather than points
    spread = info.spread * info.point

    if spread <= df.loc[i, 'atr'] * 1 / 3:
        return True
    else:
        return False
Ejemplo n.º 21
0
def get_spread_from_ticks(ticks_frame, symbol):
    """
    :param ticks_frame: pd.DataFrame, all tick info
    :return: pd.Series
    """
    spread = pd.Series((ticks_frame['ask'] - ticks_frame['bid']) *
                       (10**mt5.symbol_info(symbol).digits),
                       index=ticks_frame.index,
                       name='ask_bid_spread_pt')
    spread = spread.groupby(spread.index).mean()  # groupby() note 56b
    return spread
Ejemplo n.º 22
0
def getAfforShares(assetId, money=None, price=None):
    if money == None:
        money = mt5.account_info().margin_free
    if price == None:
        close = mt5.symbol_info_tick(assetId).last
    else:
        close = price
    step = mt5.symbol_info(assetId).volume_step
    free = 0
    while free * close < money:
        free = free + step
    return free - step
Ejemplo n.º 23
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.º 24
0
def checkAllSigs(numBefore,
                 timePeriod,
                 signals,
                 verbose=True,
                 sendMail=True,
                 placeorder=True):
    maxTime = None
    recVals = None

    currTime = dt.now()
    tradeSigs = []

    for i, currSig in enumerate(signals):
        rates = getData(numBefore, timePeriod, currSig, timeDict)
        boll = getBollBands(rates.close)
        rsi = getRSI(rates.close)
        filteredDf, maxTime = cleanDf(rates, boll, rsi)
        makeTrade, order_type = checkMakeTradeVariant(filteredDf)
        # exit()

        # recVals, maxTime = getMostRecent(rsi, boll, rates)
        # makeTrade, order_type = checkMakeTrade(recVals)
        spr = mt5.symbol_info(currSig).spread
        if spr < 50:
            if verbose:
                print(
                    f'Signal {i}:\t{currSig}\t\tSpread:{spr}\tMake trade = {makeTrade}'
                )
            pass
        else:
            if verbose: print(f'Signal {i}:\t{currSig}\t\tSpread:{spr}\tSKIP')
            continue

        # if verbose: print(f'Signal {i}:\t{currSig}\t\tSpread:{spr}\t\tMake trade = {makeTrade}')

        # If there's a signal which should be traded, open a window
        if makeTrade:
            tradeSigs.append(currSig)

            if placeorder:
                placeOrder(currSig, order_type, 100, 100)

    if sendMail and len(tradeSigs) > 0:
        sendEmail(
            f'Subject: Trading bot making {len(tradeSigs)} trades at {currTime.strftime("%H:%M:%S")} on {tradeSigs}'
        )

    if verbose:
        print(
            f'\nTrading bot found {len(tradeSigs)} suggested trades at {currTime.strftime("%H:%M:%S")}\t Make trades on signals {tradeSigs}'
        )

    return maxTime
Ejemplo n.º 25
0
def to_him_who_has_more_shall_be_given():
    ''' Track the profit on the different pairs in a basket. 
    Every n bars reallocate n % of the trade volume from the least
    profitable to the most profitable. '''

    positions = mt5.positions_get()
    if len(positions) == 0:
        return

    # How much to reallocate at a time
    close_percent = 0.1

    # How many bars to wait in between reallocation
    reallocation_cycle = 3

    baskets = get_best_and_worst_pairs_of_baskets(positions)
    if not baskets:
        return

    # Get current server time (I think this is actually more like "last update time"
    # of the passed symbol. so it won't change if the market is closed)
    server_time = mt5.symbol_info('EURUSD')._asdict()['time']

    for basket in baskets:
        
        worst_position = baskets[basket]['worst']
        best_position = baskets[basket]['best']
        # print('\n',baskets[basket],'\n')
        # print('\n',best_position,'\n')
        # iono how i wanna quantify one trade being n% more profitable...
        # how do i give meaning to the profitability of a trade...
        # maybe i just say f it and go strictly time based  
        # so like.. after 3 bars start moving funds
        # and move 5% every 3 bar or something. that 3% will become a smaller
        # and smaller number each time but i can solve that later if i want

        # See if 3 candles have closed since the last update to that trade
        time_passed = server_time - best_position['time_update']
        basket_timeframe = basket.split('_')[1]
        if time_passed >= tf_to_sec[basket_timeframe] * reallocation_cycle:

            # Reallocate the funds. So partial close on basket['worst'] and new entry on ['best']

            # 'volume' in dict is the current trade volume. im just goinng to override that value
            # with the amount i wanna close so I can pass that dict to close_trades() as is
            reallocation_lot_size = round(worst_position['volume'] * close_percent, 2)
            worst_position['volume'] = reallocation_lot_size
            close_trades([worst_position])

            symbol = best_position['symbol']
            direction = best_position['direction']
            enter_manual_trade(symbol, basket, basket_timeframe, reallocation_lot_size, direction, pair_data)            
Ejemplo n.º 26
0
def enter_manual_trade(symbol, basket, timeframe, volume, direction, pair_data) -> None:
    ''' This is used by to_him_who_has_more_shall_be_given() and enters
    a market order on a specific symbol'''

    # If '.a' or some other suffix got added to the symbol
    # remove that in order to access pair_data
    x = symbol.split('.')[0]
    digits = pair_data[x]['digits']
    atr = pair_data[x]['atr'][timeframe]

    if direction == 'buy':
        price = mt5.symbol_info(symbol).ask
        stop_loss = price - 1.5 * atr
        take_profit = price + 5 * atr
        type = mt5.ORDER_TYPE_BUY
    else:
        price = mt5.symbol_info(symbol).bid
        stop_loss = price + 1.5 * atr
        take_profit = price - 5 * atr
        type = mt5.ORDER_TYPE_SELL

    request = {
        'action': mt5.TRADE_ACTION_DEAL,
        'symbol': symbol,
        'volume': float(volume), # int will error
        'sl': round(stop_loss,  digits),
        'tp': round(take_profit,  digits),
        'deviation': 10,
        'type': type,
        'type_time': mt5.ORDER_TIME_GTC,
        'type_filling': mt5.ORDER_FILLING_IOC,
        'comment': f'{basket} reallocation', 
    }
                                                                                                                        
    # send a trading request
    result = mt5.order_send(request)
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        bot.send_message(chat_id=446051969, text=f'Manunal entry failed: {symbol} {timeframe} {direction}')
        print(f'manual entry failed on {symbol} rc: {result.retcode}')
Ejemplo n.º 27
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.º 28
0
def run(ticker):

    #print(ticker)

    if not mt5.initialize():
        print("initialize() failed, error code =", mt5.last_error())
        quit()

    info = mt5.symbol_info(ticker)

    if ticker not in USA_STOCKS:
        df_1min = get_candles(
            ticker, 'mt5.TIMEFRAME_M1',
            5000).loc[:, ['open', 'high', 'low', 'close', 'volume']]
    else:
        # Получаем с яху, потому что с МТ5 с 15 минутным лагом
        df_1min = get_american_candles(
            ticker, '3d', '1m').loc[:,
                                    ['open', 'high', 'low', 'close', 'volume']]
    df_5min = df_1min.resample('5Min').agg(AGG_DICT)
    df_hour = df_1min.resample('60Min').agg(AGG_DICT)
    df_day = df_1min.resample('1D').agg(AGG_DICT)

    rsi = RSI()
    df_1min = rsi.get_value_df(df_1min)
    df_5min = rsi.get_value_df(df_5min)

    signal = check_trade_conditions(ticker, df_day, df_hour, df_5min, df_1min)

    if signal is not None:
        signal_is_sent = check_signal_is_sent(ticker)
        position = get_positions(ticker)

        if (not signal_is_sent) and (position is None):

            acceptable_PERC_loss = (open_close_5min_dif_mean[ticker] +
                                    open_close_5min_dif_std[ticker])
            last_close = df_5min.close[-1]
            trade_size = calculate_trade_size(ticker, acceptable_PERC_loss,
                                              last_close)
            contract_size = info.trade_contract_size
            min_volume = info.volume_min
            trade_size = round(trade_size / contract_size / min_volume)
            trade_size = trade_size * min_volume

            direction = 'sell' if signal == 'sell' else 'buy'
            send_message(ticker + ' ' + direction + ' ' + str(trade_size))
            print(send_transaction(ticker, trade_size, direction))
            cur_time = datetime.now().time()
            print(cur_time, ticker, direction, trade_size)
            set_signal_is_sent_flag(ticker)
Ejemplo n.º 29
0
def checkAllSigs(numBefore,
                 timePeriod,
                 signals,
                 verbose=True,
                 sendMail=True,
                 placeorder=True):
    maxTime = None
    recVals = None

    currTime = dt.now()
    tradeSigs = []

    for i, currSig in enumerate(signals):
        rates = getData(numBefore, timePeriod, currSig, timeDict)
        rsi = getRSI(rates.close)
        filteredDf, maxTime = cleanDf(rates, rsi)
        makeTrade, order_type, rsi = checkMakeTrade(
            filteredDf[filteredDf.Date == max(filteredDf.Date)])

        spr = mt5.symbol_info(currSig).spread
        if spr < 50:
            if verbose:
                print(f'Signal {i}:\t{currSig}\t\tSpread:{spr}' +
                      '\tRSI = %.2f' % rsi + f'\tMake trade = {makeTrade}')
            pass
        else:
            if verbose: print(f'Signal {i}:\t{currSig}\t\tSpread:{spr}\tSKIP')
            continue

        # If there's a signal which should be traded, open a window
        if makeTrade:
            tradeSigs.append(currSig)

            if placeorder:
                placeOrder(currSig,
                           order_type,
                           pipsprof=50,
                           pipsloss=50,
                           lot=0.05)

    if sendMail and len(tradeSigs) > 0:
        sendEmail(
            f'Subject: Trading bot making {len(tradeSigs)} trades at {currTime.strftime("%H:%M:%S")} on {tradeSigs}'
        )

    if verbose:
        print(
            f'\nTrading bot found {len(tradeSigs)} suggested trades at {currTime.strftime("%H:%M:%S")}\t Make trades on signals {tradeSigs}'
        )

    return maxTime
Ejemplo n.º 30
0
    def stop_and_gain(self, comment=''):
        if len(Mt5.positions_get()) == 1:

            points = (Mt5.positions_get()[0].profit *
                      Mt5.symbol_info(self.symbol).trade_tick_size /
                      Mt5.symbol_info(self.symbol).trade_tick_value) / \
                     Mt5.positions_get()[0].volume

            if points / Mt5.symbol_info(self.symbol).point >= self.take_profit:
                self.profit_deals += 1
                self.close_position(comment)
                print(
                    f'Take profit reached. ('
                    f'{int(Mt5.history_deals_get((datetime.today() - timedelta(days=1)), datetime.now())[-1].profit)}'
                    f')\n')
                if Mt5.history_deals_get((datetime.today() - timedelta(days=1)), datetime.now())[-1].symbol == \
                        self.symbol:
                    self.balance += int(
                        Mt5.history_deals_get(
                            (datetime.today() - timedelta(days=1)),
                            datetime.now())[-1].profit)
                self.statistics()

            elif ((points / Mt5.symbol_info(self.symbol).point) *
                  -1) >= self.stop_loss:
                self.loss_deals += 1
                self.close_position(comment)
                print(
                    f'Stop loss reached. ('
                    f'{int(Mt5.history_deals_get((datetime.today() - timedelta(days=1)), datetime.now())[-1].profit)}'
                    f')\n')
                if Mt5.history_deals_get((datetime.today() - timedelta(days=1)), datetime.now())[-1].symbol == \
                        self.symbol:
                    self.balance += int(
                        Mt5.history_deals_get(
                            (datetime.today() - timedelta(days=1)),
                            datetime.now())[-1].profit)
                self.statistics()