522 lines
19 KiB
Python
522 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Standalone NT8 SDK session log watcher.
|
|
|
|
Tails the newest session_*.log file and emits JSON events to a webhook or stdout.
|
|
This tool is read-only with respect to NinjaTrader directories.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from dataclasses import dataclass, field
|
|
from datetime import date, datetime, time as dt_time, timedelta
|
|
from pathlib import Path
|
|
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
|
|
|
|
try:
|
|
from zoneinfo import ZoneInfo
|
|
except ImportError: # pragma: no cover - Python < 3.9 fallback
|
|
ZoneInfo = None # type: ignore
|
|
|
|
|
|
DEFAULT_CONFIG_PATH = Path(__file__).with_name("config.json")
|
|
SESSION_FILE_RE = re.compile(r"^session_(\d{8})_(\d{6})\.log$", 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)
|
|
SESSION_END_RE = re.compile(r"=== SESSION END\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\s+===", re.IGNORECASE)
|
|
KEY_VALUE_RE = re.compile(r"^([^:]+?)\s*:\s*(.*)$")
|
|
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*(.*)$", re.IGNORECASE)
|
|
SIGNAL_RE = re.compile(r"SIGNAL:\s*(.*)$", re.IGNORECASE)
|
|
SUBMIT_RE = re.compile(r"\bSUBMIT\b\s*:?(.*)$", re.IGNORECASE)
|
|
REJECT_RE = re.compile(r"REJECT:\s*reason=([^\s]+)\s+detail=(.*?)(?:\s+bar=(.*))?$", re.IGNORECASE)
|
|
REJECT_SUMMARY_RE = re.compile(r"REJECT SUMMARY:\s*reason=([^\s]+)\s+count=(\d+)", re.IGNORECASE)
|
|
WARNING_RE = re.compile(r"WARNING:\s*(.*)$", re.IGNORECASE)
|
|
CONNECTION_RE = re.compile(r"CONNECTION\s+(LOST|RESTORED)", re.IGNORECASE)
|
|
GRADE_RE = re.compile(r"\bgrade(?:=|\s+)([A-Za-z0-9+]+)", re.IGNORECASE)
|
|
SCORE_RE = re.compile(r"\bscore(?:=|\s+)(-?\d+(?:\.\d+)?)", re.IGNORECASE)
|
|
SIDE_RE = re.compile(r"\b(Buy|Sell|Long|Short)\b", re.IGNORECASE)
|
|
MODE_RE = re.compile(r"\b(?:mode|resolvedMode|runnerMode)=([^\s,;|]+)", re.IGNORECASE)
|
|
QUANTITY_RE = re.compile(r"\b(?:qty|quantity|contracts)=?(\d+)\b", re.IGNORECASE)
|
|
|
|
|
|
@dataclass
|
|
class SessionHeader:
|
|
started_at: Optional[str] = None
|
|
account: Optional[str] = None
|
|
instrument: Optional[str] = None
|
|
bar_type: Optional[str] = None
|
|
days_to_load: Optional[int] = None
|
|
historical_bars_loaded: Optional[int] = None
|
|
warmup_status: Optional[str] = None
|
|
emitted: bool = False
|
|
|
|
|
|
@dataclass
|
|
class WatchState:
|
|
current_path: Optional[Path] = None
|
|
offset: int = 0
|
|
partial: str = ""
|
|
session_header: SessionHeader = field(default_factory=SessionHeader)
|
|
session_date: Optional[date] = None
|
|
event_date: Optional[date] = None
|
|
previous_line_time: Optional[dt_time] = None
|
|
signal_seen: bool = False
|
|
silent_alert_sent: bool = False
|
|
signal_dates: Set[date] = field(default_factory=set)
|
|
silent_alert_dates: Set[date] = field(default_factory=set)
|
|
session_ended: bool = False
|
|
reject_reasons_seen: Set[str] = field(default_factory=set)
|
|
|
|
|
|
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description="Tail NT8 SDK session logs and emit webhook events.")
|
|
parser.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), help="Path to config.json")
|
|
parser.add_argument("--dry-run", action="store_true", help="Print payloads to stdout instead of POSTing")
|
|
parser.add_argument("--log-dir", help="Override config log_dir")
|
|
parser.add_argument("--webhook-url", help="Override config webhook_url")
|
|
parser.add_argument("--poll-seconds", type=float, default=2.0, help="Polling interval")
|
|
parser.add_argument("--from-start", action="store_true", help="Read current newest session file from the beginning")
|
|
parser.add_argument("--once", action="store_true", help="Process available data once and exit")
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def expand_path(raw_path: str) -> Path:
|
|
return Path(os.path.expanduser(os.path.expandvars(raw_path)))
|
|
|
|
|
|
def load_config(path: Path) -> Dict[str, Any]:
|
|
try:
|
|
with path.open("r", encoding="utf-8") as handle:
|
|
return json.load(handle)
|
|
except OSError:
|
|
return {}
|
|
except ValueError as ex:
|
|
raise RuntimeError("Invalid config JSON: {0}".format(ex))
|
|
|
|
|
|
def event_enabled(config: Dict[str, Any], event_type: str) -> bool:
|
|
events = config.get("events")
|
|
if not isinstance(events, dict):
|
|
return True
|
|
return bool(events.get(event_type, True))
|
|
|
|
|
|
def newest_session_file(log_dir: Path) -> Optional[Path]:
|
|
newest: Optional[Tuple[datetime, Path]] = None
|
|
try:
|
|
iterator = log_dir.rglob("session_*.log")
|
|
for path in iterator:
|
|
if not path.is_file():
|
|
continue
|
|
match = SESSION_FILE_RE.match(path.name)
|
|
if match is None:
|
|
continue
|
|
stamp = datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
|
|
if newest is None or stamp > newest[0]:
|
|
newest = (stamp, path)
|
|
except OSError as ex:
|
|
sys.stderr.write("logwatch: cannot scan log directory {0}: {1}\n".format(log_dir, ex))
|
|
return None
|
|
return newest[1] if newest is not None else None
|
|
|
|
|
|
def parse_time(value: str) -> dt_time:
|
|
return datetime.strptime(value, "%H:%M").time()
|
|
|
|
|
|
def now_in_timezone(name: str) -> datetime:
|
|
if ZoneInfo is not None:
|
|
try:
|
|
return datetime.now(ZoneInfo(name))
|
|
except Exception:
|
|
pass
|
|
return datetime.now()
|
|
|
|
|
|
def strip_timestamp(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_log_timestamp_time(value: Optional[str]) -> Optional[dt_time]:
|
|
if value is None:
|
|
return None
|
|
text = value.split(".", 1)[0]
|
|
try:
|
|
return datetime.strptime(text, "%H:%M:%S").time()
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def timestamp_from_session_filename(path: Path) -> Optional[datetime]:
|
|
match = SESSION_FILE_RE.match(path.name)
|
|
if match is None:
|
|
return None
|
|
return datetime.strptime("{0}_{1}".format(match.group(1), match.group(2)), "%Y%m%d_%H%M%S")
|
|
|
|
|
|
def update_event_date(state: WatchState, timestamp_text: Optional[str]) -> None:
|
|
line_time = parse_log_timestamp_time(timestamp_text)
|
|
if line_time is None:
|
|
return
|
|
if state.event_date is None:
|
|
state.event_date = state.session_date
|
|
if state.previous_line_time is not None and line_time < state.previous_line_time:
|
|
if state.event_date is not None:
|
|
state.event_date = state.event_date + timedelta(days=1)
|
|
state.previous_line_time = line_time
|
|
|
|
|
|
def emit(config: Dict[str, Any], dry_run: bool, payload: Dict[str, Any]) -> None:
|
|
payload["emitted_at_utc"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
payload["tool"] = "logwatch"
|
|
|
|
webhook_url = str(config.get("webhook_url") or "").strip()
|
|
if dry_run or not webhook_url:
|
|
sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n")
|
|
sys.stdout.flush()
|
|
return
|
|
|
|
data = json.dumps(payload).encode("utf-8")
|
|
request = urllib.request.Request(
|
|
webhook_url,
|
|
data=data,
|
|
headers={"Content-Type": "application/json", "User-Agent": "nt8-sdk-logwatch/1.0"},
|
|
method="POST",
|
|
)
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=5) as response:
|
|
response.read()
|
|
except (urllib.error.URLError, OSError, ValueError) as ex:
|
|
sys.stderr.write("logwatch: webhook POST failed; continuing: {0}\n".format(ex))
|
|
|
|
|
|
def base_payload(event_type: str, state: WatchState, line: Optional[str] = None) -> Dict[str, Any]:
|
|
payload: Dict[str, Any] = {
|
|
"event_type": event_type,
|
|
"session_file": str(state.current_path) if state.current_path is not None else None,
|
|
}
|
|
if state.event_date is not None:
|
|
payload["session_date"] = state.event_date.isoformat()
|
|
payload["event_date"] = state.event_date.isoformat()
|
|
elif state.session_date is not None:
|
|
payload["session_date"] = state.session_date.isoformat()
|
|
payload["event_date"] = state.session_date.isoformat()
|
|
if line is not None:
|
|
payload["line"] = line
|
|
return payload
|
|
|
|
|
|
def maybe_emit_session_start(config: Dict[str, Any], dry_run: bool, state: WatchState) -> None:
|
|
header = state.session_header
|
|
if header.emitted or header.started_at is None:
|
|
return
|
|
if not event_enabled(config, "session_start"):
|
|
header.emitted = True
|
|
return
|
|
payload = base_payload("SESSION START", state)
|
|
payload.update(
|
|
{
|
|
"started_at": header.started_at,
|
|
"account": header.account,
|
|
"instrument": header.instrument,
|
|
"bar_type": header.bar_type,
|
|
"days_to_load": header.days_to_load,
|
|
"historical_bars_loaded": header.historical_bars_loaded,
|
|
"warmup_status": header.warmup_status,
|
|
}
|
|
)
|
|
emit(config, dry_run, payload)
|
|
header.emitted = True
|
|
|
|
|
|
def parse_session_header_field(state: WatchState, message: str) -> None:
|
|
match = KEY_VALUE_RE.match(message)
|
|
if match is not None:
|
|
key = match.group(1).strip()
|
|
value = match.group(2).strip()
|
|
if key == "Account":
|
|
state.session_header.account = value
|
|
elif key == "Symbol":
|
|
state.session_header.instrument = value
|
|
|
|
data_match = DATA_SERIES_RE.search(message)
|
|
if data_match is not None and data_match.group(1) == "0":
|
|
state.session_header.bar_type = data_match.group(2)
|
|
state.session_header.days_to_load = int(data_match.group(3))
|
|
state.session_header.historical_bars_loaded = int(data_match.group(4))
|
|
|
|
warmup_match = FACTOR_WARMUP_RE.search(message)
|
|
if warmup_match is not None:
|
|
state.session_header.warmup_status = warmup_match.group(1)
|
|
|
|
|
|
def parse_signal_details(text: str) -> Dict[str, Any]:
|
|
details: Dict[str, Any] = {"raw": text}
|
|
grade = GRADE_RE.search(text)
|
|
score = SCORE_RE.search(text)
|
|
side = SIDE_RE.search(text)
|
|
if grade is not None:
|
|
details["grade"] = grade.group(1)
|
|
if score is not None:
|
|
try:
|
|
details["score"] = float(score.group(1))
|
|
except ValueError:
|
|
details["score"] = score.group(1)
|
|
if side is not None:
|
|
details["side"] = side.group(1)
|
|
else:
|
|
parts = text.split()
|
|
if parts:
|
|
details["side"] = parts[0]
|
|
return details
|
|
|
|
|
|
def parse_submit_details(text: str) -> Dict[str, Any]:
|
|
details: Dict[str, Any] = {"raw": text}
|
|
mode = MODE_RE.search(text)
|
|
quantity = QUANTITY_RE.search(text)
|
|
if mode is not None:
|
|
details["mode"] = mode.group(1)
|
|
if quantity is not None:
|
|
details["quantity"] = int(quantity.group(1))
|
|
return details
|
|
|
|
|
|
def handle_line(config: Dict[str, Any], dry_run: bool, state: WatchState, raw_line: str) -> None:
|
|
timestamp, message = strip_timestamp(raw_line)
|
|
update_event_date(state, timestamp)
|
|
if not message:
|
|
return
|
|
|
|
start_match = SESSION_START_RE.search(message)
|
|
if start_match is not None:
|
|
state.session_header = SessionHeader(started_at=start_match.group(1))
|
|
state.reject_reasons_seen.clear()
|
|
state.signal_seen = False
|
|
state.silent_alert_sent = False
|
|
state.signal_dates.clear()
|
|
state.silent_alert_dates.clear()
|
|
state.session_ended = False
|
|
try:
|
|
state.session_date = datetime.strptime(start_match.group(1), "%Y-%m-%d %H:%M:%S").date()
|
|
state.event_date = state.session_date
|
|
except ValueError:
|
|
state.session_date = None
|
|
return
|
|
|
|
if SESSION_END_RE.search(message) is not None:
|
|
state.session_ended = True
|
|
return
|
|
|
|
parse_session_header_field(state, message)
|
|
if message == "---" and state.session_header.started_at is not None:
|
|
maybe_emit_session_start(config, dry_run, state)
|
|
return
|
|
|
|
warning_match = WARNING_RE.search(message)
|
|
if warning_match is not None and event_enabled(config, "warning"):
|
|
payload = base_payload("WARNING", state, raw_line)
|
|
payload["message"] = warning_match.group(1)
|
|
emit(config, dry_run, payload)
|
|
|
|
connection_match = CONNECTION_RE.search(message)
|
|
if connection_match is not None and event_enabled(config, "connection"):
|
|
payload = base_payload("CONNECTION {0}".format(connection_match.group(1).upper()), state, raw_line)
|
|
payload["status"] = connection_match.group(1).upper()
|
|
emit(config, dry_run, payload)
|
|
|
|
signal_match = SIGNAL_RE.search(message)
|
|
if signal_match is not None:
|
|
state.signal_seen = True
|
|
if state.event_date is not None:
|
|
state.signal_dates.add(state.event_date)
|
|
if event_enabled(config, "signal"):
|
|
payload = base_payload("SIGNAL", state, raw_line)
|
|
payload.update(parse_signal_details(signal_match.group(1)))
|
|
emit(config, dry_run, payload)
|
|
|
|
submit_match = SUBMIT_RE.search(message)
|
|
if submit_match is not None and event_enabled(config, "submit"):
|
|
payload = base_payload("SUBMIT", state, raw_line)
|
|
payload.update(parse_submit_details(submit_match.group(1)))
|
|
emit(config, dry_run, payload)
|
|
|
|
reject_match = REJECT_RE.search(message)
|
|
if reject_match is not None:
|
|
reason = reject_match.group(1)
|
|
if reason not in state.reject_reasons_seen:
|
|
state.reject_reasons_seen.add(reason)
|
|
if event_enabled(config, "reject"):
|
|
payload = base_payload("REJECT", state, raw_line)
|
|
payload["reason"] = reason
|
|
payload["detail"] = reject_match.group(2).strip()
|
|
payload["bar"] = reject_match.group(3).strip() if reject_match.group(3) else None
|
|
emit(config, dry_run, payload)
|
|
|
|
summary_match = REJECT_SUMMARY_RE.search(message)
|
|
if summary_match is not None and event_enabled(config, "reject_summary"):
|
|
payload = base_payload("REJECT SUMMARY", state, raw_line)
|
|
payload["reason"] = summary_match.group(1)
|
|
payload["count"] = int(summary_match.group(2))
|
|
emit(config, dry_run, payload)
|
|
|
|
|
|
def read_new_lines(path: Path, state: WatchState) -> List[str]:
|
|
try:
|
|
size = path.stat().st_size
|
|
except OSError as ex:
|
|
sys.stderr.write("logwatch: cannot stat {0}: {1}\n".format(path, ex))
|
|
return []
|
|
|
|
if size < state.offset:
|
|
state.offset = 0
|
|
state.partial = ""
|
|
|
|
try:
|
|
with path.open("rb") as handle:
|
|
handle.seek(state.offset)
|
|
chunk = handle.read()
|
|
state.offset = handle.tell()
|
|
except OSError as ex:
|
|
sys.stderr.write("logwatch: cannot read {0}; continuing: {1}\n".format(path, ex))
|
|
return []
|
|
|
|
if not chunk:
|
|
return []
|
|
|
|
text = state.partial + chunk.decode("utf-8", errors="replace")
|
|
lines = text.splitlines(True)
|
|
complete: List[str] = []
|
|
state.partial = ""
|
|
for line in lines:
|
|
if line.endswith("\n") or line.endswith("\r"):
|
|
complete.append(line.rstrip("\r\n"))
|
|
else:
|
|
state.partial = line
|
|
return complete
|
|
|
|
|
|
def switch_file(state: WatchState, path: Path, from_start: bool) -> None:
|
|
state.current_path = path
|
|
state.partial = ""
|
|
state.session_header = SessionHeader()
|
|
file_timestamp = timestamp_from_session_filename(path)
|
|
state.session_date = file_timestamp.date() if file_timestamp is not None else None
|
|
state.event_date = state.session_date
|
|
state.previous_line_time = None
|
|
state.signal_seen = False
|
|
state.silent_alert_sent = False
|
|
state.signal_dates.clear()
|
|
state.silent_alert_dates.clear()
|
|
state.session_ended = False
|
|
state.reject_reasons_seen.clear()
|
|
if from_start:
|
|
state.offset = 0
|
|
else:
|
|
try:
|
|
state.offset = path.stat().st_size
|
|
except OSError:
|
|
state.offset = 0
|
|
|
|
|
|
def check_silent_window(config: Dict[str, Any], dry_run: bool, state: WatchState, current_override: Optional[datetime] = None) -> None:
|
|
if not event_enabled(config, "silent_window_alert"):
|
|
return
|
|
if state.session_header.started_at is None and state.session_date is None:
|
|
return
|
|
if state.session_ended:
|
|
return
|
|
timezone = str(config.get("timezone") or "America/New_York")
|
|
current = current_override if current_override is not None else now_in_timezone(timezone)
|
|
alert_date = current.date()
|
|
if alert_date in state.silent_alert_dates or alert_date in state.signal_dates:
|
|
return
|
|
window_end = parse_time(str(config.get("orb_window_end") or "10:15"))
|
|
if current.time() <= window_end:
|
|
return
|
|
previous_event_date = state.event_date
|
|
state.event_date = alert_date
|
|
payload = base_payload("SILENT WINDOW ALERT", state)
|
|
payload["orb_window_start"] = str(config.get("orb_window_start") or "09:30")
|
|
payload["orb_window_end"] = str(config.get("orb_window_end") or "10:15")
|
|
payload["timezone"] = timezone
|
|
payload["message"] = "ORB window elapsed with no SIGNAL line in the active session log."
|
|
emit(config, dry_run, payload)
|
|
state.event_date = previous_event_date
|
|
state.silent_alert_sent = True
|
|
state.silent_alert_dates.add(alert_date)
|
|
|
|
|
|
def watch(config: Dict[str, Any], args: argparse.Namespace) -> int:
|
|
log_dir = expand_path(args.log_dir or str(config.get("log_dir") or ""))
|
|
if not log_dir.exists() or not log_dir.is_dir():
|
|
sys.stderr.write("logwatch: log directory not found: {0}\n".format(log_dir))
|
|
return 2
|
|
|
|
if args.webhook_url is not None:
|
|
config["webhook_url"] = args.webhook_url
|
|
|
|
dry_run = bool(args.dry_run)
|
|
state = WatchState()
|
|
from_start_for_next_file = bool(args.from_start)
|
|
|
|
while True:
|
|
newest = newest_session_file(log_dir)
|
|
if newest is None:
|
|
sys.stderr.write("logwatch: no session_*.log files found under {0}\n".format(log_dir))
|
|
if args.once:
|
|
return 1
|
|
time.sleep(args.poll_seconds)
|
|
continue
|
|
|
|
if state.current_path != newest:
|
|
switch_file(state, newest, from_start_for_next_file)
|
|
from_start_for_next_file = True
|
|
sys.stderr.write("logwatch: watching {0}\n".format(newest))
|
|
|
|
for line in read_new_lines(newest, state):
|
|
handle_line(config, dry_run, state, line)
|
|
check_silent_window(config, dry_run, state)
|
|
|
|
if args.once:
|
|
if state.partial:
|
|
handle_line(config, dry_run, state, state.partial)
|
|
state.partial = ""
|
|
maybe_emit_session_start(config, dry_run, state)
|
|
check_silent_window(config, dry_run, state)
|
|
return 0
|
|
|
|
time.sleep(args.poll_seconds)
|
|
|
|
|
|
def main(argv: Sequence[str]) -> int:
|
|
args = parse_args(argv)
|
|
try:
|
|
config = load_config(expand_path(args.config))
|
|
except RuntimeError as ex:
|
|
sys.stderr.write(str(ex) + "\n")
|
|
return 2
|
|
try:
|
|
return watch(config, args)
|
|
except KeyboardInterrupt:
|
|
sys.stderr.write("logwatch: stopped\n")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|