I connected to the websocket, and the data response in the callback function handle_message
. I wish to insert all the data to influxdb using write_api.write()
, since I need with InfluxClient()
to wrap the whole CRUD function, I wrote like this:
from time import sleep
from pybit import usdt_perpetual
from dataclasses import dataclass
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
@dataclass
class Trade:
tick_direction: str
side: float
is_block_trade: str
price: float
size: float
timestamp: int
ws_linear = usdt_perpetual.WebSocket(
test=False,
ping_interval=30,
ping_timeout=10,
domain="bybit"
)
with InfluxDBClient(
url="http://localhost:8086",
token="fake_token_id",
org="organization") as client:
write_api = client.write_api(write_options=SYNCHRONOUS)
def handle_message(msg: dict) -> None:
for data in msg["data"]:
trade = Trade(data["tick_direction"], data["side"], data["is_block_trade"], float(data["price"]),
float(data["size"]), data["timestamp"])
write_api.write(bucket="test5",
record=trade,
record_measurement_name="tradeBTCUSDT",
record_time_key="timestamp",
record_tag_keys=["tick_direction", "side", "is_block_trade"],
record_field_keys=["price", "size"])
ws_linear.trade_stream(
handle_message, "BTCUSDT"
)
while True:
sleep(1)
I think it is messy that I wrap handle_message
by with InfluxClient
, how can I improve it and the overall structure of the program?