Incorrect information from the websocket

I want to manage local orderbook with manage_local_order_book.py.
This file is v2 library. I edited for v3 library. This work good.
But I am getting wrong information from websocket after a while.
I modified the file to prove it.
Below are the results

Best prices → bid:[‘30951.29000000’, ‘16.01986000’] , ask:[‘30951.30000000’, ‘0.31950000’]
Best prices → bid:[‘30952.15000000’, ‘14.05981000’] , ask:[‘30952.16000000’, ‘0.05100000’]
Best prices → bid:[‘30952.15000000’, ‘14.18427000’] , ask:[‘30952.16000000’, ‘0.04932000’]
Best prices → bid:[‘30953.39000000’, ‘14.16773000’] , ask:[‘30953.40000000’, ‘0.02977000’]

[‘145000.00000000’, ‘1.00500100’]

{‘e’: ‘depthUpdate’, ‘E’: 1688461906237, ‘s’: ‘BTCUSDT’, ‘U’: 37721178376, ‘u’: 37721178387, ‘b’: [[‘30953.39000000’, ‘13.73832000’], [‘30949.93000000’, ‘0.62491000’], [‘30943.57000000’, ‘0.07200000’], [‘30940.28000000’, ‘0.00000000’], [‘30940.21000000’, ‘0.00000000’]], ‘a’: [[‘30953.40000000’, ‘0.02689000’], [‘30953.44000000’, ‘0.00100000’], [‘30954.73000000’, ‘0.00000000’], [‘30954.90000000’, ‘0.04000000’], [‘30955.16000000’, ‘0.00000000’], [‘145000.00000000’, ‘1.00500100’]]}

Best prices → bid:[‘30953.39000000’, ‘13.73832000’] , ask:[‘145000.00000000’, ‘1.00500100’]
Best prices → bid:[‘30953.99000000’, ‘17.18252000’] , ask:[‘145000.00000000’, ‘1.00500100’]
Best prices → bid:[‘30955.98000000’, ‘11.28332000’] , ask:[‘145000.00000000’, ‘1.00500100’]

How can I fix it?

:::::::Source Code::::::::
“”"
Manages a local order book and prints out its best prices.
Based on Binance API Documentation
Instructions:
** 1. Have binance-connector installed**
** 2. Define symbol in this file and adjust other fields if needed**
** 3. python manage_local_order_book.py**
“”"

from binance.spot import Spot as Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
from binance.lib.utils import config_logging
import os
import logging
import json
import asyncio
from Piton.Kaynak.Baglantı.Bin.Calculate_Procces import Calculate_Time
from aioconsole import ainput

config_logging(logging, logging.INFO)

symbol = ‘BTCUSDT’ # Example: BNBUSDT

# base_url = ‘https://testnet.binance.vision
# stream_url = ‘wss://testnet.binance.vision/ws’

base_url = “https://api.binance.com
stream_url = “wss://stream.binance.com:9443”

order_book = {
** “lastUpdateId”: 0,**
** “bids”: ,**
** “asks”: **
}
Degisik=0
def message_handler(_,Veri):
** “”“**
** Syncs local order book with depthUpdate message’s u (Final update ID in event) and U (First update ID in event).**
** If synced, then the message will be processed.**
** “””**


** message=json.loads(Veri)**
** #print(message)**
** global order_book**
** global Degisik**
** if “depthUpdate” in json.dumps(message):**
** Problem=0**
** last_update_id = order_book[‘lastUpdateId’]**

** # logging.info(‘LastUpdateId:’ + str(last_update_id))**
** # logging.info(‘Message U:’ + str(message[‘U’]) + ’ u:’ + str(message[‘u’]))**

** if message[‘u’] <= last_update_id:**
** return # Not an update, wait for next message**
** if message[‘U’] <= last_update_id + 1 <= message[‘u’]: # U <= lastUpdateId+1 AND u >= lastUpdateId+1.**
** order_book[‘lastUpdateId’] = message[‘u’]**
** process_updates(message)**
** else:**
** logging.info(‘Out of sync, re-syncing…’)**
** order_book = get_snapshot()**
** #print(order_book)**
** if Degisik==1:**
** print(message)**
** Degisik=0**
client = Client(base_url=base_url)
ws_client = SpotWebsocketStreamClient(stream_url=stream_url,on_message=message_handler)

def get_snapshot():
** “”“**
** Retrieve order book**
** “””**
** return client.depth(symbol, limit=1000)**

def manage_order_book(side, update):
** “”“**
** Updates local order book’s bid or ask lists based on the received update ([price, quantity])**
** “””**


** price, quantity = update**

** # price exists: remove or update local order**
** for i in range(0, len(order_book[side])):**
** if price == order_book[side][i][0]:**
** # quantity is 0: remove**
** if float(quantity) == 0:**
** order_book[side].pop(i)**
** return**
** else:**
** # quantity is not 0: update the order with new quantity**
** order_book[side][i] = update**
** return**

** # price not found: add new order**
** if float(quantity) != 0:**
** order_book[side].append(update)**
** if side == ‘asks’:**
** order_book[side] = sorted(order_book[side]) # asks prices in ascendant order**
** else:**
** order_book[side] = sorted(order_book[side], reverse=True) # bids prices in descendant order**

** #maintain side depth <= 1000**
** if len(order_book[side]) > 1000:**
** order_book[side].pop(len(order_book[side]) - 1)**

def process_updates(message):
** “”“**
** Updates bid and ask orders in the local order book.**
** “””**
** global Degisik**
** for update in message[‘b’]:**
** if float(update[0])<10000:**
** print(update)**
** Degisik=1**
** if float(update[0])>40000:**
** print(update)**
** Degisik=1**
** manage_order_book(‘bids’, update)**

** for update in message[‘a’]:**
** if float(update[0])<10000:**
** print(update)**
** Degisik=1**
** if float(update[0])>40000:**
** print(update)**
** Degisik=1**
** manage_order_book(‘asks’, update)**
** return**

** # logging.info(“Condition ‘U’ <= last_update_id + 1 <= ‘u’ matched! Process diff update”)**

async def listen_ws():
** “”“**
** Listens to the ws to get the updates messages.**
** “””**

** ws_client.diff_book_depth(**
** symbol=symbol.lower(),**
** id=1,**
** speed=100**
** )**

async def get_best_price():
** “”“**
** Gets best available prices (for bid and ask) every second**
** “””**

** while True:**
** if order_book.get(‘lastUpdateId’) > 0:**
** pass**
** print(f’Best prices → bid:{order_book[“bids”][0]} , ask:{order_book[“asks”][0]}')**
** await asyncio.sleep(1)**

async def GirisBekle():
** while True:**
** line=await ainput(“Birşeyler”)**
** if line==“a”:**
** print(order_book[“asks”])**
** print(order_book[‘bids’])**

def main():
** loop = asyncio.get_event_loop()**
** loop.run_until_complete(asyncio.gather(listen_ws(), get_best_price(),GirisBekle()))**
** loop.close()**

main()

I found the source of the problem.
The problem is not in the websocket in the sort step.

Here is the correct solution for those who use the original library.

def manage_order_book(side, update):
“”"
Updates local order book’s bid or ask lists based on the received update ([price, quantity])
“”"

price, quantity = update

# price exists: remove or update local order
for i in range(0, len(order_book[side])):
    if price == order_book[side][i][0]:
        # quantity is 0: remove
        if float(quantity) == 0:
            order_book[side].pop(i)
            return
        else:
            # quantity is not 0: update the order with new quantity
            order_book[side][i] = update
            return

# price not found: add new order
if float(quantity) != 0:
    order_book[side].append(update)
    if side == 'asks':
        order_book[side] = sorted(order_book[side],key=lambda i:float(i[0]))  # asks prices in ascendant order
    else:
        order_book[side] = sorted(order_book[side],key=lambda i:float(i[0]), reverse=True)  # bids prices in descendant order    

    #maintain side depth <= 1000
    if len(order_book[side]) > 1000:
        order_book[side].pop(len(order_book[side]) - 1)

:+1: