How to build a simple Websocket in Python for ByBit and fetch the values in variables?

4.3k views Asked by At

First of all, I'm not a programmer, but a trader. Years ago I had some java training at school, so I understand the code and can build some little thing by copy&paste.

I managed to get data from the websocket in a Python script.

I need a small favour. My question: How can I put two values (price and symbol) out of the websocket data in variabel price and variable symbol?

example: variable price: 30000 variable symbol: BTCUSDT

#####################################################
from BybitWebsocket import BybitWebsocket
import logging
from time import sleep

def setup_logger():
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)  # Change this to DEBUG if you want a lot more info
    ch = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

 
if __name__ == "__main__":
    logger = setup_logger()
  
    ws_public = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                         api_key="apikey", api_secret="apisecret"
                        )
    
    ws_public.subscribe_orderBookL2("BTCUSD")

    while(1):
        logger.info(ws_public.get_data("orderBookL2_25.BTCUSD"))

        sleep(1)

#####################################################
2

There are 2 answers

0
Mr.Framon On

As @Alex B pointed out, you can implement this using the Pybit library:

from time import sleep
from pybit import usdt_perpetual
ws_linear = usdt_perpetual.WebSocket(
    test=True,
    ping_interval=30,  # the default is 30
    ping_timeout=10,  # the default is 10
    domain="bybit"  # the default is "bybit"
)
def handle_message(msg):
    print(msg)
# To subscribe to multiple symbols,
# pass a list: ["BTCUSDT", "ETHUSDT"]
# pass an interval
ws_linear.kline_stream(
    handle_message, "DOTUSDT", "D"
)
while True:
    sleep(1)

Conclusion:

{
    "topic": "candle.1.BTCUSDT",
    "data": [
        {
            "start": 1655956380,
            "end": 1655956440,
            "period": "1",
            "open": 20261,
            "close": 20257.5,
            "high": 20261,
            "low": 20256,
            "volume": "25.396",
            "turnover": "514491.9815",
            "confirm": False,
            "cross_seq": 13135807020,
            "timestamp": 1655956431377798
        }
    ],
    "timestamp_e6": 1655956431377798
}

Let's slightly transform the previous code by adding code to the handle_message() function to display the information we need in real time

from time import sleep
from pybit import usdt_perpetual

symbol_list = ["BTCUSDT", "ETHUSDT"]

ws_linear = usdt_perpetual.WebSocket(
    test=False,
    ping_interval=30,  # the default is 30
    ping_timeout=10,  # the default is 10
    domain="bybit"  # the default is "bybit"
)
def handle_message(msg):
    data = msg['data'][0]
    symbol = msg['topic'][9:]
    price = data['close']
    print(f"Symbol: {symbol}   Price: {price}")


# pass an interval
ws_linear.kline_stream(
    handle_message, symbol_list, "5"
)
while True:
    sleep(1)

Conclusion:

Symbol: BTCUSDT   Price: 16377.5
Symbol: ETHUSDT   Price: 1158.05
Symbol: ETHUSDT   Price: 1158
Symbol: BTCUSDT   Price: 16377.5
Symbol: ETHUSDT   Price: 1158
Symbol: BTCUSDT   Price: 16377.5
Symbol: BTCUSDT   Price: 16377.5

Thanks to this code, you get real-time information

2
Alex B On

I've tried to figure out your code but I'm afraid it makes no sense. Below is a very simple alternative way to achieve what you want using CCXT library. I recommend you use CCXT as it will make your life a lot easier as it's a cross exchange uniform library with a lot of documentation and support on SO.

import ccxt

exchange = ccxt.bybit()

markets = exchange.fetchMarkets()

symbol = 'BTC/USDT:USDT'
order_book = exchange.fetchOrderBook(symbol)
symbol = order_book['symbol']
best_bid = order_book['bids'][0][0]
best_ask = order_book['asks'][0][0]

print(f'{symbol} {best_bid} / {best_ask}')