chore: checkpoint remaining pre-gate worktree changes

- governance: stage v7.0 review prompts, run book, roadmap/current-status/decision updates, and sprint board state

- adapters: capture DASH/trailing-drawdown/state-telemetry strategy work already present in the worktree

- tools: capture dashboard console/KPI parser updates, logtriage notes, and runnersweep output

Build: previously clean | Tests: previously 511 passing | Includes all open staged files
This commit is contained in:
2026-08-21 14:53:15 -04:00
parent 28c30bca82
commit d84949caa3
31 changed files with 4844 additions and 142 deletions

View File

@@ -52,6 +52,12 @@ Then open:
http://127.0.0.1:8765/
```
The alternate trading-terminal view is available at:
```text
http://127.0.0.1:8765/console.html
```
Live read-only server launch:
```powershell
@@ -72,7 +78,7 @@ http://127.0.0.1:8765/
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.
For live mode, launch `server.py`; `index.html` polls `/api/state` automatically every 5 seconds and `console.html` polls every 2 seconds.
## Live Server Config
@@ -149,10 +155,14 @@ Webhook/notification failures are logged to stderr and never crash or block the
## Views
`index.html` is the triage board for deciding whether a silent session was a strategy decision or an operational defect.
`console.html` is the alternate trading-console page. It consumes the same read-only `/api/state` payload and shows live strategy status, session readiness, provenance-backed trade rows, count-only grade distribution, PNL_UPDATE curve data, real FactorType score breakdowns, and raw log tail data. Fields that are not emitted by the runtime, such as entry/exit price and per-trade P&L, are explicitly marked unavailable instead of being inferred.
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.
3. Trade detail: grade, score, and provenance fields when present in TOOL-001 trade records.
4. Provenance health: sentinel/default-value counts per field across trade records.
5. Config integrity: `ConfigHash` and `CodeVersion` timeline with drift markers.
## Data Contract

279
tools/dashboard/console.css Normal file
View File

@@ -0,0 +1,279 @@
:root {
--bg: #06090c;
--bg-glow: radial-gradient(circle at 12% -10%, #0d1f26 0%, transparent 45%);
--panel: #0b1015;
--panel-border: #1b2530;
--panel-border-soft: #141c25;
--text: #dce6ee;
--muted: #5f7182;
--muted-2: #8695a3;
--cyan: #35d1e8;
--green: #22c55e;
--green-dim: rgba(34, 197, 94, 0.14);
--red: #f5495f;
--red-dim: rgba(245, 73, 95, 0.14);
--amber: #f5a623;
--amber-dim: rgba(245, 166, 35, 0.14);
--blue: #4fa3ff;
--grade-a: #22c55e;
--grade-b: #4fa3ff;
--grade-c: #f5a623;
--grade-d: #5f7182;
--grade-f: #f5495f;
--mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, "Courier New", monospace;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
background: var(--bg-glow), var(--bg);
color: var(--text);
font-family: var(--mono);
}
a { color: var(--cyan); text-decoration: none; }
a:hover { text-decoration: underline; }
.console-header {
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 1rem;
padding: 1.5rem;
border-bottom: 1px solid var(--panel-border-soft);
}
.console-header h1 {
margin: 0.2rem 0;
font-size: clamp(1.9rem, 4vw, 4rem);
letter-spacing: -0.06em;
text-transform: uppercase;
}
.eyebrow, .subhead, .muted, .card-note, small { color: var(--muted-2); }
.eyebrow { margin: 0; font-size: 0.72rem; letter-spacing: 0.18em; text-transform: uppercase; }
.subhead { margin: 0; }
.header-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 0.7rem;
}
.header-clock { color: var(--muted-2); font-size: 0.9rem; }
.nav-link { border: 1px solid var(--panel-border); border-radius: 999rem; padding: 0.4rem 0.75rem; }
.hidden { display: none !important; }
main.console-grid {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 1rem;
padding: 1rem 1.5rem 1.5rem;
}
.col-4 { grid-column: span 4; }
.col-8 { grid-column: span 8; }
.col-12 { grid-column: span 12; }
.card {
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 0.55rem;
padding: 1rem;
}
.card-title {
position: relative;
margin: 0 0 0.8rem;
padding-left: 0.75rem;
font-size: 0.95rem;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.card-title::before {
content: "";
position: absolute;
left: 0;
top: 0.05rem;
bottom: 0.05rem;
width: 3px;
background: var(--cyan);
}
.section-stack { display: grid; gap: 1rem; }
.field-row { display: flex; justify-content: space-between; gap: 1rem; padding: 0.45rem 0; border-bottom: 1px solid var(--panel-border-soft); }
.field-row span:first-child { color: var(--muted); }
.field-row strong { text-align: right; }
.pill, .side-pill, .grade-tag {
display: inline-flex;
align-items: center;
border-radius: 999rem;
border: 1px solid currentColor;
background: transparent;
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.05em;
padding: 0.22rem 0.5rem;
text-transform: uppercase;
}
.pill.good { color: var(--green); }
.pill.bad { color: var(--red); }
.pill.warn { color: var(--amber); }
.pill.info { color: var(--blue); }
.pill.muted { color: var(--muted); }
.side-pill.long { color: var(--green); }
.side-pill.short { color: var(--red); }
.side-pill.neutral { color: var(--muted); }
.grade-a { color: var(--grade-a); }
.grade-b { color: var(--grade-b); }
.grade-c { color: var(--grade-c); }
.grade-d { color: var(--grade-d); }
.grade-f { color: var(--grade-f); }
.confluence-list, .readiness-strip, .factor-bars, .stat-grid, .grade-grid {
display: grid;
gap: 0.65rem;
}
.confluence-item, .readiness-chip, .factor-row, .stat-cell, .grade-cell {
border: 1px solid var(--panel-border-soft);
border-radius: 0.45rem;
background: rgba(255, 255, 255, 0.015);
}
.confluence-item {
display: block;
padding: 0.5rem;
}
.confluence-main {
display: flex;
justify-content: space-between;
gap: 0.6rem;
}
.confluence-reason {
color: var(--muted-2);
font-size: 0.72rem;
font-style: italic;
margin-top: 0.3rem;
}
.confluence-item.unmet { color: var(--muted); }
.confluence-score { color: var(--muted-2); white-space: nowrap; }
.source-tag { color: var(--cyan); font-size: 0.7rem; letter-spacing: 0.08em; text-transform: uppercase; }
.readiness-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.readiness-chip { padding: 0.65rem; }
.readiness-chip strong { display: block; margin-bottom: 0.25rem; }
.readiness-chip.good { border-color: rgba(34, 197, 94, 0.45); }
.readiness-chip.bad { border-color: rgba(245, 73, 95, 0.45); }
.readiness-chip.warn { border-color: rgba(245, 166, 35, 0.45); }
.readiness-summary {
border: 1px solid rgba(79, 163, 255, 0.35);
border-radius: 0.5rem;
color: var(--text);
margin: 0.9rem 0;
padding: 0.75rem;
}
.readiness-detail {
border-top: 1px solid var(--panel-border-soft);
margin-top: 0.8rem;
padding-top: 0.8rem;
}
.readiness-detail summary {
color: var(--muted-2);
cursor: pointer;
font-size: 0.78rem;
letter-spacing: 0.1em;
margin-bottom: 0.75rem;
text-transform: uppercase;
}
.telemetry-note, .data-gap {
border: 1px dashed var(--panel-border);
border-radius: 0.5rem;
color: var(--muted-2);
margin-top: 0.8rem;
padding: 0.75rem;
}
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid var(--panel-border-soft); padding: 0.65rem 0.6rem; text-align: left; white-space: nowrap; }
th { color: var(--muted); font-size: 0.72rem; letter-spacing: 0.08em; text-transform: uppercase; }
td.empty { color: var(--muted); text-align: center; }
.grade-grid { grid-template-columns: repeat(5, minmax(0, 1fr)); }
.grade-cell { padding: 0.8rem; }
.grade-cell strong { display: block; font-size: 2rem; margin-top: 0.35rem; }
.factor-row { padding: 0.65rem; }
.factor-meta { display: flex; justify-content: space-between; gap: 1rem; margin-bottom: 0.45rem; }
.factor-reason { color: var(--muted-2); font-size: 0.72rem; font-style: italic; margin-top: 0.4rem; }
.factor-track, .risk-track { background: #071018; border-radius: 999rem; overflow: hidden; }
.factor-track { height: 0.45rem; }
.factor-fill { height: 100%; width: 0; background: var(--cyan); }
.risk-track { height: 0.7rem; background: linear-gradient(90deg, var(--green-dim), var(--amber-dim), var(--red-dim)); border: 1px solid var(--panel-border-soft); }
.risk-fill { height: 100%; width: 0; background: var(--red); }
.stat-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.stat-cell { padding: 0.75rem; }
.stat-cell span { color: var(--muted); display: block; font-size: 0.75rem; text-transform: uppercase; }
.stat-cell strong { display: block; font-size: 1.45rem; margin-top: 0.3rem; }
.telemetry-subtext { color: var(--muted-2); display: block; font-size: 0.72rem; margin-top: 0.2rem; text-transform: none; }
.pnl-chart { width: 100%; min-height: 16rem; }
.pnl-chart svg { display: block; width: 100%; height: 16rem; border: 1px solid var(--panel-border-soft); border-radius: 0.45rem; background: #071018; }
.axis-label { color: var(--muted); display: flex; justify-content: space-between; margin-top: 0.4rem; font-size: 0.75rem; }
.raw-log {
max-height: 24rem;
overflow: auto;
margin: 0;
padding: 0.85rem;
background: #071018;
border: 1px solid var(--panel-border-soft);
border-radius: 0.45rem;
color: var(--muted-2);
font-family: var(--mono);
font-size: 0.82rem;
line-height: 1.45;
white-space: pre-wrap;
}
.raw-log-line { color: var(--muted-2); display: block; }
.raw-log-signal { color: var(--cyan); }
.raw-log-submit { color: var(--amber); }
.raw-log-fill { color: var(--green); }
.raw-log-reject { color: var(--red); }
.raw-log-reject-summary { color: rgba(245, 73, 95, 0.72); }
.raw-log-state { color: var(--blue); }
.raw-log-warning { color: var(--amber); }
.raw-log-connection-lost { color: var(--red); font-weight: 700; }
.raw-log-connection-restored { color: var(--green); font-weight: 700; }
.raw-log-session { color: var(--cyan); font-weight: 700; }
.footnote { color: var(--muted); margin: 0.75rem 0 0; font-size: 0.82rem; }
.unavailable { border-color: rgba(245, 73, 95, 0.55); color: var(--red); }
@media (max-width: 1100px) {
.col-4, .col-8, .col-12 { grid-column: 1 / -1; }
.readiness-strip { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 640px) {
.console-header { align-items: flex-start; flex-direction: column; padding: 1rem; }
.header-actions { justify-content: flex-start; }
main.console-grid { padding: 1rem; }
.readiness-strip, .grade-grid, .stat-grid { grid-template-columns: 1fr; }
th, td { padding: 0.55rem 0.45rem; }
}

View File

@@ -0,0 +1,145 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NT8 SDK Trading Console</title>
<link rel="stylesheet" href="console.css">
</head>
<body>
<header class="console-header">
<div>
<p class="eyebrow">Trading Console</p>
<h1 id="strategy-name">Simple ORB NT8</h1>
<p class="subhead">NQ · OPENING RANGE BREAKOUT</p>
</div>
<div class="header-actions">
<span id="live-clock" class="header-clock">--:--:-- ET</span>
<span id="market-pill" class="pill muted">Market unknown</span>
<span id="regime-pill" class="pill info hidden"></span>
<a class="nav-link" href="index.html">Triage Board</a>
</div>
</header>
<main class="console-grid">
<section class="card col-4" aria-labelledby="status-title">
<h2 id="status-title" class="card-title">Strategy Status</h2>
<div id="server-message" class="telemetry-note unavailable">Live server unavailable. Open through tools/dashboard/server.py for live data.</div>
<div class="section-stack">
<div>
<div class="field-row"><span>Connection</span><strong id="connection-pill"><span class="pill muted">Unavailable</span></strong></div>
<div class="field-row"><span>Mode</span><strong id="mode-value">-</strong></div>
<div class="field-row"><span>Account</span><strong id="account-value">-</strong></div>
<div class="field-row"><span>Symbol</span><strong id="symbol-value">NQ</strong></div>
</div>
<div>
<h3 class="card-title">Configured Risk (static)</h3>
<div class="field-row"><span>R:R Ratio</span><strong id="rr-ratio">-</strong></div>
<div class="field-row"><span>Target Ticks</span><strong id="target-ticks">-</strong></div>
<div class="field-row"><span>Stop Ticks</span><strong id="stop-ticks">-</strong></div>
<div class="field-row"><span>Target Dollars</span><strong id="target-dollars">-</strong></div>
<div class="field-row"><span>Stop Dollars</span><strong id="stop-dollars">-</strong></div>
<p class="footnote">Static configured values above. Live per-trade sizing rationale below, once a trade has submitted this session.</p>
<div id="dynamic-sizing" class="section-stack"></div>
</div>
<div>
<h3 class="card-title">Session Filter</h3>
<div class="field-row"><span>Window</span><strong id="orb-window">RTH ORB WINDOW</strong></div>
<div class="field-row"><span>RTH Guard</span><strong>09:30-16:00 ET</strong></div>
<div id="orb-range" class="section-stack"></div>
</div>
<div>
<h3 class="card-title">Confluences</h3>
<div id="confluence-list" class="confluence-list"></div>
<p id="confluence-note" class="footnote"></p>
</div>
</div>
</section>
<section class="card col-8" aria-labelledby="readiness-title">
<h2 id="readiness-title" class="card-title">Session Readiness</h2>
<p id="readiness-context" class="card-note">Read from the current session Historical readiness block.</p>
<h3 class="card-title">State Telemetry</h3>
<div id="state-telemetry" class="stat-grid"></div>
<p id="readiness-summary" class="readiness-summary">Readiness summary unavailable until data loads.</p>
<details class="readiness-detail">
<summary>Data Series Detail</summary>
<div id="data-series" class="readiness-strip"></div>
</details>
<details class="readiness-detail">
<summary>Factor Warm-Up Detail</summary>
<div id="warmup-factors" class="readiness-strip"></div>
</details>
<div id="telemetry-note" class="telemetry-note">No state telemetry received yet this session.</div>
</section>
<section class="card col-4" aria-labelledby="risk-reject-title">
<h2 id="risk-reject-title" class="card-title">Risk &amp; Rejection Summary</h2>
<p class="card-note">Full current-session file, not limited to the raw-log tail.</p>
<div id="reject-totals" class="section-stack"></div>
<div class="field-row"><span>Missed B+ Setups <small>(approximate)</small></span><strong id="missed-bplus-count">0</strong></div>
<div id="missed-bplus-samples" class="section-stack"></div>
<p class="footnote">Approximate: inferred from STATE samples after blocking REJECT reasons have appeared in the session log.</p>
</section>
<section class="card col-8" aria-labelledby="signal-outcomes-title">
<h2 id="signal-outcomes-title" class="card-title">Signals by Grade</h2>
<p class="card-note">Generated signals correlated with fills before the next signal or session end.</p>
<div class="table-wrap"><table id="signal-grade-table"></table></div>
<details class="readiness-detail">
<summary>Signal Outcome Detail</summary>
<div class="table-wrap"><table id="signal-outcome-table"></table></div>
</details>
</section>
<section class="card col-12" aria-labelledby="trade-log-title">
<h2 id="trade-log-title" class="card-title">Trade Log</h2>
<div class="table-wrap"><table id="trade-table"></table></div>
<p class="footnote">Entry/exit price and per-trade P&amp;L are not yet in trade provenance.</p>
</section>
<section class="card col-12" aria-labelledby="grade-title">
<h2 id="grade-title" class="card-title">Grade Distribution</h2>
<div id="grade-grid" class="grade-grid"></div>
</section>
<section class="card col-12" aria-labelledby="pnl-curve-title">
<h2 id="pnl-curve-title" class="card-title">Intraday P&amp;L Curve</h2>
<div id="pnl-chart" class="pnl-chart"></div>
</section>
<section class="card col-8" aria-labelledby="factor-title">
<h2 id="factor-title" class="card-title">Factor Breakdown</h2>
<p id="factor-source" class="footnote"></p>
<div id="factor-bars" class="factor-bars"></div>
</section>
<aside class="card col-4" aria-labelledby="summary-title">
<h2 id="summary-title" class="card-title">P&amp;L Summary</h2>
<div class="stat-grid">
<div class="stat-cell"><span>Instrument</span><strong id="summary-symbol">NQ</strong></div>
<div class="stat-cell"><span>Daily P&amp;L</span><strong id="summary-pnl">-</strong></div>
<div class="stat-cell"><span>Total Trades</span><strong id="summary-trades">0</strong></div>
<div class="stat-cell"><span>Position</span><strong id="summary-position">-</strong></div>
</div>
<h3 class="card-title">Session Summary</h3>
<div class="field-row"><span>Net P&amp;L</span><strong id="row-net-pnl">-</strong></div>
<div class="field-row"><span>Submits</span><strong id="row-submits">-</strong></div>
<div class="field-row"><span>Fills</span><strong id="row-fills">-</strong></div>
<div class="field-row"><span>Daily Loss Limit Used</span><strong id="loss-used-label">-</strong></div>
<div class="risk-track" aria-label="Daily loss limit used"><div id="loss-used-fill" class="risk-fill"></div></div>
</aside>
<section class="card col-12" aria-labelledby="raw-title">
<h2 id="raw-title" class="card-title">Raw Log</h2>
<pre id="raw-log" class="raw-log">No live log data loaded.</pre>
</section>
</main>
<template id="empty-row">
<tr><td class="empty" colspan="99">No data loaded.</td></tr>
</template>
<script src="console.js"></script>
</body>
</html>

671
tools/dashboard/console.js Normal file
View File

@@ -0,0 +1,671 @@
(function () {
"use strict";
var POLL_MS = 2000;
var FACTORS = ["Setup", "Trend", "Volatility", "Timing", "ExecutionQuality", "NarrowRange", "OrbRangeVsAtr", "GapDirectionAlignment", "BreakoutVolumeStrength", "PriorDayCloseStrength"];
var GRADES = ["A", "B", "C", "D", "F"];
var emptyTemplate = document.getElementById("empty-row");
var latestPayload = null;
function byId(id) { return document.getElementById(id); }
function asArray(value) { return Array.isArray(value) ? value : []; }
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, "").replace(/,/g, ""));
return isNaN(parsed) ? 0 : parsed;
}
function money(value) {
if (value === null || value === undefined || value === "") {
return "-";
}
return "$" + numberValue(value).toFixed(2);
}
function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); }
function setText(id, value) { byId(id).textContent = value; }
function setHtml(id, value) { byId(id).innerHTML = value; }
function h(value) {
return display(value).replace(/[&<>"]/g, function (character) {
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;" }[character];
});
}
function pill(label, kind) {
return '<span class="pill ' + kind + '">' + h(label) + '</span>';
}
function gradeClass(grade) {
var normalized = String(grade || "").toLowerCase().charAt(0);
return "grade-" + (normalized || "d");
}
function latestRow(payload) {
var rows = asArray(payload.rows);
return rows.length ? rows[rows.length - 1] : {};
}
function collectRejectRecords(payload) {
var results = [];
asArray(payload.reject_records || payload.rejects || payload.rejections).forEach(function (item) {
results.push(normalizeRejectRecord(item));
});
asArray(payload.rows).forEach(function (row) {
asArray(row.reject_records || row.rejects || row.rejections).forEach(function (item) {
results.push(normalizeRejectRecord(item));
});
});
asArray(payload.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 normalizeRejectRecord(item) {
if (!item) {
return {};
}
if (typeof item === "string") {
return parseRejectLine(item);
}
var line = item.line || item.message || item.raw || "";
var parsed = line ? parseRejectLine(String(line)) : {};
return {
reason: item.reason || item.reject_reason || parsed.reason,
detail: item.detail || item.reject_detail || parsed.detail || "",
bar: item.bar || item.bar_time || parsed.bar,
raw: line || item.raw || ""
};
}
function parseRejectLine(line) {
var reasonMatch = /reason=([^\s]+)/i.exec(line || "");
var detailMatch = /detail=(.*?)(?:\s+bar=|$)/i.exec(line || "");
var barMatch = /\sbar=(.*)$/i.exec(line || "");
return {
reason: reasonMatch ? reasonMatch[1] : null,
detail: detailMatch ? detailMatch[1] : "",
bar: barMatch ? barMatch[1] : null,
raw: line
};
}
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 pickFactors(payload) {
var telemetry = latestStateTelemetry(payload);
if (telemetry && asArray(telemetry.factors).length) {
return { factors: asArray(telemetry.factors), source: "live", label: "live state telemetry" };
}
var records = collectRejectRecords(payload).filter(function (record) { return record.reason === "GradeFilter"; });
var i;
for (i = records.length - 1; i >= 0; i -= 1) {
var parsed = parseFactors(records[i].detail || records[i].raw || "");
if (parsed.length) {
return { factors: parsed, source: "last rejection", label: "last GradeFilter rejection" };
}
}
return { factors: [], source: "unavailable", label: "No factor data available yet — waiting on state telemetry or a GradeFilter rejection." };
}
function latestStateTelemetry(payload) {
var live = payload.live_state || {};
if (live.state_telemetry) {
return live.state_telemetry;
}
var events = asArray(payload.events);
var i;
for (i = events.length - 1; i >= 0; i -= 1) {
if (events[i] && events[i].type === "STATE") {
return events[i];
}
}
return null;
}
function factorMap(factors) {
var map = {};
factors.forEach(function (factor) { map[factor.name] = factor; });
return map;
}
function clear(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function renderHeader(payload) {
var settings = payload.settings || {};
var telemetry = latestStateTelemetry(payload);
var regimePill = byId("regime-pill");
setText("strategy-name", settings.StrategyName || "Simple ORB NT8");
if (telemetry && telemetry.regime) {
regimePill.className = "pill info";
regimePill.textContent = "Regime " + telemetry.regime;
} else {
regimePill.className = "pill info hidden";
regimePill.textContent = "";
}
}
function renderClock() {
var now = new Date();
var parts = new Intl.DateTimeFormat("en-US", { timeZone: "America/New_York", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit", weekday: "short" }).formatToParts(now);
var values = {};
parts.forEach(function (part) { values[part.type] = part.value; });
var hour = Number(values.hour || 0);
var minute = Number(values.minute || 0);
var day = values.weekday || "";
var minutes = hour * 60 + minute;
var weekday = day !== "Sat" && day !== "Sun";
var open = weekday && minutes >= 570 && minutes < 960;
setText("live-clock", (values.hour || "--") + ":" + (values.minute || "--") + ":" + (values.second || "--") + " ET");
setHtml("market-pill", pill(open ? "Market open" : "Market closed", open ? "good" : "muted"));
}
function renderStatus(payload) {
var live = payload.live_state || {};
var settings = payload.settings || {};
var connection = live.connection || "Unavailable";
var connectionKind = connection === "OK" || connection === "RESTORED" ? "good" : (connection === "LOST" ? "bad" : "muted");
setHtml("connection-pill", pill(connection, connectionKind));
setText("mode-value", display(live.mode));
setText("account-value", display(live.account));
setText("symbol-value", display(live.symbol || settings.Instrument || "NQ"));
setText("rr-ratio", display(settings.RR_Ratio));
setText("target-ticks", display(settings.TargetTicks));
setText("stop-ticks", display(settings.StopTicks));
setText("target-dollars", display(settings.TargetDollars));
setText("stop-dollars", display(settings.StopDollars));
setText("orb-window", settings.OpeningRangeMinutes ? "09:30 + " + display(settings.OpeningRangeMinutes) + " min ORB" : "OpeningRangeMinutes unavailable");
renderOrbRange(payload);
renderDynamicSizing(payload);
renderConfluences(payload);
}
function renderOrbRange(payload) {
var node = byId("orb-range");
var fields = ((payload.live_state || {}).state_context) || {};
clear(node);
if (!("OrbHigh" in fields) || !("OrbLow" in fields)) {
node.innerHTML = '<div class="data-gap">ORB range not yet established this session.</div>';
return;
}
node.innerHTML = '<div class="field-row"><span>ORB High</span><strong>' + h(fields.OrbHigh) + '</strong></div>'
+ '<div class="field-row"><span>ORB Low</span><strong>' + h(fields.OrbLow) + '</strong></div>'
+ '<div class="field-row"><span>Window</span><strong>' + h(fields.OrbWindowStart) + ' – ' + h(fields.OrbWindowEnd) + ' ET</strong></div>';
}
function renderDynamicSizing(payload) {
var node = byId("dynamic-sizing");
var submit = (payload.live_state || {}).last_submit;
var fields = submit && submit.fields ? submit.fields : null;
clear(node);
if (!fields || !("CombinedMult" in fields)) {
node.innerHTML = '<div class="data-gap">No trade submitted yet this session — dynamic sizing rationale appears here after the first SUBMIT.</div>';
return;
}
var rows = [
["Base Target", fields.BaseTarget],
["Dynamic Target", fields.DynamicTarget],
["Grade Multiplier", fields.GradeMult],
["Mode Multiplier", fields.ModeMult],
["Combined Multiplier", fields.CombinedMult]
];
rows.forEach(function (pair) {
var row = document.createElement("div");
row.className = "field-row";
var value = pair[1];
var text = typeof value === "number" ? value.toFixed(3) : display(value);
row.innerHTML = "<span>" + h(pair[0]) + "</span><strong>" + h(text) + "</strong>";
node.appendChild(row);
});
}
function renderConfluences(payload) {
var list = byId("confluence-list");
var picked = pickFactors(payload);
var map = factorMap(picked.factors);
var reasons = ((payload.live_state || {}).state_telemetry_reasons) || {};
clear(list);
FACTORS.forEach(function (name) {
var factor = map[name];
var reason = reasons[name];
var row = document.createElement("div");
row.className = "confluence-item" + (factor ? "" : " unmet");
if (reason) {
row.title = reason;
}
row.innerHTML = "<div class=\"confluence-main\"><span>" + h(name) + "</span><span class=\"confluence-score\">" + (factor ? h(factor.score.toFixed(3) + " x " + factor.weight.toFixed(2)) : "unmet") + "</span></div>"
+ (reason ? "<div class=\"confluence-reason\">" + h(reason) + "</div>" : "");
list.appendChild(row);
});
setHtml("confluence-note", picked.factors.length ? '<span class="source-tag">' + h(picked.source) + '</span> ' + h("Showing factors from " + picked.label + ".") : h(picked.label));
}
function renderReadiness(payload) {
var readiness = payload.readiness || {};
setText("readiness-context", readiness.context || "No Historical readiness block found in the current payload.");
renderStateTelemetry(payload);
setText("readiness-summary", summarizeReadiness(readiness));
renderDataSeries(asArray(readiness.data_series));
renderWarmups(asArray(readiness.factors));
}
function renderStateTelemetry(payload) {
var node = byId("state-telemetry");
var telemetry = latestStateTelemetry(payload);
clear(node);
if (!telemetry) {
node.innerHTML = '<div class="data-gap">No state telemetry received yet this session.</div>';
setText("telemetry-note", "No state telemetry received yet this session. EnableStateTelemetry may be false, or the session may not have reached a STATE line yet.");
return;
}
var directionSource = telemetry.direction_source || telemetry.directionsource;
var recommendedContracts = ((payload.live_state || {}).state_context) || {};
node.innerHTML = '<div class="stat-cell" title="Daily SMA20 vs SMA50 trend classification: Bullish, Bearish, or Neutral. Used by the regime gate to penalize or veto trades against the prevailing trend."><span>Regime</span><strong>' + h(telemetry.regime) + '</strong></div>'
+ '<div class="stat-cell" title="The side (Buy/Sell) this telemetry sample would trade if conditions were met right now — diagnostic only, does not mean a signal was generated."><span>Direction</span><strong>' + h(telemetry.direction) + '<small class="telemetry-subtext">via ' + h(directionSource) + '</small></strong></div>'
+ '<div class="stat-cell"><span>Score</span><strong>' + h(telemetry.score !== undefined ? Number(telemetry.score).toFixed(3) : "-") + '</strong></div>'
+ '<div class="stat-cell"><span>Grade</span><strong class="' + gradeClass(telemetry.grade) + '">' + h(telemetry.grade) + '</strong></div>'
+ ('RecommendedContracts' in recommendedContracts ? '<div class="stat-cell" title="Live read-only sizing preview from the same position sizer used at signal time — not an order, just what it would recommend right now."><span>Recommended Contracts</span><strong>' + h(recommendedContracts.RecommendedContracts) + '</strong></div>' : '');
setText("telemetry-note", "Latest STATE telemetry at " + display(telemetry.timestamp) + "; direction source: " + display(directionSource) + ".");
}
function summarizeReadiness(readiness) {
var series = asArray(readiness.data_series);
var factors = asArray(readiness.factors);
var primary = series.length ? series[0] : null;
var daily = null;
var factorStatus = "unavailable";
var i;
for (i = 0; i < series.length; i += 1) {
if (String(series[i].type || "").toLowerCase().indexOf("day") >= 0 || String(series[i].type || "").toLowerCase().indexOf("daily") >= 0) {
daily = series[i];
break;
}
}
if (!daily && series.length > 1) {
daily = series[series.length - 1];
}
for (i = 0; i < factors.length; i += 1) {
var name = String(factors[i].name || "");
if (name.indexOf("NarrowRange") === 0 || name.indexOf("OrbRangeVsAtr") === 0) {
if (String(factors[i].status || "").toUpperCase() !== "SATISFIED") {
factorStatus = "still warming up";
break;
}
factorStatus = factorStatus === "unavailable" ? "SATISFIED" : factorStatus;
}
}
if (!primary && !daily && !factors.length) {
return "Readiness summary unavailable until data loads.";
}
return "Primary series: " + display(primary ? primary.historical_bars_loaded : null) + " bars loaded (" + display(primary ? primary.days_to_load : null) + "d configured). Daily context: " + display(daily ? daily.historical_bars_loaded : null) + " bars — narrow-range and ORB-vs-ATR factors are " + factorStatus + ".";
}
function renderDataSeries(series) {
var node = byId("data-series");
clear(node);
if (!series.length) {
node.innerHTML = '<div class="data-gap">No data series readiness data available.</div>';
return;
}
series.forEach(function (item) {
var chip = document.createElement("div");
chip.className = "readiness-chip info";
chip.innerHTML = "<strong>Series[" + h(item.index) + "] " + h(item.type) + "</strong><small>DaysToLoad " + h(item.days_to_load) + " · HistoricalBarsLoaded " + h(item.historical_bars_loaded) + "</small>";
node.appendChild(chip);
});
}
function renderWarmups(factors) {
var node = byId("warmup-factors");
clear(node);
if (!factors.length) {
node.innerHTML = '<div class="data-gap">No factor warm-up data available.</div>';
return;
}
factors.forEach(function (factor) {
var status = String(factor.status || "").toUpperCase();
var kind = status === "SATISFIED" ? "good" : (status === "FAILED" ? "bad" : "warn");
var chip = document.createElement("div");
chip.className = "readiness-chip " + kind;
chip.innerHTML = "<strong>" + h(factor.name) + "</strong><small>" + h(factor.status) + " · " + h(factor.loaded) + "/" + h(factor.required) + " daily bars</small>";
node.appendChild(chip);
});
}
function renderTable(id, headers, rows) {
var table = byId(id);
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tr = document.createElement("tr");
clear(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) {
tbody.appendChild(emptyTemplate.content.cloneNode(true));
} else {
rows.forEach(function (cells) {
var row = document.createElement("tr");
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 renderTrades(payload) {
var rows = asArray(payload.trades).map(function (trade) {
var side = String(trade.side || "").toLowerCase();
var grade = display(trade.confluence_grade);
return [
trade.trade_seq,
trade.timestamp_utc,
{ html: '<span class="side-pill ' + (side === "long" ? "long" : (side === "short" ? "short" : "neutral")) + '">' + h(trade.side) + '</span>' },
{ html: '<span class="grade-tag ' + gradeClass(grade) + '">' + h(grade) + '</span>' },
trade.confluence_score,
trade.resolved_runner_mode,
display(trade.stop_ticks) + " / " + display(trade.target_ticks),
trade.session_tag
];
});
renderTable("trade-table", ["Seq", "Timestamp UTC", "Side", "Grade", "Score", "Runner Mode", "Stop / Target", "Session Tag"], rows);
}
function renderRiskAndRejects(payload) {
var totals = payload.session_reject_totals || {};
var rejectNode = byId("reject-totals");
var reasons = Object.keys(totals).sort(function (a, b) { return String(a).localeCompare(String(b)); });
clear(rejectNode);
if (!reasons.length) {
rejectNode.innerHTML = '<div class="data-gap">No full-session rejection totals found yet.</div>';
} else {
reasons.forEach(function (reason) {
var row = document.createElement("div");
row.className = "field-row";
row.innerHTML = '<span>' + h(reason) + '</span><strong>' + h(totals[reason]) + '</strong>';
rejectNode.appendChild(row);
});
}
setText("missed-bplus-count", display(payload.missed_grade_b_plus_count || 0));
renderMissedBPlusSamples(payload);
}
function renderMissedBPlusSamples(payload) {
var node = byId("missed-bplus-samples");
var samples = asArray(payload.missed_grade_b_plus_samples);
clear(node);
if (!samples.length) {
node.innerHTML = '<div class="data-gap">No approximate missed B+ samples found.</div>';
return;
}
var list = document.createElement("div");
list.className = "section-stack";
samples.slice(-5).forEach(function (sample) {
var item = document.createElement("div");
item.className = "readiness-chip warn";
item.innerHTML = '<strong>' + h(sample.timestamp) + ' Grade ' + h(sample.grade) + ' · Score ' + h(Number(sample.score || 0).toFixed(3)) + '</strong><small>Blocked by ' + h(sample.blocking_reason) + '</small>';
list.appendChild(item);
});
node.appendChild(list);
}
function renderSignalOutcomes(payload) {
var summaryRows = asArray(payload.signal_grade_summary).map(function (item) {
var reasons = item.reject_reasons || {};
var reasonText = Object.keys(reasons).sort().map(function (reason) { return reason + "=" + reasons[reason]; }).join(", ");
return [
{ html: '<span class="grade-tag ' + gradeClass(item.grade) + '">' + h(item.grade) + '</span>' },
item.generated,
item.filled,
item.rejected,
reasonText || "-"
];
});
renderTable("signal-grade-table", ["Grade", "Generated", "Filled", "Rejected", "Reject Reasons"], summaryRows);
var outcomeRows = asArray(payload.signal_outcomes).map(function (item) {
return [
item.time,
item.side,
{ html: '<span class="grade-tag ' + gradeClass(item.grade) + '">' + h(item.grade) + '</span>' },
item.score === null || item.score === undefined ? "-" : Number(item.score).toFixed(3),
item.filled ? "Yes" : "No",
item.reject_reason || "-",
item.reject_detail || ""
];
});
renderTable("signal-outcome-table", ["Time", "Side", "Grade", "Score", "Filled", "Reject", "Detail"], outcomeRows);
}
function renderGrades(payload) {
var counts = { A: 0, B: 0, C: 0, D: 0, F: 0 };
asArray(payload.trades).forEach(function (trade) {
var grade = String(trade.confluence_grade || "").toUpperCase().charAt(0);
if (Object.prototype.hasOwnProperty.call(counts, grade)) {
counts[grade] += 1;
}
});
var grid = byId("grade-grid");
clear(grid);
GRADES.forEach(function (grade) {
var cell = document.createElement("div");
cell.className = "grade-cell " + gradeClass(grade);
cell.innerHTML = "<span>Grade " + h(grade) + "</span><strong>" + counts[grade] + "</strong><small>trade count</small>";
grid.appendChild(cell);
});
}
function renderPnlCurve(payload) {
var points = asArray(payload.events).filter(function (event) { return event.type === "PNL_UPDATE"; });
var node = byId("pnl-chart");
clear(node);
if (points.length < 2) {
node.innerHTML = '<div class="data-gap">Fewer than 2 PNL_UPDATE events available. Intraday curve unavailable.</div>';
return;
}
var values = points.map(function (point) { return numberValue(point.daily_pnl); });
var min = Math.min.apply(Math, values);
var max = Math.max.apply(Math, values);
var span = max - min || 1;
var width = 900;
var height = 240;
var coords = values.map(function (value, index) {
var x = points.length === 1 ? 0 : (index / (points.length - 1)) * width;
var y = height - ((value - min) / span) * height;
return x.toFixed(1) + "," + y.toFixed(1);
}).join(" ");
var zeroY = clamp(height - ((0 - min) / span) * height, 0, height);
node.innerHTML = '<svg viewBox="0 0 900 240" role="img" aria-label="Intraday P and L curve"><line x1="0" y1="' + zeroY.toFixed(1) + '" x2="900" y2="' + zeroY.toFixed(1) + '" stroke="#1b2530"/><polyline points="' + coords + '" fill="none" stroke="#35d1e8" stroke-width="3" stroke-linejoin="round" stroke-linecap="round"/></svg><div class="axis-label"><span>' + h(points[0].timestamp) + '</span><span>' + h(money(min) + ' to ' + money(max)) + '</span><span>' + h(points[points.length - 1].timestamp) + '</span></div>';
}
function renderFactors(payload) {
var node = byId("factor-bars");
var picked = pickFactors(payload);
var map = factorMap(picked.factors);
var reasons = ((payload.live_state || {}).state_telemetry_reasons) || {};
clear(node);
setHtml("factor-source", picked.factors.length ? '<span class="source-tag">' + h(picked.source) + '</span> ' + h("Showing factors from " + picked.label + ".") : h(picked.label));
FACTORS.forEach(function (name) {
var factor = map[name];
var reason = reasons[name];
var score = factor ? clamp(factor.score, 0, 1) : 0;
var row = document.createElement("div");
row.className = "factor-row";
if (reason) {
row.title = reason;
}
row.innerHTML = '<div class="factor-meta"><span>' + h(name) + '</span><strong>' + (factor ? h(factor.score.toFixed(3)) : "unavailable") + '</strong></div><div class="factor-track"><div class="factor-fill" style="width: ' + Math.round(score * 100) + '%"></div></div>'
+ (reason ? '<div class="factor-reason">' + h(reason) + '</div>' : '');
node.appendChild(row);
});
}
function renderSummary(payload) {
var live = payload.live_state || {};
var row = latestRow(payload);
var settings = payload.settings || {};
var dailyPnl = numberValue(live.daily_pnl);
var dailyLossLimit = numberValue(settings.DailyLossLimit);
var used = dailyLossLimit > 0 ? clamp(Math.abs(Math.min(0, dailyPnl)) / dailyLossLimit * 100, 0, 100) : null;
setText("summary-symbol", display(live.symbol || settings.Instrument || "NQ"));
setText("summary-pnl", money(live.daily_pnl));
setText("summary-trades", String(asArray(payload.trades).length));
setText("summary-position", display(live.position));
setText("row-net-pnl", money(row.net_pnl));
setText("row-submits", display(row.submits));
setText("row-fills", display(row.fills));
setText("loss-used-label", used === null ? "DailyLossLimit unavailable" : used.toFixed(1) + "%");
byId("loss-used-fill").style.width = (used === null ? 0 : used) + "%";
}
function renderRaw(payload) {
var lines = asArray(payload.raw_tail);
var node = byId("raw-log");
clear(node);
if (!lines.length) {
node.textContent = "No live log data loaded.";
return;
}
lines.forEach(function (line) {
var item = document.createElement("span");
item.className = "raw-log-line " + classifyLogLine(line);
item.textContent = display(line);
node.appendChild(item);
});
}
function classifyLogLine(line) {
var value = String(line || "").toUpperCase();
if (value.indexOf("CONNECTION LOST") >= 0) {
return "raw-log-connection-lost";
}
if (value.indexOf("CONNECTION RESTORED") >= 0) {
return "raw-log-connection-restored";
}
if (value.indexOf("SESSION START") >= 0 || value.indexOf("SESSION END") >= 0) {
return "raw-log-session";
}
if (value.indexOf("REJECT SUMMARY") >= 0) {
return "raw-log-reject-summary";
}
if (value.indexOf("REJECT") >= 0) {
return "raw-log-reject";
}
if (value.indexOf("SIGNAL") >= 0) {
return "raw-log-signal";
}
if (value.indexOf("SUBMIT") >= 0) {
return "raw-log-submit";
}
if (value.indexOf("FILL") >= 0) {
return "raw-log-fill";
}
if (value.indexOf("STATE") >= 0) {
return "raw-log-state";
}
if (value.indexOf("WARNING") >= 0) {
return "raw-log-warning";
}
return "";
}
function render(payload) {
latestPayload = payload;
byId("server-message").className = "telemetry-note";
setText("server-message", "Live server connected. Values are sourced from /api/state.");
renderHeader(payload);
renderStatus(payload);
renderReadiness(payload);
renderRiskAndRejects(payload);
renderSignalOutcomes(payload);
renderTrades(payload);
renderGrades(payload);
renderPnlCurve(payload);
renderFactors(payload);
renderSummary(payload);
renderRaw(payload);
}
function renderUnavailable(message) {
if (!latestPayload) {
render({ live_state: {}, readiness: {}, rows: [], diagnostics: [], events: [], trades: [], settings: {}, raw_tail: [] });
}
byId("server-message").className = "telemetry-note unavailable";
setText("server-message", message || "Live server unavailable. Open through tools/dashboard/server.py for live data.");
}
function loadServerState() {
fetch("/api/state", { cache: "no-store" }).then(function (response) {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.json();
}).then(function (payload) {
render(payload || {});
}).catch(function () {
renderUnavailable("Live server unavailable. Open through tools/dashboard/server.py for live data.");
});
}
renderClock();
renderUnavailable("Live server unavailable. Open through tools/dashboard/server.py for live data.");
loadServerState();
setInterval(renderClock, 1000);
setInterval(loadServerState, POLL_MS);
}());

View File

@@ -17,6 +17,7 @@
<span class="status-label">Mode</span>
<strong>Static HTML + vanilla JS</strong>
<span>No NT8 references. No writes.</span>
<a href="console.html">Trading Console</a>
</div>
</header>

View File

@@ -18,6 +18,11 @@ 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)
SIGNAL_RE = re.compile(r"\bSIGNAL:?\s+(Buy|Sell|Long|Short)\b(?:\s+([^|]+?))?(?:\s*\|\s*(.*))?$", re.IGNORECASE)
SIGNAL_GRADE_RE = re.compile(r"\bGrade=([^\s|]+)", re.IGNORECASE)
SIGNAL_SCORE_RE = re.compile(r"\bScore=([0-9.]+)", re.IGNORECASE)
REJECT_RE = re.compile(r"\bREJECT:\s*(.*)$", re.IGNORECASE)
REJECT_SUMMARY_RE = re.compile(r"\bREJECT SUMMARY:\s*(.*)$", 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)
@@ -29,6 +34,133 @@ MODE_RE = re.compile(r"^Mode\s*:\s*(.+)$", re.IGNORECASE)
DATA_SERIES_RE = re.compile(r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=([^\s]+)\s+HistoricalBarsLoaded=([^\s]+)", re.IGNORECASE)
FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE)
FACTOR_STATUS_RE = re.compile(r"([A-Za-z0-9_]+)=(SATISFIED|FAILED|UNSATISFIED)\s*\((\d+)/(\d+)\s+daily bars\)", re.IGNORECASE)
STATE_RE = re.compile(
r"STATE:\s*Regime=(\S+)\s+Direction=(\S+)\s+DirectionSource=(\S+)\s+Score=([0-9.]+)\s+Grade=(\S+)\s+Factors=(.*)$",
re.IGNORECASE,
)
STATE_FACTOR_ENTRY_RE = re.compile(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$")
STATE_DETAIL_RE = re.compile(r"\bSTATE_DETAIL:\s*(.*)$", re.IGNORECASE)
SIGNAL_DETAIL_RE = re.compile(r"\bSIGNAL_DETAIL:\s*(.*)$", re.IGNORECASE)
QUOTED_KV_RE = re.compile(r'(\w+)="((?:[^"\\]|\\.)*)"')
SUBMIT_FIELD_RE = re.compile(
r"\b(Scaler|Runner|Stop|Target|Mode|BaseTarget|DynamicTarget|GradeMult|ModeMult|CombinedMult)=(\S+)",
re.IGNORECASE,
)
SUBMIT_NUMERIC_FIELDS = ("BaseTarget", "DynamicTarget", "GradeMult", "ModeMult", "CombinedMult")
STATE_CONTEXT_RE = re.compile(r"\bSTATE_CONTEXT:\s*(.*)$", re.IGNORECASE)
STATE_CONTEXT_FIELD_RE = re.compile(r"(\w+)=(\S+)")
REJECT_KV_RE = re.compile(r"\b(reason|detail|bar|count)=", re.IGNORECASE)
BLOCKING_REJECT_REASONS = set(["RthGuard", "MaxDailyTrades", "KillSwitch", "CmeHoliday"])
def parse_key_values(text: str) -> Dict[str, str]:
"""Parses marker-bounded key=value text for REJECT lines.
Values such as detail=... may contain spaces or additional '=' tokens, so
this uses known key markers as boundaries rather than splitting on spaces.
"""
result: Dict[str, str] = {}
matches = list(REJECT_KV_RE.finditer(text or ""))
for index, match in enumerate(matches):
key = match.group(1)
value_start = match.end()
value_end = matches[index + 1].start() if index + 1 < len(matches) else len(text or "")
result[key] = (text or "")[value_start:value_end].strip()
return result
def grade_rank(grade: Any) -> int:
text = str(grade or "").upper().strip()
if text == "A+":
return 6
if text == "A":
return 5
if text == "B":
return 4
if text == "C":
return 3
if text == "D":
return 2
if text == "F":
return 1
return 0
def is_grade_b_or_better(grade: Any) -> bool:
return grade_rank(grade) >= grade_rank("B")
def parse_state_context_fields(text: str) -> Dict[str, str]:
"""Parses STATE_CONTEXT: unquoted Key=Value tokens (DEC-20260818-02/03).
Unlike STATE_DETAIL:/SIGNAL_DETAIL:, these values are plain tokens
(numbers, HH:mm times, booleans) with no internal spaces or quoting, so
a simple space/= split is sufficient. The field set is deliberately
generic — GetStateTelemetryContextFields() is an extension point any
strategy can override with its own keys (e.g. SimpleORBNT8's OrbHigh/
OrbLow/OrbWindowStart/OrbWindowEnd/OrbReady), plus the universal
RecommendedContracts field NT8StrategyBase always appends when present.
"""
fields: Dict[str, str] = {}
for key, value in STATE_CONTEXT_FIELD_RE.findall(text or ""):
fields[key] = value
return fields
def parse_quoted_reasons(text: str) -> Dict[str, str]:
"""Parses STATE_DETAIL:/SIGNAL_DETAIL: quoted key="value" pairs (DEC-20260817-09).
Reverses NT8StrategyBase.cs's EscapeLogValue() (\\ -> \\\\, " -> \\") with a
single backslash-escaped-char substitution, which correctly handles both
escape sequences in one pass since the original escaping only ever emits
a backslash followed by exactly one of those two characters.
"""
result: Dict[str, str] = {}
for key, raw_value in QUOTED_KV_RE.findall(text or ""):
result[key] = re.sub(r"\\(.)", r"\1", raw_value)
return result
def parse_submit_fields(detail: str) -> Dict[str, Any]:
"""Parses SUBMIT line fields, including the DEC-20260817-09 sizing-rationale
fields appended after Mode=. Numeric fields are coerced to float where
parseable; GetMetadataText() emits "N/A" for missing intent.Metadata keys,
which is left as a string so the dashboard can render it distinctly from 0.
"""
fields: Dict[str, Any] = {}
for key, value in SUBMIT_FIELD_RE.findall(detail or ""):
if key in SUBMIT_NUMERIC_FIELDS and value != "N/A":
try:
fields[key] = float(value)
continue
except ValueError:
pass
fields[key] = value
return fields
def parse_state_factors(text: str) -> List[Dict[str, Any]]:
"""Parses the DASH-002 STATE: line's Factors=name=scorexweight;... segment.
Same convention as the GradeFilter reject-detail factor breakdown
(app.js's parseFactors()), reused here for consistency rather than
inventing a second format.
"""
factors: List[Dict[str, Any]] = []
if not text:
return factors
for part in text.split(";"):
part = part.strip()
if not part:
continue
match = STATE_FACTOR_ENTRY_RE.match(part)
if match:
factors.append({
"name": match.group(1),
"score": float(match.group(2)),
"weight": float(match.group(3)) if match.group(3) else 1.0,
})
return factors
def expand_path(raw_path: str) -> Path:
@@ -113,6 +245,43 @@ def parse_money(value: str) -> float:
return 0.0
def parse_state_telemetry_detail(detail: str) -> Dict[str, Any]:
result: Dict[str, Any] = {"detail": detail}
factors_match = re.search(r"Factors=([^\n]+)$", detail or "", re.IGNORECASE)
if factors_match:
result["factors"] = parse_factor_breakdown(factors_match.group(1))
detail = detail[:factors_match.start()].strip()
for match in re.finditer(r"(Regime|Direction|DirectionSource|Score|Grade)=([^\s]+)", detail or "", re.IGNORECASE):
key = match.group(1).lower()
value = match.group(2)
if key == "score":
try:
result[key] = float(value)
except ValueError:
result[key] = value
else:
result[key] = value
return result
def parse_factor_breakdown(text: str) -> List[Dict[str, Any]]:
factors: List[Dict[str, Any]] = []
for part in (text or "").split(";"):
match = re.match(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$", part.strip(), re.IGNORECASE)
if match is None:
continue
try:
score = float(match.group(2))
except ValueError:
score = 0.0
try:
weight = float(match.group(3)) if match.group(3) else 1.0
except ValueError:
weight = 1.0
factors.append({"name": match.group(1), "score": score, "weight": weight})
return factors
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)}
@@ -123,10 +292,43 @@ def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]:
payload.update({"type": "SESSION START", "session_start": start.group(1)})
return payload
state = STATE_RE.search(message)
if state:
payload = dict(base)
payload.update({
"type": "STATE",
"regime": state.group(1),
"direction": state.group(2),
"direction_source": state.group(3),
"score": float(state.group(4)),
"grade": state.group(5),
"factors": parse_state_factors(state.group(6)),
})
return payload
submit = SUBMIT_RE.search(message)
if submit:
payload = dict(base)
payload.update({"type": "SUBMIT", "detail": submit.group(1).strip()})
detail_text = submit.group(1).strip()
payload.update({"type": "SUBMIT", "detail": detail_text, "fields": parse_submit_fields(detail_text)})
return payload
state_detail = STATE_DETAIL_RE.search(message)
if state_detail:
payload = dict(base)
payload.update({"type": "STATE_DETAIL", "reasons": parse_quoted_reasons(state_detail.group(1))})
return payload
signal_detail = SIGNAL_DETAIL_RE.search(message)
if signal_detail:
payload = dict(base)
payload.update({"type": "SIGNAL_DETAIL", "reasons": parse_quoted_reasons(signal_detail.group(1))})
return payload
state_context = STATE_CONTEXT_RE.search(message)
if state_context:
payload = dict(base)
payload.update({"type": "STATE_CONTEXT", "fields": parse_state_context_fields(state_context.group(1))})
return payload
fill = FILL_RE.search(message)
@@ -185,6 +387,160 @@ def parse_session_event(path: Path, line: str) -> Optional[Dict[str, Any]]:
return None
def parse_signal_line(message: str, timestamp: Optional[str], source_line: str, latest_state: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
signal = SIGNAL_RE.search(message or "")
if signal is None:
return None
side = signal.group(1)
detail = signal.group(3) or ""
grade_match = SIGNAL_GRADE_RE.search(message or "")
score_match = SIGNAL_SCORE_RE.search(message or "")
grade = grade_match.group(1) if grade_match else None
score: Optional[float] = None
if score_match:
try:
score = float(score_match.group(1))
except ValueError:
score = None
if latest_state is not None:
if grade is None:
grade = latest_state.get("grade")
if score is None and latest_state.get("score") is not None:
score = latest_state.get("score")
return {
"time": timestamp,
"side": side,
"grade": grade or "Unknown",
"score": score,
"filled": False,
"reject_reason": None,
"reject_detail": "",
"line": source_line,
}
def parse_full_session_kpis(path: Optional[Path]) -> Dict[str, Any]:
"""Parses full-session dashboard KPIs from a session_*.log file.
This is intentionally read-only observability. It never writes to NT8, never
touches strategy state, and cannot affect live trading behavior.
"""
empty = {
"session_reject_totals": {},
"signal_outcomes": [],
"signal_grade_summary": [],
"missed_grade_b_plus_count": 0,
"missed_grade_b_plus_samples": [],
}
if path is None or not path.exists():
return empty
try:
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
return empty
reject_summary_final: Dict[str, int] = {}
reject_record_counts: Dict[str, int] = {}
signal_outcomes: List[Dict[str, Any]] = []
latest_state: Optional[Dict[str, Any]] = None
current_signal: Optional[Dict[str, Any]] = None
active_blocking_reason: Optional[str] = None
missed_samples: List[Dict[str, Any]] = []
missed_count = 0
for line in lines:
timestamp, message = split_log_line(line)
state = STATE_RE.search(message)
if state:
latest_state = {
"timestamp": timestamp,
"regime": state.group(1),
"direction": state.group(2),
"direction_source": state.group(3),
"score": float(state.group(4)),
"grade": state.group(5),
}
if active_blocking_reason and is_grade_b_or_better(latest_state.get("grade")):
missed_count += 1
missed_samples.append({
"timestamp": timestamp,
"grade": latest_state.get("grade"),
"score": latest_state.get("score"),
"blocking_reason": active_blocking_reason,
})
missed_samples = missed_samples[-20:]
continue
reject_summary = REJECT_SUMMARY_RE.search(message)
if reject_summary:
parts = parse_key_values(reject_summary.group(1))
reason = parts.get("reason")
if reason:
try:
reject_summary_final[reason] = int(parts.get("count", "0"))
except ValueError:
reject_summary_final[reason] = 0
continue
reject = REJECT_RE.search(message)
if reject:
parts = parse_key_values(reject.group(1))
reason = parts.get("reason")
if reason:
reject_record_counts[reason] = reject_record_counts.get(reason, 0) + 1
if reason in BLOCKING_REJECT_REASONS:
active_blocking_reason = reason
if current_signal is not None and not current_signal.get("filled") and not current_signal.get("reject_reason"):
current_signal["reject_reason"] = reason
current_signal["reject_detail"] = parts.get("detail", "")
continue
parsed_signal = parse_signal_line(message, timestamp, line, latest_state)
if parsed_signal is not None:
signal_outcomes.append(parsed_signal)
current_signal = parsed_signal
continue
if FILL_RE.search(message):
if current_signal is not None and not current_signal.get("filled"):
current_signal["filled"] = True
continue
totals = dict(reject_summary_final)
for reason, count in reject_record_counts.items():
if reason not in totals:
totals[reason] = count
grade_summary: Dict[str, Dict[str, Any]] = {}
for outcome in signal_outcomes:
grade = str(outcome.get("grade") or "Unknown")
if grade not in grade_summary:
grade_summary[grade] = {"grade": grade, "generated": 0, "filled": 0, "rejected": 0, "reject_reasons": {}}
summary = grade_summary[grade]
summary["generated"] += 1
if outcome.get("filled"):
summary["filled"] += 1
if outcome.get("reject_reason"):
summary["rejected"] += 1
reason = str(outcome.get("reject_reason"))
summary["reject_reasons"][reason] = summary["reject_reasons"].get(reason, 0) + 1
sorted_grade_summary = sorted(grade_summary.values(), key=lambda item: (-grade_rank(item.get("grade")), str(item.get("grade"))))
return {
"session_reject_totals": {reason: totals[reason] for reason in sorted(totals.keys(), key=str.lower)},
"signal_outcomes": signal_outcomes,
"signal_grade_summary": sorted_grade_summary,
"missed_grade_b_plus_count": missed_count,
"missed_grade_b_plus_samples": missed_samples,
}
def parse_readiness(lines: List[str]) -> Dict[str, Any]:
data_series: Dict[int, Dict[str, Any]] = {}
factors: Dict[str, Dict[str, Any]] = {}

View File

@@ -81,6 +81,11 @@ class DashboardRuntime:
self.readiness: Dict[str, Any] = {}
self.rows: List[Dict[str, Any]] = []
self.diagnostics: List[Dict[str, Any]] = []
self.session_reject_totals: Dict[str, int] = {}
self.signal_outcomes: List[Dict[str, Any]] = []
self.signal_grade_summary: List[Dict[str, Any]] = []
self.missed_grade_b_plus_count = 0
self.missed_grade_b_plus_samples: List[Dict[str, Any]] = []
self.current_session_file: Optional[str] = None
self.current_session_date: Optional[str] = None
self.polling = config.get("polling", {}) if isinstance(config.get("polling", {}), dict) else {}
@@ -108,6 +113,11 @@ class DashboardRuntime:
"readiness": dict(self.readiness),
"rows": list(self.rows),
"diagnostics": list(self.diagnostics),
"session_reject_totals": dict(self.session_reject_totals),
"signal_outcomes": list(self.signal_outcomes),
"signal_grade_summary": list(self.signal_grade_summary),
"missed_grade_b_plus_count": self.missed_grade_b_plus_count,
"missed_grade_b_plus_samples": list(self.missed_grade_b_plus_samples),
"events": list(self.latest_events[-100:]),
"trades": list(self.trades),
"provenance": self.provenance,
@@ -145,7 +155,8 @@ class DashboardRuntime:
self.current_session_date = session_date
self.readiness = parsers.parse_readiness(raw_tail)
self._refresh_live_state_from_tail(path, raw_tail)
self.rows, self.diagnostics = self._build_current_rows(path, raw_tail)
self.rows, self.diagnostics = self._build_current_rows(path)
self._refresh_session_kpis(path)
offset = self.state.get_offset(path)
if offset is None:
try:
@@ -170,6 +181,14 @@ class DashboardRuntime:
if event is not None:
self._apply_event(event)
def _refresh_session_kpis(self, path: Path) -> None:
kpis = parsers.parse_full_session_kpis(path)
self.session_reject_totals = kpis.get("session_reject_totals", {})
self.signal_outcomes = kpis.get("signal_outcomes", [])
self.signal_grade_summary = kpis.get("signal_grade_summary", [])
self.missed_grade_b_plus_count = int(kpis.get("missed_grade_b_plus_count") or 0)
self.missed_grade_b_plus_samples = kpis.get("missed_grade_b_plus_samples", [])
def _poll_trades(self) -> None:
date_key = self.current_session_date or time.strftime("%Y%m%d")
path = parsers.trades_file_for_date(self.log_dir, date_key)
@@ -183,7 +202,7 @@ class DashboardRuntime:
return name[8:16]
return time.strftime("%Y%m%d")
def _build_current_rows(self, path: Path, lines: List[str]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
def _build_current_rows(self, path: Path) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
if logtriage is None:
return [], []
try:
@@ -195,10 +214,6 @@ class DashboardRuntime:
rows = logtriage.build_rows([session], settings_by_date, provenance_by_date, trades_by_session)
diagnostics = logtriage.build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects)
row_dicts = [row.to_dict() for row in rows]
if row_dicts:
reject_summaries, reject_records = self._parse_rejections(lines, session.date)
row_dicts[0]["reject_summaries"] = reject_summaries
row_dicts[0]["reject_records"] = reject_records
return row_dicts, diagnostics
except Exception as ex:
return [], [{"date": time.strftime("%Y-%m-%d"), "code": "LIVE ROW BUILD FAILED", "message": str(ex)}]
@@ -229,36 +244,6 @@ class DashboardRuntime:
snapshots.append(snapshot)
return {date: snapshots} if snapshots else {}
def _parse_rejections(self, lines: List[str], date: str) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
summaries: List[Dict[str, Any]] = []
records: List[Dict[str, Any]] = []
for line in lines:
timestamp, message = parsers.split_log_line(line)
if message.startswith("REJECT SUMMARY:"):
parts = self._parse_key_values(message.replace("REJECT SUMMARY:", "", 1))
summaries.append({"date": date, "reason": parts.get("reason"), "count": int(parts.get("count", "0") or 0), "line": line})
elif message.startswith("REJECT:"):
parts = self._parse_key_values(message.replace("REJECT:", "", 1))
records.append({"date": date, "reason": parts.get("reason"), "detail": parts.get("detail"), "bar": parts.get("bar"), "line": line})
return summaries, records
def _parse_key_values(self, text: str) -> Dict[str, str]:
values: Dict[str, str] = {}
keys = ["reason", "detail", "bar", "count"]
for index, key in enumerate(keys):
marker = key + "="
start = text.find(marker)
if start < 0:
continue
value_start = start + len(marker)
value_end = len(text)
for later_key in keys[index + 1:]:
later = text.find(" " + later_key + "=", value_start)
if later >= 0:
value_end = min(value_end, later)
values[key] = text[value_start:value_end].strip()
return values
def _poll_provenance(self) -> None:
provenance_path = parsers.latest_provenance_file(self.log_dir)
settings_path = parsers.latest_settings_file(self.log_dir)
@@ -285,6 +270,14 @@ class DashboardRuntime:
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 == "STATE":
self.live_state["state_telemetry"] = event
elif event_type == "STATE_DETAIL":
self.live_state["state_telemetry_reasons"] = event.get("reasons", {})
elif event_type == "SIGNAL_DETAIL":
self.live_state["last_signal_reasons"] = event.get("reasons", {})
elif event_type == "STATE_CONTEXT":
self.live_state["state_context"] = event.get("fields", {})
elif event_type == "ACCOUNT":
self.live_state["account"] = event.get("account")
elif event_type == "SYMBOL":

View File

@@ -28,6 +28,18 @@ Text mode prints:
`--json` emits machine-readable output for dashboard ingestion, including session rows, diagnostics, and per-trade records enriched with source file and line metadata.
### REJECT / REJECT SUMMARY parsing
Each session row now also includes:
- `reject_summaries`: every `REJECT SUMMARY: reason=<Reason> count=<count>` line encountered, in file order, as `{date, reason, count, line}`. Because GAP-035 writes these as periodic cumulative snapshots (first live rejection at/after 10:00 ET, then every 15 bar-minutes, plus a final snapshot at session end), this is a history of counts over the session, not a single tally.
- `reject_records`: every `REJECT: reason=<Reason> detail=<Detail> bar=<time>` line, as `{date, reason, detail, bar, line}`. GAP-035 logs at most one of these per unique reason per session.
- `reject_summary_final`: the last observed count per reason, i.e. `{reason: count}` derived from `reject_summaries` — this is the number to cite for "how many times did X block a trade this session."
The `SILENT DAY` diagnostic now includes a `Rejections: <reason>=<count>, ...` breakdown in its message (and a machine-readable `reject_totals` field) whenever `reject_summary_final` data is available for the day, so a silent day is self-explanatory instead of just flagged.
Parsing uses `parse_key_values()`, which bounds each value by the next known key marker (`reason=`, `detail=`, `bar=`, `count=`) rather than splitting on whitespace or `=`, since `detail` text can itself contain `=` (e.g. the `GradeFilter` factor breakdown `Factors=<factor>=<score>x<weight>;...`). This is the canonical parser; `tools/dashboard/server.py` no longer keeps its own copy.
## Usage
Run against the default NT8 SDK log directory:

View File

@@ -44,6 +44,34 @@ 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")
REJECT_KEYS: Tuple[str, ...] = ("reason", "detail", "bar", "count")
def parse_key_values(text: str, keys: Sequence[str] = REJECT_KEYS) -> Dict[str, str]:
"""Extract key=value pairs from REJECT/REJECT SUMMARY payload text.
Values may contain spaces or even '=' characters of their own (e.g. the
GradeFilter detail's Factors=<factor>=<score>x<weight>;... breakdown),
so each value is bounded by the next known key marker rather than by
whitespace or a naive split on '='. This is the canonical parser for
these line formats; tools/dashboard/server.py delegates to it instead
of keeping its own copy.
"""
values: Dict[str, str] = {}
for index, key in enumerate(keys):
marker = key + "="
start = text.find(marker)
if start < 0:
continue
value_start = start + len(marker)
value_end = len(text)
for later_key in keys[index + 1:]:
later = text.find(" " + later_key + "=", value_start)
if later >= 0:
value_end = min(value_end, later)
values[key] = text[value_start:value_end].strip()
return values
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Summarize NT8 SDK session artifacts.")
@@ -136,6 +164,9 @@ class SessionSummary:
settings_captured: bool = False
session_id: Optional[str] = None
source_files: Dict[str, str] = field(default_factory=dict)
reject_summaries: List[Dict[str, Any]] = field(default_factory=list)
reject_records: List[Dict[str, Any]] = field(default_factory=list)
reject_summary_final: Dict[str, int] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return {
@@ -162,6 +193,9 @@ class SessionSummary:
"session_id": self.session_id,
"timestamp": self.timestamp.isoformat(),
"source_files": self.source_files,
"reject_summaries": self.reject_summaries,
"reject_records": self.reject_records,
"reject_summary_final": self.reject_summary_final,
}
@@ -294,6 +328,35 @@ def parse_session_file(path: Path) -> SessionSummary:
if "FILL " in line:
summary.fills += 1
if "REJECT SUMMARY:" in line:
parts = parse_key_values(line.split("REJECT SUMMARY:", 1)[1])
reason = parts.get("reason")
if reason:
count_text = parts.get("count")
count_value = 0
if count_text is not None:
try:
count_value = int(count_text)
except ValueError:
count_value = 0
summary.reject_summaries.append(
{"date": summary.date, "reason": reason, "count": count_value, "line": line}
)
summary.reject_summary_final[reason] = count_value
elif "REJECT:" in line:
parts = parse_key_values(line.split("REJECT:", 1)[1])
reason = parts.get("reason")
if reason:
summary.reject_records.append(
{
"date": summary.date,
"reason": reason,
"detail": parts.get("detail", ""),
"bar": parts.get("bar"),
"line": line,
}
)
pnl_match = PNL_RE.search(line)
if pnl_match:
summary.net_pnl = parse_float(pnl_match.group(1))
@@ -541,12 +604,24 @@ def build_diagnostics(
if session_rows:
day_activity = sum(row.signals + row.submits + row.fills for row in session_rows)
if day_activity == 0:
reject_totals: Dict[str, int] = {}
for row in session_rows:
for reason, count in row.reject_summary_final.items():
reject_totals[reason] = max(reject_totals.get(reason, 0), count)
message = "SESSION START present with zero SIGNAL/SUBMIT/FILL lines for the day."
if reject_totals:
breakdown = ", ".join(
"{0}={1}".format(reason, count)
for reason, count in sorted(reject_totals.items(), key=lambda item: -item[1])
)
message += " Rejections: " + breakdown
diagnostics.append(
{
"date": date,
"code": "SILENT DAY",
"message": "SESSION START present with zero SIGNAL/SUBMIT/FILL lines for the day.",
"message": message,
"sessions": [row.path.name for row in session_rows],
"reject_totals": reject_totals,
}
)

Binary file not shown.

Binary file not shown.

View File

@@ -187,9 +187,9 @@ def is_runner_leg(row: Dict[str, str]) -> bool:
if value:
values.append(value)
text = " ".join(values).lower()
if "scaler" in text or "scale" in text:
if "scaler" in text or "scale" in text or "_s_" in text:
return False
return "runner" in text or "run" in text
return "runner" in text or "run" in text or "_r_" in text
def classify_exit(row: Dict[str, str], pnl: float) -> str: