747 lines
27 KiB
JavaScript
747 lines
27 KiB
JavaScript
(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");
|
|
}());
|