-
Notifications
You must be signed in to change notification settings - Fork 0
637 lines (610 loc) · 27.3 KB
/
Copy pathmanual-strategy-switch.yml
File metadata and controls
637 lines (610 loc) · 27.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
name: Manual Strategy Switch
on:
workflow_dispatch:
inputs:
platform:
description: "Target platform."
required: true
type: choice
options:
- longbridge
- ibkr
- schwab
- firstrade
- qmt
- binance
target_name:
description: "Target name, e.g. sg, live, live-u1599-tqqq."
required: true
type: string
strategy_profile:
description: "Canonical strategy profile to switch to."
required: true
type: string
execution_mode:
description: "live is gated; dry_run is the universal no-order path. paper is retained only as a legacy alias for dry_run, not P4 paper trading."
required: true
type: choice
default: live
options:
- live
- dry_run
- paper
live_continuity_state:
description: "Optional frozen legacy live baseline state. This cannot create a new live permission or increase risk."
required: true
type: choice
default: NONE
options:
- NONE
- ACTIVE_LKG
- ACTIVE_REDUCED
- RECONCILE_ONLY
- RISK_REDUCTION_ONLY
- PAUSED
- ROLLBACK_LKG
live_continuity_baseline_id:
description: "Required only with a continuity state: audited identifier of the existing authorised baseline."
required: false
type: string
live_continuity_captured_at:
description: "Required only with a continuity state: ISO date when the exact legacy target was captured."
required: false
type: string
variable_scope:
description: "Where GitHub variables are written. blank = platform default."
required: false
type: choice
default: default
options:
- default
- repository
- environment
github_environment:
description: "Environment name when variable_scope=environment. blank = platform default."
required: false
type: string
deployment_selector:
description: "Runtime deployment_selector. blank = derived from target_name."
required: false
type: string
account_selector:
description: "Comma-separated broker account selectors. blank = account_scope."
required: false
type: string
account_scope:
description: "Runtime account_scope/account group. blank = deployment_selector."
required: false
type: string
service_name:
description: "Runtime service name. blank = platform default."
required: false
type: string
plugin_mode:
description: "none disables mounts. current preserves the selected strategy's existing mounts exactly; it cannot add or change a plugin."
required: true
type: choice
default: none
options:
- none
- current
extra_variables_json:
description: "Optional JSON object of non-secret extra variables. DCA profiles may include dca_mode and dca_base_investment_usd control fields. cash_only_execution_mode may be current, enabled, or disabled. Research-only option overlays are rejected."
required: false
type: string
reserved_cash_ratio:
description: "Optional platform reserved-cash ratio override."
required: false
type: string
min_reserved_cash_usd:
description: "Optional platform minimum reserved cash override."
required: false
type: string
income_layer_start_usd:
description: "Optional income layer activation asset amount."
required: false
type: string
income_layer_max_ratio:
description: "Optional income layer maximum allocation ratio."
required: false
type: string
option_overlay_mode:
description: "Option overlay policy: current preserves variables, enabled applies profile defaults, disabled clears it."
required: true
type: choice
default: current
options:
- current
- enabled
- disabled
service_targets_mode:
description: "auto updates an existing multi-service target when configured; allow_create explicitly permits a new target."
required: true
type: choice
default: auto
options:
- auto
- allow_create
- off
apply:
description: "Actually write GitHub variables. false = preview only."
required: true
type: boolean
default: false
trigger_platform_sync:
description: "After apply, dispatch a supported Cloud Run environment sync workflow."
required: true
type: boolean
default: false
confirm_apply:
description: "Required for writes. Use APPLY for variable writes, APPLY_AND_SYNC when trigger_platform_sync=true."
required: false
type: string
platform_sync_workflow:
description: "Cloud Run target platform workflow filename."
required: false
type: string
default: sync-cloud-run-env.yml
permissions:
contents: read
concurrency:
group: runtime-strategy-switch-${{ inputs.platform }}-${{ inputs.target_name }}
cancel-in-progress: false
jobs:
switch:
name: Build and apply runtime switch
runs-on: ubuntu-latest
timeout-minutes: 15
environment: runtime-strategy-switch
permissions:
contents: read
env:
GH_TOKEN: ${{ secrets.RUNTIME_SETTINGS_GH_TOKEN }}
PLATFORM: ${{ inputs.platform }}
TARGET_NAME: ${{ inputs.target_name }}
STRATEGY_PROFILE: ${{ inputs.strategy_profile }}
EXECUTION_MODE: ${{ inputs.execution_mode }}
LIVE_CONTINUITY_STATE: ${{ inputs.live_continuity_state }}
LIVE_CONTINUITY_BASELINE_ID: ${{ inputs.live_continuity_baseline_id }}
LIVE_CONTINUITY_CAPTURED_AT: ${{ inputs.live_continuity_captured_at }}
VARIABLE_SCOPE: ${{ inputs.variable_scope }}
GITHUB_ENVIRONMENT_NAME: ${{ inputs.github_environment }}
DEPLOYMENT_SELECTOR: ${{ inputs.deployment_selector }}
ACCOUNT_SELECTOR: ${{ inputs.account_selector }}
ACCOUNT_SCOPE: ${{ inputs.account_scope }}
SERVICE_NAME: ${{ inputs.service_name }}
PLUGIN_MODE: ${{ inputs.plugin_mode }}
EXTRA_VARIABLES_JSON: ${{ inputs.extra_variables_json }}
RESERVED_CASH_RATIO: ${{ inputs.reserved_cash_ratio }}
MIN_RESERVED_CASH_USD: ${{ inputs.min_reserved_cash_usd }}
INCOME_LAYER_START_USD: ${{ inputs.income_layer_start_usd }}
INCOME_LAYER_MAX_RATIO: ${{ inputs.income_layer_max_ratio }}
OPTION_OVERLAY_MODE: ${{ inputs.option_overlay_mode }}
SERVICE_TARGETS_MODE: ${{ inputs.service_targets_mode }}
APPLY_SWITCH: ${{ inputs.apply }}
TRIGGER_PLATFORM_SYNC: ${{ inputs.trigger_platform_sync }}
CONFIRM_APPLY: ${{ inputs.confirm_apply }}
PLATFORM_SYNC_WORKFLOW: ${{ inputs.platform_sync_workflow }}
STRATEGY_SWITCH_CONSOLE_URL: ${{ vars.STRATEGY_SWITCH_CONSOLE_URL }}
STRATEGY_SWITCH_SYNC_TOKEN: ${{ secrets.STRATEGY_SWITCH_SYNC_TOKEN || secrets.RUNTIME_SETTINGS_GH_TOKEN }}
RUNTIME_SETTINGS_PLATFORM_REPOSITORIES_JSON: ${{ vars.RUNTIME_SETTINGS_PLATFORM_REPOSITORIES_JSON }}
RUNTIME_SETTINGS_LONGBRIDGE_REPO: ${{ vars.RUNTIME_SETTINGS_LONGBRIDGE_REPO }}
RUNTIME_SETTINGS_IBKR_REPO: ${{ vars.RUNTIME_SETTINGS_IBKR_REPO }}
RUNTIME_SETTINGS_SCHWAB_REPO: ${{ vars.RUNTIME_SETTINGS_SCHWAB_REPO }}
RUNTIME_SETTINGS_FIRSTRADE_REPO: ${{ vars.RUNTIME_SETTINGS_FIRSTRADE_REPO }}
RUNTIME_SETTINGS_QMT_REPO: ${{ vars.RUNTIME_SETTINGS_QMT_REPO }}
RUNTIME_SETTINGS_BINANCE_REPO: ${{ vars.RUNTIME_SETTINGS_BINANCE_REPO }}
steps:
- name: Checkout
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: Enforce write safety gates
run: |
set -euo pipefail
if [ "${APPLY_SWITCH}" != "true" ] && [ "${TRIGGER_PLATFORM_SYNC}" = "true" ]; then
echo "trigger_platform_sync=true is invalid unless apply=true." >&2
exit 2
fi
if [ "${LIVE_CONTINUITY_STATE}" != "NONE" ]; then
echo "Legacy continuity recovery is intentionally unavailable from this workflow. Use the private reconciliation recovery controller after fresh read-only evidence, bound dual review, and an owner confirmation." >&2
exit 2
fi
settings_activation="$(
python3 python/scripts/runtime_settings.py settings-activation "${PLATFORM}"
)"
if [ "${TRIGGER_PLATFORM_SYNC}" = "true" ]; then
case "${settings_activation}" in
cloud_run_sync_workflow)
;;
next_runtime_workflow_dispatch)
echo "Oracle/VPS runtime activates settings on its next externally scheduled GitHub Actions dispatch; trigger_platform_sync is unsupported for ${PLATFORM}." >&2
exit 2
;;
not_wired)
echo "QMT has no live runtime configuration; trigger_platform_sync is unsupported." >&2
exit 2
;;
*)
echo "Unsupported settings activation mode for ${PLATFORM}: ${settings_activation}" >&2
exit 2
;;
esac
fi
if [ "${APPLY_SWITCH}" = "true" ]; then
if [ -z "${GH_TOKEN:-}" ]; then
echo "RUNTIME_SETTINGS_GH_TOKEN is required for apply=true." >&2
exit 2
fi
if [ "${TRIGGER_PLATFORM_SYNC}" = "true" ]; then
if [ "${CONFIRM_APPLY:-}" != "APPLY_AND_SYNC" ]; then
echo "Set confirm_apply=APPLY_AND_SYNC when trigger_platform_sync=true." >&2
exit 2
fi
elif [ "${CONFIRM_APPLY:-}" != "APPLY" ]; then
echo "Set confirm_apply=APPLY when apply=true." >&2
exit 2
fi
fi
case "${PLATFORM}" in
longbridge|ibkr|schwab|firstrade)
if [ "${SERVICE_TARGETS_MODE}" != "off" ] && [ -z "${GH_TOKEN:-}" ]; then
echo "RUNTIME_SETTINGS_GH_TOKEN is required for multi-service preview because the workflow must read and patch CLOUD_RUN_SERVICE_TARGETS_JSON." >&2
exit 2
fi
;;
*)
if [ "${SERVICE_TARGETS_MODE}" = "allow_create" ]; then
echo "service_targets_mode=allow_create is not supported for ${PLATFORM}." >&2
exit 2
fi
;;
esac
- name: Resolve platform repository
id: platform
run: |
set -euo pipefail
repo="$(python3 python/scripts/runtime_settings.py repository "${PLATFORM}")"
echo "repository=${repo}" >> "$GITHUB_OUTPUT"
- name: Fetch existing service targets
if: >-
(env.APPLY_SWITCH == 'true' || env.SERVICE_TARGETS_MODE != 'off') &&
contains(fromJSON('["longbridge","ibkr","schwab","firstrade"]'), env.PLATFORM)
env:
TARGET_REPOSITORY: ${{ steps.platform.outputs.repository }}
run: |
set -euo pipefail
output_file="${RUNNER_TEMP}/existing-service-targets.json"
target_environment=""
if [ "${PLATFORM}" = "ibkr" ] && [ "${VARIABLE_SCOPE}" = "environment" ]; then
target_environment="${GITHUB_ENVIRONMENT_NAME:-${TARGET_NAME}}"
fi
python - <<'PY' \
"${TARGET_REPOSITORY}" \
"${output_file}" \
"${target_environment}" \
"${PLATFORM}" \
"${SERVICE_TARGETS_MODE}"
import json
import os
import subprocess
import sys
repo, output_path, environment, platform, mode = sys.argv[1:6]
command = ["gh", "variable", "list", "--repo", repo, "--json", "name,value"]
if environment:
command.extend(["--env", environment])
raw = subprocess.check_output(
command,
text=True,
)
variables = json.loads(raw)
value = ""
for item in variables:
if item.get("name") == "CLOUD_RUN_SERVICE_TARGETS_JSON":
value = str(item.get("value") or "").strip()
break
if not value:
if (platform == "ibkr" and mode != "off") or mode == "allow_create":
with open(output_path, "w", encoding="utf-8") as handle:
handle.write("{}")
else:
try:
os.unlink(output_path)
except FileNotFoundError:
pass
raise SystemExit(0)
try:
payload = json.loads(value)
except json.JSONDecodeError:
payload = json.loads(value.replace("\\n", "\n"))
with open(output_path, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, separators=(",", ":"))
PY
if [ -f "${output_file}" ]; then
echo "EXISTING_SERVICE_TARGETS_JSON_FILE=${output_file}" >> "$GITHUB_ENV"
fi
- name: Reject unsafe service inventory bypass
if: env.APPLY_SWITCH == 'true' && env.SERVICE_TARGETS_MODE == 'off'
run: |
set -euo pipefail
if [ -f "${EXISTING_SERVICE_TARGETS_JSON_FILE:-}" ]; then
echo "existing CLOUD_RUN_SERVICE_TARGETS_JSON requires service_targets_mode=patch or allow_create" >&2
exit 2
fi
- name: Fetch current plugin mounts for continuity
if: env.PLUGIN_MODE == 'current'
env:
TARGET_REPOSITORY: ${{ steps.platform.outputs.repository }}
run: |
set -euo pipefail
case "${PLATFORM}" in
longbridge) mounts_variable="LONGBRIDGE_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
ibkr) mounts_variable="IBKR_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
schwab) mounts_variable="SCHWAB_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
firstrade) mounts_variable="FIRSTRADE_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
qmt) mounts_variable="QMT_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
binance) mounts_variable="BINANCE_STRATEGY_PLUGIN_MOUNTS_JSON" ;;
*) echo "Unsupported platform: ${PLATFORM}" >&2; exit 2 ;;
esac
target_environment=""
if [ "${VARIABLE_SCOPE}" = "environment" ]; then
target_environment="${GITHUB_ENVIRONMENT_NAME:-${TARGET_NAME}}"
elif [ "${VARIABLE_SCOPE}" = "default" ] && [ "${PLATFORM}" = "longbridge" ]; then
target_environment="longbridge-${TARGET_NAME}"
fi
output_file="${RUNNER_TEMP}/current-plugin-mounts.json"
if [ -f "${EXISTING_SERVICE_TARGETS_JSON_FILE:-}" ]; then
set +e
python3 python/scripts/extract_service_plugin_mounts.py \
--service-targets-file "${EXISTING_SERVICE_TARGETS_JSON_FILE}" \
--mounts-variable "${mounts_variable}" \
--service-name "${SERVICE_NAME:-}" \
--target-name "${TARGET_NAME}" \
--output "${output_file}"
extraction_status=$?
set -e
if [ "${extraction_status}" -eq 0 ]; then
echo "CURRENT_PLUGIN_MOUNTS_JSON_FILE=${output_file}" >> "$GITHUB_ENV"
exit 0
fi
if [ "${extraction_status}" -ne 3 ]; then
echo "Unable to safely preserve service-specific ${mounts_variable}." >&2
exit "${extraction_status}"
fi
fi
python - <<'PY' "${TARGET_REPOSITORY}" "${mounts_variable}" "${target_environment}" "${output_file}"
import json
import subprocess
import sys
repo, variable, environment, output_path = sys.argv[1:5]
command = ["gh", "variable", "list", "--repo", repo, "--json", "name,value"]
if environment:
command.extend(["--env", environment])
values = json.loads(subprocess.check_output(command, text=True))
raw = next((item.get("value") for item in values if item.get("name") == variable), None)
if not isinstance(raw, str) or not raw.strip():
raise SystemExit(f"{variable} is required when plugin_mode=current")
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
raise SystemExit(f"{variable} must contain valid JSON") from exc
if not isinstance(payload, dict) or not isinstance(payload.get("strategy_plugins"), list):
raise SystemExit(f"{variable} must contain a strategy_plugins array")
with open(output_path, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, separators=(",", ":"))
PY
echo "CURRENT_PLUGIN_MOUNTS_JSON_FILE=${output_file}" >> "$GITHUB_ENV"
- name: Build switch target
run: |
set -euo pipefail
target_file="${RUNNER_TEMP}/runtime-switch-target.json"
args=(
--platform "${PLATFORM}"
--target-name "${TARGET_NAME}"
--strategy-profile "${STRATEGY_PROFILE}"
--execution-mode "${EXECUTION_MODE}"
--plugin-mode "${PLUGIN_MODE}"
--option-overlay-mode "${OPTION_OVERLAY_MODE}"
--output "${target_file}"
)
if [ "${VARIABLE_SCOPE}" != "default" ]; then
args+=(--variable-scope "${VARIABLE_SCOPE}")
fi
if [ -n "${GITHUB_ENVIRONMENT_NAME:-}" ]; then
args+=(--github-environment "${GITHUB_ENVIRONMENT_NAME}")
fi
if [ -n "${DEPLOYMENT_SELECTOR:-}" ]; then
args+=(--deployment-selector "${DEPLOYMENT_SELECTOR}")
fi
if [ -n "${ACCOUNT_SELECTOR:-}" ]; then
args+=(--account-selector "${ACCOUNT_SELECTOR}")
fi
if [ -n "${ACCOUNT_SCOPE:-}" ]; then
args+=(--account-scope "${ACCOUNT_SCOPE}")
fi
if [ -n "${SERVICE_NAME:-}" ]; then
args+=(--service-name "${SERVICE_NAME}")
fi
if [ "${PLUGIN_MODE}" = "current" ]; then
args+=(--current-plugin-mounts-json-file "${CURRENT_PLUGIN_MOUNTS_JSON_FILE}")
fi
if [ "${LIVE_CONTINUITY_STATE}" != "NONE" ]; then
args+=(--live-continuity-state "${LIVE_CONTINUITY_STATE}")
args+=(--live-continuity-baseline-id "${LIVE_CONTINUITY_BASELINE_ID}")
args+=(--live-continuity-captured-at "${LIVE_CONTINUITY_CAPTURED_AT}")
fi
if [ -n "${EXTRA_VARIABLES_JSON:-}" ]; then
args+=(--extra-variables-json "${EXTRA_VARIABLES_JSON}")
fi
if [ -n "${RESERVED_CASH_RATIO:-}" ]; then
args+=(--reserved-cash-ratio "${RESERVED_CASH_RATIO}")
fi
if [ -n "${MIN_RESERVED_CASH_USD:-}" ]; then
args+=(--min-reserved-cash-usd "${MIN_RESERVED_CASH_USD}")
fi
if [ -n "${INCOME_LAYER_START_USD:-}" ]; then
args+=(--income-layer-start-usd "${INCOME_LAYER_START_USD}")
fi
if [ -n "${INCOME_LAYER_MAX_RATIO:-}" ]; then
args+=(--income-layer-max-ratio "${INCOME_LAYER_MAX_RATIO}")
fi
if [ -f "${EXISTING_SERVICE_TARGETS_JSON_FILE:-}" ]; then
args+=(--existing-service-targets-json-file "${EXISTING_SERVICE_TARGETS_JSON_FILE}")
fi
if [ "${SERVICE_TARGETS_MODE}" = "allow_create" ]; then
args+=(--allow-create-service-target)
fi
python3 python/scripts/build_runtime_switch.py "${args[@]}"
python3 python/scripts/runtime_settings.py validate "${target_file}"
echo "TARGET_FILE=${target_file}" >> "$GITHUB_ENV"
- name: Preview assignments
run: |
set -euo pipefail
python3 python/scripts/runtime_settings.py render "${TARGET_FILE}" --format json --redact-values > "${RUNNER_TEMP}/assignments.json"
python - <<'PY' "${TARGET_FILE}" "${RUNNER_TEMP}/assignments.json" >> "$GITHUB_STEP_SUMMARY"
import json
import sys
target = json.load(open(sys.argv[1], encoding="utf-8"))
assignments = json.load(open(sys.argv[2], encoding="utf-8"))
print("## Runtime switch preview")
print()
print(f"- platform: `{target['runtime_target']['platform_id']}`")
print("- target_id: `<redacted>`")
print("- repository: `<redacted>`")
print(f"- variable_scope: `{target['github']['variable_scope']}`")
if target["github"].get("environment"):
print("- environment: `<redacted>`")
print("- strategy_profile: `<redacted>`")
print("- service_name: `<redacted>`")
print(f"- execution_mode: `{target['runtime_target']['execution_mode']}`")
continuity = target["runtime_target"].get("live_continuity")
if isinstance(continuity, dict):
print(f"- live_continuity_state: `{continuity['state']}`")
print(f"- live_continuity_baseline_kind: `{continuity['baseline_kind']}`")
print("- values: `<redacted>`")
print()
print("### Variables")
for assignment in assignments:
print(f"- `{assignment['name']}` = `{assignment['value']}`")
PY
- name: Preflight IBKR deployment plan
if: env.PLATFORM == 'ibkr' && env.SERVICE_TARGETS_MODE != 'off'
env:
TARGET_REPOSITORY: ${{ steps.platform.outputs.repository }}
run: |
set -euo pipefail
platform_root="${RUNNER_TEMP}/interactive-brokers-platform"
repository_variables_file="${RUNNER_TEMP}/ibkr-repository-variables.json"
trap 'rm -f "${repository_variables_file}"' EXIT
gh auth setup-git
git clone --quiet --depth 1 --branch main \
"https://github.com/${TARGET_REPOSITORY}.git" \
"${platform_root}"
python3 -m pip install --quiet uv
uv sync --frozen --no-dev --quiet --project "${platform_root}"
gh variable list \
--repo "${TARGET_REPOSITORY}" \
--json name,value \
> "${repository_variables_file}"
python3 python/scripts/preflight_ibkr_switch.py \
--target-file "${TARGET_FILE}" \
--platform-root "${platform_root}" \
--repository-variables-file "${repository_variables_file}"
- name: Apply GitHub variable updates
if: env.APPLY_SWITCH == 'true'
run: python3 python/scripts/runtime_settings.py apply "${TARGET_FILE}" --yes
- name: Dispatch platform sync workflow
if: env.APPLY_SWITCH == 'true' && env.TRIGGER_PLATFORM_SYNC == 'true'
env:
TARGET_REPOSITORY: ${{ steps.platform.outputs.repository }}
run: |
set -euo pipefail
workflow="${PLATFORM_SYNC_WORKFLOW:-sync-cloud-run-env.yml}"
case "${PLATFORM}" in
longbridge|ibkr)
gh workflow run "${workflow}" --repo "${TARGET_REPOSITORY}" --ref main -f target=configured
;;
schwab|firstrade)
gh workflow run "${workflow}" --repo "${TARGET_REPOSITORY}" --ref main
;;
*)
echo "No platform sync dispatch rule for ${PLATFORM}" >&2
exit 2
;;
esac
echo "Dispatched ${workflow} in ${TARGET_REPOSITORY}."
- name: Sync strategy switch account defaults
if: env.APPLY_SWITCH == 'true' && env.STRATEGY_SWITCH_CONSOLE_URL != ''
run: |
set -euo pipefail
python - <<'PY'
import json
import os
import sys
import urllib.error
import urllib.request
root = os.environ.get("GITHUB_WORKSPACE") or os.getcwd()
sys.path.insert(0, os.path.join(root, "python", "scripts"))
import runtime_settings
base_url = os.environ["STRATEGY_SWITCH_CONSOLE_URL"].rstrip("/")
token = os.environ["STRATEGY_SWITCH_SYNC_TOKEN"]
if not token:
print("::warning::STRATEGY_SWITCH_SYNC_TOKEN is missing; account default sync skipped")
raise SystemExit(0)
with open(os.environ["TARGET_FILE"], encoding="utf-8") as handle:
target = json.load(handle)
runtime_target = target["runtime_target"]
github = target["github"]
continuity = runtime_target.get("live_continuity")
if not isinstance(continuity, dict):
continuity = {}
payload = {
"platform": runtime_target["platform_id"],
"target_name": target["target_id"].split("/", 1)[1],
"strategy_profile": runtime_target["strategy_profile"],
"execution_mode": runtime_target["execution_mode"],
"live_continuity_state": continuity.get("state", "NONE"),
"variable_scope": "default",
"plugin_mode": os.environ["PLUGIN_MODE"],
"option_overlay_mode": os.environ.get("OPTION_OVERLAY_MODE", "current"),
"cash_only_execution_mode": "current",
"deployment_selector": runtime_target["deployment_selector"],
"account_selector": ",".join(runtime_target["account_selector"]),
"account_scope": runtime_target["account_scope"],
"service_name": runtime_target["service_name"],
}
if continuity.get("state") and continuity.get("state") != "NONE":
payload["live_continuity_baseline_id"] = continuity.get("baseline_id", "")
payload["live_continuity_captured_at"] = continuity.get("captured_at", "")
extra_variables_json = os.environ.get("EXTRA_VARIABLES_JSON", "").strip()
if extra_variables_json:
try:
extra_variables = json.loads(extra_variables_json)
except json.JSONDecodeError:
extra_variables = {}
cash_only_mode = str(extra_variables.get("cash_only_execution_mode") or "current").strip().lower()
if cash_only_mode in {"enabled", "disabled"}:
payload["cash_only_execution_mode"] = cash_only_mode
payload.update(runtime_settings.extract_account_sync_controls(target))
if github.get("environment"):
payload["github_environment"] = github["environment"]
request = urllib.request.Request(
f"{base_url}/api/internal/sync-account-default",
data=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"User-Agent": "QuantRuntimeSettings-strategy-switch-sync",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=20) as response:
body = response.read().decode("utf-8")
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"::warning::Strategy switch account default sync failed: HTTP {exc.code}: {body[:1000]}")
raise SystemExit(0)
except Exception as exc: # noqa: BLE001
print(f"::warning::Strategy switch account default sync failed: {exc}")
raise SystemExit(0)
print(body)
PY