mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-29 12:43:48 +00:00
add a websockets router
This commit is contained in:
@@ -71,6 +71,7 @@ openbb-charting = { path = "./obbject_extensions/charting", optional = true, dev
|
||||
openbb-econometrics = { path = "./extensions/econometrics", optional = true, develop = true }
|
||||
openbb-quantitative = { path = "./extensions/quantitative", optional = true, develop = true }
|
||||
openbb-technical = { path = "./extensions/technical", optional = true, develop = true }
|
||||
openbb-websockets = { path = "./extensions/websockets", optional = true, develop = true }
|
||||
"""
|
||||
|
||||
|
||||
|
||||
0
openbb_platform/extensions/websockets/README.md
vendored
Normal file
0
openbb_platform/extensions/websockets/README.md
vendored
Normal file
@@ -0,0 +1 @@
|
||||
"""OpenBB WebSockets Router Extension."""
|
||||
@@ -0,0 +1,233 @@
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||
from starlette.websockets import WebSocketState
|
||||
|
||||
from openbb_websockets.helpers import get_logger, parse_kwargs
|
||||
|
||||
connected_clients = set()
|
||||
|
||||
kwargs = parse_kwargs()
|
||||
|
||||
HOST = kwargs.pop("host", None) or "localhost"
|
||||
PORT = kwargs.pop("port", None) or 6666
|
||||
PORT = int(PORT)
|
||||
|
||||
RESULTS_FILE = kwargs.pop("results_file", None)
|
||||
TABLE_NAME = kwargs.pop("table_name", None) or "records"
|
||||
SLEEP_TIME = kwargs.pop("sleep_time", None) or 0.25
|
||||
AUTH_TOKEN = kwargs.pop("auth_token", None)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.websocket("/")
|
||||
async def websocket_endpoint( # noqa: PLR0915
|
||||
websocket: WebSocket, auth_token: Optional[str] = None
|
||||
):
|
||||
|
||||
broadcast_server = BroadcastServer(
|
||||
RESULTS_FILE,
|
||||
TABLE_NAME,
|
||||
SLEEP_TIME,
|
||||
str(AUTH_TOKEN),
|
||||
)
|
||||
auth_token = str(auth_token)
|
||||
|
||||
if (
|
||||
broadcast_server.auth_token is not None
|
||||
and auth_token != broadcast_server.auth_token
|
||||
):
|
||||
await websocket.accept()
|
||||
await websocket.send_text(
|
||||
"ERROR: Invalid authentication token. Could not connect to the broadcast."
|
||||
)
|
||||
broadcast_server.logger.error(
|
||||
"ERROR: Invalid authentication token passed by a client connecting."
|
||||
)
|
||||
await websocket.close(code=1008, reason="Invalid authentication token")
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
if RESULTS_FILE is None:
|
||||
raise ValueError("Results file path is required for WebSocket server.")
|
||||
|
||||
broadcast_server.websocket = websocket
|
||||
connected_clients.add(broadcast_server)
|
||||
|
||||
stream_task = asyncio.create_task(broadcast_server.stream_results())
|
||||
try:
|
||||
await websocket.receive_text()
|
||||
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception as e:
|
||||
broadcast_server.logger.error(f"Unexpected error: {e}")
|
||||
pass
|
||||
finally:
|
||||
if broadcast_server in connected_clients:
|
||||
connected_clients.remove(broadcast_server)
|
||||
stream_task.cancel()
|
||||
try:
|
||||
await stream_task
|
||||
except asyncio.CancelledError:
|
||||
broadcast_server.logger.info("Stream task cancelled")
|
||||
except Exception as e:
|
||||
broadcast_server.logger.error(f"Error while cancelling stream task: {e}")
|
||||
if websocket.client_state != WebSocketState.DISCONNECTED:
|
||||
try:
|
||||
await websocket.close()
|
||||
except RuntimeError as e:
|
||||
broadcast_server.logger.error(f"Error while closing websocket: {e}")
|
||||
|
||||
|
||||
class BroadcastServer:
|
||||
"""Stream new results from a continuously written SQLite database.
|
||||
|
||||
Not intended to be used directly, it is initialized by the server app when it accepts a new connection.
|
||||
It is responsible for reading the results database and sending new messages to the connected client(s).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
results_file,
|
||||
table_name,
|
||||
sleep_time: float = 0.25,
|
||||
auth_token: Optional[str] = None,
|
||||
):
|
||||
|
||||
self.results_file = results_file
|
||||
self.table_name = table_name
|
||||
self.logger = get_logger("openbb.websocket.broadcast_server")
|
||||
self.sleep_time = sleep_time
|
||||
self.auth_token = auth_token
|
||||
self._app = app
|
||||
self.websocket = None
|
||||
|
||||
async def stream_results(self): # noqa: PLR0915
|
||||
"""Continuously read the database and send new messages as JSON via WebSocket."""
|
||||
import sqlite3 # noqa
|
||||
from pathlib import Path
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
|
||||
file_path = Path(self.results_file).absolute()
|
||||
last_id = 0
|
||||
|
||||
if not file_path.exists():
|
||||
self.logger.error(f"Results file not found: {file_path}")
|
||||
return
|
||||
else:
|
||||
conn = sqlite3.connect(self.results_file)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(f"SELECT MAX(id) FROM {self.table_name}") # noqa:S608
|
||||
last_id = cursor.fetchone()[0] or 0
|
||||
conn.close()
|
||||
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
if file_path.exists():
|
||||
conn = sqlite3.connect(self.results_file)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
f"SELECT * FROM {self.table_name} WHERE id > ?", # noqa:S608
|
||||
(last_id,),
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
|
||||
if rows:
|
||||
for row in rows:
|
||||
index, message = row
|
||||
await self.broadcast(json.dumps(json.loads(message)))
|
||||
last_id = max(row[0] for row in rows)
|
||||
else:
|
||||
self.logger.error(f"Results file not found: {file_path}")
|
||||
break
|
||||
|
||||
await asyncio.sleep(self.sleep_time)
|
||||
except KeyboardInterrupt:
|
||||
self.logger.info("\nResults stream cancelled.")
|
||||
break
|
||||
except sqlite3.OperationalError as e:
|
||||
if "no such table" in str(e):
|
||||
self.logger.error(
|
||||
"Results file was removed by the parent process."
|
||||
)
|
||||
break
|
||||
else:
|
||||
raise OpenBBError(e) from e
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception as e:
|
||||
self.logger.error(f"Unexpected error: {e}")
|
||||
finally:
|
||||
return
|
||||
|
||||
async def broadcast(self, message: str):
|
||||
"""Broadcast a message to all connected connected clients."""
|
||||
disconnected_clients = set()
|
||||
for client in connected_clients.copy():
|
||||
try:
|
||||
await client.websocket.send_text(message)
|
||||
except WebSocketDisconnect:
|
||||
disconnected_clients.add(client)
|
||||
except Exception as e:
|
||||
self.logger.error(f"Unexpected error: {e}")
|
||||
disconnected_clients.add(client)
|
||||
# Remove disconnected connected clients
|
||||
for client in disconnected_clients:
|
||||
connected_clients.remove(client)
|
||||
|
||||
def start_app(self, host: str = "127.0.0.1", port: int = 6666, **kwargs):
|
||||
uvicorn.run(
|
||||
self._app,
|
||||
host=host,
|
||||
port=port,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def create_broadcast_server(
|
||||
results_file: str,
|
||||
table_name: str,
|
||||
sleep_time: float = 0.25,
|
||||
auth_token: Optional[str] = None,
|
||||
**kwargs,
|
||||
):
|
||||
return BroadcastServer(results_file, table_name, sleep_time, auth_token)
|
||||
|
||||
|
||||
def main():
|
||||
broadcast_server = create_broadcast_server(
|
||||
RESULTS_FILE,
|
||||
TABLE_NAME,
|
||||
SLEEP_TIME,
|
||||
str(AUTH_TOKEN),
|
||||
)
|
||||
|
||||
try:
|
||||
broadcast_server.start_app(
|
||||
host=HOST,
|
||||
port=PORT,
|
||||
**kwargs,
|
||||
)
|
||||
except TypeError as e:
|
||||
broadcast_server.logger.error(
|
||||
f"Invalid keyword argument passed to unvicorn. -> {e.args[0]}\n"
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
broadcast_server.logger.info("Broadcast server terminated.")
|
||||
finally:
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,675 @@
|
||||
"""WebSocket Client module for interacting with a provider websocket in a non-blocking pattern."""
|
||||
|
||||
# pylint: disable=too-many-statements
|
||||
# flake8: noqa: PLR0915
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Literal, Optional
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from openbb_core.provider.abstract.data import Data
|
||||
|
||||
|
||||
class WebSocketClient:
|
||||
"""Client for interacting with a websocket server in a non-blocking pattern.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name to assign the WebSocket connection. Used to identify and manage multiple instances.
|
||||
module : str
|
||||
The Python module for the provider server connection. Runs in a separate thread.
|
||||
Example: 'openbb_fmp.websockets.server'. Pass additional keyword arguments by including kwargs.
|
||||
symbol : Optional[str]
|
||||
The symbol(s) requested to subscribe. Enter multiple symbols separated by commas without spaces.
|
||||
limit : Optional[int]
|
||||
The limit of records to hold in memory. Once the limit is reached, the oldest records are removed.
|
||||
Default is None.
|
||||
results_file : Optional[str]
|
||||
Absolute path to the file for continuous writing. By default, a temporary file is created.
|
||||
table_name : Optional[str]
|
||||
SQL table name to store serialized data messages. By default, 'records'.
|
||||
save_results : bool
|
||||
Whether to persist the results after the main Python session ends. Default is False.
|
||||
data_model : Optional[Data]
|
||||
Pydantic data model to validate the results before storing them in the database.
|
||||
Also used to deserialize the results from the database.
|
||||
auth_token : Optional[str]
|
||||
The authentication token to use for the WebSocket connection. Default is None.
|
||||
Only used for API and Python application endpoints.
|
||||
logger : Optional[logging.Logger]
|
||||
The logger instance to use this connection. By default, a new logger is created.
|
||||
kwargs : dict
|
||||
Additional keyword arguments to pass to the target module.
|
||||
|
||||
Properties
|
||||
----------
|
||||
symbol : str
|
||||
Symbol(s) requested to subscribe.
|
||||
module : str
|
||||
Path to the provider connection script.
|
||||
is_running : bool
|
||||
Check if the provider connection is running.
|
||||
is_broadcasting : bool
|
||||
Check if the broadcast server is running.
|
||||
broadcast_address : str
|
||||
URI address for the results broadcast server.
|
||||
results : list
|
||||
All stored results from the provider's WebSocket stream. The results are stored in a SQLite database.
|
||||
Set the 'limit' property to cap the number of stored records.
|
||||
Clear the results by deleting the property. e.g., del client.results
|
||||
transformed_results : list
|
||||
Deserialize the records from the results file using the provided data model, if available.
|
||||
|
||||
Methods
|
||||
-------
|
||||
connect
|
||||
Connect to the provider WebSocket stream.
|
||||
disconnect
|
||||
Disconnect from the provider WebSocket.
|
||||
subscribe
|
||||
Subscribe to a new symbol or list of symbols.
|
||||
unsubscribe
|
||||
Unsubscribe from a symbol or list of symbols.
|
||||
start_broadcasting
|
||||
Start the broadcast server to stream results over a network connection.
|
||||
stop_broadcasting
|
||||
Stop the broadcast server and disconnect all reading clients.
|
||||
send_message
|
||||
Send a message to the WebSocket process.
|
||||
"""
|
||||
|
||||
def __init__( # noqa: PLR0913
|
||||
self,
|
||||
name: str,
|
||||
module: str,
|
||||
symbol: Optional[str] = None,
|
||||
limit: Optional[int] = None,
|
||||
results_file: Optional[str] = None,
|
||||
table_name: Optional[str] = None,
|
||||
save_results: bool = False,
|
||||
data_model: Optional["Data"] = None,
|
||||
auth_token: Optional[str] = None,
|
||||
logger: Optional[logging.Logger] = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""Initialize the WebSocketClient class."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio # noqa
|
||||
import atexit
|
||||
import tempfile
|
||||
import threading
|
||||
from aiosqlite import DatabaseError
|
||||
from queue import Queue
|
||||
from pathlib import Path
|
||||
from openbb_websockets.helpers import get_logger
|
||||
|
||||
self.name = name
|
||||
self.module = module.replace(".py", "")
|
||||
self.results_file = results_file if results_file else None
|
||||
self.table_name = table_name if table_name else "records"
|
||||
self._limit = limit
|
||||
self.data_model = data_model
|
||||
self._auth_token = auth_token
|
||||
self._symbol = symbol
|
||||
self._kwargs = (
|
||||
[f"{k}={str(v).strip().replace(" ", "_")}" for k, v in kwargs.items()]
|
||||
if kwargs
|
||||
else None
|
||||
)
|
||||
|
||||
self._process = None
|
||||
self._psutil_process = None
|
||||
self._thread = None
|
||||
self._log_thread = None
|
||||
self._provider_message_queue = Queue()
|
||||
self._stop_log_thread_event = threading.Event()
|
||||
self._stop_broadcasting_event = threading.Event()
|
||||
self._broadcast_address = None
|
||||
self._broadcast_process = None
|
||||
self._psutil_broadcast_process = None
|
||||
self._broadcast_thread = None
|
||||
self._broadcast_log_thread = None
|
||||
self._broadcast_message_queue = Queue()
|
||||
|
||||
if not results_file:
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
pass
|
||||
temp_file_path = temp_file.name
|
||||
self.results_path = Path(temp_file_path).absolute()
|
||||
self.results_file = temp_file_path
|
||||
|
||||
self.results_path = Path(self.results_file).absolute()
|
||||
self.save_results = save_results
|
||||
self.logger = logger if logger else get_logger("openbb.websocket.client")
|
||||
|
||||
atexit.register(self._atexit)
|
||||
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
except RuntimeError:
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
if loop.is_running():
|
||||
loop.create_task(self._setup_database())
|
||||
else:
|
||||
asyncio.run(self._setup_database())
|
||||
except DatabaseError as e:
|
||||
self.logger.error("Error setting up the SQLite database and table: %s", e)
|
||||
|
||||
def _atexit(self):
|
||||
"""Clean up the WebSocket client processes at exit."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import os
|
||||
|
||||
if self.is_running:
|
||||
self.disconnect()
|
||||
if self.is_broadcasting:
|
||||
self.stop_broadcasting()
|
||||
if self.save_results:
|
||||
self.logger.info("Websocket results saved to, %s\n", self.results_file)
|
||||
if os.path.exists(self.results_file):
|
||||
os.remove(self.results_file)
|
||||
|
||||
async def _setup_database(self):
|
||||
"""Set up the SQLite database and table."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_websockets.helpers import setup_database
|
||||
|
||||
return await setup_database(self.results_path, self.table_name)
|
||||
|
||||
def _log_provider_output(self, output_queue):
|
||||
"""Log output from the provider server queue."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import queue # noqa
|
||||
import sys
|
||||
from openbb_websockets.helpers import clean_message
|
||||
|
||||
while not self._stop_log_thread_event.is_set():
|
||||
try:
|
||||
output = output_queue.get(timeout=1)
|
||||
if output:
|
||||
output = clean_message(output)
|
||||
output = output + "\n"
|
||||
sys.stdout.write(output + "\n")
|
||||
sys.stdout.flush()
|
||||
except queue.Empty:
|
||||
continue
|
||||
|
||||
def _log_broadcast_output(self, output_queue):
|
||||
"""Log output from the broadcast server queue."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import queue # noqa
|
||||
import sys
|
||||
from openbb_websockets.helpers import clean_message
|
||||
|
||||
while not self._stop_broadcasting_event.is_set():
|
||||
try:
|
||||
output = output_queue.get(timeout=1)
|
||||
|
||||
if output and "Uvicorn running" in output:
|
||||
address = (
|
||||
output.split("Uvicorn running on ")[-1]
|
||||
.strip()
|
||||
.replace(" (Press CTRL+C to quit)", "")
|
||||
.replace("http", "ws")
|
||||
)
|
||||
output = "INFO: " + f"Stream results from {address}"
|
||||
self._broadcast_address = address
|
||||
|
||||
if output and "Started server process" in output:
|
||||
output = None
|
||||
|
||||
if output and "Waiting for application startup." in output:
|
||||
output = None
|
||||
|
||||
if output and "Application startup complete." in output:
|
||||
output = None
|
||||
|
||||
if output:
|
||||
if "ERROR:" in output:
|
||||
output = output.replace("ERROR:", "BROADCAST ERROR:") + "\n"
|
||||
if "INFO:" in output:
|
||||
output = output.replace("INFO:", "BROADCAST INFO:") + "\n"
|
||||
output = output[0] if isinstance(output, tuple) else output
|
||||
output = clean_message(output)
|
||||
sys.stdout.write(output + "\n")
|
||||
sys.stdout.flush()
|
||||
except queue.Empty:
|
||||
continue
|
||||
|
||||
def connect(self):
|
||||
"""Connect to the provider WebSocket."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json # noqa
|
||||
import os
|
||||
import queue
|
||||
import subprocess
|
||||
import threading
|
||||
import psutil
|
||||
|
||||
if self.is_running:
|
||||
self.logger.info("Provider connection already running.")
|
||||
return
|
||||
|
||||
symbol = self.symbol
|
||||
|
||||
if not symbol:
|
||||
self.logger.info("No subscribed symbols.")
|
||||
return
|
||||
|
||||
command = self.module.copy()
|
||||
command.extend([f"symbol={symbol}"])
|
||||
command.extend([f"results_file={self.results_file}"])
|
||||
command.extend([f"table_name={self.table_name}"]),
|
||||
|
||||
if self.limit:
|
||||
command.extend([f"limit={self.limit}"])
|
||||
|
||||
if self._kwargs:
|
||||
for kwarg in self._kwargs:
|
||||
if kwarg not in command:
|
||||
command.extend([kwarg])
|
||||
|
||||
self._process = subprocess.Popen( # noqa
|
||||
command,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.PIPE,
|
||||
env=os.environ,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
self._psutil_process = psutil.Process(self._process.pid)
|
||||
|
||||
log_output_queue = queue.Queue()
|
||||
self._thread = threading.Thread(
|
||||
target=non_blocking_websocket,
|
||||
args=(
|
||||
self,
|
||||
log_output_queue,
|
||||
self._provider_message_queue,
|
||||
),
|
||||
)
|
||||
self._thread.daemon = True
|
||||
self._thread.start()
|
||||
|
||||
self._log_thread = threading.Thread(
|
||||
target=self._log_provider_output,
|
||||
args=(log_output_queue,),
|
||||
)
|
||||
self._log_thread.daemon = True
|
||||
self._log_thread.start()
|
||||
|
||||
if not self.is_running:
|
||||
self.logger.error("The provider server failed to start.")
|
||||
|
||||
def send_message(
|
||||
self, message, target: Literal["provider", "broadcast"] = "provider"
|
||||
):
|
||||
"""Send a message to the WebSocket process."""
|
||||
if target == "provider":
|
||||
self._provider_message_queue.put(message)
|
||||
read_message_queue(self, self._provider_message_queue)
|
||||
elif target == "broadcast":
|
||||
self._broadcast_message_queue.put(message)
|
||||
read_message_queue(self, self._broadcast_message_queue, target="broadcast")
|
||||
|
||||
def disconnect(self):
|
||||
"""Disconnect from the provider WebSocket."""
|
||||
self._stop_log_thread_event.set()
|
||||
if self._process is None or self.is_running is False:
|
||||
self.logger.info("Not connected to the provider WebSocket.")
|
||||
return
|
||||
if (
|
||||
self._psutil_process is not None
|
||||
and hasattr(self._psutil_process, "is_running")
|
||||
and self._psutil_process.is_running()
|
||||
):
|
||||
self._psutil_process.kill()
|
||||
self._process.wait()
|
||||
self._thread.join()
|
||||
self._log_thread.join()
|
||||
self._stop_log_thread_event.clear()
|
||||
self.logger.info("Disconnected from the provider WebSocket.")
|
||||
return
|
||||
|
||||
def subscribe(self, symbol):
|
||||
"""Subscribe to a new symbol or list of symbols."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json
|
||||
|
||||
ticker = symbol if isinstance(symbol, list) else symbol.split(",")
|
||||
msg = {"event": "subscribe", "symbol": ticker}
|
||||
self.send_message(json.dumps(msg))
|
||||
old_symbols = self.symbol.split(",")
|
||||
new_symbols = list(set(old_symbols + ticker))
|
||||
self._symbol = ",".join(new_symbols)
|
||||
|
||||
def unsubscribe(self, symbol):
|
||||
"""Unsubscribe from a symbol or list of symbols."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json
|
||||
|
||||
if not self.symbol:
|
||||
self.logger.info("No subscribed symbols.")
|
||||
return
|
||||
|
||||
ticker = symbol if isinstance(symbol, list) else symbol.split(",")
|
||||
msg = {"event": "unsubscribe", "symbol": ticker}
|
||||
self.send_message(json.dumps(msg))
|
||||
old_symbols = self.symbol.split(",")
|
||||
new_symbols = list(set(old_symbols) - set(ticker))
|
||||
self._symbol = ",".join(new_symbols)
|
||||
|
||||
@property
|
||||
def is_running(self):
|
||||
"""Check if the provider connection is running."""
|
||||
if hasattr(self._psutil_process, "is_running"):
|
||||
return self._psutil_process.is_running()
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_broadcasting(self):
|
||||
"""Check if the broadcast server is running."""
|
||||
if hasattr(self._psutil_broadcast_process, "is_running"):
|
||||
return self._psutil_broadcast_process.is_running()
|
||||
return False
|
||||
|
||||
@property
|
||||
def results(self):
|
||||
"""Retrieve the raw results dumped by the WebSocket stream."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json # noqa
|
||||
import sqlite3
|
||||
|
||||
output: list = []
|
||||
file_path = self.results_path
|
||||
if file_path.exists():
|
||||
with sqlite3.connect(file_path) as conn:
|
||||
cursor = conn.execute(f"SELECT * FROM {self.table_name}") # noqa
|
||||
for row in cursor:
|
||||
index, message = row
|
||||
output.append(json.loads(message))
|
||||
|
||||
return output
|
||||
|
||||
self.logger.info("No results found in %s", self.results_file)
|
||||
|
||||
return []
|
||||
|
||||
@results.deleter
|
||||
def results(self):
|
||||
"""Clear results stored from the WebSocket stream."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio
|
||||
import sqlite3
|
||||
|
||||
try:
|
||||
with sqlite3.connect(self.results_path) as conn:
|
||||
conn.execute(f"DELETE FROM {self.table_name}") # noqa
|
||||
conn.commit()
|
||||
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
except RuntimeError:
|
||||
loop = asyncio.new_event_loop()
|
||||
loop.run_until_complete(self._setup_database())
|
||||
self.logger.info(
|
||||
"Results cleared from table %s in %s",
|
||||
self.table_name,
|
||||
self.results_file,
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.error("Error clearing results: %s", e)
|
||||
|
||||
@property
|
||||
def module(self):
|
||||
"""Path to the provider connection script."""
|
||||
return self._module
|
||||
|
||||
@module.setter
|
||||
def module(self, module):
|
||||
"""Set the path to the provider connection script."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import sys
|
||||
|
||||
self._module = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
module,
|
||||
]
|
||||
|
||||
@property
|
||||
def symbol(self):
|
||||
"""Symbol(s) requested to subscribe."""
|
||||
return self._symbol
|
||||
|
||||
@property
|
||||
def limit(self):
|
||||
"""Get the limit of records to hold in memory."""
|
||||
return self._limit
|
||||
|
||||
@limit.setter
|
||||
def limit(self, limit):
|
||||
"""Set the limit of records to hold in memory."""
|
||||
self._limit = limit
|
||||
|
||||
@property
|
||||
def broadcast_address(self):
|
||||
"""Get the WebSocket broadcast address."""
|
||||
return (
|
||||
self._broadcast_address
|
||||
if self._broadcast_address and self.is_broadcasting
|
||||
else None
|
||||
)
|
||||
|
||||
def start_broadcasting(
|
||||
self,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 6666,
|
||||
**kwargs,
|
||||
):
|
||||
"""Broadcast results over a network connection."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import os # noqa
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import psutil
|
||||
import queue
|
||||
from openbb_platform_api.utils.api import check_port
|
||||
|
||||
if (
|
||||
self._broadcast_process is not None
|
||||
and self._broadcast_process.poll() is None
|
||||
):
|
||||
self.logger.info(
|
||||
f"WebSocket broadcast already running on: {self._broadcast_address}"
|
||||
)
|
||||
return
|
||||
|
||||
open_port = check_port(host, port)
|
||||
|
||||
if open_port != port:
|
||||
msg = f"Port {port} is already in use. Using {open_port} instead."
|
||||
self.logger.warning(msg)
|
||||
|
||||
command = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"openbb_websockets.broadcast",
|
||||
f"host={host}",
|
||||
f"port={open_port}",
|
||||
f"results_file={self.results_file}",
|
||||
f"table_name={self.table_name}",
|
||||
f"auth_token={self._auth_token}",
|
||||
]
|
||||
if kwargs:
|
||||
for kwarg in kwargs:
|
||||
command.extend([f"{kwarg}={kwargs[kwarg]}"])
|
||||
|
||||
self._broadcast_process = subprocess.Popen( # noqa
|
||||
command,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
stdin=subprocess.PIPE,
|
||||
env=os.environ,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
)
|
||||
self._psutil_broadcast_process = psutil.Process(self._broadcast_process.pid)
|
||||
output_queue = queue.Queue()
|
||||
self._broadcast_thread = threading.Thread(
|
||||
target=non_blocking_broadcast,
|
||||
args=(
|
||||
self,
|
||||
output_queue,
|
||||
self._broadcast_message_queue,
|
||||
),
|
||||
)
|
||||
self._broadcast_thread.daemon = True
|
||||
self._broadcast_thread.start()
|
||||
|
||||
self._broadcast_log_thread = threading.Thread(
|
||||
target=self._log_broadcast_output,
|
||||
args=(output_queue,),
|
||||
)
|
||||
self._broadcast_log_thread.daemon = True
|
||||
self._broadcast_log_thread.start()
|
||||
|
||||
if not self.is_broadcasting:
|
||||
self.logger.error(
|
||||
"The broadcast server failed to start on: %s",
|
||||
self._broadcast_address,
|
||||
)
|
||||
|
||||
def stop_broadcasting(self):
|
||||
"""Stop the broadcast server."""
|
||||
broadcast_address = self._broadcast_address
|
||||
self._stop_broadcasting_event.set()
|
||||
if self._broadcast_process is None or self.is_broadcasting is False:
|
||||
self.logger.info("Not currently broadcasting.")
|
||||
return
|
||||
if (
|
||||
self._psutil_broadcast_process is not None
|
||||
and hasattr(self._psutil_broadcast_process, "is_running")
|
||||
and self._psutil_broadcast_process.is_running()
|
||||
):
|
||||
self._psutil_broadcast_process.kill()
|
||||
if broadcast_address:
|
||||
self.logger.info("Stopped broadcasting to: %s", broadcast_address)
|
||||
|
||||
self._broadcast_process.wait()
|
||||
self._broadcast_thread.join()
|
||||
self._broadcast_log_thread.join()
|
||||
self._broadcast_process = None
|
||||
self._psutil_broadcast_process = None
|
||||
self._broadcast_address = None
|
||||
self._stop_broadcasting_event.clear()
|
||||
return
|
||||
|
||||
@property
|
||||
def transformed_results(self):
|
||||
"""Deserialize the records from the results file."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json
|
||||
|
||||
if not self.data_model:
|
||||
raise NotImplementedError("No model provided to transform the results.")
|
||||
|
||||
return [self.data_model.model_validate(json.loads(d)) for d in self.results]
|
||||
|
||||
def __repr__(self):
|
||||
"""Return the WebSocketClient representation."""
|
||||
return (
|
||||
f"WebSocketClient(module={self.module}, symbol={self.symbol}, "
|
||||
f"is_running={self.is_running}, provider_pid: "
|
||||
f"{self._psutil_process.pid if self._psutil_process else ''}, is_broadcasting={self.is_broadcasting}, "
|
||||
f"broadcast_address={self.broadcast_address}, "
|
||||
f"broadcast_pid: {self._psutil_broadcast_process.pid if self._psutil_broadcast_process else ''}, "
|
||||
f"results_file={self.results_file}, table_name={self.table_name}, "
|
||||
f"save_results={self.save_results})"
|
||||
)
|
||||
|
||||
|
||||
def non_blocking_websocket(client, output_queue, provider_message_queue):
|
||||
"""Communicate with the threaded process."""
|
||||
try:
|
||||
while not client._stop_log_thread_event.is_set():
|
||||
while not provider_message_queue.empty():
|
||||
read_message_queue(client, provider_message_queue)
|
||||
output = client._process.stdout.readline()
|
||||
if output == "" and client._process.poll() is not None:
|
||||
break
|
||||
if output:
|
||||
output_queue.put(output.strip())
|
||||
|
||||
except Exception as e:
|
||||
raise e from e
|
||||
client.logger.error(f"Error in non_blocking_websocket: {e}")
|
||||
finally:
|
||||
client._process.stdout.close()
|
||||
client._process.wait()
|
||||
|
||||
|
||||
def send_message(
|
||||
client, message, target: Literal["provider", "broadcast"] = "provider"
|
||||
):
|
||||
"""Send a message to the WebSocket process."""
|
||||
try:
|
||||
if target == "provider":
|
||||
if client._process and client._process.stdin:
|
||||
client._process.stdin.write(message + "\n")
|
||||
client._process.stdin.flush()
|
||||
else:
|
||||
client.logger.error("Provider process is not running.")
|
||||
elif target == "broadcast":
|
||||
if client._broadcast_process and client._broadcast_process.stdin:
|
||||
client._broadcast_process.stdin.write(message + "\n")
|
||||
client._broadcast_process.stdin.flush()
|
||||
else:
|
||||
client.logger.error("Broadcast process is not running.")
|
||||
except Exception as e:
|
||||
client.logger.error(f"Error sending message to WebSocket process: {e}")
|
||||
|
||||
|
||||
def read_message_queue(
|
||||
client, message_queue, target: Literal["provider", "broadcast"] = "provider"
|
||||
):
|
||||
"""Read messages from the queue and send them to the WebSocket process."""
|
||||
while not message_queue.empty():
|
||||
try:
|
||||
if target == "provider":
|
||||
while not client._stop_log_thread_event.is_set():
|
||||
message = message_queue.get(timeout=1)
|
||||
if message:
|
||||
send_message(client, message, target="provider")
|
||||
elif target == "broadcast":
|
||||
while not client._stop_broadcasting_event.is_set():
|
||||
message = message_queue.get(timeout=1)
|
||||
if message:
|
||||
send_message(client, message, target="broadcast")
|
||||
except Exception as e:
|
||||
err = f"Error reading message queue: {e.args[0]} -> {message}"
|
||||
client.logger.error(err)
|
||||
finally:
|
||||
break
|
||||
|
||||
|
||||
def non_blocking_broadcast(client, output_queue, broadcast_message_queue):
|
||||
"""Continuously read the output from the broadcast process and log it to the main thread."""
|
||||
try:
|
||||
while not client._stop_broadcasting_event.is_set():
|
||||
while not broadcast_message_queue.empty():
|
||||
read_message_queue(client, broadcast_message_queue, target="broadcast")
|
||||
|
||||
output = client._broadcast_process.stdout.readline()
|
||||
if output == "" and client._broadcast_process.poll() is not None:
|
||||
break
|
||||
if output:
|
||||
output_queue.put(output.strip())
|
||||
except Exception as e:
|
||||
client.logger.error(f"Error in non_blocking_broadcast: {e}")
|
||||
finally:
|
||||
client._broadcast_process.stdout.close()
|
||||
client._broadcast_process.wait()
|
||||
@@ -0,0 +1,238 @@
|
||||
"""WebSockets helpers."""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
from openbb_core.provider.utils.errors import UnauthorizedError
|
||||
|
||||
AUTH_TOKEN_FILTER = re.compile(
|
||||
r"(auth_token=)([^&]*)",
|
||||
re.IGNORECASE | re.MULTILINE,
|
||||
)
|
||||
|
||||
connected_clients: dict = {}
|
||||
|
||||
|
||||
def clean_message(message: str) -> str:
|
||||
"""Clean the message."""
|
||||
return AUTH_TOKEN_FILTER.sub(r"\1********", message)
|
||||
|
||||
|
||||
def get_logger(name, level=logging.INFO):
|
||||
"""Get a logger instance."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
logger = logging.getLogger(f"{name}-{uuid.uuid4()}")
|
||||
handler = logging.StreamHandler()
|
||||
handler.setLevel(level)
|
||||
formatter = logging.Formatter("%(message)s\n")
|
||||
handler.setFormatter(formatter)
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(level)
|
||||
return logger
|
||||
|
||||
|
||||
async def get_status(name: str) -> dict:
|
||||
"""Get the status of a client."""
|
||||
if name not in connected_clients:
|
||||
raise OpenBBError(f"Client {name} not connected.")
|
||||
client = connected_clients[name]
|
||||
provider_pid = client._psutil_process.pid if client.is_running else None
|
||||
broadcast_pid = (
|
||||
client._psutil_broadcast_process.pid if client.is_broadcasting else None
|
||||
)
|
||||
status = {
|
||||
"name": client.name,
|
||||
"auth_required": client._auth_token is not None,
|
||||
"subscribed_symbols": client.symbol,
|
||||
"is_running": client.is_running,
|
||||
"provider_pid": provider_pid,
|
||||
"is_broadcasting": client.is_broadcasting,
|
||||
"broadcast_address": client.broadcast_address,
|
||||
"broadcast_pid": broadcast_pid,
|
||||
"results_file": client.results_file,
|
||||
"table_name": client.table_name,
|
||||
"save_results": client.save_results,
|
||||
}
|
||||
return status
|
||||
|
||||
|
||||
async def check_auth(name: str, auth_token: Optional[str] = None) -> bool:
|
||||
"""Check the auth token."""
|
||||
if name not in connected_clients:
|
||||
raise OpenBBError(f"Client {name} not connected.")
|
||||
client = connected_clients[name]
|
||||
if client._auth_token is None:
|
||||
return True
|
||||
if auth_token is None:
|
||||
raise UnauthorizedError(f"Client authorization token is required for {name}.")
|
||||
if auth_token != client._auth_token:
|
||||
raise UnauthorizedError(f"Invalid client authorization token for {name}.")
|
||||
return True
|
||||
|
||||
|
||||
def handle_termination_signal(logger):
|
||||
"""Handle termination signals to ensure graceful shutdown."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import sys
|
||||
|
||||
logger.info(
|
||||
"PROVIDER INFO: Termination signal received. WebSocket connection closed."
|
||||
)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
def parse_kwargs():
|
||||
"""Parse command line keyword arguments."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:].copy()
|
||||
_kwargs: dict = {}
|
||||
for i, arg in enumerate(args):
|
||||
if "=" in arg:
|
||||
key, value = arg.split("=")
|
||||
_kwargs[key] = value
|
||||
elif arg.startswith("--"):
|
||||
key = arg[2:]
|
||||
if i + 1 < len(args) and not args[i + 1].startswith("--"):
|
||||
value = args[i + 1]
|
||||
if isinstance(value, str) and value.lower() in ["false", "true"]:
|
||||
value = value.lower() == "true"
|
||||
elif isinstance(value, str) and value.lower() == "none":
|
||||
value = None
|
||||
_kwargs[key] = value
|
||||
else:
|
||||
_kwargs[key] = True
|
||||
|
||||
return _kwargs
|
||||
|
||||
|
||||
async def setup_database(results_path, table_name):
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import os # noqa
|
||||
import aiosqlite
|
||||
|
||||
async with aiosqlite.connect(results_path) as conn:
|
||||
if os.path.exists(results_path):
|
||||
try:
|
||||
await conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
||||
except aiosqlite.DatabaseError:
|
||||
os.remove(results_path)
|
||||
|
||||
async with aiosqlite.connect(results_path) as conn:
|
||||
await conn.execute(
|
||||
f"""
|
||||
CREATE TABLE IF NOT EXISTS {table_name} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
message TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
await conn.commit()
|
||||
|
||||
|
||||
async def write_to_db(message, results_path, table_name, limit):
|
||||
"""Write the WebSocket message to the SQLite database."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import json # noqa
|
||||
import aiosqlite
|
||||
|
||||
conn = await aiosqlite.connect(results_path)
|
||||
await conn.execute(
|
||||
f"INSERT INTO {table_name} (message) VALUES (?)", # noqa
|
||||
(json.dumps(message),),
|
||||
)
|
||||
await conn.commit()
|
||||
records = await conn.execute(f"SELECT COUNT(*) FROM {table_name}") # noqa
|
||||
count = (await records.fetchone())[0]
|
||||
count = await conn.execute(f"SELECT COUNT(*) FROM {table_name}") # noqa
|
||||
current_count = int((await count.fetchone())[0])
|
||||
limit = 0 if limit is None else int(limit)
|
||||
|
||||
if current_count > limit and limit != 0:
|
||||
await conn.execute(
|
||||
f"""
|
||||
DELETE FROM {table_name}
|
||||
WHERE id IN (
|
||||
SELECT id FROM {table_name}
|
||||
ORDER BY id DESC
|
||||
LIMIT -1 OFFSET ?
|
||||
)
|
||||
""", # noqa: S608
|
||||
(limit,),
|
||||
)
|
||||
|
||||
await conn.commit()
|
||||
await conn.close()
|
||||
|
||||
|
||||
class StdOutSink:
|
||||
"""Filter stdout for PII."""
|
||||
|
||||
def write(self, message):
|
||||
"""Write to stdout."""
|
||||
cleaned_message = AUTH_TOKEN_FILTER.sub(r"\1********", message)
|
||||
if cleaned_message != message:
|
||||
cleaned_message = f"{cleaned_message}\n"
|
||||
sys.__stdout__.write(cleaned_message)
|
||||
|
||||
def flush(self):
|
||||
"""Flush stdout."""
|
||||
sys.__stdout__.flush()
|
||||
|
||||
|
||||
class AuthTokenFilter(logging.Formatter):
|
||||
"""Custom logging formatter to filter auth tokens."""
|
||||
|
||||
def format(self, record):
|
||||
original_message = super().format(record)
|
||||
cleaned_message = AUTH_TOKEN_FILTER.sub(r"\1********", original_message)
|
||||
return cleaned_message
|
||||
|
||||
|
||||
class MessageQueue:
|
||||
def __init__(self, max_size: int = 1000, max_retries=5, backoff_factor=0.5):
|
||||
"""Initialize the MessageQueue."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from asyncio import Queue
|
||||
|
||||
self.queue = Queue(maxsize=max_size)
|
||||
self.max_retries = max_retries
|
||||
self.backoff_factor = backoff_factor
|
||||
self.logger = get_logger("openbb.websocket.queue")
|
||||
|
||||
async def dequeue(self):
|
||||
return await self.queue.get()
|
||||
|
||||
async def enqueue(self, message):
|
||||
"""Enqueue a message."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from asyncio import sleep
|
||||
from queue import Full
|
||||
|
||||
retries = 0
|
||||
while retries < self.max_retries:
|
||||
try:
|
||||
await self.queue.put(message)
|
||||
return
|
||||
except Full:
|
||||
retries += 1
|
||||
msg = f"Queue is full. Retrying {retries}/{self.max_retries}..."
|
||||
self.logger.warning(msg)
|
||||
await sleep(self.backoff_factor * retries)
|
||||
self.logger.error("Failed to enqueue message after maximum retries.")
|
||||
|
||||
async def process_queue(self, handler):
|
||||
while True:
|
||||
message = await self.queue.get()
|
||||
await self._process_message(message, handler)
|
||||
self.queue.task_done()
|
||||
|
||||
async def _process_message(self, message, handler):
|
||||
await handler(message)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Convenience tool for listening to raw broadcast streams outside of the main application thread."""
|
||||
|
||||
|
||||
class Listener:
|
||||
"""WebSocket broadcast listener. Not intended to be initialized directly, use the 'listen' function."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
"""Initialize the Listener. All keyword arguments are passed directly to websockets.connect."""
|
||||
|
||||
self.loop = None
|
||||
self.websocket = None
|
||||
self.current_task = None
|
||||
self.kwargs = {}
|
||||
if kwargs:
|
||||
self.kwargs = kwargs
|
||||
|
||||
async def listen(self, url, **kwargs): # noqa: PLR0915
|
||||
"""Listen for WebSocket messages."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio # noqa
|
||||
import json
|
||||
import websockets
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
from openbb_core.provider.utils.errors import UnauthorizedError
|
||||
from openbb_websockets.helpers import clean_message, get_logger
|
||||
from websockets.exceptions import InvalidStatusCode
|
||||
|
||||
kwargs = kwargs or {}
|
||||
|
||||
if self.kwargs:
|
||||
for k, v in self.kwargs.items():
|
||||
if k not in kwargs:
|
||||
kwargs[k] = v
|
||||
|
||||
self.logger = get_logger(url)
|
||||
url = url.replace("http", "ws")
|
||||
|
||||
if url.startswith("localhost"):
|
||||
url = url.replace("localhost", "ws://localhost")
|
||||
|
||||
if url[0].isdigit():
|
||||
url = f"ws://{url}"
|
||||
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
async with websockets.connect(url, **kwargs) as websocket:
|
||||
self.websocket = websocket
|
||||
url = clean_message(url)
|
||||
self.logger.info(
|
||||
f"\nListening for messages from {clean_message(url)}"
|
||||
)
|
||||
for handler in self.logger.handlers:
|
||||
handler.flush()
|
||||
async for message in websocket:
|
||||
if (
|
||||
isinstance(message, str)
|
||||
and "Invalid authentication token" in message
|
||||
):
|
||||
raise UnauthorizedError(message)
|
||||
self.logger.info(json.loads(message))
|
||||
for handler in self.logger.handlers:
|
||||
handler.flush()
|
||||
except UnauthorizedError as error:
|
||||
self.logger.error(error)
|
||||
break
|
||||
except (KeyboardInterrupt, asyncio.CancelledError):
|
||||
self.logger.info("Disconnected from server.")
|
||||
break
|
||||
except (
|
||||
websockets.ConnectionClosedError,
|
||||
asyncio.IncompleteReadError,
|
||||
):
|
||||
self.logger.error(
|
||||
f"The process hosting {clean_message(url)} was terminated."
|
||||
)
|
||||
break
|
||||
except websockets.exceptions.InvalidURI as error:
|
||||
self.logger.error(f"Invalid URI -> {error}")
|
||||
break
|
||||
except InvalidStatusCode as error:
|
||||
self.logger.error(f"Invalid status code -> {error}")
|
||||
break
|
||||
except OSError as error:
|
||||
if "Multiple exceptions" in str(error):
|
||||
err = str(error).split("Multiple exceptions:")[1].strip()
|
||||
err = err.split("[")[-1].strip().replace("]", ":")
|
||||
self.logger.error(
|
||||
f"An error occurred while attempting to connect to: {clean_message(url)} -> {err}"
|
||||
)
|
||||
else:
|
||||
self.logger.error(
|
||||
f"An error occurred while attempting to connect to: {clean_message(url)} -> {error}"
|
||||
)
|
||||
break
|
||||
except Exception as error:
|
||||
self.logger.error(f"An unexpected error occurred: {error}")
|
||||
raise OpenBBError(error) from error
|
||||
finally:
|
||||
if self.websocket:
|
||||
await self.websocket.close()
|
||||
|
||||
def stop(self):
|
||||
if self.current_task:
|
||||
self.current_task.cancel()
|
||||
self.loop.run_until_complete(self.current_task)
|
||||
if self.websocket:
|
||||
self.loop.run_until_complete(self.websocket.close())
|
||||
if not self.loop.is_closed():
|
||||
self.loop.stop()
|
||||
|
||||
async def start_listening(self, url, **kwargs):
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio
|
||||
import contextlib
|
||||
|
||||
self.current_task = self.loop.create_task(self.listen(url, **kwargs))
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self.current_task
|
||||
|
||||
def run(self, url, **kwargs):
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import asyncio
|
||||
|
||||
try:
|
||||
self.loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
self.loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self.loop)
|
||||
try:
|
||||
self.loop.run_until_complete(self.start_listening(url, **kwargs))
|
||||
except KeyboardInterrupt:
|
||||
self.logger.info("\nWebSocket listener terminated.")
|
||||
finally:
|
||||
self.stop()
|
||||
|
||||
|
||||
def listen(url, **kwargs):
|
||||
"""Listen for WebSocket messages from a given URL. This function is blocking.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
url : str
|
||||
The WebSocket URL to connect to.
|
||||
kwargs : dict
|
||||
Additional keyword arguments passed directly to websockets.connect
|
||||
"""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
|
||||
try:
|
||||
listener = Listener(**kwargs)
|
||||
listener.run(url, **kwargs)
|
||||
except Exception as e:
|
||||
raise OpenBBError(e) from e
|
||||
finally:
|
||||
return
|
||||
@@ -0,0 +1,98 @@
|
||||
"""WebSockets models."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from openbb_core.provider.abstract.data import Data
|
||||
from openbb_core.provider.abstract.query_params import QueryParams
|
||||
from openbb_core.provider.utils.descriptions import (
|
||||
DATA_DESCRIPTIONS,
|
||||
QUERY_DESCRIPTIONS,
|
||||
)
|
||||
from pydantic import ConfigDict, Field, field_validator
|
||||
|
||||
from openbb_websockets.client import WebSocketClient
|
||||
|
||||
|
||||
class WebSocketQueryParams(QueryParams):
|
||||
"""Query parameters for WebSocket connection creation."""
|
||||
|
||||
symbol: str = Field(
|
||||
description=QUERY_DESCRIPTIONS.get("symbol", ""),
|
||||
)
|
||||
name: str = Field(
|
||||
description="Name to assign the client connection.",
|
||||
)
|
||||
auth_token: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Authentication token for API access control of the client, not related to the provider credentials.",
|
||||
)
|
||||
results_file: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Absolute path to the file for continuous writing. By default, a temporary file is created.",
|
||||
)
|
||||
save_results: bool = Field(
|
||||
default=False,
|
||||
description="Whether to save the results after the session ends.",
|
||||
)
|
||||
table_name: str = Field(
|
||||
default="records",
|
||||
description="Name of the SQL table to write the results to.",
|
||||
)
|
||||
limit: Optional[int] = Field(
|
||||
default=1000,
|
||||
description="Maximum number of newest records to keep in the database."
|
||||
+ " If None, all records are kept, which can be memory-intensive.",
|
||||
)
|
||||
sleep_time: float = Field(
|
||||
default=0.25,
|
||||
description="Time to sleep between checking for new records in the database from the broadcast server."
|
||||
+ " The default is 0.25 seconds.",
|
||||
)
|
||||
broadcast_host: str = Field(
|
||||
default="127.0.0.1",
|
||||
description="IP address to bind the broadcast server to.",
|
||||
)
|
||||
broadcast_port: int = Field(
|
||||
default=6666,
|
||||
description="Port to bind the broadcast server to.",
|
||||
)
|
||||
start_broadcast: bool = Field(
|
||||
default=True,
|
||||
description="Whether to start the broadcast server."
|
||||
+ " Set to False if system or network conditions do not allow it."
|
||||
+ " Can be started manually with the 'start_broadcasting' method.",
|
||||
)
|
||||
|
||||
|
||||
class WebSocketData(Data):
|
||||
"""WebSocket data model."""
|
||||
|
||||
date: datetime = Field(
|
||||
description=DATA_DESCRIPTIONS.get("date", ""),
|
||||
)
|
||||
symbol: str = Field(
|
||||
description=DATA_DESCRIPTIONS.get("symbol", ""),
|
||||
)
|
||||
|
||||
|
||||
class WebSocketConnection(Data):
|
||||
"""Data model for returning WebSocketClient from the Provider Interface."""
|
||||
|
||||
__model_config__ = ConfigDict(
|
||||
extra="forbid",
|
||||
)
|
||||
|
||||
client: Any = Field(
|
||||
description="Instance of WebSocketClient class initialized by a provider Fetcher."
|
||||
+ " The client is used to communicate with the provider's data stream."
|
||||
+ " It is not returned to the user, but is handled by the router for API access.",
|
||||
exclude=True,
|
||||
)
|
||||
|
||||
@field_validator("client", mode="before", check_fields=False)
|
||||
def _validate_client(cls, v):
|
||||
"""Validate the client."""
|
||||
if not isinstance(v, WebSocketClient):
|
||||
raise ValueError("Client must be an instance of WebSocketClient.")
|
||||
return v
|
||||
@@ -0,0 +1,428 @@
|
||||
"""Websockets Router."""
|
||||
|
||||
# pylint: disable=unused-argument
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from typing import Any, Optional
|
||||
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
from openbb_core.app.model.command_context import CommandContext
|
||||
from openbb_core.app.model.example import APIEx
|
||||
from openbb_core.app.model.obbject import OBBject
|
||||
from openbb_core.app.provider_interface import (
|
||||
ExtraParams,
|
||||
ProviderChoices,
|
||||
StandardParams,
|
||||
)
|
||||
from openbb_core.app.query import Query
|
||||
from openbb_core.app.router import Router
|
||||
from openbb_core.provider.utils.errors import EmptyDataError
|
||||
|
||||
from openbb_websockets.helpers import (
|
||||
StdOutSink,
|
||||
check_auth,
|
||||
connected_clients,
|
||||
get_status,
|
||||
)
|
||||
|
||||
router = Router("", description="WebSockets Router")
|
||||
sys.stdout = StdOutSink()
|
||||
|
||||
|
||||
@router.command(
|
||||
model="WebSocketConnection",
|
||||
)
|
||||
async def create_connection(
|
||||
cc: CommandContext,
|
||||
provider_choices: ProviderChoices,
|
||||
standard_params: StandardParams,
|
||||
extra_params: ExtraParams,
|
||||
) -> OBBject:
|
||||
"""Create a new provider websocket connection."""
|
||||
name = extra_params.name
|
||||
if name in connected_clients:
|
||||
broadcast_address = connected_clients[name].broadcast_address
|
||||
is_running = connected_clients[name].is_running
|
||||
if broadcast_address or is_running:
|
||||
raise OpenBBError(
|
||||
f"Client {name} already connected! Broadcasting to: {broadcast_address}"
|
||||
)
|
||||
raise OpenBBError(f"Client {name} already connected but not running.")
|
||||
del name
|
||||
|
||||
obbject = await OBBject.from_query(Query(**locals()))
|
||||
client = obbject.results.client
|
||||
|
||||
await asyncio.sleep(1)
|
||||
|
||||
if not client.is_running:
|
||||
client._atexit()
|
||||
raise OpenBBError("Client failed to connect.")
|
||||
|
||||
if hasattr(extra_params, "start_broadcast") and extra_params.start_broadcast:
|
||||
client.start_broadcasting()
|
||||
|
||||
client_name = client.name
|
||||
connected_clients[client_name] = client
|
||||
results = await get_status(client_name)
|
||||
|
||||
obbject.results = results
|
||||
|
||||
return obbject
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def get_results(name: str, auth_token: Optional[str] = None) -> OBBject:
|
||||
"""Get all recorded results from a client connection.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[Data]
|
||||
The recorded results from the client.
|
||||
"""
|
||||
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
if not client.results:
|
||||
raise EmptyDataError(f"No results recorded for client {name}.")
|
||||
try:
|
||||
return OBBject(results=client.transformed_results)
|
||||
except NotImplementedError:
|
||||
return OBBject(results=client.results)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def clear_results(name: str, auth_token: Optional[str] = None) -> OBBject[str]:
|
||||
"""Clear all stored results from a client connection. Does not stop the client or broadcast.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The number of results cleared from the client.
|
||||
"""
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
n_before = len(client.results)
|
||||
del client.results
|
||||
return OBBject(results=f"{n_before} results cleared from {name}.")
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def subscribe(
|
||||
name: str, symbol: str, auth_token: Optional[str] = None
|
||||
) -> OBBject[str]:
|
||||
"""Subscribe to a new symbol.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
symbol : str
|
||||
The symbol to subscribe to.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client subscribed to the symbol.
|
||||
"""
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
symbols = client.symbol.split(",")
|
||||
if symbols and symbol in symbols:
|
||||
raise OpenBBError(f"Client {name} already subscribed to {symbol}.")
|
||||
client.subscribe(symbol)
|
||||
# await asyncio.sleep(2)
|
||||
if client.is_running:
|
||||
return OBBject(results=f"Added {symbol} to client {name} connection.")
|
||||
client.logger.error(
|
||||
f"Client {name} failed to subscribe to {symbol} and is not running."
|
||||
)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def unsubscribe(
|
||||
name: str, symbol: str, auth_token: Optional[str] = None
|
||||
) -> OBBject[str]:
|
||||
"""Unsubscribe to a symbol.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
symbol : str
|
||||
The symbol to unsubscribe from.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client unsubscribed from the symbol.
|
||||
"""
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
symbols = client.symbol.split(",")
|
||||
if symbol not in symbols:
|
||||
raise OpenBBError(f"Client {name} not subscribed to {symbol}.")
|
||||
client.unsubscribe(symbol)
|
||||
# await asyncio.sleep(2)
|
||||
if client.is_running:
|
||||
return OBBject(results=f"Client {name} unsubscribed to {symbol}.")
|
||||
client.logger.error(
|
||||
f"Client {name} failed to unsubscribe to {symbol} and is not running."
|
||||
)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def get_client_status(name: str = "all") -> OBBject[list[dict]]:
|
||||
"""Get the status of a client, or all client connections.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client. Default is "all".
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[dict]
|
||||
The status of the client(s).
|
||||
"""
|
||||
if not connected_clients:
|
||||
raise OpenBBError("No active connections.")
|
||||
if name == "all":
|
||||
connections = [
|
||||
await get_status(client.name) for client in connected_clients.values()
|
||||
]
|
||||
else:
|
||||
connections = [await get_status(name)]
|
||||
return OBBject(results=connections)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
include_in_schema=False,
|
||||
)
|
||||
async def get_client(name: str, auth_token: Optional[str] = None) -> OBBject:
|
||||
"""Get an open client connection object. This endpoint is only available from the Python interface.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
WebSocketClient
|
||||
The provider client connection object.
|
||||
"""
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
return OBBject(results=client)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def stop_connection(name: str, auth_token: Optional[str] = None) -> OBBject[str]:
|
||||
"""Stop a the connection to the provider's websocket. Does not stop the broadcast server.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the provider connection was stopped.
|
||||
"""
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
client.disconnect()
|
||||
return OBBject(
|
||||
results=f"Client {name} connection to the provider's websocket was stopped."
|
||||
)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def restart_connection(
|
||||
name: str, auth_token: Optional[str] = None
|
||||
) -> OBBject[str]:
|
||||
"""Restart a websocket connection.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client connection was restarted.
|
||||
"""
|
||||
if name not in connected_clients:
|
||||
raise OpenBBError(f"No active client named, {name}. Use create_connection.")
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
client.connect()
|
||||
return OBBject(results=f"Client {name} connection was restarted.")
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def stop_broadcasting(
|
||||
name: str, auth_token: Optional[str] = None
|
||||
) -> OBBject[str]:
|
||||
"""Stop the broadcast server.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client stopped broadcasting to the address.
|
||||
"""
|
||||
if name not in connected_clients:
|
||||
raise OpenBBError(f"Client {name} not connected.")
|
||||
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
|
||||
client = connected_clients[name]
|
||||
|
||||
if not client.is_broadcasting:
|
||||
raise OpenBBError(f"Client {name} not broadcasting.")
|
||||
|
||||
old_address = client.broadcast_address
|
||||
client.stop_broadcasting()
|
||||
|
||||
if not client.is_running:
|
||||
client._atexit()
|
||||
del connected_clients[name]
|
||||
return OBBject(
|
||||
results=f"Client {name} stopped broadcasting and was not running, client removed."
|
||||
)
|
||||
|
||||
return OBBject(results=f"Client {name} stopped broadcasting to: {old_address}")
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def start_broadcasting(
|
||||
name: str,
|
||||
auth_token: Optional[str] = None,
|
||||
host: str = "127.0.0.1",
|
||||
port: int = 6666,
|
||||
uvicorn_kwargs: Optional[dict[str, Any]] = None,
|
||||
) -> OBBject[str]:
|
||||
"""Start broadcasting from a websocket.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
host : str
|
||||
The host address to broadcast to. Default is 127.0.0.1"
|
||||
port : int
|
||||
The port to broadcast to. Default is 6666.
|
||||
uvicorn_kwargs : Optional[dict[str, Any]]
|
||||
Additional keyword arguments for passing directly to the uvicorn server.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client started broadcasting.
|
||||
"""
|
||||
if name not in connected_clients:
|
||||
raise OpenBBError(f"Client {name} not connected.")
|
||||
if not await check_auth(name, auth_token):
|
||||
raise OpenBBError("Error finding client.")
|
||||
client = connected_clients[name]
|
||||
kwargs = uvicorn_kwargs if uvicorn_kwargs else {}
|
||||
client.start_broadcasting(host=host, port=port, **kwargs)
|
||||
|
||||
await asyncio.sleep(2)
|
||||
if not client.is_broadcasting:
|
||||
raise OpenBBError(f"Client {name} failed to broadcast.")
|
||||
return OBBject(
|
||||
results=f"Client {name} started broadcasting to {client.broadcast_address}."
|
||||
)
|
||||
|
||||
|
||||
@router.command(
|
||||
methods=["GET"],
|
||||
)
|
||||
async def kill(name: str, auth_token: Optional[str] = None) -> OBBject[str]:
|
||||
"""Kills a client.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
The name of the client.
|
||||
auth_token : Optional[str]
|
||||
The client's authorization token.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
The message that the client was killed.
|
||||
"""
|
||||
if not connected_clients:
|
||||
raise OpenBBError("No connections to kill.")
|
||||
elif name and name not in connected_clients:
|
||||
raise OpenBBError(f"Client {name} not connected.")
|
||||
client = connected_clients[name]
|
||||
client._atexit()
|
||||
del connected_clients[name]
|
||||
return OBBject(results=f"Clients {name} killed.")
|
||||
1618
openbb_platform/extensions/websockets/poetry.lock
generated
vendored
Normal file
1618
openbb_platform/extensions/websockets/poetry.lock
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
19
openbb_platform/extensions/websockets/pyproject.toml
vendored
Normal file
19
openbb_platform/extensions/websockets/pyproject.toml
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
[tool.poetry]
|
||||
name = "openbb-websockets"
|
||||
version = "1.0.0b"
|
||||
description = "Websockets extension for OpenBB"
|
||||
authors = ["OpenBB Team <hello@openbb.co>"]
|
||||
license = "AGPL-3.0-only"
|
||||
readme = "README.md"
|
||||
packages = [{ include = "openbb_websockets" }]
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.9"
|
||||
openbb-core = "^1.3.5"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry.plugins."openbb_core_extension"]
|
||||
websockets = "openbb_websockets.websockets_router:router"
|
||||
@@ -63,6 +63,7 @@ from openbb_fmp.models.revenue_geographic import FMPRevenueGeographicFetcher
|
||||
from openbb_fmp.models.risk_premium import FMPRiskPremiumFetcher
|
||||
from openbb_fmp.models.share_statistics import FMPShareStatisticsFetcher
|
||||
from openbb_fmp.models.treasury_rates import FMPTreasuryRatesFetcher
|
||||
from openbb_fmp.models.websocket_connection import FMPWebSocketFetcher
|
||||
from openbb_fmp.models.world_news import FMPWorldNewsFetcher
|
||||
from openbb_fmp.models.yield_curve import FMPYieldCurveFetcher
|
||||
|
||||
@@ -137,6 +138,7 @@ stock market information (news, currencies, and stock prices).""",
|
||||
"TreasuryRates": FMPTreasuryRatesFetcher,
|
||||
"WorldNews": FMPWorldNewsFetcher,
|
||||
"EtfHistorical": FMPEquityHistoricalFetcher,
|
||||
"WebSocketConnection": FMPWebSocketFetcher,
|
||||
"YieldCurve": FMPYieldCurveFetcher,
|
||||
},
|
||||
repr_name="Financial Modeling Prep (FMP)",
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""FMP WebSocket model."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
from openbb_core.provider.abstract.fetcher import Fetcher
|
||||
from openbb_websockets.client import WebSocketClient
|
||||
from openbb_websockets.models import (
|
||||
WebSocketConnection,
|
||||
WebSocketData,
|
||||
WebSocketQueryParams,
|
||||
)
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
URL_MAP = {
|
||||
"stock": "wss://websockets.financialmodelingprep.com",
|
||||
"fx": "wss://forex.financialmodelingprep.com",
|
||||
"crypto": "wss://crypto.financialmodelingprep.com",
|
||||
}
|
||||
|
||||
|
||||
class FmpWebSocketQueryParams(WebSocketQueryParams):
|
||||
"""FMP WebSocket query parameters."""
|
||||
|
||||
__json_schema_extra__ = {
|
||||
"symbol": {"multiple_items_allowed": True},
|
||||
"asset_type": {
|
||||
"multiple_items_allowed": False,
|
||||
"choices": ["stock", "fx", "crypto"],
|
||||
},
|
||||
}
|
||||
|
||||
symbol: str = Field(
|
||||
description="The symbol(s) of the asset to fetch data for.",
|
||||
)
|
||||
asset_type: Literal["stock", "fx", "crypto"] = Field(
|
||||
default="crypto",
|
||||
description="The asset type, required for the provider URI.",
|
||||
)
|
||||
|
||||
|
||||
class FmpWebSocketData(WebSocketData):
|
||||
"""FMP WebSocket data model."""
|
||||
|
||||
__alias_dict__ = {
|
||||
"symbol": "s",
|
||||
"date": "t",
|
||||
"exchange": "e",
|
||||
"type": "type",
|
||||
"bid_size": "bs",
|
||||
"bid_price": "bp",
|
||||
"ask_size": "as",
|
||||
"ask_price": "ap",
|
||||
"last_price": "lp",
|
||||
"last_size": "ls",
|
||||
}
|
||||
|
||||
symbol: str = Field(
|
||||
description="The symbol of the asset.",
|
||||
)
|
||||
date: datetime = Field(
|
||||
description="The datetime of the data.",
|
||||
)
|
||||
exchange: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The exchange of the data.",
|
||||
)
|
||||
type: Literal["quote", "trade", "break"] = Field(
|
||||
description="The type of data.",
|
||||
)
|
||||
bid_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The price of the bid.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
bid_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the bid.",
|
||||
)
|
||||
ask_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the ask.",
|
||||
)
|
||||
ask_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The price of the ask.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
last_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The last trade price.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
last_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the trade.",
|
||||
)
|
||||
|
||||
@field_validator("type", mode="before", check_fields=False)
|
||||
def _valiidate_data_type(cls, v):
|
||||
"""Validate the data type."""
|
||||
return (
|
||||
"quote" if v == "Q" else "trade" if v == "T" else "break" if v == "B" else v
|
||||
)
|
||||
|
||||
@field_validator("date", mode="before", check_fields=False)
|
||||
def _validate_date(cls, v):
|
||||
"""Validate the date."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from pytz import timezone
|
||||
|
||||
if isinstance(v, str):
|
||||
return datetime.fromisoformat(v)
|
||||
try:
|
||||
return datetime.fromtimestamp(v / 1000)
|
||||
except Exception:
|
||||
if isinstance(v, (int, float)):
|
||||
# Check if the timestamp is in nanoseconds and convert to seconds
|
||||
if v > 1e12:
|
||||
v = v / 1e9 # Convert nanoseconds to seconds
|
||||
dt = datetime.fromtimestamp(v)
|
||||
dt = timezone("America/New_York").localize(dt)
|
||||
return dt
|
||||
return v
|
||||
|
||||
|
||||
class FmpWebSocketConnection(WebSocketConnection):
|
||||
"""FMP WebSocket connection model."""
|
||||
|
||||
|
||||
class FMPWebSocketFetcher(Fetcher[FmpWebSocketQueryParams, FmpWebSocketConnection]):
|
||||
"""FMP WebSocket model."""
|
||||
|
||||
@staticmethod
|
||||
def transform_query(params: dict[str, Any]) -> FmpWebSocketQueryParams:
|
||||
"""Transform the query parameters."""
|
||||
return FmpWebSocketQueryParams(**params)
|
||||
|
||||
@staticmethod
|
||||
def extract_data(
|
||||
query: FmpWebSocketQueryParams,
|
||||
credentials: Optional[dict[str, str]],
|
||||
**kwargs: Any,
|
||||
) -> WebSocketClient:
|
||||
"""Extract data from the WebSocket."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
import time
|
||||
|
||||
api_key = credentials.get("fmp_api_key") if credentials else ""
|
||||
url = URL_MAP[query.asset_type]
|
||||
|
||||
symbol = query.symbol.lower()
|
||||
|
||||
kwargs = {
|
||||
"url": url,
|
||||
"api_key": api_key,
|
||||
}
|
||||
|
||||
client = WebSocketClient(
|
||||
name=query.name,
|
||||
module="openbb_fmp.utils.websocket_client",
|
||||
symbol=symbol,
|
||||
limit=query.limit,
|
||||
results_file=query.results_file,
|
||||
table_name=query.table_name,
|
||||
save_results=query.save_results,
|
||||
data_model=FmpWebSocketData,
|
||||
sleep_time=query.sleep_time,
|
||||
broadcast_host=query.broadcast_host,
|
||||
broadcast_port=query.broadcast_port,
|
||||
auth_token=query.auth_token,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
try:
|
||||
client.connect()
|
||||
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
client.disconnect()
|
||||
raise OpenBBError(e) from e
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
if client.is_running:
|
||||
return client
|
||||
|
||||
client.disconnect()
|
||||
raise OpenBBError("Failed to connect to the WebSocket.")
|
||||
|
||||
@staticmethod
|
||||
def transform_data(
|
||||
data: WebSocketClient,
|
||||
query: FmpWebSocketQueryParams,
|
||||
**kwargs: Any,
|
||||
) -> FmpWebSocketConnection:
|
||||
"""Return the client as an instance of Data."""
|
||||
return FmpWebSocketConnection(client=data)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""FMP WebSocket server."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
|
||||
import websockets
|
||||
import websockets.exceptions
|
||||
from openbb_fmp.models.websocket_connection import FmpWebSocketData
|
||||
from openbb_websockets.helpers import (
|
||||
MessageQueue,
|
||||
get_logger,
|
||||
handle_termination_signal,
|
||||
parse_kwargs,
|
||||
write_to_db,
|
||||
)
|
||||
|
||||
queue = MessageQueue()
|
||||
command_queue = MessageQueue()
|
||||
|
||||
|
||||
# Create a logger instance.
|
||||
logger = get_logger("openbb.websocket.fmp")
|
||||
kwargs = parse_kwargs()
|
||||
|
||||
|
||||
async def login(websocket, api_key):
|
||||
login_event = {
|
||||
"event": "login",
|
||||
"data": {
|
||||
"apiKey": api_key,
|
||||
},
|
||||
}
|
||||
try:
|
||||
await websocket.send(json.dumps(login_event))
|
||||
response = await websocket.recv()
|
||||
if json.loads(response).get("message") == "Unauthorized":
|
||||
logger.error(
|
||||
"PROVIDER ERROR: Account not authorized."
|
||||
" Please check that the API key is entered correctly and is entitled to access."
|
||||
)
|
||||
sys.exit(1)
|
||||
msg = json.loads(response).get("message")
|
||||
logger.info("PROVIDER INFO: %s", msg)
|
||||
except Exception as e:
|
||||
logger.error("PROVIDER ERROR: %s", e.args[0])
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
async def subscribe(websocket, symbol, event):
|
||||
"""Subscribe or unsubscribe to a symbol."""
|
||||
ticker = symbol.split(",") if isinstance(symbol, str) else symbol
|
||||
subscribe_event = {
|
||||
"event": event,
|
||||
"data": {
|
||||
"ticker": ticker,
|
||||
},
|
||||
}
|
||||
try:
|
||||
await websocket.send(json.dumps(subscribe_event))
|
||||
except Exception as e:
|
||||
msg = f"PROVIDER ERROR: {e}"
|
||||
logger.error(msg)
|
||||
|
||||
|
||||
async def read_stdin_and_queue_commands():
|
||||
"""Read from stdin and queue commands."""
|
||||
while True:
|
||||
line = await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)
|
||||
sys.stdin.flush()
|
||||
|
||||
if not line:
|
||||
break
|
||||
|
||||
try:
|
||||
command = json.loads(line.strip())
|
||||
await command_queue.enqueue(command)
|
||||
except json.JSONDecodeError:
|
||||
logger.error("Invalid JSON received from stdin")
|
||||
|
||||
|
||||
async def process_message(message, results_path, table_name, limit):
|
||||
result = {}
|
||||
message = json.loads(message)
|
||||
if message.get("event") != "heartbeat":
|
||||
if message.get("event") in ["login", "subscribe", "unsubscribe"]:
|
||||
msg = f"PROVIDER INFO: {message.get("message")}"
|
||||
logger.info(msg)
|
||||
return None
|
||||
try:
|
||||
result = FmpWebSocketData.model_validate(message).model_dump_json(
|
||||
exclude_none=True, exclude_unset=True
|
||||
)
|
||||
except Exception as e:
|
||||
msg = f"PROVIDER ERROR: Error validating data: {e}"
|
||||
logger.error(msg)
|
||||
return None
|
||||
if result:
|
||||
await write_to_db(result, results_path, table_name, limit)
|
||||
return
|
||||
|
||||
|
||||
async def connect_and_stream(url, symbol, api_key, results_path, table_name, limit):
|
||||
"""Connect to the WebSocket and stream data to file."""
|
||||
|
||||
handler_task = asyncio.create_task(
|
||||
queue.process_queue(
|
||||
lambda message: process_message(message, results_path, table_name, limit)
|
||||
)
|
||||
)
|
||||
|
||||
stdin_task = asyncio.create_task(read_stdin_and_queue_commands())
|
||||
|
||||
try:
|
||||
async with websockets.connect(url) as websocket:
|
||||
await login(websocket, api_key)
|
||||
await subscribe(websocket, symbol, "subscribe")
|
||||
|
||||
while True:
|
||||
ws_task = asyncio.create_task(websocket.recv())
|
||||
cmd_task = asyncio.create_task(command_queue.dequeue())
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
[ws_task, cmd_task], return_when=asyncio.FIRST_COMPLETED
|
||||
)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
|
||||
for task in done:
|
||||
if task == ws_task:
|
||||
message = task.result()
|
||||
await queue.enqueue(message)
|
||||
elif task == cmd_task:
|
||||
command = task.result()
|
||||
symbol = command.get("symbol")
|
||||
event = command.get("event")
|
||||
if symbol and event:
|
||||
await subscribe(websocket, symbol, event)
|
||||
|
||||
except websockets.ConnectionClosed:
|
||||
logger.info("PROVIDER INFO: The WebSocket connection was closed.")
|
||||
|
||||
except websockets.WebSocketException as e:
|
||||
logger.error(e)
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
msg = f"PROVIDER ERROR: Unexpected error -> {e}"
|
||||
logger.error(msg)
|
||||
sys.exit(1)
|
||||
|
||||
finally:
|
||||
handler_task.cancel()
|
||||
stdin_task.cancel()
|
||||
await asyncio.gather(handler_task, stdin_task, return_exceptions=True)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
loop.add_signal_handler(sig, handle_termination_signal, logger)
|
||||
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
connect_and_stream(
|
||||
kwargs["url"],
|
||||
kwargs["symbol"],
|
||||
kwargs["api_key"],
|
||||
os.path.abspath(kwargs["results_file"]),
|
||||
kwargs["table_name"],
|
||||
kwargs.get("limit", None),
|
||||
),
|
||||
loop,
|
||||
)
|
||||
loop.run_forever()
|
||||
|
||||
except (KeyboardInterrupt, websockets.ConnectionClosed):
|
||||
logger.error("PROVIDER ERROR: WebSocket connection closed")
|
||||
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
msg = f"PROVIDER ERROR: {e.args[0]}"
|
||||
logger.error(msg)
|
||||
|
||||
finally:
|
||||
sys.exit(0)
|
||||
@@ -6,6 +6,7 @@ from openbb_tiingo.models.crypto_historical import TiingoCryptoHistoricalFetcher
|
||||
from openbb_tiingo.models.currency_historical import TiingoCurrencyHistoricalFetcher
|
||||
from openbb_tiingo.models.equity_historical import TiingoEquityHistoricalFetcher
|
||||
from openbb_tiingo.models.trailing_dividend_yield import TiingoTrailingDivYieldFetcher
|
||||
from openbb_tiingo.models.websocket_connection import TiingoWebSocketFetcher
|
||||
from openbb_tiingo.models.world_news import TiingoWorldNewsFetcher
|
||||
|
||||
tiingo_provider = Provider(
|
||||
@@ -22,6 +23,7 @@ power hedge funds, tech companies, and individuals.""",
|
||||
"CryptoHistorical": TiingoCryptoHistoricalFetcher,
|
||||
"CurrencyHistorical": TiingoCurrencyHistoricalFetcher,
|
||||
"TrailingDividendYield": TiingoTrailingDivYieldFetcher,
|
||||
"WebSocketConnection": TiingoWebSocketFetcher,
|
||||
},
|
||||
repr_name="Tiingo",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Tiingo WebSocket model."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from openbb_core.app.model.abstract.error import OpenBBError
|
||||
from openbb_core.provider.abstract.fetcher import Fetcher
|
||||
from openbb_core.provider.utils.descriptions import (
|
||||
QUERY_DESCRIPTIONS,
|
||||
)
|
||||
from openbb_websockets.client import WebSocketClient
|
||||
from openbb_websockets.models import (
|
||||
WebSocketConnection,
|
||||
WebSocketData,
|
||||
WebSocketQueryParams,
|
||||
)
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
URL_MAP = {
|
||||
"stock": "wss://api.tiingo.com/iex",
|
||||
"fx": "wss://api.tiingo.com/fx",
|
||||
"crypto": "wss://api.tiingo.com/crypto",
|
||||
}
|
||||
|
||||
# These are the data array order of definitions.
|
||||
IEX_FIELDS = [
|
||||
"type",
|
||||
"date",
|
||||
"timestamp",
|
||||
"symbol",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_price",
|
||||
"ask_size",
|
||||
"last_price",
|
||||
"last_size",
|
||||
"halted",
|
||||
"after_hours",
|
||||
"sweep_order",
|
||||
"oddlot",
|
||||
"nms_rule",
|
||||
]
|
||||
FX_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_price",
|
||||
"ask_size",
|
||||
"ask_price",
|
||||
]
|
||||
CRYPTO_TRADE_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"exchange",
|
||||
"last_size",
|
||||
"last_price",
|
||||
]
|
||||
CRYPTO_QUOTE_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"exchange",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_size",
|
||||
"ask_price",
|
||||
]
|
||||
|
||||
|
||||
class TiingoWebSocketQueryParams(WebSocketQueryParams):
|
||||
"""Tiingo WebSocket query parameters."""
|
||||
|
||||
__json_schema_extra__ = {
|
||||
"symbol": {"multiple_items_allowed": True},
|
||||
"asset_type": {
|
||||
"multiple_items_allowed": False,
|
||||
"choices": ["stock", "fx", "crypto"],
|
||||
},
|
||||
"feed": {
|
||||
"multiple_items_allowed": False,
|
||||
"choices": ["trade", "trade_and_quote"],
|
||||
},
|
||||
}
|
||||
|
||||
symbol: str = Field(
|
||||
description=QUERY_DESCRIPTIONS.get("symbol", "") + "Use '*' for all symbols.",
|
||||
)
|
||||
asset_type: Literal["stock", "fx", "crypto"] = Field(
|
||||
default="crypto",
|
||||
description="The asset type for the feed.",
|
||||
)
|
||||
feed: Literal["trade", "trade_and_quote"] = Field(
|
||||
default="trade_and_quote",
|
||||
description="The type of data feed to subscribe to. FX only supports quote.",
|
||||
)
|
||||
|
||||
|
||||
class TiingoWebSocketData(WebSocketData):
|
||||
"""Tiingo WebSocket data model."""
|
||||
|
||||
timestamp: Optional[int] = Field(
|
||||
default=None,
|
||||
description="Nanoseconds since POSIX time UTC.",
|
||||
)
|
||||
type: Literal["quote", "trade", "break"] = Field(
|
||||
description="The type of data.",
|
||||
)
|
||||
exchange: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The exchange of the data. Only for crypto.",
|
||||
)
|
||||
bid_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the bid.",
|
||||
)
|
||||
bid_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The price of the bid.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
mid_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The mid price.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
ask_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The price of the ask.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
ask_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the ask.",
|
||||
)
|
||||
last_price: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The last trade price.",
|
||||
json_schema_extra={"x-unit_measurement": "currency"},
|
||||
)
|
||||
last_size: Optional[float] = Field(
|
||||
default=None,
|
||||
description="The size of the trade.",
|
||||
)
|
||||
halted: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="If the asset is halted. Only for stock.",
|
||||
)
|
||||
after_hours: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="If the data is after hours. Only for stock.",
|
||||
)
|
||||
sweep_order: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="If the order is an intermarket sweep order. Only for stock.",
|
||||
)
|
||||
oddlot: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="If the order is an oddlot. Only for stock.",
|
||||
)
|
||||
nms_rule: Optional[bool] = Field(
|
||||
default=None,
|
||||
description="True if the order is not subject to NMS Rule 611. Only for stock.",
|
||||
)
|
||||
|
||||
@field_validator("type", mode="before", check_fields=False)
|
||||
def _valiidate_data_type(cls, v):
|
||||
"""Validate the data type."""
|
||||
return (
|
||||
"quote" if v == "Q" else "trade" if v == "T" else "break" if v == "B" else v
|
||||
)
|
||||
|
||||
@field_validator("date", mode="before", check_fields=False)
|
||||
def _validate_date(cls, v):
|
||||
"""Validate the date."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from pytz import timezone
|
||||
|
||||
if isinstance(v, str):
|
||||
return datetime.fromisoformat(v)
|
||||
try:
|
||||
return datetime.fromtimestamp(v / 1000)
|
||||
except Exception:
|
||||
if isinstance(v, (int, float)):
|
||||
# Check if the timestamp is in nanoseconds and convert to seconds
|
||||
if v > 1e12:
|
||||
v = v / 1e9 # Convert nanoseconds to seconds
|
||||
dt = datetime.fromtimestamp(v)
|
||||
dt = timezone("America/New_York").localize(dt)
|
||||
return dt
|
||||
return v
|
||||
|
||||
|
||||
class TiingoWebSocketConnection(WebSocketConnection):
|
||||
"""Tiingo WebSocket connection model."""
|
||||
|
||||
|
||||
class TiingoWebSocketFetcher(
|
||||
Fetcher[TiingoWebSocketQueryParams, TiingoWebSocketConnection]
|
||||
):
|
||||
"""Tiingo WebSocket model."""
|
||||
|
||||
@staticmethod
|
||||
def transform_query(params: dict[str, Any]) -> TiingoWebSocketQueryParams:
|
||||
"""Transform the query parameters."""
|
||||
asset_type = params.get("asset_type")
|
||||
feed = params.get("feed")
|
||||
|
||||
if asset_type == "fx" and feed == "trade":
|
||||
raise ValueError("FX only supports quote feed.")
|
||||
|
||||
return TiingoWebSocketQueryParams(**params)
|
||||
|
||||
@staticmethod
|
||||
async def aextract_data(
|
||||
query: TiingoWebSocketQueryParams,
|
||||
credentials: Optional[dict[str, str]],
|
||||
**kwargs: Any,
|
||||
) -> WebSocketClient:
|
||||
"""Initiailze the WebSocketClient and connect."""
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from asyncio import sleep
|
||||
|
||||
api_key = credentials.get("tiingo_token") if credentials else ""
|
||||
url = URL_MAP[query.asset_type]
|
||||
threshold_level = (
|
||||
5
|
||||
if query.asset_type == "fx" or query.feed == "trade"
|
||||
else (
|
||||
2
|
||||
if query.asset_type == "crypto" and query.feed == "trade_and_quote"
|
||||
else 0
|
||||
)
|
||||
)
|
||||
|
||||
symbol = query.symbol.lower()
|
||||
|
||||
kwargs = {
|
||||
"url": url,
|
||||
"api_key": api_key,
|
||||
"threshold_level": threshold_level,
|
||||
}
|
||||
|
||||
client = WebSocketClient(
|
||||
name=query.name,
|
||||
module="openbb_tiingo.utils.websocket_client",
|
||||
symbol=symbol.lower(),
|
||||
limit=query.limit,
|
||||
results_file=query.results_file,
|
||||
table_name=query.table_name,
|
||||
save_results=query.save_results,
|
||||
data_model=TiingoWebSocketData,
|
||||
sleep_time=query.sleep_time,
|
||||
broadcast_host=query.broadcast_host,
|
||||
broadcast_port=query.broadcast_port,
|
||||
auth_token=query.auth_token,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
try:
|
||||
client.connect()
|
||||
# Unhandled exceptions are caught and raised as OpenBBError
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
client.disconnect()
|
||||
raise OpenBBError(e) from e
|
||||
|
||||
# Wait for the connection to be established before returning.
|
||||
await sleep(2)
|
||||
|
||||
if client.is_running:
|
||||
return client
|
||||
|
||||
client.disconnect()
|
||||
raise OpenBBError("Failed to connect to the WebSocket.")
|
||||
|
||||
@staticmethod
|
||||
def transform_data(
|
||||
data: WebSocketClient,
|
||||
query: TiingoWebSocketQueryParams,
|
||||
**kwargs: Any,
|
||||
) -> TiingoWebSocketConnection:
|
||||
"""Return the client as an instance of Data."""
|
||||
return TiingoWebSocketConnection(client=data)
|
||||
@@ -0,0 +1,278 @@
|
||||
"""FMP WebSocket server."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
|
||||
import websockets
|
||||
from openbb_core.provider.utils.errors import UnauthorizedError
|
||||
from openbb_tiingo.models.websocket_connection import TiingoWebSocketData
|
||||
from openbb_websockets.helpers import (
|
||||
MessageQueue,
|
||||
get_logger,
|
||||
handle_termination_signal,
|
||||
parse_kwargs,
|
||||
write_to_db,
|
||||
)
|
||||
|
||||
# These are the data array definitions.
|
||||
IEX_FIELDS = [
|
||||
"type",
|
||||
"date",
|
||||
"timestamp",
|
||||
"symbol",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_price",
|
||||
"ask_size",
|
||||
"last_price",
|
||||
"last_size",
|
||||
"halted",
|
||||
"after_hours",
|
||||
"sweep_order",
|
||||
"oddlot",
|
||||
"nms_rule",
|
||||
]
|
||||
FX_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_price",
|
||||
"ask_size",
|
||||
"ask_price",
|
||||
]
|
||||
CRYPTO_TRADE_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"exchange",
|
||||
"last_size",
|
||||
"last_price",
|
||||
]
|
||||
CRYPTO_QUOTE_FIELDS = [
|
||||
"type",
|
||||
"symbol",
|
||||
"date",
|
||||
"exchange",
|
||||
"bid_size",
|
||||
"bid_price",
|
||||
"mid_price",
|
||||
"ask_size",
|
||||
"ask_price",
|
||||
]
|
||||
subscription_id = None
|
||||
queue = MessageQueue()
|
||||
logger = get_logger("openbb.websocket.tiingo")
|
||||
kwargs = parse_kwargs()
|
||||
|
||||
|
||||
# Subscribe and unsubscribe events are handled in a separate connection using the subscription_id set by the login event.
|
||||
async def update_symbols(symbol, event):
|
||||
"""Update the symbols to subscribe to."""
|
||||
url = kwargs["url"]
|
||||
|
||||
if not subscription_id:
|
||||
logger.error(
|
||||
"PROVIDER ERROR: Must be assigned a subscription ID to update symbols. Try logging in."
|
||||
)
|
||||
return
|
||||
|
||||
update_event = {
|
||||
"eventName": event,
|
||||
"authorization": kwargs["api_key"],
|
||||
"eventData": {
|
||||
"subscriptionId": subscription_id,
|
||||
"tickers": symbol,
|
||||
},
|
||||
}
|
||||
|
||||
async with websockets.connect(url) as websocket:
|
||||
await websocket.send(json.dumps(update_event))
|
||||
response = await websocket.recv()
|
||||
message = json.loads(response)
|
||||
if message.get("response", {}).get("code") != 200:
|
||||
logger.error(f"PROVIDER ERROR: {message}")
|
||||
else:
|
||||
msg = (
|
||||
f"PROVIDER INFO: {message.get('response', {}).get('message')}. "
|
||||
f"Subscribed to symbols: {message.get('data', {}).get('tickers')}"
|
||||
)
|
||||
logger.info(msg)
|
||||
|
||||
|
||||
async def read_stdin_and_update_symbols():
|
||||
"""Read from stdin and update symbols."""
|
||||
while True:
|
||||
line = await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)
|
||||
sys.stdin.flush()
|
||||
|
||||
if not line:
|
||||
break
|
||||
|
||||
line = json.loads(line.strip())
|
||||
|
||||
if line:
|
||||
symbol = line.get("symbol")
|
||||
event = line.get("event")
|
||||
await update_symbols(symbol, event)
|
||||
|
||||
|
||||
async def process_message(message, results_path, table_name, limit):
|
||||
result = {}
|
||||
data_message = {}
|
||||
message = json.loads(message)
|
||||
msg = ""
|
||||
if message.get("messageType") == "E":
|
||||
response = message.get("response", {})
|
||||
msg = f"PROVIDER ERROR: {response.get('code')}: {response.get('message')}"
|
||||
logger.error(msg)
|
||||
sys.exit(1)
|
||||
elif message.get("messageType") == "I":
|
||||
response = message.get("response", {})
|
||||
|
||||
if response.get("code") != 200:
|
||||
msg = (
|
||||
f"PROVIDER ERROR: {response.get('code')}: {response.get('message')}"
|
||||
)
|
||||
logger.error(msg)
|
||||
raise UnauthorizedError(msg)
|
||||
|
||||
if response.get("code") == 200:
|
||||
msg = f"PROVIDER INFO: Authorization: {response.get('message')}"
|
||||
logger.info(msg)
|
||||
if message.get("data", {}).get("subscriptionId"):
|
||||
global subscription_id
|
||||
|
||||
subscription_id = message["data"]["subscriptionId"]
|
||||
|
||||
if "tickers" in message.get("data", {}):
|
||||
tickers = message["data"]["tickers"]
|
||||
threshold_level = message["data"].get("thresholdLevel")
|
||||
msg = f"PROVIDER INFO: Subscribed to {tickers} with threshold level {threshold_level}"
|
||||
logger.info(msg)
|
||||
elif message.get("messageType") == "A":
|
||||
data = message.get("data", [])
|
||||
service = message.get("service")
|
||||
if service == "iex":
|
||||
data_message = {IEX_FIELDS[i]: data[i] for i in range(len(data))}
|
||||
elif service == "fx":
|
||||
data_message = {FX_FIELDS[i]: data[i] for i in range(len(data))}
|
||||
elif service == "crypto_data":
|
||||
if data[0] == "T":
|
||||
data_message = {
|
||||
CRYPTO_TRADE_FIELDS[i]: data[i] for i in range(len(data))
|
||||
}
|
||||
elif data[0] == "Q":
|
||||
data_message = {
|
||||
CRYPTO_QUOTE_FIELDS[i]: data[i] for i in range(len(data))
|
||||
}
|
||||
else:
|
||||
return
|
||||
|
||||
try:
|
||||
result = TiingoWebSocketData.model_validate(data_message).model_dump_json(
|
||||
exclude_none=True, exclude_unset=True
|
||||
)
|
||||
except Exception as e:
|
||||
msg = f"PROVIDER ERROR: Error validating data: {e}"
|
||||
logger.error(msg)
|
||||
return
|
||||
if result:
|
||||
await write_to_db(result, results_path, table_name, limit)
|
||||
return
|
||||
|
||||
|
||||
async def connect_and_stream(
|
||||
url, symbol, threshold_level, api_key, results_path, table_name, limit
|
||||
):
|
||||
"""Connect to the WebSocket and stream data to file."""
|
||||
|
||||
handler_task = asyncio.create_task(
|
||||
queue.process_queue(
|
||||
lambda message: process_message(message, results_path, table_name, limit)
|
||||
)
|
||||
)
|
||||
|
||||
stdin_task = asyncio.create_task(read_stdin_and_update_symbols())
|
||||
|
||||
if isinstance(symbol, str):
|
||||
ticker = symbol.lower().split(",")
|
||||
|
||||
subscribe_event = {
|
||||
"eventName": "subscribe",
|
||||
"authorization": api_key,
|
||||
"eventData": {"thresholdLevel": threshold_level, "tickers": ticker},
|
||||
}
|
||||
try:
|
||||
async with websockets.connect(
|
||||
url, ping_interval=20, ping_timeout=20, max_queue=1000
|
||||
) as websocket:
|
||||
logger.info("PROVIDER INFO: WebSocket connection established.")
|
||||
await websocket.send(json.dumps(subscribe_event))
|
||||
while True:
|
||||
message = await websocket.recv()
|
||||
await queue.enqueue(message)
|
||||
|
||||
except websockets.ConnectionClosed as e:
|
||||
msg = f"PROVIDER INFO: The WebSocket connection was closed -> {e.reason}"
|
||||
logger.info(msg)
|
||||
# Attempt to reopen the connection
|
||||
await asyncio.sleep(5)
|
||||
await connect_and_stream(
|
||||
url, symbol, threshold_level, api_key, results_path, table_name, limit
|
||||
)
|
||||
|
||||
except websockets.WebSocketException as e:
|
||||
logger.error(e)
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
msg = f"PROVIDER ERROR: Unexpected error -> {e}"
|
||||
logger.error(msg)
|
||||
sys.exit(1)
|
||||
|
||||
finally:
|
||||
handler_task.cancel()
|
||||
await handler_task
|
||||
stdin_task.cancel()
|
||||
await stdin_task
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
loop.add_signal_handler(sig, handle_termination_signal, logger)
|
||||
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
connect_and_stream(
|
||||
kwargs["url"],
|
||||
kwargs["symbol"],
|
||||
kwargs["threshold_level"],
|
||||
kwargs["api_key"],
|
||||
os.path.abspath(kwargs["results_file"]),
|
||||
kwargs["table_name"],
|
||||
kwargs.get("limit", None),
|
||||
),
|
||||
loop,
|
||||
)
|
||||
loop.run_forever()
|
||||
|
||||
except (KeyboardInterrupt, websockets.ConnectionClosed):
|
||||
logger.error("PROVIDER ERROR: WebSocket connection closed")
|
||||
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
msg = f"PROVIDER ERROR: {e.args[0]}"
|
||||
logger.error(msg)
|
||||
|
||||
finally:
|
||||
sys.exit(0)
|
||||
3
openbb_platform/pyproject.toml
vendored
3
openbb_platform/pyproject.toml
vendored
@@ -61,6 +61,7 @@ openbb-charting = { version = "^2.2.4", optional = true }
|
||||
openbb-econometrics = { version = "^1.4.4", optional = true }
|
||||
openbb-quantitative = { version = "^1.3.4", optional = true }
|
||||
openbb-technical = { version = "^1.3.4", optional = true }
|
||||
openbb-websockets = { version = "^1.3.4", optional = true }
|
||||
|
||||
[tool.poetry.extras]
|
||||
alpha_vantage = ["openbb-alpha-vantage"]
|
||||
@@ -80,6 +81,7 @@ stockgrid = ["openbb-stockgrid"]
|
||||
technical = ["openbb-technical"]
|
||||
tmx = ["openbb-tmx"]
|
||||
tradier = ["openbb-tradier"]
|
||||
websockets = ["openbb-websockets"]
|
||||
wsj = ["openbb-wsj"]
|
||||
|
||||
|
||||
@@ -101,6 +103,7 @@ all = [
|
||||
"openbb-technical",
|
||||
"openbb-tmx",
|
||||
"openbb-tradier",
|
||||
"openbb-websockets",
|
||||
"openbb-wsj",
|
||||
]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user