tools: add DASH-001 TOOL-001 TOOL-002 TOOL-003 and RUNNER-001 utilities

This commit is contained in:
2026-08-16 16:59:18 -04:00
parent 83d25cb2cd
commit 0a2106a7a6
24 changed files with 5440 additions and 0 deletions

166
tools/dashboard/README.md Normal file
View File

@@ -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.

746
tools/dashboard/app.js Normal file
View File

@@ -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: '<span class="pill good">traded</span>' };
}
if (status === "violation") {
return { html: '<span class="pill bad">config violation</span>' };
}
return { html: '<span class="pill warn">silent</span>' };
}
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 = "<strong>" + date + "</strong><span>" + classifySilentDate(data, date).replace(/-/g, " ") + "</span>";
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 = '<span class="reason-label">' + display(item.reason) + '</span><div class="bar-track"><div class="bar-fill" style="width:' + Math.max(3, Math.round((numberValue(item.count) / max) * 100)) + '%"></div></div><span class="reason-count">' + display(item.count) + '</span>';
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 = "<span>" + count + "</span>";
chart.appendChild(bar);
});
var threshold = document.createElement("div");
threshold.className = "threshold-line";
threshold.style.left = Math.round(GRADE_A_THRESHOLD * 100) + "%";
threshold.innerHTML = '<span>Grade A / 0.80</span>';
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: '<span class="pill bad">' + drift.join(" + ") + '</span>' } : { html: '<span class="pill good">stable</span>' }];
});
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");
}());

View File

@@ -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]
}
}

198
tools/dashboard/index.html Normal file
View File

@@ -0,0 +1,198 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NT8 SDK Read-Only Dashboard</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="app-header">
<div>
<p class="eyebrow">NT8 SDK</p>
<h1>Decision Or Defect?</h1>
<p class="subhead">Headline dashboard for deciding whether a silent session was intentional strategy filtering or an operational defect.</p>
</div>
<div class="status-card">
<span class="status-label">Mode</span>
<strong>Static HTML + vanilla JS</strong>
<span>No NT8 references. No writes.</span>
</div>
</header>
<main>
<section class="panel input-panel" aria-labelledby="input-title">
<div>
<h2 id="input-title">Load TOOL-001 JSON</h2>
<p>Generate with <code>python tools/logtriage/logtriage.py --json &gt; triage.json</code>, then select that file here. The file stays local in the browser.</p>
</div>
<div class="input-actions">
<label class="file-button">
Select triage.json
<input id="json-file" type="file" accept="application/json,.json">
</label>
<button id="load-sample" type="button">Load Empty Shell</button>
</div>
<textarea id="json-paste" placeholder="Optional: paste TOOL-001 JSON here, then click Load Pasted JSON."></textarea>
<button id="load-pasted" type="button">Load Pasted JSON</button>
<p id="load-message" class="load-message" role="status">No JSON loaded.</p>
</section>
<section class="panel" aria-labelledby="live-title">
<div class="section-title">
<div>
<h2 id="live-title">Live Local Server</h2>
<p id="server-status" class="panel-note">Open through `server.py` to enable live polling from read-only log files.</p>
</div>
<button id="load-server" type="button">Load Server State</button>
</div>
<div class="metrics-grid">
<article class="metric-card">
<span>Connection</span>
<strong id="live-connection">-</strong>
<small>From newest session log</small>
</article>
<article class="metric-card">
<span>Daily P&L</span>
<strong id="live-pnl">-</strong>
<small>Latest PNL_UPDATE</small>
</article>
<article class="metric-card">
<span>Position</span>
<strong id="live-position">-</strong>
<small>Latest PNL_UPDATE</small>
</article>
<article class="metric-card">
<span>Notifications</span>
<strong id="live-notify">-</strong>
<small>Apprise status</small>
</article>
</div>
<pre id="raw-tail" class="raw-tail"></pre>
</section>
<section class="panel headline-panel" aria-labelledby="headline-title">
<div class="section-title">
<div>
<p class="eyebrow">Headline View</p>
<h2 id="headline-title">Was Silence A Decision Or A Defect?</h2>
</div>
<p id="contract-message" class="panel-note">Load TOOL-001 JSON to classify silent sessions.</p>
</div>
<div class="metrics-grid decision-grid" aria-label="Decision defect summary">
<article class="metric-card decision-card">
<span>Silent By Decision</span>
<strong id="metric-decision-silent">0</strong>
<small>Primarily GradeFilter or MaxDailyTrades</small>
</article>
<article class="metric-card defect-card">
<span>Silent By Defect</span>
<strong id="metric-defect-silent">0</strong>
<small>ORB/RTH/warmup/config defects</small>
</article>
<article class="metric-card unknown-card">
<span>Silent Unknown</span>
<strong id="metric-unknown-silent">0</strong>
<small>No reject summary available</small>
</article>
<article class="metric-card">
<span>Threshold</span>
<strong>0.80</strong>
<small>MinTradeGrade=5 / Grade A</small>
</article>
</div>
<div id="health-strip" class="health-strip" aria-label="Session health strip"></div>
</section>
<section class="panel" aria-labelledby="silent-title">
<div class="section-title">
<div>
<h2 id="silent-title">Silent Day Explorer</h2>
<p class="panel-note">Zero-SIGNAL sessions grouped by date. Decision reasons and defect reasons are color-coded.</p>
</div>
<div class="legend">
<span><i class="dot decision"></i>Decision</span>
<span><i class="dot defect"></i>Defect</span>
<span><i class="dot unknown"></i>Unknown</span>
</div>
</div>
<div id="silent-explorer" class="silent-explorer"></div>
</section>
<section class="split-grid">
<article class="panel" aria-labelledby="grade-title">
<h2 id="grade-title">Grade Distribution</h2>
<p class="panel-note">Histogram of computed confluence scores. The vertical marker is the Grade A threshold at 0.80.</p>
<div id="grade-histogram" class="histogram"></div>
</article>
<article class="panel" aria-labelledby="factor-title">
<h2 id="factor-title">Factor Breakdown</h2>
<p class="panel-note">For GradeFilter rejections, identifies which factors most often drag the composite under threshold.</p>
<div class="table-wrap"><table id="factor-table"></table></div>
</article>
</section>
<section class="metrics-grid" aria-label="Gate progress">
<article class="metric-card">
<span>Trades Banked</span>
<strong id="metric-trades">0 / 20</strong>
<div class="progress-track"><div id="trade-progress" class="progress-fill"></div></div>
</article>
<article class="metric-card">
<span>Days Elapsed</span>
<strong id="metric-days">0</strong>
<small>Unique session dates</small>
</article>
<article class="metric-card">
<span>Current Streak</span>
<strong id="metric-streak">0</strong>
<small>Consecutive traded sessions</small>
</article>
<article class="metric-card">
<span>Diagnostics</span>
<strong id="metric-diagnostics">0</strong>
<small>TOOL-001 findings</small>
</article>
</section>
<section class="panel" aria-labelledby="timeline-title">
<div class="section-title">
<h2 id="timeline-title">Daily Timeline</h2>
<div class="legend">
<span><i class="dot traded"></i>Traded</span>
<span><i class="dot silent"></i>Silent</span>
<span><i class="dot violation"></i>Config violation</span>
</div>
</div>
<div class="table-wrap"><table id="timeline-table"></table></div>
</section>
<section class="panel" aria-labelledby="trade-title">
<div class="section-title">
<h2 id="trade-title">Trade Detail</h2>
<p>Grade, score, entry/exit, and scaler/runner attribution are shown when present in TOOL-001 trade records.</p>
</div>
<div class="table-wrap"><table id="trade-table"></table></div>
</section>
<section class="split-grid">
<article class="panel" aria-labelledby="provenance-title">
<h2 id="provenance-title">Provenance Health</h2>
<p class="panel-note">Counts sentinel/default values per field across trade records.</p>
<div class="table-wrap"><table id="provenance-table"></table></div>
</article>
<article class="panel" aria-labelledby="config-title">
<h2 id="config-title">Config Integrity</h2>
<p class="panel-note">ConfigHash and CodeVersion timeline with drift markers.</p>
<div class="table-wrap"><table id="config-table"></table></div>
</article>
</section>
</main>
<template id="empty-row">
<tr><td class="empty" colspan="99">No data loaded.</td></tr>
</template>
<script src="app.js"></script>
</body>
</html>

52
tools/dashboard/notify.py Normal file
View File

@@ -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),
}

220
tools/dashboard/parsers.py Normal file
View File

@@ -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

View File

@@ -0,0 +1 @@
apprise>=1.8.0

327
tools/dashboard/server.py Normal file
View File

@@ -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())

87
tools/dashboard/state.py Normal file
View File

@@ -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)

392
tools/dashboard/styles.css Normal file
View File

@@ -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; }
}