-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1748 lines (1614 loc) · 79.9 KB
/
main.py
File metadata and controls
1748 lines (1614 loc) · 79.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Alpha Engine Executor — daily morning order-book planner.
Reads signals.json from S3, applies risk rules and position sizing,
writes approved entries and urgent exits to the intraday order book.
The daemon (daemon.py) is the sole order executor — it uses technical
triggers to time entries and executes exits immediately.
No orders are placed by this module. All trade execution happens in
the daemon via IB Gateway.
Runs on boot via systemd (alpha-engine-morning.service) on the trading
instance, which is started/stopped daily by the micro instance's cron.
Usage:
python main.py # write order book (requires IB Gateway for NAV/positions)
python main.py --dry-run # print planned orders without writing order book
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import sys
import time as _time
from datetime import date, datetime
from pathlib import Path
from typing import Any
import yaml
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from executor.ibkr import IBKRClient, SimulatedIBKRClient
from executor.order_book import OrderBook
from executor.position_sizer import compute_position_size
from executor.risk_guard import check_order, compute_drawdown_multiplier
from executor.signal_reader import get_actionable_signals, read_signals_with_fallback
from executor.strategies.config import load_strategy_config
from executor.strategies.exit_manager import evaluate_exits, SECTOR_ETF_MAP
from executor.price_cache import (
_MACRO_SYMBOLS,
load_atr_14_pct,
load_daily_vwap,
load_feature_coverage,
load_price_histories,
)
from executor.trade_logger import (
backup_to_s3,
get_entry_dates,
init_db,
log_risk_event,
log_shadow_book_block,
log_trade,
)
from alpha_engine_lib.logging import setup_logging
# Suppress benign IB Error codes that don't represent real failures:
# 10197 — "No market data during competing live session". The daemon
# keeps receiving delayed ticks via the delayedLast fallback in
# price_monitor.py, so flow-doctor's ERROR alert is spam.
# 10349 — "Order TIF was set to DAY based on order preset". IB echoes
# this back every time the preset matches the submitted TIF=DAY
# (ibkr.py sets DAY defensively after the HSY cancel cycle on
# 2026-04-13). The order is still placed and filled.
# Every executor entrypoint passes the same pattern list so all three
# fire through the shared handler.
_FLOW_DOCTOR_EXCLUDE_PATTERNS = [r"Error 10197", r"Error 10349"]
_FLOW_DOCTOR_YAML = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "flow-doctor.yaml")
setup_logging("main", flow_doctor_yaml=_FLOW_DOCTOR_YAML, exclude_patterns=_FLOW_DOCTOR_EXCLUDE_PATTERNS)
logger = logging.getLogger(__name__)
from executor.config_loader import get_config_path
# S3-delivered executor params (loaded once per cold-start)
_executor_params_cache: dict | None = None
_executor_params_loaded: bool = False
# Flat param name → nested config path mapping
_PARAM_MAP = {
"atr_multiplier": ("strategy", "exit_manager", "atr_multiplier"),
"time_decay_reduce_days": ("strategy", "exit_manager", "time_decay_reduce_days"),
"time_decay_exit_days": ("strategy", "exit_manager", "time_decay_exit_days"),
"min_score": ("min_score_to_enter",),
"max_position_pct": ("max_position_pct",),
"reduce_fraction": ("reduce_fraction",),
"atr_sizing_target_risk": ("atr_sizing_target_risk",),
"confidence_sizing_min": ("confidence_sizing_min",),
"confidence_sizing_range": ("confidence_sizing_range",),
"staleness_decay_per_day": ("staleness_decay_per_day",),
"earnings_sizing_reduction": ("earnings_sizing_reduction",),
"earnings_proximity_days": ("earnings_proximity_days",),
"momentum_gate_threshold": ("momentum_gate_threshold",),
"correlation_block_threshold": ("correlation_block_threshold",),
"profit_take_pct": ("strategy", "exit_manager", "profit_take_pct"),
"momentum_exit_threshold": ("strategy", "exit_manager", "momentum_exit_threshold"),
}
# (type, min, max) for each S3-delivered param — values outside range are rejected
_PARAM_VALIDATORS = {
"atr_multiplier": (float, 0.5, 10.0),
"time_decay_reduce_days": (int, 1, 30),
"time_decay_exit_days": (int, 1, 60),
"min_score": (float, 0, 100),
"max_position_pct": (float, 0.01, 0.25),
"reduce_fraction": (float, 0.1, 1.0),
"atr_sizing_target_risk": (float, 0.005, 0.10),
"confidence_sizing_min": (float, 0.3, 1.0),
"confidence_sizing_range": (float, 0.1, 1.0),
"staleness_decay_per_day": (float, 0.0, 0.2),
"earnings_sizing_reduction": (float, 0.0, 1.0),
"earnings_proximity_days": (int, 1, 30),
"momentum_gate_threshold": (float, -30, 0),
"correlation_block_threshold": (float, 0.3, 1.0),
"profit_take_pct": (float, 0.05, 1.0),
"momentum_exit_threshold": (float, -50, 0),
}
_EXECUTOR_PARAMS_CACHE_PATH = Path(__file__).resolve().parent.parent / "config" / ".executor_params_cache.json"
def _load_executor_params_from_s3(bucket: str) -> dict | None:
"""Read config/executor_params.json from S3. Cache per cold-start.
Fallback chain: S3 → local cache file → None (hardcoded defaults).
On successful S3 read, writes a local cache so the last known optimal
params survive transient S3 failures.
"""
global _executor_params_cache, _executor_params_loaded
if _executor_params_loaded:
return _executor_params_cache
_executor_params_loaded = True
try:
import json
import boto3
s3 = boto3.client("s3")
obj = s3.get_object(Bucket=bucket, Key="config/executor_params.json")
data = json.loads(obj["Body"].read())
# Advisory schema validation (log warnings, never block)
_unknown_keys = [k for k in data if k not in _PARAM_MAP and k not in (
"disabled_triggers", "use_p_up_sizing", "p_up_sizing_blend",
"updated_at", "best_sharpe", "best_alpha", "improvement_pct",
"n_combos_tested", "manual_override",
)]
if _unknown_keys:
logger.warning("executor_params.json contains unknown keys: %s", _unknown_keys)
# Only keep safe-to-override params (numeric) + special non-numeric params
safe = {k: v for k, v in data.items() if k in _PARAM_MAP}
# Phase 4 non-numeric params: disabled_triggers (list), p_up sizing (bool)
for special_key in ("disabled_triggers", "use_p_up_sizing", "p_up_sizing_blend"):
if special_key in data:
safe[special_key] = data[special_key]
if safe:
logger.info("Loaded executor params from S3: %s", safe)
_executor_params_cache = safe
# Persist to local cache for fault tolerance
try:
_EXECUTOR_PARAMS_CACHE_PATH.write_text(json.dumps(safe, indent=2))
except Exception:
logger.debug("Failed to write executor params cache", exc_info=True)
return _executor_params_cache
except Exception as e:
logger.warning("Could not read executor params from S3: %s", e)
# Fallback: last known optimal from local cache
try:
if _EXECUTOR_PARAMS_CACHE_PATH.exists():
import json
data = json.loads(_EXECUTOR_PARAMS_CACHE_PATH.read_text())
safe = {k: v for k, v in data.items() if k in _PARAM_MAP}
if safe:
logger.info("Loaded executor params from local cache (last known optimal): %s", safe)
_executor_params_cache = safe
return _executor_params_cache
except Exception as e2:
logger.warning("Could not read local executor params cache: %s", e2)
logger.warning("Both S3 and local cache failed for executor params — using hardcoded defaults")
return None
def _merge_s3_params(config: dict, s3_params: dict) -> dict[str, Any]:
"""Merge flat S3 param names into nested config structure with validation."""
for param, value in s3_params.items():
# Phase 4 non-numeric params: merge directly into top-level config
if param == "disabled_triggers" and isinstance(value, list):
config.setdefault("intraday", {}).setdefault("entry_triggers", {})["disabled_triggers"] = value
logger.info("S3 disabled_triggers: %s", value)
continue
if param == "use_p_up_sizing" and isinstance(value, bool):
config["use_p_up_sizing"] = value
logger.info("S3 use_p_up_sizing: %s", value)
continue
if param == "p_up_sizing_blend" and isinstance(value, (int, float)):
config["p_up_sizing_blend"] = float(value)
continue
path = _PARAM_MAP.get(param)
if not path:
continue
validator = _PARAM_VALIDATORS.get(param)
if validator:
expected_type, lo, hi = validator
if not isinstance(value, (int, float)):
logger.warning("S3 param %s: invalid type %s — skipping", param, type(value).__name__)
continue
value = expected_type(value)
if not (lo <= value <= hi):
logger.warning("S3 param %s=%s out of range [%s, %s] — skipping", param, value, lo, hi)
continue
target = config
for key in path[:-1]:
target = target.setdefault(key, {})
target[path[-1]] = value
return config
_LOAD_CONFIG_CACHE: dict | None = None
def load_config() -> dict:
"""Load and return the risk.yaml config dict.
Cached for the process lifetime: risk.yaml is read-only at runtime
and re-reading on every call wastes ~20 ms per executor.run()
invocation. Live executor calls this once per boot, so caching is a
no-op there. Backtester loops 100k+ times per predictor_param_sweep,
so per-call cache hit drops the load_config cost from ~1 sec total
(50-call profile) to ~1 ms.
A deep copy is returned so that the per-call config_override merge
in run() (which mutates nested ``config["strategy"][...]`` dicts)
can't pollute the cache. Deepcopy of a ~30-key nested dict is sub-
millisecond — much cheaper than re-parsing YAML.
Tests that need to override the config path can clear the cache by
setting ``executor.main._LOAD_CONFIG_CACHE = None`` before invoking
``load_config()``.
"""
global _LOAD_CONFIG_CACHE
import copy
if _LOAD_CONFIG_CACHE is None:
with open(get_config_path()) as f:
_LOAD_CONFIG_CACHE = yaml.safe_load(f)
return copy.deepcopy(_LOAD_CONFIG_CACHE)
def _compute_support_level(price_history, strategy_config: dict) -> float | None:
"""Compute N-day low from price history for support-bounce entry trigger.
Accepts a pandas DataFrame indexed by date with a ``low`` column.
"""
lookback = strategy_config.get("intraday_support_lookback_days", 20)
if price_history is None or len(price_history) < lookback:
return None
lows = price_history["low"].iloc[-lookback:]
# Drop zeros/NaNs the way the prior list-based path did via ``if bar.get("low")``
valid = lows[(lows.notna()) & (lows > 0)]
if valid.empty:
return None
return float(valid.min())
def _read_signals(
config: dict,
signals_bucket: str,
run_date: str,
simulate: bool,
signals_override: dict | None,
conn,
) -> tuple[dict, dict, str, dict, str | None]:
"""Read and validate signals from S3 or override.
Returns ``(signals_raw, signals, run_date, predictions_by_ticker,
predictions_date)``. ``predictions_date`` is the
``predictor/predictions/{date}.json`` filename date the GBM run
produced (None if predictions weren't loaded — simulate mode or S3
miss); ``signals_raw["date"]`` is the corresponding signals.json
filename date and is read directly off ``signals_raw`` by callers
that need it.
"""
if signals_override is not None:
signals_raw = signals_override
run_date = signals_raw.get("date", run_date)
else:
try:
signals_raw = read_signals_with_fallback(signals_bucket, run_date)
except RuntimeError as e:
logger.error(f"Cannot proceed without signals: {e}")
if conn:
conn.close()
raise
# Defense-in-depth universe filter — drop buy_candidates whose tickers
# aren't in the ArcticDB universe library. Research's population_selector
# (alpha-engine-research#41) is the primary guardrail; this catches
# anything that slipped past (manual edits, Research bug, universe-drift
# window). See filter_buy_candidates_to_universe for scope + rationale.
#
# Skipped in simulate mode (2026-04-27): the backtester already
# pre-filters signals against the ArcticDB universe ONCE at the
# simulation-loop bootstrap (``backtest.py:_run_simulation_loop``
# line 826 calls ``get_universe_symbols`` once, then per-date
# ``_simulate_single_date`` runs ``_filter_signals_to_universe`` against
# that set). Re-running the filter inside ``_read_signals`` would
# call ``universe_lib.list_symbols()`` per signal date — an
# ArcticDB round-trip the profile measured at ~424 ms/call, which
# blew the predictor_param_sweep budget. Live executor still pays
# the per-call cost (runs once per trading day, where the cost is
# negligible).
if not simulate:
from executor.signal_reader import filter_buy_candidates_to_universe
signals_raw = filter_buy_candidates_to_universe(signals_raw, signals_bucket)
# Admission gate — refuse buy_candidates below hard coverage floor
# (default 0.30). Companion to the position sizer's coverage derate:
# the derate handles partial-coverage tickers gracefully, this gate
# refuses tickers whose coverage is so low that no amount of derating
# produces a trustworthy signal (pure pre-history IPOs, OHLCV-only
# symbols, etc.). Held positions exempt — admission applies to ENTRY
# only, not to unwinding existing exposure. Skipped in simulate mode
# to preserve backtester replay parity against historical signals.
if not simulate and config.get("coverage_admission_enabled", True):
from executor.signal_reader import filter_buy_candidates_by_coverage
from executor.price_cache import load_feature_coverage
buy_tickers = [
e.get("ticker") for e in (signals_raw.get("buy_candidates") or [])
if isinstance(e, dict) and e.get("ticker")
]
if buy_tickers:
min_cov = float(config.get("min_coverage_for_admission", 0.30))
try:
cov_map = load_feature_coverage(buy_tickers, signals_bucket)
signals_raw = filter_buy_candidates_by_coverage(
signals_raw, cov_map, min_coverage=min_cov,
)
except RuntimeError as exc:
# ArcticDB unreachable — same posture as other preflight
# reads: hard-fail, don't silently admit everything.
logger.error("Admission gate failed on ArcticDB read: %s", exc)
raise
if not simulate:
from executor.signal_reader import patch_unknown_sectors_with_constituents
try:
n_patched = patch_unknown_sectors_with_constituents(signals_raw, signals_bucket)
if n_patched:
logger.warning(
"[sector_fallback] Backfilled %d sectors from constituents.json "
"(research signals.json escape from alpha-engine-research#126)",
n_patched,
)
except Exception as e:
logger.warning("Sector backfill skipped: %s", e)
signals = get_actionable_signals(signals_raw)
# Alert if signals are stale (research didn't run recently)
if not simulate:
try:
signals_date_raw = signals_raw.get("date", run_date)
_sig_age = (date.fromisoformat(run_date) - date.fromisoformat(signals_date_raw)).days
if _sig_age > 2:
from executor.notifier import send_daemon_status
send_daemon_status(
f"\u26a0\ufe0f *Stale signals*\n"
f"Using signals from {signals_date_raw} ({_sig_age} days old)\n"
f"Research may not have run this week."
)
except Exception:
logger.debug("Stale signals Telegram notification failed", exc_info=True)
# Load GBM predictions for rationale capture
predictions_date: str | None = None
if not simulate:
try:
from executor.signal_reader import read_predictions
predictions_by_ticker, predictions_date = read_predictions(signals_bucket)
except Exception as e:
logger.warning("Failed to load GBM predictions: %s", e)
predictions_by_ticker = {}
else:
predictions_by_ticker = {}
# Coverage guard: every buy_candidate must have a prediction row, otherwise
# the GBM veto gate is structurally unreachable for that ticker and we'd
# be sizing positions around a risk control. Skip in simulate mode (no
# live trading, predictions intentionally empty). The weekday Step Function
# coverage-gap Choice state is the self-healing mechanism; this guard is
# read-time defense-in-depth. Always emits CloudWatch metric (value 0 on
# success) so the alarm baseline is continuous.
if not simulate:
from executor.signal_reader import assert_predictions_cover_buy_candidates
assert_predictions_cover_buy_candidates(signals_raw, predictions_by_ticker)
logger.info(
f"Signals | regime={signals['market_regime']} "
f"| ENTER={len(signals['enter'])} EXIT={len(signals['exit'])} "
f"REDUCE={len(signals['reduce'])} HOLD={len(signals['hold'])}"
)
return signals_raw, signals, run_date, predictions_by_ticker, predictions_date
def _plan_entries(
enter_signals: list[dict],
signals_raw: dict,
predictions_by_ticker: dict,
config: dict,
strategy_config: dict,
market_regime: str,
sector_ratings: dict,
ibkr,
portfolio_nav: float,
peak_nav: float,
current_positions: dict,
price_histories: dict | None,
atr_map: dict,
dd_multiplier: float,
signal_age_days: int,
earnings_by_ticker: dict,
vwap_map: dict,
coverage_map: dict,
ob: OrderBook,
run_date: str,
dry_run: bool,
simulate: bool,
predictions_date: str | None = None,
regime_intensity_z: float | None = None,
) -> tuple[int, list[dict], list[dict], list[dict]]:
"""Live-shell wrapper around ``executor.deciders.decide_entries``.
Resolves ``prices_now`` from the IB / sim client, calls the pure
decider, and dispatches results:
* simulate: ``ibkr.place_market_order`` per accepted entry to
accumulate sim_client position state across dates.
* live (not simulate, not dry_run): ``ob.add_entry`` per
``entries_with_meta`` to write the daemon's order book.
* dry_run: log only, no side effects.
Returns ``(n_entered, orders, blocked, risk_events)``. The fourth
element is the structured veto/override log emitted by
``decide_entries`` (Phase 2 transparency-inventory). Caller persists
via ``trade_logger.log_risk_event``.
"""
from executor.deciders import decide_entries
# Resolve prices_now from IB/sim client up-front so the decider is
# broker-agnostic. For each enter signal we need the price; we
# also tolerate missing prices (the decider treats them as
# "no price available — skip").
prices_now: dict[str, float] = {}
for sig in enter_signals:
t = sig.get("ticker")
if not t:
continue
p = ibkr.get_current_price(t)
if p is not None:
prices_now[t] = p
plan = decide_entries(
enter_signals=enter_signals,
signals_raw=signals_raw,
predictions_by_ticker=predictions_by_ticker,
config=config,
strategy_config=strategy_config,
market_regime=market_regime,
sector_ratings=sector_ratings,
portfolio_nav=portfolio_nav,
peak_nav=peak_nav,
current_positions=current_positions,
prices_now=prices_now,
price_histories=price_histories,
atr_map=atr_map,
vwap_map=vwap_map,
coverage_map=coverage_map,
dd_multiplier=dd_multiplier,
signal_age_days=signal_age_days,
earnings_by_ticker=earnings_by_ticker,
run_date=run_date,
predictions_date=predictions_date,
regime_intensity_z=regime_intensity_z,
)
# Dispatch decisions to side-effecting layer.
if simulate:
# Accumulate sim_client position state for next-iteration
# already-held check. See plan.orders comment in deciders.py.
for o in plan.orders:
if o["action"] == "ENTER":
ibkr.place_market_order(o["ticker"], "BUY", o["shares"])
elif not dry_run:
# Live: persist each entry-with-meta to the daemon's order book.
for entry in plan.entries_with_meta:
ob.add_entry(entry)
return plan.n_entered, plan.orders, plan.blocked, plan.risk_events
def _plan_exits_and_reduces(
signals: dict,
strategy_exits: list[dict],
predictions_by_ticker: dict,
current_positions: dict,
ibkr,
portfolio_nav: float,
config: dict,
market_regime: str,
ob: OrderBook,
run_date: str,
dry_run: bool,
simulate: bool,
signals_date: str | None = None,
predictions_date: str | None = None,
) -> list[dict]:
"""Live-shell wrapper around ``executor.deciders.decide_exits_and_reduces``.
Resolves prices_now from IB / sim client, calls the pure decider,
and dispatches results to side-effecting layer:
* simulate: ``ibkr.place_market_order(SELL)`` per accepted exit/reduce
* live: ``ob.add_urgent_exit`` per ``urgent_exits_with_meta``
* dry_run: log only
Returns the orders list (populated in simulate mode for accumulator).
"""
from executor.deciders import decide_exits_and_reduces
# Tickers we may need a price for (held positions referenced by
# exit / reduce signals). Resolve via ibkr; missing prices fall
# back to avg_cost inside the decider.
candidate_tickers: set[str] = set()
for sig in signals.get("exit", []) + signals.get("reduce", []):
t = sig.get("ticker")
if t:
candidate_tickers.add(t)
for sig in strategy_exits:
t = sig.get("ticker")
if t:
candidate_tickers.add(t)
prices_now: dict[str, float] = {}
for t in candidate_tickers:
if t not in current_positions:
continue
p = ibkr.get_current_price(t)
if p is not None:
prices_now[t] = p
plan = decide_exits_and_reduces(
signals=signals,
strategy_exits=strategy_exits,
current_positions=current_positions,
prices_now=prices_now,
predictions_by_ticker=predictions_by_ticker,
config=config,
market_regime=market_regime,
portfolio_nav=portfolio_nav,
run_date=run_date,
signals_date=signals_date,
predictions_date=predictions_date,
)
if simulate:
# Apply orders to sim_client so position state carries to next sim date.
for o in plan.orders:
if o["action"] == "EXIT":
ibkr.place_market_order(o["ticker"], "SELL", o["shares"])
elif o["action"] == "REDUCE":
ibkr.place_market_order(o["ticker"], "SELL", o["shares"])
elif not dry_run:
for entry in plan.urgent_exits_with_meta:
ob.add_urgent_exit(entry)
return plan.orders
def _write_order_book_summary(
ob: OrderBook,
blocked_entries: list[dict] | None,
signals_bucket: str,
run_date: str,
) -> None:
"""Write a public-safe order book summary to S3 for the dashboard."""
import boto3
summary = {
"date": run_date,
"entries_approved": [
{"ticker": e["ticker"]} for e in ob.pending_entries()
],
"entries_blocked": [
{"ticker": b["ticker"], "reason": b.get("block_reason", b.get("reason", "unknown"))}
for b in (blocked_entries or [])
],
"exits": [
{"ticker": e["ticker"], "reason": e.get("reason", "research_signal")}
for e in ob.pending_urgent_exits()
if e.get("signal") != "COVER"
],
"covers": [
{"ticker": e["ticker"]}
for e in ob.pending_urgent_exits()
if e.get("signal") == "COVER"
],
}
try:
s3 = boto3.client("s3")
key = f"order_books/{run_date}/summary.json"
s3.put_object(
Bucket=signals_bucket,
Key=key,
Body=json.dumps(summary, indent=2),
ContentType="application/json",
)
logger.info("Order book summary written to s3://%s/%s", signals_bucket, key)
except Exception as e:
logger.warning("Failed to write order book summary (non-fatal): %s", e)
def _write_stops_and_finalize(
ibkr,
ob: OrderBook,
price_histories: dict | None,
atr_map: dict,
strategy_config: dict,
conn,
run_date: str,
blocked_entries: list[dict] | None = None,
signals_bucket: str | None = None,
) -> None:
"""Write stop records for held positions, detect shorts, save order book, notify."""
# ATR previously computed inline via _compute_atr(ticker_hist). Since
# 2026-04-16 the executor reads atr_14_pct from the feature-store map
# (load_atr_14_pct in main()) — same definition the predictor and sizing
# path use. atr_dollar derives from entry_price × atr_pct so trailing stops
# stay in dollar-denominated semantics (bracket_orders consumes dollars).
# Add stop records for all current positions
current_pos = ibkr.get_positions()
for t, pos in current_pos.items():
pos_shares = int(pos.get("shares", 0))
if pos_shares <= 0:
continue
# Skip tickers with pending urgent exits
urgent_exit_tickers = {u["ticker"] for u in ob.pending_urgent_exits()}
if t in urgent_exit_tickers:
continue
entry_price = pos.get("avg_cost", 0)
atr_mult = strategy_config.get("intraday_trailing_stop_atr_multiple", 2.0)
ticker_atr_pct = atr_map.get(t)
if not ticker_atr_pct or ticker_atr_pct <= 0 or entry_price <= 0:
# load_atr_14_pct's hard-fail covers signal tickers + held positions
# at the top of main(); if we still hit a missing value here it's
# either a position that wasn't in the held-set at ATR load time
# (race condition) or entry_price <=0 from IBKR — skip this stop.
logger.warning(
"No ATR or invalid entry_price for %s — skipping stop (atr_pct=%s, entry_price=%s)",
t, ticker_atr_pct, entry_price,
)
continue
atr_val = ticker_atr_pct * entry_price
stop_price = round(entry_price - atr_val * atr_mult, 2)
ob.add_stop({
"ticker": t,
"entry_price": entry_price,
"current_stop": stop_price,
"trail_atr": atr_val or 0,
"atr_multiple": atr_mult,
"high_water": entry_price,
"entry_date": (conn and get_entry_dates(conn, [t]).get(t)) or run_date,
"shares": pos_shares,
})
# Detect short positions and add urgent cover orders
for t, pos in current_pos.items():
pos_shares = int(pos.get("shares", 0))
if pos_shares < 0:
cover_shares = abs(pos_shares)
logger.warning(
"SHORT DETECTED: %s has %d shares — adding urgent COVER for %d shares",
t, pos_shares, cover_shares,
)
ob.add_urgent_exit({
"ticker": t,
"signal": "COVER",
"shares": cover_shares,
"reason": "short_position_cover",
"detail": f"Covering accidental short of {cover_shares} shares",
})
ob.save()
# Backup full order book to S3 for audit trail
if signals_bucket:
ob.backup_to_s3(signals_bucket, run_date)
# Write public-safe summary for dashboard
if signals_bucket:
_write_order_book_summary(ob, blocked_entries, signals_bucket, run_date)
n_entries = len(ob.pending_entries())
n_urgent = len(ob.pending_urgent_exits())
n_stops = len(ob.active_stops())
n_covers = sum(1 for u in ob.pending_urgent_exits() if u.get("signal") == "COVER")
logger.info(
"Order book written: %d entries, %d urgent exits (%d covers), %d stops",
n_entries, n_urgent, n_covers, n_stops,
)
# Build notification with blocked entry transparency
blocked_lines = ""
if blocked_entries:
blocked_lines = f"\nBlocked ({len(blocked_entries)}):\n"
for b in blocked_entries:
blocked_lines += f" {b['ticker']}: {b.get('block_reason', b.get('reason', 'unknown'))}\n"
try:
from executor.notifier import send_daemon_status
send_daemon_status(
f"\u2705 *Order book written*\n"
f"Date: {run_date}\n"
f"Entries: {n_entries} | Urgent exits: {n_urgent} | Stops: {n_stops}"
f"{blocked_lines}"
)
except Exception:
logger.debug("Order book Telegram notification failed", exc_info=True)
def run(
dry_run: bool = False,
simulate: bool = False,
ibkr_client=None, # injected by backtester when simulate=True
signals_override: dict = None, # injected signals dict (skips S3 read)
price_histories: dict = None, # injected by backtester for exit manager
config_override: dict = None, # injected by backtester param sweep
atr_map: dict | None = None, # injected by backtester to skip per-call ArcticDB read
vwap_map: dict | None = None, # injected by backtester to skip per-call ArcticDB read
coverage_map: dict | None = None, # injected by backtester to skip per-call ArcticDB read
) -> list[dict] | None:
"""
Returns list of order dicts when simulate=True, else None.
All other behaviour (risk guard, position sizer, trade logger) is unchanged.
"""
orders = []
run_date = str(date.today())
_health_start = _time.time()
logger.info(f"Executor starting | date={run_date} | dry_run={dry_run} | simulate={simulate}")
config = load_config()
if config_override:
for key, val in config_override.items():
if key == "strategy" and isinstance(val, dict) and "strategy" in config:
for sub_key, sub_val in val.items():
if isinstance(sub_val, dict) and isinstance(config["strategy"].get(sub_key), dict):
config["strategy"][sub_key].update(sub_val)
else:
config["strategy"][sub_key] = sub_val
elif key in _PARAM_MAP:
# Route flat param names through the same mapping as S3 params
# so backtester sweep keys (e.g. "min_score") land in the right
# nested config location (e.g. "min_score_to_enter").
path = _PARAM_MAP[key]
target = config
for p in path[:-1]:
target = target.setdefault(p, {})
target[path[-1]] = val
else:
config[key] = val
# Merge S3-delivered params (backtester recommendations) if not in simulate mode
if not simulate and not config_override:
s3_params = _load_executor_params_from_s3(config.get("signals_bucket", "alpha-engine-research"))
if s3_params:
config = _merge_s3_params(config, s3_params)
db_path = config["db_path"]
signals_bucket = config["signals_bucket"]
trades_bucket = config["trades_bucket"]
# Preflight: AWS_REGION + S3 bucket reachable. Skip in simulate mode
# (backtester injects orders directly, no real S3 interaction).
# Raises RuntimeError on failure → propagates to non-zero exit.
if not simulate:
from executor.preflight import ExecutorPreflight
ExecutorPreflight(bucket=signals_bucket, mode="main").run()
# ── Flow Doctor: retrieve the shared instance set up at module import ───
from alpha_engine_lib.logging import get_flow_doctor
fd = get_flow_doctor() if not simulate else None
# ── 0. Check upstream health — hard-fail if anything upstream is broken ──
# Running on stale signals or a failed predictor produces a degraded
# portfolio that contradicts the system's design. Per the "hard-fail until
# stable" standard, any unknown/failed/stale upstream must abort executor
# BEFORE we read signals or touch the order book. The trading instance
# will remain idle for the day and be stopped at 13:30 PT as usual.
# Per-module staleness tolerance (hours):
# research — 192h (runs weekly Sat; grace covers Sat→next Fri)
# predictor_inference — 26h (runs every weekday morning; catches a Mon
# miss without false-alarming on the weekend)
# daily_data — 26h (same weekday 13:05 UTC cadence as predictor;
# stamp written by alpha-engine-data after
# daily_closes.collect — catches ran-and-failed
# states that the direct LastModified check
# below would miss)
_UPSTREAM_MAX_AGE_H = {"research": 192, "predictor_inference": 26, "daily_data": 26}
if not simulate:
_health_failures: list[str] = []
try:
from executor.health_status import check_upstream_health
# Pass the loosest module tolerance as the library default so
# check_upstream_health doesn't prematurely mark research stale;
# we re-check per-module against _UPSTREAM_MAX_AGE_H below.
upstream = check_upstream_health(
signals_bucket,
list(_UPSTREAM_MAX_AGE_H),
max_age_hours=max(_UPSTREAM_MAX_AGE_H.values()),
)
except Exception as _ue:
# A health-check read failure is itself a reason to hard-fail —
# we don't know the state of upstream, so we refuse to trade.
upstream = {}
_health_failures.append(f"health-check error: {_ue}")
for mod, max_hrs in _UPSTREAM_MAX_AGE_H.items():
info = upstream.get(mod)
if info is None:
_health_failures.append(f"{mod}: no health data returned")
continue
if info["status"] == "unknown":
_health_failures.append(f"{mod}: no health data found")
elif info["status"] == "failed":
_health_failures.append(f"{mod}: last run FAILED")
elif info["age_hours"] is None or info["age_hours"] < 0:
_health_failures.append(f"{mod}: last_success missing")
elif info["age_hours"] > max_hrs:
_health_failures.append(
f"{mod}: {info['age_hours']:.0f}h ({info['age_hours']/24:.1f}d) stale "
f"(max {max_hrs}h)"
)
if _health_failures:
msg = (
"Upstream health FAILED — executor aborting:\n"
+ "\n".join(f" - {w}" for w in _health_failures)
)
logger.error(msg)
try:
from executor.notifier import send_daemon_status
send_daemon_status(
"\u274c *Upstream health FAILED*\n"
f"Date: {run_date}\n"
+ "\n".join(f"- {w}" for w in _health_failures)
+ "\n\nExecutor aborted — no order book written."
)
except Exception:
logger.debug("Upstream failure Telegram notification failed", exc_info=True)
raise RuntimeError(msg)
# Direct freshness check on the ArcticDB macro library. The
# stamp-based check_upstream_health above covers predictor/research
# "did it run"; this catches the "stamp green but data blob is
# yesterday's" failure mode (partial writes, retries skipping
# DataPhase1). SPY is the canary — written by the daily_append
# post-close job to the macro library (NOT universe). If SPY has
# no row for the last closed trading day, the post-close pipeline
# did not complete and the executor must abort before any signals
# are read.
try:
import pandas as _pd
from executor.price_cache import _open_macro_library
from alpha_engine_lib.trading_calendar import last_closed_trading_day
_macro = _open_macro_library(signals_bucket)
_spy_df = _macro.read("SPY").data
_expected_min = _pd.Timestamp(last_closed_trading_day()).normalize()
_idx = _spy_df.index.normalize() if hasattr(_spy_df.index, "normalize") else _spy_df.index
if _spy_df.empty or (_idx >= _expected_min).sum() == 0:
_latest = _pd.Timestamp(_spy_df.index[-1]).date() if not _spy_df.empty else "EMPTY"
raise RuntimeError(
f"ArcticDB macro has no SPY row >= {_expected_min.date()} "
f"(latest: {_latest}). Post-close daily-data job did not "
f"complete for the last closed trading day."
)
except Exception as _freshness_err:
msg = f"ArcticDB freshness check FAILED — executor aborting: {_freshness_err}"
logger.error(msg)
try:
from executor.notifier import send_daemon_status
send_daemon_status(
"\u274c *ArcticDB universe stale/missing*\n"
f"Date: {run_date}\n"
f"{_freshness_err}\n\nExecutor aborted — no order book written."
)
except Exception:
logger.debug("ArcticDB freshness Telegram notification failed", exc_info=True)
raise RuntimeError(msg) from _freshness_err
conn = None if simulate else init_db(db_path)
# ── 1. Read signals from S3 (or use injected override) ──────────────────
try:
signals_raw, signals, run_date, predictions_by_ticker, predictions_date = _read_signals(
config, signals_bucket, run_date, simulate, signals_override, conn,
)
except Exception as _sig_err:
if fd:
fd.report(_sig_err, severity="error", context={
"site": "signal_read", "run_date": run_date})
if conn:
conn.close()
# Re-raise so systemd marks the service as 'failed' (not 'inactive (dead)').
# Returning silently hides signal-read failures from systemctl status, which
# is how today's (2026-04-10) incident went undetected for 3 hours.
raise
market_regime = signals["market_regime"]
sector_ratings = signals["sector_ratings"]
# ── 2. Connect to IBKR (or use injected simulated client) ───────────────
if simulate:
ibkr = ibkr_client
else:
ibkr = IBKRClient(
host=config["ibkr_host"],
port=config["ibkr_port"],
client_id=config["ibkr_client_id"],
reconnect_attempts=config.get("ibkr_reconnect_attempts", 3),
)
try:
portfolio_nav = ibkr.get_portfolio_nav()
current_positions = ibkr.get_positions()
peak_nav = ibkr.get_peak_nav(conn)
# Enrich positions with sector data from signals
universe_sectors = {
s["ticker"]: s.get("sector", "")
for s in signals_raw.get("universe", []) + signals_raw.get("buy_candidates", [])
if s.get("ticker")
}
for ticker, pos in current_positions.items():
pos["sector"] = universe_sectors.get(ticker, "")
# ── 2b. Enrich positions with entry_date from trades.db ──────────────────
# Also pulls stance + catalyst_date (stance taxonomy arc 2026-05-11):
# exit_manager.evaluate_exits reads pos["stance"] / pos["catalyst_date"]
# to apply stance-conditional exit rules (ATR multiplier override,
# time-decay disable for quality/catalyst, hard exit at
# catalyst_date+3d for catalyst). NULL for legacy positions logged
# before this PR — falls through to baseline behavior.
if conn and current_positions:
from executor.trade_logger import get_entry_stance_and_catalyst
entry_dates = get_entry_dates(conn, list(current_positions.keys()))
stance_lookup = get_entry_stance_and_catalyst(
conn, list(current_positions.keys()),
)
for ticker, pos in current_positions.items():
pos["entry_date"] = entry_dates.get(ticker)
stance_info = stance_lookup.get(ticker, {})
pos["stance"] = stance_info.get("stance")
pos["catalyst_date"] = stance_info.get("catalyst_date")
logger.info(f"Entry dates resolved for {len(entry_dates)}/{len(current_positions)} positions")
# ── 2b'. Resolve regime substrate ONCE per planning cycle ──────────────
# Used by Wire 2 (position_sizer regime multiplier) AND Wire 3
# (regime-aware drawdown tiers). Gated by either flag so the
# read is skipped entirely when both wires are off — avoids
# per-cycle S3 GET when neither feature is active. Returns None
# on any failure mode; both wires degrade to legacy behavior
# under None.
regime_intensity_z: float | None = None
if (
(config.get("regime_sizing_enabled", False)
or config.get("regime_drawdown_enabled", False))
and not simulate
):
try:
from executor.signal_reader import (
extract_intensity_z,
read_regime_substrate,
)
substrate = read_regime_substrate(signals_bucket)
regime_intensity_z = extract_intensity_z(substrate)
logger.info(
"regime wires enabled | intensity_z=%s",
f"{regime_intensity_z:.3f}" if regime_intensity_z is not None else "None",
)
except Exception as _rs_err:
logger.warning(
"regime substrate read failed (%s) — falling back to legacy behavior",
_rs_err,
)
regime_intensity_z = None
# ── 2b''. Resolve daily fast-signal forced-bear latch (F2) ─────────────
# regime-fast-signal-260515.md Stage F2. The daily BOCPD