Exemplo n.º 1
0
Arquivo: main.py Projeto: kz0/BITMEX
    def __init__(self):
        self.logger = setup_logger()
        test = False
        api_key = os.getenv('API_KEY')
        api_secret = os.getenv('API_SECRET')
        test_url = 'https://testnet.bitmex.com/api/v1'
        product_url = 'https://www.bitmex.com/api/v1'

        self.logger.info('APIKEY: %s' % api_key)
        if test:
            url = test_url
        else:
            url = product_url
        self.cli = bitmex(test=test, api_key=api_key, api_secret=api_secret)
        self.ws = BitMEXWebsocket(endpoint=url,
                                  symbols=["XBTUSD", self.contract_name],
                                  api_key=api_key,
                                  api_secret=api_secret)

        # init redis client
        self.redis_cli = redis.Redis(host='35.230.143.112',
                                     password='******',
                                     port=6379,
                                     decode_responses=True)

        self.last_sms_time = 0
Exemplo n.º 2
0
    def __init__(self):
        self.logger = setup_logger()
        test = False
        api_key = 'dbS7FklMUz4A0Ftf_0eb-khj'
        api_secret = 'UGbHj7ucCrz1xz5slMhPPAV72wemdXxxMk4J2OS_73foWObM'
        test_url = 'https://testnet.bitmex.com/api/v1'
        product_url = 'https://www.bitmex.com/api/v1'
        if test:
            url = test_url
        else:
            url = product_url
        self.cli = bitmex(test=test, api_key=api_key, api_secret=api_secret)
        self.ws = BitMEXWebsocket(endpoint=url,
                                  symbols=[self.contract_name],
                                  api_key=api_key,
                                  api_secret=api_secret)
        #init redis client
        self.redis_cli = redis.Redis(host='localhost', port=6379, decode_responses=True)

        # test reids
        self.redis_cli.sadd(self.filled_order_set, 'test orderid')

        # threading lock
        self._value_lock = threading.Lock()
        self.unfilled_sell_list = ''
        self.unfilled_buy_list = ''
Exemplo n.º 3
0
def run():
    logger = setup_logger()

    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = BitMEXWebsocket(
        endpoint="https://testnet.bitmex.com/api/v1",
        symbol="XBTUSD",
        api_key='-H4GmpGWNC505KogaaKyxoch',
        api_secret='GBM8hOsE9PYnKj374IHqv7M096sEpRSfoLZvA3hvY6oIHizJ')

    logger.info("Instrument data: %s" % ws.get_instrument())

    # Run forever
    while (ws.ws.sock.connected):
        # print("test")
        logger.info("Ticker: %s" % ws.get_ticker())
        data = ws.get_ticker()
        data = [str(data[k]) for k in data]
        with open(r'bitmex.csv', 'a') as f:
            writer = csv.writer(f)
            writer.writerow(data)
        f.close()
        # if ws.api_key:
        #     logger.info("Funds: %s" % ws.funds())
        # logger.info("Market Depth: %s" % ws.market_depth())
        # logger.info("Recent Trades: %s\n\n" % ws.recent_trades())
        sleep(10)
Exemplo n.º 4
0
def run():
    if "BITMEX_API_KEY" not in os.environ:
      print("BITMEX_API_KEY env var must be set")
      exit(1)

    if "BITMEX_API_SECRET" not in os.environ:
      print("BITMEX_API_SECRET env var must be set")
      exit(1)

    bq = BigQuery(
      table="XBTUSD_trade_data",
      dataset="bitmex",
      schema=schema)
    logger = setup_logger()

    ws = BitMEXWebsocket(
      endpoint="https://www.bitmex.com/api/v1",
      symbol="XBTUSD",
      api_key=os.environ.get('BITMEX_API_KEY'),
      api_secret=os.environ.get('BITMEX_API_SECRET')
    )

    while(ws.ws.sock.connected):
      if ws.api_key:
        rows_to_insert = ws.recent_trades()
        errors = bq.client.insert_rows(bq.tbl, rows_to_insert)
        if errors != []:
          print(errors)
Exemplo n.º 5
0
def run(producer):
    logger = setup_logger()
    symbolSpot, symbolNear, symbolFar = getSymbolPair()

    #ws_spot = BitMEXWebsocket(endpoint=__ENDPOINT, symbol=symbolSpot, api_key=__API_KEY, api_secret=__API_SECRET)
    ws_near = BitMEXWebsocket(endpoint=__ENDPOINT,
                              symbol=symbolNear,
                              api_key=__API_KEY,
                              api_secret=__API_SECRET)
    ws_far = BitMEXWebsocket(endpoint=__ENDPOINT,
                             symbol=symbolFar,
                             api_key=__API_KEY,
                             api_secret=__API_SECRET)

    #prev_spot_count = 0
    prev_near_count = 0
    prev_far_count = 0

    while (ws_near.ws.sock.connected and ws_far.ws.sock.connected):
        #prev_spot_count = getRecentTrade(ws_spot, prev_spot_count, logger, producer)
        prev_near_count = getRecentTrade(ws_near, prev_near_count, logger,
                                         producer)
        prev_far_count = getRecentTrade(ws_far, prev_far_count, logger,
                                        producer)
        time.sleep(1)
Exemplo n.º 6
0
    def __init__(self, ticker):

        self.ExchangeName = "BITMEX"
        self.ticker = ticker
        self.webSocketURL = "wss://testnet.bitmex.com/realtime"
        self.instruments = ["XBTUSD"]
        self.location = "/Users/jeroenderyck/Documents/Data/CryptoPrices/"
        self.path = os.path.join(
            self.location, '%s_%s.csv' % (self.ExchangeName, self.ticker))

        if self.ValidateTicker(ticker):

            self.logger = setup_logger()

            self.ws = BitMEXWebsocket(
                endpoint="wss://testnet.bitmex.com/realtime",
                symbol=ticker,
                api_key="wwvS30igJDo6Ksxa0h2EP1Eq",
                api_secret="-DOHRIUObpSQilqyr2y18YcTRi5NWFIV95du4i8rG4VveOBI")

            #self.logger.info("Instrument data: {}".format(self.ws.get_instrument()))

        else:
            print("please take an instrument available from bitmex",
                  str(self.instruments))
Exemplo n.º 7
0
 def get(self):
     if not request.args:
         return create_error_response(400, "Query Error",
                                      'Missing Query Parameter "symbol"')
     try:
         if request.args["symbol"]:
             ws = BitMEXWebsocket(
                 endpoint="https://testnet.bitmex.com/api/v1",
                 symbol=request.args["symbol"],
                 api_key=None,
                 api_secret=None)
             trades = []
             trades = ws.recent_trades()
             for trade in trades:
                 body = MasonControls(symbol=trade["symbol"],
                                      side=trade["side"],
                                      size=trade["size"],
                                      price=trade["price"])
                 body.add_control("buckets",
                                  href=api.url_for(BucketedPriceAction) +
                                  "?{timebucket}",
                                  title="Trades in time buckets")
                 body.add_control("self",
                                  href=api.url_for(PriceAction) +
                                  "?symbol={}".format(trade["symbol"]))
             return Response(json.dumps(body), status=200, mimetype=MASON)
     except:
         print(traceback.format_exc())
         return create_error_response(400, "Query Error",
                                      "Query Parameter doesn't exist")
Exemplo n.º 8
0
    def __init__(self, apiconfpth=kfpth):

        f = open(apiconfpth, 'r')
        lines = f.readlines()
        f.close()

        apikey = lines[0].replace('\r', '').replace('\n', '')
        secretkey = lines[1].replace('\r', '').replace('\n', '')

        self.client = bitmex.bitmex(test=True,
                                    api_key=apikey,
                                    api_secret=secretkey)
        # https://www.bitmex.com/realtime
        # https://www.bitmex.com/api/v1
        self.ws = BitMEXWebsocket(
            endpoint="https://testnet.bitmex.com/realtime",
            symbol="XBTUSD",
            api_key=None,
            api_secret=None)

        self.logger = self.setup_logger()

        self.logger.info("Instrument data: %s" % self.ws.get_instrument())

        AlarmPrice.initAlarmObj(self.ws)
Exemplo n.º 9
0
    def reconnect_websocket(self):
        # 再接続が必要がチェック
        need_reconnect = False
        if self.ws is None:
            need_reconnect = True
        else:
            if self.ws.connected == False:
                self.ws.exit()
                need_reconnect = True

        # 再接続
        if need_reconnect:
            market = self.exchange.market(self.settings.symbol)
            # ストリーミング設定
            if self.testnet.use:
                self.ws = BitMEXWebsocket(
                    endpoint='wss://testnet.bitmex.com/realtime',
                    symbol=market['id'],
                    api_key=self.testnet.apiKey,
                    api_secret=self.testnet.secret)
            else:
                self.ws = BitMEXWebsocket(endpoint='wss://www.bitmex.com',
                                          symbol=market['id'],
                                          api_key=self.settings.apiKey,
                                          api_secret=self.settings.secret)
            # ネットワーク負荷の高いトピックの配信を停止
            self.ws.unsubscribe(['orderBookL2'])
Exemplo n.º 10
0
    def __init__(self):
        self.ws = BitMEXWebsocket(
            endpoint="wss://www.bitmex.com/realtime",
            symbol="XBTUSD",
            api_key='68_LZNeK1m7TEwnksVTe_7ig',
            api_secret='wKJXpjr6Y28BNDF4G97TBevkzLG0HVOurFDBn2dx42Sf_Aga')

        self.client = MongoClient('mongodb://localhost:27017/')
        self.db = self.client.main_database

        self.order_book = self.db.orderbook
        self.position = self.db.position
        self.balance = self.db.balance

        #uncomment these 3 methods to check out the db

        #to see orderbooks
        #self.check_db(self.find_all_orderbook())

        #to see position
        #self.check_db(self.find_all_positions())

        #to see balance
        #self.check_db(self.find_all_balance())

        self.__on_open()
        self.fetch_data()
Exemplo n.º 11
0
    def run(self):

        logger = self.setup_logger('WS')

        try:
            # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
            self.ws = BitMEXWebsocket(endpoint=self.bitmex_address,
                                      symbol="XBTUSD",
                                      api_key=None,
                                      api_secret=None)

            self.ws.get_instrument()

            logger.info('WS connector loaded')

            while self.ws.ws.sock.connected:
                self.get_ticker(logger)
                if self.ws.api_key:
                    self.get_funds(logger)
                self.get_orderbook(logger)
                self.get_instrument(logger)
                # self.get_trades(logger)
        except:
            logger.error('\033[91m{}\033[0m'.format(traceback.format_exc()))
        finally:
            self.running_lock.release()
            self.es_thread.join()
            logger.error('\033[91mTHIS IS THE END\033[0m')
Exemplo n.º 12
0
def initBitmexWebSocket(apiKey: str, apiSecret: str):
    """Instantiate a connection"""
    ws = BitMEXWebsocket(endpoint="wss://testnet.bitmex.com/realtime",
                         symbol="XBTUSD",
                         api_key=apiKey,
                         api_secret=apiSecret)
    ws.get_instrument()
    return ws
Exemplo n.º 13
0
def update_trades():
    ws_trades = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD",
                         api_key=None, api_secret=None)
    while (ws_trades.ws.sock.connected):
        trades=ws_trades.recent_trades()
        db.mkt.update_one({"_id":"trades"},{"$set":{"recent_trades": trades}})
        logging.info("trades done")
        sleep(5)
Exemplo n.º 14
0
 def __init__(self, api_key=None, api_secret=None, symbol="XBTUSD"):
     endpoint = "https://testnet.bitmex.com/api/v1"
     if api_key:
         endpoint = "https://www.bitmex.com/api/v1"
     self.ws = BitMEXWebsocket(endpoint=endpoint,
                               symbol=symbol,
                               api_key=api_key,
                               api_secret=api_secret)
Exemplo n.º 15
0
def update_instrument():
    ws_ins = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD",
                         api_key=None, api_secret=None)
    while (ws_ins.ws.sock.connected):
        instrument=ws_ins.get_instrument()
        db.mkt.update_one({"_id":"instrument"},{"$set":instrument})
        logging.info("instrument done")
        sleep(60)
Exemplo n.º 16
0
    def __init__(self, symbol):
        self.ctr = 0
        self.symbol = symbol
        #self.logger = self.setup_logger()

        # hoang: wbFfEOkZqut7OG8rueCPTmEsCsYHyqxakxlg1dNoZbz7EJ6w
        # hoang: ZJ7ZG0bDrem884wQkNnvv2PB

        api_key = "ZJ7ZG0bDrem884wQkNnvv2PB"  #"9FR7reF9F71NDZG_BDoMsfm9" # 8vXVw923QlDRoRtXSwvwbXlU
        api_secret = "wbFfEOkZqut7OG8rueCPTmEsCsYHyqxakxlg1dNoZbz7EJ6w"  #"TiXEEabXxJ_KX5ev_RoOnB-JVQqDdj4AAMJvRBXpPhtAKGVH" # nFZS4qiArohuyY_4J9oGBk49X2iL5LteAXCrHcHveF6j5Gwi

        # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
        self.ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1",
                                  symbol=self.symbol,
                                  api_key=api_key,
                                  api_secret=api_secret)
        self.ws.get_instrument()

        #self.logger.info("Instrument data: %s" % self.ws.get_instrument())
        self.client = bitmex.bitmex(test=False,
                                    api_key=api_key,
                                    api_secret=api_secret)
        self.last_r = None
        self.last_spread = None
        #self.clean = False

        self.tick = []
        self.cur_volatility = None
        self.act_volatility = None
        self.streak = 0
        self.prev_len = 0
        self.cur_len = 0
        self.idle = 0
        self.first = True
        self.sleep_ctr = 0
        self.general_ctr = 0

        exchange = ccxt.bitmex()
        date_N_days_ago = (
            datetime.datetime.now() -
            datetime.timedelta(hours=2)).strftime("%Y-%m-%d %H:%M:%S")
        since = time.mktime(
            datetime.datetime.strptime(date_N_days_ago,
                                       "%Y-%m-%d %H:%M:%S").timetuple()) * 1000
        df = exchange.fetch_ohlcv('ETH/USD',
                                  timeframe='1m',
                                  since=since,
                                  limit=500)
        df = pd.DataFrame(df)
        df.columns = ["Timestamp", "Open", "High", "Low", "tick", "Volume"]

        self.df = pd.DataFrame({'tick': df.tick.values.tolist()})
        #print (df.tail())
        #print (self.df.tail())

        # always fetch df using ccxt
        # check number of pos: if len(pos) > 0 : self.first = False
        logging.info("App Initiated!")
Exemplo n.º 17
0
def update_ticker():
    ws_ticker = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD",
                         api_key=None, api_secret=None)
    while (ws_ticker.ws.sock.connected):
        ws_ticker.get_instrument()
        ticker=ws_ticker.get_ticker()
        db.mkt.update_one({"_id":"ticker"},{"$set":ticker})
        logging.info("ticker done")
        sleep(5)
Exemplo n.º 18
0
    def get(self, apikey):
        acc = User.query.filter_by(api_public=apikey).first()
        if not acc:
            return create_error_response(
                404, "Account does not exist",
                "Account with api-key '{}' does not exist.".format(apikey))
        if not authorize(acc, request):
            return create_error_response(401, "Unauthorized",
                                         "No API-key or wrong API-key")

        try:
            ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                                 symbol="",
                                 api_key=apikey,
                                 api_secret=request.headers["api_secret"])

            positions = []
            parsed_positions = []
            positions = ws.positions()
            ws.exit()
            if positions:
                for position in positions:

                    parsed_position_symbol = position["symbol"]
                    parsed_position_size = position["currentQty"]
                    if position["crossMargin"] == True:
                        parsed_position_leverage = 0
                    else:
                        parsed_position_leverage = position["leverage"]
                    parsed_position_entyprice = position["avgEntryPrice"]
                    parsed_position_liquidationPrice = position[
                        "liquidationPrice"]

                    parsed_position = MasonControls(
                        symbol=parsed_position_symbol,
                        size=parsed_position_size,
                        leverage=parsed_position_leverage,
                        avgEntryPrice=parsed_position_entyprice,
                        liquidationPrice=parsed_position_liquidationPrice)
                    parsed_position.add_control(
                        "self",
                        href=api.url_for(Position,
                                         apikey=apikey,
                                         symbol=parsed_position_symbol))
                    if not position["currentQty"] == 0:
                        parsed_positions.append(parsed_position)

            body = MasonControls(items=parsed_positions)
            body.add_control_account(apikey)
            body.add_control("self", api.url_for(Positions, apikey=apikey))
            return Response(json.dumps(body), status=200, mimetype=MASON)

        except TypeError:
            return create_error_response(400, "Query Error",
                                         "Query Parameter doesn't exist")
Exemplo n.º 19
0
def run():
    logger = setup_logger()

    #symbole
    symbol = "XBTUSD"

    # Instantiating the WS will make it connect. Be sure to add an auth method. You can use login/password
    # or api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol=symbol,
                         login=None, password=None, api_key=None, api_secret=None)

    logger.info("Instrument data: %s" % ws.get_instrument())
Exemplo n.º 20
0
def run():
    logger = setup_logger()
    config = configparser.ConfigParser()
    config.read('config.ini')
    client = bitmex.bitmex(api_key=config['AUTH']['api_key'],
        api_secret=config['AUTH']['api_secret'])

    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD",
                         api_key=config['AUTH']['api_key'],
                         api_secret=config['AUTH']['api_secret'])

    # logger.info("Instrument data: %s" % ws.get_instrument())

    a1 = config['VALUES']['a1']
    a2 = config['VALUES']['a2']
    aQty = config['VALUES']['aQty']
    b1 = config['VALUES']['b1']
    b2 = config['VALUES']['b2']
    bQty = config['VALUES']['bQty']

    # Run forever
    triggered = False
    try:

        (body, response) = client.Order.Order_new(
                symbol='XBTUSD', orderQty=aQty, price="8999",
                contingencyType="OneTriggersTheOther", clOrdLinkID="Triggered").result()
        while(ws.ws.sock.connected):
            price = ws.get_ticker()
            print(price['mid'])
            if not triggered and price['mid'] > float(a1):
                (body, response) = client.Order.Order_new(
                    symbol='XBTUSD', orderQty=aQty, price=a1,
                    contingencyType="OneTriggersTheOther", clOrdLinkID="Triggered").result()
                (body, response) = client.Order.Order_new(
                    symbol='XBTUSD', orderQty=aQty, price=a2, side="Sell",
                    clOrdLinkID="Triggered").result()
                triggered = True
            elif not triggered and price['mid'] < float(b1):
                (body, response) = client.Order.Order_new(
                    symbol='XBTUSD', orderQty=bQty, price=b1, side="Sell",
                    contingencyType="OneTriggersTheOther", clOrdLinkID="Triggered").result()
                (body, response) = client.Order.Order_new(
                    symbol='XBTUSD', orderQty=bQty, price=b2,
                    clOrdLinkID="Triggered").result()
                triggered = True

            pp = pprint.PrettyPrinter(indent=4)
            sleep(1)
    except KeyboardInterrupt as e:
        print(client.Order.Order_cancelAll().result())
Exemplo n.º 21
0
    def __init__(self):
        self.logger = setup_logger()
        test = False
        self.api_key = 'kVfKITnQdJEzEC2sKYlVr9mM'
        self.api_secret = 'joccPUd5_DwOd3CDL1lSq_prKDxxM6oRQCmu7aALcw_6KWCi'
        test_url = 'https://testnet.bitmex.com/api/v1'
        product_url = 'https://www.bitmex.com/api/v1'
        if test:
            url = test_url
            self.filled_order_set = 'filled_order_set2'
            self.setting_ht = 'grid_setting_hash2'
            self.api_key = 'hDZPEs8ECXv9A1OfBysNIySo'
            self.api_secret = '_KkD8sZiG8T1rhNRqN2EvnGu9C4lJXoQHi6v4lj6eVyNxAM4'
        else:
            url = product_url
        self.cli = bitmex(test=test, api_key=self.api_key, api_secret=self.api_secret)
        self.ws = BitMEXWebsocket(endpoint=url,
                                  symbols=self.contract_names,
                                  api_key=self.api_key,
                                  api_secret=self.api_secret)
        # init redis client
        self.redis_cli = redis.Redis(host='localhost', port=6379, decode_responses=True)

        # # threading lock
        # self._value_lock = threading.Lock()

        self.logger.info('从redis同步参数')

        self.price_dist = int(self.redis_cli.hget(self.setting_ht, 'price_dist'))
        self.profit_dist = int(self.redis_cli.hget(self.setting_ht, 'profit_dist'))
        self.init_position = int(self.redis_cli.hget(self.setting_ht, 'init_position'))
        self.final_position = int(self.redis_cli.hget(self.setting_ht, 'final_position'))
        self.unit_amount = int(self.redis_cli.hget(self.setting_ht, 'unit_amount'))
        self.unfilled_buy_list = 'unfilled_buy_list'
        self.unfilled_sell_list = 'unfilled_sell_list'

        self.logger.info('同步委托列表')
        self.redis_cli.ltrim(self.unfilled_buy_list, 1, 0)
        self.redis_cli.ltrim(self.unfilled_sell_list, 1, 0)

        for o in self.get_unfilled_orders({'orderQty': self.unit_amount, 'ordStatus': 'New'}):
            redis_item = {'orderID': o['orderID'],
                          'side': o['side'],
                          'price': o['price'],
                          'orderQty': o['orderQty']
                          }
            if o['side'] == 'Buy':
                self.redis_insert_buy(self.unfilled_buy_list, redis_item)
            else:
                self.redis_insert_sell(self.unfilled_sell_list, redis_item)
        self.logger.info('同步完毕')
Exemplo n.º 22
0
    def __init__(self, symbol: str = "XBTUSD"):
        self._symbol = symbol

        self._rest_api = bitmex.bitmex(test=True,
                                       api_key=API_KEY,
                                       api_secret=API_SECRET)
        self._ws_api = BitMEXWebsocket(
            endpoint="https://testnet.bitmex.com/api/v1",
            symbol=self._symbol,
            api_key=API_KEY,
            api_secret=API_SECRET)

        self._static_data = pd.DataFrame()
        self._data = []
Exemplo n.º 23
0
def run(mexbot):

    mexbot.logger.debug("Started Ticker thread")

    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                         symbol=mexbot.symbol,
                         api_key=mexbot.config.get("api_key"),
                         api_secret=mexbot.config.get("api_secret"))

    mexbot.logger.debug("Instrument data: %s" % ws.get_instrument())

    # Run forever
    while (ws.ws.sock.connected):
        mexbot.update_ticker(ws.get_ticker())
    mexbot.logger.error("Websocket disconnected")
 def connect_to_api(self):
     # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
     ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                          symbol=symbol,
                          api_key=None,
                          api_secret=None)
     print(ws)
Exemplo n.º 25
0
 def __init__(self,
              symbol,
              key,
              kl1m_length=120,
              kl5m_length=60,
              kl1h_length=24):
     self.symbol = symbol
     self.api_key = key[0]
     self.secret_key = key[1]
     # 按交易所websocket使用方法初始化ws
     self.__ws = BitMEXWebsocket(endpoint="wss://www.bitmex.com/realtime",
                                 symbol=self.symbol,
                                 api_key=key[0],
                                 api_secret=key[1])
     self.kl1m = []
     self.__kl1m_length = kl1m_length
     self.kl5m = []
     self.__kl5m_length = kl5m_length
     self.kl1h = []
     self.__kl1h_length = kl1h_length
     # 按当前时间使用rest api初始化各k线
     self.__init_kline()
     # 使用websocket实时更新各k线
     th_refresh = Thread(target=self.__refresh_kline, args=())
     th_refresh.start()
Exemplo n.º 26
0
def login():
    global ws
    global client
    global apikey
    global secretapikey
    global pair

    choice = str(
        input('''
Login:
1. Enter Login Details
2. Remember Previous Login Details
3. Exit

'''))
    if choice == '1':
        apikey = str(input("Enter your API Key: "))
        secretapikey = str(input("Enter your Secret API Key: "))
        ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                             symbol=pair,
                             api_key=apikey,
                             api_secret=secretapikey)
        client = bitmex(test=True, api_key=apikey, api_secret=secretapikey)
        print('Login Successful \n')

        mainmenu()

    elif choice == '2':
        apikey = '1Bk8AeOWOjO2DCUjFSOFQK11'
        secretapikey = 'crGr--X10duyKqUKKtfgfS5E0FrgsF2jz439eSrHjlkVMgS3'
        connect()
        mainmenu()

    elif choice == '3':
        exit()
Exemplo n.º 27
0
def run(mexbot):
    print("in thread")
    logger = setup_logger()

    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                         symbol=mexbot.symbol,
                         api_key=None,
                         api_secret=None)

    logger.info("Instrument data: %s" % ws.get_instrument())

    # Run forever
    while (ws.ws.sock.connected):
        # logger.info("Ticker: %s" % ws.get_ticker())
        mexbot.updateTicker(ws.get_ticker())
Exemplo n.º 28
0
    def __init__(self, value_pair):
        global Flag_of_begining
        Flag_of_begining = False
        api_key = '6AnZMBW9F-a2Yf1cH28v_l8j'
        self.value_pair = value_pair
        self.Flag_of_begining = False
        secret_key = 'JsFkkeg2AMQziEsWioNmQzGm9LDNS5310NkXAT1FRxZdpu6k'
        self.ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",
                                  symbol=f'{self.value_pair}',
                                  api_key=api_key,
                                  api_secret=secret_key)
        self.ws.get_instrument()
        self.counter = 0
        self.shoulder = 50
        self.start_money = 10

        pass
def bitmex_funding_rate_trigger(ticker, sma_period, anomaly_threshold_percent,
                                telegram_token, telegram_chat_id,
                                bearish_bias_msg, bullish_bias_msg):
    ws = BitMEXWebsocket(endpoint=f'wss://www.bitmex.com/realtime',
                         symbol=f'{ticker}')
    rolling_data_set = []
    i = 0
    messaging = 0
    while ws.ws.sock.connected:
        snapshot = ws.get_instrument()
        data = {
            'fundingRate': snapshot['fundingRate'],
            'fundingTimestamp': snapshot['fundingTimestamp'],
            'fundingInterval': snapshot['fundingInterval'],
            'indicativeFundingRate': snapshot['indicativeFundingRate'],
            'symbol': snapshot['symbol']
        }

        if i < sma_period:
            rolling_data_set.append(data['indicativeFundingRate'])
            i = i + 1
        else:
            diff = data['indicativeFundingRate'] - numpy.mean(rolling_data_set)
            # check if rolling average has a negative spike
            if diff < 0 and abs(diff / numpy.mean(rolling_data_set)
                                ) > anomaly_threshold_percent / 100:
                # Send Telegram message based Rolling average
                msg = f'Current funding rate: {data["indicativeFundingRate"]}\nMean funding rate: {numpy.mean(rolling_data_set)}\n' \
                      f'Spike %: {abs(diff / numpy.mean(rolling_data_set)) * 100} below average\n<b>{bullish_bias_msg}</b> '
                if messaging == 1:
                    send_telegram(f'{telegram_token}', telegram_chat_id, msg)
                    messaging = 0
            # check if rolling average has a positive spike
            elif diff > 0 and abs(diff / numpy.mean(rolling_data_set)
                                  ) > anomaly_threshold_percent / 100:
                # Send Telegram message based Rolling average
                msg = f'Current funding rate: {data["indicativeFundingRate"]}\nMean funding rate: {numpy.mean(rolling_data_set)}\n' \
                      f'Spike %: {abs(diff / numpy.mean(rolling_data_set)) * 100} above average\n<b>{bearish_bias_msg}</b> '
                if messaging == 1:
                    send_telegram(f'{telegram_token}', telegram_chat_id, msg)
                    messaging = 0
            else:
                # Rolling data set. Discarding the oldest value and adding new value.
                rolling_data_set = rolling_data_set[1:]
                rolling_data_set.append(data['indicativeFundingRate'])
                messaging = 1
Exemplo n.º 30
0
    def test_on_subscribe_called_on_sub_error_message(self, mocker):
        """
        on_message should call on_subscribe when subscription error is received
        """
        error = mocker.patch('bitmex_websocket.BitMEXWebsocket.on_error')
        socket = BitMEXWebsocket()
        message = {
            "status": 400,
            "error": "Unknown table: instrument_",
            "meta": {},
            "request": {
                "op": "subscribe",
                "args": ["instrument_:XBTH17"]
            }
        }

        socket.on_message({}, json.dumps(message))
        error.assert_called_with({}, "Unknown table: instrument_")
Exemplo n.º 31
0
def run():
    logger = setup_logger()

    # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD",
                         api_key=None, api_secret=None)

    logger.info("Instrument data: %s" % ws.get_instrument())

    # Run forever
    while(ws.ws.sock.connected):
        logger.info("Ticker: %s" % ws.get_ticker())
        if ws.config['api_key']:
            logger.info("Funds: %s" % ws.funds())
        logger.info("Market Depth: %s" % ws.market_depth())
        logger.info("Recent Trades: %s\n\n" % ws.recent_trades())
        sleep(10)
Exemplo n.º 32
0
def run():
    logger = setup_logger()

    # Instantiating the WS will make it connect. Be sure to add an auth method. You can use login/password
    # or api_key/api_secret.
    ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBT24H",
                         login="******", password="******", api_key=None, api_secret=None)

    logger.info("Instrument data: %s" % ws.get_instrument())

    # Run forever
    while(ws.ws.sock.connected):
        logger.info("Ticker: %s" % ws.get_ticker())
        logger.info("Funds: %s" % ws.funds())
        logger.info("Market Depth: %s" % ws.market_depth())
        logger.info("Recent Trades: %s\n\n" % ws.recent_trades())
        sleep(10)