DEV Community

Cover image for Bybit's Pybit: How to subscribe to kline stream via WebSocket
Kyle Foo
Kyle Foo

Posted on

Bybit's Pybit: How to subscribe to kline stream via WebSocket

As a beginner crypto trader, I often look at automating my trades so I can sleep at ease. Bybit is one of the exchanges that offers open-sourced API, but its documentation can be outdated at times. Hence, I'm learning via trial and error and finally figured out how to use its WebSocket API.

Bybit's python library has been released with a new version. As of the time of writing, v2.1.0 of Pybit is available for download.

Now, let's look at how to consume Pybit WebSocket API to stream realtime kline data:

from datetime import date, datetime, timedelta
import dateparser
import time
import hmac
import json
from pybit import usdt_perpetual

# Apply for API keys and secrets at

# Initialize web socket connection instance
ws = usdt_perpetual.WebSocket(

# Initialize http connection instance
session = usdt_perpetual.HTTP(endpoint="", api_key=api_key, api_secret=api_secret)

# Define a target price that you want to enter your position
target_price = 40000

# handle_position is a callback that will be triggered on every new websocket event (push frequency can be 1-60s)
def handle_position(message):
    data = message["data"][0]
    if data:
        # check for target_price for entering position, if confirm=True, the data is the final tick for the interval. Otherwise, it is a snapshot.
        if data['close'] >= target_price and data['confirm'] == True:
            print("Buy Order | {} | {}".format(data['close'], time.strftime("%m/%d/%y, %H:%M:%S", time.localtime())))
            tp = target_price + (target_price * 0.05)
            sl = target_price - (target_price * 0.05)
            # Buy at market price to enter Long position
            ret = session.place_active_order(
                qty=0.001, # amount to buy
            print("Buy Order Id | {}".format(ret["result"]["order_id"], time.strftime("%m/%d/%y, %H:%M:%S", time.localtime())))

# start kline stream here and pass in callback, symbol and desired kline interval
ws.kline_stream(callback=handle_position, symbol="BTCUSDT", interval="5")

Enter fullscreen mode Exit fullscreen mode

Notes: Do request for free credits on so that you can have imaginary $$ to test your algorithm. Request can be done via live chat support.

Reference to official Pybit's WebSocket example:

Top comments (0)