221 lines
7.8 KiB
Python
221 lines
7.8 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)
|
|
PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=([^\s]+)\s+Position=([^\s]+)\s+Qty=(\d+)", 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[datetime, Path]] = None
|
|
for path in log_dir.rglob("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
|
|
stamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
|
|
if newest is None or stamp > newest[0]:
|
|
newest = (stamp, path)
|
|
return newest[1] if newest else None
|
|
|
|
|
|
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
|
|
|
|
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
|
|
|
|
return None
|
|
|
|
|
|
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
|