From f617574b160a2649eb92d627a4ff52851915e25f Mon Sep 17 00:00:00 2001 From: mo Date: Mon, 17 Aug 2026 12:20:42 -0400 Subject: [PATCH] fix: add DASH-003 live trades and session rows --- SPRINT_BOARD.md | 1 + TASK_DASH-003_PROMPT.md | 59 +++++++++++++++++++++ tools/dashboard/app.js | 2 +- tools/dashboard/parsers.py | 23 ++++++-- tools/dashboard/server.py | 104 +++++++++++++++++++++++++++++++++++-- 5 files changed, 180 insertions(+), 9 deletions(-) create mode 100644 TASK_DASH-003_PROMPT.md diff --git a/SPRINT_BOARD.md b/SPRINT_BOARD.md index 73267b8..573dc17 100644 --- a/SPRINT_BOARD.md +++ b/SPRINT_BOARD.md @@ -28,6 +28,7 @@ - Related: `docs/IDEAS_BACKLOG.md` (n8n AM Briefing — related but separate item), `NT8_SDK_Master_Document` Appendix B (Command Center spec — source of feature inspiration for external version). - **Extension (2026-08-16):** Add outbound notification module to the dashboard's Python server (NOT to the NinjaScript strategy) using Apprise for unified Discord/Notifiarr/ntfy/etc. delivery. Alerts on FILL, SUBMIT, BREAKEVEN, CONNECTION LOST/RESTORED, daily P&L milestones. Bind server to 127.0.0.1 only, read-only endpoints, no POST/write routes. Poll interval must be explicit/configurable: 1-2s for live session-log tail, 5-10s for trades table/config panel. - **Bugfix/Extension (2026-08-17):** Live server current-session selection now uses newest root-level `session_*.log` by file modification time and populates `current_session` even when notification offsets start at EOF. Dashboard adds a Bars/Days-Loaded panel from existing Historical readiness and FactorWarmup log lines. +- **[DASH-003] Bugfix/Extension (2026-08-17):** `/api/state` live trades now reads only the current session date's `trades_*.jsonl` instead of falling back to old historical trade records; `/api/state` also returns current-session rows/diagnostics so Daily Timeline, Config Integrity, Silent Day Explorer, and Decision/Defect headline populate without manual JSON load. **[DASH-002] Continuous Confluence & Regime Telemetry** | Weekend window 2026-08-16 | 🔵 ACTIVE - Scope: `src\` source change — adds `EnableStateTelemetry` parameter emitting periodic factor/regime state to session log (currently only logged at signal time). Additive observability only; existing SIGNAL/SUBMIT/FILL/PNL_UPDATE lines must remain byte-for-byte unaffected. diff --git a/TASK_DASH-003_PROMPT.md b/TASK_DASH-003_PROMPT.md new file mode 100644 index 0000000..e815b9a --- /dev/null +++ b/TASK_DASH-003_PROMPT.md @@ -0,0 +1,59 @@ +# TASK: DASH-003 — Fix live trades feed + add live session rows +# Staged: 2026-08-17 +# Sprint: Parallel Product Work — dashboard-only +# ───────────────────────────────────────────────────────────────── + +## Part 1 — BUGFIX: /api/state trades field is stale (priority) + +app.js's renderServerState() correctly feeds payload.trades from /api/state +into Trade Detail, Grade Distribution, and Provenance Health on every 5s +poll — this is NOT gated behind manual JSON load, it's already live by +design. But the server is currently returning only 2 old trade records +(matching pre-8/16 sentinel data) instead of today's actual fills from +today's trades_Simple_ORB_NT8_YYYYMMDD.jsonl. + +READ-FIRST: locate where server.py/parsers.py builds the `trades` field for +/api/state. Compare its file-selection logic against the current_session +fix already applied — confirm whether this is the same root cause (not +selecting the newest/today's trades_*.jsonl by date) or a separate issue +(e.g. reading a cached/fixed path, or filtering by a stale session_id). + +FIX: ensure /api/state's trades field always reflects the CURRENT day's +trades_*.jsonl, refreshed on the same poll cycle as everything else. + +VALIDATE: with a real trade present in today's trades file, confirm it +appears in Trade Detail/Grade Distribution/Provenance Health within one +poll cycle, without any manual action. + +## Part 2 — Live session rows (unblocks Daily Timeline, Config Integrity, +## Silent Day Explorer, and the Decision/Defect headline counts) + +renderServerState() in app.js currently calls: + render({ rows: [], diagnostics: [], trade_records: asArray(payload.trades) }) + +`rows: []` is hardcoded — these four sections structurally cannot populate +from the live server no matter what, since they all key off data.rows. + +Add a `rows` (or `sessions`) field to /api/state's response, built from the +CURRENT session's log + provenance file, matching the same row shape +logtriage.py's triage.json already produces for TOOL-001 rows (account, +instrument, bar_type, signals, submits, fills, net_pnl, config_hash, +code_version, reject_summaries). Reuse logtriage's parsing logic rather +than reimplementing it — import/call the existing module if feasible. + +Update app.js's renderServerState() to pass this real rows data instead of +the hardcoded empty array. + +Scope for this pass: CURRENT session only (today), not a full historical +rescan — that remains logtriage.py's job for multi-day analysis. This just +makes today's session visible live without a manual step. + +## VALIDATION +- Confirm Daily Timeline shows today's session with real signal/submit/ + fill/net_pnl counts, live, without loading any file. +- Confirm Config Integrity shows today's ConfigHash/CodeVersion. +- Confirm no regression to the manual "Load TOOL-001 JSON" path — it must + still work independently for historical/offline analysis. + +## GOVERNANCE +Track as [DASH-003] in SPRINT_BOARD.md. diff --git a/tools/dashboard/app.js b/tools/dashboard/app.js index ef8e7e7..b39335a 100644 --- a/tools/dashboard/app.js +++ b/tools/dashboard/app.js @@ -716,7 +716,7 @@ if (rawTail) { rawTail.textContent = asArray(payload.raw_tail).slice(-80).join("\n"); } - render({ rows: [], diagnostics: [], trade_records: asArray(payload.trades) }, "server state"); + render({ rows: asArray(payload.rows || payload.sessions), diagnostics: asArray(payload.diagnostics), trade_records: asArray(payload.trades) }, "server state"); } function loadServerState() { diff --git a/tools/dashboard/parsers.py b/tools/dashboard/parsers.py index d194d24..448c3b0 100644 --- a/tools/dashboard/parsers.py +++ b/tools/dashboard/parsers.py @@ -80,8 +80,12 @@ def newest_matching(log_dir: Path, pattern: str, regex: re.Pattern[str]) -> Opti 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) + return trades_file_for_date(log_dir, today) + + +def trades_file_for_date(log_dir: Path, yyyymmdd: str) -> Optional[Path]: + candidates = sorted(path for path in log_dir.glob("trades_Simple_ORB_NT8_{0}.jsonl".format(yyyymmdd)) if path.is_file()) if log_dir.exists() else [] + return candidates[-1] if candidates else None def latest_provenance_file(log_dir: Path) -> Optional[Path]: @@ -260,16 +264,27 @@ def read_trades(path: Optional[Path]) -> List[Dict[str, Any]]: if path is None or not path.exists(): return [] records: List[Dict[str, Any]] = [] + date = None + match = TRADES_FILE_RE.match(path.name) + if match: + raw = match.group(1) + date = "{0}-{1}-{2}".format(raw[0:4], raw[4:6], raw[6:8]) try: with path.open("r", encoding="utf-8", errors="replace") as handle: - for line in handle: + for line_number, line in enumerate(handle, start=1): text = line.strip() if not text: continue try: - records.append(json.loads(text)) + record = json.loads(text) except ValueError: continue + if isinstance(record, dict): + if date is not None and "date" not in record: + record["date"] = date + record.setdefault("path", path.name) + record.setdefault("line", line_number) + records.append(record) except OSError: return [] return records diff --git a/tools/dashboard/server.py b/tools/dashboard/server.py index 7ba6603..2eb60e7 100644 --- a/tools/dashboard/server.py +++ b/tools/dashboard/server.py @@ -22,6 +22,13 @@ from state import DashboardState BASE_DIR = Path(__file__).resolve().parent +LOGTRIAGE_DIR = BASE_DIR.parent / "logtriage" +if str(LOGTRIAGE_DIR) not in sys.path: + sys.path.insert(0, str(LOGTRIAGE_DIR)) +try: + import logtriage +except ImportError: # pragma: no cover - dashboard can still serve without live rows + logtriage = None # type: ignore[assignment] DEFAULT_CONFIG_PATH = BASE_DIR / "config.example.json" ALLOWED_METHODS = {"GET", "HEAD", "OPTIONS"} @@ -72,7 +79,10 @@ class DashboardRuntime: self.settings: Dict[str, str] = {} self.raw_tail: List[str] = [] self.readiness: Dict[str, Any] = {} + self.rows: List[Dict[str, Any]] = [] + self.diagnostics: List[Dict[str, Any]] = [] self.current_session_file: Optional[str] = None + self.current_session_date: 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)) @@ -96,6 +106,8 @@ class DashboardRuntime: "current_session": self.state.current_session, "live_state": self.live_state, "readiness": dict(self.readiness), + "rows": list(self.rows), + "diagnostics": list(self.diagnostics), "events": list(self.latest_events[-100:]), "trades": list(self.trades), "provenance": self.provenance, @@ -113,9 +125,7 @@ class DashboardRuntime: 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 + self._poll_trades() if now >= self._next_provenance_poll: self._poll_provenance() self._next_provenance_poll = now + self.provenance_poll_seconds @@ -127,12 +137,15 @@ class DashboardRuntime: return raw_tail = parsers.tail_lines(path) session_key = parsers.session_key(path, raw_tail) + session_date = self._session_date_from_path(path) self.state.rollover_session(session_key) with self.lock: self.raw_tail = raw_tail self.current_session_file = str(path) + self.current_session_date = session_date self.readiness = parsers.parse_readiness(raw_tail) self._refresh_live_state_from_tail(path, raw_tail) + self.rows, self.diagnostics = self._build_current_rows(path, raw_tail) offset = self.state.get_offset(path) if offset is None: try: @@ -158,11 +171,94 @@ class DashboardRuntime: self._apply_event(event) def _poll_trades(self) -> None: - path = parsers.today_trades_file(self.log_dir) + date_key = self.current_session_date or time.strftime("%Y%m%d") + path = parsers.trades_file_for_date(self.log_dir, date_key) trades = parsers.read_trades(path) with self.lock: self.trades = trades + def _session_date_from_path(self, path: Path) -> str: + name = path.name + if name.startswith("session_") and len(name) >= 16: + return name[8:16] + return time.strftime("%Y%m%d") + + def _build_current_rows(self, path: Path, lines: List[str]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + if logtriage is None: + return [], [] + try: + session = logtriage.parse_session_file(path) + settings_by_date = self._settings_by_date(session.date) + provenance_by_date = self._provenance_by_date(session.date) + trade_file = parsers.trades_file_for_date(self.log_dir, session.timestamp.strftime("%Y%m%d")) + trades_by_session, trade_defects = logtriage.parse_trade_files([trade_file] if trade_file is not None else []) + rows = logtriage.build_rows([session], settings_by_date, provenance_by_date, trades_by_session) + diagnostics = logtriage.build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects) + row_dicts = [row.to_dict() for row in rows] + if row_dicts: + reject_summaries, reject_records = self._parse_rejections(lines, session.date) + row_dicts[0]["reject_summaries"] = reject_summaries + row_dicts[0]["reject_records"] = reject_records + return row_dicts, diagnostics + except Exception as ex: + return [], [{"date": time.strftime("%Y-%m-%d"), "code": "LIVE ROW BUILD FAILED", "message": str(ex)}] + + def _settings_by_date(self, date: str) -> Dict[str, List[Any]]: + if logtriage is None: + return {} + snapshots = [] + for path in self.log_dir.glob("settings_*.txt") if self.log_dir.exists() else []: + try: + snapshot = logtriage.parse_settings_file(path) + except Exception: + continue + if snapshot.date == date: + snapshots.append(snapshot) + return {date: snapshots} if snapshots else {} + + def _provenance_by_date(self, date: str) -> Dict[str, List[Any]]: + if logtriage is None: + return {} + snapshots = [] + for path in self.log_dir.glob("provenance_*.json") if self.log_dir.exists() else []: + try: + snapshot = logtriage.parse_provenance_file(path) + except Exception: + continue + if snapshot is not None and snapshot.date == date: + snapshots.append(snapshot) + return {date: snapshots} if snapshots else {} + + def _parse_rejections(self, lines: List[str], date: str) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + summaries: List[Dict[str, Any]] = [] + records: List[Dict[str, Any]] = [] + for line in lines: + timestamp, message = parsers.split_log_line(line) + if message.startswith("REJECT SUMMARY:"): + parts = self._parse_key_values(message.replace("REJECT SUMMARY:", "", 1)) + summaries.append({"date": date, "reason": parts.get("reason"), "count": int(parts.get("count", "0") or 0), "line": line}) + elif message.startswith("REJECT:"): + parts = self._parse_key_values(message.replace("REJECT:", "", 1)) + records.append({"date": date, "reason": parts.get("reason"), "detail": parts.get("detail"), "bar": parts.get("bar"), "line": line}) + return summaries, records + + def _parse_key_values(self, text: str) -> Dict[str, str]: + values: Dict[str, str] = {} + keys = ["reason", "detail", "bar", "count"] + for index, key in enumerate(keys): + marker = key + "=" + start = text.find(marker) + if start < 0: + continue + value_start = start + len(marker) + value_end = len(text) + for later_key in keys[index + 1:]: + later = text.find(" " + later_key + "=", value_start) + if later >= 0: + value_end = min(value_end, later) + values[key] = text[value_start:value_end].strip() + return values + def _poll_provenance(self) -> None: provenance_path = parsers.latest_provenance_file(self.log_dir) settings_path = parsers.latest_settings_file(self.log_dir)