Aggregate the levels of the orderbook

710 Views Asked by At

How can I aggregate the levels of the orderbook? Now it gets streamed every 0.05 tick but I need to stream this every 0.50 interval of price.

How can I unite the various levels on the orderbook?

This is the code:

from time import sleep
from pybit import usdt_perpetual
    
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):
print(msg)

ws_linear.orderbook_25_stream(
    handle_message, "ETHUSDT"
)

while True:
sleep(1)

Thank you

1

There are 1 best solutions below

0
On

Here you have usable orderbook if it helps. Note: this code is not the cleanest, but it gets the job done.

import hmac
import json
import threading
import time
import websocket

ws_url = "wss://stream.bybit.com/realtime_public"

api_key = ""
api_secret = ""

order_book = []
orderbook = []
orderbook_size = []
orderbook_array_length = 1000
data = []

# Generate expires.
expires = int((time.time() + 1) * 1000)

# Generate signature.
signature = str(hmac.new(
    bytes(api_secret, "utf-8"),
    bytes(f"GET/realtime{expires}", "utf-8"), digestmod="sha256"
).hexdigest())

param = "api_key={api_key}&expires={expires}&signature={signature}".format(
    api_key=api_key,
    expires=expires,
    signature=signature
)

url = ws_url + "?" + param


def on_message(ws, message):
    global orderbook
    global orderbook_size
    message = json.loads(message)
    for i in range(0, max(len(message['data']['update']), len(message['data']['insert']), len(message['data']['delete'])), 1):
        if len(message['data']['update']) != 0 and i < len(message['data']['update']):
            orderbook_size.append((message['data']['update'][i]['price'], message['data']['update'][i]['size'], message['data']['update'][i]['symbol']))
            if len(orderbook_size) > orderbook_array_length:
                del (orderbook_size[0])

            data_append = [(message['data']['update'][i]['price'], message['data']['update'][i]['side'], message['data']['update'][i]['symbol'])]
            if message['data']['update'][i]['side'] == 'Buy':
                data_append_opposite = [(message['data']['update'][i]['price'], 'Sell', message['data']['update'][i]['symbol'])]
            else:
                data_append_opposite = [(message['data']['update'][i]['price'], 'Buy', message['data']['update'][i]['symbol'])]

            if data_append_opposite[0] in orderbook:
                orderbook.remove(data_append_opposite[0])

            if data_append[0] not in orderbook:
                orderbook.append((message['data']['update'][i]['price'], message['data']['update'][i]['side'], message['data']['update'][i]['symbol']))
                orderbook.sort(key=lambda x: x[0])


        if len(message['data']['insert']) != 0 and i < len(message['data']['insert']):
            orderbook_size.append((message['data']['insert'][i]['price'], message['data']['insert'][i]['size'], message['data']['insert'][i]['symbol']))
            if len(orderbook_size) > orderbook_array_length:
                del (orderbook_size[0])

            orderbook.append((message['data']['insert'][i]['price'], message['data']['insert'][i]['side'], message['data']['insert'][i]['symbol']))
            orderbook.sort(key=lambda x: x[0])


        if len(message['data']['delete']) != 0 and i < len(message['data']['delete']):
            data_remove = [(message['data']['delete'][i]['price'], message['data']['delete'][i]['side'], message['data']['delete'][i]['symbol'])]
            if data_remove[0] in orderbook:
                orderbook.remove(data_remove[0])


def on_error(ws, error):
    print(f"Error: {error}")


def on_close(ws):
    print(f"Connection close")


def on_open(ws):
    ws.send('{"op": "subscribe", "args": ["orderBookL2_25.BTCUSDT"]}')
    print("Opened connection")


ws = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close)
wst = threading.Thread(target=ws.run_forever)
wst.daemon = True
wst.start()

while True:
    time.sleep(1)
    order_book = []
    try:
        for i in range(0, len(orderbook), 1):
            # entire orderbook
            for s in range(-1,len(orderbook_size)* -1, -1):
                if orderbook[i][0] == orderbook_size[s][0]:
                    order_book.append((orderbook[i][0], orderbook[i][1], orderbook_size[s][1]))
                    break

            # orderbook with depth of 1
            if orderbook[i - 1][1] == 'Buy' and orderbook[i][1] == 'Buy' and orderbook[i + 1][1] == 'Sell' and orderbook[i + 2][1] == 'Sell':
                for r in range(i, len(orderbook), 1):
                    if len(orderbook) > r > i+25:
                        del (orderbook[r])
                    if r >= len(orderbook):
                        break
                for r in range(i, 0, -1):
                    if 0 < r < i-25:
                        del (orderbook[r])
                    if r >= len(orderbook):
                        break

                for s in range(-1,len(orderbook_size)* -1, -1):
                    if orderbook[i][0] == orderbook_size[s][0]:
                        data.append((orderbook[i][0], orderbook[i][1], orderbook_size[s][1]))
                        break
                for s in range(-1,len(orderbook_size)* -1, -1):
                    if orderbook[i+1][0] == orderbook_size[s][0]:
                        data.append((orderbook[i + 1][0], orderbook[i + 1][1], orderbook_size[s][1]))
                        break
                print(data)
                data = []
        print(order_book)
    except Exception as error:
        print(error)