- governance: stage v7.0 review prompts, run book, roadmap/current-status/decision updates, and sprint board state - adapters: capture DASH/trailing-drawdown/state-telemetry strategy work already present in the worktree - tools: capture dashboard console/KPI parser updates, logtriage notes, and runnersweep output Build: previously clean | Tests: previously 511 passing | Includes all open staged files
673 lines
25 KiB
Python
673 lines
25 KiB
Python
"""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)
|
|
SIGNAL_RE = re.compile(r"\bSIGNAL:?\s+(Buy|Sell|Long|Short)\b(?:\s+([^|]+?))?(?:\s*\|\s*(.*))?$", re.IGNORECASE)
|
|
SIGNAL_GRADE_RE = re.compile(r"\bGrade=([^\s|]+)", re.IGNORECASE)
|
|
SIGNAL_SCORE_RE = re.compile(r"\bScore=([0-9.]+)", re.IGNORECASE)
|
|
REJECT_RE = re.compile(r"\bREJECT:\s*(.*)$", re.IGNORECASE)
|
|
REJECT_SUMMARY_RE = re.compile(r"\bREJECT SUMMARY:\s*(.*)$", 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)
|
|
CONNECTION_STATE_RE = re.compile(r"^ConnectionLost\s*:\s*(True|False)$", re.IGNORECASE)
|
|
PNL_RE = re.compile(r"PNL_UPDATE\s+DayPnL=([^\s]+)\s+Position=([^\s]+)\s+Qty=(\d+)", re.IGNORECASE)
|
|
ACCOUNT_RE = re.compile(r"^Account\s*:\s*(.+)$", re.IGNORECASE)
|
|
SYMBOL_RE = re.compile(r"^Symbol\s*:\s*(.+)$", re.IGNORECASE)
|
|
MODE_RE = re.compile(r"^Mode\s*:\s*(.+)$", re.IGNORECASE)
|
|
DATA_SERIES_RE = re.compile(r"DataSeries\[(\d+)\]\s*:\s*Type=([^\s]+)\s+DaysToLoad=([^\s]+)\s+HistoricalBarsLoaded=([^\s]+)", re.IGNORECASE)
|
|
FACTOR_WARMUP_RE = re.compile(r"FactorWarmup\s*:\s*(.*)$", re.IGNORECASE)
|
|
FACTOR_STATUS_RE = re.compile(r"([A-Za-z0-9_]+)=(SATISFIED|FAILED|UNSATISFIED)\s*\((\d+)/(\d+)\s+daily bars\)", re.IGNORECASE)
|
|
STATE_RE = re.compile(
|
|
r"STATE:\s*Regime=(\S+)\s+Direction=(\S+)\s+DirectionSource=(\S+)\s+Score=([0-9.]+)\s+Grade=(\S+)\s+Factors=(.*)$",
|
|
re.IGNORECASE,
|
|
)
|
|
STATE_FACTOR_ENTRY_RE = re.compile(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$")
|
|
STATE_DETAIL_RE = re.compile(r"\bSTATE_DETAIL:\s*(.*)$", re.IGNORECASE)
|
|
SIGNAL_DETAIL_RE = re.compile(r"\bSIGNAL_DETAIL:\s*(.*)$", re.IGNORECASE)
|
|
QUOTED_KV_RE = re.compile(r'(\w+)="((?:[^"\\]|\\.)*)"')
|
|
SUBMIT_FIELD_RE = re.compile(
|
|
r"\b(Scaler|Runner|Stop|Target|Mode|BaseTarget|DynamicTarget|GradeMult|ModeMult|CombinedMult)=(\S+)",
|
|
re.IGNORECASE,
|
|
)
|
|
SUBMIT_NUMERIC_FIELDS = ("BaseTarget", "DynamicTarget", "GradeMult", "ModeMult", "CombinedMult")
|
|
STATE_CONTEXT_RE = re.compile(r"\bSTATE_CONTEXT:\s*(.*)$", re.IGNORECASE)
|
|
STATE_CONTEXT_FIELD_RE = re.compile(r"(\w+)=(\S+)")
|
|
REJECT_KV_RE = re.compile(r"\b(reason|detail|bar|count)=", re.IGNORECASE)
|
|
BLOCKING_REJECT_REASONS = set(["RthGuard", "MaxDailyTrades", "KillSwitch", "CmeHoliday"])
|
|
|
|
|
|
def parse_key_values(text: str) -> Dict[str, str]:
|
|
"""Parses marker-bounded key=value text for REJECT lines.
|
|
|
|
Values such as detail=... may contain spaces or additional '=' tokens, so
|
|
this uses known key markers as boundaries rather than splitting on spaces.
|
|
"""
|
|
result: Dict[str, str] = {}
|
|
matches = list(REJECT_KV_RE.finditer(text or ""))
|
|
for index, match in enumerate(matches):
|
|
key = match.group(1)
|
|
value_start = match.end()
|
|
value_end = matches[index + 1].start() if index + 1 < len(matches) else len(text or "")
|
|
result[key] = (text or "")[value_start:value_end].strip()
|
|
return result
|
|
|
|
|
|
def grade_rank(grade: Any) -> int:
|
|
text = str(grade or "").upper().strip()
|
|
if text == "A+":
|
|
return 6
|
|
if text == "A":
|
|
return 5
|
|
if text == "B":
|
|
return 4
|
|
if text == "C":
|
|
return 3
|
|
if text == "D":
|
|
return 2
|
|
if text == "F":
|
|
return 1
|
|
return 0
|
|
|
|
|
|
def is_grade_b_or_better(grade: Any) -> bool:
|
|
return grade_rank(grade) >= grade_rank("B")
|
|
|
|
|
|
def parse_state_context_fields(text: str) -> Dict[str, str]:
|
|
"""Parses STATE_CONTEXT: unquoted Key=Value tokens (DEC-20260818-02/03).
|
|
|
|
Unlike STATE_DETAIL:/SIGNAL_DETAIL:, these values are plain tokens
|
|
(numbers, HH:mm times, booleans) with no internal spaces or quoting, so
|
|
a simple space/= split is sufficient. The field set is deliberately
|
|
generic — GetStateTelemetryContextFields() is an extension point any
|
|
strategy can override with its own keys (e.g. SimpleORBNT8's OrbHigh/
|
|
OrbLow/OrbWindowStart/OrbWindowEnd/OrbReady), plus the universal
|
|
RecommendedContracts field NT8StrategyBase always appends when present.
|
|
"""
|
|
fields: Dict[str, str] = {}
|
|
for key, value in STATE_CONTEXT_FIELD_RE.findall(text or ""):
|
|
fields[key] = value
|
|
return fields
|
|
|
|
|
|
def parse_quoted_reasons(text: str) -> Dict[str, str]:
|
|
"""Parses STATE_DETAIL:/SIGNAL_DETAIL: quoted key="value" pairs (DEC-20260817-09).
|
|
|
|
Reverses NT8StrategyBase.cs's EscapeLogValue() (\\ -> \\\\, " -> \\") with a
|
|
single backslash-escaped-char substitution, which correctly handles both
|
|
escape sequences in one pass since the original escaping only ever emits
|
|
a backslash followed by exactly one of those two characters.
|
|
"""
|
|
result: Dict[str, str] = {}
|
|
for key, raw_value in QUOTED_KV_RE.findall(text or ""):
|
|
result[key] = re.sub(r"\\(.)", r"\1", raw_value)
|
|
return result
|
|
|
|
|
|
def parse_submit_fields(detail: str) -> Dict[str, Any]:
|
|
"""Parses SUBMIT line fields, including the DEC-20260817-09 sizing-rationale
|
|
fields appended after Mode=. Numeric fields are coerced to float where
|
|
parseable; GetMetadataText() emits "N/A" for missing intent.Metadata keys,
|
|
which is left as a string so the dashboard can render it distinctly from 0.
|
|
"""
|
|
fields: Dict[str, Any] = {}
|
|
for key, value in SUBMIT_FIELD_RE.findall(detail or ""):
|
|
if key in SUBMIT_NUMERIC_FIELDS and value != "N/A":
|
|
try:
|
|
fields[key] = float(value)
|
|
continue
|
|
except ValueError:
|
|
pass
|
|
fields[key] = value
|
|
return fields
|
|
|
|
|
|
def parse_state_factors(text: str) -> List[Dict[str, Any]]:
|
|
"""Parses the DASH-002 STATE: line's Factors=name=scorexweight;... segment.
|
|
|
|
Same convention as the GradeFilter reject-detail factor breakdown
|
|
(app.js's parseFactors()), reused here for consistency rather than
|
|
inventing a second format.
|
|
"""
|
|
factors: List[Dict[str, Any]] = []
|
|
if not text:
|
|
return factors
|
|
for part in text.split(";"):
|
|
part = part.strip()
|
|
if not part:
|
|
continue
|
|
match = STATE_FACTOR_ENTRY_RE.match(part)
|
|
if match:
|
|
factors.append({
|
|
"name": match.group(1),
|
|
"score": float(match.group(2)),
|
|
"weight": float(match.group(3)) if match.group(3) else 1.0,
|
|
})
|
|
return factors
|
|
|
|
|
|
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[float, str, Path]] = None
|
|
for path in log_dir.glob("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
|
|
try:
|
|
mtime = path.stat().st_mtime
|
|
except OSError:
|
|
continue
|
|
if newest is None or (mtime, path.name) > (newest[0], newest[1]):
|
|
newest = (mtime, path.name, path)
|
|
return newest[2] if newest else None
|
|
|
|
|
|
def session_key(path: Path, lines: List[str]) -> str:
|
|
for line in lines:
|
|
timestamp, message = split_log_line(line)
|
|
start = SESSION_START_RE.search(message)
|
|
if start:
|
|
return start.group(1)
|
|
return path.stem
|
|
|
|
|
|
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")
|
|
return trades_file_for_date(log_dir, today)
|
|
|
|
|
|
def trades_file_for_date(log_dir: Path, yyyymmdd: str) -> Optional[Path]:
|
|
candidates = sorted(path for path in log_dir.glob("trades_Simple_ORB_NT8_{0}.jsonl".format(yyyymmdd)) if path.is_file()) if log_dir.exists() else []
|
|
return candidates[-1] if candidates else None
|
|
|
|
|
|
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_state_telemetry_detail(detail: str) -> Dict[str, Any]:
|
|
result: Dict[str, Any] = {"detail": detail}
|
|
factors_match = re.search(r"Factors=([^\n]+)$", detail or "", re.IGNORECASE)
|
|
if factors_match:
|
|
result["factors"] = parse_factor_breakdown(factors_match.group(1))
|
|
detail = detail[:factors_match.start()].strip()
|
|
for match in re.finditer(r"(Regime|Direction|DirectionSource|Score|Grade)=([^\s]+)", detail or "", re.IGNORECASE):
|
|
key = match.group(1).lower()
|
|
value = match.group(2)
|
|
if key == "score":
|
|
try:
|
|
result[key] = float(value)
|
|
except ValueError:
|
|
result[key] = value
|
|
else:
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def parse_factor_breakdown(text: str) -> List[Dict[str, Any]]:
|
|
factors: List[Dict[str, Any]] = []
|
|
for part in (text or "").split(";"):
|
|
match = re.match(r"^([^=]+)=([0-9.]+)(?:x([0-9.]+))?$", part.strip(), re.IGNORECASE)
|
|
if match is None:
|
|
continue
|
|
try:
|
|
score = float(match.group(2))
|
|
except ValueError:
|
|
score = 0.0
|
|
try:
|
|
weight = float(match.group(3)) if match.group(3) else 1.0
|
|
except ValueError:
|
|
weight = 1.0
|
|
factors.append({"name": match.group(1), "score": score, "weight": weight})
|
|
return factors
|
|
|
|
|
|
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
|
|
|
|
state = STATE_RE.search(message)
|
|
if state:
|
|
payload = dict(base)
|
|
payload.update({
|
|
"type": "STATE",
|
|
"regime": state.group(1),
|
|
"direction": state.group(2),
|
|
"direction_source": state.group(3),
|
|
"score": float(state.group(4)),
|
|
"grade": state.group(5),
|
|
"factors": parse_state_factors(state.group(6)),
|
|
})
|
|
return payload
|
|
|
|
submit = SUBMIT_RE.search(message)
|
|
if submit:
|
|
payload = dict(base)
|
|
detail_text = submit.group(1).strip()
|
|
payload.update({"type": "SUBMIT", "detail": detail_text, "fields": parse_submit_fields(detail_text)})
|
|
return payload
|
|
|
|
state_detail = STATE_DETAIL_RE.search(message)
|
|
if state_detail:
|
|
payload = dict(base)
|
|
payload.update({"type": "STATE_DETAIL", "reasons": parse_quoted_reasons(state_detail.group(1))})
|
|
return payload
|
|
|
|
signal_detail = SIGNAL_DETAIL_RE.search(message)
|
|
if signal_detail:
|
|
payload = dict(base)
|
|
payload.update({"type": "SIGNAL_DETAIL", "reasons": parse_quoted_reasons(signal_detail.group(1))})
|
|
return payload
|
|
|
|
state_context = STATE_CONTEXT_RE.search(message)
|
|
if state_context:
|
|
payload = dict(base)
|
|
payload.update({"type": "STATE_CONTEXT", "fields": parse_state_context_fields(state_context.group(1))})
|
|
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
|
|
|
|
connection_state = CONNECTION_STATE_RE.search(message)
|
|
if connection_state:
|
|
payload = dict(base)
|
|
payload.update({"type": "CONNECTION STATE", "status": "LOST" if connection_state.group(1).lower() == "true" else "OK"})
|
|
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
|
|
|
|
account = ACCOUNT_RE.search(message)
|
|
if account:
|
|
payload = dict(base)
|
|
payload.update({"type": "ACCOUNT", "account": account.group(1).strip()})
|
|
return payload
|
|
|
|
symbol = SYMBOL_RE.search(message)
|
|
if symbol:
|
|
payload = dict(base)
|
|
payload.update({"type": "SYMBOL", "symbol": symbol.group(1).strip()})
|
|
return payload
|
|
|
|
mode = MODE_RE.search(message)
|
|
if mode:
|
|
payload = dict(base)
|
|
payload.update({"type": "MODE", "mode": mode.group(1).strip()})
|
|
return payload
|
|
|
|
return None
|
|
|
|
|
|
def parse_signal_line(message: str, timestamp: Optional[str], source_line: str, latest_state: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
signal = SIGNAL_RE.search(message or "")
|
|
if signal is None:
|
|
return None
|
|
|
|
side = signal.group(1)
|
|
detail = signal.group(3) or ""
|
|
grade_match = SIGNAL_GRADE_RE.search(message or "")
|
|
score_match = SIGNAL_SCORE_RE.search(message or "")
|
|
grade = grade_match.group(1) if grade_match else None
|
|
score: Optional[float] = None
|
|
if score_match:
|
|
try:
|
|
score = float(score_match.group(1))
|
|
except ValueError:
|
|
score = None
|
|
|
|
if latest_state is not None:
|
|
if grade is None:
|
|
grade = latest_state.get("grade")
|
|
if score is None and latest_state.get("score") is not None:
|
|
score = latest_state.get("score")
|
|
|
|
return {
|
|
"time": timestamp,
|
|
"side": side,
|
|
"grade": grade or "Unknown",
|
|
"score": score,
|
|
"filled": False,
|
|
"reject_reason": None,
|
|
"reject_detail": "",
|
|
"line": source_line,
|
|
}
|
|
|
|
|
|
def parse_full_session_kpis(path: Optional[Path]) -> Dict[str, Any]:
|
|
"""Parses full-session dashboard KPIs from a session_*.log file.
|
|
|
|
This is intentionally read-only observability. It never writes to NT8, never
|
|
touches strategy state, and cannot affect live trading behavior.
|
|
"""
|
|
empty = {
|
|
"session_reject_totals": {},
|
|
"signal_outcomes": [],
|
|
"signal_grade_summary": [],
|
|
"missed_grade_b_plus_count": 0,
|
|
"missed_grade_b_plus_samples": [],
|
|
}
|
|
if path is None or not path.exists():
|
|
return empty
|
|
|
|
try:
|
|
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
except OSError:
|
|
return empty
|
|
|
|
reject_summary_final: Dict[str, int] = {}
|
|
reject_record_counts: Dict[str, int] = {}
|
|
signal_outcomes: List[Dict[str, Any]] = []
|
|
latest_state: Optional[Dict[str, Any]] = None
|
|
current_signal: Optional[Dict[str, Any]] = None
|
|
active_blocking_reason: Optional[str] = None
|
|
missed_samples: List[Dict[str, Any]] = []
|
|
missed_count = 0
|
|
|
|
for line in lines:
|
|
timestamp, message = split_log_line(line)
|
|
|
|
state = STATE_RE.search(message)
|
|
if state:
|
|
latest_state = {
|
|
"timestamp": timestamp,
|
|
"regime": state.group(1),
|
|
"direction": state.group(2),
|
|
"direction_source": state.group(3),
|
|
"score": float(state.group(4)),
|
|
"grade": state.group(5),
|
|
}
|
|
if active_blocking_reason and is_grade_b_or_better(latest_state.get("grade")):
|
|
missed_count += 1
|
|
missed_samples.append({
|
|
"timestamp": timestamp,
|
|
"grade": latest_state.get("grade"),
|
|
"score": latest_state.get("score"),
|
|
"blocking_reason": active_blocking_reason,
|
|
})
|
|
missed_samples = missed_samples[-20:]
|
|
continue
|
|
|
|
reject_summary = REJECT_SUMMARY_RE.search(message)
|
|
if reject_summary:
|
|
parts = parse_key_values(reject_summary.group(1))
|
|
reason = parts.get("reason")
|
|
if reason:
|
|
try:
|
|
reject_summary_final[reason] = int(parts.get("count", "0"))
|
|
except ValueError:
|
|
reject_summary_final[reason] = 0
|
|
continue
|
|
|
|
reject = REJECT_RE.search(message)
|
|
if reject:
|
|
parts = parse_key_values(reject.group(1))
|
|
reason = parts.get("reason")
|
|
if reason:
|
|
reject_record_counts[reason] = reject_record_counts.get(reason, 0) + 1
|
|
if reason in BLOCKING_REJECT_REASONS:
|
|
active_blocking_reason = reason
|
|
if current_signal is not None and not current_signal.get("filled") and not current_signal.get("reject_reason"):
|
|
current_signal["reject_reason"] = reason
|
|
current_signal["reject_detail"] = parts.get("detail", "")
|
|
continue
|
|
|
|
parsed_signal = parse_signal_line(message, timestamp, line, latest_state)
|
|
if parsed_signal is not None:
|
|
signal_outcomes.append(parsed_signal)
|
|
current_signal = parsed_signal
|
|
continue
|
|
|
|
if FILL_RE.search(message):
|
|
if current_signal is not None and not current_signal.get("filled"):
|
|
current_signal["filled"] = True
|
|
continue
|
|
|
|
totals = dict(reject_summary_final)
|
|
for reason, count in reject_record_counts.items():
|
|
if reason not in totals:
|
|
totals[reason] = count
|
|
|
|
grade_summary: Dict[str, Dict[str, Any]] = {}
|
|
for outcome in signal_outcomes:
|
|
grade = str(outcome.get("grade") or "Unknown")
|
|
if grade not in grade_summary:
|
|
grade_summary[grade] = {"grade": grade, "generated": 0, "filled": 0, "rejected": 0, "reject_reasons": {}}
|
|
summary = grade_summary[grade]
|
|
summary["generated"] += 1
|
|
if outcome.get("filled"):
|
|
summary["filled"] += 1
|
|
if outcome.get("reject_reason"):
|
|
summary["rejected"] += 1
|
|
reason = str(outcome.get("reject_reason"))
|
|
summary["reject_reasons"][reason] = summary["reject_reasons"].get(reason, 0) + 1
|
|
|
|
sorted_grade_summary = sorted(grade_summary.values(), key=lambda item: (-grade_rank(item.get("grade")), str(item.get("grade"))))
|
|
|
|
return {
|
|
"session_reject_totals": {reason: totals[reason] for reason in sorted(totals.keys(), key=str.lower)},
|
|
"signal_outcomes": signal_outcomes,
|
|
"signal_grade_summary": sorted_grade_summary,
|
|
"missed_grade_b_plus_count": missed_count,
|
|
"missed_grade_b_plus_samples": missed_samples,
|
|
}
|
|
|
|
|
|
def parse_readiness(lines: List[str]) -> Dict[str, Any]:
|
|
data_series: Dict[int, Dict[str, Any]] = {}
|
|
factors: Dict[str, Dict[str, Any]] = {}
|
|
context = ""
|
|
bars_required = ""
|
|
for line in lines:
|
|
timestamp, message = split_log_line(line)
|
|
if message.startswith("Historical readiness"):
|
|
context = message
|
|
required = re.search(r"BarsRequiredToTrade=([^\s]+)", message, re.IGNORECASE)
|
|
if required:
|
|
bars_required = required.group(1)
|
|
data_match = DATA_SERIES_RE.search(message)
|
|
if data_match:
|
|
index = int(data_match.group(1))
|
|
data_series[index] = {
|
|
"index": index,
|
|
"type": data_match.group(2),
|
|
"days_to_load": data_match.group(3),
|
|
"historical_bars_loaded": data_match.group(4),
|
|
}
|
|
warmup = FACTOR_WARMUP_RE.search(message)
|
|
if warmup:
|
|
for factor in FACTOR_STATUS_RE.finditer(warmup.group(1)):
|
|
factors[factor.group(1)] = {
|
|
"name": factor.group(1),
|
|
"status": factor.group(2).upper(),
|
|
"loaded": int(factor.group(3)),
|
|
"required": int(factor.group(4)),
|
|
}
|
|
return {
|
|
"context": context,
|
|
"bars_required_to_trade": bars_required,
|
|
"data_series": [data_series[index] for index in sorted(data_series.keys())],
|
|
"factors": [factors[name] for name in sorted(factors.keys())],
|
|
}
|
|
|
|
|
|
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]] = []
|
|
date = None
|
|
match = TRADES_FILE_RE.match(path.name)
|
|
if match:
|
|
raw = match.group(1)
|
|
date = "{0}-{1}-{2}".format(raw[0:4], raw[4:6], raw[6:8])
|
|
try:
|
|
with path.open("r", encoding="utf-8", errors="replace") as handle:
|
|
for line_number, line in enumerate(handle, start=1):
|
|
text = line.strip()
|
|
if not text:
|
|
continue
|
|
try:
|
|
record = json.loads(text)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(record, dict):
|
|
if date is not None and "date" not in record:
|
|
record["date"] = date
|
|
record.setdefault("path", path.name)
|
|
record.setdefault("line", line_number)
|
|
records.append(record)
|
|
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
|