tools: add DASH-001 TOOL-001 TOOL-002 TOOL-003 and RUNNER-001 utilities
This commit is contained in:
66
tools/configdiff/README.md
Normal file
66
tools/configdiff/README.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# configdiff
|
||||
|
||||
`configdiff` is a standalone Python CLI that parses `settings_Simple_ORB_NT8_*.txt` exports and reports configuration drift without referencing any NinjaTrader assembly.
|
||||
|
||||
Python was chosen instead of a .NET console app so the tool stays fully outside `NT8-SDK.sln`, adds no NT8 dependency surface, and cannot affect deployed NT8 output.
|
||||
|
||||
## What It Reports
|
||||
|
||||
- A matrix of every parsed settings parameter across every export in scope
|
||||
- Highlighted changed values using `*value*`
|
||||
- Explicit callouts when `ConfigHash` is identical but parameters still differ
|
||||
This independently catches the known DEC-20260810-01 BarsPeriod/hash defect before GAP-038 lands.
|
||||
- Exit code `1` when drift is detected inside a declared gate window
|
||||
|
||||
## Inputs
|
||||
|
||||
The tool scans a directory for:
|
||||
|
||||
- `settings_Simple_ORB_NT8_*.txt`
|
||||
|
||||
Default directory:
|
||||
|
||||
`%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk`
|
||||
|
||||
## Usage
|
||||
|
||||
Run across all matching exports:
|
||||
|
||||
```powershell
|
||||
python tools/configdiff/configdiff.py
|
||||
```
|
||||
|
||||
Run against a specific archive directory:
|
||||
|
||||
```powershell
|
||||
python tools/configdiff/configdiff.py "C:\logs\nt8-sdk-archive"
|
||||
```
|
||||
|
||||
Check only a gate window starting on a specific date:
|
||||
|
||||
```powershell
|
||||
python tools/configdiff/configdiff.py --gate-start 2026-08-07
|
||||
```
|
||||
|
||||
Use the exit code in automation:
|
||||
|
||||
```powershell
|
||||
python tools/configdiff/configdiff.py --gate-start 2026-08-07
|
||||
if ($LASTEXITCODE -eq 1) { "Drift detected inside gate window" }
|
||||
```
|
||||
|
||||
## Drift Semantics
|
||||
|
||||
- Drift is evaluated on configuration-bearing fields parsed from the settings export.
|
||||
- Volatile runtime fields are excluded from drift detection:
|
||||
- `ExportTime`
|
||||
- `ConfigHash`
|
||||
- `CodeVersion`
|
||||
- `PortfolioStatus`
|
||||
- The matrix still shows every parsed field so the full export remains visible.
|
||||
|
||||
## Notes
|
||||
|
||||
- The tool is read-only.
|
||||
- It does not import or reference any NinjaTrader or NT8 SDK assembly.
|
||||
- When `ConfigHash` matches but parameters differ, the report calls that out explicitly instead of trusting the hash.
|
||||
278
tools/configdiff/configdiff.py
Normal file
278
tools/configdiff/configdiff.py
Normal file
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Standalone NT8 SDK settings drift detector."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, date
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
DEFAULT_INPUT_DIR = r"%USERPROFILE%\Documents\NinjaTrader 8\log\nt8-sdk"
|
||||
SETTINGS_FILE_RE = re.compile(r"^settings_Simple_ORB_NT8_(\d{8})_(\d{6})\.txt$", re.IGNORECASE)
|
||||
KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$")
|
||||
|
||||
NON_DRIFT_FIELDS = set([
|
||||
"ExportTime",
|
||||
"ConfigHash",
|
||||
"CodeVersion",
|
||||
"PortfolioStatus",
|
||||
])
|
||||
|
||||
|
||||
@dataclass
|
||||
class SettingsExport:
|
||||
path: Path
|
||||
timestamp: datetime
|
||||
label: str
|
||||
config_hash: Optional[str]
|
||||
values: Dict[str, str]
|
||||
|
||||
|
||||
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Detect drift across settings_Simple_ORB_NT8_*.txt exports.")
|
||||
parser.add_argument(
|
||||
"input_dir",
|
||||
nargs="?",
|
||||
default=DEFAULT_INPUT_DIR,
|
||||
help="Directory containing settings_Simple_ORB_NT8_*.txt exports",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--gate-start",
|
||||
dest="gate_start",
|
||||
help="Scope the check to exports on or after YYYY-MM-DD; exit code becomes 1 when drift is detected in that gate window.",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def expand_input_dir(raw_path: str) -> Path:
|
||||
return Path(os.path.expanduser(os.path.expandvars(raw_path)))
|
||||
|
||||
|
||||
def read_lines(path: Path) -> List[str]:
|
||||
try:
|
||||
return path.read_text(encoding="utf-8", errors="replace").splitlines()
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def parse_gate_start(raw_value: Optional[str]) -> Optional[date]:
|
||||
if not raw_value:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(raw_value, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
raise ValueError("Invalid --gate-start value: {0}. Expected YYYY-MM-DD.".format(raw_value))
|
||||
|
||||
|
||||
def parse_settings_file(path: Path) -> SettingsExport:
|
||||
match = SETTINGS_FILE_RE.match(path.name)
|
||||
if not match:
|
||||
raise ValueError("Invalid settings export name: {0}".format(path.name))
|
||||
|
||||
timestamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
|
||||
values: Dict[str, str] = {}
|
||||
|
||||
for line in read_lines(path):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("===") or stripped.startswith("---"):
|
||||
continue
|
||||
|
||||
key_match = KEY_VALUE_RE.match(line)
|
||||
if not key_match:
|
||||
continue
|
||||
|
||||
key = key_match.group(1).strip()
|
||||
value = key_match.group(2).strip()
|
||||
values[key] = value
|
||||
|
||||
return SettingsExport(
|
||||
path=path,
|
||||
timestamp=timestamp,
|
||||
label=timestamp.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
config_hash=values.get("ConfigHash"),
|
||||
values=values,
|
||||
)
|
||||
|
||||
|
||||
def collect_exports(input_dir: Path) -> List[SettingsExport]:
|
||||
exports: List[SettingsExport] = []
|
||||
for path in sorted(input_dir.rglob("*")):
|
||||
if path.is_file() and SETTINGS_FILE_RE.match(path.name):
|
||||
exports.append(parse_settings_file(path))
|
||||
exports.sort(key=lambda item: item.timestamp)
|
||||
return exports
|
||||
|
||||
|
||||
def filter_exports(exports: Sequence[SettingsExport], gate_start: Optional[date]) -> List[SettingsExport]:
|
||||
if gate_start is None:
|
||||
return list(exports)
|
||||
return [item for item in exports if item.timestamp.date() >= gate_start]
|
||||
|
||||
|
||||
def get_matrix_parameters(exports: Sequence[SettingsExport]) -> List[str]:
|
||||
names = set()
|
||||
for export in exports:
|
||||
names.update(export.values.keys())
|
||||
return sorted(names)
|
||||
|
||||
|
||||
def get_drift_parameters(exports: Sequence[SettingsExport]) -> List[str]:
|
||||
params: List[str] = []
|
||||
for name in get_matrix_parameters(exports):
|
||||
if name in NON_DRIFT_FIELDS:
|
||||
continue
|
||||
distinct = set()
|
||||
for export in exports:
|
||||
distinct.add(export.values.get(name, "(missing)"))
|
||||
if len(distinct) > 1:
|
||||
params.append(name)
|
||||
return params
|
||||
|
||||
|
||||
def get_hash_collision_defects(exports: Sequence[SettingsExport]) -> List[Dict[str, object]]:
|
||||
groups: Dict[str, List[SettingsExport]] = {}
|
||||
defects: List[Dict[str, object]] = []
|
||||
|
||||
for export in exports:
|
||||
if export.config_hash:
|
||||
groups.setdefault(export.config_hash, []).append(export)
|
||||
|
||||
for config_hash in sorted(groups.keys()):
|
||||
group = groups[config_hash]
|
||||
if len(group) < 2:
|
||||
continue
|
||||
|
||||
changed_params: List[str] = []
|
||||
for name in get_matrix_parameters(group):
|
||||
if name in NON_DRIFT_FIELDS:
|
||||
continue
|
||||
distinct = set()
|
||||
for export in group:
|
||||
distinct.add(export.values.get(name, "(missing)"))
|
||||
if len(distinct) > 1:
|
||||
changed_params.append(name)
|
||||
|
||||
if changed_params:
|
||||
defects.append(
|
||||
{
|
||||
"config_hash": config_hash,
|
||||
"exports": group,
|
||||
"parameters": changed_params,
|
||||
}
|
||||
)
|
||||
|
||||
return defects
|
||||
|
||||
|
||||
def format_value(value: Optional[str], changed: bool) -> str:
|
||||
text = value if value is not None and value != "" else "(missing)"
|
||||
if changed:
|
||||
return "*{0}*".format(text)
|
||||
return text
|
||||
|
||||
|
||||
def render_matrix(exports: Sequence[SettingsExport]) -> str:
|
||||
if not exports:
|
||||
return "MATRIX\nNo matching settings exports found."
|
||||
|
||||
headers = ["Parameter", "Changed"] + [export.label for export in exports]
|
||||
rows: List[List[str]] = [headers]
|
||||
|
||||
drift_params = set(get_drift_parameters(exports))
|
||||
for name in get_matrix_parameters(exports):
|
||||
changed = name in drift_params
|
||||
row = [name, "YES" if changed else "no"]
|
||||
for export in exports:
|
||||
row.append(format_value(export.values.get(name), changed))
|
||||
rows.append(row)
|
||||
|
||||
widths = [0] * len(headers)
|
||||
for row in rows:
|
||||
for index, value in enumerate(row):
|
||||
if len(value) > widths[index]:
|
||||
widths[index] = len(value)
|
||||
|
||||
rendered: List[str] = ["MATRIX"]
|
||||
for row_index, row in enumerate(rows):
|
||||
rendered.append(" | ".join(row[index].ljust(widths[index]) for index in range(len(headers))))
|
||||
if row_index == 0:
|
||||
rendered.append("-+-".join("-" * widths[index] for index in range(len(headers))))
|
||||
return "\n".join(rendered)
|
||||
|
||||
|
||||
def render_summary(input_dir: Path, exports: Sequence[SettingsExport], scoped_exports: Sequence[SettingsExport], gate_start: Optional[date]) -> Tuple[str, bool]:
|
||||
drift_params = get_drift_parameters(scoped_exports)
|
||||
defects = get_hash_collision_defects(scoped_exports)
|
||||
drift_detected = len(drift_params) > 0
|
||||
|
||||
lines: List[str] = []
|
||||
lines.append("SCOPE")
|
||||
lines.append("Input directory: {0}".format(input_dir))
|
||||
lines.append("Matched exports: {0}".format(len(exports)))
|
||||
if gate_start is None:
|
||||
lines.append("Scope: all matched exports")
|
||||
else:
|
||||
lines.append("Scope: exports on or after {0} ({1} export(s))".format(gate_start.isoformat(), len(scoped_exports)))
|
||||
lines.append("")
|
||||
lines.append("DRIFT SUMMARY")
|
||||
lines.append("Drift detected: {0}".format("YES" if drift_detected else "no"))
|
||||
if drift_params:
|
||||
lines.append("Changed parameters: {0}".format(", ".join(drift_params)))
|
||||
else:
|
||||
lines.append("Changed parameters: none")
|
||||
|
||||
lines.append("")
|
||||
lines.append("HASH DEFECT CHECK")
|
||||
if defects:
|
||||
for defect in defects:
|
||||
lines.append(
|
||||
"IDENTICAL ConfigHash with differing parameters: {0}".format(defect["config_hash"])
|
||||
)
|
||||
lines.append("Differing parameters: {0}".format(", ".join(defect["parameters"])))
|
||||
for export in defect["exports"]:
|
||||
values: List[str] = []
|
||||
for name in defect["parameters"]:
|
||||
values.append("{0}={1}".format(name, export.values.get(name, "(missing)")))
|
||||
lines.append(" - {0} [{1}] {2}".format(export.label, export.path.name, "; ".join(values)))
|
||||
else:
|
||||
lines.append("No identical-hash parameter divergence detected.")
|
||||
|
||||
return "\n".join(lines), drift_detected
|
||||
|
||||
|
||||
def main(argv: Sequence[str]) -> int:
|
||||
args = parse_args(argv)
|
||||
|
||||
try:
|
||||
gate_start = parse_gate_start(args.gate_start)
|
||||
except ValueError as ex:
|
||||
sys.stderr.write(str(ex) + "\n")
|
||||
return 2
|
||||
|
||||
input_dir = expand_input_dir(args.input_dir)
|
||||
if not input_dir.exists() or not input_dir.is_dir():
|
||||
sys.stderr.write("Input directory not found: {0}\n".format(input_dir))
|
||||
return 2
|
||||
|
||||
exports = collect_exports(input_dir)
|
||||
scoped_exports = filter_exports(exports, gate_start)
|
||||
|
||||
summary, drift_detected = render_summary(input_dir, exports, scoped_exports, gate_start)
|
||||
matrix = render_matrix(scoped_exports)
|
||||
|
||||
sys.stdout.write(summary + "\n\n")
|
||||
sys.stdout.write(matrix + "\n")
|
||||
|
||||
if gate_start is not None and drift_detected:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Reference in New Issue
Block a user