279 lines
8.9 KiB
Python
279 lines
8.9 KiB
Python
#!/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:]))
|