How to receive real time data through Bitmex Websocket Api on python?

501 views Asked by At

I understand that I can use "while true" and call the 'get_ticker' method to get the last price of the product, but this drives from python instead of the market itself. I was wondering if there is a way to get the last price as BitMEX's website changes. Thanks

1

There are 1 answers

0
Fedor Soldatkin On

Check my bitmex project, there is solution of your problem: bitmex-supervisor

Essential code fragments:

In __init__():

self.last_price = 0
self._min_price = float('inf')
self._max_price = -1

self.initial_price = float('nan')

self.tracking = False

Methods:

@property
def min_price(self):
    return self._min_price

@min_price.setter
def min_price(self, value):
    if value < self.initial_price:
        self.callback_price_decreased()  # here you can do some stuff
    self._min_price = value

@property
def max_price(self):
    return self._max_price

@max_price.setter
def max_price(self, value):
    if value > self.initial_price:
        self.callback_price_increased()  # here you can do some stuff
    self._max_price = value

def stop_trailing(self):
    self.tracking = False

def start_trailing(self, initial_price: float):
    """
    :param initial_price: the price after reaching which order will be moving
    """

    self._max_price = -1
    self._min_price = float('inf')
    self.initial_price = initial_price
    self.tracking = True

In __on_message():

instrument = self.get_instrument(symbol=self.order.symbol)
    if instrument is not None:
        self.last_price = instrument['lastPrice']
        if self.tracking:
            if self.last_price > self.max_price and self.order.side == 'Sell':
                self.max_price = self.last_price
            elif self.last_price < self.min_price and self.order.side == 'Buy':
                self.min_price = self.last_price