diff --git a/tools/configdiff/README.md b/tools/configdiff/README.md new file mode 100644 index 0000000..69d72df --- /dev/null +++ b/tools/configdiff/README.md @@ -0,0 +1,66 @@ +# configdiff + +`configdiff` is a standalone Python CLI that parses `settings_Simple_ORB_NT8_*.txt` exports and reports configuration drift without referencing any NinjaTrader assembly. + +Python was chosen instead of a .NET console app so the tool stays fully outside `NT8-SDK.sln`, adds no NT8 dependency surface, and cannot affect deployed NT8 output. + +## What It Reports + +- A matrix of every parsed settings parameter across every export in scope +- Highlighted changed values using `*value*` +- Explicit callouts when `ConfigHash` is identical but parameters still differ + This independently catches the known DEC-20260810-01 BarsPeriod/hash defect before GAP-038 lands. +- Exit code `1` when drift is detected inside a declared gate window + +## Inputs + +The tool scans a directory for: + +- `settings_Simple_ORB_NT8_*.txt` + +Default directory: + +`%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk` + +## Usage + +Run across all matching exports: + +```powershell +python tools/configdiff/configdiff.py +``` + +Run against a specific archive directory: + +```powershell +python tools/configdiff/configdiff.py "C:\logs\nt8-sdk-archive" +``` + +Check only a gate window starting on a specific date: + +```powershell +python tools/configdiff/configdiff.py --gate-start 2026-08-07 +``` + +Use the exit code in automation: + +```powershell +python tools/configdiff/configdiff.py --gate-start 2026-08-07 +if ($LASTEXITCODE -eq 1) { "Drift detected inside gate window" } +``` + +## Drift Semantics + +- Drift is evaluated on configuration-bearing fields parsed from the settings export. +- Volatile runtime fields are excluded from drift detection: + - `ExportTime` + - `ConfigHash` + - `CodeVersion` + - `PortfolioStatus` +- The matrix still shows every parsed field so the full export remains visible. + +## Notes + +- The tool is read-only. +- It does not import or reference any NinjaTrader or NT8 SDK assembly. +- When `ConfigHash` matches but parameters differ, the report calls that out explicitly instead of trusting the hash. diff --git a/tools/configdiff/configdiff.py b/tools/configdiff/configdiff.py new file mode 100644 index 0000000..2226a98 --- /dev/null +++ b/tools/configdiff/configdiff.py @@ -0,0 +1,278 @@ +#!/usr/bin/env python3 +"""Standalone NT8 SDK settings drift detector.""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +from dataclasses import dataclass +from datetime import datetime, date +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Tuple + + +DEFAULT_INPUT_DIR = r"%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk" +SETTINGS_FILE_RE = re.compile(r"^settings_Simple_ORB_NT8_(\d{8})_(\d{6})\.txt$", re.IGNORECASE) +KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$") + +NON_DRIFT_FIELDS = set([ + "ExportTime", + "ConfigHash", + "CodeVersion", + "PortfolioStatus", +]) + + +@dataclass +class SettingsExport: + path: Path + timestamp: datetime + label: str + config_hash: Optional[str] + values: Dict[str, str] + + +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Detect drift across settings_Simple_ORB_NT8_*.txt exports.") + parser.add_argument( + "input_dir", + nargs="?", + default=DEFAULT_INPUT_DIR, + help="Directory containing settings_Simple_ORB_NT8_*.txt exports", + ) + parser.add_argument( + "--gate-start", + dest="gate_start", + help="Scope the check to exports on or after YYYY-MM-DD; exit code becomes 1 when drift is detected in that gate window.", + ) + return parser.parse_args(argv) + + +def expand_input_dir(raw_path: str) -> Path: + return Path(os.path.expanduser(os.path.expandvars(raw_path))) + + +def read_lines(path: Path) -> List[str]: + try: + return path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return [] + + +def parse_gate_start(raw_value: Optional[str]) -> Optional[date]: + if not raw_value: + return None + try: + return datetime.strptime(raw_value, "%Y-%m-%d").date() + except ValueError: + raise ValueError("Invalid --gate-start value: {0}. Expected YYYY-MM-DD.".format(raw_value)) + + +def parse_settings_file(path: Path) -> SettingsExport: + match = SETTINGS_FILE_RE.match(path.name) + if not match: + raise ValueError("Invalid settings export name: {0}".format(path.name)) + + timestamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S") + values: Dict[str, str] = {} + + for line in read_lines(path): + stripped = line.strip() + if not stripped or stripped.startswith("===") or stripped.startswith("---"): + continue + + key_match = KEY_VALUE_RE.match(line) + if not key_match: + continue + + key = key_match.group(1).strip() + value = key_match.group(2).strip() + values[key] = value + + return SettingsExport( + path=path, + timestamp=timestamp, + label=timestamp.strftime("%Y-%m-%d %H:%M:%S"), + config_hash=values.get("ConfigHash"), + values=values, + ) + + +def collect_exports(input_dir: Path) -> List[SettingsExport]: + exports: List[SettingsExport] = [] + for path in sorted(input_dir.rglob("*")): + if path.is_file() and SETTINGS_FILE_RE.match(path.name): + exports.append(parse_settings_file(path)) + exports.sort(key=lambda item: item.timestamp) + return exports + + +def filter_exports(exports: Sequence[SettingsExport], gate_start: Optional[date]) -> List[SettingsExport]: + if gate_start is None: + return list(exports) + return [item for item in exports if item.timestamp.date() >= gate_start] + + +def get_matrix_parameters(exports: Sequence[SettingsExport]) -> List[str]: + names = set() + for export in exports: + names.update(export.values.keys()) + return sorted(names) + + +def get_drift_parameters(exports: Sequence[SettingsExport]) -> List[str]: + params: List[str] = [] + for name in get_matrix_parameters(exports): + if name in NON_DRIFT_FIELDS: + continue + distinct = set() + for export in exports: + distinct.add(export.values.get(name, "(missing)")) + if len(distinct) > 1: + params.append(name) + return params + + +def get_hash_collision_defects(exports: Sequence[SettingsExport]) -> List[Dict[str, object]]: + groups: Dict[str, List[SettingsExport]] = {} + defects: List[Dict[str, object]] = [] + + for export in exports: + if export.config_hash: + groups.setdefault(export.config_hash, []).append(export) + + for config_hash in sorted(groups.keys()): + group = groups[config_hash] + if len(group) < 2: + continue + + changed_params: List[str] = [] + for name in get_matrix_parameters(group): + if name in NON_DRIFT_FIELDS: + continue + distinct = set() + for export in group: + distinct.add(export.values.get(name, "(missing)")) + if len(distinct) > 1: + changed_params.append(name) + + if changed_params: + defects.append( + { + "config_hash": config_hash, + "exports": group, + "parameters": changed_params, + } + ) + + return defects + + +def format_value(value: Optional[str], changed: bool) -> str: + text = value if value is not None and value != "" else "(missing)" + if changed: + return "*{0}*".format(text) + return text + + +def render_matrix(exports: Sequence[SettingsExport]) -> str: + if not exports: + return "MATRIX\nNo matching settings exports found." + + headers = ["Parameter", "Changed"] + [export.label for export in exports] + rows: List[List[str]] = [headers] + + drift_params = set(get_drift_parameters(exports)) + for name in get_matrix_parameters(exports): + changed = name in drift_params + row = [name, "YES" if changed else "no"] + for export in exports: + row.append(format_value(export.values.get(name), changed)) + rows.append(row) + + widths = [0] * len(headers) + for row in rows: + for index, value in enumerate(row): + if len(value) > widths[index]: + widths[index] = len(value) + + rendered: List[str] = ["MATRIX"] + for row_index, row in enumerate(rows): + rendered.append(" | ".join(row[index].ljust(widths[index]) for index in range(len(headers)))) + if row_index == 0: + rendered.append("-+-".join("-" * widths[index] for index in range(len(headers)))) + return "\n".join(rendered) + + +def render_summary(input_dir: Path, exports: Sequence[SettingsExport], scoped_exports: Sequence[SettingsExport], gate_start: Optional[date]) -> Tuple[str, bool]: + drift_params = get_drift_parameters(scoped_exports) + defects = get_hash_collision_defects(scoped_exports) + drift_detected = len(drift_params) > 0 + + lines: List[str] = [] + lines.append("SCOPE") + lines.append("Input directory: {0}".format(input_dir)) + lines.append("Matched exports: {0}".format(len(exports))) + if gate_start is None: + lines.append("Scope: all matched exports") + else: + lines.append("Scope: exports on or after {0} ({1} export(s))".format(gate_start.isoformat(), len(scoped_exports))) + lines.append("") + lines.append("DRIFT SUMMARY") + lines.append("Drift detected: {0}".format("YES" if drift_detected else "no")) + if drift_params: + lines.append("Changed parameters: {0}".format(", ".join(drift_params))) + else: + lines.append("Changed parameters: none") + + lines.append("") + lines.append("HASH DEFECT CHECK") + if defects: + for defect in defects: + lines.append( + "IDENTICAL ConfigHash with differing parameters: {0}".format(defect["config_hash"]) + ) + lines.append("Differing parameters: {0}".format(", ".join(defect["parameters"]))) + for export in defect["exports"]: + values: List[str] = [] + for name in defect["parameters"]: + values.append("{0}={1}".format(name, export.values.get(name, "(missing)"))) + lines.append(" - {0} [{1}] {2}".format(export.label, export.path.name, "; ".join(values))) + else: + lines.append("No identical-hash parameter divergence detected.") + + return "\n".join(lines), drift_detected + + +def main(argv: Sequence[str]) -> int: + args = parse_args(argv) + + try: + gate_start = parse_gate_start(args.gate_start) + except ValueError as ex: + sys.stderr.write(str(ex) + "\n") + return 2 + + input_dir = expand_input_dir(args.input_dir) + if not input_dir.exists() or not input_dir.is_dir(): + sys.stderr.write("Input directory not found: {0}\n".format(input_dir)) + return 2 + + exports = collect_exports(input_dir) + scoped_exports = filter_exports(exports, gate_start) + + summary, drift_detected = render_summary(input_dir, exports, scoped_exports, gate_start) + matrix = render_matrix(scoped_exports) + + sys.stdout.write(summary + "\n\n") + sys.stdout.write(matrix + "\n") + + if gate_start is not None and drift_detected: + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/dashboard/README.md b/tools/dashboard/README.md new file mode 100644 index 0000000..1aa15ba --- /dev/null +++ b/tools/dashboard/README.md @@ -0,0 +1,166 @@ +# dashboard + +`dashboard` is a standalone read-only dashboard for TOOL-001 JSON output and live local NT8 SDK log artifacts. + +Implementation choice: static HTML + vanilla JavaScript plus an optional dependency-free Python localhost server. The server reads files only, binds to `127.0.0.1`, has no write/POST endpoints, and can optionally send outbound notifications through Apprise. + +## Safety Properties + +- Read-only browser UI +- No NinjaTrader assembly references +- No writes to any NinjaTrader directory +- No network dependency or CDN usage +- No package install required +- Can run directly from disk or on localhost only +- Server binds only to `127.0.0.1`; `0.0.0.0` is rejected in code +- Server implements only `GET`, `HEAD`, and `OPTIONS`; `POST`, `PUT`, `PATCH`, and `DELETE` return `405 Method Not Allowed` +- Runtime state is written only to `tools/dashboard/dashboard_state.json` by default to avoid duplicate notifications after restart + +## Generate Input JSON + +From the repo root: + +```powershell +python tools/logtriage/logtriage.py --json | Out-File -Encoding utf8 triage.json +``` + +For an archive directory: + +```powershell +python tools/logtriage/logtriage.py "C:\logs\nt8-sdk-archive" --json | Out-File -Encoding utf8 triage.json +``` + +PowerShell 5.1 `>` redirection writes UTF-16LE by default. Use `Out-File -Encoding utf8` so the browser can parse the JSON file. + +## Launch + +Direct file launch: + +```powershell +Start-Process .\tools\dashboard\index.html +``` + +Static localhost-only launch: + +```powershell +python -m http.server 8765 --bind 127.0.0.1 --directory tools/dashboard +``` + +Then open: + +```text +http://127.0.0.1:8765/ +``` + +Live read-only server launch: + +```powershell +Copy-Item .\tools\dashboard\config.example.json .\tools\dashboard\config.json +python .\tools\dashboard\server.py --config .\tools\dashboard\config.json +``` + +Then open: + +```text +http://127.0.0.1:8765/ +``` + +## Usage + +1. Generate `triage.json` from TOOL-001. +2. Open the dashboard. +3. Click `Select triage.json` and choose the generated file. +4. Review the five views. + +For live mode, launch `server.py`; the browser polls `/api/state` automatically every 5 seconds. + +## Live Server Config + +`config.example.json`: + +```json +{ + "host": "127.0.0.1", + "port": 8765, + "log_dir": "%USERPROFILE%\\Documents\\NinjaTrader 8\\log\\nt8-sdk", + "state_file": "dashboard_state.json", + "polling": { + "session_log_seconds": 2, + "trades_seconds": 10, + "provenance_seconds": 10 + }, + "notifications": { + "enabled": false, + "targets": [], + "events": { + "submit": true, + "fill": true, + "breakeven": true, + "connection": true, + "daily_pnl_milestones": true + }, + "daily_pnl_milestones": [100, 250, 500, -100, -250, -500] + } +} +``` + +`%USERPROFILE%` is expanded with Python environment-variable expansion, not a hardcoded username. + +Polling defaults: + +- newest session log tail: `2` seconds +- trades JSONL table: `10` seconds +- provenance/settings panel: `10` seconds + +## Notifications + +Install optional Apprise support: + +```powershell +python -m pip install -r .\tools\dashboard\requirements.txt +``` + +Add Apprise URLs to `config.json`: + +```json +"notifications": { + "enabled": true, + "targets": [ + "discord://webhook_id/webhook_token", + "ntfy://ntfy.sh/your-topic" + ] +} +``` + +Notification triggers: + +- `SUBMIT` +- `FILL` +- `BREAKEVEN` +- `CONNECTION LOST` +- `CONNECTION RESTORED` +- `PNL_UPDATE` crossing configured daily P&L milestones + +Daily P&L milestone tracking resets only on session rollover via `SESSION START`, not on position-flat. This intentionally mirrors the corrected MaxDailyTrades behavior: position-flat does not re-arm daily state. + +Offset and dedup state persist to `tools/dashboard/dashboard_state.json` by default. This prevents a mid-day server restart from re-firing the entire day’s notification history. If that file is deleted, the server starts at the current end of the already-existing newest session log to avoid historical notification replay. + +Webhook/notification failures are logged to stderr and never crash or block the dashboard poller. + +## Views + +1. Gate progress: trades banked against the 20-trade minimum, elapsed session days, current traded-session streak, and diagnostic count. +2. Daily timeline: one row per session, color-coded as traded, silent, or config violation. +3. Trade detail: grade, score, entry/exit fields, and scaler versus runner P&L attribution when present in TOOL-001 trade records. +4. Provenance health: sentinel/default-value counts per provenance field across trade records. +5. Config integrity: `ConfigHash` and `CodeVersion` timeline with drift markers. + +## Data Contract + +The dashboard consumes TOOL-001 JSON with these top-level fields: + +- `rows`: session summaries +- `diagnostics`: diagnostics emitted by TOOL-001 +- `trade_records`: per-trade JSONL records enriched with `date`, `path`, and `line` + +The UI is tolerant of missing fields and displays `-` when a requested value is absent. diff --git a/tools/dashboard/app.js b/tools/dashboard/app.js new file mode 100644 index 0000000..ed9c6e8 --- /dev/null +++ b/tools/dashboard/app.js @@ -0,0 +1,746 @@ +(function () { + "use strict"; + + var MIN_TRADES = 20; + var GRADE_A_THRESHOLD = 0.80; + var DECISION_REASONS = { GradeFilter: true, MaxDailyTrades: true }; + var DEFECT_REASONS = { OrbRangeNotEstablished: true, RthGuard: true, WarmupIncomplete: true, KillSwitch: true, ConnectionLost: true, CmeHoliday: true }; + var emptyTemplate = document.getElementById("empty-row"); + var fileInput = document.getElementById("json-file"); + var pasteInput = document.getElementById("json-paste"); + var loadPasted = document.getElementById("load-pasted"); + var loadSample = document.getElementById("load-sample"); + var loadServer = document.getElementById("load-server"); + var loadMessage = document.getElementById("load-message"); + + function asArray(value) { + return Array.isArray(value) ? value : []; + } + + function valueOf(row, names) { + var i; + for (i = 0; i < names.length; i += 1) { + if (row && Object.prototype.hasOwnProperty.call(row, names[i]) && row[names[i]] !== null && row[names[i]] !== undefined && row[names[i]] !== "") { + return row[names[i]]; + } + } + return null; + } + + function display(value) { + if (value === null || value === undefined || value === "") { + return "-"; + } + return String(value); + } + + function numberValue(value) { + if (typeof value === "number") { + return value; + } + if (value === null || value === undefined) { + return 0; + } + var parsed = parseFloat(String(value).replace(/[$,]/g, "")); + return isNaN(parsed) ? 0 : parsed; + } + + function dateOf(row) { + var value = valueOf(row, ["date", "session_date", "trade_date"]); + if (value) { + return String(value).substring(0, 10); + } + value = valueOf(row, ["timestamp", "entry_time", "time", "generated_at_utc"]); + return value ? String(value).substring(0, 10) : "unknown"; + } + + function normalize(payload) { + var rows = asArray(payload.rows || payload.sessions); + var diagnostics = asArray(payload.diagnostics); + var trades = asArray(payload.trade_records || payload.trades || payload.trade_details); + var rejectSummaries = collectRejectSummaries(payload, rows, diagnostics); + var rejectRecords = collectRejectRecords(payload, rows, diagnostics); + return { rows: rows, diagnostics: diagnostics, trades: trades, rejectSummaries: rejectSummaries, rejectRecords: rejectRecords, raw: payload }; + } + + function collectRejectSummaries(payload, rows, diagnostics) { + var results = []; + asArray(payload.reject_summaries || payload.reject_summary || payload.rejectSummary).forEach(function (item) { + results.push(normalizeRejectSummary(item)); + }); + rows.forEach(function (row) { + asArray(row.reject_summaries || row.reject_summary || row.rejectSummary).forEach(function (item) { + var summary = normalizeRejectSummary(item); + summary.date = summary.date || dateOf(row); + summary.session_file = summary.session_file || (row.source_files && row.source_files.session) || row.session_file; + results.push(summary); + }); + }); + diagnostics.forEach(function (item) { + if (item && (item.code === "REJECT SUMMARY" || item.event_type === "REJECT SUMMARY")) { + results.push(normalizeRejectSummary(item)); + } + }); + return results.filter(function (item) { return item.reason; }); + } + + function collectRejectRecords(payload, rows, diagnostics) { + var results = []; + asArray(payload.reject_records || payload.rejects || payload.rejections).forEach(function (item) { + results.push(normalizeRejectRecord(item)); + }); + rows.forEach(function (row) { + asArray(row.reject_records || row.rejects || row.rejections).forEach(function (item) { + var record = normalizeRejectRecord(item); + record.date = record.date || dateOf(row); + results.push(record); + }); + }); + diagnostics.forEach(function (item) { + if (item && (item.code === "REJECT" || item.event_type === "REJECT")) { + results.push(normalizeRejectRecord(item)); + } + }); + return results.filter(function (item) { return item.reason || item.detail; }); + } + + function normalizeRejectSummary(item) { + if (!item) { + return {}; + } + if (typeof item === "string") { + return parseRejectSummaryLine(item); + } + var reason = valueOf(item, ["reason", "reject_reason"]); + var count = valueOf(item, ["count", "reject_count"]); + var line = valueOf(item, ["line", "message", "raw"]); + var parsed = line ? parseRejectSummaryLine(String(line)) : {}; + return { + date: dateOf(item), + reason: reason || parsed.reason, + count: count !== null ? numberValue(count) : numberValue(parsed.count), + session_file: valueOf(item, ["session_file", "session", "path"]), + raw: line || item.raw || "" + }; + } + + function normalizeRejectRecord(item) { + if (!item) { + return {}; + } + if (typeof item === "string") { + return parseRejectLine(item); + } + var line = valueOf(item, ["line", "message", "raw"]); + var parsed = line ? parseRejectLine(String(line)) : {}; + return { + date: dateOf(item), + reason: valueOf(item, ["reason", "reject_reason"]) || parsed.reason, + detail: valueOf(item, ["detail", "reject_detail"]) || parsed.detail || "", + bar: valueOf(item, ["bar", "bar_time"]) || parsed.bar, + raw: line || item.raw || "" + }; + } + + function parseRejectSummaryLine(line) { + var match = /REJECT SUMMARY:\s*reason=([^\s]+)\s+count=(\d+)/i.exec(line); + if (!match) { + return {}; + } + return { reason: match[1], count: parseInt(match[2], 10) }; + } + + function parseRejectLine(line) { + var match = /REJECT:\s*reason=([^\s]+)\s+detail=(.*?)(?:\s+bar=(.*))?$/i.exec(line); + if (!match) { + return {}; + } + return { reason: match[1], detail: match[2], bar: match[3] || null }; + } + + function uniqueDates(rows, trades) { + var map = {}; + rows.forEach(function (row) { map[dateOf(row)] = true; }); + trades.forEach(function (row) { map[dateOf(row)] = true; }); + return Object.keys(map).filter(function (date) { return date !== "unknown"; }).sort(); + } + + function visibleCalendarDates(dates, count) { + if (dates.length === 0) { + return []; + } + var last = parseDate(dates[dates.length - 1]); + var result = []; + var i; + for (i = count - 1; i >= 0; i -= 1) { + result.push(formatDate(addDays(last, -i))); + } + return result; + } + + function parseDate(value) { + var parts = String(value).split("-"); + return new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2])); + } + + function addDays(value, days) { + var result = new Date(value.getTime()); + result.setDate(result.getDate() + days); + return result; + } + + function formatDate(value) { + var month = String(value.getMonth() + 1); + var day = String(value.getDate()); + if (month.length < 2) { + month = "0" + month; + } + if (day.length < 2) { + day = "0" + day; + } + return value.getFullYear() + "-" + month + "-" + day; + } + + function tradesForDate(trades, date) { + return trades.filter(function (trade) { return dateOf(trade) === date; }); + } + + function diagnosticsForDate(diagnostics, date) { + return diagnostics.filter(function (item) { return String(item.date || "") === date; }); + } + + function isConfigViolation(row, diagnostics, date) { + if (row && (row.kill_switch === false || row.verbose_log === false || row.test_mode === true)) { + return true; + } + return diagnosticsForDate(diagnostics, date).some(function (item) { + return item.code === "GATE CONFIG VIOLATION" || item.code === "CONFIG DRIFT" || item.code === "PARALLEL INSTANCE"; + }); + } + + function isTraded(row, trades, date) { + if (tradesForDate(trades, date).length > 0) { + return true; + } + return numberValue(row && row.fills) > 0 || numberValue(row && row.submits) > 0; + } + + function sessionStatus(row, diagnostics, trades, date) { + if (isConfigViolation(row, diagnostics, date)) { + return "violation"; + } + if (isTraded(row, trades, date)) { + return "traded"; + } + return "silent"; + } + + function currentStreak(rows, trades) { + var dates = uniqueDates(rows, trades); + var streak = 0; + var i; + for (i = dates.length - 1; i >= 0; i -= 1) { + var row = rows.filter(function (item) { return dateOf(item) === dates[i]; })[0] || null; + if (!isTraded(row, trades, dates[i])) { + break; + } + streak += 1; + } + return streak; + } + + function setText(id, value) { + document.getElementById(id).textContent = value; + } + + function setTextIfPresent(id, value) { + var node = document.getElementById(id); + if (node) { + node.textContent = value; + } + } + + function clearTable(table) { + while (table.firstChild) { + table.removeChild(table.firstChild); + } + } + + function addEmpty(table) { + table.appendChild(emptyTemplate.content.cloneNode(true)); + } + + function renderTable(id, headers, rows, rowClass) { + var table = document.getElementById(id); + var thead = document.createElement("thead"); + var tbody = document.createElement("tbody"); + var tr = document.createElement("tr"); + + clearTable(table); + headers.forEach(function (header) { + var th = document.createElement("th"); + th.textContent = header; + tr.appendChild(th); + }); + thead.appendChild(tr); + table.appendChild(thead); + + if (rows.length === 0) { + addEmpty(tbody); + } else { + rows.forEach(function (cells) { + var row = document.createElement("tr"); + if (rowClass) { + row.className = rowClass(cells) || ""; + } + cells.forEach(function (cell) { + var td = document.createElement("td"); + if (cell && cell.html) { + td.innerHTML = cell.html; + } else { + td.textContent = display(cell); + } + row.appendChild(td); + }); + tbody.appendChild(row); + }); + } + table.appendChild(tbody); + } + + function statusPill(status) { + if (status === "traded") { + return { html: 'traded' }; + } + if (status === "violation") { + return { html: 'config violation' }; + } + return { html: 'silent' }; + } + + function reasonClass(reason) { + if (DECISION_REASONS[reason]) { + return "decision"; + } + if (DEFECT_REASONS[reason]) { + return "defect"; + } + return "unknown"; + } + + function summariesForDate(data, date) { + return data.rejectSummaries.filter(function (item) { return item.date === date; }); + } + + function dayRows(data, date) { + return data.rows.filter(function (row) { return dateOf(row) === date; }); + } + + function dayHasConfigViolation(data, date) { + return dayRows(data, date).some(function (row) { return isConfigViolation(row, data.diagnostics, date); }); + } + + function classifySilentDate(data, date) { + var summaries = summariesForDate(data, date); + var hasDecision = summaries.some(function (item) { return reasonClass(item.reason) === "decision"; }); + var hasDefect = summaries.some(function (item) { return reasonClass(item.reason) === "defect"; }); + if (hasDefect) { + return "silent-by-defect"; + } + if (hasDecision) { + return "silent-by-decision"; + } + return "silent-unknown"; + } + + function dayHealth(data, date) { + if (dayRows(data, date).length === 0) { + return "no-session"; + } + if (dayHasConfigViolation(data, date)) { + return "config-violation"; + } + if (dayRows(data, date).some(function (row) { return isTraded(row, data.trades, date); })) { + return "traded"; + } + return classifySilentDate(data, date); + } + + function renderHeadline(data) { + var dates = uniqueDates(data.rows, data.trades); + var counts = { "silent-by-decision": 0, "silent-by-defect": 0, "silent-unknown": 0 }; + dates.forEach(function (date) { + var health = dayHealth(data, date); + if (Object.prototype.hasOwnProperty.call(counts, health)) { + counts[health] += 1; + } + }); + setText("metric-decision-silent", String(counts["silent-by-decision"])); + setText("metric-defect-silent", String(counts["silent-by-defect"])); + setText("metric-unknown-silent", String(counts["silent-unknown"])); + var missing = []; + if (data.rejectSummaries.length === 0) { + missing.push("REJECT SUMMARY counts"); + } + if (data.rejectRecords.length === 0) { + missing.push("per-reject factor detail"); + } + document.getElementById("contract-message").textContent = missing.length ? "Current JSON lacks " + missing.join(" and ") + "; silent classification is partial." : "Reject summaries and factor detail are available."; + renderHealthStrip(data, visibleCalendarDates(dates, 20)); + } + + function renderHealthStrip(data, dates) { + var strip = document.getElementById("health-strip"); + while (strip.firstChild) { + strip.removeChild(strip.firstChild); + } + dates.forEach(function (date) { + var item = document.createElement("div"); + var health = dayHealth(data, date); + item.className = "health-cell " + health; + item.title = date + " " + health; + item.textContent = date.substring(5); + strip.appendChild(item); + }); + } + + function renderSilentExplorer(data) { + var container = document.getElementById("silent-explorer"); + while (container.firstChild) { + container.removeChild(container.firstChild); + } + var dates = uniqueDates(data.rows, data.trades).filter(function (date) { + return dayRows(data, date).length > 0 && !dayRows(data, date).some(function (row) { return isTraded(row, data.trades, date); }); + }); + if (dates.length === 0) { + container.appendChild(emptyMessage("No silent sessions in the loaded JSON.")); + return; + } + dates.forEach(function (date) { + var summaries = summariesForDate(data, date); + var card = document.createElement("div"); + card.className = "silent-card " + classifySilentDate(data, date); + var title = document.createElement("div"); + title.className = "silent-title"; + title.innerHTML = "" + date + "" + classifySilentDate(data, date).replace(/-/g, " ") + ""; + card.appendChild(title); + if (summaries.length === 0) { + card.appendChild(emptyMessage("No REJECT SUMMARY data in logtriage JSON for this silent day.")); + } else { + card.appendChild(reasonBars(summaries)); + } + container.appendChild(card); + }); + } + + function emptyMessage(text) { + var node = document.createElement("p"); + node.className = "empty-note"; + node.textContent = text; + return node; + } + + function reasonBars(summaries) { + var wrap = document.createElement("div"); + var max = summaries.reduce(function (largest, item) { return Math.max(largest, numberValue(item.count)); }, 1); + summaries.sort(function (a, b) { return numberValue(b.count) - numberValue(a.count); }).forEach(function (item) { + var row = document.createElement("div"); + row.className = "reason-row " + reasonClass(item.reason); + row.innerHTML = '' + display(item.reason) + '
' + display(item.count) + ''; + wrap.appendChild(row); + }); + return wrap; + } + + function allScores(data) { + var scores = []; + data.trades.forEach(function (trade) { + var score = valueOf(trade, ["confluence_score", "score", "trade_score", "confluence_weighted_score"]); + if (score !== null) { + scores.push(numberValue(score)); + } + }); + data.rejectRecords.forEach(function (record) { + var match = /Score=([0-9.]+)/i.exec(record.detail || record.raw || ""); + if (match) { + scores.push(numberValue(match[1])); + } + }); + return scores.filter(function (score) { return score > 0; }); + } + + function renderGradeDistribution(data) { + var container = document.getElementById("grade-histogram"); + while (container.firstChild) { + container.removeChild(container.firstChild); + } + var scores = allScores(data); + if (scores.length === 0) { + container.appendChild(emptyMessage("No confluence scores exposed in the loaded JSON.")); + return; + } + var buckets = []; + var i; + for (i = 0; i < 10; i += 1) { + buckets.push(0); + } + scores.forEach(function (score) { + var index = Math.min(9, Math.max(0, Math.floor(score * 10))); + buckets[index] += 1; + }); + var max = buckets.reduce(function (largest, count) { return Math.max(largest, count); }, 1); + var chart = document.createElement("div"); + chart.className = "histogram-chart"; + buckets.forEach(function (count, index) { + var bar = document.createElement("div"); + bar.className = "histogram-bar" + (index >= 8 ? " above-threshold" : ""); + bar.style.height = Math.max(4, Math.round((count / max) * 100)) + "%"; + bar.title = (index / 10).toFixed(1) + "-" + ((index + 1) / 10).toFixed(1) + ": " + count; + bar.innerHTML = "" + count + ""; + chart.appendChild(bar); + }); + var threshold = document.createElement("div"); + threshold.className = "threshold-line"; + threshold.style.left = Math.round(GRADE_A_THRESHOLD * 100) + "%"; + threshold.innerHTML = 'Grade A / 0.80'; + chart.appendChild(threshold); + container.appendChild(chart); + } + + function parseFactors(detail) { + var factors = []; + var match = /Factors=([^\n]+)/i.exec(detail || ""); + if (!match) { + return factors; + } + match[1].split(";").forEach(function (part) { + var factor = /^([^=]+)=([0-9.]+)(?:x([0-9.]+))?/i.exec(part.trim()); + if (factor) { + factors.push({ name: factor[1], score: numberValue(factor[2]), weight: factor[3] ? numberValue(factor[3]) : 1 }); + } + }); + return factors; + } + + function renderFactorBreakdown(data) { + var stats = {}; + data.rejectRecords.filter(function (record) { return record.reason === "GradeFilter"; }).forEach(function (record) { + var factors = parseFactors(record.detail || record.raw || ""); + var lowest = null; + factors.forEach(function (factor) { + if (!stats[factor.name]) { + stats[factor.name] = { count: 0, total: 0, drag: 0 }; + } + stats[factor.name].count += 1; + stats[factor.name].total += factor.score; + if (lowest === null || factor.score < lowest.score) { + lowest = factor; + } + }); + if (lowest && stats[lowest.name]) { + stats[lowest.name].drag += 1; + } + }); + var rows = Object.keys(stats).map(function (name) { + return [name, stats[name].count, (stats[name].total / stats[name].count).toFixed(3), stats[name].drag]; + }).sort(function (a, b) { return numberValue(b[3]) - numberValue(a[3]); }); + renderTable("factor-table", ["Factor", "Seen", "Avg Score", "Lowest-Factor Count"], rows); + } + + function renderMetrics(data) { + var tradeCount = data.trades.length; + if (tradeCount === 0) { + tradeCount = data.rows.reduce(function (sum, row) { return sum + numberValue(row.fills || row.submits); }, 0); + } + var dates = uniqueDates(data.rows, data.trades); + setText("metric-trades", tradeCount + " / " + MIN_TRADES); + setText("metric-days", String(dates.length)); + setText("metric-streak", String(currentStreak(data.rows, data.trades))); + setText("metric-diagnostics", String(data.diagnostics.length)); + document.getElementById("trade-progress").style.width = Math.min(100, Math.round((tradeCount / MIN_TRADES) * 100)) + "%"; + } + + function renderTimeline(data) { + var rows = data.rows.slice().sort(function (a, b) { return dateOf(a).localeCompare(dateOf(b)); }); + var tableRows = rows.map(function (row) { + var date = dateOf(row); + var status = sessionStatus(row, data.diagnostics, data.trades, date); + var dayDiagnostics = diagnosticsForDate(data.diagnostics, date).map(function (item) { return item.code; }).join(", "); + return [ + date, + statusPill(status), + display(row.account), + display(row.instrument), + display(row.bar_type || row.session_bar_type), + display(row.signals), + display(row.submits), + display(row.fills), + display(row.net_pnl), + dayDiagnostics || "-", + status + ]; + }); + + renderTable("timeline-table", ["Date", "Status", "Account", "Instrument", "Bars", "Signals", "Submits", "Fills", "Net P&L", "Diagnostics"], tableRows.map(function (row) { return row.slice(0, 10); }), function (cells) { + var status = cells[1] && cells[1].html && cells[1].html.indexOf("config violation") >= 0 ? "violation" : cells[1].html.indexOf("traded") >= 0 ? "traded" : "silent"; + return "status-" + status; + }); + } + + function renderTrades(data) { + var rows = data.trades.map(function (trade) { + var scaler = valueOf(trade, ["scaler_pnl", "scalp_pnl", "scalerPnL", "scaler_pnl_attribution"]); + var runner = valueOf(trade, ["runner_pnl", "runnerPnL", "runner_pnl_attribution"]); + return [ + dateOf(trade), + display(valueOf(trade, ["trade_seq", "sequence", "line"])), + display(valueOf(trade, ["confluence_grade", "grade", "trade_grade"])), + display(valueOf(trade, ["confluence_score", "score", "trade_score"])), + display(valueOf(trade, ["entry_time", "entryTime", "submitted_at"])), + display(valueOf(trade, ["entry_price", "entryPrice", "average_entry_price"])), + display(valueOf(trade, ["exit_time", "exitTime", "closed_at"])), + display(valueOf(trade, ["exit_price", "exitPrice", "average_exit_price"])), + display(scaler), + display(runner), + display(valueOf(trade, ["session_id"])), + display(valueOf(trade, ["path"])) + ]; + }); + renderTable("trade-table", ["Date", "Seq", "Grade", "Score", "Entry Time", "Entry", "Exit Time", "Exit", "Scaler P&L", "Runner P&L", "Session", "Source"], rows); + } + + function isSentinel(field, value) { + if (value === null || value === undefined || value === "") { + return true; + } + var text = String(value).trim().toLowerCase(); + if (text === "unknown" || text === "n/a" || text === "default" || text === "00000000-0000-0000-0000-000000000000") { + return true; + } + if ((field === "confluence_score" || field === "OrbRangeTicks" || field === "orb_range_ticks") && numberValue(value) === 0) { + return true; + } + return false; + } + + function renderProvenance(data) { + var preferred = ["session_id", "config_hash", "code_version", "confluence_grade", "confluence_score", "risk_mode", "OrbRangeTicks", "orb_range_ticks", "runner_mode"]; + var fields = []; + preferred.forEach(function (field) { + if (data.trades.some(function (trade) { return Object.prototype.hasOwnProperty.call(trade, field); })) { + fields.push(field); + } + }); + if (fields.length === 0) { + fields = preferred.slice(0, 7); + } + var rows = fields.map(function (field) { + var count = data.trades.reduce(function (sum, trade) { return sum + (isSentinel(field, trade[field]) ? 1 : 0); }, 0); + return [field, count, data.trades.length, data.trades.length ? Math.round((count / data.trades.length) * 100) + "%" : "-"]; + }); + renderTable("provenance-table", ["Field", "Sentinel Count", "Records", "Rate"], rows); + } + + function renderConfig(data) { + var previousHash = null; + var previousVersion = null; + var rows = data.rows.slice().sort(function (a, b) { return dateOf(a).localeCompare(dateOf(b)); }).map(function (row) { + var hash = row.config_hash || "-"; + var codeVersion = row.code_version || "-"; + var drift = []; + if (previousHash !== null && hash !== previousHash) { + drift.push("ConfigHash"); + } + if (previousVersion !== null && codeVersion !== previousVersion) { + drift.push("CodeVersion"); + } + previousHash = hash; + previousVersion = codeVersion; + return [dateOf(row), display(hash), display(row.config_hash_8), display(codeVersion), drift.length ? { html: '' + drift.join(" + ") + '' } : { html: 'stable' }]; + }); + renderTable("config-table", ["Date", "ConfigHash", "Hash(8)", "CodeVersion", "Drift"], rows); + } + + function render(payload, label) { + var data = normalize(payload); + renderHeadline(data); + renderSilentExplorer(data); + renderGradeDistribution(data); + renderFactorBreakdown(data); + renderMetrics(data); + renderTimeline(data); + renderTrades(data); + renderProvenance(data); + renderConfig(data); + loadMessage.textContent = "Loaded " + label + ": " + data.rows.length + " sessions, " + data.trades.length + " trades, " + data.diagnostics.length + " diagnostics."; + } + + function renderServerState(payload) { + var live = payload.live_state || {}; + var notify = payload.notifications || {}; + setTextIfPresent("server-status", "Polling " + (payload.session_file || "no session file") + " from " + (payload.log_dir || "configured log directory") + "."); + setTextIfPresent("live-connection", live.connection || "-", ""); + setTextIfPresent("live-pnl", live.daily_pnl !== undefined ? String(live.daily_pnl) : "-"); + setTextIfPresent("live-position", live.position ? live.position + " " + (live.quantity !== undefined ? live.quantity : "") : "-"); + setTextIfPresent("live-notify", notify.enabled ? (notify.available ? "enabled" : "unavailable") : "disabled"); + var rawTail = document.getElementById("raw-tail"); + if (rawTail) { + rawTail.textContent = asArray(payload.raw_tail).slice(-80).join("\n"); + } + render({ rows: [], diagnostics: [], trade_records: asArray(payload.trades) }, "server state"); + } + + function loadServerState() { + if (!window.fetch) { + setTextIfPresent("server-status", "Fetch API unavailable in this browser."); + return; + } + fetch("/api/state", { cache: "no-store" }).then(function (response) { + if (!response.ok) { + throw new Error("HTTP " + response.status); + } + return response.json(); + }).then(function (payload) { + renderServerState(payload); + }).catch(function (error) { + setTextIfPresent("server-status", "Live server unavailable: " + error.message); + }); + } + + function loadJsonText(text, label) { + try { + render(JSON.parse(text), label); + } catch (error) { + loadMessage.textContent = "Failed to parse JSON: " + error.message; + } + } + + fileInput.addEventListener("change", function () { + var file = fileInput.files && fileInput.files[0]; + if (!file) { + return; + } + var reader = new FileReader(); + reader.onload = function () { loadJsonText(String(reader.result || ""), file.name); }; + reader.onerror = function () { loadMessage.textContent = "Failed to read selected file."; }; + reader.readAsText(file); + }); + + loadPasted.addEventListener("click", function () { + loadJsonText(pasteInput.value, "pasted JSON"); + }); + + loadSample.addEventListener("click", function () { + render({ tool: "logtriage", rows: [], trade_records: [], diagnostics: [] }, "empty shell"); + }); + + if (loadServer) { + loadServer.addEventListener("click", loadServerState); + if (window.location.protocol === "http:" || window.location.protocol === "https:") { + loadServerState(); + window.setInterval(loadServerState, 5000); + } + } + + render({ tool: "logtriage", rows: [], trade_records: [], diagnostics: [] }, "empty shell"); +}()); diff --git a/tools/dashboard/config.example.json b/tools/dashboard/config.example.json new file mode 100644 index 0000000..4090cf0 --- /dev/null +++ b/tools/dashboard/config.example.json @@ -0,0 +1,23 @@ +{ + "host": "127.0.0.1", + "port": 8765, + "log_dir": "%USERPROFILE%\\Documents\\NinjaTrader 8\\log\\nt8-sdk", + "state_file": "dashboard_state.json", + "polling": { + "session_log_seconds": 2, + "trades_seconds": 10, + "provenance_seconds": 10 + }, + "notifications": { + "enabled": false, + "targets": [], + "events": { + "submit": true, + "fill": true, + "breakeven": true, + "connection": true, + "daily_pnl_milestones": true + }, + "daily_pnl_milestones": [100, 250, 500, -100, -250, -500] + } +} diff --git a/tools/dashboard/index.html b/tools/dashboard/index.html new file mode 100644 index 0000000..d4204ec --- /dev/null +++ b/tools/dashboard/index.html @@ -0,0 +1,198 @@ + + + + + + NT8 SDK Read-Only Dashboard + + + +
+
+

NT8 SDK

+

Decision Or Defect?

+

Headline dashboard for deciding whether a silent session was intentional strategy filtering or an operational defect.

+
+
+ Mode + Static HTML + vanilla JS + No NT8 references. No writes. +
+
+ +
+
+
+

Load TOOL-001 JSON

+

Generate with python tools/logtriage/logtriage.py --json > triage.json, then select that file here. The file stays local in the browser.

+
+
+ + +
+ + +

No JSON loaded.

+
+ +
+
+
+

Live Local Server

+

Open through `server.py` to enable live polling from read-only log files.

+
+ +
+
+
+ Connection + - + From newest session log +
+
+ Daily P&L + - + Latest PNL_UPDATE +
+
+ Position + - + Latest PNL_UPDATE +
+
+ Notifications + - + Apprise status +
+
+

+    
+ +
+
+
+

Headline View

+

Was Silence A Decision Or A Defect?

+
+

Load TOOL-001 JSON to classify silent sessions.

+
+
+
+ Silent By Decision + 0 + Primarily GradeFilter or MaxDailyTrades +
+
+ Silent By Defect + 0 + ORB/RTH/warmup/config defects +
+
+ Silent Unknown + 0 + No reject summary available +
+
+ Threshold + 0.80 + MinTradeGrade=5 / Grade A +
+
+
+
+ +
+
+
+

Silent Day Explorer

+

Zero-SIGNAL sessions grouped by date. Decision reasons and defect reasons are color-coded.

+
+
+ Decision + Defect + Unknown +
+
+
+
+ +
+
+

Grade Distribution

+

Histogram of computed confluence scores. The vertical marker is the Grade A threshold at 0.80.

+
+
+
+

Factor Breakdown

+

For GradeFilter rejections, identifies which factors most often drag the composite under threshold.

+
+
+
+ +
+
+ Trades Banked + 0 / 20 +
+
+
+ Days Elapsed + 0 + Unique session dates +
+
+ Current Streak + 0 + Consecutive traded sessions +
+
+ Diagnostics + 0 + TOOL-001 findings +
+
+ +
+
+

Daily Timeline

+
+ Traded + Silent + Config violation +
+
+
+
+ +
+
+

Trade Detail

+

Grade, score, entry/exit, and scaler/runner attribution are shown when present in TOOL-001 trade records.

+
+
+
+ +
+
+

Provenance Health

+

Counts sentinel/default values per field across trade records.

+
+
+
+

Config Integrity

+

ConfigHash and CodeVersion timeline with drift markers.

+
+
+
+
+ + + + + + diff --git a/tools/dashboard/notify.py b/tools/dashboard/notify.py new file mode 100644 index 0000000..1468117 --- /dev/null +++ b/tools/dashboard/notify.py @@ -0,0 +1,52 @@ +"""Outbound notifications for the dashboard server.""" + +from __future__ import annotations + +import json +import sys +from typing import Any, Dict, List + + +class AppriseNotifier: + def __init__(self, config: Dict[str, Any]) -> None: + notifications = config.get("notifications", {}) if isinstance(config.get("notifications", {}), dict) else {} + self.enabled = bool(notifications.get("enabled", False)) + self.targets: List[str] = [str(item) for item in notifications.get("targets", [])] + self.available = False + self._apprise = None + + if not self.enabled: + return + if not self.targets: + sys.stderr.write("dashboard notify: enabled but no Apprise targets configured; notifications disabled\n") + self.enabled = False + return + try: + import apprise # type: ignore + except ImportError: + sys.stderr.write("dashboard notify: Apprise is not installed; run pip install -r tools/dashboard/requirements.txt\n") + self.enabled = False + return + + app = apprise.Apprise() + for target in self.targets: + app.add(target) + self._apprise = app + self.available = True + + def send(self, event: Dict[str, Any]) -> None: + if not self.enabled or not self.available or self._apprise is None: + return + title = "NT8 {0}".format(event.get("type", "event")) + body = json.dumps(event, sort_keys=True) + try: + self._apprise.notify(title=title, body=body) + except Exception as ex: # best-effort notifier boundary + sys.stderr.write("dashboard notify: Apprise send failed; continuing: {0}\n".format(ex)) + + def status(self) -> Dict[str, Any]: + return { + "enabled": self.enabled, + "available": self.available, + "target_count": len(self.targets), + } diff --git a/tools/dashboard/parsers.py b/tools/dashboard/parsers.py new file mode 100644 index 0000000..2e5e6fb --- /dev/null +++ b/tools/dashboard/parsers.py @@ -0,0 +1,220 @@ +"""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 diff --git a/tools/dashboard/requirements.txt b/tools/dashboard/requirements.txt new file mode 100644 index 0000000..ac314ac --- /dev/null +++ b/tools/dashboard/requirements.txt @@ -0,0 +1 @@ +apprise>=1.8.0 diff --git a/tools/dashboard/server.py b/tools/dashboard/server.py new file mode 100644 index 0000000..6e639e7 --- /dev/null +++ b/tools/dashboard/server.py @@ -0,0 +1,327 @@ +#!/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.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, + "live_state": self.live_state, + "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 + 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) + self.raw_tail = parsers.tail_lines(path) + self.current_session_file = str(path) + for line in lines: + event = parsers.parse_session_event(path, line) + if event is not None: + self._handle_event(event) + self.state.save() + + 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: + 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 == "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") + self._handle_pnl_milestones(event) + 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 + + with self.lock: + self.latest_events.append(event) + self.latest_events = self.latest_events[-500:] + + self._notify_event(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()) diff --git a/tools/dashboard/state.py b/tools/dashboard/state.py new file mode 100644 index 0000000..8c4608b --- /dev/null +++ b/tools/dashboard/state.py @@ -0,0 +1,87 @@ +"""Persistent dashboard runtime state. + +The state file lives under tools/dashboard by default. It is used only to +avoid duplicate outbound notifications after server restarts. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, Iterable, Optional, Set + + +class DashboardState: + def __init__(self, path: Path) -> None: + self.path = path + self.offsets: Dict[str, int] = {} + self.partial_lines: Dict[str, str] = {} + self.fingerprints: Set[str] = set() + self.current_session: Optional[str] = None + self.pnl_milestones: Dict[str, Set[str]] = {} + self.load() + + def load(self) -> None: + if not self.path.exists(): + return + try: + payload = json.loads(self.path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + self.offsets = {str(k): int(v) for k, v in payload.get("offsets", {}).items()} + self.partial_lines = {str(k): str(v) for k, v in payload.get("partial_lines", {}).items()} + self.fingerprints = set(str(item) for item in payload.get("fingerprints", [])) + self.current_session = payload.get("current_session") + self.pnl_milestones = {} + for session, values in payload.get("pnl_milestones", {}).items(): + self.pnl_milestones[str(session)] = set(str(item) for item in values) + + def save(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "offsets": self.offsets, + "partial_lines": self.partial_lines, + "fingerprints": sorted(self.fingerprints), + "current_session": self.current_session, + "pnl_milestones": {key: sorted(value) for key, value in self.pnl_milestones.items()}, + } + self.path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8") + + def get_offset(self, path: Path) -> Optional[int]: + return self.offsets.get(str(path)) + + def set_offset(self, path: Path, offset: int) -> None: + self.offsets[str(path)] = int(offset) + + def get_partial(self, path: Path) -> str: + return self.partial_lines.get(str(path), "") + + def set_partial(self, path: Path, value: str) -> None: + if value: + self.partial_lines[str(path)] = value + else: + self.partial_lines.pop(str(path), None) + + def seen_fingerprint(self, value: str) -> bool: + return value in self.fingerprints + + def add_fingerprint(self, value: str) -> None: + self.fingerprints.add(value) + if len(self.fingerprints) > 5000: + self.fingerprints = set(sorted(self.fingerprints)[-3000:]) + + def rollover_session(self, session_key: str) -> None: + if self.current_session != session_key: + self.current_session = session_key + self.pnl_milestones.setdefault(session_key, set()) + + def seen_milestone(self, session_key: str, milestone: float) -> bool: + key = self._milestone_key(milestone) + return key in self.pnl_milestones.setdefault(session_key, set()) + + def add_milestone(self, session_key: str, milestone: float) -> None: + self.pnl_milestones.setdefault(session_key, set()).add(self._milestone_key(milestone)) + + @staticmethod + def _milestone_key(milestone: float) -> str: + return "{0:g}".format(milestone) diff --git a/tools/dashboard/styles.css b/tools/dashboard/styles.css new file mode 100644 index 0000000..7cedd39 --- /dev/null +++ b/tools/dashboard/styles.css @@ -0,0 +1,392 @@ +:root { + --bg: #101418; + --panel: #171d24; + --panel-2: #1d2630; + --text: #edf3f8; + --muted: #95a5b4; + --line: #2c3743; + --accent: #74d3ff; + --good: #49d17d; + --warn: #ffd166; + --bad: #ff6b6b; + --decision: #58d68d; + --defect: #ff6b6b; + --unknown: #a7b0bb; + --purple: #b794f4; + --shadow: 0 18px 45px rgba(0, 0, 0, 0.32); + font-family: Arial, Helvetica, sans-serif; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: radial-gradient(circle at top left, #1c3342 0, var(--bg) 38rem); + color: var(--text); +} + +code { + background: #0d1117; + border: 1px solid var(--line); + border-radius: 0.35rem; + padding: 0.05rem 0.3rem; +} + +.app-header { + display: flex; + gap: 1rem; + justify-content: space-between; + align-items: flex-end; + padding: 2rem; +} + +.eyebrow { + color: var(--accent); + font-size: 0.75rem; + letter-spacing: 0.18em; + margin: 0 0 0.4rem; + text-transform: uppercase; +} + +h1, h2, p { margin-top: 0; } +h1 { font-size: clamp(2rem, 5vw, 4.4rem); line-height: 0.95; margin-bottom: 0.75rem; } +h2 { margin-bottom: 0.55rem; } +.subhead, .panel-note, .load-message, small { color: var(--muted); } + +main { + display: grid; + gap: 1rem; + padding: 0 2rem 2rem; +} + +.panel, .metric-card, .status-card { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.01)), var(--panel); + border: 1px solid var(--line); + border-radius: 1rem; + box-shadow: var(--shadow); +} + +.panel { padding: 1.2rem; } + +.status-card { + min-width: 17rem; + padding: 1rem; + display: grid; + gap: 0.25rem; +} + +.status-label, .metric-card span { + color: var(--muted); + font-size: 0.78rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.input-panel { + display: grid; + gap: 0.8rem; +} + +.input-actions { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; +} + +button, .file-button { + background: var(--accent); + color: #061018; + border: 0; + border-radius: 0.6rem; + cursor: pointer; + display: inline-flex; + font-weight: 700; + padding: 0.7rem 1rem; +} + +button:hover, .file-button:hover { filter: brightness(1.06); } +.file-button input { display: none; } + +textarea { + width: 100%; + min-height: 7rem; + resize: vertical; + background: #0d1117; + border: 1px solid var(--line); + border-radius: 0.8rem; + color: var(--text); + padding: 0.9rem; +} + +.metrics-grid, .split-grid { + display: grid; + gap: 1rem; + grid-template-columns: repeat(4, minmax(0, 1fr)); +} + +.split-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } + +.metric-card { + padding: 1rem; + display: grid; + gap: 0.5rem; +} + +.metric-card strong { font-size: 2rem; } + +.progress-track { + height: 0.55rem; + background: #0d1117; + border-radius: 99rem; + overflow: hidden; +} + +.progress-fill { + width: 0; + height: 100%; + background: linear-gradient(90deg, var(--accent), var(--good)); + transition: width 160ms ease-out; +} + +.section-title { + display: flex; + gap: 1rem; + justify-content: space-between; + align-items: baseline; +} + +.legend { + color: var(--muted); + display: flex; + gap: 1rem; + flex-wrap: wrap; + font-size: 0.9rem; +} + +.dot { + display: inline-block; + width: 0.65rem; + height: 0.65rem; + border-radius: 50%; + margin-right: 0.35rem; +} + +.traded { background: var(--good); } +.silent { background: var(--warn); } +.violation { background: var(--bad); } +.decision { background: var(--decision); } +.defect { background: var(--defect); } +.unknown { background: var(--unknown); } + +.table-wrap { overflow-x: auto; } + +table { + border-collapse: collapse; + min-width: 100%; +} + +th, td { + border-bottom: 1px solid var(--line); + padding: 0.65rem 0.7rem; + text-align: left; + vertical-align: top; + white-space: nowrap; +} + +th { + color: var(--muted); + font-size: 0.75rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +tr.status-traded td:first-child { border-left: 0.35rem solid var(--good); } +tr.status-silent td:first-child { border-left: 0.35rem solid var(--warn); } +tr.status-violation td:first-child { border-left: 0.35rem solid var(--bad); } + +.pill { + border-radius: 99rem; + display: inline-block; + font-size: 0.78rem; + font-weight: 700; + padding: 0.22rem 0.55rem; +} + +.pill.good { background: rgba(73, 209, 125, 0.16); color: var(--good); } +.pill.warn { background: rgba(255, 209, 102, 0.16); color: var(--warn); } +.pill.bad { background: rgba(255, 107, 107, 0.16); color: var(--bad); } +.empty { color: var(--muted); text-align: center; } + +.raw-tail { + background: #0d1117; + border: 1px solid var(--line); + border-radius: 0.8rem; + color: var(--muted); + max-height: 20rem; + overflow: auto; + padding: 0.9rem; + white-space: pre-wrap; +} + +.headline-panel { + border-color: rgba(116, 211, 255, 0.38); +} + +.decision-grid .metric-card { + min-height: 8rem; +} + +.decision-card { border-color: rgba(88, 214, 141, 0.48); } +.defect-card { border-color: rgba(255, 107, 107, 0.48); } +.unknown-card { border-color: rgba(167, 176, 187, 0.48); } + +.health-strip { + display: grid; + gap: 0.35rem; + grid-template-columns: repeat(20, minmax(2.2rem, 1fr)); + margin-top: 1rem; +} + +.health-cell { + border: 1px solid var(--line); + border-radius: 0.45rem; + color: #071017; + font-size: 0.74rem; + font-weight: 700; + min-height: 2.2rem; + padding: 0.55rem 0.25rem; + text-align: center; +} + +.health-cell.traded { background: var(--good); } +.health-cell.silent-by-decision { background: var(--decision); } +.health-cell.silent-by-defect { background: var(--defect); color: #fff; } +.health-cell.config-violation { background: var(--purple); color: #fff; } +.health-cell.silent-unknown { background: var(--unknown); } +.health-cell.no-session { background: #2d3742; color: var(--muted); } + +.silent-explorer { + display: grid; + gap: 0.75rem; +} + +.silent-card { + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 0.8rem; + padding: 0.8rem; +} + +.silent-card.silent-by-decision { border-left: 0.45rem solid var(--decision); } +.silent-card.silent-by-defect { border-left: 0.45rem solid var(--defect); } +.silent-card.silent-unknown { border-left: 0.45rem solid var(--unknown); } + +.silent-title { + align-items: baseline; + display: flex; + gap: 0.75rem; + margin-bottom: 0.65rem; +} + +.silent-title span { + color: var(--muted); + text-transform: capitalize; +} + +.reason-row { + align-items: center; + display: grid; + gap: 0.6rem; + grid-template-columns: 12rem 1fr 4rem; + margin: 0.45rem 0; +} + +.reason-label, .reason-count { + color: var(--text); + font-size: 0.9rem; +} + +.bar-track { + background: #0d1117; + border-radius: 99rem; + height: 0.9rem; + overflow: hidden; +} + +.bar-fill { + height: 100%; +} + +.reason-row.decision .bar-fill { background: var(--decision); } +.reason-row.defect .bar-fill { background: var(--defect); } +.reason-row.unknown .bar-fill { background: var(--unknown); } + +.empty-note { + color: var(--muted); + margin: 0.4rem 0 0; +} + +.histogram { + min-height: 16rem; +} + +.histogram-chart { + align-items: end; + border-bottom: 1px solid var(--line); + border-left: 1px solid var(--line); + display: grid; + gap: 0.35rem; + grid-template-columns: repeat(10, 1fr); + height: 15rem; + margin-top: 1rem; + padding: 1rem 0.5rem 0; + position: relative; +} + +.histogram-bar { + background: var(--warn); + border-radius: 0.35rem 0.35rem 0 0; + min-height: 0.25rem; + position: relative; +} + +.histogram-bar.above-threshold { + background: var(--decision); +} + +.histogram-bar span { + color: var(--text); + font-size: 0.72rem; + left: 50%; + position: absolute; + top: -1.1rem; + transform: translateX(-50%); +} + +.threshold-line { + border-left: 2px solid var(--bad); + bottom: 0; + position: absolute; + top: 0; +} + +.threshold-line span { + background: var(--bad); + border-radius: 0.35rem; + color: #fff; + font-size: 0.72rem; + left: 0.25rem; + padding: 0.15rem 0.35rem; + position: absolute; + top: 0.25rem; + white-space: nowrap; +} + +@media (max-width: 900px) { + .app-header { align-items: stretch; flex-direction: column; padding: 1rem; } + main { padding: 0 1rem 1rem; } + .metrics-grid, .split-grid { grid-template-columns: 1fr; } + .health-strip { grid-template-columns: repeat(5, 1fr); } + .reason-row { grid-template-columns: 1fr; } + .section-title { display: block; } +} diff --git a/tools/logtriage/README.md b/tools/logtriage/README.md new file mode 100644 index 0000000..291bddd --- /dev/null +++ b/tools/logtriage/README.md @@ -0,0 +1,58 @@ +# logtriage + +`logtriage` is a standalone Python CLI for triaging NT8 SDK runtime artifacts without referencing any NinjaTrader assembly or changing deployed NT8 output. + +Python was chosen instead of a .NET console app because it keeps the tool fully outside `NT8-SDK.sln`, requires no solution or publish changes, and avoids any chance of being pulled into `NinjaTrader.Custom.dll` deployment. + +## Inputs + +The script reads these files from a directory: + +- `session_*.log` +- `trades_*.jsonl` +- `provenance_*.json` +- `settings_*.txt` + +Default input directory: + +`%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk` + +## Output + +Text mode prints: + +1. A per-day table with: + `Date | Account | Instrument | BarType | DaysToLoad | DailyBars | WarmupOK | Signals | Submits | Fills | NetPnL | KillSwitch | VerboseLog | ConfigHash(8) | TestMode` +2. A `DIAGNOSTICS` section flagging: + `SILENT DAY`, `PARALLEL INSTANCE`, `NO CONFIG CAPTURE`, `GATE CONFIG VIOLATION`, `CONFIG DRIFT`, and `PROVENANCE DEFECT` + +`--json` emits machine-readable output for dashboard ingestion, including session rows, diagnostics, and per-trade records enriched with source file and line metadata. + +## Usage + +Run against the default NT8 SDK log directory: + +```powershell +python tools/logtriage/logtriage.py +``` + +Run against a specific archive directory: + +```powershell +python tools/logtriage/logtriage.py "C:\logs\nt8-sdk-archive" +``` + +Emit JSON for another tool or dashboard: + +```powershell +python tools/logtriage/logtriage.py --json | Out-File -Encoding utf8 triage.json +``` + +## Notes + +- The tool is read-only. +- It does not import or reference any NinjaTrader or NT8 SDK assembly. +- Session rows are built from `session_*.log` and enriched with nearest same-day `settings_*.txt` and `provenance_*.json` snapshots. +- JSON session rows include `config_hash`, `config_hash_8`, and `code_version` when present in settings or provenance artifacts. +- JSON output includes `trade_records` copied from `trades_*.jsonl` with added `date`, `path`, and `line` fields for dashboard traceability. +- Trade provenance defects are scanned directly from `trades_*.jsonl` rows. diff --git a/tools/logtriage/logtriage.py b/tools/logtriage/logtriage.py new file mode 100644 index 0000000..b22d633 --- /dev/null +++ b/tools/logtriage/logtriage.py @@ -0,0 +1,771 @@ +#!/usr/bin/env python3 +"""Standalone NT8 SDK log triage utility. + +Reads session logs, settings exports, provenance snapshots, and trade JSONL files +from the NT8 SDK log directory and emits a per-day summary table plus diagnostics. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from dataclasses import dataclass, field +from datetime import datetime +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar + + +DEFAULT_INPUT_DIR = r"%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk" +FILENAME_TIMESTAMP_FORMAT = "%Y%m%d_%H%M%S" + + +SESSION_FILE_RE = re.compile(r"^session_(\d{8})_(\d{6})\.log$", re.IGNORECASE) +SETTINGS_FILE_RE = re.compile(r"^settings_.+_(\d{8})_(\d{6})\.txt$", re.IGNORECASE) +PROVENANCE_FILE_RE = re.compile(r"^provenance_.+_(\d{8})_(\d{6})\.json$", re.IGNORECASE) +TRADES_FILE_RE = re.compile(r"^trades_.+_(\d{8})\.jsonl$", re.IGNORECASE) + +ACCOUNT_RE = re.compile(r"Account\s*:\s*(.+)$") +SYMBOL_RE = re.compile(r"Symbol\s*:\s*(.+)$") +VERBOSE_RE = re.compile(r"VerboseLog\s*:\s*(True|False)\s+FileLog:\s*(True|False)", re.IGNORECASE) +DATA_SERIES_RE = re.compile( + r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=(\d+)\s+HistoricalBarsLoaded=(\d+)", + re.IGNORECASE, +) +FACTOR_WARMUP_RE = re.compile( + r"FactorWarmup\s*:\s*NarrowRangeFactorCalculator=(SATISFIED|NOT SATISFIED)\s+\((\d+)/7 daily bars\)\s+" + r"OrbRangeVsAtrFactorCalculator=(SATISFIED|NOT SATISFIED)", + re.IGNORECASE, +) +PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=\$?(-?[\d,]+(?:\.\d+)?)", re.IGNORECASE) +TEST_MODE_RE = re.compile(r"\|\s*<(TEST MODE ACTIVE|LIVE MODE)>", re.IGNORECASE) +KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$") +T = TypeVar("T") + + +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Summarize NT8 SDK session artifacts.") + parser.add_argument( + "input_dir", + nargs="?", + default=DEFAULT_INPUT_DIR, + help="Directory containing session_*.log, settings_*.txt, provenance_*.json, and trades_*.jsonl", + ) + parser.add_argument( + "--json", + action="store_true", + help="Emit machine-readable JSON instead of a text table.", + ) + return parser.parse_args(argv) + + +def expand_input_dir(raw_path: str) -> Path: + expanded = os.path.expanduser(os.path.expandvars(raw_path)) + return Path(expanded) + + +def parse_bool(value: Any) -> Optional[bool]: + if isinstance(value, bool): + return value + if value is None: + return None + text = str(value).strip().lower() + if text == "true": + return True + if text == "false": + return False + return None + + +def parse_float(value: Any) -> Optional[float]: + if value is None: + return None + if isinstance(value, (float, int)): + return float(value) + text = str(value).strip().replace("$", "").replace(",", "") + if not text: + return None + try: + return float(text) + except ValueError: + return None + + +def parse_timestamp_from_match(match: re.Match[str]) -> datetime: + return datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), FILENAME_TIMESTAMP_FORMAT) + + +def safe_json_load(path: Path) -> Optional[Any]: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + +def read_lines(path: Path) -> List[str]: + try: + return path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return [] + + +@dataclass +class SessionSummary: + path: Path + timestamp: datetime + date: str + account: Optional[str] = None + instrument: Optional[str] = None + session_bar_type: Optional[str] = None + bar_type: Optional[str] = None + days_to_load: Optional[int] = None + daily_bars: Optional[int] = None + warmup_ok: Optional[bool] = None + signals: int = 0 + submits: int = 0 + fills: int = 0 + net_pnl: Optional[float] = None + kill_switch: Optional[bool] = None + verbose_log: Optional[bool] = None + config_hash: Optional[str] = None + code_version: Optional[str] = None + test_mode: Optional[bool] = None + session_start: bool = False + settings_captured: bool = False + session_id: Optional[str] = None + source_files: Dict[str, str] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + return { + "date": self.date, + "account": self.account, + "instrument": self.instrument, + "bar_type": self.bar_type, + "session_bar_type": self.session_bar_type, + "days_to_load": self.days_to_load, + "daily_bars": self.daily_bars, + "warmup_ok": self.warmup_ok, + "signals": self.signals, + "submits": self.submits, + "fills": self.fills, + "net_pnl": self.net_pnl, + "kill_switch": self.kill_switch, + "verbose_log": self.verbose_log, + "config_hash": self.config_hash, + "config_hash_8": short_hash(self.config_hash), + "code_version": self.code_version, + "test_mode": self.test_mode, + "session_start": self.session_start, + "settings_captured": self.settings_captured, + "session_id": self.session_id, + "timestamp": self.timestamp.isoformat(), + "source_files": self.source_files, + } + + +@dataclass +class SettingsSnapshot: + path: Path + timestamp: datetime + date: str + account: Optional[str] = None + instrument: Optional[str] = None + bars_period: Optional[str] = None + enable_kill_switch: Optional[bool] = None + enable_verbose_logging: Optional[bool] = None + test_mode: Optional[bool] = None + config_hash: Optional[str] = None + code_version: Optional[str] = None + + +@dataclass +class ProvenanceSnapshot: + path: Path + timestamp: datetime + date: str + session_id: Optional[str] = None + config_hash: Optional[str] = None + code_version: Optional[str] = None + test_mode: Optional[bool] = None + + +@dataclass +class TradeAggregate: + path: Path + date: str + session_id: Optional[str] + submits: int = 0 + records: List[Dict[str, Any]] = field(default_factory=list) + provenance_defects: List[Dict[str, Any]] = field(default_factory=list) + + +def short_hash(value: Optional[str]) -> Optional[str]: + if not value: + return None + return value[:8] + + +def format_bool(value: Optional[bool]) -> str: + if value is True: + return "True" + if value is False: + return "False" + return "?" + + +def format_text(value: Optional[Any]) -> str: + if value is None: + return "?" + text = str(value).strip() + return text if text else "?" + + +def format_pnl(value: Optional[float]) -> str: + if value is None: + return "?" + return "{0:.2f}".format(value) + + +def parse_session_file(path: Path) -> SessionSummary: + match = SESSION_FILE_RE.match(path.name) + if not match: + raise ValueError("Invalid session file name: {0}".format(path.name)) + + timestamp = parse_timestamp_from_match(match) + summary = SessionSummary( + path=path, + timestamp=timestamp, + date=timestamp.strftime("%Y-%m-%d"), + source_files={"session": path.name}, + ) + + for line in read_lines(path): + if "=== SESSION START" in line: + summary.session_start = True + + account_match = ACCOUNT_RE.search(line) + if account_match: + summary.account = account_match.group(1).strip() + + symbol_match = SYMBOL_RE.search(line) + if symbol_match: + summary.instrument = symbol_match.group(1).strip() + + verbose_match = VERBOSE_RE.search(line) + if verbose_match: + summary.verbose_log = parse_bool(verbose_match.group(1)) + + data_series_match = DATA_SERIES_RE.search(line) + if data_series_match: + index = int(data_series_match.group(1)) + bar_type = data_series_match.group(2).strip() + days_to_load = int(data_series_match.group(3)) + loaded_bars = int(data_series_match.group(4)) + + if index == 0: + summary.session_bar_type = bar_type + if summary.bar_type is None: + summary.bar_type = bar_type + summary.days_to_load = days_to_load + + if "daybarstype" in bar_type.lower(): + summary.daily_bars = loaded_bars + + factor_match = FACTOR_WARMUP_RE.search(line) + if factor_match: + summary.warmup_ok = ( + factor_match.group(1).upper() == "SATISFIED" + and factor_match.group(3).upper() == "SATISFIED" + ) + if summary.daily_bars is None: + summary.daily_bars = int(factor_match.group(2)) + + if "WARNING: EnableKillSwitch=False" in line: + summary.kill_switch = False + + if "SIGNAL:" in line: + summary.signals += 1 + + if "SUBMIT " in line: + summary.submits += 1 + + if "FILL " in line: + summary.fills += 1 + + pnl_match = PNL_RE.search(line) + if pnl_match: + summary.net_pnl = parse_float(pnl_match.group(1)) + + test_mode_match = TEST_MODE_RE.search(line) + if test_mode_match: + summary.test_mode = test_mode_match.group(1).upper() == "TEST MODE ACTIVE" + + return summary + + +def parse_settings_file(path: Path) -> SettingsSnapshot: + match = SETTINGS_FILE_RE.match(path.name) + if not match: + raise ValueError("Invalid settings file name: {0}".format(path.name)) + + timestamp = parse_timestamp_from_match(match) + snapshot = SettingsSnapshot(path=path, timestamp=timestamp, date=timestamp.strftime("%Y-%m-%d")) + + for raw_line in read_lines(path): + key_match = KEY_VALUE_RE.match(raw_line) + if not key_match: + continue + + key = key_match.group(1).strip() + value = key_match.group(2).strip() + + if key == "Account": + snapshot.account = value + elif key == "Instrument": + snapshot.instrument = value + elif key == "BarsPeriod": + snapshot.bars_period = value + elif key == "EnableKillSwitch": + snapshot.enable_kill_switch = parse_bool(value) + elif key == "EnableVerboseLogging": + snapshot.enable_verbose_logging = parse_bool(value) + elif key == "TestMode": + snapshot.test_mode = parse_bool(value) + elif key == "ConfigHash": + snapshot.config_hash = value + elif key == "CodeVersion": + snapshot.code_version = value + + return snapshot + + +def parse_provenance_file(path: Path) -> Optional[ProvenanceSnapshot]: + match = PROVENANCE_FILE_RE.match(path.name) + if not match: + raise ValueError("Invalid provenance file name: {0}".format(path.name)) + + payload = safe_json_load(path) + if not isinstance(payload, dict): + return None + + timestamp = parse_timestamp_from_match(match) + banner = str(payload.get("test_mode_banner", "")).strip().upper() + test_mode: Optional[bool] = None + if banner == "": + test_mode = True + elif banner == "": + test_mode = False + + return ProvenanceSnapshot( + path=path, + timestamp=timestamp, + date=timestamp.strftime("%Y-%m-%d"), + session_id=payload.get("session_id"), + config_hash=payload.get("config_hash"), + code_version=payload.get("code_version"), + test_mode=test_mode, + ) + + +def parse_trade_files(paths: Sequence[Path]) -> Tuple[Dict[Tuple[str, Optional[str]], TradeAggregate], List[Dict[str, Any]]]: + aggregates: Dict[Tuple[str, Optional[str]], TradeAggregate] = {} + defects: List[Dict[str, Any]] = [] + + for path in paths: + match = TRADES_FILE_RE.match(path.name) + if not match: + continue + + date = datetime.strptime(match.group(1), "%Y%m%d").strftime("%Y-%m-%d") + for line_number, raw_line in enumerate(read_lines(path), start=1): + text = raw_line.strip() + if not text: + continue + + try: + row = json.loads(text) + except ValueError: + defects.append( + { + "date": date, + "code": "PROVENANCE DEFECT", + "message": "Invalid JSON in trade file {0}:{1}".format(path.name, line_number), + "path": path.name, + "line": line_number, + } + ) + continue + + session_id = row.get("session_id") + key = (date, session_id) + aggregate = aggregates.get(key) + if aggregate is None: + aggregate = TradeAggregate(path=path, date=date, session_id=session_id) + aggregates[key] = aggregate + aggregate.submits += 1 + record = dict(row) + record["date"] = date + record["path"] = path.name + record["line"] = line_number + aggregate.records.append(record) + + defect_fields: List[str] = [] + if str(row.get("confluence_grade", "")).strip() == "Unknown": + defect_fields.append("confluence_grade=Unknown") + if parse_float(row.get("confluence_score")) == 0.0: + defect_fields.append("confluence_score=0.0") + if str(row.get("risk_mode", "")).strip() == "Unknown": + defect_fields.append("risk_mode=Unknown") + if parse_float(row.get("OrbRangeTicks")) == 0.0: + defect_fields.append("OrbRangeTicks=0.0") + + if defect_fields: + defect = { + "date": date, + "code": "PROVENANCE DEFECT", + "message": ", ".join(defect_fields), + "path": path.name, + "line": line_number, + "session_id": session_id, + "trade_seq": row.get("trade_seq"), + } + aggregate.provenance_defects.append(defect) + defects.append(defect) + + return aggregates, defects + + +def nearest_same_day(items: Sequence[T], target: datetime, get_timestamp: Callable[[T], datetime]) -> Optional[T]: + best_item: Optional[T] = None + best_delta: Optional[float] = None + for item in items: + delta = abs((get_timestamp(item) - target).total_seconds()) + if best_delta is None or delta < best_delta: + best_item = item + best_delta = delta + return best_item + + +def build_rows( + sessions: Sequence[SessionSummary], + settings_by_date: Dict[str, List[SettingsSnapshot]], + provenance_by_date: Dict[str, List[ProvenanceSnapshot]], + trades_by_session: Dict[Tuple[str, Optional[str]], TradeAggregate], +) -> List[SessionSummary]: + rows: List[SessionSummary] = [] + + for session in sorted(sessions, key=lambda item: item.timestamp): + settings = nearest_same_day(settings_by_date.get(session.date, []), session.timestamp, lambda item: item.timestamp) + provenance = nearest_same_day(provenance_by_date.get(session.date, []), session.timestamp, lambda item: item.timestamp) + + if settings is not None: + session.settings_captured = True + session.source_files["settings"] = settings.path.name + if session.account is None: + session.account = settings.account + if session.instrument is None: + session.instrument = settings.instrument + if settings.bars_period: + session.bar_type = settings.bars_period + if settings.enable_kill_switch is not None: + session.kill_switch = settings.enable_kill_switch + if settings.enable_verbose_logging is not None: + session.verbose_log = settings.enable_verbose_logging + if settings.test_mode is not None: + session.test_mode = settings.test_mode + if settings.config_hash: + session.config_hash = settings.config_hash + if settings.code_version: + session.code_version = settings.code_version + + if provenance is not None: + session.source_files["provenance"] = provenance.path.name + session.session_id = provenance.session_id + if provenance.config_hash and not session.config_hash: + session.config_hash = provenance.config_hash + if provenance.code_version and not session.code_version: + session.code_version = provenance.code_version + if provenance.test_mode is not None and session.test_mode is None: + session.test_mode = provenance.test_mode + + if session.session_id is not None: + trade_aggregate = trades_by_session.get((session.date, session.session_id)) + if trade_aggregate is not None: + session.source_files["trades"] = trade_aggregate.path.name + if trade_aggregate.submits > session.submits: + session.submits = trade_aggregate.submits + + rows.append(session) + + return rows + + +def build_diagnostics( + rows: Sequence[SessionSummary], + settings_by_date: Dict[str, List[SettingsSnapshot]], + provenance_by_date: Dict[str, List[ProvenanceSnapshot]], + trade_defects: Sequence[Dict[str, Any]], +) -> List[Dict[str, Any]]: + diagnostics: List[Dict[str, Any]] = [] + rows_by_date: Dict[str, List[SessionSummary]] = {} + for row in rows: + rows_by_date.setdefault(row.date, []).append(row) + + all_dates = set(rows_by_date.keys()) + all_dates.update(settings_by_date.keys()) + all_dates.update(provenance_by_date.keys()) + dates = sorted(all_dates) + previous_hashes: Optional[Tuple[str, Tuple[str, ...]]] = None + + for date in dates: + day_rows = rows_by_date.get(date, []) + day_settings = settings_by_date.get(date, []) + day_provenance = provenance_by_date.get(date, []) + accounts = sorted( + {row.account for row in day_rows if row.account}.union( + {item.account for item in day_settings if item.account} + ) + ) + config_hashes = sorted( + {row.config_hash for row in day_rows if row.config_hash}.union( + {item.config_hash for item in day_settings if item.config_hash} + ).union( + {item.config_hash for item in day_provenance if item.config_hash} + ) + ) + session_rows = [row for row in day_rows if row.session_start] + bar_types = sorted({row.session_bar_type or row.bar_type for row in day_rows if row.session_bar_type or row.bar_type}) + + if session_rows: + day_activity = sum(row.signals + row.submits + row.fills for row in session_rows) + if day_activity == 0: + diagnostics.append( + { + "date": date, + "code": "SILENT DAY", + "message": "SESSION START present with zero SIGNAL/SUBMIT/FILL lines for the day.", + "sessions": [row.path.name for row in session_rows], + } + ) + + if len(accounts) > 1 or len(config_hashes) > 1 or len(bar_types) > 1: + diagnostics.append( + { + "date": date, + "code": "PARALLEL INSTANCE", + "message": "Multiple accounts, config hashes, or primary bar types observed on the same day.", + "accounts": accounts, + "config_hashes": config_hashes, + "bar_types": bar_types, + } + ) + + if session_rows and not settings_by_date.get(date): + diagnostics.append( + { + "date": date, + "code": "NO CONFIG CAPTURE", + "message": "Session log exists but no settings_*.txt was found for the day.", + } + ) + + for row in day_rows: + if row.kill_switch is False or row.verbose_log is False: + details: List[str] = [] + if row.kill_switch is False: + details.append("EnableKillSwitch=False") + if row.verbose_log is False: + details.append("VerboseLog=False") + diagnostics.append( + { + "date": date, + "code": "GATE CONFIG VIOLATION", + "message": ", ".join(details), + "session": row.path.name, + } + ) + + hash_tuple = tuple(config_hashes) + if hash_tuple: + if previous_hashes is not None and previous_hashes[1] != hash_tuple: + diagnostics.append( + { + "date": date, + "code": "CONFIG DRIFT", + "message": "ConfigHash set changed from previous observed day.", + "previous_date": previous_hashes[0], + "previous_config_hashes": list(previous_hashes[1]), + "current_config_hashes": list(hash_tuple), + } + ) + previous_hashes = (date, hash_tuple) + + diagnostics.extend(sorted(trade_defects, key=lambda item: (item.get("date", ""), item.get("path", ""), item.get("line", 0)))) + + return diagnostics + + +def row_table_values(row: SessionSummary) -> List[str]: + return [ + row.date, + format_text(row.account), + format_text(row.instrument), + format_text(row.bar_type), + format_text(row.days_to_load), + format_text(row.daily_bars), + format_bool(row.warmup_ok), + str(row.signals), + str(row.submits), + str(row.fills), + format_pnl(row.net_pnl), + format_bool(row.kill_switch), + format_bool(row.verbose_log), + format_text(short_hash(row.config_hash)), + format_bool(row.test_mode), + ] + + +def render_table(rows: Sequence[SessionSummary]) -> str: + headers = [ + "Date", + "Account", + "Instrument", + "BarType", + "DaysToLoad", + "DailyBars", + "WarmupOK", + "Signals", + "Submits", + "Fills", + "NetPnL", + "KillSwitch", + "VerboseLog", + "ConfigHash(8)", + "TestMode", + ] + + lines: List[List[str]] = [headers] + for row in rows: + lines.append(row_table_values(row)) + + widths = [0] * len(headers) + for line in lines: + for index, value in enumerate(line): + widths[index] = max(widths[index], len(value)) + + rendered: List[str] = [] + for line_index, line in enumerate(lines): + rendered.append(" | ".join(value.ljust(widths[index]) for index, value in enumerate(line))) + if line_index == 0: + rendered.append("-+-".join("-" * widths[index] for index in range(len(widths)))) + + return "\n".join(rendered) + + +def render_diagnostics(diagnostics: Sequence[Dict[str, Any]]) -> str: + if not diagnostics: + return "DIAGNOSTICS\nNone" + + lines = ["DIAGNOSTICS"] + for item in diagnostics: + lines.append("[{0}] {1}: {2}".format(item.get("date", "?"), item.get("code", "?"), item.get("message", ""))) + return "\n".join(lines) + + +def collect_inputs(input_dir: Path) -> Tuple[List[SessionSummary], Dict[str, List[SettingsSnapshot]], Dict[str, List[ProvenanceSnapshot]], Dict[Tuple[str, Optional[str]], TradeAggregate], List[Dict[str, Any]]]: + sessions: List[SessionSummary] = [] + settings_by_date: Dict[str, List[SettingsSnapshot]] = {} + provenance_by_date: Dict[str, List[ProvenanceSnapshot]] = {} + + trade_paths: List[Path] = [] + + for path in sorted(input_dir.rglob("*")): + if not path.is_file(): + continue + + if SESSION_FILE_RE.match(path.name): + sessions.append(parse_session_file(path)) + continue + + if SETTINGS_FILE_RE.match(path.name): + snapshot = parse_settings_file(path) + settings_by_date.setdefault(snapshot.date, []).append(snapshot) + continue + + if PROVENANCE_FILE_RE.match(path.name): + snapshot = parse_provenance_file(path) + if snapshot is not None: + provenance_by_date.setdefault(snapshot.date, []).append(snapshot) + continue + + if TRADES_FILE_RE.match(path.name): + trade_paths.append(path) + + trades_by_session, trade_defects = parse_trade_files(trade_paths) + return sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects + + +def build_output(input_dir: Path) -> Dict[str, Any]: + sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects = collect_inputs(input_dir) + rows = build_rows(sessions, settings_by_date, provenance_by_date, trades_by_session) + diagnostics = build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects) + trade_records: List[Dict[str, Any]] = [] + for key in sorted(trades_by_session.keys(), key=lambda item: (item[0], item[1] or "")): + trade_records.extend(trades_by_session[key].records) + + return { + "tool": "logtriage", + "implementation": { + "language": "Python", + "reason": "Standalone script avoids any NT8 assembly reference, solution change, or deployed output impact.", + }, + "source_dir": str(input_dir), + "generated_at_utc": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), + "rows": [row.to_dict() for row in rows], + "trade_records": trade_records, + "diagnostics": diagnostics, + } + + +def main(argv: Sequence[str]) -> int: + args = parse_args(argv) + input_dir = expand_input_dir(args.input_dir) + + if not input_dir.exists() or not input_dir.is_dir(): + sys.stderr.write("Input directory not found: {0}\n".format(input_dir)) + return 1 + + sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects = collect_inputs(input_dir) + rows = build_rows(sessions, settings_by_date, provenance_by_date, trades_by_session) + diagnostics = build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects) + trade_records: List[Dict[str, Any]] = [] + for key in sorted(trades_by_session.keys(), key=lambda item: (item[0], item[1] or "")): + trade_records.extend(trades_by_session[key].records) + + output = { + "tool": "logtriage", + "implementation": { + "language": "Python", + "reason": "Standalone script avoids any NT8 assembly reference, solution change, or deployed output impact.", + }, + "source_dir": str(input_dir), + "generated_at_utc": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), + "rows": [row.to_dict() for row in rows], + "trade_records": trade_records, + "diagnostics": diagnostics, + } + + if args.json: + json.dump(output, sys.stdout, indent=2) + sys.stdout.write("\n") + return 0 + + sys.stdout.write(render_table(rows) + "\n\n") + sys.stdout.write(render_diagnostics(diagnostics) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/logwatch/README.md b/tools/logwatch/README.md new file mode 100644 index 0000000..602d806 --- /dev/null +++ b/tools/logwatch/README.md @@ -0,0 +1,189 @@ +# logwatch + +`logwatch.py` is a standalone, read-only Python log tailer for NT8 SDK session logs. It has no NinjaTrader assembly references, no DLL involvement, and does not write to any NinjaTrader directory. + +It tails the newest `session_*.log` under the configured log directory and emits JSON payloads to a webhook. Use `--dry-run` to print payloads to stdout instead of posting. + +## Safety + +- Reads log files using shared normal file reads only. +- Never opens logs for writing. +- Never writes to the NinjaTrader directory. +- Webhook failures are written to stderr and do not crash or block the watcher. +- Default `config.json` ships with an empty `webhook_url`. + +## Launch + +Dry run against the default log directory: + +```powershell +python tools\logwatch\logwatch.py --dry-run +``` + +Process the current newest session from the beginning once: + +```powershell +python tools\logwatch\logwatch.py --dry-run --from-start --once +``` + +Override the log directory: + +```powershell +python tools\logwatch\logwatch.py --dry-run --log-dir "C:\Users\billy\Documents\NinjaTrader 8\log\nt8-sdk" +``` + +Post to a webhook: + +```powershell +python tools\logwatch\logwatch.py --webhook-url "http://127.0.0.1:5678/webhook/nt8-logwatch" +``` + +## Config + +Edit `tools/logwatch/config.json`: + +```json +{ + "webhook_url": "", + "log_dir": "%USERPROFILE%\\Documents\\NinjaTrader 8\\log\\nt8-sdk", + "orb_window_start": "09:30", + "orb_window_end": "10:15", + "timezone": "America/New_York", + "events": { + "session_start": true, + "signal": true, + "submit": true, + "reject": true, + "reject_summary": true, + "warning": true, + "connection": true, + "silent_window_alert": true + } +} +``` + +## n8n Webhook Example + +1. Create a new n8n workflow. +2. Add a `Webhook` trigger node. +3. Set method to `POST`. +4. Set path to `nt8-logwatch`. +5. Add a `Switch` node using `{{$json.event_type}}`. +6. Add branches for `SILENT WINDOW ALERT`, `REJECT`, `WARNING`, and `SIGNAL`. +7. Send high-priority notifications for `SILENT WINDOW ALERT` and `CONNECTION LOST`. +8. Copy the test or production webhook URL into `config.json` or pass it with `--webhook-url`. + +## Event Payloads + +### SESSION START + +```json +{ + "tool": "logwatch", + "event_type": "SESSION START", + "session_file": "C:\\Users\\billy\\Documents\\NinjaTrader 8\\log\\nt8-sdk\\session_20260813_070512.log", + "session_date": "2026-08-13", + "started_at": "2026-08-13 07:05:12", + "account": "SimSimple ORB", + "instrument": "NQ SEP26", + "bar_type": "HFTAlgoBarsType", + "days_to_load": 3, + "historical_bars_loaded": 750199, + "warmup_status": "NarrowRangeFactorCalculator=SATISFIED (87/7 daily bars) OrbRangeVsAtrFactorCalculator=SATISFIED (87/5 daily bars)", + "emitted_at_utc": "2026-08-16T04:00:00Z" +} +``` + +### SIGNAL + +```json +{ + "tool": "logwatch", + "event_type": "SIGNAL", + "side": "Buy", + "grade": "A", + "score": 0.83, + "raw": "Buy NQ SEP26 | grade=A score=0.83", + "session_date": "2026-08-10" +} +``` + +### SUBMIT + +```json +{ + "tool": "logwatch", + "event_type": "SUBMIT", + "mode": "Mode1DualLeg", + "quantity": 2, + "raw": "mode=Mode1DualLeg quantity=2" +} +``` + +### REJECT + +```json +{ + "tool": "logwatch", + "event_type": "REJECT", + "reason": "GradeFilter", + "detail": "Score=4.300 Grade=C MinTradeGrade=B Factors=...", + "bar": "2026-08-13 09:45:00" +} +``` + +Only the first `REJECT` per reason is emitted each session. + +### REJECT SUMMARY + +```json +{ + "tool": "logwatch", + "event_type": "REJECT SUMMARY", + "reason": "GradeFilter", + "count": 311 +} +``` + +### WARNING + +```json +{ + "tool": "logwatch", + "event_type": "WARNING", + "message": "DataSeries[0] DaysToLoad below 30; DaysToLoad=3. Advisory only; trading is not blocked." +} +``` + +### CONNECTION LOST / RESTORED + +```json +{ + "tool": "logwatch", + "event_type": "CONNECTION LOST", + "status": "LOST" +} +``` + +### SILENT WINDOW ALERT + +```json +{ + "tool": "logwatch", + "event_type": "SILENT WINDOW ALERT", + "session_date": "2026-08-13", + "orb_window_start": "09:30", + "orb_window_end": "10:15", + "timezone": "America/New_York", + "message": "ORB window elapsed with no SIGNAL line in the active session log." +} +``` + +This is the early-warning event for GAP-034: the ORB window has elapsed and the active session log has no `SIGNAL:` line. + +## Robustness Notes + +- Newer `session_*.log` files are detected and tailed automatically. +- Partial lines are buffered until complete. +- If NT8 rotates/truncates a file, the read offset resets safely. +- File-lock/read errors are reported to stderr and retried on the next poll. diff --git a/tools/logwatch/config.json b/tools/logwatch/config.json new file mode 100644 index 0000000..30e45e2 --- /dev/null +++ b/tools/logwatch/config.json @@ -0,0 +1,17 @@ +{ + "webhook_url": "", + "log_dir": "%USERPROFILE%\\Documents\\NinjaTrader 8\\log\\nt8-sdk", + "orb_window_start": "09:30", + "orb_window_end": "10:15", + "timezone": "America/New_York", + "events": { + "session_start": true, + "signal": true, + "submit": true, + "reject": true, + "reject_summary": true, + "warning": true, + "connection": true, + "silent_window_alert": true + } +} diff --git a/tools/logwatch/logwatch.py b/tools/logwatch/logwatch.py new file mode 100644 index 0000000..6a23c2a --- /dev/null +++ b/tools/logwatch/logwatch.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +"""Standalone NT8 SDK session log watcher. + +Tails the newest session_*.log file and emits JSON events to a webhook or stdout. +This tool is read-only with respect to NinjaTrader directories. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import time +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from datetime import date, datetime, time as dt_time, timedelta +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple + +try: + from zoneinfo import ZoneInfo +except ImportError: # pragma: no cover - Python < 3.9 fallback + ZoneInfo = None # type: ignore + + +DEFAULT_CONFIG_PATH = Path(__file__).with_name("config.json") +SESSION_FILE_RE = re.compile(r"^session_(\d{8})_(\d{6})\.log$", 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) +SESSION_END_RE = re.compile(r"=== SESSION END\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+===", re.IGNORECASE) +KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$") +DATA_SERIES_RE = re.compile( + r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=(\d+)\s+HistoricalBarsLoaded=(\d+)", + re.IGNORECASE, +) +FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE) +SIGNAL_RE = re.compile(r"SIGNAL:\s*(.*)$", re.IGNORECASE) +SUBMIT_RE = re.compile(r"\bSUBMIT\b\s*:?(.*)$", re.IGNORECASE) +REJECT_RE = re.compile(r"REJECT:\s*reason=([^\s]+)\s+detail=(.*?)(?:\s+bar=(.*))?$", re.IGNORECASE) +REJECT_SUMMARY_RE = re.compile(r"REJECT SUMMARY:\s*reason=([^\s]+)\s+count=(\d+)", re.IGNORECASE) +WARNING_RE = re.compile(r"WARNING:\s*(.*)$", re.IGNORECASE) +CONNECTION_RE = re.compile(r"CONNECTION\s+(LOST|RESTORED)", re.IGNORECASE) +GRADE_RE = re.compile(r"\bgrade(?:=|\s+)([A-Za-z0-9+]+)", re.IGNORECASE) +SCORE_RE = re.compile(r"\bscore(?:=|\s+)(-?\d+(?:\.\d+)?)", re.IGNORECASE) +SIDE_RE = re.compile(r"\b(Buy|Sell|Long|Short)\b", re.IGNORECASE) +MODE_RE = re.compile(r"\b(?:mode|resolvedMode|runnerMode)=([^\s,;|]+)", re.IGNORECASE) +QUANTITY_RE = re.compile(r"\b(?:qty|quantity|contracts)=?(\d+)\b", re.IGNORECASE) + + +@dataclass +class SessionHeader: + started_at: Optional[str] = None + account: Optional[str] = None + instrument: Optional[str] = None + bar_type: Optional[str] = None + days_to_load: Optional[int] = None + historical_bars_loaded: Optional[int] = None + warmup_status: Optional[str] = None + emitted: bool = False + + +@dataclass +class WatchState: + current_path: Optional[Path] = None + offset: int = 0 + partial: str = "" + session_header: SessionHeader = field(default_factory=SessionHeader) + session_date: Optional[date] = None + event_date: Optional[date] = None + previous_line_time: Optional[dt_time] = None + signal_seen: bool = False + silent_alert_sent: bool = False + signal_dates: Set[date] = field(default_factory=set) + silent_alert_dates: Set[date] = field(default_factory=set) + session_ended: bool = False + reject_reasons_seen: Set[str] = field(default_factory=set) + + +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Tail NT8 SDK session logs and emit webhook events.") + parser.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), help="Path to config.json") + parser.add_argument("--dry-run", action="store_true", help="Print payloads to stdout instead of POSTing") + parser.add_argument("--log-dir", help="Override config log_dir") + parser.add_argument("--webhook-url", help="Override config webhook_url") + parser.add_argument("--poll-seconds", type=float, default=2.0, help="Polling interval") + parser.add_argument("--from-start", action="store_true", help="Read current newest session file from the beginning") + parser.add_argument("--once", action="store_true", help="Process available data once and exit") + return parser.parse_args(argv) + + +def expand_path(raw_path: str) -> Path: + return Path(os.path.expanduser(os.path.expandvars(raw_path))) + + +def load_config(path: Path) -> Dict[str, Any]: + try: + with path.open("r", encoding="utf-8") as handle: + return json.load(handle) + except OSError: + return {} + except ValueError as ex: + raise RuntimeError("Invalid config JSON: {0}".format(ex)) + + +def event_enabled(config: Dict[str, Any], event_type: str) -> bool: + events = config.get("events") + if not isinstance(events, dict): + return True + return bool(events.get(event_type, True)) + + +def newest_session_file(log_dir: Path) -> Optional[Path]: + newest: Optional[Tuple[datetime, Path]] = None + try: + iterator = log_dir.rglob("session_*.log") + for path in iterator: + 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) + except OSError as ex: + sys.stderr.write("logwatch: cannot scan log directory {0}: {1}\n".format(log_dir, ex)) + return None + return newest[1] if newest is not None else None + + +def parse_time(value: str) -> dt_time: + return datetime.strptime(value, "%H:%M").time() + + +def now_in_timezone(name: str) -> datetime: + if ZoneInfo is not None: + try: + return datetime.now(ZoneInfo(name)) + except Exception: + pass + return datetime.now() + + +def strip_timestamp(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_log_timestamp_time(value: Optional[str]) -> Optional[dt_time]: + if value is None: + return None + text = value.split(".", 1)[0] + try: + return datetime.strptime(text, "%H:%M:%S").time() + except ValueError: + return None + + +def timestamp_from_session_filename(path: Path) -> Optional[datetime]: + match = SESSION_FILE_RE.match(path.name) + if match is None: + return None + return datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S") + + +def update_event_date(state: WatchState, timestamp_text: Optional[str]) -> None: + line_time = parse_log_timestamp_time(timestamp_text) + if line_time is None: + return + if state.event_date is None: + state.event_date = state.session_date + if state.previous_line_time is not None and line_time < state.previous_line_time: + if state.event_date is not None: + state.event_date = state.event_date + timedelta(days=1) + state.previous_line_time = line_time + + +def emit(config: Dict[str, Any], dry_run: bool, payload: Dict[str, Any]) -> None: + payload["emitted_at_utc"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") + payload["tool"] = "logwatch" + + webhook_url = str(config.get("webhook_url") or "").strip() + if dry_run or not webhook_url: + sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n") + sys.stdout.flush() + return + + data = json.dumps(payload).encode("utf-8") + request = urllib.request.Request( + webhook_url, + data=data, + headers={"Content-Type": "application/json", "User-Agent": "nt8-sdk-logwatch/1.0"}, + method="POST", + ) + try: + with urllib.request.urlopen(request, timeout=5) as response: + response.read() + except (urllib.error.URLError, OSError, ValueError) as ex: + sys.stderr.write("logwatch: webhook POST failed; continuing: {0}\n".format(ex)) + + +def base_payload(event_type: str, state: WatchState, line: Optional[str] = None) -> Dict[str, Any]: + payload: Dict[str, Any] = { + "event_type": event_type, + "session_file": str(state.current_path) if state.current_path is not None else None, + } + if state.event_date is not None: + payload["session_date"] = state.event_date.isoformat() + payload["event_date"] = state.event_date.isoformat() + elif state.session_date is not None: + payload["session_date"] = state.session_date.isoformat() + payload["event_date"] = state.session_date.isoformat() + if line is not None: + payload["line"] = line + return payload + + +def maybe_emit_session_start(config: Dict[str, Any], dry_run: bool, state: WatchState) -> None: + header = state.session_header + if header.emitted or header.started_at is None: + return + if not event_enabled(config, "session_start"): + header.emitted = True + return + payload = base_payload("SESSION START", state) + payload.update( + { + "started_at": header.started_at, + "account": header.account, + "instrument": header.instrument, + "bar_type": header.bar_type, + "days_to_load": header.days_to_load, + "historical_bars_loaded": header.historical_bars_loaded, + "warmup_status": header.warmup_status, + } + ) + emit(config, dry_run, payload) + header.emitted = True + + +def parse_session_header_field(state: WatchState, message: str) -> None: + match = KEY_VALUE_RE.match(message) + if match is not None: + key = match.group(1).strip() + value = match.group(2).strip() + if key == "Account": + state.session_header.account = value + elif key == "Symbol": + state.session_header.instrument = value + + data_match = DATA_SERIES_RE.search(message) + if data_match is not None and data_match.group(1) == "0": + state.session_header.bar_type = data_match.group(2) + state.session_header.days_to_load = int(data_match.group(3)) + state.session_header.historical_bars_loaded = int(data_match.group(4)) + + warmup_match = FACTOR_WARMUP_RE.search(message) + if warmup_match is not None: + state.session_header.warmup_status = warmup_match.group(1) + + +def parse_signal_details(text: str) -> Dict[str, Any]: + details: Dict[str, Any] = {"raw": text} + grade = GRADE_RE.search(text) + score = SCORE_RE.search(text) + side = SIDE_RE.search(text) + if grade is not None: + details["grade"] = grade.group(1) + if score is not None: + try: + details["score"] = float(score.group(1)) + except ValueError: + details["score"] = score.group(1) + if side is not None: + details["side"] = side.group(1) + else: + parts = text.split() + if parts: + details["side"] = parts[0] + return details + + +def parse_submit_details(text: str) -> Dict[str, Any]: + details: Dict[str, Any] = {"raw": text} + mode = MODE_RE.search(text) + quantity = QUANTITY_RE.search(text) + if mode is not None: + details["mode"] = mode.group(1) + if quantity is not None: + details["quantity"] = int(quantity.group(1)) + return details + + +def handle_line(config: Dict[str, Any], dry_run: bool, state: WatchState, raw_line: str) -> None: + timestamp, message = strip_timestamp(raw_line) + update_event_date(state, timestamp) + if not message: + return + + start_match = SESSION_START_RE.search(message) + if start_match is not None: + state.session_header = SessionHeader(started_at=start_match.group(1)) + state.reject_reasons_seen.clear() + state.signal_seen = False + state.silent_alert_sent = False + state.signal_dates.clear() + state.silent_alert_dates.clear() + state.session_ended = False + try: + state.session_date = datetime.strptime(start_match.group(1), "%Y-%m-%d %H:%M:%S").date() + state.event_date = state.session_date + except ValueError: + state.session_date = None + return + + if SESSION_END_RE.search(message) is not None: + state.session_ended = True + return + + parse_session_header_field(state, message) + if message == "---" and state.session_header.started_at is not None: + maybe_emit_session_start(config, dry_run, state) + return + + warning_match = WARNING_RE.search(message) + if warning_match is not None and event_enabled(config, "warning"): + payload = base_payload("WARNING", state, raw_line) + payload["message"] = warning_match.group(1) + emit(config, dry_run, payload) + + connection_match = CONNECTION_RE.search(message) + if connection_match is not None and event_enabled(config, "connection"): + payload = base_payload("CONNECTION {0}".format(connection_match.group(1).upper()), state, raw_line) + payload["status"] = connection_match.group(1).upper() + emit(config, dry_run, payload) + + signal_match = SIGNAL_RE.search(message) + if signal_match is not None: + state.signal_seen = True + if state.event_date is not None: + state.signal_dates.add(state.event_date) + if event_enabled(config, "signal"): + payload = base_payload("SIGNAL", state, raw_line) + payload.update(parse_signal_details(signal_match.group(1))) + emit(config, dry_run, payload) + + submit_match = SUBMIT_RE.search(message) + if submit_match is not None and event_enabled(config, "submit"): + payload = base_payload("SUBMIT", state, raw_line) + payload.update(parse_submit_details(submit_match.group(1))) + emit(config, dry_run, payload) + + reject_match = REJECT_RE.search(message) + if reject_match is not None: + reason = reject_match.group(1) + if reason not in state.reject_reasons_seen: + state.reject_reasons_seen.add(reason) + if event_enabled(config, "reject"): + payload = base_payload("REJECT", state, raw_line) + payload["reason"] = reason + payload["detail"] = reject_match.group(2).strip() + payload["bar"] = reject_match.group(3).strip() if reject_match.group(3) else None + emit(config, dry_run, payload) + + summary_match = REJECT_SUMMARY_RE.search(message) + if summary_match is not None and event_enabled(config, "reject_summary"): + payload = base_payload("REJECT SUMMARY", state, raw_line) + payload["reason"] = summary_match.group(1) + payload["count"] = int(summary_match.group(2)) + emit(config, dry_run, payload) + + +def read_new_lines(path: Path, state: WatchState) -> List[str]: + try: + size = path.stat().st_size + except OSError as ex: + sys.stderr.write("logwatch: cannot stat {0}: {1}\n".format(path, ex)) + return [] + + if size < state.offset: + state.offset = 0 + state.partial = "" + + try: + with path.open("rb") as handle: + handle.seek(state.offset) + chunk = handle.read() + state.offset = handle.tell() + except OSError as ex: + sys.stderr.write("logwatch: cannot read {0}; continuing: {1}\n".format(path, ex)) + return [] + + if not chunk: + return [] + + text = state.partial + chunk.decode("utf-8", errors="replace") + lines = text.splitlines(True) + complete: List[str] = [] + state.partial = "" + for line in lines: + if line.endswith("\n") or line.endswith("\r"): + complete.append(line.rstrip("\r\n")) + else: + state.partial = line + return complete + + +def switch_file(state: WatchState, path: Path, from_start: bool) -> None: + state.current_path = path + state.partial = "" + state.session_header = SessionHeader() + file_timestamp = timestamp_from_session_filename(path) + state.session_date = file_timestamp.date() if file_timestamp is not None else None + state.event_date = state.session_date + state.previous_line_time = None + state.signal_seen = False + state.silent_alert_sent = False + state.signal_dates.clear() + state.silent_alert_dates.clear() + state.session_ended = False + state.reject_reasons_seen.clear() + if from_start: + state.offset = 0 + else: + try: + state.offset = path.stat().st_size + except OSError: + state.offset = 0 + + +def check_silent_window(config: Dict[str, Any], dry_run: bool, state: WatchState, current_override: Optional[datetime] = None) -> None: + if not event_enabled(config, "silent_window_alert"): + return + if state.session_header.started_at is None and state.session_date is None: + return + if state.session_ended: + return + timezone = str(config.get("timezone") or "America/New_York") + current = current_override if current_override is not None else now_in_timezone(timezone) + alert_date = current.date() + if alert_date in state.silent_alert_dates or alert_date in state.signal_dates: + return + window_end = parse_time(str(config.get("orb_window_end") or "10:15")) + if current.time() <= window_end: + return + previous_event_date = state.event_date + state.event_date = alert_date + payload = base_payload("SILENT WINDOW ALERT", state) + payload["orb_window_start"] = str(config.get("orb_window_start") or "09:30") + payload["orb_window_end"] = str(config.get("orb_window_end") or "10:15") + payload["timezone"] = timezone + payload["message"] = "ORB window elapsed with no SIGNAL line in the active session log." + emit(config, dry_run, payload) + state.event_date = previous_event_date + state.silent_alert_sent = True + state.silent_alert_dates.add(alert_date) + + +def watch(config: Dict[str, Any], args: argparse.Namespace) -> int: + log_dir = expand_path(args.log_dir or str(config.get("log_dir") or "")) + if not log_dir.exists() or not log_dir.is_dir(): + sys.stderr.write("logwatch: log directory not found: {0}\n".format(log_dir)) + return 2 + + if args.webhook_url is not None: + config["webhook_url"] = args.webhook_url + + dry_run = bool(args.dry_run) + state = WatchState() + from_start_for_next_file = bool(args.from_start) + + while True: + newest = newest_session_file(log_dir) + if newest is None: + sys.stderr.write("logwatch: no session_*.log files found under {0}\n".format(log_dir)) + if args.once: + return 1 + time.sleep(args.poll_seconds) + continue + + if state.current_path != newest: + switch_file(state, newest, from_start_for_next_file) + from_start_for_next_file = True + sys.stderr.write("logwatch: watching {0}\n".format(newest)) + + for line in read_new_lines(newest, state): + handle_line(config, dry_run, state, line) + check_silent_window(config, dry_run, state) + + if args.once: + if state.partial: + handle_line(config, dry_run, state, state.partial) + state.partial = "" + maybe_emit_session_start(config, dry_run, state) + check_silent_window(config, dry_run, state) + return 0 + + time.sleep(args.poll_seconds) + + +def main(argv: Sequence[str]) -> int: + args = parse_args(argv) + try: + config = load_config(expand_path(args.config)) + except RuntimeError as ex: + sys.stderr.write(str(ex) + "\n") + return 2 + try: + return watch(config, args) + except KeyboardInterrupt: + sys.stderr.write("logwatch: stopped\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/logwatch/test_logwatch.py b/tools/logwatch/test_logwatch.py new file mode 100644 index 0000000..c5cf64e --- /dev/null +++ b/tools/logwatch/test_logwatch.py @@ -0,0 +1,41 @@ +import contextlib +import io +import json +import unittest +from datetime import datetime + +import logwatch + + +class LogwatchDateTests(unittest.TestCase): + def test_overnight_session_silent_alert_uses_current_event_date(self): + config = { + "webhook_url": "", + "orb_window_start": "09:30", + "orb_window_end": "10:15", + "timezone": "America/New_York", + "events": {"silent_window_alert": True, "connection": True, "session_start": True}, + } + state = logwatch.WatchState() + state.session_date = datetime(2026, 8, 13, 17, 26, 24).date() + state.event_date = state.session_date + + with contextlib.redirect_stdout(io.StringIO()): + logwatch.handle_line(config, True, state, "[17:26:24.803] === SESSION START 2026-08-13 17:26:24 ===") + logwatch.handle_line(config, True, state, "[17:26:24.803] Account : SimSimple ORB") + logwatch.handle_line(config, True, state, "[08:23:20.300] CONNECTION LOST at 08:23:20 Status=ConnectionLost") + + self.assertEqual(datetime(2026, 8, 14).date(), state.event_date) + + output = io.StringIO() + with contextlib.redirect_stdout(output): + logwatch.check_silent_window(config, True, state, datetime(2026, 8, 14, 10, 16, 0)) + + payload = json.loads(output.getvalue().strip()) + self.assertEqual("SILENT WINDOW ALERT", payload["event_type"]) + self.assertEqual("2026-08-14", payload["session_date"]) + self.assertEqual("2026-08-14", payload["event_date"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/market-data/.gitkeep b/tools/market-data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tools/preflight/README.md b/tools/preflight/README.md new file mode 100644 index 0000000..73ab8de --- /dev/null +++ b/tools/preflight/README.md @@ -0,0 +1,114 @@ +# preflight + +`preflight.ps1` is a standalone PowerShell script for morning go/no-go checks before enabling the strategy. It does not import or reference any NinjaTrader assembly. + +PowerShell was chosen because this tool is an operator-side environment check: process count, file writability, deployed-source hash verification, and disk-space checks are all native PowerShell tasks and do not need any .NET solution changes. + +## What It Checks + +The script prints `PASS` or `FAIL` for: + +1. Exactly one `NinjaTrader` process running +2. Log directory writable and no current-day `session_YYYYMMDD_*.log` already present +3. Most recent `settings_Simple_ORB_NT8_*.txt` export has: + - `TestMode=False` + - `EnableKillSwitch=True` + - `EnableVerboseLogging=True` + - `EnableFileLogging=True` + - `MinTradeGrade=5` + - `MaxDailyTrades=1` +4. Most recent settings export `Account` and `Instrument` match the expected arguments +5. Deployed `NT8StrategyBase.cs` hash matches the repo copy +6. Free disk space in the log directory drive is greater than `1 GB` + +Every failure prints a specific remedy. The script exits `0` only when every check passes. Any failure returns exit code `1`. + +## Usage + +Run with the expected account and instrument: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\preflight\preflight.ps1 ` + -ExpectAccount "SimSimple ORB" ` + -ExpectInstrument "NQ SEP26" +``` + +Override the log directory if needed: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\preflight\preflight.ps1 ` + -ExpectAccount "SimSimple ORB" ` + -ExpectInstrument "NQ SEP26" ` + -LogDirectory "C:\Users\billy\Documents\NinjaTrader 8\log\nt8-sdk" +``` + +Override the repo/deployed file paths for validation or alternate installs: + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\preflight\preflight.ps1 ` + -ExpectAccount "SimSimple ORB" ` + -ExpectInstrument "NQ SEP26" ` + -RepoStrategyBasePath "C:\dev\nt8-sdk\src\NT8.Adapters\Strategies\NT8StrategyBase.cs" ` + -DeployedStrategyBasePath "C:\Users\billy\Documents\NinjaTrader 8\bin\Custom\Strategies\NT8StrategyBase.cs" +``` + +## Defaults + +- `LogDirectory`: `%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk` +- `RepoStrategyBasePath`: `src\NT8.Adapters\Strategies\NT8StrategyBase.cs` relative to the repo root +- `DeployedStrategyBasePath`: `%USERPROFILE%\Documents\NinjaTrader 8\bin\Custom\Strategies\NT8StrategyBase.cs` + +## Notes + +- The script is read-only except for a temporary write/delete probe file in the log directory used to verify writability. +- The settings check uses the most recently modified `settings_Simple_ORB_NT8_*.txt` file in the log directory. +- The hash check compares SHA-256 of the repo and deployed `NT8StrategyBase.cs` files. + +## Gate 3 Freeze Mode + +Freeze mode captures Gate Run #3 provenance under `docs/gate-runs/gate3/freeze_YYYYMMDD_HHMMSS` and writes `docs/gate-runs/gate3/baseline.json` plus `DEC-GATE3-CONFIG.md` when all freeze gates pass. + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\preflight\preflight.ps1 ` + -ExpectAccount "SimSimple ORB" ` + -ExpectInstrument "NQ SEP26" ` + --freeze +``` + +PowerShell also accepts `-Freeze`. + +Freeze captures: + +- current settings export +- `ConfigHash` and `CodeVersion` +- git commit SHA +- `git status --porcelain`, which must be clean +- full test suite result from `dotnet test NT8-SDK.sln --configuration Release --verbosity minimal` +- SHA-256 hash of every deployed `.cs` file in the NT8 `Strategies` folder +- `tools/configdiff` report for the preceding 3 settings exports + +If the worktree is dirty, freeze exits non-zero and writes a failed capture folder with `git-status-porcelain.txt` and `FREEZE_FAILED.txt`. It does not create or replace `baseline.json`. + +## Gate 3 Verify Mode + +Verify mode repeats the capture and compares significant fields against `docs/gate-runs/gate3/baseline.json`. It exits non-zero on any difference. + +```powershell +powershell -ExecutionPolicy Bypass -File .\tools\preflight\preflight.ps1 ` + -ExpectAccount "SimSimple ORB" ` + -ExpectInstrument "NQ SEP26" ` + --verify +``` + +PowerShell also accepts `-Verify`. + +Verify compares: + +- settings values +- `ConfigHash` +- `CodeVersion` +- git SHA +- clean git status +- full-suite pass/fail status +- configdiff pass/fail status +- deployed strategy source hashes diff --git a/tools/preflight/preflight.ps1 b/tools/preflight/preflight.ps1 new file mode 100644 index 0000000..44fe339 --- /dev/null +++ b/tools/preflight/preflight.ps1 @@ -0,0 +1,559 @@ +param( + [Parameter(Mandatory = $true)] + [string]$ExpectAccount, + + [Parameter(Mandatory = $true)] + [string]$ExpectInstrument, + + [string]$LogDirectory = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'log', 'nt8-sdk'), + + [string]$RepoStrategyBasePath = '', + + [string]$DeployedStrategyBasePath = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'bin', 'Custom', 'Strategies', 'NT8StrategyBase.cs'), + + [string]$NtStrategiesDirectory = [System.IO.Path]::Combine($env:USERPROFILE, 'Documents', 'NinjaTrader 8', 'bin', 'Custom', 'Strategies'), + + [string]$GateDirectory = '', + + [switch]$Freeze, + + [switch]$Verify +) + +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' + +$script:AllPassed = $true + +function Get-ScriptDirectory { + $scriptPath = $MyInvocation.ScriptName + if ([string]::IsNullOrEmpty($scriptPath)) { + $scriptPath = $MyInvocation.MyCommand.Path + } + if ([string]::IsNullOrEmpty($scriptPath)) { + return [System.IO.Directory]::GetCurrentDirectory() + } + return Split-Path -Parent $scriptPath +} + +$script:ScriptDir = Get-ScriptDirectory +$script:RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $script:ScriptDir '..\..')) +if ([string]::IsNullOrEmpty($RepoStrategyBasePath)) { + $RepoStrategyBasePath = [System.IO.Path]::GetFullPath((Join-Path $script:RepoRoot 'src\NT8.Adapters\Strategies\NT8StrategyBase.cs')) +} +if ([string]::IsNullOrEmpty($GateDirectory)) { + $GateDirectory = [System.IO.Path]::GetFullPath((Join-Path $script:RepoRoot 'docs\gate-runs\gate3')) +} + +function Write-CheckResult { + param( + [int]$Number, + [bool]$Passed, + [string]$Title, + [string]$Detail, + [string]$Remedy + ) + + if ($Passed) { + [Console]::WriteLine(('PASS {0}. {1} - {2}' -f $Number, $Title, $Detail)) + } + else { + $script:AllPassed = $false + [Console]::WriteLine(('FAIL {0}. {1} - {2}' -f $Number, $Title, $Detail)) + [Console]::WriteLine((' Remedy: {0}' -f $Remedy)) + } +} + +function Get-SettingsValue { + param( + [hashtable]$Values, + [string]$Key + ) + + if ($Values.ContainsKey($Key)) { + return [string]$Values[$Key] + } + return $null +} + +function Get-SettingsTimestamp { + param([System.IO.FileInfo]$File) + + if ($File.Name -match 'settings_.+_(\d{8})_(\d{6})\.txt$') { + return [DateTime]::ParseExact(($matches[1] + '_' + $matches[2]), 'yyyyMMdd_HHmmss', [System.Globalization.CultureInfo]::InvariantCulture) + } + return $File.LastWriteTime +} + +function Get-SettingsExports { + param([string]$DirectoryPath) + + if (-not (Test-Path -LiteralPath $DirectoryPath -PathType Container)) { + return @() + } + + return @(Get-ChildItem -LiteralPath $DirectoryPath -Recurse -File -Filter 'settings_Simple_ORB_NT8_*.txt' | Sort-Object @{ Expression = { Get-SettingsTimestamp -File $_ } }, FullName) +} + +function Get-LatestSettingsExport { + param([string]$DirectoryPath) + + $files = @(Get-SettingsExports -DirectoryPath $DirectoryPath) + if ($files.Count -eq 0) { + return $null + } + return $files[$files.Count - 1] +} + +function Parse-SettingsExport { + param([string]$FilePath) + + $values = @{} + $lines = Get-Content -LiteralPath $FilePath -ErrorAction Stop + foreach ($line in $lines) { + if ([string]::IsNullOrWhiteSpace($line)) { continue } + if ($line.StartsWith('===') -or $line.StartsWith('---')) { continue } + + $parts = $line -split '\s*:\s*', 2 + if ($parts.Length -ne 2) { continue } + + $key = $parts[0].Trim() + $value = $parts[1].Trim() + $values[$key] = $value + } + return $values +} + +function Convert-SettingsToObject { + param([hashtable]$Values) + + $ordered = New-Object System.Collections.Specialized.OrderedDictionary + $keys = @($Values.Keys | Sort-Object) + foreach ($key in $keys) { + $ordered.Add($key, [string]$Values[$key]) + } + return $ordered +} + +function Test-RequiredSetting { + param( + [hashtable]$Values, + [string]$Key, + [string]$Expected + ) + + $actual = Get-SettingsValue -Values $Values -Key $Key + if ($actual -eq $null) { + return @{ Passed = $false; Message = ('missing {0}' -f $Key) } + } + if ($actual -ne $Expected) { + return @{ Passed = $false; Message = ('{0}={1} (expected {2})' -f $Key, $actual, $Expected) } + } + return @{ Passed = $true; Message = ('{0}={1}' -f $Key, $actual) } +} + +function Get-FreeSpaceBytes { + param([string]$DirectoryPath) + + $resolved = Resolve-Path -LiteralPath $DirectoryPath + $root = [System.IO.Path]::GetPathRoot($resolved.Path) + $drive = New-Object System.IO.DriveInfo($root) + return $drive.AvailableFreeSpace +} + +function Invoke-ExternalCapture { + param( + [string]$Command, + [string]$OutputPath, + [string]$WorkingDirectory + ) + + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = 'powershell.exe' + $psi.Arguments = '-NoProfile -ExecutionPolicy Bypass -Command "' + $Command.Replace('"', '\"') + '"' + $psi.WorkingDirectory = $WorkingDirectory + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.UseShellExecute = $false + $process = [System.Diagnostics.Process]::Start($psi) + $stdout = $process.StandardOutput.ReadToEnd() + $stderr = $process.StandardError.ReadToEnd() + $process.WaitForExit() + $content = $stdout + if (-not [string]::IsNullOrEmpty($stderr)) { + $content += "`r`nSTDERR:`r`n" + $stderr + } + [System.IO.File]::WriteAllText($OutputPath, $content) + return $process.ExitCode +} + +function Get-GitSha { + $sha = (& git -C $script:RepoRoot rev-parse HEAD 2>$null) + if ($LASTEXITCODE -ne 0) { throw 'git rev-parse HEAD failed' } + return [string]$sha +} + +function Get-GitPorcelain { + $status = (& git -C $script:RepoRoot status --porcelain 2>$null) + if ($LASTEXITCODE -ne 0) { throw 'git status --porcelain failed' } + return @($status) +} + +function Write-DeployedSourceHashes { + param( + [string]$DirectoryPath, + [string]$TextPath, + [string]$JsonPath + ) + + $items = @() + $lines = New-Object System.Collections.Generic.List[string] + if (Test-Path -LiteralPath $DirectoryPath -PathType Container) { + $files = @(Get-ChildItem -LiteralPath $DirectoryPath -Recurse -File -Filter '*.cs' | Sort-Object FullName) + foreach ($file in $files) { + $hash = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash + $relative = $file.FullName.Substring($DirectoryPath.Length).TrimStart('\') + $lines.Add(('{0} {1}' -f $hash, $relative)) + $items += @{ path = $relative; sha256 = $hash } + } + } + [System.IO.File]::WriteAllLines($TextPath, $lines.ToArray()) + ($items | ConvertTo-Json -Depth 5) | Out-File -LiteralPath $JsonPath -Encoding UTF8 + return $items +} + +function Copy-PrecedingSettingsExports { + param( + [System.IO.FileInfo[]]$Exports, + [string]$Destination + ) + + if (-not (Test-Path -LiteralPath $Destination)) { + New-Item -ItemType Directory -Path $Destination | Out-Null + } + $selected = @($Exports | Select-Object -Last 3) + foreach ($file in $selected) { + Copy-Item -LiteralPath $file.FullName -Destination (Join-Path $Destination $file.Name) -Force + } + return $selected +} + +function Write-DecisionDraft { + param( + [string]$Path, + [string]$CaptureName, + [hashtable]$Settings, + [string]$ConfigHash, + [string]$CodeVersion, + [string]$GitSha + ) + + $lines = New-Object System.Collections.Generic.List[string] + $lines.Add('# DEC-GATE3-CONFIG') + $lines.Add('') + $lines.Add('- **ID:** DEC-GATE3-CONFIG') + $lines.Add(('- **Date:** {0}' -f (Get-Date -Format 'yyyy-MM-dd'))) + $lines.Add('- **Status:** draft') + $lines.Add('- **Reason:** GAP-034 is not closed; Gate Run #3 cannot start with an unexplained zero-trade defect.') + $lines.Add(('- **Capture:** `{0}`' -f $CaptureName)) + $lines.Add(('- **Git Commit:** `{0}`' -f $GitSha)) + $lines.Add(('- **ConfigHash:** `{0}`' -f $ConfigHash)) + $lines.Add(('- **CodeVersion:** `{0}`' -f $CodeVersion)) + $lines.Add('') + $lines.Add('## Frozen Parameters') + $lines.Add('') + $lines.Add('| Parameter | Value |') + $lines.Add('|---|---|') + foreach ($key in @($Settings.Keys | Sort-Object)) { + $lines.Add(('| `{0}` | `{1}` |' -f $key, $Settings[$key])) + } + [System.IO.File]::WriteAllLines($Path, $lines.ToArray()) +} + +function New-SignificantManifest { + param( + [string]$CaptureName, + [hashtable]$Settings, + [string]$ConfigHash, + [string]$CodeVersion, + [string]$GitSha, + [object[]]$DeployedHashes, + [bool]$TestsPassed, + [bool]$ConfigDiffPassed + ) + + return [ordered]@{ + capture = $CaptureName + config_hash = $ConfigHash + code_version = $CodeVersion + git_sha = $GitSha + git_status_clean = $true + tests_passed = $TestsPassed + configdiff_passed = $ConfigDiffPassed + settings = Convert-SettingsToObject -Values $Settings + deployed_strategy_hashes = $DeployedHashes + } +} + +function Write-JsonFile { + param( + [string]$Path, + [object]$Value + ) + ($Value | ConvertTo-Json -Depth 20) | Out-File -LiteralPath $Path -Encoding UTF8 +} + +function Compare-Manifest { + param( + [object]$Baseline, + [object]$Current + ) + + $baselineComparable = $Baseline | Select-Object -Property * -ExcludeProperty capture + $currentComparable = $Current | Select-Object -Property * -ExcludeProperty capture + $baselineJson = ($baselineComparable | ConvertTo-Json -Depth 20) + $currentJson = ($currentComparable | ConvertTo-Json -Depth 20) + if ($baselineJson -eq $currentJson) { + return '' + } + return "BASELINE:`r`n$baselineJson`r`n`r`nCURRENT:`r`n$currentJson" +} + +function Invoke-GateCapture { + param([bool]$VerifyMode) + + $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss' + if (-not (Test-Path -LiteralPath $GateDirectory)) { + New-Item -ItemType Directory -Path $GateDirectory | Out-Null + } + $captureName = if ($VerifyMode) { 'verify_' + $timestamp } else { 'freeze_' + $timestamp } + $captureDir = Join-Path $GateDirectory $captureName + $suffix = 1 + while (Test-Path -LiteralPath $captureDir) { + $captureName = if ($VerifyMode) { 'verify_' + $timestamp + '_' + $suffix } else { 'freeze_' + $timestamp + '_' + $suffix } + $captureDir = Join-Path $GateDirectory $captureName + $suffix++ + } + New-Item -ItemType Directory -Path $captureDir | Out-Null + + $gitStatus = Get-GitPorcelain + [System.IO.File]::WriteAllLines((Join-Path $captureDir 'git-status-porcelain.txt'), $gitStatus) + if ($gitStatus.Count -ne 0) { + [System.IO.File]::WriteAllText((Join-Path $captureDir 'FREEZE_FAILED.txt'), 'git status --porcelain is not clean. Freeze/verify baseline is invalid until the working tree is clean.') + [Console]::WriteLine(('FAIL: git status --porcelain is not clean. Capture written to {0}' -f $captureDir)) + return 1 + } + + $gitSha = Get-GitSha + [System.IO.File]::WriteAllText((Join-Path $captureDir 'git-commit.txt'), $gitSha) + + $settingsExports = @(Get-SettingsExports -DirectoryPath $LogDirectory) + if ($settingsExports.Count -eq 0) { throw 'No settings_Simple_ORB_NT8_*.txt export found.' } + $latestSettings = $settingsExports[$settingsExports.Count - 1] + $settingsValues = Parse-SettingsExport -FilePath $latestSettings.FullName + Copy-Item -LiteralPath $latestSettings.FullName -Destination (Join-Path $captureDir $latestSettings.Name) -Force + + $configHash = Get-SettingsValue -Values $settingsValues -Key 'ConfigHash' + $codeVersion = Get-SettingsValue -Values $settingsValues -Key 'CodeVersion' + [System.IO.File]::WriteAllText((Join-Path $captureDir 'config-hash.txt'), [string]$configHash) + [System.IO.File]::WriteAllText((Join-Path $captureDir 'code-version.txt'), [string]$codeVersion) + + $testOutput = Join-Path $captureDir 'full-test-suite.txt' + $testCommand = 'dotnet test NT8-SDK.sln --configuration Release --verbosity minimal' + $testExit = Invoke-ExternalCapture -Command $testCommand -OutputPath $testOutput -WorkingDirectory $script:RepoRoot + $testsPassed = $testExit -eq 0 + + $hashTextPath = Join-Path $captureDir 'deployed-strategy-source-hashes.txt' + $hashJsonPath = Join-Path $captureDir 'deployed-strategy-source-hashes.json' + $deployedHashes = @(Write-DeployedSourceHashes -DirectoryPath $NtStrategiesDirectory -TextPath $hashTextPath -JsonPath $hashJsonPath) + + $precedingDir = Join-Path $captureDir 'preceding-3-settings' + $selectedSettings = @(Copy-PrecedingSettingsExports -Exports $settingsExports -Destination $precedingDir) + $configDiffOutput = Join-Path $captureDir 'configdiff-preceding-3-sessions.txt' + $configDiffCommand = 'python tools\configdiff\configdiff.py "' + $precedingDir + '"' + $configDiffExit = Invoke-ExternalCapture -Command $configDiffCommand -OutputPath $configDiffOutput -WorkingDirectory $script:RepoRoot + $configDiffPassed = $configDiffExit -eq 0 + + $metadata = [ordered]@{ + captured_at = (Get-Date).ToString('o') + capture = $captureName + settings_source = $latestSettings.FullName + settings_copied = $latestSettings.Name + preceding_settings = @($selectedSettings | ForEach-Object { $_.FullName }) + config_hash = $configHash + code_version = $codeVersion + git_sha = $gitSha + tests_exit_code = $testExit + configdiff_exit_code = $configDiffExit + } + Write-JsonFile -Path (Join-Path $captureDir 'capture-metadata.json') -Value $metadata + + $manifest = New-SignificantManifest -CaptureName $captureName -Settings $settingsValues -ConfigHash $configHash -CodeVersion $codeVersion -GitSha $gitSha -DeployedHashes $deployedHashes -TestsPassed $testsPassed -ConfigDiffPassed $configDiffPassed + Write-JsonFile -Path (Join-Path $captureDir 'manifest.json') -Value $manifest + + if (-not $VerifyMode) { + Write-JsonFile -Path (Join-Path $GateDirectory 'baseline.json') -Value $manifest + Write-DecisionDraft -Path (Join-Path $GateDirectory 'DEC-GATE3-CONFIG.md') -CaptureName $captureName -Settings $settingsValues -ConfigHash $configHash -CodeVersion $codeVersion -GitSha $gitSha + [Console]::WriteLine(('Freeze draft capture written to {0}' -f $captureDir)) + } + else { + $baselinePath = Join-Path $GateDirectory 'baseline.json' + if (-not (Test-Path -LiteralPath $baselinePath -PathType Leaf)) { throw 'No baseline.json found. Run -Freeze first.' } + $baseline = Get-Content -LiteralPath $baselinePath -Raw | ConvertFrom-Json + $diff = Compare-Manifest -Baseline $baseline -Current $manifest + if ([string]::IsNullOrEmpty($diff)) { + [System.IO.File]::WriteAllText((Join-Path $captureDir 'verify-result.txt'), 'PASS') + [Console]::WriteLine(('VERIFY PASS: {0}' -f $captureDir)) + } + else { + [System.IO.File]::WriteAllText((Join-Path $captureDir 'verify-diff.txt'), $diff) + [Console]::WriteLine(('VERIFY FAIL: baseline differs. Diff written to {0}' -f (Join-Path $captureDir 'verify-diff.txt'))) + return 1 + } + } + + if (-not $testsPassed) { + [Console]::WriteLine('FAIL: full test suite did not pass.') + return 1 + } + if (-not $configDiffPassed) { + [Console]::WriteLine('FAIL: configdiff preceding-3-sessions report detected drift.') + return 1 + } + return 0 +} + +function Invoke-PreflightChecks { + [Console]::WriteLine('NT8 SDK preflight') + [Console]::WriteLine(('LogDirectory: {0}' -f $LogDirectory)) + [Console]::WriteLine(('ExpectAccount: {0}' -f $ExpectAccount)) + [Console]::WriteLine(('ExpectInstrument: {0}' -f $ExpectInstrument)) + [Console]::WriteLine('') + + $todayStamp = Get-Date -Format 'yyyyMMdd' + $latestSettings = $null + $settingsValues = $null + + try { + $ntProcesses = @(Get-Process -Name 'NinjaTrader' -ErrorAction SilentlyContinue) + Write-CheckResult -Number 1 -Passed ($ntProcesses.Count -eq 1) -Title 'Exactly one NinjaTrader process running' -Detail ('found {0} NinjaTrader process(es)' -f $ntProcesses.Count) -Remedy 'Close extra NinjaTrader instances or start NinjaTrader so exactly one process is running before enabling the strategy.' + + $logDirExists = Test-Path -LiteralPath $LogDirectory -PathType Container + $logDirWritable = $false + $currentDayLogExists = $false + $logDetailParts = @() + if (-not $logDirExists) { + $logDetailParts += 'log directory missing' + } + else { + $probePath = Join-Path $LogDirectory 'preflight_write_test.tmp' + try { + [System.IO.File]::WriteAllText($probePath, 'ok') + Remove-Item -LiteralPath $probePath -Force -ErrorAction SilentlyContinue + $logDirWritable = $true + } + catch { $logDirWritable = $false } + + $existingSessionLogs = @(Get-ChildItem -LiteralPath $LogDirectory -File -Filter ('session_{0}_*.log' -f $todayStamp) -ErrorAction SilentlyContinue) + $currentDayLogExists = $existingSessionLogs.Count -gt 0 + $logDetailParts += ('writable={0}' -f $logDirWritable) + $logDetailParts += ('current-day session logs={0}' -f $existingSessionLogs.Count) + } + Write-CheckResult -Number 2 -Passed ($logDirExists -and $logDirWritable -and (-not $currentDayLogExists)) -Title 'Log directory writable and no current-day session log present' -Detail ([string]::Join('; ', $logDetailParts)) -Remedy ('Create/fix permissions on the log directory and archive or remove any existing session_' + $todayStamp + '_*.log before starting a new session.') + + if ($logDirExists) { + $latestSettings = Get-LatestSettingsExport -DirectoryPath $LogDirectory + if ($latestSettings -ne $null) { $settingsValues = Parse-SettingsExport -FilePath $latestSettings.FullName } + } + + $requiredChecks = @( + @{ Key = 'TestMode'; Expected = 'False' }, + @{ Key = 'EnableKillSwitch'; Expected = 'True' }, + @{ Key = 'EnableVerboseLogging'; Expected = 'True' }, + @{ Key = 'EnableFileLogging'; Expected = 'True' }, + @{ Key = 'MinTradeGrade'; Expected = '5' }, + @{ Key = 'MaxDailyTrades'; Expected = '1' } + ) + $settingsPassed = $true + $settingsMessages = @() + if ($latestSettings -eq $null -or $settingsValues -eq $null) { + $settingsPassed = $false + $settingsMessages += 'no settings_Simple_ORB_NT8_*.txt export found' + } + else { + foreach ($check in $requiredChecks) { + $result = Test-RequiredSetting -Values $settingsValues -Key $check.Key -Expected $check.Expected + $settingsMessages += $result.Message + if (-not $result.Passed) { $settingsPassed = $false } + } + } + Write-CheckResult -Number 3 -Passed $settingsPassed -Title 'Most recent settings export has required gate values' -Detail ([string]::Join('; ', $settingsMessages)) -Remedy 'Export fresh settings from the intended strategy instance and set TestMode=False, EnableKillSwitch=True, EnableVerboseLogging=True, EnableFileLogging=True, MinTradeGrade=5, and MaxDailyTrades=1 before enabling.' + + $matchPassed = $true + $matchMessages = @() + if ($latestSettings -eq $null -or $settingsValues -eq $null) { + $matchPassed = $false + $matchMessages += 'no settings export available for account/instrument validation' + } + else { + $actualAccount = Get-SettingsValue -Values $settingsValues -Key 'Account' + $actualInstrument = Get-SettingsValue -Values $settingsValues -Key 'Instrument' + if ($actualAccount -ne $ExpectAccount) { $matchPassed = $false } + if ($actualInstrument -ne $ExpectInstrument) { $matchPassed = $false } + $matchMessages += ('Account={0} (expected {1})' -f $actualAccount, $ExpectAccount) + $matchMessages += ('Instrument={0} (expected {1})' -f $actualInstrument, $ExpectInstrument) + } + Write-CheckResult -Number 4 -Passed $matchPassed -Title 'Most recent settings export matches expected account and instrument' -Detail ([string]::Join('; ', $matchMessages)) -Remedy 'Load the correct workspace/strategy settings, export them again, and confirm Account and Instrument match the morning run plan before enabling.' + + $hashPassed = $false + $hashDetail = '' + if ((Test-Path -LiteralPath $RepoStrategyBasePath -PathType Leaf) -and (Test-Path -LiteralPath $DeployedStrategyBasePath -PathType Leaf)) { + $repoHash = (Get-FileHash -LiteralPath $RepoStrategyBasePath -Algorithm SHA256).Hash + $deployedHash = (Get-FileHash -LiteralPath $DeployedStrategyBasePath -Algorithm SHA256).Hash + $hashPassed = $repoHash -eq $deployedHash + $hashDetail = ('repo={0} deployed={1}' -f $repoHash, $deployedHash) + } + else { + $hashDetail = 'repo or deployed NT8StrategyBase.cs missing' + } + Write-CheckResult -Number 5 -Passed $hashPassed -Title 'Deployed NT8StrategyBase.cs matches repo copy' -Detail $hashDetail -Remedy 'Redeploy NT8StrategyBase.cs from the repo to the NinjaTrader Strategies directory and confirm the deployed source exactly matches the repo copy before enabling.' + + $spacePassed = $false + $spaceDetail = '' + if ($logDirExists) { + $freeBytes = Get-FreeSpaceBytes -DirectoryPath $LogDirectory + $spacePassed = $freeBytes -gt 1GB + $spaceDetail = ('free space={0} GB' -f [Math]::Round(($freeBytes / 1GB), 2)) + } + else { $spaceDetail = 'log directory missing' } + Write-CheckResult -Number 6 -Passed $spacePassed -Title 'Disk space greater than 1 GB in log directory drive' -Detail $spaceDetail -Remedy 'Free disk space on the log drive or move the log directory to a drive with more than 1 GB available before enabling the strategy.' + } + catch { + $script:AllPassed = $false + [Console]::WriteLine(('FAIL PRECHECK - unexpected error: {0}' -f $_.Exception.Message)) + [Console]::WriteLine(' Remedy: Fix the reported error and rerun preflight before enabling the strategy.') + } + + [Console]::WriteLine('') + if ($script:AllPassed) { + [Console]::WriteLine('OVERALL: PASS') + return 0 + } + [Console]::WriteLine('OVERALL: FAIL') + return 1 +} + +if ($Freeze -and $Verify) { + [Console]::WriteLine('Use only one mode: -Freeze or -Verify.') + exit 2 +} + +if ($Freeze) { + exit (Invoke-GateCapture -VerifyMode $false) +} + +if ($Verify) { + exit (Invoke-GateCapture -VerifyMode $true) +} + +exit (Invoke-PreflightChecks) diff --git a/tools/replay/.gitkeep b/tools/replay/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tools/runnersweep/README.md b/tools/runnersweep/README.md new file mode 100644 index 0000000..6dbb23a --- /dev/null +++ b/tools/runnersweep/README.md @@ -0,0 +1,108 @@ +# runnersweep + +`runnersweep.py` analyzes NT8 Strategy Analyzer exports for the DEC-20260815-01 runner redesign sweep. It is offline analysis only: no strategy code changes, no NinjaTrader assembly references, no DLL involvement. + +I chose Strategy Analyzer exports rather than a direct SDK-core harness. The mandatory validity rules require Tick Replay with a non-time-based HFT Algo Bars primary series; using Strategy Analyzer exports preserves NT8's bar construction instead of approximating it outside NT8. + +## Sweep Grid + +Full factorial, 18 combinations: + +- `BreakevenTriggerTicks`: `20`, `28`, `36`, `44`, `52`, `disabled` +- `RunnerTrailTicks`: `12`, `20`, `28` + +## Mandatory Validity Rules + +Each run is marked invalid unless the export or metadata proves: + +- Strategy Analyzer start date is at least 60 trading days before the evaluation window start. +- Tick Replay was enabled. +- Daily bars loaded are reported and at least 60. + +The result table reports `Daily Bars` for each combination as warm-up proof. + +## Expected Export Shape + +The tool accepts either one combined CSV or a directory of CSVs. It reads files recursively. + +Parameters can be supplied as columns: + +- `BreakevenTriggerTicks` +- `RunnerTrailTicks` + +Or in filenames, for example: + +- `BE20_Trail12.csv` +- `BreakevenTriggerTicks-disabled_RunnerTrailTicks28.csv` + +Useful trade columns: + +- `Profit`, `Net profit`, `PnL`, or `P&L` +- `Leg`, `Entry name`, `Exit name`, `Signal name`, `EntrySignal`, `ExitSignal` +- `R`, `R Multiple`, or `Initial Risk` +- `StartDate`, `EvaluationStartDate`, `TickReplay`, `DailyBarsLoaded` + +Runner rows are identified by `runner`/`run` in leg or signal names. Scaler rows are excluded from runner-leg metrics but included in combined strategy metrics. + +## Metadata Sidecar + +If Strategy Analyzer exports do not include mandatory metadata, provide `metadata.json`: + +```json +[ + { + "BreakevenTriggerTicks": 20, + "RunnerTrailTicks": 12, + "StartDate": "2026-05-01", + "EvaluationStartDate": "2026-08-01", + "TickReplay": true, + "DailyBarsLoaded": 87 + } +] +``` + +## Usage + +Markdown table: + +```powershell +python tools\runnersweep\runnersweep.py "C:\exports\runner-sweep" --metadata "C:\exports\runner-sweep\metadata.json" +``` + +JSON: + +```powershell +python tools\runnersweep\runnersweep.py "C:\exports\runner-sweep" --metadata "C:\exports\runner-sweep\metadata.json" --json +``` + +If the evaluation start date is not in the exports: + +```powershell +python tools\runnersweep\runnersweep.py "C:\exports\runner-sweep" --eval-start 2026-08-01 +``` + +## Output Metrics + +Per combination: + +- runner net P&L +- runner win rate +- runner average R +- percent of runner exits at breakeven +- percent of runner exits at trail stop +- percent of runner exits at full stop +- combined strategy profit factor +- combined max drawdown +- combined trade count + +## Recommendation Logic + +Only valid combinations are considered. + +If every valid setting has runner net P&L `<= 0`, the recommendation is explicitly: + +```text +Recommendation: disable the runner leg. Runner net P&L is non-positive for every valid setting. +``` + +Otherwise, the tool recommends the valid combination with the highest runner net P&L, using combined PF and lower max drawdown as tie-breakers. diff --git a/tools/runnersweep/runnersweep.py b/tools/runnersweep/runnersweep.py new file mode 100644 index 0000000..5c78031 --- /dev/null +++ b/tools/runnersweep/runnersweep.py @@ -0,0 +1,506 @@ +#!/usr/bin/env python3 +"""Offline runner parameter sweep analyzer for NT8 Strategy Analyzer exports.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +import os +import re +import sys +from dataclasses import dataclass, field +from datetime import date, datetime, timedelta +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + + +BREAKEVEN_VALUES = ["20", "28", "36", "44", "52", "disabled"] +TRAIL_VALUES = ["12", "20", "28"] +EXPECTED_COMBINATIONS = [(be, trail) for be in BREAKEVEN_VALUES for trail in TRAIL_VALUES] + +PARAM_RE = re.compile( + r"(?:BE|Breakeven|BreakevenTriggerTicks)[_=-]?(disabled|20|28|36|44|52).*?(?:Trail|RunnerTrailTicks)[_=-]?(12|20|28)", + re.IGNORECASE, +) + + +@dataclass +class TradeRow: + combo: Tuple[str, str] + path: Path + row_number: int + fields: Dict[str, str] + is_runner: bool + pnl: float + r_value: Optional[float] + exit_kind: str + + +@dataclass +class RunMetadata: + combo: Tuple[str, str] + start_date: Optional[date] = None + evaluation_start_date: Optional[date] = None + tick_replay: Optional[bool] = None + daily_bars_loaded: Optional[int] = None + source: str = "" + errors: List[str] = field(default_factory=list) + + +@dataclass +class ComboResult: + combo: Tuple[str, str] + metadata: RunMetadata + all_trades: List[TradeRow] + runner_trades: List[TradeRow] + valid: bool + invalid_reasons: List[str] + runner_net_pnl: float + runner_win_rate: Optional[float] + runner_avg_r: Optional[float] + pct_breakeven: Optional[float] + pct_trail_stop: Optional[float] + pct_full_stop: Optional[float] + combined_pf: Optional[float] + max_drawdown: float + trade_count: int + + +def parse_args(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Analyze 18-combo runner breakeven/trail Strategy Analyzer sweep exports.") + parser.add_argument("input", help="Directory containing Strategy Analyzer CSV exports, or one combined CSV file") + parser.add_argument("--json", action="store_true", help="Emit JSON instead of Markdown") + parser.add_argument("--eval-start", help="Evaluation window start date YYYY-MM-DD if not present in exports/metadata") + parser.add_argument("--metadata", help="Optional metadata JSON file keyed by combination") + return parser.parse_args(argv) + + +def expand_path(raw: str) -> Path: + return Path(os.path.expanduser(os.path.expandvars(raw))) + + +def normalize_header(value: str) -> str: + return re.sub(r"[^a-z0-9]", "", value.strip().lower()) + + +def get_field(row: Dict[str, str], names: Sequence[str]) -> Optional[str]: + normalized = {normalize_header(key): value for key, value in row.items()} + for name in names: + key = normalize_header(name) + if key in normalized and normalized[key] not in (None, ""): + return normalized[key] + return None + + +def parse_float(value: Optional[str]) -> Optional[float]: + if value is None: + return None + text = str(value).strip().replace("$", "").replace(",", "").replace("%", "") + if not text: + return None + if text.startswith("(") and text.endswith(")"): + text = "-" + text[1:-1] + try: + return float(text) + except ValueError: + return None + + +def parse_int(value: Optional[str]) -> Optional[int]: + number = parse_float(value) + if number is None: + return None + return int(number) + + +def parse_bool(value: Optional[str]) -> Optional[bool]: + if value is None: + return None + text = str(value).strip().lower() + if text in ("true", "yes", "1", "enabled", "on"): + return True + if text in ("false", "no", "0", "disabled", "off"): + return False + return None + + +def parse_date(value: Optional[str]) -> Optional[date]: + if value is None: + return None + text = str(value).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%Y%m%d"): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + pass + return None + + +def trading_days_between(start: date, end: date) -> int: + days = 0 + current = start + while current < end: + if current.weekday() < 5: + days += 1 + current += timedelta(days=1) + return days + + +def combo_from_text(text: str) -> Optional[Tuple[str, str]]: + match = PARAM_RE.search(text) + if match is None: + return None + be = match.group(1).lower() + trail = match.group(2) + return (be, trail) + + +def combo_from_row(row: Dict[str, str], path: Path) -> Optional[Tuple[str, str]]: + be = get_field(row, ["BreakevenTriggerTicks", "Breakeven", "BE", "BE Ticks"]) + trail = get_field(row, ["RunnerTrailTicks", "Trail", "TrailTicks"]) + if be is not None and trail is not None: + be_text = str(be).strip().lower() + if be_text in ("off", "false", "none", "disabled"): + be_text = "disabled" + else: + parsed = parse_int(be_text) + if parsed is not None: + be_text = str(parsed) + trail_int = parse_int(trail) + if be_text in BREAKEVEN_VALUES and trail_int is not None and str(trail_int) in TRAIL_VALUES: + return (be_text, str(trail_int)) + return combo_from_text(path.stem) + + +def discover_csv_files(input_path: Path) -> List[Path]: + if input_path.is_file(): + return [input_path] + return sorted(path for path in input_path.rglob("*.csv") if path.is_file()) + + +def is_runner_leg(row: Dict[str, str]) -> bool: + values = [] + for key in ("Leg", "Entry name", "Exit name", "Signal name", "Name", "From entry signal", "EntrySignal", "ExitSignal"): + value = get_field(row, [key]) + if value: + values.append(value) + text = " ".join(values).lower() + if "scaler" in text or "scale" in text: + return False + return "runner" in text or "run" in text + + +def classify_exit(row: Dict[str, str], pnl: float) -> str: + text_parts = [] + for key in ("Exit name", "ExitSignal", "Exit reason", "Reason", "Order name", "Name"): + value = get_field(row, [key]) + if value: + text_parts.append(value) + text = " ".join(text_parts).lower() + if "breakeven" in text or "break even" in text or "be" == text.strip(): + return "breakeven" + if "trail" in text: + return "trail_stop" + if "stop" in text: + return "full_stop" + if abs(pnl) <= 0.01: + return "breakeven" + return "other" + + +def pnl_from_row(row: Dict[str, str]) -> float: + for names in (["Profit", "Profit currency", "Net profit", "PnL", "P&L"], ["Cum profit"]): + value = get_field(row, names) + parsed = parse_float(value) + if parsed is not None: + return parsed + return 0.0 + + +def r_from_row(row: Dict[str, str], pnl: float) -> Optional[float]: + direct = parse_float(get_field(row, ["R", "R Multiple", "RMultiple", "Runner R"])) + if direct is not None: + return direct + risk = parse_float(get_field(row, ["Initial Risk", "Risk", "Risk Dollars", "InitialRisk"])); + if risk is not None and risk != 0: + return pnl / abs(risk) + return None + + +def parse_trade_rows(csv_files: Sequence[Path]) -> Tuple[List[TradeRow], Dict[Tuple[str, str], RunMetadata]]: + trades: List[TradeRow] = [] + metadata: Dict[Tuple[str, str], RunMetadata] = {} + for path in csv_files: + try: + with path.open("r", encoding="utf-8-sig", newline="") as handle: + reader = csv.DictReader(handle) + if reader.fieldnames is None: + continue + for row_number, row in enumerate(reader, start=2): + combo = combo_from_row(row, path) + if combo is None: + continue + if combo not in metadata: + metadata[combo] = metadata_from_row(combo, row, path) + else: + merge_metadata(metadata[combo], metadata_from_row(combo, row, path)) + pnl = pnl_from_row(row) + trade = TradeRow( + combo=combo, + path=path, + row_number=row_number, + fields=row, + is_runner=is_runner_leg(row), + pnl=pnl, + r_value=r_from_row(row, pnl), + exit_kind=classify_exit(row, pnl), + ) + trades.append(trade) + except OSError as ex: + sys.stderr.write("Could not read {0}: {1}\n".format(path, ex)) + return trades, metadata + + +def metadata_from_row(combo: Tuple[str, str], row: Dict[str, str], path: Path) -> RunMetadata: + return RunMetadata( + combo=combo, + start_date=parse_date(get_field(row, ["StartDate", "Strategy Analyzer Start Date", "Backtest Start", "From"])), + evaluation_start_date=parse_date(get_field(row, ["EvaluationStartDate", "Evaluation Start", "Window Start"])), + tick_replay=parse_bool(get_field(row, ["TickReplay", "Tick Replay"])), + daily_bars_loaded=parse_int(get_field(row, ["DailyBarsLoaded", "Daily Bars Loaded", "DailyBars"])), + source=str(path), + ) + + +def merge_metadata(target: RunMetadata, incoming: RunMetadata) -> None: + if target.start_date is None: + target.start_date = incoming.start_date + if target.evaluation_start_date is None: + target.evaluation_start_date = incoming.evaluation_start_date + if target.tick_replay is None: + target.tick_replay = incoming.tick_replay + if target.daily_bars_loaded is None: + target.daily_bars_loaded = incoming.daily_bars_loaded + + +def load_metadata_override(path: Optional[str]) -> Dict[Tuple[str, str], RunMetadata]: + if not path: + return {} + metadata_path = expand_path(path) + try: + payload = json.loads(metadata_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as ex: + raise RuntimeError("Could not read metadata file {0}: {1}".format(metadata_path, ex)) + result: Dict[Tuple[str, str], RunMetadata] = {} + items: Iterable[Any] + if isinstance(payload, list): + items = payload + elif isinstance(payload, dict): + items = payload.values() + else: + return result + for item in items: + if not isinstance(item, dict): + continue + combo = combo_from_row({str(k): str(v) for k, v in item.items()}, metadata_path) + if combo is None: + continue + result[combo] = RunMetadata( + combo=combo, + start_date=parse_date(item.get("start_date") or item.get("StartDate")), + evaluation_start_date=parse_date(item.get("evaluation_start_date") or item.get("EvaluationStartDate")), + tick_replay=parse_bool(item.get("tick_replay") or item.get("TickReplay")), + daily_bars_loaded=parse_int(item.get("daily_bars_loaded") or item.get("DailyBarsLoaded")), + source=str(metadata_path), + ) + return result + + +def validate_metadata(meta: RunMetadata, eval_start_override: Optional[date]) -> List[str]: + reasons: List[str] = [] + eval_start = meta.evaluation_start_date or eval_start_override + if meta.start_date is None: + reasons.append("missing Strategy Analyzer start date") + if eval_start is None: + reasons.append("missing evaluation window start date") + if meta.start_date is not None and eval_start is not None: + warmup_days = trading_days_between(meta.start_date, eval_start) + if warmup_days < 60: + reasons.append("warmup {0} trading days < 60".format(warmup_days)) + if meta.tick_replay is not True: + reasons.append("Tick Replay not proven enabled") + if meta.daily_bars_loaded is None: + reasons.append("missing DailyBarsLoaded proof") + elif meta.daily_bars_loaded < 60: + reasons.append("DailyBarsLoaded {0} < 60".format(meta.daily_bars_loaded)) + return reasons + + +def profit_factor(trades: Sequence[TradeRow]) -> Optional[float]: + wins = sum(trade.pnl for trade in trades if trade.pnl > 0) + losses = abs(sum(trade.pnl for trade in trades if trade.pnl < 0)) + if losses == 0: + return None if wins == 0 else math.inf + return wins / losses + + +def max_drawdown(trades: Sequence[TradeRow]) -> float: + equity = 0.0 + peak = 0.0 + max_dd = 0.0 + for trade in trades: + equity += trade.pnl + if equity > peak: + peak = equity + drawdown = peak - equity + if drawdown > max_dd: + max_dd = drawdown + return max_dd + + +def percent(count: int, total: int) -> Optional[float]: + if total == 0: + return None + return (float(count) / float(total)) * 100.0 + + +def analyze(trades: Sequence[TradeRow], metadata: Dict[Tuple[str, str], RunMetadata], eval_start_override: Optional[date]) -> List[ComboResult]: + grouped: Dict[Tuple[str, str], List[TradeRow]] = {combo: [] for combo in EXPECTED_COMBINATIONS} + for trade in trades: + grouped.setdefault(trade.combo, []).append(trade) + + results: List[ComboResult] = [] + for combo in EXPECTED_COMBINATIONS: + all_trades = grouped.get(combo, []) + runner_trades = [trade for trade in all_trades if trade.is_runner] + meta = metadata.get(combo, RunMetadata(combo=combo)) + invalid_reasons = validate_metadata(meta, eval_start_override) + if not all_trades: + invalid_reasons.append("missing trade rows") + if not runner_trades: + invalid_reasons.append("missing runner-leg rows") + runner_rs = [trade.r_value for trade in runner_trades if trade.r_value is not None] + results.append( + ComboResult( + combo=combo, + metadata=meta, + all_trades=all_trades, + runner_trades=runner_trades, + valid=len(invalid_reasons) == 0, + invalid_reasons=invalid_reasons, + runner_net_pnl=sum(trade.pnl for trade in runner_trades), + runner_win_rate=percent(len([trade for trade in runner_trades if trade.pnl > 0]), len(runner_trades)), + runner_avg_r=(sum(runner_rs) / len(runner_rs)) if runner_rs else None, + pct_breakeven=percent(len([trade for trade in runner_trades if trade.exit_kind == "breakeven"]), len(runner_trades)), + pct_trail_stop=percent(len([trade for trade in runner_trades if trade.exit_kind == "trail_stop"]), len(runner_trades)), + pct_full_stop=percent(len([trade for trade in runner_trades if trade.exit_kind == "full_stop"]), len(runner_trades)), + combined_pf=profit_factor(all_trades), + max_drawdown=max_drawdown(all_trades), + trade_count=len(all_trades), + ) + ) + return results + + +def fmt_money(value: float) -> str: + return "${0:,.2f}".format(value) + + +def fmt_optional(value: Optional[float], suffix: str = "") -> str: + if value is None: + return "INVALID" + if math.isinf(value): + return "inf" + return "{0:.2f}{1}".format(value, suffix) + + +def result_to_dict(result: ComboResult) -> Dict[str, Any]: + return { + "breakeven_trigger_ticks": result.combo[0], + "runner_trail_ticks": result.combo[1], + "valid": result.valid, + "invalid_reasons": result.invalid_reasons, + "daily_bars_loaded": result.metadata.daily_bars_loaded, + "runner_net_pnl": result.runner_net_pnl, + "runner_win_rate": result.runner_win_rate, + "runner_avg_r": result.runner_avg_r, + "runner_exit_breakeven_pct": result.pct_breakeven, + "runner_exit_trail_stop_pct": result.pct_trail_stop, + "runner_exit_full_stop_pct": result.pct_full_stop, + "combined_profit_factor": result.combined_pf, + "combined_max_drawdown": result.max_drawdown, + "combined_trade_count": result.trade_count, + } + + +def recommend(results: Sequence[ComboResult]) -> str: + valid = [result for result in results if result.valid] + if not valid: + return "No recommendation: no valid sweep combinations. Fix export metadata and rerun." + if all(result.runner_net_pnl <= 0 for result in valid): + return "Recommendation: disable the runner leg. Runner net P&L is non-positive for every valid setting." + best = sorted(valid, key=lambda item: (item.runner_net_pnl, item.combined_pf or 0.0, -item.max_drawdown), reverse=True)[0] + return ( + "Recommendation: BreakevenTriggerTicks={0}, RunnerTrailTicks={1}. " + "This valid combination produced the best runner net P&L ({2}) with combined PF={3}, max DD={4}, trade count={5}." + ).format(best.combo[0], best.combo[1], fmt_money(best.runner_net_pnl), fmt_optional(best.combined_pf), fmt_money(best.max_drawdown), best.trade_count) + + +def render_markdown(results: Sequence[ComboResult]) -> str: + lines: List[str] = [] + lines.append("# Runner Sweep Results") + lines.append("") + lines.append(recommend(results)) + lines.append("") + lines.append("| BE Trigger | Trail | Valid | Daily Bars | Runner Net P&L | Runner Win % | Avg R | BE Exit % | Trail Exit % | Full Stop % | Combined PF | Max DD | Trades | Invalid Reasons |") + lines.append("|---|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|") + for result in results: + lines.append( + "| {0} | {1} | {2} | {3} | {4} | {5} | {6} | {7} | {8} | {9} | {10} | {11} | {12} | {13} |".format( + result.combo[0], + result.combo[1], + "YES" if result.valid else "no", + result.metadata.daily_bars_loaded if result.metadata.daily_bars_loaded is not None else "INVALID", + fmt_money(result.runner_net_pnl), + fmt_optional(result.runner_win_rate, "%"), + fmt_optional(result.runner_avg_r), + fmt_optional(result.pct_breakeven, "%"), + fmt_optional(result.pct_trail_stop, "%"), + fmt_optional(result.pct_full_stop, "%"), + fmt_optional(result.combined_pf), + fmt_money(result.max_drawdown), + result.trade_count, + "; ".join(result.invalid_reasons) if result.invalid_reasons else "", + ) + ) + return "\n".join(lines) + + +def main(argv: Sequence[str]) -> int: + args = parse_args(argv) + input_path = expand_path(args.input) + if not input_path.exists(): + sys.stderr.write("Input not found: {0}\n".format(input_path)) + return 2 + try: + metadata_overrides = load_metadata_override(args.metadata) + except RuntimeError as ex: + sys.stderr.write(str(ex) + "\n") + return 2 + csv_files = discover_csv_files(input_path) + trades, metadata = parse_trade_rows(csv_files) + for combo, meta in metadata_overrides.items(): + metadata[combo] = meta + eval_start = parse_date(args.eval_start) + results = analyze(trades, metadata, eval_start) + if args.json: + sys.stdout.write(json.dumps({"results": [result_to_dict(result) for result in results], "recommendation": recommend(results)}, indent=2) + "\n") + else: + sys.stdout.write(render_markdown(results) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))