add data classes for ticker message

This commit is contained in:
null 2024-03-01 14:40:04 +01:00
parent 5090972b73
commit 962c84d89f
3 changed files with 59 additions and 2 deletions

14
app.py
View File

@ -4,6 +4,7 @@ import json
from rethinkdb import RethinkDB
from pybit.unified_trading import WebSocket
from time import sleep
from messages.TickerData import Message,TickerData
r = RethinkDB()
@ -34,7 +35,10 @@ def fetch_symbols():
return []
def handle_message(message):
print(message)
msg = Message.from_json(message)
if (isinstance(msg.data, TickerData)):
print(msg.data)
def watch_symbols_table():
feed = r.table(TABLE_NAME).changes().run(rdb_conn)
@ -52,7 +56,7 @@ def subscribe_to_symbol(symbol):
callback=handle_message
)
if __name__ == "__main__":
def main():
for symbol in fetch_symbols():
subscribe_to_symbol(symbol)
@ -60,3 +64,9 @@ if __name__ == "__main__":
while True:
sleep(1)
if __name__ == "__main__":
main()

47
messages/TickerData.py Normal file
View File

@ -0,0 +1,47 @@
from dataclasses import dataclass
from typing import Generic, TypeVar, Optional
import json
T = TypeVar('T')
@dataclass
class TickerData:
symbol: str
tickDirection: str
price24hPcnt: str
lastPrice: str
prevPrice24h: str
highPrice24h: str
lowPrice24h: str
prevPrice1h: str
markPrice: str
indexPrice: str
openInterest: str
openInterestValue: str
turnover24h: str
volume24h: str
nextFundingTime: str
fundingRate: str
bid1Price: str
bid1Size: str
ask1Price: str
ask1Size: str
@dataclass
class Message(Generic[T]):
topic: str
type: str
data: Optional[T] = None
cs: Optional[int] = None
ts: Optional[int] = None
@staticmethod
def from_json(json_dict: dict) -> 'Message[T]':
if json_dict['topic'].startswith("tickers"):
data = TickerData(**json_dict['data'])
else:
data = None
json_dict.pop('data', None)
return Message(**json_dict, data=data)

0
messages/__init__.py Normal file
View File