1

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)

#####################################################
Osman
  • 81
  • 2
  • 7
  • 1
    Can you edit your question so the code block is propertly formated in the body of question. [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). – Alex B Jun 09 '22 at 23:10

2 Answers2

2

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

Mr.Framon
  • 21
  • 5
1

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}')
Alex B
  • 1,092
  • 1
  • 14
  • 39
  • Thnx! I'll look into ccxt. I didn't know this. – Osman Jun 10 '22 at 13:55
  • @Osman I've looked a bit more into the `BybitWebsocket Adapter` library that you are trying to use and wouldn't recommend using it as it's 3+ years old and I'm not sure it even works anymore. Try CCXT as it's the easiest to use with lots of support or alternatively you can try Pybit which is a library specifically designed for python and bybit. https://pypi.org/project/pybit/ – Alex B Jun 10 '22 at 15:07