Coverage for scripts/order_events_audit.py: 100%

90 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""V5.3.1 (development/Problems.md #34/#96) - standalone audit of every 

2real `order-events.json` this repo has ever produced (`backtests/*/**/ 

3order-events.json`, ~45 files as of this writing), turning the ad hoc 

4`grep`/manual-scan evidence Problems.md #34 was built from into a 

5repeatable, versioned tool instead of a one-off investigation. 

6 

7Never wired into `aq` (matches scripts/profile_subsystems.py's own 

8convention - a standalone local-dev diagnostic, not a system report). 

9 

10Reports, per run and aggregated across every run: 

11- a status-value histogram (cross-checks execution/order_gate.py's 

12 PENDING_ORDER_STATUS_NAMES/TERMINAL_*_STATUS_NAMES tuples stay 

13 exhaustive against whatever Lean's real OrderStatus enum actually 

14 produces - the tool's main forward-looking value, catching a future 

15 new/renamed status string before it silently falls through to 

16 "unknown") 

17- per-order fill latency (wall-clock time between the first "submitted" 

18 event and the terminal "filled"/"canceled" event for the same orderId - 

19 reported in hours, not "bars": a Unix timestamp alone can't be 

20 faithfully converted to a bar count without the exact trading calendar, 

21 and an approximate one would be more misleading than an honest 

22 time-based number) 

23- an UPPER-BOUND proxy for fallback-triggered market orders: Lean's 

24 order-events log carries no field linking a canceled limit order to 

25 the market order that (if `fallback_to_market_on_timeout` was on for 

26 that asset class) may have followed it, so this reports "canceled" 

27 counts only, honestly labeled as an upper bound, never presented as an 

28 exact fallback count. 

29 

30Usage: 

31 python scripts/order_events_audit.py [--backtests-dir backtests] [--output PATH] 

32""" 

33 

34from __future__ import annotations 

35 

36import argparse 

37import json 

38import sys 

39from collections import Counter 

40from collections.abc import Iterator 

41from pathlib import Path 

42 

43ROOT_DIR = Path(__file__).resolve().parent.parent 

44BACKTESTS_DIR = ROOT_DIR / "backtests" 

45OUTPUT_PATH = Path(__file__).resolve().parent / "order_events_audit_output.txt" 

46 

47 

48def _iter_order_events_jsons(backtests_dir: Path) -> Iterator[Path]: 

49 """Yields every backtest run's order-events.json, newest folder first 

50 by mtime (not name - same "non-timestamped ad hoc folder names can 

51 otherwise sort ahead of real ones" reasoning as 

52 generate_backtest_report.py::_iter_backtest_result_jsons(), though 

53 this tool aggregates across ALL runs rather than picking one "latest", 

54 so the ordering only affects report readability, not correctness).""" 

55 if not backtests_dir.exists(): 

56 return 

57 run_dirs = sorted( 

58 (d for d in backtests_dir.iterdir() if d.is_dir()), 

59 key=lambda d: d.stat().st_mtime, 

60 reverse=True, 

61 ) 

62 for run_dir in run_dirs: 

63 yield from sorted(run_dir.glob("*-order-events.json")) 

64 

65 

66def load_order_events(path: Path) -> list[dict]: 

67 """Thin loader - order-events.json is a single JSON array (not JSONL). 

68 Returns [] for a missing/malformed file rather than raising, so one 

69 bad file never aborts a whole-repo audit.""" 

70 try: 

71 data = json.loads(path.read_text(encoding="utf-8")) 

72 except (OSError, json.JSONDecodeError): 

73 return [] 

74 return data if isinstance(data, list) else [] 

75 

76 

77def summarize_order_events(events: list[dict]) -> dict: 

78 """Pure function (no file I/O) - status histogram, per-order fill 

79 latency (hours between first "submitted" and the terminal 

80 "filled"/"canceled" event for that orderId), and canceled-count-by- 

81 symbol (the honest upper-bound fallback proxy - see module docstring). 

82 

83 Returns {"num_events", "num_orders", "status_histogram", 

84 "fill_latency_hours": {"mean", "median", "max", "num_orders_measured"}, 

85 "canceled_count_by_symbol"}. An empty events list returns all-zero/ 

86 empty stats, never raises.""" 

87 if not events: 

88 return { 

89 "num_events": 0, 

90 "num_orders": 0, 

91 "status_histogram": {}, 

92 "fill_latency_hours": {"mean": None, "median": None, "max": None, "num_orders_measured": 0}, 

93 "canceled_count_by_symbol": {}, 

94 } 

95 

96 status_histogram = Counter(event.get("status", "unknown") for event in events) 

97 

98 events_by_order_id: dict = {} 

99 for event in events: 

100 events_by_order_id.setdefault(event.get("orderId"), []).append(event) 

101 

102 fill_latency_hours: list[float] = [] 

103 canceled_count_by_symbol: Counter = Counter() 

104 for order_events in events_by_order_id.values(): 

105 order_events_sorted = sorted(order_events, key=lambda e: e.get("time", 0.0)) 

106 submitted = next((e for e in order_events_sorted if e.get("status") == "submitted"), None) 

107 terminal = next((e for e in order_events_sorted if e.get("status") in ("filled", "canceled")), None) 

108 if submitted is not None and terminal is not None: 

109 latency_seconds = float(terminal.get("time", 0.0)) - float(submitted.get("time", 0.0)) 

110 if latency_seconds >= 0: 

111 fill_latency_hours.append(latency_seconds / 3600.0) 

112 if terminal is not None and terminal.get("status") == "canceled": 

113 canceled_count_by_symbol[terminal.get("symbolValue", terminal.get("symbol", "unknown"))] += 1 

114 

115 fill_latency_summary = { 

116 "mean": (sum(fill_latency_hours) / len(fill_latency_hours)) if fill_latency_hours else None, 

117 "median": sorted(fill_latency_hours)[len(fill_latency_hours) // 2] if fill_latency_hours else None, 

118 "max": max(fill_latency_hours) if fill_latency_hours else None, 

119 "num_orders_measured": len(fill_latency_hours), 

120 } 

121 

122 return { 

123 "num_events": len(events), 

124 "num_orders": len(events_by_order_id), 

125 "status_histogram": dict(status_histogram), 

126 "fill_latency_hours": fill_latency_summary, 

127 "canceled_count_by_symbol": dict(canceled_count_by_symbol), 

128 } 

129 

130 

131def _merge_summaries(summaries: list[dict]) -> dict: 

132 """Aggregates summarize_order_events()'s per-file output across every 

133 file found - a simple sum/recompute, not a re-scan of raw events.""" 

134 total_status_histogram: Counter = Counter() 

135 total_canceled_by_symbol: Counter = Counter() 

136 all_fill_latencies: list[float] = [] 

137 total_events = 0 

138 total_orders = 0 

139 

140 for summary in summaries: 

141 total_events += summary["num_events"] 

142 total_orders += summary["num_orders"] 

143 total_status_histogram.update(summary["status_histogram"]) 

144 total_canceled_by_symbol.update(summary["canceled_count_by_symbol"]) 

145 latency = summary["fill_latency_hours"] 

146 if latency["mean"] is not None: 

147 # Reconstruct the underlying values is not possible from a 

148 # summary alone - approximate by repeating the mean 

149 # num_orders_measured times, which preserves the aggregate 

150 # mean exactly and is a reasonable (if slightly smoothed) 

151 # approximation for max/median across files. 

152 all_fill_latencies.extend([latency["mean"]] * latency["num_orders_measured"]) 

153 

154 return { 

155 "num_files": len(summaries), 

156 "num_events": total_events, 

157 "num_orders": total_orders, 

158 "status_histogram": dict(total_status_histogram), 

159 "fill_latency_hours": { 

160 "mean": (sum(all_fill_latencies) / len(all_fill_latencies)) if all_fill_latencies else None, 

161 "num_orders_measured": len(all_fill_latencies), 

162 }, 

163 "canceled_count_by_symbol_top_20": dict(total_canceled_by_symbol.most_common(20)), 

164 } 

165 

166 

167def main() -> int: 

168 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

169 parser.add_argument("--backtests-dir", type=Path, default=BACKTESTS_DIR) 

170 parser.add_argument("--output", type=Path, default=OUTPUT_PATH) 

171 args = parser.parse_args() 

172 

173 per_file_summaries = [] 

174 lines = [] 

175 for path in _iter_order_events_jsons(args.backtests_dir): 

176 events = load_order_events(path) 

177 if not events: 

178 continue 

179 summary = summarize_order_events(events) 

180 per_file_summaries.append(summary) 

181 lines.append(f"{path.relative_to(args.backtests_dir)}: {summary['num_orders']} orders, {summary['status_histogram']}") 

182 

183 if not per_file_summaries: 

184 print(f"No order-events.json files found under {args.backtests_dir}.", file=sys.stderr) 

185 return 1 

186 

187 aggregate = _merge_summaries(per_file_summaries) 

188 lines.append("") 

189 lines.append(f"=== Aggregate across {aggregate['num_files']} files ===") 

190 lines.append(f"Total orders: {aggregate['num_orders']}, total events: {aggregate['num_events']}") 

191 lines.append(f"Status histogram: {aggregate['status_histogram']}") 

192 lines.append(f"Fill latency (hours): {aggregate['fill_latency_hours']}") 

193 lines.append(f"Top canceled symbols (upper-bound fallback proxy, see module docstring): {aggregate['canceled_count_by_symbol_top_20']}") 

194 

195 output_text = "\n".join(lines) 

196 args.output.parent.mkdir(parents=True, exist_ok=True) 

197 args.output.write_text(output_text, encoding="utf-8") 

198 print(output_text) 

199 print(f"\nFull audit written to {args.output}") 

200 return 0 

201 

202 

203if __name__ == "__main__": 

204 sys.exit(main())