-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1262 lines (1104 loc) · 46.6 KB
/
main.py
File metadata and controls
1262 lines (1104 loc) · 46.6 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
"""IBKR strategy runner for shared us_equity strategy profiles."""
import os
import threading
import time
import traceback
from datetime import datetime
from zoneinfo import ZoneInfo
import google.auth
import pandas as pd
import requests
from flask import Flask, request
try:
from google.cloud import compute_v1
except ImportError:
compute_v1 = None
from application.cycle_result import coerce_strategy_cycle_result
from application.runtime_broker_adapters import build_runtime_broker_adapters
from application.runtime_composer import build_runtime_composer
from application.runtime_strategy_adapters import (
build_runtime_strategy_adapters,
fetch_yfinance_historical_candles,
)
from application.rebalance_service import run_strategy_core as run_rebalance_cycle
from application.signal_snapshot import build_signal_snapshot
from decision_mapper import map_strategy_decision
from entrypoints.cloud_run import is_market_open_today
from notifications.telegram import build_strategy_display_name, build_translator, send_telegram_message
from quant_platform_kit.notifications.strategy_plugin_alerts import (
StrategyPluginAlertStateSettings,
build_strategy_plugin_alert_context_label as build_alert_context_label,
publish_strategy_plugin_alerts as dispatch_strategy_plugin_alerts,
)
from quant_platform_kit.common.runtime_assembly import build_runtime_assembly
from quant_platform_kit.common.runtime_reports import (
append_runtime_report_error,
build_runtime_report_base,
finalize_runtime_report,
persist_runtime_report,
)
from quant_platform_kit.common.strategy_plugins import (
build_strategy_plugin_report_payload,
load_configured_strategy_plugin_signals,
parse_strategy_plugin_mounts,
)
from quant_platform_kit.ibkr import (
connect_ib as ibkr_connect_ib,
ensure_event_loop as ibkr_ensure_event_loop,
fetch_historical_price_candles,
fetch_historical_price_series,
fetch_quote_snapshots,
)
from application.ibkr_order_execution import submit_order_intent
from application.ibkr_portfolio import fetch_portfolio_snapshot
from application.execution_service import (
check_order_submitted as application_check_order_submitted,
execute_rebalance as application_execute_rebalance,
get_market_prices as application_get_market_prices,
)
from application.paper_liquidation_service import execute_paper_liquidation
from runtime_logging import build_run_id, emit_runtime_log, extract_cloud_trace
from runtime_config_support import (
EXECUTION_BACKEND_GATEWAY,
load_platform_runtime_settings,
resolve_ib_gateway_ip_mode,
)
from strategy_runtime import load_strategy_runtime
app = Flask(__name__)
ensure_event_loop = ibkr_ensure_event_loop
NEW_YORK_TZ = ZoneInfo("America/New_York")
STRATEGY_RUN_LOCK = threading.Lock()
def get_project_id():
try:
_, project_id = google.auth.default()
return project_id if project_id else os.getenv("GOOGLE_CLOUD_PROJECT")
except Exception:
return os.getenv("GOOGLE_CLOUD_PROJECT")
def get_ib_gateway_ip_mode():
raw_value = os.getenv("IB_GATEWAY_IP_MODE")
if raw_value is None and "RUNTIME_SETTINGS" in globals():
raw_value = RUNTIME_SETTINGS.ib_gateway_ip_mode
return resolve_ib_gateway_ip_mode(
raw_value,
logger=lambda message: print(message, flush=True),
)
def resolve_gce_instance_ip(instance_name, zone):
if not compute_v1:
print(f"google-cloud-compute not installed, using {instance_name} as host directly", flush=True)
return instance_name
try:
ip_mode = get_ib_gateway_ip_mode()
project = get_project_id()
client = compute_v1.InstancesClient()
instance = client.get(project=project, zone=zone, instance=instance_name)
internal_ip = None
external_ip = None
for iface in instance.network_interfaces:
if iface.network_i_p:
internal_ip = iface.network_i_p
for ac in iface.access_configs:
if ac.nat_i_p:
external_ip = ac.nat_i_p
candidates = (
(("internal", internal_ip), ("external", external_ip))
if ip_mode == "internal"
else (("external", external_ip), ("internal", internal_ip))
)
for label, ip in candidates:
if ip:
print(f"Resolved {instance_name} → {ip} ({label}, mode={ip_mode})", flush=True)
return ip
except Exception as exc:
print(f"GCE resolve failed for {instance_name}: {exc}, using as hostname", flush=True)
return instance_name
def get_ib_host():
global IB_HOST
if IB_HOST:
return IB_HOST
host = RUNTIME_SETTINGS.ib_gateway_instance_name
zone = RUNTIME_SETTINGS.ib_gateway_zone
if zone:
host = resolve_gce_instance_ip(host, zone)
IB_HOST = host
return host
def get_ib_gateway_mode():
return RUNTIME_SETTINGS.ib_gateway_mode
def get_ib_port():
configured_port = getattr(RUNTIME_SETTINGS, "ib_gateway_port", None)
if configured_port is not None:
return configured_port
return 4002 if get_ib_gateway_mode() == "paper" else 4001
def get_ib_connect_timeout_seconds():
raw_value = os.getenv("IBKR_CONNECT_TIMEOUT_SECONDS", "60")
try:
timeout_seconds = int(raw_value)
except (TypeError, ValueError):
print(f"Invalid IBKR_CONNECT_TIMEOUT_SECONDS={raw_value!r}; using 60", flush=True)
return 60
if timeout_seconds <= 0:
print(f"Invalid IBKR_CONNECT_TIMEOUT_SECONDS={raw_value!r}; using 60", flush=True)
return 60
return timeout_seconds
def get_positive_int_env(name, default):
raw_value = os.getenv(name, str(default))
try:
parsed = int(raw_value)
except (TypeError, ValueError):
print(f"Invalid {name}={raw_value!r}; using {default}", flush=True)
return default
if parsed <= 0:
print(f"Invalid {name}={raw_value!r}; using {default}", flush=True)
return default
return parsed
def get_non_negative_float_env(name, default):
raw_value = os.getenv(name, str(default))
try:
parsed = float(raw_value)
except (TypeError, ValueError):
print(f"Invalid {name}={raw_value!r}; using {default}", flush=True)
return default
if parsed < 0:
print(f"Invalid {name}={raw_value!r}; using {default}", flush=True)
return default
return parsed
def _env_flag(name: str) -> bool:
return str(os.getenv(name) or "").strip().lower() in {"1", "true", "yes", "on"}
def _split_env_list(value: str | None) -> tuple[str, ...]:
return tuple(
item.strip()
for item in str(value or "").replace(";", ",").split(",")
if item.strip()
)
RUNTIME_SETTINGS = load_platform_runtime_settings(project_id_resolver=get_project_id)
IB_HOST = None
IB_PORT = get_ib_port()
IB_CLIENT_ID = RUNTIME_SETTINGS.ib_client_id
IB_CONNECT_TIMEOUT_SECONDS = get_ib_connect_timeout_seconds()
IB_CONNECT_ATTEMPTS = get_positive_int_env("IBKR_CONNECT_ATTEMPTS", 3)
IB_CONNECT_RETRY_DELAY_SECONDS = get_non_negative_float_env("IBKR_CONNECT_RETRY_DELAY_SECONDS", 5.0)
IB_CLIENT_ID_RETRY_OFFSET = get_positive_int_env("IBKR_CLIENT_ID_RETRY_OFFSET", 100)
STRATEGY_PROFILE = RUNTIME_SETTINGS.strategy_profile
STRATEGY_DISPLAY_NAME = RUNTIME_SETTINGS.strategy_display_name
ACCOUNT_GROUP = RUNTIME_SETTINGS.account_group
SERVICE_NAME = RUNTIME_SETTINGS.service_name
ACCOUNT_IDS = RUNTIME_SETTINGS.account_ids
PROJECT_ID = RUNTIME_SETTINGS.project_id
EXECUTION_BACKEND = RUNTIME_SETTINGS.execution_backend
QUANTCONNECT_PROJECT_ID = getattr(RUNTIME_SETTINGS, "quantconnect_project_id", None)
QUANTCONNECT_NODE_ID = getattr(RUNTIME_SETTINGS, "quantconnect_node_id", None)
MARKET = RUNTIME_SETTINGS.market
MARKET_CALENDAR = RUNTIME_SETTINGS.market_calendar
MARKET_CURRENCY = RUNTIME_SETTINGS.market_currency
MARKET_DATA_SYMBOL_SUFFIX = RUNTIME_SETTINGS.market_data_symbol_suffix
MARKET_EXCHANGE = RUNTIME_SETTINGS.market_exchange
MARKET_TIMEZONE = RUNTIME_SETTINGS.market_timezone
STRATEGY_RUNTIME = load_strategy_runtime(
STRATEGY_PROFILE,
runtime_settings=RUNTIME_SETTINGS,
logger=lambda message: print(message, flush=True),
)
STRATEGY_ENTRYPOINT = STRATEGY_RUNTIME.entrypoint
STRATEGY_SIGNAL_SOURCE = (
"feature_snapshot"
if "feature_snapshot" in STRATEGY_RUNTIME.required_inputs
else "market_data"
)
STRATEGY_STATUS_ICON = STRATEGY_RUNTIME.status_icon
SIGNAL_EFFECTIVE_AFTER_TRADING_DAYS = getattr(
getattr(STRATEGY_RUNTIME.runtime_adapter, "runtime_policy", None),
"signal_effective_after_trading_days",
None,
)
FEATURE_RUNTIME_PARAMETERS = dict(STRATEGY_RUNTIME.runtime_config)
STRATEGY_RUNTIME_CONFIG = dict(STRATEGY_RUNTIME.merged_runtime_config)
SAFE_HAVEN = str(STRATEGY_RUNTIME_CONFIG.get("safe_haven") or "BIL")
RANKING_POOL = list(STRATEGY_RUNTIME_CONFIG.get("ranking_pool", ()))
CANARY_ASSETS = list(STRATEGY_RUNTIME_CONFIG.get("canary_assets", ()))
TOP_N = STRATEGY_RUNTIME_CONFIG.get("top_n")
SMA_PERIOD = int(STRATEGY_RUNTIME_CONFIG.get("sma_period", 200))
CANARY_BAD_THRESHOLD = STRATEGY_RUNTIME_CONFIG.get("canary_bad_threshold")
REBALANCE_MONTHS = STRATEGY_RUNTIME_CONFIG.get("rebalance_months")
FEATURE_SNAPSHOT_PATH = RUNTIME_SETTINGS.feature_snapshot_path
FEATURE_SNAPSHOT_MANIFEST_PATH = RUNTIME_SETTINGS.feature_snapshot_manifest_path
FEATURE_RUNTIME_CONFIG_PATH = (
STRATEGY_RUNTIME_CONFIG.get("runtime_config_path")
or RUNTIME_SETTINGS.strategy_config_path
)
FEATURE_RUNTIME_CONFIG_SOURCE = (
STRATEGY_RUNTIME_CONFIG.get("runtime_config_source")
or RUNTIME_SETTINGS.strategy_config_source
)
RECONCILIATION_OUTPUT_PATH = RUNTIME_SETTINGS.reconciliation_output_path
PAPER_LIQUIDATE_ONLY = _env_flag("IBKR_PAPER_LIQUIDATE_ONLY")
TG_TOKEN = RUNTIME_SETTINGS.tg_token
TG_CHAT_ID = RUNTIME_SETTINGS.tg_chat_id
NOTIFY_LANG = RUNTIME_SETTINGS.notify_lang
CASH_RESERVE_RATIO = STRATEGY_RUNTIME.cash_reserve_ratio
CASH_RESERVE_FLOOR_USD = getattr(STRATEGY_RUNTIME, "cash_reserve_floor_usd", 0.0)
REBALANCE_THRESHOLD_RATIO = STRATEGY_RUNTIME.rebalance_threshold_ratio
LIMIT_BUY_PREMIUM = 1.005
SELL_SETTLE_DELAY_SEC = 3
HIST_DATA_PACING_SEC = 0.5
SEPARATOR = "━━━━━━━━━━━━━━━━━━"
def t(key, **kwargs):
return build_translator(NOTIFY_LANG)(key, **kwargs)
strategy_display_name = build_strategy_display_name(t)(
STRATEGY_PROFILE,
fallback_name=STRATEGY_DISPLAY_NAME,
)
RUNTIME_LOG_CONTEXT = build_runtime_assembly(
platform="interactive_brokers",
deploy_target="cloud_run",
service_name=SERVICE_NAME or os.getenv("K_SERVICE", "interactive-brokers-platform"),
strategy_profile=STRATEGY_PROFILE,
runtime_target=RUNTIME_SETTINGS.runtime_target,
account_scope=ACCOUNT_GROUP,
account_group=ACCOUNT_GROUP,
project_id=PROJECT_ID,
instance_name=RUNTIME_SETTINGS.ib_gateway_instance_name,
extra_context_fields={
"account_ids": list(ACCOUNT_IDS),
"strategy_target_mode": RUNTIME_SETTINGS.strategy_target_mode,
"strategy_artifact_dir": RUNTIME_SETTINGS.strategy_artifact_dir,
"strategy_display_name": STRATEGY_DISPLAY_NAME,
"strategy_display_name_localized": strategy_display_name,
"execution_backend": EXECUTION_BACKEND,
"ib_connect_attempts": IB_CONNECT_ATTEMPTS,
"ib_client_id_retry_offset": IB_CLIENT_ID_RETRY_OFFSET,
"quantconnect_project_id": QUANTCONNECT_PROJECT_ID,
"quantconnect_node_id": QUANTCONNECT_NODE_ID,
"market": MARKET,
"market_calendar": MARKET_CALENDAR,
"market_currency": MARKET_CURRENCY,
"market_data_symbol_suffix": MARKET_DATA_SYMBOL_SUFFIX,
"market_exchange": MARKET_EXCHANGE,
"market_timezone": MARKET_TIMEZONE,
},
).build_log_context(run_id="")
def resolve_reporting_managed_symbols() -> tuple[str, ...]:
configured_managed_symbols = STRATEGY_RUNTIME_CONFIG.get("managed_symbols")
fallback_managed_symbols = tuple(dict.fromkeys([*RANKING_POOL, SAFE_HAVEN])) if RANKING_POOL else (SAFE_HAVEN,)
return tuple(
str(symbol)
for symbol in (configured_managed_symbols or fallback_managed_symbols)
if str(symbol or "").strip()
)
def build_strategy_adapters():
return build_runtime_strategy_adapters(
strategy_runtime=STRATEGY_RUNTIME,
strategy_profile=STRATEGY_PROFILE,
translator=t,
pacing_sec=HIST_DATA_PACING_SEC,
resolve_run_as_of_date_fn=resolve_run_as_of_date,
fetch_historical_price_series_fn=fetch_market_historical_price_series,
fetch_historical_price_candles_fn=fetch_market_historical_price_candles,
map_strategy_decision_fn=map_strategy_decision,
fallback_historical_candles_fn=fetch_market_fallback_historical_candles,
build_strategy_plugin_report_payload_fn=build_strategy_plugin_report_payload,
load_configured_strategy_plugin_signals_fn=load_configured_strategy_plugin_signals,
parse_strategy_plugin_mounts_fn=parse_strategy_plugin_mounts,
)
def format_market_data_symbol(symbol: str) -> str:
value = str(symbol or "").strip().upper()
if not value or not MARKET_DATA_SYMBOL_SUFFIX or "." in value:
return value
return f"{value}{MARKET_DATA_SYMBOL_SUFFIX}"
def fetch_market_historical_price_series(ib, symbol, **kwargs):
return fetch_historical_price_series(
ib,
str(symbol).strip().upper(),
exchange=MARKET_EXCHANGE,
currency=MARKET_CURRENCY,
**kwargs,
)
def fetch_market_historical_price_candles(ib, symbol, **kwargs):
return fetch_historical_price_candles(
ib,
str(symbol).strip().upper(),
exchange=MARKET_EXCHANGE,
currency=MARKET_CURRENCY,
**kwargs,
)
def fetch_market_fallback_historical_candles(symbol, **kwargs):
return fetch_yfinance_historical_candles(format_market_data_symbol(symbol), **kwargs)
def fetch_market_quote_snapshots(ib, symbols, **kwargs):
return fetch_quote_snapshots(
ib,
symbols,
exchange=MARKET_EXCHANGE,
currency=MARKET_CURRENCY,
**kwargs,
)
def submit_market_order_intent(ib, order_intent, **kwargs):
return submit_order_intent(
ib,
order_intent,
stock_exchange=MARKET_EXCHANGE,
stock_currency=MARKET_CURRENCY,
**kwargs,
)
def fetch_market_portfolio_snapshot(ib, **kwargs):
return fetch_portfolio_snapshot(ib, currency=MARKET_CURRENCY, **kwargs)
def build_broker_adapters(*, dry_run_only_override: bool | None = None):
effective_dry_run_only = RUNTIME_SETTINGS.dry_run_only if dry_run_only_override is None else bool(dry_run_only_override)
return build_runtime_broker_adapters(
host_resolver=get_ib_host,
ib_port=IB_PORT,
ib_client_id=IB_CLIENT_ID,
connect_timeout_seconds=IB_CONNECT_TIMEOUT_SECONDS,
connect_attempts=IB_CONNECT_ATTEMPTS,
connect_retry_delay_seconds=IB_CONNECT_RETRY_DELAY_SECONDS,
client_id_retry_offset=IB_CLIENT_ID_RETRY_OFFSET,
ensure_event_loop_fn=ensure_event_loop,
connect_ib_fn=ibkr_connect_ib,
fetch_portfolio_snapshot_fn=fetch_market_portfolio_snapshot,
fetch_quote_snapshots_fn=fetch_market_quote_snapshots,
submit_order_intent_fn=submit_market_order_intent,
application_get_market_prices_fn=application_get_market_prices,
application_check_order_submitted_fn=application_check_order_submitted,
application_execute_rebalance_fn=application_execute_rebalance,
execute_paper_liquidation_fn=execute_paper_liquidation,
translator=t,
strategy_profile=STRATEGY_PROFILE,
account_group=ACCOUNT_GROUP,
service_name=SERVICE_NAME,
account_ids=tuple(ACCOUNT_IDS),
dry_run_only=effective_dry_run_only,
cash_reserve_ratio=CASH_RESERVE_RATIO,
cash_reserve_floor_usd=CASH_RESERVE_FLOOR_USD,
rebalance_threshold_ratio=REBALANCE_THRESHOLD_RATIO,
limit_buy_premium=LIMIT_BUY_PREMIUM,
quantity_step=RUNTIME_SETTINGS.quantity_step,
min_order_notional=RUNTIME_SETTINGS.min_order_notional,
safe_haven_cash_substitute_threshold_usd=RUNTIME_SETTINGS.safe_haven_cash_substitute_threshold_usd,
sell_settle_delay_sec=SELL_SETTLE_DELAY_SEC,
separator=SEPARATOR,
strategy_display_name=strategy_display_name,
sleep_fn=time.sleep,
market_currency=MARKET_CURRENCY,
printer=print,
)
def build_composer(*, dry_run_only_override: bool | None = None, strategy_plugin_signals=()):
effective_dry_run_only = RUNTIME_SETTINGS.dry_run_only if dry_run_only_override is None else bool(dry_run_only_override)
def compute_signals_fn(ib, current_holdings):
if strategy_plugin_signals:
return compute_signals(
ib,
current_holdings,
strategy_plugin_signals=strategy_plugin_signals,
)
return compute_signals(ib, current_holdings)
return build_runtime_composer(
service_name=SERVICE_NAME or os.getenv("K_SERVICE", "interactive-brokers-platform"),
strategy_profile=STRATEGY_PROFILE,
strategy_domain=RUNTIME_SETTINGS.strategy_domain,
account_group=ACCOUNT_GROUP,
project_id=PROJECT_ID,
instance_name=RUNTIME_SETTINGS.ib_gateway_instance_name,
account_ids=tuple(ACCOUNT_IDS),
strategy_target_mode=RUNTIME_SETTINGS.strategy_target_mode,
strategy_artifact_dir=RUNTIME_SETTINGS.strategy_artifact_dir,
strategy_display_name=STRATEGY_DISPLAY_NAME,
strategy_display_name_localized=strategy_display_name,
managed_symbols=resolve_reporting_managed_symbols(),
signal_effective_after_trading_days=SIGNAL_EFFECTIVE_AFTER_TRADING_DAYS,
signal_source=STRATEGY_SIGNAL_SOURCE,
status_icon=STRATEGY_STATUS_ICON,
safe_haven=SAFE_HAVEN,
dry_run_only=effective_dry_run_only,
strategy_config_source=FEATURE_RUNTIME_CONFIG_SOURCE,
ib_gateway_host_resolver=get_ib_host,
ib_gateway_port=IB_PORT,
ib_gateway_mode=RUNTIME_SETTINGS.ib_gateway_mode,
ib_gateway_ip_mode=RUNTIME_SETTINGS.ib_gateway_ip_mode,
ib_client_id=IB_CLIENT_ID,
ib_connect_timeout_seconds=IB_CONNECT_TIMEOUT_SECONDS,
feature_snapshot_path=FEATURE_SNAPSHOT_PATH,
feature_snapshot_manifest_path=FEATURE_SNAPSHOT_MANIFEST_PATH,
strategy_config_path=FEATURE_RUNTIME_CONFIG_PATH,
reconciliation_output_path=RECONCILIATION_OUTPUT_PATH,
translator=t,
separator=SEPARATOR,
send_message=send_tg_message,
connect_ib_fn=connect_ib,
build_portfolio_snapshot_fn=build_portfolio_snapshot,
compute_signals_fn=compute_signals_fn,
execute_rebalance_fn=lambda ib, target_weights, positions, account_values, **kwargs: execute_rebalance(
ib,
target_weights,
positions,
account_values,
dry_run_only_override=effective_dry_run_only,
**kwargs,
),
run_id_builder=build_run_id,
event_logger=emit_runtime_log,
report_builder=build_runtime_report_base,
report_persister=persist_runtime_report,
trace_extractor=extract_cloud_trace,
env_reader=os.getenv,
printer=print,
runtime_target=RUNTIME_SETTINGS.runtime_target,
extra_reporting_fields={
"execution_backend": EXECUTION_BACKEND,
"quantconnect_project_id": QUANTCONNECT_PROJECT_ID,
"quantconnect_node_id": QUANTCONNECT_NODE_ID,
"market": MARKET,
"market_calendar": MARKET_CALENDAR,
"market_currency": MARKET_CURRENCY,
"market_data_symbol_suffix": MARKET_DATA_SYMBOL_SUFFIX,
"market_exchange": MARKET_EXCHANGE,
"market_timezone": MARKET_TIMEZONE,
},
)
def send_tg_message(message):
return send_telegram_message(
message,
token=TG_TOKEN,
chat_id=TG_CHAT_ID,
requests_module=requests,
)
def publish_notification(*, detailed_text, compact_text):
build_composer().build_notification_adapters().publish_cycle_notification(
detailed_text=detailed_text,
compact_text=compact_text,
)
def _runtime_error_notification_targets() -> tuple[tuple[str, str], ...]:
targets: list[tuple[str, str]] = []
if TG_TOKEN and TG_CHAT_ID:
targets.append((TG_TOKEN, TG_CHAT_ID))
seen: set[tuple[str, str]] = set()
unique_targets: list[tuple[str, str]] = []
for target in targets:
if target in seen:
continue
seen.add(target)
unique_targets.append(target)
return tuple(unique_targets)
def _runtime_error_notification_message(exc: Exception, *, route_label: str | None = None) -> str:
error_text = f"{type(exc).__name__}: {exc}"
if len(error_text) > 1200:
error_text = error_text[:1197] + "..."
route = route_label or f"{request.method} {request.path}"
return "\n".join(
(
"IBKR strategy run failed",
f"service: {SERVICE_NAME or os.getenv('K_SERVICE', 'interactive-brokers-platform')}",
f"revision: {os.getenv('K_REVISION') or '<unknown>'}",
f"route: {route}",
f"strategy: {STRATEGY_PROFILE}",
f"account_group: {ACCOUNT_GROUP}",
f"error: {error_text}",
)
)
def _notify_runtime_error(exc: Exception, *, route_label: str | None = None) -> bool:
targets = _runtime_error_notification_targets()
if not targets:
print("IBKR runtime error notification skipped: no Telegram target configured.", flush=True)
return False
message = _runtime_error_notification_message(exc, route_label=route_label)
for token, chat_id in targets:
send_telegram_message(
message,
token=token,
chat_id=chat_id,
requests_module=requests,
)
return True
def _publish_runtime_failure_notification(*, detailed_text: str, compact_text: str, exc: Exception) -> bool:
try:
publish_notification(detailed_text=detailed_text, compact_text=compact_text)
return True
except Exception as notification_exc:
print(f"IBKR runtime error notification fallback: {notification_exc}", flush=True)
return _notify_runtime_error(exc)
def _handle_route_runtime_error(exc: Exception, *, route_label: str | None = None):
print(f"IBKR route failed before strategy-cycle handling: {type(exc).__name__}: {exc}", flush=True)
traceback.print_exc()
_notify_runtime_error(exc, route_label=route_label)
return "Error", 500
def _route_with_runtime_error_fallback(handler, *args, route_label: str | None = None, **kwargs):
try:
return handler(*args, **kwargs)
except Exception as exc:
return _handle_route_runtime_error(exc, route_label=route_label)
def require_gateway_execution_backend():
if EXECUTION_BACKEND == EXECUTION_BACKEND_GATEWAY:
return
raise RuntimeError(
f"IBKR execution_backend={EXECUTION_BACKEND!r} is configured; "
"Gateway connection and direct order execution are disabled for this service. "
"Run the QuantConnect deployment/algorithm path for this account group."
)
def connect_ib():
require_gateway_execution_backend()
return build_broker_adapters().connect_ib()
def _build_health_probe_connection_error_message(exc: Exception) -> str:
return f"{t('health_probe_title')}\n{t('ibkr_connection_error_prefix')}{str(exc)}"
def log_runtime_event(log_context, event, **fields):
return build_composer().build_reporting_adapters().log_event(log_context, event, **fields)
def build_execution_report(log_context, *, dry_run_only_override: bool | None = None):
return build_composer(dry_run_only_override=dry_run_only_override).build_reporting_adapters().build_report(log_context)
def persist_execution_report(report, *, dry_run_only_override: bool | None = None):
return build_composer(dry_run_only_override=dry_run_only_override).build_reporting_adapters().persist_execution_report(report)
def build_request_log_context():
return build_composer().build_reporting_adapters().build_log_context(
trace_header=request.headers.get("X-Cloud-Trace-Context"),
)
def resolve_run_as_of_date() -> pd.Timestamp:
explicit = os.getenv("IBKR_RUN_AS_OF_DATE")
if explicit:
return pd.Timestamp(explicit).normalize()
return pd.Timestamp(datetime.now(NEW_YORK_TZ).date())
def get_historical_close(ib, symbol, duration="2 Y", bar_size="1 day"):
return build_strategy_adapters().get_historical_close(
ib,
symbol,
duration=duration,
bar_size=bar_size,
)
def get_historical_candles(ib, symbol, duration="2 Y", bar_size="1 day"):
return build_strategy_adapters().get_historical_candles(
ib,
symbol,
duration=duration,
bar_size=bar_size,
)
def compute_signals(ib, current_holdings, *, strategy_plugin_signals=()):
return build_strategy_adapters().compute_signals(
ib,
current_holdings,
strategy_plugin_signals=strategy_plugin_signals,
)
def load_strategy_plugin_signals():
return build_strategy_adapters().load_strategy_plugin_signals(
getattr(RUNTIME_SETTINGS, "strategy_plugin_mounts_json", None)
)
def attach_strategy_plugin_report(report, *, signals, error: str | None = None):
build_strategy_adapters().attach_strategy_plugin_report(report, signals=signals, error=error)
def build_strategy_plugin_notification_lines(signals) -> tuple[str, ...]:
return build_strategy_adapters().build_strategy_plugin_notification_lines(signals)
def build_strategy_plugin_alert_messages(signals):
return build_strategy_adapters().build_strategy_plugin_alert_messages(signals)
def build_strategy_plugin_alert_state_settings():
return StrategyPluginAlertStateSettings.from_env(
gcp_project_id=PROJECT_ID,
)
def build_strategy_plugin_alert_context_label() -> str:
return build_alert_context_label(
platform_id="ibkr",
strategy_profile=STRATEGY_PROFILE,
account_scope=ACCOUNT_GROUP,
service_name=SERVICE_NAME,
runtime_target=RUNTIME_SETTINGS.runtime_target,
)
def _has_signal_snapshot_details(snapshot: dict[str, object]) -> bool:
return any(
snapshot.get(field_name)
for field_name in (
"signal_as_of",
"market_date",
"latest_price_source",
"target_weights",
"target_values",
"indicators",
"signal",
"status",
)
)
def _count_orders(*candidates) -> int:
for candidate in candidates:
if isinstance(candidate, (list, tuple)):
return len(candidate)
return 0
def _build_cycle_report_summary(cycle_result, execution_summary, reconciliation_record, *, dry_run: bool) -> dict:
orders_submitted_count = _count_orders(
execution_summary.get("orders_submitted"),
reconciliation_record.get("orders_submitted"),
)
orders_skipped_count = _count_orders(
execution_summary.get("orders_skipped"),
reconciliation_record.get("orders_skipped"),
)
orders_previewed_count = orders_submitted_count if dry_run else 0
summary = {
"result": cycle_result.result,
"execution_status": execution_summary.get("execution_status") or reconciliation_record.get("execution_status"),
"no_op_reason": execution_summary.get("no_op_reason") or reconciliation_record.get("no_op_reason"),
"orders_submitted_count": orders_submitted_count,
"orders_previewed_count": orders_previewed_count,
"orders_skipped_count": orders_skipped_count,
"dry_run_order_preview_available": bool(dry_run and orders_previewed_count > 0),
"snapshot_price_fallback_used": bool(
execution_summary.get("snapshot_price_fallback_used")
or reconciliation_record.get("snapshot_price_fallback_used")
),
"snapshot_price_fallback_count": int(
execution_summary.get("snapshot_price_fallback_count")
or reconciliation_record.get("snapshot_price_fallback_count")
or 0
),
}
quote_snapshot = execution_summary.get("quote_snapshot") or reconciliation_record.get("quote_snapshot")
if quote_snapshot:
summary["quote_snapshot"] = quote_snapshot
return summary
def _build_notification_delivery_log_for_report(
*,
platform: str,
strategy_profile: str,
run_id: str,
dry_run: bool,
orders_previewed_count: int,
delivery_events: list[dict],
) -> dict:
events = [dict(event) for event in delivery_events if dict(event).get("delivery_status") == "sent"]
if not dry_run or orders_previewed_count <= 0 or not events:
return {}
return {
"notification_schema_version": "hk_live_enablement_notification.v1",
"notification_event_type": "hk_snapshot_live_enablement_dry_run",
"notification_correlation_id": str(run_id or ""),
"locales": ["en", "zh-Hans"],
"profile": str(strategy_profile or ""),
"platform": str(platform or ""),
"validation_status": "passed",
"orders_previewed": int(orders_previewed_count),
"delivery_events": events,
"notification_contains_profile": True,
"notification_contains_platform": True,
"notification_contains_validation_status": True,
"notification_contains_order_preview_summary": True,
"notification_redacts_sensitive_fields": True,
"redaction_policy": "raw notification text is not persisted; only sha256 and length are recorded",
}
def publish_strategy_plugin_alerts(signals, *, report=None):
result = dispatch_strategy_plugin_alerts(
signals,
notification_settings=RUNTIME_SETTINGS,
translator=t,
strategy_label=STRATEGY_PROFILE,
context_label=build_strategy_plugin_alert_context_label(),
state_settings=build_strategy_plugin_alert_state_settings(),
log_message=print,
)
if report is not None:
result.attach_to_report(report)
return result
def build_account_notification_lines() -> tuple[str, ...]:
account_ids = tuple(str(account_id).strip() for account_id in ACCOUNT_IDS if str(account_id).strip())
if not account_ids:
return ()
return (t("account_ids_detail", account_ids=", ".join(account_ids)),)
def build_extra_notification_lines(strategy_plugin_signals=()) -> tuple[str, ...]:
return (
t(
"market_scope_detail",
market=MARKET,
currency=MARKET_CURRENCY,
exchange=MARKET_EXCHANGE,
calendar=MARKET_CALENDAR,
),
*build_account_notification_lines(),
*build_strategy_plugin_notification_lines(strategy_plugin_signals),
)
def get_current_portfolio(ib):
return build_broker_adapters().get_current_portfolio(ib)
def build_portfolio_snapshot(ib):
return build_broker_adapters().build_portfolio_snapshot(
ib,
get_current_portfolio_fallback=get_current_portfolio,
)
def get_market_prices(ib, symbols):
return build_broker_adapters().get_market_prices(ib, symbols)
def check_order_submitted(report):
return build_broker_adapters().check_order_submitted(report)
def execute_rebalance(
ib,
target_weights,
positions,
account_values,
*,
strategy_symbols=None,
signal_metadata=None,
dry_run_only_override: bool | None = None,
):
return build_broker_adapters(dry_run_only_override=dry_run_only_override).execute_rebalance(
ib,
target_weights,
positions,
account_values,
strategy_symbols=strategy_symbols,
signal_metadata=signal_metadata,
)
def _format_liquidation_orders(orders) -> str:
return build_broker_adapters().format_liquidation_orders(orders)
def run_paper_liquidation_cycle():
require_gateway_execution_backend()
if RUNTIME_SETTINGS.ib_gateway_mode != "paper":
raise RuntimeError("IBKR_PAPER_LIQUIDATE_ONLY is only allowed when ib_gateway_mode=paper")
return build_broker_adapters().run_paper_liquidation_cycle(
connect_ib_fn=connect_ib,
get_current_portfolio_fn=get_current_portfolio,
publish_notification_fn=publish_notification,
)
def run_strategy_core(
*,
strategy_plugin_signals=(),
dry_run_only_override: bool | None = None,
notification_delivery_events: list[dict] | None = None,
):
if PAPER_LIQUIDATE_ONLY and dry_run_only_override is None:
return run_paper_liquidation_cycle()
composer = build_composer(
dry_run_only_override=dry_run_only_override,
strategy_plugin_signals=strategy_plugin_signals,
)
try:
rebalance_runtime = composer.build_rebalance_runtime(
silent_cycle_notifications=bool(dry_run_only_override),
notification_delivery_events=notification_delivery_events,
)
except TypeError as exc:
if "notification_delivery_events" not in str(exc):
raise
rebalance_runtime = composer.build_rebalance_runtime(
silent_cycle_notifications=bool(dry_run_only_override),
)
return run_rebalance_cycle(
runtime=rebalance_runtime,
config=composer.build_rebalance_config(
extra_notification_lines=build_extra_notification_lines(strategy_plugin_signals),
),
)
def _handle_request(*, dry_run_only_override: bool | None = None, response_body: str = "OK"):
if request.method == "GET":
if dry_run_only_override is None:
return "OK - use POST to execute strategy", 200
return f"{response_body} - use POST to run precheck", 200
log_context = build_request_log_context()
report = build_execution_report(log_context, dry_run_only_override=dry_run_only_override)
strategy_plugin_signals, strategy_plugin_error = load_strategy_plugin_signals()
attach_strategy_plugin_report(
report,
signals=strategy_plugin_signals,
error=strategy_plugin_error,
)
lock_acquired = STRATEGY_RUN_LOCK.acquire(blocking=False)
try:
log_runtime_event(
log_context,
"strategy_cycle_received",
message="Received strategy precheck request" if dry_run_only_override else "Received strategy execution request",
http_method=request.method,
execution_window="precheck" if dry_run_only_override else "execution",
)
if not lock_acquired:
log_runtime_event(
log_context,
"strategy_cycle_already_running",
message="Another strategy execution is already running; skip overlapping request",
severity="WARNING",
)
finalize_runtime_report(
report,
status="skipped",
diagnostics={"skip_reason": "already_running"},
)
return "Already Running", 200
if not is_market_open_today(
calendar_name=MARKET_CALENDAR,
timezone_name=MARKET_TIMEZONE,
logger=lambda message: print(message, flush=True),
):
log_runtime_event(
log_context,
"market_closed",
message="Market closed; skip strategy execution",
execution_window="precheck" if dry_run_only_override else "execution",
market=MARKET,
market_calendar=MARKET_CALENDAR,
market_timezone=MARKET_TIMEZONE,
)
finalize_runtime_report(
report,
status="skipped",
diagnostics={"skip_reason": "market_closed"},
)
return "Market Closed", 200
log_runtime_event(
log_context,
"strategy_cycle_started",
message="Starting strategy precheck" if dry_run_only_override else "Starting strategy execution",
execution_window="precheck" if dry_run_only_override else "execution",
)
if dry_run_only_override is None:
publish_strategy_plugin_alerts(strategy_plugin_signals, report=report)
notification_delivery_events: list[dict] = []
cycle_result = coerce_strategy_cycle_result(
run_strategy_core(
strategy_plugin_signals=strategy_plugin_signals,
dry_run_only_override=dry_run_only_override,
notification_delivery_events=notification_delivery_events,
)
)
execution_summary = dict(cycle_result.execution_summary or {})
reconciliation_record = dict(cycle_result.reconciliation_record or {})
signal_metadata = dict(cycle_result.signal_metadata or {})
signal_snapshot = dict(signal_metadata.get("signal_snapshot") or {})
if not signal_snapshot:
signal_snapshot = build_signal_snapshot(
platform="ibkr",
strategy_profile=signal_metadata.get("strategy_profile") or STRATEGY_PROFILE,
metadata=signal_metadata,
target_weights=cycle_result.target_weights,