772 lines
27 KiB
Python
772 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Standalone NT8 SDK log triage utility.
|
|
|
|
Reads session logs, settings exports, provenance snapshots, and trade JSONL files
|
|
from the NT8 SDK log directory and emits a per-day summary table plus diagnostics.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar
|
|
|
|
|
|
DEFAULT_INPUT_DIR = r"%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk"
|
|
FILENAME_TIMESTAMP_FORMAT = "%Y%m%d_%H%M%S"
|
|
|
|
|
|
SESSION_FILE_RE = re.compile(r"^session_(\d{8})_(\d{6})\.log$", re.IGNORECASE)
|
|
SETTINGS_FILE_RE = re.compile(r"^settings_.+_(\d{8})_(\d{6})\.txt$", re.IGNORECASE)
|
|
PROVENANCE_FILE_RE = re.compile(r"^provenance_.+_(\d{8})_(\d{6})\.json$", re.IGNORECASE)
|
|
TRADES_FILE_RE = re.compile(r"^trades_.+_(\d{8})\.jsonl$", re.IGNORECASE)
|
|
|
|
ACCOUNT_RE = re.compile(r"Account\s*:\s*(.+)$")
|
|
SYMBOL_RE = re.compile(r"Symbol\s*:\s*(.+)$")
|
|
VERBOSE_RE = re.compile(r"VerboseLog\s*:\s*(True|False)\s+FileLog:\s*(True|False)", re.IGNORECASE)
|
|
DATA_SERIES_RE = re.compile(
|
|
r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=(\d+)\s+HistoricalBarsLoaded=(\d+)",
|
|
re.IGNORECASE,
|
|
)
|
|
FACTOR_WARMUP_RE = re.compile(
|
|
r"FactorWarmup\s*:\s*NarrowRangeFactorCalculator=(SATISFIED|NOT SATISFIED)\s+\((\d+)/7 daily bars\)\s+"
|
|
r"OrbRangeVsAtrFactorCalculator=(SATISFIED|NOT SATISFIED)",
|
|
re.IGNORECASE,
|
|
)
|
|
PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=\$?(-?[\d,]+(?:\.\d+)?)", re.IGNORECASE)
|
|
TEST_MODE_RE = re.compile(r"\|\s*<(TEST MODE ACTIVE|LIVE MODE)>", re.IGNORECASE)
|
|
KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$")
|
|
T = TypeVar("T")
|
|
|
|
|
|
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description="Summarize NT8 SDK session artifacts.")
|
|
parser.add_argument(
|
|
"input_dir",
|
|
nargs="?",
|
|
default=DEFAULT_INPUT_DIR,
|
|
help="Directory containing session_*.log, settings_*.txt, provenance_*.json, and trades_*.jsonl",
|
|
)
|
|
parser.add_argument(
|
|
"--json",
|
|
action="store_true",
|
|
help="Emit machine-readable JSON instead of a text table.",
|
|
)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def expand_input_dir(raw_path: str) -> Path:
|
|
expanded = os.path.expanduser(os.path.expandvars(raw_path))
|
|
return Path(expanded)
|
|
|
|
|
|
def parse_bool(value: Any) -> Optional[bool]:
|
|
if isinstance(value, bool):
|
|
return value
|
|
if value is None:
|
|
return None
|
|
text = str(value).strip().lower()
|
|
if text == "true":
|
|
return True
|
|
if text == "false":
|
|
return False
|
|
return None
|
|
|
|
|
|
def parse_float(value: Any) -> Optional[float]:
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, (float, int)):
|
|
return float(value)
|
|
text = str(value).strip().replace("$", "").replace(",", "")
|
|
if not text:
|
|
return None
|
|
try:
|
|
return float(text)
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def parse_timestamp_from_match(match: re.Match[str]) -> datetime:
|
|
return datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), FILENAME_TIMESTAMP_FORMAT)
|
|
|
|
|
|
def safe_json_load(path: Path) -> Optional[Any]:
|
|
try:
|
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return None
|
|
|
|
|
|
def read_lines(path: Path) -> List[str]:
|
|
try:
|
|
return path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
except OSError:
|
|
return []
|
|
|
|
|
|
@dataclass
|
|
class SessionSummary:
|
|
path: Path
|
|
timestamp: datetime
|
|
date: str
|
|
account: Optional[str] = None
|
|
instrument: Optional[str] = None
|
|
session_bar_type: Optional[str] = None
|
|
bar_type: Optional[str] = None
|
|
days_to_load: Optional[int] = None
|
|
daily_bars: Optional[int] = None
|
|
warmup_ok: Optional[bool] = None
|
|
signals: int = 0
|
|
submits: int = 0
|
|
fills: int = 0
|
|
net_pnl: Optional[float] = None
|
|
kill_switch: Optional[bool] = None
|
|
verbose_log: Optional[bool] = None
|
|
config_hash: Optional[str] = None
|
|
code_version: Optional[str] = None
|
|
test_mode: Optional[bool] = None
|
|
session_start: bool = False
|
|
settings_captured: bool = False
|
|
session_id: Optional[str] = None
|
|
source_files: Dict[str, str] = field(default_factory=dict)
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"date": self.date,
|
|
"account": self.account,
|
|
"instrument": self.instrument,
|
|
"bar_type": self.bar_type,
|
|
"session_bar_type": self.session_bar_type,
|
|
"days_to_load": self.days_to_load,
|
|
"daily_bars": self.daily_bars,
|
|
"warmup_ok": self.warmup_ok,
|
|
"signals": self.signals,
|
|
"submits": self.submits,
|
|
"fills": self.fills,
|
|
"net_pnl": self.net_pnl,
|
|
"kill_switch": self.kill_switch,
|
|
"verbose_log": self.verbose_log,
|
|
"config_hash": self.config_hash,
|
|
"config_hash_8": short_hash(self.config_hash),
|
|
"code_version": self.code_version,
|
|
"test_mode": self.test_mode,
|
|
"session_start": self.session_start,
|
|
"settings_captured": self.settings_captured,
|
|
"session_id": self.session_id,
|
|
"timestamp": self.timestamp.isoformat(),
|
|
"source_files": self.source_files,
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class SettingsSnapshot:
|
|
path: Path
|
|
timestamp: datetime
|
|
date: str
|
|
account: Optional[str] = None
|
|
instrument: Optional[str] = None
|
|
bars_period: Optional[str] = None
|
|
enable_kill_switch: Optional[bool] = None
|
|
enable_verbose_logging: Optional[bool] = None
|
|
test_mode: Optional[bool] = None
|
|
config_hash: Optional[str] = None
|
|
code_version: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class ProvenanceSnapshot:
|
|
path: Path
|
|
timestamp: datetime
|
|
date: str
|
|
session_id: Optional[str] = None
|
|
config_hash: Optional[str] = None
|
|
code_version: Optional[str] = None
|
|
test_mode: Optional[bool] = None
|
|
|
|
|
|
@dataclass
|
|
class TradeAggregate:
|
|
path: Path
|
|
date: str
|
|
session_id: Optional[str]
|
|
submits: int = 0
|
|
records: List[Dict[str, Any]] = field(default_factory=list)
|
|
provenance_defects: List[Dict[str, Any]] = field(default_factory=list)
|
|
|
|
|
|
def short_hash(value: Optional[str]) -> Optional[str]:
|
|
if not value:
|
|
return None
|
|
return value[:8]
|
|
|
|
|
|
def format_bool(value: Optional[bool]) -> str:
|
|
if value is True:
|
|
return "True"
|
|
if value is False:
|
|
return "False"
|
|
return "?"
|
|
|
|
|
|
def format_text(value: Optional[Any]) -> str:
|
|
if value is None:
|
|
return "?"
|
|
text = str(value).strip()
|
|
return text if text else "?"
|
|
|
|
|
|
def format_pnl(value: Optional[float]) -> str:
|
|
if value is None:
|
|
return "?"
|
|
return "{0:.2f}".format(value)
|
|
|
|
|
|
def parse_session_file(path: Path) -> SessionSummary:
|
|
match = SESSION_FILE_RE.match(path.name)
|
|
if not match:
|
|
raise ValueError("Invalid session file name: {0}".format(path.name))
|
|
|
|
timestamp = parse_timestamp_from_match(match)
|
|
summary = SessionSummary(
|
|
path=path,
|
|
timestamp=timestamp,
|
|
date=timestamp.strftime("%Y-%m-%d"),
|
|
source_files={"session": path.name},
|
|
)
|
|
|
|
for line in read_lines(path):
|
|
if "=== SESSION START" in line:
|
|
summary.session_start = True
|
|
|
|
account_match = ACCOUNT_RE.search(line)
|
|
if account_match:
|
|
summary.account = account_match.group(1).strip()
|
|
|
|
symbol_match = SYMBOL_RE.search(line)
|
|
if symbol_match:
|
|
summary.instrument = symbol_match.group(1).strip()
|
|
|
|
verbose_match = VERBOSE_RE.search(line)
|
|
if verbose_match:
|
|
summary.verbose_log = parse_bool(verbose_match.group(1))
|
|
|
|
data_series_match = DATA_SERIES_RE.search(line)
|
|
if data_series_match:
|
|
index = int(data_series_match.group(1))
|
|
bar_type = data_series_match.group(2).strip()
|
|
days_to_load = int(data_series_match.group(3))
|
|
loaded_bars = int(data_series_match.group(4))
|
|
|
|
if index == 0:
|
|
summary.session_bar_type = bar_type
|
|
if summary.bar_type is None:
|
|
summary.bar_type = bar_type
|
|
summary.days_to_load = days_to_load
|
|
|
|
if "daybarstype" in bar_type.lower():
|
|
summary.daily_bars = loaded_bars
|
|
|
|
factor_match = FACTOR_WARMUP_RE.search(line)
|
|
if factor_match:
|
|
summary.warmup_ok = (
|
|
factor_match.group(1).upper() == "SATISFIED"
|
|
and factor_match.group(3).upper() == "SATISFIED"
|
|
)
|
|
if summary.daily_bars is None:
|
|
summary.daily_bars = int(factor_match.group(2))
|
|
|
|
if "WARNING: EnableKillSwitch=False" in line:
|
|
summary.kill_switch = False
|
|
|
|
if "SIGNAL:" in line:
|
|
summary.signals += 1
|
|
|
|
if "SUBMIT " in line:
|
|
summary.submits += 1
|
|
|
|
if "FILL " in line:
|
|
summary.fills += 1
|
|
|
|
pnl_match = PNL_RE.search(line)
|
|
if pnl_match:
|
|
summary.net_pnl = parse_float(pnl_match.group(1))
|
|
|
|
test_mode_match = TEST_MODE_RE.search(line)
|
|
if test_mode_match:
|
|
summary.test_mode = test_mode_match.group(1).upper() == "TEST MODE ACTIVE"
|
|
|
|
return summary
|
|
|
|
|
|
def parse_settings_file(path: Path) -> SettingsSnapshot:
|
|
match = SETTINGS_FILE_RE.match(path.name)
|
|
if not match:
|
|
raise ValueError("Invalid settings file name: {0}".format(path.name))
|
|
|
|
timestamp = parse_timestamp_from_match(match)
|
|
snapshot = SettingsSnapshot(path=path, timestamp=timestamp, date=timestamp.strftime("%Y-%m-%d"))
|
|
|
|
for raw_line in read_lines(path):
|
|
key_match = KEY_VALUE_RE.match(raw_line)
|
|
if not key_match:
|
|
continue
|
|
|
|
key = key_match.group(1).strip()
|
|
value = key_match.group(2).strip()
|
|
|
|
if key == "Account":
|
|
snapshot.account = value
|
|
elif key == "Instrument":
|
|
snapshot.instrument = value
|
|
elif key == "BarsPeriod":
|
|
snapshot.bars_period = value
|
|
elif key == "EnableKillSwitch":
|
|
snapshot.enable_kill_switch = parse_bool(value)
|
|
elif key == "EnableVerboseLogging":
|
|
snapshot.enable_verbose_logging = parse_bool(value)
|
|
elif key == "TestMode":
|
|
snapshot.test_mode = parse_bool(value)
|
|
elif key == "ConfigHash":
|
|
snapshot.config_hash = value
|
|
elif key == "CodeVersion":
|
|
snapshot.code_version = value
|
|
|
|
return snapshot
|
|
|
|
|
|
def parse_provenance_file(path: Path) -> Optional[ProvenanceSnapshot]:
|
|
match = PROVENANCE_FILE_RE.match(path.name)
|
|
if not match:
|
|
raise ValueError("Invalid provenance file name: {0}".format(path.name))
|
|
|
|
payload = safe_json_load(path)
|
|
if not isinstance(payload, dict):
|
|
return None
|
|
|
|
timestamp = parse_timestamp_from_match(match)
|
|
banner = str(payload.get("test_mode_banner", "")).strip().upper()
|
|
test_mode: Optional[bool] = None
|
|
if banner == "<TEST MODE ACTIVE>":
|
|
test_mode = True
|
|
elif banner == "<LIVE MODE>":
|
|
test_mode = False
|
|
|
|
return ProvenanceSnapshot(
|
|
path=path,
|
|
timestamp=timestamp,
|
|
date=timestamp.strftime("%Y-%m-%d"),
|
|
session_id=payload.get("session_id"),
|
|
config_hash=payload.get("config_hash"),
|
|
code_version=payload.get("code_version"),
|
|
test_mode=test_mode,
|
|
)
|
|
|
|
|
|
def parse_trade_files(paths: Sequence[Path]) -> Tuple[Dict[Tuple[str, Optional[str]], TradeAggregate], List[Dict[str, Any]]]:
|
|
aggregates: Dict[Tuple[str, Optional[str]], TradeAggregate] = {}
|
|
defects: List[Dict[str, Any]] = []
|
|
|
|
for path in paths:
|
|
match = TRADES_FILE_RE.match(path.name)
|
|
if not match:
|
|
continue
|
|
|
|
date = datetime.strptime(match.group(1), "%Y%m%d").strftime("%Y-%m-%d")
|
|
for line_number, raw_line in enumerate(read_lines(path), start=1):
|
|
text = raw_line.strip()
|
|
if not text:
|
|
continue
|
|
|
|
try:
|
|
row = json.loads(text)
|
|
except ValueError:
|
|
defects.append(
|
|
{
|
|
"date": date,
|
|
"code": "PROVENANCE DEFECT",
|
|
"message": "Invalid JSON in trade file {0}:{1}".format(path.name, line_number),
|
|
"path": path.name,
|
|
"line": line_number,
|
|
}
|
|
)
|
|
continue
|
|
|
|
session_id = row.get("session_id")
|
|
key = (date, session_id)
|
|
aggregate = aggregates.get(key)
|
|
if aggregate is None:
|
|
aggregate = TradeAggregate(path=path, date=date, session_id=session_id)
|
|
aggregates[key] = aggregate
|
|
aggregate.submits += 1
|
|
record = dict(row)
|
|
record["date"] = date
|
|
record["path"] = path.name
|
|
record["line"] = line_number
|
|
aggregate.records.append(record)
|
|
|
|
defect_fields: List[str] = []
|
|
if str(row.get("confluence_grade", "")).strip() == "Unknown":
|
|
defect_fields.append("confluence_grade=Unknown")
|
|
if parse_float(row.get("confluence_score")) == 0.0:
|
|
defect_fields.append("confluence_score=0.0")
|
|
if str(row.get("risk_mode", "")).strip() == "Unknown":
|
|
defect_fields.append("risk_mode=Unknown")
|
|
if parse_float(row.get("OrbRangeTicks")) == 0.0:
|
|
defect_fields.append("OrbRangeTicks=0.0")
|
|
|
|
if defect_fields:
|
|
defect = {
|
|
"date": date,
|
|
"code": "PROVENANCE DEFECT",
|
|
"message": ", ".join(defect_fields),
|
|
"path": path.name,
|
|
"line": line_number,
|
|
"session_id": session_id,
|
|
"trade_seq": row.get("trade_seq"),
|
|
}
|
|
aggregate.provenance_defects.append(defect)
|
|
defects.append(defect)
|
|
|
|
return aggregates, defects
|
|
|
|
|
|
def nearest_same_day(items: Sequence[T], target: datetime, get_timestamp: Callable[[T], datetime]) -> Optional[T]:
|
|
best_item: Optional[T] = None
|
|
best_delta: Optional[float] = None
|
|
for item in items:
|
|
delta = abs((get_timestamp(item) - target).total_seconds())
|
|
if best_delta is None or delta < best_delta:
|
|
best_item = item
|
|
best_delta = delta
|
|
return best_item
|
|
|
|
|
|
def build_rows(
|
|
sessions: Sequence[SessionSummary],
|
|
settings_by_date: Dict[str, List[SettingsSnapshot]],
|
|
provenance_by_date: Dict[str, List[ProvenanceSnapshot]],
|
|
trades_by_session: Dict[Tuple[str, Optional[str]], TradeAggregate],
|
|
) -> List[SessionSummary]:
|
|
rows: List[SessionSummary] = []
|
|
|
|
for session in sorted(sessions, key=lambda item: item.timestamp):
|
|
settings = nearest_same_day(settings_by_date.get(session.date, []), session.timestamp, lambda item: item.timestamp)
|
|
provenance = nearest_same_day(provenance_by_date.get(session.date, []), session.timestamp, lambda item: item.timestamp)
|
|
|
|
if settings is not None:
|
|
session.settings_captured = True
|
|
session.source_files["settings"] = settings.path.name
|
|
if session.account is None:
|
|
session.account = settings.account
|
|
if session.instrument is None:
|
|
session.instrument = settings.instrument
|
|
if settings.bars_period:
|
|
session.bar_type = settings.bars_period
|
|
if settings.enable_kill_switch is not None:
|
|
session.kill_switch = settings.enable_kill_switch
|
|
if settings.enable_verbose_logging is not None:
|
|
session.verbose_log = settings.enable_verbose_logging
|
|
if settings.test_mode is not None:
|
|
session.test_mode = settings.test_mode
|
|
if settings.config_hash:
|
|
session.config_hash = settings.config_hash
|
|
if settings.code_version:
|
|
session.code_version = settings.code_version
|
|
|
|
if provenance is not None:
|
|
session.source_files["provenance"] = provenance.path.name
|
|
session.session_id = provenance.session_id
|
|
if provenance.config_hash and not session.config_hash:
|
|
session.config_hash = provenance.config_hash
|
|
if provenance.code_version and not session.code_version:
|
|
session.code_version = provenance.code_version
|
|
if provenance.test_mode is not None and session.test_mode is None:
|
|
session.test_mode = provenance.test_mode
|
|
|
|
if session.session_id is not None:
|
|
trade_aggregate = trades_by_session.get((session.date, session.session_id))
|
|
if trade_aggregate is not None:
|
|
session.source_files["trades"] = trade_aggregate.path.name
|
|
if trade_aggregate.submits > session.submits:
|
|
session.submits = trade_aggregate.submits
|
|
|
|
rows.append(session)
|
|
|
|
return rows
|
|
|
|
|
|
def build_diagnostics(
|
|
rows: Sequence[SessionSummary],
|
|
settings_by_date: Dict[str, List[SettingsSnapshot]],
|
|
provenance_by_date: Dict[str, List[ProvenanceSnapshot]],
|
|
trade_defects: Sequence[Dict[str, Any]],
|
|
) -> List[Dict[str, Any]]:
|
|
diagnostics: List[Dict[str, Any]] = []
|
|
rows_by_date: Dict[str, List[SessionSummary]] = {}
|
|
for row in rows:
|
|
rows_by_date.setdefault(row.date, []).append(row)
|
|
|
|
all_dates = set(rows_by_date.keys())
|
|
all_dates.update(settings_by_date.keys())
|
|
all_dates.update(provenance_by_date.keys())
|
|
dates = sorted(all_dates)
|
|
previous_hashes: Optional[Tuple[str, Tuple[str, ...]]] = None
|
|
|
|
for date in dates:
|
|
day_rows = rows_by_date.get(date, [])
|
|
day_settings = settings_by_date.get(date, [])
|
|
day_provenance = provenance_by_date.get(date, [])
|
|
accounts = sorted(
|
|
{row.account for row in day_rows if row.account}.union(
|
|
{item.account for item in day_settings if item.account}
|
|
)
|
|
)
|
|
config_hashes = sorted(
|
|
{row.config_hash for row in day_rows if row.config_hash}.union(
|
|
{item.config_hash for item in day_settings if item.config_hash}
|
|
).union(
|
|
{item.config_hash for item in day_provenance if item.config_hash}
|
|
)
|
|
)
|
|
session_rows = [row for row in day_rows if row.session_start]
|
|
bar_types = sorted({row.session_bar_type or row.bar_type for row in day_rows if row.session_bar_type or row.bar_type})
|
|
|
|
if session_rows:
|
|
day_activity = sum(row.signals + row.submits + row.fills for row in session_rows)
|
|
if day_activity == 0:
|
|
diagnostics.append(
|
|
{
|
|
"date": date,
|
|
"code": "SILENT DAY",
|
|
"message": "SESSION START present with zero SIGNAL/SUBMIT/FILL lines for the day.",
|
|
"sessions": [row.path.name for row in session_rows],
|
|
}
|
|
)
|
|
|
|
if len(accounts) > 1 or len(config_hashes) > 1 or len(bar_types) > 1:
|
|
diagnostics.append(
|
|
{
|
|
"date": date,
|
|
"code": "PARALLEL INSTANCE",
|
|
"message": "Multiple accounts, config hashes, or primary bar types observed on the same day.",
|
|
"accounts": accounts,
|
|
"config_hashes": config_hashes,
|
|
"bar_types": bar_types,
|
|
}
|
|
)
|
|
|
|
if session_rows and not settings_by_date.get(date):
|
|
diagnostics.append(
|
|
{
|
|
"date": date,
|
|
"code": "NO CONFIG CAPTURE",
|
|
"message": "Session log exists but no settings_*.txt was found for the day.",
|
|
}
|
|
)
|
|
|
|
for row in day_rows:
|
|
if row.kill_switch is False or row.verbose_log is False:
|
|
details: List[str] = []
|
|
if row.kill_switch is False:
|
|
details.append("EnableKillSwitch=False")
|
|
if row.verbose_log is False:
|
|
details.append("VerboseLog=False")
|
|
diagnostics.append(
|
|
{
|
|
"date": date,
|
|
"code": "GATE CONFIG VIOLATION",
|
|
"message": ", ".join(details),
|
|
"session": row.path.name,
|
|
}
|
|
)
|
|
|
|
hash_tuple = tuple(config_hashes)
|
|
if hash_tuple:
|
|
if previous_hashes is not None and previous_hashes[1] != hash_tuple:
|
|
diagnostics.append(
|
|
{
|
|
"date": date,
|
|
"code": "CONFIG DRIFT",
|
|
"message": "ConfigHash set changed from previous observed day.",
|
|
"previous_date": previous_hashes[0],
|
|
"previous_config_hashes": list(previous_hashes[1]),
|
|
"current_config_hashes": list(hash_tuple),
|
|
}
|
|
)
|
|
previous_hashes = (date, hash_tuple)
|
|
|
|
diagnostics.extend(sorted(trade_defects, key=lambda item: (item.get("date", ""), item.get("path", ""), item.get("line", 0))))
|
|
|
|
return diagnostics
|
|
|
|
|
|
def row_table_values(row: SessionSummary) -> List[str]:
|
|
return [
|
|
row.date,
|
|
format_text(row.account),
|
|
format_text(row.instrument),
|
|
format_text(row.bar_type),
|
|
format_text(row.days_to_load),
|
|
format_text(row.daily_bars),
|
|
format_bool(row.warmup_ok),
|
|
str(row.signals),
|
|
str(row.submits),
|
|
str(row.fills),
|
|
format_pnl(row.net_pnl),
|
|
format_bool(row.kill_switch),
|
|
format_bool(row.verbose_log),
|
|
format_text(short_hash(row.config_hash)),
|
|
format_bool(row.test_mode),
|
|
]
|
|
|
|
|
|
def render_table(rows: Sequence[SessionSummary]) -> str:
|
|
headers = [
|
|
"Date",
|
|
"Account",
|
|
"Instrument",
|
|
"BarType",
|
|
"DaysToLoad",
|
|
"DailyBars",
|
|
"WarmupOK",
|
|
"Signals",
|
|
"Submits",
|
|
"Fills",
|
|
"NetPnL",
|
|
"KillSwitch",
|
|
"VerboseLog",
|
|
"ConfigHash(8)",
|
|
"TestMode",
|
|
]
|
|
|
|
lines: List[List[str]] = [headers]
|
|
for row in rows:
|
|
lines.append(row_table_values(row))
|
|
|
|
widths = [0] * len(headers)
|
|
for line in lines:
|
|
for index, value in enumerate(line):
|
|
widths[index] = max(widths[index], len(value))
|
|
|
|
rendered: List[str] = []
|
|
for line_index, line in enumerate(lines):
|
|
rendered.append(" | ".join(value.ljust(widths[index]) for index, value in enumerate(line)))
|
|
if line_index == 0:
|
|
rendered.append("-+-".join("-" * widths[index] for index in range(len(widths))))
|
|
|
|
return "\n".join(rendered)
|
|
|
|
|
|
def render_diagnostics(diagnostics: Sequence[Dict[str, Any]]) -> str:
|
|
if not diagnostics:
|
|
return "DIAGNOSTICS\nNone"
|
|
|
|
lines = ["DIAGNOSTICS"]
|
|
for item in diagnostics:
|
|
lines.append("[{0}] {1}: {2}".format(item.get("date", "?"), item.get("code", "?"), item.get("message", "")))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def collect_inputs(input_dir: Path) -> Tuple[List[SessionSummary], Dict[str, List[SettingsSnapshot]], Dict[str, List[ProvenanceSnapshot]], Dict[Tuple[str, Optional[str]], TradeAggregate], List[Dict[str, Any]]]:
|
|
sessions: List[SessionSummary] = []
|
|
settings_by_date: Dict[str, List[SettingsSnapshot]] = {}
|
|
provenance_by_date: Dict[str, List[ProvenanceSnapshot]] = {}
|
|
|
|
trade_paths: List[Path] = []
|
|
|
|
for path in sorted(input_dir.rglob("*")):
|
|
if not path.is_file():
|
|
continue
|
|
|
|
if SESSION_FILE_RE.match(path.name):
|
|
sessions.append(parse_session_file(path))
|
|
continue
|
|
|
|
if SETTINGS_FILE_RE.match(path.name):
|
|
snapshot = parse_settings_file(path)
|
|
settings_by_date.setdefault(snapshot.date, []).append(snapshot)
|
|
continue
|
|
|
|
if PROVENANCE_FILE_RE.match(path.name):
|
|
snapshot = parse_provenance_file(path)
|
|
if snapshot is not None:
|
|
provenance_by_date.setdefault(snapshot.date, []).append(snapshot)
|
|
continue
|
|
|
|
if TRADES_FILE_RE.match(path.name):
|
|
trade_paths.append(path)
|
|
|
|
trades_by_session, trade_defects = parse_trade_files(trade_paths)
|
|
return sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects
|
|
|
|
|
|
def build_output(input_dir: Path) -> Dict[str, Any]:
|
|
sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects = collect_inputs(input_dir)
|
|
rows = build_rows(sessions, settings_by_date, provenance_by_date, trades_by_session)
|
|
diagnostics = build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects)
|
|
trade_records: List[Dict[str, Any]] = []
|
|
for key in sorted(trades_by_session.keys(), key=lambda item: (item[0], item[1] or "")):
|
|
trade_records.extend(trades_by_session[key].records)
|
|
|
|
return {
|
|
"tool": "logtriage",
|
|
"implementation": {
|
|
"language": "Python",
|
|
"reason": "Standalone script avoids any NT8 assembly reference, solution change, or deployed output impact.",
|
|
},
|
|
"source_dir": str(input_dir),
|
|
"generated_at_utc": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"rows": [row.to_dict() for row in rows],
|
|
"trade_records": trade_records,
|
|
"diagnostics": diagnostics,
|
|
}
|
|
|
|
|
|
def main(argv: Sequence[str]) -> int:
|
|
args = parse_args(argv)
|
|
input_dir = expand_input_dir(args.input_dir)
|
|
|
|
if not input_dir.exists() or not input_dir.is_dir():
|
|
sys.stderr.write("Input directory not found: {0}\n".format(input_dir))
|
|
return 1
|
|
|
|
sessions, settings_by_date, provenance_by_date, trades_by_session, trade_defects = collect_inputs(input_dir)
|
|
rows = build_rows(sessions, settings_by_date, provenance_by_date, trades_by_session)
|
|
diagnostics = build_diagnostics(rows, settings_by_date, provenance_by_date, trade_defects)
|
|
trade_records: List[Dict[str, Any]] = []
|
|
for key in sorted(trades_by_session.keys(), key=lambda item: (item[0], item[1] or "")):
|
|
trade_records.extend(trades_by_session[key].records)
|
|
|
|
output = {
|
|
"tool": "logtriage",
|
|
"implementation": {
|
|
"language": "Python",
|
|
"reason": "Standalone script avoids any NT8 assembly reference, solution change, or deployed output impact.",
|
|
},
|
|
"source_dir": str(input_dir),
|
|
"generated_at_utc": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"rows": [row.to_dict() for row in rows],
|
|
"trade_records": trade_records,
|
|
"diagnostics": diagnostics,
|
|
}
|
|
|
|
if args.json:
|
|
json.dump(output, sys.stdout, indent=2)
|
|
sys.stdout.write("\n")
|
|
return 0
|
|
|
|
sys.stdout.write(render_table(rows) + "\n\n")
|
|
sys.stdout.write(render_diagnostics(diagnostics) + "\n")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|