-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_runtime_switch.py
More file actions
1148 lines (1021 loc) · 46.3 KB
/
Copy pathbuild_runtime_switch.py
File metadata and controls
1148 lines (1021 loc) · 46.3 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
#!/usr/bin/env python3
"""Build a transient runtime target for a manual strategy switch."""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
ROOT = SCRIPT_DIR.parents[1]
from runtime_settings import ( # noqa: E402
LIVE_CONTINUITY_STATES,
SUPPORTED_PLATFORMS,
compact_json,
env_string,
platform_repository,
runtime_target_fingerprint,
select_service_target_entry_index,
validate_target,
)
DEFAULT_ARTIFACT_BUCKET_URI = "gs://qsl-runtime-logs-shared"
PLATFORM_CONFIG_PATH = ROOT / "platform-config.json"
IBIT_ZSCORE_EXIT_STRATEGY_PROFILE = "ibit_smart_dca"
PLATFORM_DRY_RUN_VARIABLES = {
"schwab": "SCHWAB_DRY_RUN_ONLY",
"longbridge": "LONGBRIDGE_DRY_RUN_ONLY",
"ibkr": "IBKR_DRY_RUN_ONLY",
"firstrade": "FIRSTRADE_DRY_RUN_ONLY",
"qmt": "QMT_DRY_RUN_ONLY",
"binance": "BINANCE_DRY_RUN",
}
PLATFORM_RESERVED_CASH_RATIO_VARIABLES = {
"schwab": "SCHWAB_RESERVED_CASH_RATIO",
"longbridge": "LONGBRIDGE_RESERVED_CASH_RATIO",
"ibkr": "IBKR_RESERVED_CASH_RATIO",
"firstrade": "FIRSTRADE_RESERVED_CASH_RATIO",
}
PLATFORM_MIN_RESERVED_CASH_VARIABLES = {
"schwab": "SCHWAB_MIN_RESERVED_CASH_USD",
"longbridge": "LONGBRIDGE_MIN_RESERVED_CASH_USD",
"ibkr": "IBKR_MIN_RESERVED_CASH_USD",
"firstrade": "FIRSTRADE_MIN_RESERVED_CASH_USD",
}
PLATFORM_CASH_ONLY_EXECUTION_VARIABLES = {
"schwab": "SCHWAB_CASH_ONLY_EXECUTION",
"longbridge": "LONGBRIDGE_CASH_ONLY_EXECUTION",
"ibkr": "IBKR_CASH_ONLY_EXECUTION",
"firstrade": "FIRSTRADE_CASH_ONLY_EXECUTION",
}
PLATFORM_FEATURE_SNAPSHOT_VARIABLES = {
"schwab": ("SCHWAB_FEATURE_SNAPSHOT_PATH", "SCHWAB_FEATURE_SNAPSHOT_MANIFEST_PATH"),
"longbridge": (
"LONGBRIDGE_FEATURE_SNAPSHOT_PATH",
"LONGBRIDGE_FEATURE_SNAPSHOT_MANIFEST_PATH",
),
"ibkr": ("IBKR_FEATURE_SNAPSHOT_PATH", "IBKR_FEATURE_SNAPSHOT_MANIFEST_PATH"),
"firstrade": (
"FIRSTRADE_FEATURE_SNAPSHOT_PATH",
"FIRSTRADE_FEATURE_SNAPSHOT_MANIFEST_PATH",
),
}
INCOME_LAYER_VARIABLES = (
"INCOME_LAYER_ENABLED",
"INCOME_LAYER_START_USD",
"INCOME_LAYER_MAX_RATIO",
)
MARKET_SIGNAL_RUNTIME_SUFFIXES = (
"MARKET_SIGNAL_HANDOFF_INDEX_URI",
"MARKET_SIGNAL_HANDOFF_MANIFEST_URI",
"MARKET_SIGNAL_CONSUMPTION_AUDIT_URI",
"MARKET_SIGNAL_CACHE_DIR",
"MARKET_SIGNAL_REQUIRED",
"MARKET_SIGNAL_FALLBACK_MODE",
"MARKET_SIGNAL_MAX_STALE_DAYS",
)
PLATFORM_MARKET_SIGNAL_PREFIXES = {
"schwab": "SCHWAB",
"longbridge": "LONGBRIDGE",
"ibkr": "IBKR",
"firstrade": "FIRSTRADE",
"qmt": "QMT",
}
MARKET_SIGNAL_RUNTIME_VARIABLES = tuple(MARKET_SIGNAL_RUNTIME_SUFFIXES) + tuple(
f"{prefix}_{suffix}"
for prefix in PLATFORM_MARKET_SIGNAL_PREFIXES.values()
for suffix in MARKET_SIGNAL_RUNTIME_SUFFIXES
)
CASH_ONLY_EXECUTION_VARIABLE = "CASH_ONLY_EXECUTION"
CASH_ONLY_EXECUTION_MODES = frozenset({"current", "enabled", "disabled"})
CASH_ONLY_EXECUTION_CONTROL_FIELD = "cash_only_execution_mode"
LEGACY_INCOME_LAYER_VARIABLES = (
"INCOME_THRESHOLD_USD",
"QQQI_INCOME_RATIO",
"INCOME_LAYER_QQQI_WEIGHT",
"INCOME_LAYER_SPYI_WEIGHT",
)
LEGACY_INCOME_LAYER_CONTROL_FIELDS = (
"income_threshold_usd",
"qqqi_income_ratio",
"income_layer_qqqi_weight",
"income_layer_spyi_weight",
)
OPTION_OVERLAY_CONTROL_FIELDS = (
"option_overlay_enabled",
"option_growth_overlay_enabled",
"option_growth_overlay_recipe",
"option_growth_overlay_start_usd",
"option_growth_overlay_nav_budget_ratio",
"option_income_overlay_enabled",
"option_income_overlay_recipe",
"option_income_overlay_start_usd",
"option_income_overlay_nav_risk_ratio",
)
OPTION_OVERLAY_VARIABLES = tuple(field.upper() for field in OPTION_OVERLAY_CONTROL_FIELDS)
OPTION_OVERLAY_MODES = frozenset({"current", "enabled", "disabled"})
OPTION_OVERLAY_PROFILE_PATH = ROOT / "web" / "strategy-switch-console" / "strategy-profiles.example.json"
RUNTIME_TARGET_VARIABLES = ("RUNTIME_TARGET_ENABLED",)
DCA_PROFILES = frozenset(
{
"nasdaq_sp500_smart_dca",
"ibit_smart_dca",
}
)
DCA_SUPPORTED_PLATFORMS = frozenset({"longbridge", "ibkr", "schwab", "firstrade"})
DCA_MODES = frozenset({"fixed", "smart"})
DCA_MODE_VARIABLE = "DCA_MODE"
DCA_BASE_INVESTMENT_VARIABLE = "DCA_BASE_INVESTMENT_USD"
DCA_RUNTIME_VARIABLES = (
DCA_MODE_VARIABLE,
DCA_BASE_INVESTMENT_VARIABLE,
)
DCA_MODE_CONTROL_FIELD = "dca_mode"
DCA_BASE_INVESTMENT_CONTROL_FIELD = "dca_base_investment_usd"
IBIT_ZSCORE_EXIT_ENABLED_VARIABLE = "IBIT_ZSCORE_EXIT_ENABLED"
IBIT_ZSCORE_EXIT_MODE_VARIABLE = "IBIT_ZSCORE_EXIT_MODE"
IBIT_ZSCORE_EXIT_PARKING_SYMBOL_VARIABLE = "IBIT_ZSCORE_EXIT_PARKING_SYMBOL"
IBIT_ZSCORE_EXIT_RISK_REDUCED_EXPOSURE_VARIABLE = "IBIT_ZSCORE_EXIT_RISK_REDUCED_EXPOSURE"
IBIT_ZSCORE_EXIT_RISK_OFF_EXPOSURE_VARIABLE = "IBIT_ZSCORE_EXIT_RISK_OFF_EXPOSURE"
IBIT_ZSCORE_EXIT_ALLOW_OUTSIDE_WINDOW_VARIABLE = "IBIT_ZSCORE_EXIT_ALLOW_OUTSIDE_EXECUTION_WINDOW"
IBIT_ZSCORE_EXIT_RUNTIME_VARIABLES = (
IBIT_ZSCORE_EXIT_ENABLED_VARIABLE,
IBIT_ZSCORE_EXIT_MODE_VARIABLE,
IBIT_ZSCORE_EXIT_PARKING_SYMBOL_VARIABLE,
IBIT_ZSCORE_EXIT_RISK_REDUCED_EXPOSURE_VARIABLE,
IBIT_ZSCORE_EXIT_RISK_OFF_EXPOSURE_VARIABLE,
IBIT_ZSCORE_EXIT_ALLOW_OUTSIDE_WINDOW_VARIABLE,
)
IBIT_ZSCORE_EXIT_CONTROL_FIELDS = (
"ibit_zscore_exit_mode",
"ibit_zscore_exit_parking_symbol",
"ibit_zscore_exit_risk_reduced_exposure",
"ibit_zscore_exit_risk_off_exposure",
"ibit_zscore_exit_allow_outside_execution_window",
)
DEFAULT_VARIABLE_SCOPE = {
"longbridge": "environment",
"ibkr": "repository",
"schwab": "repository",
"firstrade": "repository",
"qmt": "repository",
"binance": "repository",
}
REPOSITORY_SCOPED_SERVICE_INVENTORY_PLATFORMS = frozenset(
{"longbridge", "schwab", "firstrade"}
)
DEFAULT_SERVICE_NAME = {
"schwab": "charles-schwab-quant-service",
"firstrade": "firstrade-quant-service",
"qmt": "qmt-quant-service",
"binance": "binance-platform",
}
PLATFORM_ALIASES = {
"firsttrade": "firstrade",
}
def _normalize_platform(value: str) -> str:
platform = str(value or "").strip().lower()
platform = PLATFORM_ALIASES.get(platform, platform)
if platform not in SUPPORTED_PLATFORMS:
supported = ", ".join(sorted(SUPPORTED_PLATFORMS))
raise ValueError(f"unsupported platform {value!r}; supported: {supported}")
return platform
def _normalize_target_name(value: str) -> str:
text = str(value or "").strip()
if not text:
raise ValueError("target_name is required")
return re.sub(r"[^A-Za-z0-9._=-]+", "-", text).strip("-")
def _deployment_selector_default(platform: str, target_name: str) -> str:
if platform in {"firstrade", "qmt"}:
return platform
return target_name.upper() if target_name.lower() in {"sg", "hk", "paper"} else target_name
def _account_scope_default(platform: str, deployment_selector: str) -> str:
if platform == "firstrade":
return "US"
if platform == "qmt":
return "CN"
return deployment_selector
def _account_selector_default(platform: str, account_scope: str) -> list[str]:
if platform in {"firstrade", "qmt"}:
return [platform]
return [account_scope]
def _default_service_name(platform: str, target_name: str) -> str:
if platform in DEFAULT_SERVICE_NAME:
return DEFAULT_SERVICE_NAME[platform]
normalized = target_name.lower()
if platform == "longbridge":
return f"longbridge-quant-{normalized}-service"
if platform == "ibkr":
return f"interactive-brokers-{normalized}-service"
raise ValueError(f"no default service_name for platform {platform!r}")
def _default_github_environment(platform: str, target_name: str, variable_scope: str) -> str | None:
if variable_scope != "environment":
return None
if platform == "longbridge":
return f"longbridge-{target_name.lower()}"
return target_name
def _split_csv(value: str | None) -> list[str]:
if not value:
return []
return [item.strip() for item in value.replace(";", ",").split(",") if item.strip()]
def _load_json_object(value: str, *, field_name: str) -> dict[str, Any]:
text = str(value or "").strip()
if not text:
return {}
try:
payload = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError(f"{field_name} must be valid JSON") from exc
if not isinstance(payload, dict):
raise ValueError(f"{field_name} must decode to an object")
return payload
def _load_json_from_file(path: str | None, *, field_name: str) -> dict[str, Any] | list[Any]:
if not path:
return {}
try:
payload = json.loads(Path(path).read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"{field_name} must be valid JSON") from exc
if not isinstance(payload, (dict, list)):
raise ValueError(f"{field_name} must decode to an object or array")
return payload
def _parse_extra_variables(pairs: list[str], raw_json: str) -> dict[str, Any]:
extras = _load_json_object(raw_json, field_name="extra_variables_json")
for pair in pairs:
name, sep, value = pair.partition("=")
if not sep or not name.strip():
raise ValueError(f"extra variable must be NAME=VALUE, got: {pair!r}")
extras[name.strip()] = value
return extras
def _normalize_dca_mode(value: str) -> str:
mode = str(value or "").strip().lower()
aliases = {
"ordinary": "fixed",
"ordinary_dca": "fixed",
"fixed_dca": "fixed",
"smart_dca": "smart",
}
mode = aliases.get(mode, mode)
if mode not in DCA_MODES:
raise ValueError("dca_mode must be fixed or smart")
return mode
def _validate_dca_platform(platform: str, strategy_profile: str) -> None:
profile = str(strategy_profile or "").strip().lower()
if profile in DCA_PROFILES and platform not in DCA_SUPPORTED_PLATFORMS:
supported = ", ".join(sorted(DCA_SUPPORTED_PLATFORMS))
raise ValueError(
f"DCA strategy profiles are only supported on {supported}; "
f"got platform={platform!r}, strategy_profile={profile!r}"
)
def _normalize_positive_decimal(value: str, *, field_name: str) -> str:
text = str(value or "").strip()
if not text or not re.fullmatch(r"(?:\d+|\d*\.\d+)", text):
raise ValueError(f"{field_name} must be a positive decimal number")
numeric = float(text)
if not numeric > 0:
raise ValueError(f"{field_name} must be greater than 0")
return text
def _normalize_nonnegative_decimal(value: str, *, field_name: str) -> str:
text = str(value or "").strip()
if not text or not re.fullmatch(r"(?:\d+|\d*\.\d+)", text):
raise ValueError(f"{field_name} must be a non-negative decimal number")
numeric = float(text)
if numeric < 0:
raise ValueError(f"{field_name} must be non-negative")
return text
def _normalize_ratio_decimal(value: str, *, field_name: str) -> str:
text = str(value or "").strip()
if not text or not re.fullmatch(r"(?:\d+|\d*\.\d+)", text):
raise ValueError(f"{field_name} must be a decimal number")
numeric = float(text)
if numeric < 0 or numeric > 1:
raise ValueError(f"{field_name} must be between 0 and 1")
return text
def _normalize_optional_bool_text(value: str, *, field_name: str) -> str:
text = str(value if value is not None else "").strip().lower()
if text in {"1", "true", "yes", "y", "on"}:
return "true"
if text in {"0", "false", "no", "n", "off"}:
return "false"
raise ValueError(f"{field_name} must be true or false")
def _normalize_option_overlay_mode(value: str) -> str:
mode = str(value or "current").strip().lower()
if mode not in OPTION_OVERLAY_MODES:
raise ValueError("option_overlay_mode must be current, enabled, or disabled")
return mode
def _normalize_option_recipe(value: str, *, field_name: str) -> str:
text = str(value or "").strip()
if not text or not re.fullmatch(r"[A-Za-z0-9._=-]{1,120}", text):
raise ValueError(f"{field_name} must be a recipe slug")
return text
def _normalize_symbol_text(value: str, *, field_name: str) -> str:
text = str(value or "").strip().upper().removesuffix(".US")
if not text or not re.fullmatch(r"[A-Z0-9.-]{1,12}", text):
raise ValueError(f"{field_name} must be a symbol")
return text
def _cash_only_extra_variables(args: argparse.Namespace, platform: str) -> dict[str, str]:
mode = str(getattr(args, "cash_only_execution_mode", None) or "current").strip().lower()
if mode not in CASH_ONLY_EXECUTION_MODES:
raise ValueError("cash_only_execution_mode must be current, enabled, or disabled")
if mode == "current":
return {}
variable = PLATFORM_CASH_ONLY_EXECUTION_VARIABLES.get(platform)
if not variable:
return {}
return {variable: env_string(mode == "enabled")}
def _extract_cash_only_control_fields(extra_variables: dict[str, Any]) -> dict[str, Any]:
controls: dict[str, Any] = {}
if CASH_ONLY_EXECUTION_CONTROL_FIELD in extra_variables:
controls[CASH_ONLY_EXECUTION_CONTROL_FIELD] = extra_variables.pop(CASH_ONLY_EXECUTION_CONTROL_FIELD)
return controls
def _extract_dca_control_fields(extra_variables: dict[str, Any]) -> dict[str, Any]:
controls: dict[str, Any] = {}
for field_name in (DCA_MODE_CONTROL_FIELD, DCA_BASE_INVESTMENT_CONTROL_FIELD):
if field_name in extra_variables:
controls[field_name] = extra_variables.pop(field_name)
return controls
def _extract_ibit_zscore_exit_control_fields(extra_variables: dict[str, Any]) -> dict[str, Any]:
controls: dict[str, Any] = {}
for field_name in IBIT_ZSCORE_EXIT_CONTROL_FIELDS:
if field_name in extra_variables:
controls[field_name] = extra_variables.pop(field_name)
return controls
def _disabled_option_overlay_extra_variables() -> dict[str, str]:
values = {variable: "" for variable in OPTION_OVERLAY_VARIABLES}
values["OPTION_OVERLAY_ENABLED"] = "false"
values["OPTION_GROWTH_OVERLAY_ENABLED"] = "false"
values["OPTION_INCOME_OVERLAY_ENABLED"] = "false"
return values
def _profile_bool(item: dict[str, Any], field_name: str, *, default: bool = False) -> bool:
if item.get(field_name) is None or str(item.get(field_name)).strip() == "":
return default
return _normalize_optional_bool_text(item[field_name], field_name=field_name) == "true"
def _option_family_defaults(item: dict[str, Any], family: str) -> dict[str, str]:
control_prefix = f"option_{family}_overlay"
env_prefix = f"OPTION_{family.upper()}_OVERLAY"
enabled = _profile_bool(item, f"{control_prefix}_enabled", default=False)
values = {
f"{env_prefix}_ENABLED": "true" if enabled else "false",
f"{env_prefix}_RECIPE": "",
f"{env_prefix}_START_USD": "",
}
if family == "growth":
ratio_field = "option_growth_overlay_nav_budget_ratio"
ratio_variable = "OPTION_GROWTH_OVERLAY_NAV_BUDGET_RATIO"
else:
ratio_field = "option_income_overlay_nav_risk_ratio"
ratio_variable = "OPTION_INCOME_OVERLAY_NAV_RISK_RATIO"
values[ratio_variable] = ""
if not enabled:
return values
values[f"{env_prefix}_RECIPE"] = _normalize_option_recipe(
item.get(f"{control_prefix}_recipe"),
field_name=f"{control_prefix}_recipe",
)
values[f"{env_prefix}_START_USD"] = _normalize_nonnegative_decimal(
item.get(f"{control_prefix}_start_usd"),
field_name=f"{control_prefix}_start_usd",
)
values[ratio_variable] = _normalize_ratio_decimal(item.get(ratio_field), field_name=ratio_field)
return values
def _load_option_overlay_profile_defaults() -> dict[str, dict[str, str]]:
try:
payload = json.loads(OPTION_OVERLAY_PROFILE_PATH.read_text(encoding="utf-8"))
except OSError as exc:
raise ValueError(f"cannot read {OPTION_OVERLAY_PROFILE_PATH}") from exc
except json.JSONDecodeError as exc:
raise ValueError(f"{OPTION_OVERLAY_PROFILE_PATH} must be valid JSON") from exc
if not isinstance(payload, list):
raise ValueError(f"{OPTION_OVERLAY_PROFILE_PATH} must contain a strategy profile list")
defaults: dict[str, dict[str, str]] = {}
for item in payload:
if not isinstance(item, dict):
continue
profile = str(item.get("profile") or item.get("strategy_profile") or "").strip().lower()
if not profile:
continue
if not _profile_bool(item, "option_overlay_enabled", default=False):
continue
values = _disabled_option_overlay_extra_variables()
values["OPTION_OVERLAY_ENABLED"] = "true"
values.update(_option_family_defaults(item, "growth"))
values.update(_option_family_defaults(item, "income"))
if values["OPTION_GROWTH_OVERLAY_ENABLED"] != "true" and values["OPTION_INCOME_OVERLAY_ENABLED"] != "true":
raise ValueError(f"{profile} option overlay is enabled without a growth or income family")
defaults[profile] = values
return defaults
def _option_overlay_extra_variables(args: argparse.Namespace, strategy_profile: str) -> dict[str, str]:
mode = _normalize_option_overlay_mode(getattr(args, "option_overlay_mode", "current"))
if mode == "current":
return {}
if mode == "disabled":
return _disabled_option_overlay_extra_variables()
defaults = _load_option_overlay_profile_defaults().get(strategy_profile)
if not defaults:
raise ValueError("option_overlay_mode enabled is only supported for strategies with option overlay defaults")
return dict(defaults)
def _dca_extra_variables(
args: argparse.Namespace,
strategy_profile: str,
controls: dict[str, Any] | None = None,
) -> dict[str, Any]:
controls = dict(controls or {})
is_dca_profile = strategy_profile in DCA_PROFILES
dca_mode = args.dca_mode if str(args.dca_mode or "").strip() else controls.get(DCA_MODE_CONTROL_FIELD, "")
dca_base_investment_usd = (
args.dca_base_investment_usd
if str(args.dca_base_investment_usd or "").strip()
else controls.get(DCA_BASE_INVESTMENT_CONTROL_FIELD, "")
)
has_dca_mode = bool(str(dca_mode or "").strip())
has_dca_base = bool(str(dca_base_investment_usd or "").strip())
if not is_dca_profile:
if has_dca_mode or has_dca_base:
raise ValueError("DCA settings are only supported for DCA strategy profiles")
return {variable: "" for variable in DCA_RUNTIME_VARIABLES}
extra_variables: dict[str, Any] = {}
if has_dca_mode:
extra_variables[DCA_MODE_VARIABLE] = _normalize_dca_mode(dca_mode)
if has_dca_base:
extra_variables[DCA_BASE_INVESTMENT_VARIABLE] = _normalize_positive_decimal(
dca_base_investment_usd,
field_name="dca_base_investment_usd",
)
return extra_variables
def _effective_dca_mode(
args: argparse.Namespace,
strategy_profile: str,
controls: dict[str, Any] | None = None,
) -> str:
if strategy_profile not in DCA_PROFILES:
return ""
controls = dict(controls or {})
raw_mode = args.dca_mode if str(args.dca_mode or "").strip() else controls.get(DCA_MODE_CONTROL_FIELD, "")
return _normalize_dca_mode(raw_mode) if str(raw_mode or "").strip() else "fixed"
def _reject_direct_dca_extra_variables(extra_variables: dict[str, Any]) -> None:
provided = [
variable
for variable in DCA_RUNTIME_VARIABLES
if variable in extra_variables and str(extra_variables.get(variable) or "").strip()
]
if provided:
names = ", ".join(provided)
raise ValueError(
f"use dca_mode and dca_base_investment_usd control fields instead of extra_variables_json for {names}"
)
def _reject_direct_ibit_zscore_exit_extra_variables(extra_variables: dict[str, Any]) -> None:
provided = [
variable
for variable in IBIT_ZSCORE_EXIT_RUNTIME_VARIABLES
if variable in extra_variables and str(extra_variables.get(variable) or "").strip()
]
if provided:
names = ", ".join(provided)
raise ValueError(
"IBIT_ZSCORE_EXIT variables are derived from ibit_smart_dca smart DCA mode; "
f"do not set them directly: {names}"
)
def _reject_research_only_extra_variables(extra_variables: dict[str, Any]) -> None:
blocked = [
name
for name in (
*OPTION_OVERLAY_CONTROL_FIELDS,
*OPTION_OVERLAY_VARIABLES,
*LEGACY_INCOME_LAYER_CONTROL_FIELDS,
*LEGACY_INCOME_LAYER_VARIABLES,
)
if name in extra_variables
]
if blocked:
names = ", ".join(blocked)
raise ValueError(
"direct option overlay settings and legacy income controls are research-only "
f"and are not supported by live strategy switch settings: {names}"
)
def _ibit_zscore_exit_extra_variables(
args: argparse.Namespace,
strategy_profile: str,
plugin_mode: str,
dca_mode: str,
) -> dict[str, Any]:
is_ibit_profile = strategy_profile == IBIT_ZSCORE_EXIT_STRATEGY_PROFILE
if not is_ibit_profile:
return {variable: "" for variable in IBIT_ZSCORE_EXIT_RUNTIME_VARIABLES}
mode = "live" if plugin_mode != "none" and dca_mode == "smart" else "disabled"
return {
IBIT_ZSCORE_EXIT_ENABLED_VARIABLE: "true" if mode != "disabled" else "false",
IBIT_ZSCORE_EXIT_MODE_VARIABLE: "paper" if mode == "disabled" else mode,
IBIT_ZSCORE_EXIT_PARKING_SYMBOL_VARIABLE: _normalize_symbol_text(
"BOXX",
field_name="ibit_zscore_exit_parking_symbol",
),
IBIT_ZSCORE_EXIT_RISK_REDUCED_EXPOSURE_VARIABLE: _normalize_ratio_decimal(
"0.50",
field_name="ibit_zscore_exit_risk_reduced_exposure",
),
IBIT_ZSCORE_EXIT_RISK_OFF_EXPOSURE_VARIABLE: _normalize_ratio_decimal(
"0.25",
field_name="ibit_zscore_exit_risk_off_exposure",
),
IBIT_ZSCORE_EXIT_ALLOW_OUTSIDE_WINDOW_VARIABLE: _normalize_optional_bool_text(
"true",
field_name="ibit_zscore_exit_allow_outside_execution_window",
),
}
def _auto_plugin_mounts(strategy_profile: str, artifact_bucket_uri: str, dca_mode: str = "") -> list[dict[str, Any]]:
"""Retire name-based plugin selection without expanding runtime authority."""
del strategy_profile, artifact_bucket_uri, dca_mode
return []
def _current_plugin_mounts(args: argparse.Namespace, strategy_profile: str) -> list[dict[str, Any]]:
path = str(getattr(args, "current_plugin_mounts_json_file", "") or "").strip()
if not path:
raise ValueError("plugin_mode=current requires current_plugin_mounts_json_file")
payload = _load_json_from_file(path, field_name="current_plugin_mounts_json_file")
if not isinstance(payload, dict):
raise ValueError("current_plugin_mounts_json_file must contain an object")
mounts = payload.get("strategy_plugins")
if not isinstance(mounts, list) or any(not isinstance(item, dict) for item in mounts):
raise ValueError("current_plugin_mounts_json_file.strategy_plugins must be an array of objects")
unexpected = {
str(item.get("strategy") or "").strip()
for item in mounts
if str(item.get("strategy") or "").strip() != strategy_profile
}
if unexpected:
raise ValueError(
"plugin_mode=current only preserves mounts for the selected strategy; "
f"found: {', '.join(sorted(unexpected))}"
)
return [dict(item) for item in mounts]
def _plugin_mounts(args: argparse.Namespace, strategy_profile: str, dca_mode: str = "") -> list[dict[str, Any]]:
mode = str(args.plugin_mode or "none").strip().lower()
if mode == "none":
return []
if mode == "auto":
return _auto_plugin_mounts(strategy_profile, args.artifact_bucket_uri, dca_mode)
if mode == "current":
return _current_plugin_mounts(args, strategy_profile)
if mode == "custom":
raise ValueError(
"legacy custom plugin mounts are retired; a P1/P2/P3-bound strategy_plugin_signal.v2 adapter is required"
)
raise ValueError(f"unsupported plugin_mode {args.plugin_mode!r}")
def _execution_mode_and_dry_run(raw_mode: str) -> tuple[str, bool]:
mode = str(raw_mode or "").strip().lower()
if mode == "live":
return "live", False
if mode in {"paper", "dry_run", "dry-run"}:
# Platform sync adapters currently consume this legacy no-order
# envelope. Policy validation maps it back to the canonical dry_run
# control mode; do not alter deployed payload compatibility here.
return "paper", True
raise ValueError("execution_mode must be live, paper, or dry_run")
def _validate_requested_execution_mode(strategy_profile: str, raw_mode: str) -> None:
"""Keep legacy ``paper`` requests within their original strategy scope.
The emitted no-order envelope is intentionally compatible with deployed
platform parsers. A new ``dry_run`` request may use it for any strategy;
an explicit old ``paper`` request must still be listed in the strategy
profile so it cannot broaden a historical mode allowance.
"""
if str(raw_mode or "").strip().lower() != "paper":
return
config = _load_platform_config()
strategies = config.get("strategies")
strategy = strategies.get(strategy_profile) if isinstance(strategies, dict) else None
if not isinstance(strategy, dict):
return
allowed_modes = strategy.get("allowed_execution_modes")
if isinstance(allowed_modes, str):
allowed = {part.strip().lower() for part in re.split(r"[,\s/|]+", allowed_modes) if part.strip()}
elif isinstance(allowed_modes, (list, tuple, set)):
allowed = {str(part or "").strip().lower() for part in allowed_modes if str(part or "").strip()}
else:
allowed = set()
if allowed and "paper" not in allowed:
raise ValueError(f"strategy {strategy_profile!r} does not allow paper execution; use dry_run")
def _load_platform_config() -> dict[str, Any]:
try:
payload = json.loads(PLATFORM_CONFIG_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise ValueError(f"unable to load platform config {PLATFORM_CONFIG_PATH}: {exc}") from exc
if not isinstance(payload, dict):
raise ValueError("platform-config.json must contain an object")
return payload
def _scheduler_plan_for_strategy(
strategy_profile: str,
plugin_mounts: list[dict[str, Any]] | tuple[dict[str, Any], ...] = (),
) -> dict[str, str]:
profile = str(strategy_profile or "").strip().lower()
config = _load_platform_config()
scheduling = config.get("scheduling")
strategies = config.get("strategies")
domains = config.get("domains")
if not isinstance(scheduling, dict) or not isinstance(strategies, dict) or not isinstance(domains, dict):
raise ValueError("platform-config.json must define scheduling, strategies, and domains")
scheduler_profiles = scheduling.get("profiles")
strategy = strategies.get(profile)
if not isinstance(scheduler_profiles, dict) or not isinstance(strategy, dict):
raise ValueError(f"strategy {profile!r} is missing from the scheduling catalog")
domain = domains.get(strategy.get("domain"))
if not isinstance(domain, dict):
raise ValueError(f"strategy {profile!r} has no configured scheduling domain")
scheduler_profile = strategy.get("scheduler_profile") or domain.get("scheduler_profile")
plugin_overrides = strategy.get("scheduler_profile_by_plugin") or {}
if not isinstance(plugin_overrides, dict):
raise ValueError(f"strategy {profile!r} scheduler_profile_by_plugin must be an object")
for mount in plugin_mounts:
if (
not isinstance(mount, dict)
or mount.get("strategy") != profile
or mount.get("enabled") is not True
):
continue
plugin = str(mount.get("plugin") or "").strip()
if plugin in plugin_overrides:
scheduler_profile = plugin_overrides[plugin]
scheduler = scheduler_profiles.get(scheduler_profile)
if not isinstance(scheduler, dict):
raise ValueError(
f"strategy {profile!r} references unknown scheduler profile {scheduler_profile!r}"
)
return {str(key): str(value) for key, value in scheduler.items()}
def _market_plan_for_strategy(strategy_profile: str) -> dict[str, str]:
profile = str(strategy_profile or "").strip().lower()
config = _load_platform_config()
strategies = config.get("strategies")
domains = config.get("domains")
strategy = strategies.get(profile) if isinstance(strategies, dict) else None
if not isinstance(strategy, dict) or not isinstance(domains, dict):
raise ValueError(f"strategy {profile!r} is missing from the market catalog")
domain = domains.get(strategy.get("domain"))
if not isinstance(domain, dict):
raise ValueError(f"strategy {profile!r} has no configured market domain")
market = {
field: str(domain.get(field) or "").strip()
for field in ("market", "market_calendar", "market_timezone")
}
missing = [field for field, value in market.items() if not value]
if missing:
raise ValueError(
f"strategy {profile!r} market domain is missing {', '.join(missing)}"
)
return market
def _feature_snapshot_extra_variables(
platform: str,
strategy_profile: str,
extra_variables: dict[str, Any],
) -> dict[str, str]:
variable_names = PLATFORM_FEATURE_SNAPSHOT_VARIABLES.get(platform)
if not variable_names:
return {}
snapshot_variable, manifest_variable = variable_names
config = _load_platform_config()
strategies = config.get("strategies")
strategy = strategies.get(strategy_profile) if isinstance(strategies, dict) else None
if not isinstance(strategy, dict):
raise ValueError(f"strategy {strategy_profile!r} is missing from the runtime artifact catalog")
runtime_artifacts = strategy.get("runtime_artifacts") or {}
if not isinstance(runtime_artifacts, dict):
raise ValueError(f"strategy {strategy_profile!r} runtime_artifacts must be an object")
feature_snapshot = runtime_artifacts.get("feature_snapshot") or {}
if not isinstance(feature_snapshot, dict):
raise ValueError(
f"strategy {strategy_profile!r} runtime_artifacts.feature_snapshot must be an object"
)
explicit = snapshot_variable in extra_variables or manifest_variable in extra_variables
if explicit:
snapshot_path = extra_variables.get(snapshot_variable)
manifest_path = extra_variables.get(manifest_variable)
else:
snapshot_path = feature_snapshot.get("path")
manifest_path = feature_snapshot.get("manifest_path")
snapshot_path = snapshot_path.strip() if isinstance(snapshot_path, str) else ""
manifest_path = manifest_path.strip() if isinstance(manifest_path, str) else ""
if explicit and not feature_snapshot and (snapshot_path or manifest_path):
raise ValueError(
f"strategy {strategy_profile!r} does not accept feature snapshot artifacts"
)
if bool(snapshot_path) != bool(manifest_path):
raise ValueError(
f"strategy {strategy_profile!r} feature snapshot path and manifest path must be configured together"
)
if feature_snapshot.get("required") is True and not (snapshot_path and manifest_path):
raise ValueError(
f"strategy {strategy_profile!r} requires feature snapshot path and manifest path"
)
return {
snapshot_variable: snapshot_path,
manifest_variable: manifest_path,
}
def _build_runtime_target(args: argparse.Namespace) -> dict[str, Any]:
platform = _normalize_platform(args.platform)
target_name = _normalize_target_name(args.target_name)
execution_mode, dry_run_only = _execution_mode_and_dry_run(args.execution_mode)
deployment_selector = (
args.deployment_selector.strip()
if args.deployment_selector
else _deployment_selector_default(platform, target_name)
)
account_scope = (
args.account_scope.strip() if args.account_scope else _account_scope_default(platform, deployment_selector)
)
account_selector = _split_csv(args.account_selector) or _account_selector_default(platform, account_scope)
service_name = args.service_name.strip() if args.service_name else _default_service_name(platform, target_name)
strategy_profile = args.strategy_profile.strip().lower()
_validate_requested_execution_mode(strategy_profile, args.execution_mode)
_validate_dca_platform(platform, strategy_profile)
runtime_target: dict[str, Any] = {
"platform_id": platform,
"strategy_profile": strategy_profile,
"dry_run_only": dry_run_only,
"deployment_selector": deployment_selector,
"account_selector": account_selector,
"account_scope": account_scope,
"service_name": service_name,
"execution_mode": execution_mode,
"scheduler": _scheduler_plan_for_strategy(strategy_profile),
**_market_plan_for_strategy(strategy_profile),
}
execution_windows = _load_json_object(args.execution_windows_json, field_name="execution_windows_json")
if execution_windows:
runtime_target["execution_windows"] = execution_windows
_apply_live_continuity(runtime_target, args)
return runtime_target
def _apply_live_continuity(runtime_target: dict[str, Any], args: argparse.Namespace) -> None:
"""Attach a frozen legacy baseline without granting new live authority."""
state = str(getattr(args, "live_continuity_state", "") or "").strip().upper()
if not state or state == "NONE":
return
if state not in LIVE_CONTINUITY_STATES:
raise ValueError(f"live_continuity_state must be one of NONE, {', '.join(sorted(LIVE_CONTINUITY_STATES))}")
if runtime_target.get("execution_mode") != "live" or runtime_target.get("dry_run_only") is not False:
raise ValueError("live_continuity is only valid for an execution_mode=live, non-dry-run target")
baseline_id = str(getattr(args, "live_continuity_baseline_id", "") or "").strip()
captured_at = str(getattr(args, "live_continuity_captured_at", "") or "").strip()
if not baseline_id or not captured_at:
raise ValueError(
"live_continuity_baseline_id and live_continuity_captured_at are required when live_continuity_state is set"
)
runtime_target["live_continuity"] = {
"state": state,
"baseline_kind": "legacy_authorized",
"baseline_id": baseline_id,
"baseline_target_sha256": runtime_target_fingerprint(runtime_target),
"captured_at": captured_at,
}
def _build_target_entry(
*,
platform: str,
runtime_target: dict[str, Any],
mounts_variable: str,
mounts: list[dict[str, Any]],
extra_variables: dict[str, Any],
) -> dict[str, Any]:
service_name = str(runtime_target["service_name"])
entry: dict[str, Any] = {
"service": service_name,
"runtime_target": dict(runtime_target),
}
if platform == "ibkr":
entry["ACCOUNT_GROUP"] = runtime_target["account_scope"]
dry_run_variable = PLATFORM_DRY_RUN_VARIABLES.get(platform)
if dry_run_variable:
entry[dry_run_variable] = env_string(runtime_target["dry_run_only"])
if mounts_variable:
entry[mounts_variable] = {"strategy_plugins": mounts}
entry.update(extra_variables)
return entry
def _preserve_reserved_cash_fields(
*,
platform: str,
current_entry: dict[str, Any],
replacement: dict[str, Any],
) -> None:
for variable in (
PLATFORM_MIN_RESERVED_CASH_VARIABLES.get(platform),
PLATFORM_RESERVED_CASH_RATIO_VARIABLES.get(platform),
PLATFORM_CASH_ONLY_EXECUTION_VARIABLES.get(platform),
CASH_ONLY_EXECUTION_VARIABLE,
*INCOME_LAYER_VARIABLES,
*OPTION_OVERLAY_VARIABLES,
*RUNTIME_TARGET_VARIABLES,
*DCA_RUNTIME_VARIABLES,
*IBIT_ZSCORE_EXIT_RUNTIME_VARIABLES,
*MARKET_SIGNAL_RUNTIME_VARIABLES,
):
if variable and variable not in replacement and variable in current_entry:
replacement[variable] = current_entry[variable]
def _patch_service_targets(
*,
current_payload: dict[str, Any] | list[Any],
platform: str,
runtime_target: dict[str, Any],
mounts_variable: str,
mounts: list[dict[str, Any]],
extra_variables: dict[str, Any],
allow_create: bool,
) -> dict[str, Any] | list[dict[str, Any]]:
payload = dict(current_payload) if isinstance(current_payload, dict) else None
if payload is not None:
raw_entries = payload.get("targets", [])
if not isinstance(raw_entries, list):
raise ValueError("service targets must be an array")
else:
raw_entries = current_payload
if any(not isinstance(item, dict) for item in raw_entries):
raise ValueError("service target entries must be objects")
entries = [dict(item) for item in raw_entries]
replacement = _build_target_entry(
platform=platform,
runtime_target=runtime_target,
mounts_variable=mounts_variable,
mounts=mounts,
extra_variables=extra_variables,
)
matched_index = select_service_target_entry_index(
runtime_target,
entries,
allow_account_scope_fallback=not allow_create,
)
if matched_index is not None:
current_entry = entries[matched_index]
_preserve_reserved_cash_fields(
platform=platform,
current_entry=current_entry,
replacement=replacement,
)
entries[matched_index] = {**current_entry, **replacement}
elif not allow_create:
platform_label = "IBKR " if platform == "ibkr" else ""
raise ValueError(
f"existing {platform_label}service target was not found; "
"use --allow-create-service-target to append a new target"
)
else:
entries.append(replacement)
if payload is None:
return entries
payload["targets"] = entries
return payload
def build_switch_target(args: argparse.Namespace) -> dict[str, Any]:
platform = _normalize_platform(args.platform)
target_name = _normalize_target_name(args.target_name)
variable_scope = args.variable_scope or DEFAULT_VARIABLE_SCOPE[platform]
if variable_scope not in {"repository", "environment"}:
raise ValueError("variable_scope must be repository or environment")
github_environment = args.github_environment or _default_github_environment(platform, target_name, variable_scope)
runtime_target = _build_runtime_target(args)
extra_variables = _parse_extra_variables(args.extra_variable, args.extra_variables_json)
cash_only_controls = _extract_cash_only_control_fields(extra_variables)
dca_controls = _extract_dca_control_fields(extra_variables)
_extract_ibit_zscore_exit_control_fields(extra_variables)
effective_dca_mode = _effective_dca_mode(args, runtime_target["strategy_profile"], dca_controls)
mounts = _plugin_mounts(args, runtime_target["strategy_profile"], effective_dca_mode)
runtime_target["scheduler"] = _scheduler_plan_for_strategy(runtime_target["strategy_profile"], mounts)
mounts_variable = f"{SUPPORTED_PLATFORMS[platform]['plugin_mounts_prefix']}STRATEGY_PLUGIN_MOUNTS_JSON"
if cash_only_controls.get(CASH_ONLY_EXECUTION_CONTROL_FIELD):
args.cash_only_execution_mode = str(cash_only_controls[CASH_ONLY_EXECUTION_CONTROL_FIELD]).strip().lower()
_reject_direct_dca_extra_variables(extra_variables)
_reject_direct_ibit_zscore_exit_extra_variables(extra_variables)
_reject_research_only_extra_variables(extra_variables)