Files
nt8-sdk/tools/dashboard/server.py

353 lines
14 KiB
Python

#!/usr/bin/env python3
"""Localhost-only read-only dashboard server."""
from __future__ import annotations
import argparse
import json
import mimetypes
import os
import sys
import threading
import time
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse
import parsers
from notify import AppriseNotifier
from state import DashboardState
BASE_DIR = Path(__file__).resolve().parent
DEFAULT_CONFIG_PATH = BASE_DIR / "config.example.json"
ALLOWED_METHODS = {"GET", "HEAD", "OPTIONS"}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run the NT8 SDK read-only dashboard server.")
parser.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), help="Path to dashboard config JSON")
parser.add_argument("--host", help="Override host; only 127.0.0.1 is allowed")
parser.add_argument("--port", type=int, help="Override port")
return parser.parse_args()
def load_config(path: Path) -> Dict[str, Any]:
try:
return json.loads(path.read_text(encoding="utf-8"))
except OSError:
return json.loads(DEFAULT_CONFIG_PATH.read_text(encoding="utf-8"))
except ValueError as ex:
raise RuntimeError("Invalid dashboard config: {0}".format(ex))
def resolve_state_path(config: Dict[str, Any]) -> Path:
raw = str(config.get("state_file") or "dashboard_state.json")
candidate = parsers.expand_path(raw)
if candidate.is_absolute():
return candidate
return BASE_DIR / candidate
def notifications_enabled(config: Dict[str, Any], event_key: str) -> bool:
notifications = config.get("notifications", {}) if isinstance(config.get("notifications", {}), dict) else {}
events = notifications.get("events", {}) if isinstance(notifications.get("events", {}), dict) else {}
return bool(events.get(event_key, True))
class DashboardRuntime:
def __init__(self, config: Dict[str, Any]) -> None:
self.config = config
self.log_dir = parsers.expand_path(str(config.get("log_dir") or ""))
self.state = DashboardState(resolve_state_path(config))
self.notifier = AppriseNotifier(config)
self.lock = threading.Lock()
self.stop_event = threading.Event()
self.latest_events: List[Dict[str, Any]] = []
self.live_state: Dict[str, Any] = {}
self.trades: List[Dict[str, Any]] = []
self.provenance: Optional[Dict[str, Any]] = None
self.settings: Dict[str, str] = {}
self.raw_tail: List[str] = []
self.readiness: Dict[str, Any] = {}
self.current_session_file: Optional[str] = None
self.polling = config.get("polling", {}) if isinstance(config.get("polling", {}), dict) else {}
self.session_poll_seconds = float(self.polling.get("session_log_seconds", 2))
self.trades_poll_seconds = float(self.polling.get("trades_seconds", 10))
self.provenance_poll_seconds = float(self.polling.get("provenance_seconds", 10))
self._next_trades_poll = 0.0
self._next_provenance_poll = 0.0
self._thread = threading.Thread(target=self._run, name="dashboard-poller", daemon=True)
def start(self) -> None:
self._thread.start()
def stop(self) -> None:
self.stop_event.set()
self._thread.join(timeout=5)
def snapshot(self) -> Dict[str, Any]:
with self.lock:
return {
"log_dir": str(self.log_dir),
"session_file": self.current_session_file,
"current_session": self.state.current_session,
"live_state": self.live_state,
"readiness": dict(self.readiness),
"events": list(self.latest_events[-100:]),
"trades": list(self.trades),
"provenance": self.provenance,
"settings": dict(self.settings),
"raw_tail": list(self.raw_tail),
"polling": {
"session_log_seconds": self.session_poll_seconds,
"trades_seconds": self.trades_poll_seconds,
"provenance_seconds": self.provenance_poll_seconds,
},
"notifications": self.notifier.status(),
}
def _run(self) -> None:
while not self.stop_event.is_set():
now = time.time()
self._poll_session_log()
if now >= self._next_trades_poll:
self._poll_trades()
self._next_trades_poll = now + self.trades_poll_seconds
if now >= self._next_provenance_poll:
self._poll_provenance()
self._next_provenance_poll = now + self.provenance_poll_seconds
self.stop_event.wait(self.session_poll_seconds)
def _poll_session_log(self) -> None:
path = parsers.newest_session_file(self.log_dir)
if path is None:
return
raw_tail = parsers.tail_lines(path)
session_key = parsers.session_key(path, raw_tail)
self.state.rollover_session(session_key)
with self.lock:
self.raw_tail = raw_tail
self.current_session_file = str(path)
self.readiness = parsers.parse_readiness(raw_tail)
self._refresh_live_state_from_tail(path, raw_tail)
offset = self.state.get_offset(path)
if offset is None:
try:
offset = path.stat().st_size
except OSError:
offset = 0
self.state.set_offset(path, offset)
self.state.save()
partial = self.state.get_partial(path)
lines, next_offset, next_partial = parsers.read_new_complete_lines(path, offset, partial)
self.state.set_offset(path, next_offset)
self.state.set_partial(path, next_partial)
for line in lines:
event = parsers.parse_session_event(path, line)
if event is not None:
self._handle_event(event)
self.state.save()
def _refresh_live_state_from_tail(self, path: Path, lines: List[str]) -> None:
for line in lines:
event = parsers.parse_session_event(path, line)
if event is not None:
self._apply_event(event)
def _poll_trades(self) -> None:
path = parsers.today_trades_file(self.log_dir)
trades = parsers.read_trades(path)
with self.lock:
self.trades = trades
def _poll_provenance(self) -> None:
provenance_path = parsers.latest_provenance_file(self.log_dir)
settings_path = parsers.latest_settings_file(self.log_dir)
provenance = parsers.read_json(provenance_path)
settings = parsers.read_settings(settings_path)
with self.lock:
self.provenance = provenance
self.settings = settings
def _handle_event(self, event: Dict[str, Any]) -> None:
self._apply_event(event)
if str(event.get("type") or "") == "PNL_UPDATE":
self._handle_pnl_milestones(event)
with self.lock:
self.latest_events.append(event)
self.latest_events = self.latest_events[-500:]
self._notify_event(event)
def _apply_event(self, event: Dict[str, Any]) -> None:
event_type = str(event.get("type") or "")
if event_type == "SESSION START":
session_key = str(event.get("session_start") or event.get("source") or "unknown")
self.state.rollover_session(session_key)
self.live_state["session_start"] = event.get("session_start")
elif event_type == "ACCOUNT":
self.live_state["account"] = event.get("account")
elif event_type == "SYMBOL":
self.live_state["symbol"] = event.get("symbol")
elif event_type == "MODE":
self.live_state["mode"] = event.get("mode")
elif event_type == "PNL_UPDATE":
self.live_state["daily_pnl"] = event.get("daily_pnl")
self.live_state["position"] = event.get("position")
self.live_state["quantity"] = event.get("quantity")
elif event_type.startswith("CONNECTION"):
self.live_state["connection"] = event.get("status")
elif event_type == "FILL":
self.live_state["last_fill"] = event
elif event_type == "SUBMIT":
self.live_state["last_submit"] = event
elif event_type == "BREAKEVEN":
self.live_state["last_breakeven"] = event
def _handle_pnl_milestones(self, event: Dict[str, Any]) -> None:
if not notifications_enabled(self.config, "daily_pnl_milestones"):
return
session_key = self.state.current_session or str(event.get("source") or "unknown")
pnl = float(event.get("daily_pnl") or 0.0)
notifications = self.config.get("notifications", {}) if isinstance(self.config.get("notifications", {}), dict) else {}
milestones = notifications.get("daily_pnl_milestones", [])
for milestone in milestones:
try:
value = float(milestone)
except (TypeError, ValueError):
continue
crossed = (value >= 0 and pnl >= value) or (value < 0 and pnl <= value)
if crossed and not self.state.seen_milestone(session_key, value):
self.state.add_milestone(session_key, value)
payload = dict(event)
payload["type"] = "DAILY PNL MILESTONE"
payload["milestone"] = value
self._notify_event(payload)
def _notify_event(self, event: Dict[str, Any]) -> None:
event_type = str(event.get("type") or "")
key_map = {
"SUBMIT": "submit",
"FILL": "fill",
"BREAKEVEN": "breakeven",
"CONNECTION LOST": "connection",
"CONNECTION RESTORED": "connection",
"DAILY PNL MILESTONE": "daily_pnl_milestones",
}
config_key = key_map.get(event_type)
if config_key is None or not notifications_enabled(self.config, config_key):
return
if not self.notifier.enabled or not self.notifier.available:
return
fingerprint = "{0}|{1}|{2}|{3}".format(event_type, event.get("source"), event.get("line"), event.get("milestone"))
if self.state.seen_fingerprint(fingerprint):
return
self.state.add_fingerprint(fingerprint)
self.notifier.send(event)
class DashboardHandler(BaseHTTPRequestHandler):
runtime: DashboardRuntime
def do_GET(self) -> None:
parsed = urlparse(self.path)
if parsed.path == "/api/state":
self._send_json(self.runtime.snapshot())
return
if parsed.path == "/api/health":
self._send_json({"ok": True, "host": self.server.server_address[0], "methods": sorted(ALLOWED_METHODS)})
return
path = "/index.html" if parsed.path == "/" else parsed.path
self._send_static(path)
def do_HEAD(self) -> None:
self.send_response(HTTPStatus.OK)
self.end_headers()
def do_OPTIONS(self) -> None:
self.send_response(HTTPStatus.NO_CONTENT)
self.send_header("Allow", ", ".join(sorted(ALLOWED_METHODS)))
self.end_headers()
def do_POST(self) -> None:
self._method_not_allowed()
def do_PUT(self) -> None:
self._method_not_allowed()
def do_PATCH(self) -> None:
self._method_not_allowed()
def do_DELETE(self) -> None:
self._method_not_allowed()
def _method_not_allowed(self) -> None:
self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
self.send_header("Allow", ", ".join(sorted(ALLOWED_METHODS)))
self.end_headers()
def _send_json(self, payload: Dict[str, Any]) -> None:
data = json.dumps(payload, sort_keys=True).encode("utf-8")
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _send_static(self, request_path: str) -> None:
relative = request_path.lstrip("/").replace("/", os.sep)
candidate = (BASE_DIR / relative).resolve()
try:
candidate.relative_to(BASE_DIR)
except ValueError:
self.send_error(HTTPStatus.NOT_FOUND)
return
if not candidate.is_file():
self.send_error(HTTPStatus.NOT_FOUND)
return
data = candidate.read_bytes()
content_type = mimetypes.guess_type(str(candidate))[0] or "application/octet-stream"
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, format: str, *args: Any) -> None:
sys.stderr.write("dashboard: " + (format % args) + "\n")
def main() -> int:
args = parse_args()
try:
config = load_config(parsers.expand_path(args.config))
except RuntimeError as ex:
sys.stderr.write(str(ex) + "\n")
return 2
host = args.host or str(config.get("host") or "127.0.0.1")
if host != "127.0.0.1":
sys.stderr.write("dashboard: refusing to bind to {0}; only 127.0.0.1 is allowed\n".format(host))
return 2
port = args.port or int(config.get("port") or 8765)
runtime = DashboardRuntime(config)
DashboardHandler.runtime = runtime
server = ThreadingHTTPServer(("127.0.0.1", port), DashboardHandler)
runtime.start()
sys.stderr.write("dashboard: listening on http://127.0.0.1:{0}/\n".format(port))
try:
server.serve_forever()
except KeyboardInterrupt:
sys.stderr.write("dashboard: stopped\n")
finally:
runtime.stop()
server.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())