I am trying to implement a websocket client that connects to the popular crypto exchange FTX. I have simplified my problem to the following example code below:
import asyncio import websockets import json async def consumer() -> None: async with websockets.connect("wss://ftx.com/ws/") as websocket: await websocket.send(json.dumps({ "op":"subscribe", "channel":"trades", "market":"BTC-PERP" })) totalVol = 0 async for message in websocket: message = json.loads(message) # print("message: " + str(message)) if message["type"]=="update": result = message["data"] for record in result: totalVol += float(record["size"]) print("totalVol: " + str(totalVol)) asyncio.run(consumer())
The output of the program overall is as expected, but with one major problem: the cumulative trading volume that gets output to the console is WAY too low. It should be about 1,000x-10,000x larger. I can show this more rigorously by building candles from the webscoekt data and comparing to the same resolution from the historical API. But it is pretty easy to convince yourself of this if you just go visit the ftx website, and see that the 1-minute trading volume for the BTC-PERP market tends to be in the millions each minute, whereas this is printing out volumes in the hundreds each minute.
I did a little bit of research, and the best answers seemed to be that the problem is not using an async implementation of the message handling. But I believe the above implementation is asyncronous.
Could someone please help me understand why I am not seeing the expected behavior, and how I might fix it?
Thank You,
Paul
Advertisement
Answer
If I understand the result from the server correctly, you should be multiplying “size” with “price”:
import asyncio import websockets import json async def consumer() -> None: async with websockets.connect("wss://ftx.com/ws/") as websocket: await websocket.send( json.dumps( {"op": "subscribe", "channel": "trades", "market": "BTC-PERP"} ) ) totalVol = 0 async for message in websocket: message = json.loads(message) if message["type"] == "update": result = message["data"] for record in result: totalVol += record["size"] * record["price"] print("totalVol:", totalVol) asyncio.run(consumer())
Prints more “realistic” values:
... totalVol: 1420555.7282999994 totalVol: 1436185.2012999994 totalVol: 1436278.1292999994 totalVol: 1441894.4652999996 ...