This commit is contained in:
null
2024-03-06 09:25:52 +01:00
parent d8948b8051
commit 5bb4da7499
3 changed files with 100 additions and 129 deletions
+43
View File
@@ -0,0 +1,43 @@
from pybit.unified_trading import WebSocket
from typing import Callable
from functools import partial
from .TickerData import Message, TickerData
WS_URL = "wss://stream.bybit.com/v5/public/linear"
ws = WebSocket(
testnet=True,
channel_type="linear",
)
subscribed: set[str] = set()
lastPrice: dict[str, float] = dict()
class Bybit:
@staticmethod
def subscribe_symbol(symbol: str, callback: Callable[[TickerData], None]):
global subscribed
if symbol not in subscribed:
subscribed.add(symbol)
ws.ticker_stream(
symbol=symbol,
callback=lambda m: Bybit.handle_message(m, callback)
)
@staticmethod
def handle_message(message, callback: Callable[[TickerData], None]):
msg = Message.from_json(message)
if msg.data is not None and isinstance(msg.data, TickerData):
Bybit.handle_tickerdata(msg.data, callback)
@staticmethod
def handle_tickerdata(data: TickerData, callback: Callable[[TickerData], None]):
global lastPrice
if data.symbol not in lastPrice or lastPrice[data.symbol] != data.lastPrice:
lastPrice[data.symbol] = data.lastPrice
Bybit.handle_new_tickerdata(data, callback)
@staticmethod
def handle_new_tickerdata(data: TickerData, callback: Callable[[TickerData], None]):
callback(data)
+48
View File
@@ -0,0 +1,48 @@
import os
from typing import Callable
from rethinkdb import RethinkDB
from .Condition import Condition
RDB_HOST = os.environ.get('RETHINKDB_URL')
RDB_PORT = os.environ.get('RETHINKDB_PORT')
DB_NAME = "finfree"
TABLE_NAME = 'conditions'
r = RethinkDB()
connection = None
def get_connection():
global connection
if connection is None or not connection.is_open():
connection = r.connect(RDB_HOST, RDB_PORT, db=DB_NAME)
return connection
def getRethinkDB():
return r
def fetch_conditions() -> list[Condition]:
try:
cursor = r.table(TABLE_NAME).run(get_connection())
return [Condition(**doc) for doc in cursor]
except Exception as e:
print(f"Error fetching symbols: {e}")
return []
conditions: list[Condition] = list()
class DbConnector:
def watch_conditions(callback: Callable[[Condition], None]):
global conditions
conditions = fetch_conditions()
for cond in conditions:
callback(cond)
feed = r.table(TABLE_NAME).changes().run(get_connection())
for change in feed:
if change['new_val'] and not change['old_val']: # New symbol added
cond: Condition = change['new_val']
callback(cond)