python websocket fetch returns empty object


I’m trying to use the pybit package ( on a crypto exchange, but when i try to fetch the data from the websocket, all I get is an empty object as a response.

import pybit

endpoint_public = 'wss://'

subs = [

ws_unauth = WebSocket(endpoint_public, subscriptions=subs)


the output is this

Asked By: sambess



EDIT: 2022.09.19

It seems they changed code in module and examples in documentation are different. They don’t use fetch() but they assign subscription to functions – handlers – and websocket runs own (hidden) loop to fetch data and execute assigned function.

I found three problems:

First: code works for me if I use endpoint realtime instead of realtime_public – I found it in somewhere in ByBit API documentation (not in documentation for Python module)

Second: there is no 'last_price.BTCUSD' in documentation – and this generate errors when I try it with endpoint realtime – and other subscriptions don’t work.

Third: first fetch may not give result and it may need to sleep() short time before first fetch. Normally code should run in some loop and get data every few (milli)seconds and then it makes no problem. You could also use if to run some code only if you get data.

import pybit
import time

endpoint_public = 'wss://'

subs = [
#    'last_price.BTCUSD'

ws_unauth = pybit.WebSocket(endpoint_public, subscriptions=subs)

#print(ws_unauth.fetch('last_price.BTCUSD'))    # doesn't work with `realtime_public`; generate error with `realtime`  
print(ws_unauth.fetch('orderBookL2_25.BTCUSD')) # doesn't work with `realtime_public`; works with `realtime`


  {'price': '40702.50', 'symbol': 'BTCUSD', 'id': 407025000, 'side': 'Buy', 'size': 350009}, 
  {'price': '40703.00', 'symbol': 'BTCUSD', 'id': 407030000, 'side': 'Buy', 'size': 10069}, 
  {'price': '40705.00', 'symbol': 'BTCUSD', 'id': 407050000, 'side': 'Buy', 'size': 28}, 
  # ...


ByBit API Documentation shows also examples for Public Topic.

They use:

  • realtime instead of realtime_public,
  • loop to fetch data periodically,
  • if data to skip empty response.
from pybit import WebSocket
subs = [
ws = WebSocket(
while True:
    data = ws.fetch(subs[0])
    if data:

ByBit API Documentation shows also examples for Private Topic.

They also use:

  • realtime instead of realtime_public ( + api_key, api_secret),
  • loop to fetch data periodically,
  • if data to skip empty response.

For test they use stream-testnet but in real code it should use stream.

Answered By: furas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.