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

302 lines
11 KiB
Python

"""Read-only parsers for NT8 SDK dashboard artifacts."""
from __future__ import annotations
import json
import os
import re
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
SESSION_FILE_RE = re.compile(r"^session_(\d{8})_(\d{6})\.log$", re.IGNORECASE)
TRADES_FILE_RE = re.compile(r"^trades_Simple_ORB_NT8_(\d{8})\.jsonl$", re.IGNORECASE)
PROVENANCE_FILE_RE = re.compile(r"^provenance_Simple_ORB_NT8_(\d{8})_(\d{6})\.json$", re.IGNORECASE)
SETTINGS_FILE_RE = re.compile(r"^settings_Simple_ORB_NT8_(\d{8})_(\d{6})\.txt$", re.IGNORECASE)
LOG_TS_RE = re.compile(r"^\[(\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?)\]\s*(.*)$")
SESSION_START_RE = re.compile(r"=== SESSION START\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+===", re.IGNORECASE)
SUBMIT_RE = re.compile(r"\bSUBMIT\b\s*(.*)$", re.IGNORECASE)
FILL_RE = re.compile(r"\bFILL\b\s+(Long|Short)\s+(\d+)\s+@\s+([0-9.]+)", re.IGNORECASE)
BREAKEVEN_RE = re.compile(r"\bBREAKEVEN\b\s*(.*)$", re.IGNORECASE)
RUNNER_CLOSED_RE = re.compile(r"RUNNER closed", re.IGNORECASE)
CONNECTION_RE = re.compile(r"CONNECTION\s+(LOST|RESTORED)", re.IGNORECASE)
CONNECTION_STATE_RE = re.compile(r"^ConnectionLost\s*:\s*(True|False)$", re.IGNORECASE)
PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=([^\s]+)\s+Position=([^\s]+)\s+Qty=(\d+)", re.IGNORECASE)
ACCOUNT_RE = re.compile(r"^Account\s*:\s*(.+)$", re.IGNORECASE)
SYMBOL_RE = re.compile(r"^Symbol\s*:\s*(.+)$", re.IGNORECASE)
MODE_RE = re.compile(r"^Mode\s*:\s*(.+)$", re.IGNORECASE)
DATA_SERIES_RE = re.compile(r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=([^\s]+)\s+HistoricalBarsLoaded=([^\s]+)", re.IGNORECASE)
FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE)
FACTOR_STATUS_RE = re.compile(r"([A-Za-z0-9_]+)=(SATISFIED|FAILED|UNSATISFIED)\s*\((\d+)/(\d+)\s+daily bars\)", re.IGNORECASE)
def expand_path(raw_path: str) -> Path:
return Path(os.path.expanduser(os.path.expandvars(raw_path)))
def newest_session_file(log_dir: Path) -> Optional[Path]:
newest: Optional[Tuple[float, str, Path]] = None
for path in log_dir.glob("session_*.log") if log_dir.exists() else []:
if not path.is_file():
continue
match = SESSION_FILE_RE.match(path.name)
if match is None:
continue
try:
mtime = path.stat().st_mtime
except OSError:
continue
if newest is None or (mtime, path.name) > (newest[0], newest[1]):
newest = (mtime, path.name, path)
return newest[2] if newest else None
def session_key(path: Path, lines: List[str]) -> str:
for line in lines:
timestamp, message = split_log_line(line)
start = SESSION_START_RE.search(message)
if start:
return start.group(1)
return path.stem
def newest_matching(log_dir: Path, pattern: str, regex: re.Pattern[str]) -> Optional[Path]:
newest: Optional[Tuple[datetime, Path]] = None
for path in log_dir.rglob(pattern) if log_dir.exists() else []:
if not path.is_file():
continue
match = regex.match(path.name)
if match is None:
continue
if len(match.groups()) >= 2:
stamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
else:
stamp = datetime.strptime(match.group(1), "%Y%m%d")
if newest is None or stamp > newest[0]:
newest = (stamp, path)
return newest[1] if newest else None
def today_trades_file(log_dir: Path) -> Optional[Path]:
today = datetime.now().strftime("%Y%m%d")
candidates = sorted(path for path in log_dir.rglob("trades_Simple_ORB_NT8_{0}.jsonl".format(today)) if path.is_file()) if log_dir.exists() else []
return candidates[-1] if candidates else newest_matching(log_dir, "trades_Simple_ORB_NT8_*.jsonl", TRADES_FILE_RE)
def latest_provenance_file(log_dir: Path) -> Optional[Path]:
return newest_matching(log_dir, "provenance_Simple_ORB_NT8_*.json", PROVENANCE_FILE_RE)
def latest_settings_file(log_dir: Path) -> Optional[Path]:
return newest_matching(log_dir, "settings_Simple_ORB_NT8_*.txt", SETTINGS_FILE_RE)
def split_log_line(line: str) -> Tuple[Optional[str], str]:
match = LOG_TS_RE.match(line)
if match is None:
return None, line.strip()
return match.group(1), match.group(2).strip()
def parse_money(value: str) -> float:
text = value.strip().replace("$", "").replace(",", "")
if text.startswith("(") and text.endswith(")"):
text = "-" + text[1:-1]
try:
return float(text)
except ValueError:
return 0.0
def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]:
timestamp, message = split_log_line(line)
base: Dict[str, Any] = {"timestamp": timestamp, "line": line, "source": str(path)}
start = SESSION_START_RE.search(message)
if start:
payload = dict(base)
payload.update({"type": "SESSION START", "session_start": start.group(1)})
return payload
submit = SUBMIT_RE.search(message)
if submit:
payload = dict(base)
payload.update({"type": "SUBMIT", "detail": submit.group(1).strip()})
return payload
fill = FILL_RE.search(message)
if fill:
payload = dict(base)
payload.update({"type": "FILL", "side": fill.group(1), "quantity": int(fill.group(2)), "price": float(fill.group(3))})
return payload
breakeven = BREAKEVEN_RE.search(message)
if breakeven:
payload = dict(base)
payload.update({"type": "BREAKEVEN", "detail": breakeven.group(1).strip()})
return payload
if RUNNER_CLOSED_RE.search(message):
payload = dict(base)
payload.update({"type": "RUNNER CLOSED"})
return payload
connection = CONNECTION_RE.search(message)
if connection:
payload = dict(base)
payload.update({"type": "CONNECTION {0}".format(connection.group(1).upper()), "status": connection.group(1).upper()})
return payload
connection_state = CONNECTION_STATE_RE.search(message)
if connection_state:
payload = dict(base)
payload.update({"type": "CONNECTION STATE", "status": "LOST" if connection_state.group(1).lower() == "true" else "OK"})
return payload
pnl = PNL_RE.search(message)
if pnl:
payload = dict(base)
payload.update({"type": "PNL_UPDATE", "daily_pnl": parse_money(pnl.group(1)), "position": pnl.group(2), "quantity": int(pnl.group(3))})
return payload
account = ACCOUNT_RE.search(message)
if account:
payload = dict(base)
payload.update({"type": "ACCOUNT", "account": account.group(1).strip()})
return payload
symbol = SYMBOL_RE.search(message)
if symbol:
payload = dict(base)
payload.update({"type": "SYMBOL", "symbol": symbol.group(1).strip()})
return payload
mode = MODE_RE.search(message)
if mode:
payload = dict(base)
payload.update({"type": "MODE", "mode": mode.group(1).strip()})
return payload
return None
def parse_readiness(lines: List[str]) -> Dict[str, Any]:
data_series: Dict[int, Dict[str, Any]] = {}
factors: Dict[str, Dict[str, Any]] = {}
context = ""
bars_required = ""
for line in lines:
timestamp, message = split_log_line(line)
if message.startswith("Historical readiness"):
context = message
required = re.search(r"BarsRequiredToTrade=([^\s]+)", message, re.IGNORECASE)
if required:
bars_required = required.group(1)
data_match = DATA_SERIES_RE.search(message)
if data_match:
index = int(data_match.group(1))
data_series[index] = {
"index": index,
"type": data_match.group(2),
"days_to_load": data_match.group(3),
"historical_bars_loaded": data_match.group(4),
}
warmup = FACTOR_WARMUP_RE.search(message)
if warmup:
for factor in FACTOR_STATUS_RE.finditer(warmup.group(1)):
factors[factor.group(1)] = {
"name": factor.group(1),
"status": factor.group(2).upper(),
"loaded": int(factor.group(3)),
"required": int(factor.group(4)),
}
return {
"context": context,
"bars_required_to_trade": bars_required,
"data_series": [data_series[index] for index in sorted(data_series.keys())],
"factors": [factors[name] for name in sorted(factors.keys())],
}
def read_new_complete_lines(path: Path, offset: int, partial: str) -> Tuple[List[str], int, str]:
try:
size = path.stat().st_size
if size < offset:
offset = 0
partial = ""
with path.open("rb") as handle:
handle.seek(offset)
chunk = handle.read()
offset = handle.tell()
except OSError:
return [], offset, partial
if not chunk:
return [], offset, partial
text = partial + chunk.decode("utf-8", errors="replace")
pieces = text.splitlines(True)
lines: List[str] = []
next_partial = ""
for piece in pieces:
if piece.endswith("\n") or piece.endswith("\r"):
lines.append(piece.rstrip("\r\n"))
else:
next_partial = piece
return lines, offset, next_partial
def tail_lines(path: Optional[Path], limit: int = 300) -> List[str]:
if path is None or not path.exists():
return []
try:
with path.open("r", encoding="utf-8", errors="replace") as handle:
lines = handle.read().splitlines()
except OSError:
return []
return lines[-limit:]
def read_trades(path: Optional[Path]) -> List[Dict[str, Any]]:
if path is None or not path.exists():
return []
records: List[Dict[str, Any]] = []
try:
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
text = line.strip()
if not text:
continue
try:
records.append(json.loads(text))
except ValueError:
continue
except OSError:
return []
return records
def read_json(path: Optional[Path]) -> Optional[Dict[str, Any]]:
if path is None or not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def read_settings(path: Optional[Path]) -> Dict[str, str]:
if path is None or not path.exists():
return {}
values: Dict[str, str] = {}
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
if not line or line.startswith("===") or line.startswith("---"):
continue
if ":" not in line:
continue
key, value = line.split(":", 1)
values[key.strip()] = value.strip()
except OSError:
return {}
return values