sparkle/app/core/websocket.py

56 lines
1.7 KiB
Python
Raw Permalink Normal View History

2024-09-06 01:23:00 +00:00
import websocket
import threading
import json
import asyncio
from fastapi import WebSocket
from app.core.config import settings
from typing import List
connected_clients: List[WebSocket] = []
2024-09-06 12:54:19 +00:00
finnhub_ws: websocket.WebSocketApp = None
2024-09-06 01:23:00 +00:00
2024-09-06 12:54:19 +00:00
# WebSocket event handlers
2024-09-06 01:23:00 +00:00
async def on_message(ws, message):
2024-09-06 12:54:19 +00:00
print("Received message from Finnhub WebSocket:", message)
print("Forwarding message to connected clients:", connected_clients)
2024-09-06 01:23:00 +00:00
for client in connected_clients:
2024-09-06 12:54:19 +00:00
try:
2024-09-06 01:23:00 +00:00
await client.send_text(message)
except Exception as e:
print("Error sending message to client:", e)
def on_error(ws, error):
print("Error:", error)
def on_close(ws):
2024-09-06 12:54:19 +00:00
print("### Finnhub WebSocket closed ###")
2024-09-06 01:23:00 +00:00
def on_open(ws):
2024-09-06 12:54:19 +00:00
global finnhub_ws
finnhub_ws = ws
2024-09-06 01:23:00 +00:00
ws.send(json.dumps({'type': 'subscribe', 'symbol': 'AAPL'}))
ws.send(json.dumps({'type': 'subscribe', 'symbol': 'AMZN'}))
ws.send(json.dumps({'type': 'subscribe', 'symbol': 'BINANCE:BTCUSDT'}))
ws.send(json.dumps({'type': 'subscribe', 'symbol': 'IC MARKETS:1'}))
2024-09-06 12:54:19 +00:00
def forward_message_to_finnhub(message: str):
global finnhub_ws
if finnhub_ws:
finnhub_ws.send(message)
print("Forwarded message to Finnhub:", message)
else:
print("Finnhub WebSocket is not connected.")
2024-09-06 01:23:00 +00:00
def start_finnhub_websocket():
websocket.enableTrace(True)
2024-09-06 12:54:19 +00:00
ws = websocket.WebSocketApp(
f"wss://ws.finnhub.io?token={settings.FINNHUB_API_KEY}",
on_message=lambda ws, msg: asyncio.run(on_message(ws, msg)),
on_error=on_error,
on_close=on_close
)
2024-09-06 01:23:00 +00:00
ws.on_open = on_open
2024-09-06 12:54:19 +00:00
# Run WebSocket in a separate thread
2024-09-06 01:23:00 +00:00
thread = threading.Thread(target=ws.run_forever)
thread.start()