From 26259612396e9ec78461d0d44d4960614c0e693a Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:15:14 +0800 Subject: [PATCH] refactor: migrate package layout to src/firstrade_platform - Move application, entrypoints, notifications, main, and strategy/runtime modules into src/firstrade_platform/ with updated setuptools, pytest, coverage, Dockerfile, CODEOWNERS, script, and test imports. - Remove pytest from runtime dependencies in pyproject.toml and refresh uv.lock via uv lock. - Add executable check for rg in CI public configuration scan and fix remaining test layout/import checks. - Sync README.md, README.zh-CN.md, AGENTS.md, CONTRIBUTING.md, and docs/ for src/firstrade_platform/ paths. - Update Dependabot actions group/prefix, tighten commitlint rules, add dependabot-policy.json, and drop retired ft-account-facts-sync-once.yml. --- .github/CODEOWNERS | 10 +- .github/dependabot.yml | 4 +- .github/scripts/dependabot-policy.json | 5 + .github/workflows/ci.yml | 3 +- .github/workflows/engineering-governance.yml | 8 +- .github/workflows/fee-schedule-check.yml | 4 +- .../workflows/ft-account-facts-sync-once.yml | 82 ---------------- AGENTS.md | 7 +- CONTRIBUTING.md | 2 +- Dockerfile | 2 +- README.md | 8 +- README.zh-CN.md | 10 +- docs/shared-test-imports.md | 5 +- docs/statement-reconciliation.md | 4 +- docs/statement-reconciliation.zh-CN.md | 4 +- pyproject.toml | 23 +---- scripts/build_cloud_run_env_sync_plan.py | 5 +- scripts/check_fee_schedule.py | 14 ++- scripts/emit_unified_digest_candidates.py | 9 +- scripts/execution_report_heartbeat.py | 4 +- scripts/firstrade_smoke_check.py | 7 +- scripts/inspect_account_history_schema.py | 7 +- scripts/print_strategy_profile_status.py | 7 +- scripts/publish_archived_account_history.py | 10 +- scripts/publish_digest_before_read.py | 6 +- scripts/publish_runtime_daily.py | 2 +- scripts/release_cached_currency.py | 2 +- scripts/send_paper_notification_preview.py | 9 +- ...erify_deployed_runtime_target_admission.py | 7 +- src/firstrade_platform/__init__.py | 1 + .../application}/__init__.py | 0 .../application}/account_facts_publisher.py | 2 +- .../application}/account_facts_readonly.py | 2 +- .../application}/account_payload_utils.py | 0 .../application}/broker_reconciliation.py | 0 .../application}/execution_receipt_adapter.py | 0 .../application}/execution_service.py | 0 .../application}/firstrade_client.py | 4 +- .../application}/firstrade_fee_schedule.py | 0 .../application}/paper_execution_admission.py | 0 .../paper_execution_command_consumer.py | 0 .../application}/rebalance_service.py | 28 +++--- .../application}/runtime_broker_adapters.py | 4 +- .../application}/session_check_service.py | 8 +- .../application}/signal_snapshot.py | 0 .../application}/state_persistence.py | 0 .../application}/statement_reconciliation.py | 2 +- .../application}/strategy_run_persistence.py | 4 +- .../firstrade_platform/decision_mapper.py | 0 .../entrypoints}/__init__.py | 0 .../entrypoints}/cloud_run.py | 0 main.py => src/firstrade_platform/main.py | 44 ++++----- .../notifications}/__init__.py | 0 .../notifications}/compact_adapter.py | 0 .../digest_snapshot/__init__.py | 0 .../digest_snapshot/digest_archive.py | 0 .../digest_snapshot/digest_candidates.py | 0 .../digest_snapshot/digest_routing.py | 0 .../digest_snapshot/unified_contract.py | 0 .../notifications}/telegram.py | 4 +- .../notifications}/unified.py | 10 +- .../runtime_config_support.py | 4 +- .../runtime_execution_policy.py | 2 +- .../firstrade_platform/strategy_loader.py | 7 +- .../firstrade_platform/strategy_registry.py | 0 .../firstrade_platform/strategy_runtime.py | 4 +- tests/test_account_alert_redaction.py | 8 +- tests/test_account_facts_endpoint.py | 8 +- tests/test_account_facts_publisher.py | 2 +- tests/test_account_facts_readonly.py | 2 +- tests/test_broker_reconciliation.py | 2 +- tests/test_build_market_inputs.py | 2 +- tests/test_cached_funds_archive.py | 6 +- tests/test_candidate_failure_diagnostics.py | 2 +- tests/test_check_fee_schedule.py | 2 +- tests/test_cloud_run_entrypoint.py | 2 +- tests/test_compact_notification_adapter.py | 2 +- tests/test_coverage_source_layout.py | 93 ++++++++++++------- tests/test_daily_notification_policy.py | 20 ++-- tests/test_decision_mapper.py | 2 +- tests/test_execution_receipt_adapter.py | 2 +- tests/test_execution_service.py | 4 +- tests/test_firstrade_client.py | 8 +- tests/test_forced_session_renewal.py | 12 +-- tests/test_heartbeat_archive_reader.py | 4 +- tests/test_inspect_account_history_schema.py | 2 +- tests/test_market_hours_gate.py | 2 +- tests/test_notification_consolidation.py | 4 +- tests/test_notification_off_equivalence.py | 10 +- tests/test_notification_qrs_roundtrip.py | 2 +- tests/test_notification_quiet.py | 2 +- tests/test_notification_scoped_state.py | 2 +- tests/test_notification_storage_and_wiring.py | 6 +- tests/test_notifications.py | 10 +- tests/test_notifications_telegram.py | 2 +- tests/test_paper_execution_admission.py | 2 +- .../test_paper_execution_command_consumer.py | 2 +- tests/test_paper_notification_preview.py | 11 ++- ..._plugin_alert_settings_characterization.py | 4 +- .../test_publish_archived_account_history.py | 4 +- tests/test_publish_digest_before_read.py | 6 +- tests/test_rebalance_service.py | 90 +++++++++--------- tests/test_request_handling.py | 6 +- tests/test_runtime_broker_adapters.py | 2 +- tests/test_runtime_config_support.py | 2 +- tests/test_runtime_execution_policy.py | 20 ++-- tests/test_runtime_notification_i18n.py | 7 +- tests/test_sender_receipt_identity.py | 4 +- tests/test_session_check_service.py | 4 +- tests/test_session_renew_auth_logging.py | 6 +- tests/test_signal_snapshot.py | 2 +- tests/test_state_error_redaction.py | 2 +- tests/test_statement_reconciliation.py | 4 +- tests/test_strategy_registry.py | 4 +- tests/test_strategy_run_claim.py | 4 +- tests/test_strategy_runtime.py | 6 +- tests/test_telegram_token_resolution.py | 8 +- tests/test_unified_notification_wiring.py | 2 +- tests/test_value_target_facade_parity.py | 2 +- tests/value_target_parity_cases.py | 4 +- uv.lock | 2 - 121 files changed, 411 insertions(+), 424 deletions(-) create mode 100644 .github/scripts/dependabot-policy.json delete mode 100644 .github/workflows/ft-account-facts-sync-once.yml create mode 100644 src/firstrade_platform/__init__.py rename {application => src/firstrade_platform/application}/__init__.py (100%) rename {application => src/firstrade_platform/application}/account_facts_publisher.py (99%) rename {application => src/firstrade_platform/application}/account_facts_readonly.py (99%) rename {application => src/firstrade_platform/application}/account_payload_utils.py (100%) rename {application => src/firstrade_platform/application}/broker_reconciliation.py (100%) rename {application => src/firstrade_platform/application}/execution_receipt_adapter.py (100%) rename {application => src/firstrade_platform/application}/execution_service.py (100%) rename {application => src/firstrade_platform/application}/firstrade_client.py (99%) rename {application => src/firstrade_platform/application}/firstrade_fee_schedule.py (100%) rename {application => src/firstrade_platform/application}/paper_execution_admission.py (100%) rename {application => src/firstrade_platform/application}/paper_execution_command_consumer.py (100%) rename {application => src/firstrade_platform/application}/rebalance_service.py (97%) rename {application => src/firstrade_platform/application}/runtime_broker_adapters.py (99%) rename {application => src/firstrade_platform/application}/session_check_service.py (98%) rename {application => src/firstrade_platform/application}/signal_snapshot.py (100%) rename {application => src/firstrade_platform/application}/state_persistence.py (100%) rename {application => src/firstrade_platform/application}/statement_reconciliation.py (99%) rename {application => src/firstrade_platform/application}/strategy_run_persistence.py (98%) rename decision_mapper.py => src/firstrade_platform/decision_mapper.py (100%) rename {entrypoints => src/firstrade_platform/entrypoints}/__init__.py (100%) rename {entrypoints => src/firstrade_platform/entrypoints}/cloud_run.py (100%) rename main.py => src/firstrade_platform/main.py (96%) rename {notifications => src/firstrade_platform/notifications}/__init__.py (100%) rename {notifications => src/firstrade_platform/notifications}/compact_adapter.py (100%) rename {notifications => src/firstrade_platform/notifications}/digest_snapshot/__init__.py (100%) rename {notifications => src/firstrade_platform/notifications}/digest_snapshot/digest_archive.py (100%) rename {notifications => src/firstrade_platform/notifications}/digest_snapshot/digest_candidates.py (100%) rename {notifications => src/firstrade_platform/notifications}/digest_snapshot/digest_routing.py (100%) rename {notifications => src/firstrade_platform/notifications}/digest_snapshot/unified_contract.py (100%) rename {notifications => src/firstrade_platform/notifications}/telegram.py (99%) rename {notifications => src/firstrade_platform/notifications}/unified.py (98%) rename runtime_config_support.py => src/firstrade_platform/runtime_config_support.py (99%) rename runtime_execution_policy.py => src/firstrade_platform/runtime_execution_policy.py (92%) rename strategy_loader.py => src/firstrade_platform/strategy_loader.py (88%) rename strategy_registry.py => src/firstrade_platform/strategy_registry.py (100%) rename strategy_runtime.py => src/firstrade_platform/strategy_runtime.py (98%) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 1b4ddb84..d358e2db 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4,9 +4,9 @@ /.env.example @Pigbibi /.github/CODEOWNERS @Pigbibi /.github/workflows/ @Pigbibi -/application/execution_receipt_adapter.py @Pigbibi -/application/execution_service.py @Pigbibi -/application/paper_execution_admission.py @Pigbibi -/application/paper_execution_command_consumer.py @Pigbibi -/runtime_execution_policy.py @Pigbibi +/src/firstrade_platform/application/execution_receipt_adapter.py @Pigbibi +/src/firstrade_platform/application/execution_service.py @Pigbibi +/src/firstrade_platform/application/paper_execution_admission.py @Pigbibi +/src/firstrade_platform/application/paper_execution_command_consumer.py @Pigbibi +/src/firstrade_platform/runtime_execution_policy.py @Pigbibi /scripts/execution_report_heartbeat.py @Pigbibi diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 81a320c1..b66e64dd 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -13,8 +13,10 @@ updates: directory: / schedule: interval: weekly + commit-message: + prefix: "chore" groups: - actions-minor-and-patch: + actions: patterns: - "*" open-pull-requests-limit: 3 diff --git a/.github/scripts/dependabot-policy.json b/.github/scripts/dependabot-policy.json new file mode 100644 index 00000000..4c275195 --- /dev/null +++ b/.github/scripts/dependabot-policy.json @@ -0,0 +1,5 @@ +{ + "action_files": [ + ".github/workflows/ci.yml" + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4f34f60..fb60bd21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,8 @@ jobs: shell: bash run: | set -euo pipefail - command -v rg + rg_bin="$(command -v rg)" + test -x "$rg_bin" if rg -l '\$\{\{[[:space:]]*vars\.(GLOBAL_TELEGRAM_CHAT_ID|CLOUD_RUN_SERVICES|CLOUD_RUN_SERVICE|RUNTIME_HEARTBEAT_REQUIRED_SERVICES|RUNTIME_GUARD_SCHEDULER_JOB_PATTERN)([[:space:]]|\}\}|\|\|)' .github/workflows; then echo "Sensitive operational runtime configuration must use GitHub Secrets, not GitHub Variables." >&2 exit 1 diff --git a/.github/workflows/engineering-governance.yml b/.github/workflows/engineering-governance.yml index 37dd6caf..6da83ede 100644 --- a/.github/workflows/engineering-governance.yml +++ b/.github/workflows/engineering-governance.yml @@ -43,6 +43,12 @@ jobs: tool="$RUNNER_TEMP/governance-commitlint" npm install --prefix "$tool" --ignore-scripts --no-audit --no-fund \ @commitlint/cli@21.2.4 @commitlint/config-conventional@21.2.4 - printf '%s\n' "module.exports = {extends: [require.resolve('@commitlint/config-conventional')], defaultIgnores: true, ignores: [(message) => /^Merge /.test(message)], rules: {'subject-case': [0], 'header-max-length': [2, 'always', 72], 'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'refactor', 'test', 'chore', 'perf', 'ci']]}};" > "$tool/commitlint.config.cjs" + printf '%s\n' "module.exports = {extends: [require.resolve('@commitlint/config-conventional')], defaultIgnores: true, rules: {'subject-case': [0], 'header-max-length': [2, 'always', 72], 'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'refactor', 'test', 'chore', 'perf', 'ci', 'build']]}};" > "$tool/commitlint.config.cjs" + for message in 'Merge bypass' 'Merge fix: bypass'; do + if printf '%s\n' "$message" | node "$tool/node_modules/@commitlint/cli/cli.js" --config "$tool/commitlint.config.cjs" >/dev/null 2>&1; then + echo "commitlint incorrectly ignored: $message" >&2 + exit 1 + fi + done node "$tool/node_modules/@commitlint/cli/cli.js" \ --config "$tool/commitlint.config.cjs" --from "$PR_BASE" --to "$PR_HEAD" --verbose diff --git a/.github/workflows/fee-schedule-check.yml b/.github/workflows/fee-schedule-check.yml index b35165f0..bd638beb 100644 --- a/.github/workflows/fee-schedule-check.yml +++ b/.github/workflows/fee-schedule-check.yml @@ -3,7 +3,7 @@ name: Fee schedule check # Monthly review of the Firstrade fee schedule (tracking issue #497). # # check: compares the SEC Section 31 rate and the FINRA TAF rates on the official sites with -# application/firstrade_fee_schedule.py. Any fetch/parse failure is an error, never a pass. +# src/firstrade_platform/application/firstrade_fee_schedule.py. Any fetch/parse failure is an error, never a pass. # bump: only when every value is unchanged. Pushes a branch that moves `verified_through` to the # end of next month (plus the test pin and docs) and opens a PR. It never merges. # notify: when rates changed, the check failed, or the PR could not be opened. Opens or updates one @@ -205,7 +205,7 @@ jobs: echo echo "## What changed" echo - echo "Moves \`verified_through\` in \`application/firstrade_fee_schedule.py\` to \`$new_date\`" + echo "Moves \`verified_through\` in \`src/firstrade_platform/application/firstrade_fee_schedule.py\` to \`$new_date\`" echo "so sells dated up to then keep reconciling instead of returning \`unsupported\`. No" echo "rate row was changed. The test review pin and the doc mentions move with it." echo diff --git a/.github/workflows/ft-account-facts-sync-once.yml b/.github/workflows/ft-account-facts-sync-once.yml deleted file mode 100644 index c99f8898..00000000 --- a/.github/workflows/ft-account-facts-sync-once.yml +++ /dev/null @@ -1,82 +0,0 @@ -name: FT account-facts sync once - -# Supported path: dispatch Invoke Cloud Run → Scheduler OIDC + app Authorization -# against /account-facts-sync. The previous Cloud Run Job self-POST returned -# gateway HTML 404 (run 37898342496). A workflow_call reusable wrapper hit -# startup_failure (run 37915762568); same-repo workflow_dispatch is the -# reliable hand-off. - -on: - workflow_dispatch: - -permissions: - actions: write - contents: read - -concurrency: - group: ft-account-facts-sync-once - cancel-in-progress: false - -jobs: - sync: - name: Dispatch Invoke for /account-facts-sync - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - name: Trigger Invoke Cloud Run - id: trigger - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - before="$(date -u +%Y-%m-%dT%H:%M:%SZ)" - echo "before=${before}" >> "$GITHUB_OUTPUT" - gh workflow run "Invoke Cloud Run" \ - --repo "${GITHUB_REPOSITORY}" \ - --ref "${GITHUB_REF_NAME}" \ - -f path=/account-facts-sync \ - -f allow_live_execution=false - echo "Dispatched Invoke Cloud Run for /account-facts-sync (after ${before})" - - - name: Wait for Invoke result - env: - GH_TOKEN: ${{ github.token }} - BEFORE: ${{ steps.trigger.outputs.before }} - run: | - set -euo pipefail - invoke_id="" - for _ in $(seq 1 36); do - sleep 5 - mapfile -t rows < <( - gh run list \ - --repo "${GITHUB_REPOSITORY}" \ - --workflow "Invoke Cloud Run" \ - --limit 8 \ - --json databaseId,status,conclusion,createdAt,url,event \ - --jq '.[] | select(.event=="workflow_dispatch") | [.databaseId, .status, (.conclusion // ""), .createdAt, .url] | @tsv' - ) - for row in "${rows[@]:-}"; do - id="$(echo "$row" | cut -f1)" - status="$(echo "$row" | cut -f2)" - conclusion="$(echo "$row" | cut -f3)" - created="$(echo "$row" | cut -f4)" - url="$(echo "$row" | cut -f5)" - # Prefer runs at/after our dispatch timestamp. - if [[ -n "$BEFORE" && "$created" < "$BEFORE" ]]; then - continue - fi - invoke_id="$id" - echo "invoke_run id=${id} status=${status} conclusion=${conclusion} created=${created} url=${url}" - if [ "$status" = "completed" ]; then - if [ "$conclusion" = "success" ]; then - echo "Invoke succeeded: ${url}" - exit 0 - fi - echo "Invoke finished without success (conclusion=${conclusion}): ${url}" >&2 - exit 1 - fi - break - done - done - echo "Timed out waiting for Invoke Cloud Run (last_id=${invoke_id:-none})." >&2 - exit 1 diff --git a/AGENTS.md b/AGENTS.md index dcc2254d..4af42cfe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,10 +16,7 @@ QuantPlatformKit and UsEquityStrategies at pinned revisions. ## Layout -- `application/` — Firstrade client, execution and reconciliation logic. -- `entrypoints/`, `main.py` — service entry points. -- `strategy/` — strategy loading and registry. -- `notifications/` — notification composition. +- `src/firstrade_platform/` — installable runtime package (`application/`, `entrypoints/`, `notifications/`, `main.py`, strategy loading/registry, and runtime policy modules). - `scripts/`, `cloudbuild.yaml` — deployment and operator tooling. - `docs/` — runtime and notification contracts. - `tests/` — offline tests with a mocked broker boundary. @@ -54,7 +51,7 @@ Organization documentation rules run in CI via `QuantStrategyLab/.github/.github ## Do not - Do not remove the default dry-run behaviour or weaken the live order gates in - `application/firstrade_client.py`. + `src/firstrade_platform/application/firstrade_client.py`. - Do not add credentials, cookies, account identifiers, balances or raw order payloads to examples or tests. - Do not treat a successful call to the unofficial API as proof of account diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 02a11da5..a94025d2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ make failure modes obvious. Rules for contributions: - Do not remove the default dry-run behavior. -- Do not weaken the live order gates in `application/firstrade_client.py`. +- Do not weaken the live order gates in `src/firstrade_platform/application/firstrade_client.py`. - Do not add credentials, cookies, account IDs, balances, or raw order payloads to examples or tests. - Keep upstream attribution in `NOTICE.md`. diff --git a/Dockerfile b/Dockerfile index 435ba4a2..c00ba7a3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,4 +27,4 @@ USER appuser RUN /app/.venv/bin/python -m scripts.publish_digest_before_read --help -CMD ["/app/.venv/bin/python", "-m", "gunicorn", "--bind", ":8080", "main:app"] +CMD ["/app/.venv/bin/python", "-m", "gunicorn", "--bind", ":8080", "firstrade_platform.main:app"] diff --git a/README.md b/README.md index d9346fcd..de388a69 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ The existing daily Execution Report Heartbeat also invokes this snapshot path on The Cloud Run service must remain IAM-protected. The caller needs `roles/run.invoker` and must send its Google-signed ID token in `X-Serverless-Authorization`; the separate application token goes in `Authorization: Bearer …`. See [Cloud Run service-to-service authentication](https://cloud.google.com/run/docs/authenticating/service-to-service). Neither token is a Firstrade credential. -Configure the following only through protected Cloud Run environment variables and Secret Manager references: `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`, `FIRSTRADE_ACCOUNT_FACTS_SYNC_URL` (must equal the approved sync URL defined as `_APPROVED_SYNC_URL` in `application/account_facts_publisher.py`), `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN` (a dedicated secret), `FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`, `FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`, `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY`, and `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`. The account identity is taken from the single exact selector in the protected runtime target; if `FIRSTRADE_ACCOUNT` is also set, it must match. All values must match the trusted QRS binding and current runtime target. Do not derive or invent a binding ID. +Configure the following only through protected Cloud Run environment variables and Secret Manager references: `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`, `FIRSTRADE_ACCOUNT_FACTS_SYNC_URL` (must equal the approved sync URL defined as `_APPROVED_SYNC_URL` in `src/firstrade_platform/application/account_facts_publisher.py`), `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN` (a dedicated secret), `FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`, `FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`, `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY`, and `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`. The account identity is taken from the single exact selector in the protected runtime target; if `FIRSTRADE_ACCOUNT` is also set, it must match. All values must match the trusted QRS binding and current runtime target. Do not derive or invent a binding ID. The existing manual Cloud Run environment sync carries the six non-token settings through the selected Firstrade target's `env` configuration in `CLOUD_RUN_SERVICE_TARGETS_JSON`; the legacy single-service path can use matching `FIRSTRADE_ACCOUNT_FACTS_*` inputs. Keep target, binding, account key, and scope in protected GitHub configuration. Set the protected GitHub variable `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME` to the name of the already-approved Secret Manager secret. The workflow maps that Secret Manager reference to `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`; it never accepts a raw token value from GitHub Actions. Keep the enable switch unset or `false` until deployment adoption is separately reviewed. This source change does not apply Cloud Run configuration or establish deployment adoption. @@ -128,9 +128,11 @@ Keep the sync disabled until the receiver-side account binding and separate sync ## Repository layout +- `src/firstrade_platform/`: installable runtime package (`application/`, `entrypoints/`, `notifications/`, `main.py`, and strategy and runtime policy modules). - `tests/`: unit, contract, and regression tests. - `.github/workflows/`: CI, scheduled jobs, release, or deployment workflows. - `scripts/`: operator scripts and local helpers. +- `docs/`: runtime, reconciliation, and notification contracts. ## Quick start @@ -142,7 +144,9 @@ uv run --no-sync python scripts/check_qpk_pin_consistency.py ## Useful docs +- [Documentation index](docs/README.md) - [Isolated paper command consumer](docs/paper-execution-command-consumer.md) +- [Configurable display names](docs/display-names.md) ## Community and security @@ -157,5 +161,3 @@ See [CONTRIBUTING.md](CONTRIBUTING.md). AI assistants and maintainers follow [AG ## License See [LICENSE](LICENSE). - -Display/notification naming configuration: [display names](docs/display-names.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 9b426a3a..b4e89e74 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -50,11 +50,11 @@ FirstradePlatform 是 QuantStrategyLab 的实验性 Firstrade 执行平台。实 现有 Runtime Target Lifecycle 手动入口的 `metadata_only=true` 会核实际接收流量的修订,并只输出同步开关、固定目的地、绑定配置、token 引用与缓存配置是否存在。它不读取 Secret 内容或缓存,不调用券商;绑定准确性及缓存有效性明确标为尚未核验。配置存在不能代表余额已同步。 -`POST /account-facts-sync` 是手动触发、仅读取缓存会话的账户快照入口。只有 `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED=true` 时才开放;它不会登录、刷新凭据、自行定时、下单或发送通知。它只发布券商直接返回的净资产,以及存在时的 `cash_balance`;不会读取持仓,因此持仓读取失败或持仓资料不完整不会阻塞余额快照;也不会用 buying power 或持仓计算资产或现金。 +`POST /account-facts-sync` 是手动触发、仅读取缓存会话的账户快照入口。只有 `FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED=true` 时才开放;它不会登录、刷新凭据、自行定时、下单或发送通知。它发布券商直接返回的净资产,以及存在时的 `cash_balance`;显式设置 `FIRSTRADE_ACCOUNT_FACTS_POSITION_CURRENCY` 时也会采集持仓,否则不会因持仓读取失败或持仓资料不完整阻塞余额快照;也不会用 buying power 或持仓计算资产或现金。 Cloud Run 服务必须继续受 IAM 保护。调用方需要 `roles/run.invoker`,并把 Google 签名的 ID token 放在 `X-Serverless-Authorization`;独立的应用 token 放在 `Authorization: Bearer …`。参见 [Cloud Run 服务间认证文档](https://cloud.google.com/run/docs/authenticating/service-to-service)。这两种 token 都不是 Firstrade 凭据。 -以下配置只能通过受保护的 Cloud Run 环境变量和 Secret Manager 引用配置:`FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`、`FIRSTRADE_ACCOUNT_FACTS_SYNC_URL`(必须与 `application/account_facts_publisher.py` 中 `_APPROVED_SYNC_URL` 定义的已批准同步地址完全一致)、`FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`(专用 secret)、`FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`、`FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`、`FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY` 和 `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`。账户身份复用受保护 runtime target 中唯一且精确的 selector;若同时设置 `FIRSTRADE_ACCOUNT`,它必须完全匹配。所有值都必须与 QRS 可信绑定及当前 runtime target 一致;不要推导或编造 binding ID。 +以下配置只能通过受保护的 Cloud Run 环境变量和 Secret Manager 引用配置:`FIRSTRADE_ACCOUNT_FACTS_SYNC_ENABLED`、`FIRSTRADE_ACCOUNT_FACTS_SYNC_URL`(必须与 `src/firstrade_platform/application/account_facts_publisher.py` 中 `_APPROVED_SYNC_URL` 定义的已批准同步地址完全一致)、`FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`(专用 secret)、`FIRSTRADE_ACCOUNT_FACTS_TARGET_ID`、`FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID`、`FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_KEY` 和 `FIRSTRADE_ACCOUNT_FACTS_ACCOUNT_SCOPE`。账户身份复用受保护 runtime target 中唯一且精确的 selector;若同时设置 `FIRSTRADE_ACCOUNT`,它必须完全匹配。所有值都必须与 QRS 可信绑定及当前 runtime target 一致;不要推导或编造 binding ID。 现有手动 Cloud Run 环境同步会从 `CLOUD_RUN_SERVICE_TARGETS_JSON` 中所选 Firstrade target 的 `env` 配置传递六个非 token 项;单服务旧配置路径也可使用匹配的 `FIRSTRADE_ACCOUNT_FACTS_*` 输入。target、binding、account key 和 scope 放在受保护的 GitHub 配置中。受保护的 GitHub variable `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN_SECRET_NAME` 只填写已批准 Secret Manager secret 的名称;workflow 只把这个 Secret Manager 引用映射到 `FIRSTRADE_ACCOUNT_FACTS_SYNC_TOKEN`,不会接受 GitHub Actions 传入的明文 token。部署另行审查和采用前,启用开关应保持未设置或 `false`。本次源码修改没有应用 Cloud Run 配置,也不代表部署已采用。 @@ -80,9 +80,11 @@ FIRSTRADE_ACCOUNT=synthetic-native-account-id # 可选;设置后必须匹配 ## 仓库结构 +- `src/firstrade_platform/`:可安装的运行时包(`application/`、`entrypoints/`、`notifications/`、`main.py` 及策略与运行时策略模块)。 - `tests/`:单元测试、契约测试和回归测试。 - `.github/workflows/`:CI、定时任务、发布或部署 workflow。 - `scripts/`:运维脚本和本地辅助工具。 +- `docs/`:运行时、对账与通知契约文档。 ## 快速开始 @@ -94,7 +96,9 @@ uv run --no-sync python scripts/check_qpk_pin_consistency.py ## 延伸文档 -- 暂无独立 `docs/` 目录;请先阅读本 README 和 workflow 文件。 +- [文档索引](docs/README.md) +- [隔离的 paper 命令消费者](docs/paper-execution-command-consumer.md) +- [显示名称配置](docs/display-names.md) ## 社区和安全 diff --git a/docs/shared-test-imports.md b/docs/shared-test-imports.md index bdbd0f78..7a9847f2 100644 --- a/docs/shared-test-imports.md +++ b/docs/shared-test-imports.md @@ -8,7 +8,7 @@ Dependency installation is preparation; run tests without network or credential The installed-lock lane checks VCS URL, exact locked revision and version together with every loaded shared module's actual file/spec origin, package search path, distribution ownership and RECORD SHA-256. Editable installs and sibling shadows fail. -The existing sibling entries in pytest's `pythonpath` remain unchanged. +Pytest's `pythonpath` resolves `src` and `.` without sibling repository checkouts. ```bash uv run --no-sync python -m pytest -q -p test_support.pytest_provenance \ @@ -55,4 +55,5 @@ transient modules loaded and removed between boundaries by arbitrary third-party Existing test-specific path edits and mocks remain in place, so legacy whole-suite source ambiguity remains characterized rather than eliminated. The test support is excluded from the setuptools production package selection; pins, production source, -existing scanner/completion checks and coverage configuration are unchanged. +existing scanner/completion checks and `src/firstrade_platform` coverage configuration +remain intact. diff --git a/docs/statement-reconciliation.md b/docs/statement-reconciliation.md index 202fbe97..afc379f4 100644 --- a/docs/statement-reconciliation.md +++ b/docs/statement-reconciliation.md @@ -1,7 +1,7 @@ # Statement reconciliation: fee split and valuation basis Two reconciliation gaps looked unexplained but have fixed, documented causes. -`application/statement_reconciliation.py` models them as pure, offline helpers. +`src/firstrade_platform/application/statement_reconciliation.py` models them as pure, offline helpers. Nothing in it calls a broker, reads credentials, or writes data. ## Desk-executed sells: broker-assisted fee plus regulatory fee @@ -34,7 +34,7 @@ Worked case, 2026-08-28 IBIT: `2 x 43.7724 = 87.5448`, minus `19.95` and `0.01` gives `67.58`, which matches the reported amount. The earlier "unexplained `19.96`" is the sum of the two fees. -Rates live in `application/firstrade_fee_schedule.py` as effective-dated +Rates live in `src/firstrade_platform/application/firstrade_fee_schedule.py` as effective-dated segments (SEC `0.00` from 2025-05-14, `20.60` per million from 2026-04-04). TAF for covered equities: `0.000195` per share (max `$9.79`) in 2026, paused 2026-10-01 to 2026-12-31 (SR-FINRA-2026-021), then `0.000195` / `$9.79` again diff --git a/docs/statement-reconciliation.zh-CN.md b/docs/statement-reconciliation.zh-CN.md index b5a01761..9b12eda7 100644 --- a/docs/statement-reconciliation.zh-CN.md +++ b/docs/statement-reconciliation.zh-CN.md @@ -1,7 +1,7 @@ # 对账:费用拆分与估值口径 有两类对账差异看起来无法解释,但原因固定且已记录。 -`application/statement_reconciliation.py` 用纯离线函数对它们建模,不调用券商、不读取凭据、不写入数据。 +`src/firstrade_platform/application/statement_reconciliation.py` 用纯离线函数对它们建模,不调用券商、不读取凭据、不写入数据。 ## 人工委托卖单:经纪人协助费 + 监管费 @@ -19,7 +19,7 @@ 示例,2026-08-28 IBIT:`2 x 43.7724 = 87.5448`,减去 `19.95` 和 `0.01` 得 `67.58`,与实际到账一致。此前的“无法解释 `19.96`”即这两项费用之和。 -费率以带生效日期的分段形式放在 `application/firstrade_fee_schedule.py`(SEC 自 2025-05-14 起 `0.00`,自 2026-04-04 起每百万 `20.60`)。TAF(普通股/ETF)2026 年每股 `0.000195`(单笔上限 `$9.79`),2026-10-01 至 2026-12-31 暂停(SR-FINRA-2026-021);因 SR-FINRA-2026-020 将剩余涨幅推迟两年,2027、2028 年仍为 `0.000195` / `$9.79`,2029-01-01 起 `0.000232` / `$11.61`,2030-01-01 起 `0.000240` / `$12.05`,2031-01-01 起 `0.000249` / `$12.50`。SEC 或 FINRA 发布新费率时更新分段;`load_fee_schedule()` 会校验顺序和取值。 +费率以带生效日期的分段形式放在 `src/firstrade_platform/application/firstrade_fee_schedule.py`(SEC 自 2025-05-14 起 `0.00`,自 2026-04-04 起每百万 `20.60`)。TAF(普通股/ETF)2026 年每股 `0.000195`(单笔上限 `$9.79`),2026-10-01 至 2026-12-31 暂停(SR-FINRA-2026-021);因 SR-FINRA-2026-020 将剩余涨幅推迟两年,2027、2028 年仍为 `0.000195` / `$9.79`,2029-01-01 起 `0.000232` / `$11.61`,2030-01-01 起 `0.000240` / `$12.05`,2031-01-01 起 `0.000249` / `$12.50`。SEC 或 FINRA 发布新费率时更新分段;`load_fee_schedule()` 会校验顺序和取值。 `verified_through`(当前 `2026-12-01`)是费率最后一次对照公开来源核实的交易日。之后的交易日为 `unsupported`(`..._not_verified_after_<日期>`):SEC 2027 财年 Section 31 费率尚未公布(FY2026 费率在 2027 财年拨款法案生效后 60 天内继续有效),上述 FINRA 备案虽即时生效但仍可能被 SEC 暂停。更新来源核实时需在同一变更中推进 `verified_through`。 diff --git a/pyproject.toml b/pyproject.toml index 60c8a3ef..ec8ed59d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,6 @@ dependencies = [ "google-cloud-storage", "gunicorn", "pandas_market_calendars", - "pytest", "pytz", "requests", "quant-platform-kit @ git+https://github.com/QuantStrategyLab/QuantPlatformKit.git@5d0714201f3813f68a9833083cd21f6d61e5b702", @@ -35,29 +34,15 @@ test = [ ] [tool.setuptools] -py-modules = [ - "decision_mapper", - "main", - "runtime_config_support", - "runtime_execution_policy", - "strategy_loader", - "strategy_registry", - "strategy_runtime", -] +package-dir = {"" = "src"} [tool.setuptools.packages.find] -include = [ - "application*", - "entrypoints*", - "notifications*", - "scripts*", -] +where = ["src"] [tool.pytest.ini_options] pythonpath = [ + "src", ".", - "../QuantPlatformKit/src", - "../UsEquityStrategies/src", ] testpaths = ["tests"] @@ -74,7 +59,7 @@ ignore = ["E701", "E702", "E741", "F841", "F821", "B008", "F401", "F601", "E402" [tool.coverage.run] branch = true -source = ["."] +source = ["src/firstrade_platform"] omit = ["tests/*", "*/external/*", ".venv/*", "build/*", "dist/*"] [tool.coverage.report] diff --git a/scripts/build_cloud_run_env_sync_plan.py b/scripts/build_cloud_run_env_sync_plan.py index af0a1503..57b17475 100644 --- a/scripts/build_cloud_run_env_sync_plan.py +++ b/scripts/build_cloud_run_env_sync_plan.py @@ -9,6 +9,7 @@ ROOT = Path(__file__).resolve().parents[1] +SRC = ROOT / "src" QPK_SRC = ROOT.parent / "QuantPlatformKit" / "src" UES_SRC = ROOT.parent / "UsEquityStrategies" / "src" @@ -32,7 +33,7 @@ def _should_add_local_src(candidate: Path) -> bool: return True -for candidate in (ROOT, QPK_SRC, UES_SRC): +for candidate in (SRC, ROOT, QPK_SRC, UES_SRC): if not _should_add_local_src(candidate): continue candidate_str = str(candidate) @@ -41,7 +42,7 @@ def _should_add_local_src(candidate: Path) -> bool: from scripts.cloud_run_tag_preflight import validate_diagnostic -from strategy_registry import ( # noqa: E402 +from firstrade_platform.strategy_registry import ( # noqa: E402 FIRSTRADE_PLATFORM, get_platform_profile_status_matrix, resolve_strategy_definition, diff --git a/scripts/check_fee_schedule.py b/scripts/check_fee_schedule.py index 94f28875..0591cef4 100644 --- a/scripts/check_fee_schedule.py +++ b/scripts/check_fee_schedule.py @@ -6,7 +6,7 @@ ``check`` Fetch the SEC Section 31 advisory and the FINRA Trading Activity Fee (TAF) - sources, compare them with ``application/firstrade_fee_schedule.py`` and + sources, compare them with ``src/firstrade_platform/application/firstrade_fee_schedule.py`` and write a Markdown report plus a JSON result. Any fetch or parse failure is an ``error``; any difference is ``changed``. Only a complete match is ``unchanged``. Rates are never edited. @@ -42,10 +42,14 @@ from pathlib import Path from typing import Any -from application.firstrade_fee_schedule import DEFAULT_FEE_SCHEDULE_CONFIG - REPO_ROOT = Path(__file__).resolve().parent.parent -SCHEDULE_FILE = REPO_ROOT / "application" / "firstrade_fee_schedule.py" +SRC_DIR = REPO_ROOT / "src" +if str(SRC_DIR) not in sys.path: + sys.path.insert(0, str(SRC_DIR)) + +from firstrade_platform.application.firstrade_fee_schedule import DEFAULT_FEE_SCHEDULE_CONFIG + +SCHEDULE_FILE = REPO_ROOT / "src" / "firstrade_platform" / "application" / "firstrade_fee_schedule.py" TEST_FILE = REPO_ROOT / "tests" / "test_statement_reconciliation.py" DOC_FILES = ( REPO_ROOT / "docs" / "statement-reconciliation.md", @@ -609,7 +613,7 @@ def render_report(status: str, report: Report | None, error: str | None, today: lines += ["## Sources", ""] + [f"- {s}" for s in report.sources] + [""] if status != STATUS_UNCHANGED: lines += ["Rates are never changed automatically. Review the sources, update " - "`application/firstrade_fee_schedule.py`, its tests and docs in a normal " + "`src/firstrade_platform/application/firstrade_fee_schedule.py`, its tests and docs in a normal " "PR, then move `verified_through`. Tracking issue: #497.", ""] return "\n".join(lines) diff --git a/scripts/emit_unified_digest_candidates.py b/scripts/emit_unified_digest_candidates.py index b1a00096..0c4f1815 100644 --- a/scripts/emit_unified_digest_candidates.py +++ b/scripts/emit_unified_digest_candidates.py @@ -3,10 +3,13 @@ from contextlib import redirect_stderr, redirect_stdout import sys from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +ROOT = Path(__file__).resolve().parents[1] +for candidate in (ROOT / "src", ROOT): + if str(candidate) not in sys.path: + sys.path.insert(0, str(candidate)) import json import os -from notifications.unified import CandidateStorageError, emit_candidates # noqa: E402 +from firstrade_platform.notifications.unified import CandidateStorageError, emit_candidates # noqa: E402 # Exact local codes only. Never print provider messages, exception class names, @@ -85,7 +88,7 @@ def main(): except Exception as error: diagnostic = _failure_diagnostic(error, stage) print(json.dumps({"status": "candidate_projection_failed", "uploaded": False, **diagnostic})) - from notifications.unified import alert_text, coverage_locale + from firstrade_platform.notifications.unified import alert_text, coverage_locale from scripts.execution_report_heartbeat import _send_telegram marker = os.environ.get("RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH") try: diff --git a/scripts/execution_report_heartbeat.py b/scripts/execution_report_heartbeat.py index af515a8c..4f89aff3 100644 --- a/scripts/execution_report_heartbeat.py +++ b/scripts/execution_report_heartbeat.py @@ -760,7 +760,7 @@ def _send_telegram(message: str) -> bool: def _deliver_alert(message: str, *, kind: str, now: dt.datetime, affected_keys=None) -> bool: - from notifications.unified import alert_text, enabled, notify_heartbeat + from firstrade_platform.notifications.unified import alert_text, enabled, notify_heartbeat if not enabled(): return _send_telegram(message) result = notify_heartbeat(kind=kind, send=lambda: _send_telegram(alert_text(kind, _notification_locale())), @@ -770,7 +770,7 @@ def _deliver_alert(message: str, *, kind: str, now: dt.datetime, affected_keys=N def _send_normal_heartbeat(name: str, detail: str, *, quiet_eligible: bool = True, now: dt.datetime | None = None, recovery_reports=(), affected_keys=None) -> int: - from notifications.unified import alert_text, coverage_locale, enabled, notify_heartbeat + from firstrade_platform.notifications.unified import alert_text, coverage_locale, enabled, notify_heartbeat if quiet_eligible or enabled(): locale = coverage_locale() if quiet_eligible else _notification_locale() message = alert_text("candidate_write_failure" if quiet_eligible else "receipt_unacceptable", locale) diff --git a/scripts/firstrade_smoke_check.py b/scripts/firstrade_smoke_check.py index 2ac9d1a8..fb8c99be 100755 --- a/scripts/firstrade_smoke_check.py +++ b/scripts/firstrade_smoke_check.py @@ -19,10 +19,11 @@ from typing import Any ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) +for candidate in (ROOT / "src", ROOT): + if str(candidate) not in sys.path: + sys.path.insert(0, str(candidate)) -from application.firstrade_client import ( # noqa: E402 +from firstrade_platform.application.firstrade_client import ( # noqa: E402 FirstradeBrokerClient, FirstradeCredentials, FirstradePlatformError, diff --git a/scripts/inspect_account_history_schema.py b/scripts/inspect_account_history_schema.py index 64e6701d..1a6721b3 100644 --- a/scripts/inspect_account_history_schema.py +++ b/scripts/inspect_account_history_schema.py @@ -9,8 +9,13 @@ from pathlib import Path import re import subprocess +import sys -from application.firstrade_client import ( +SRC_DIR = Path(__file__).resolve().parents[1] / "src" +if str(SRC_DIR) not in sys.path: + sys.path.insert(0, str(SRC_DIR)) + +from firstrade_platform.application.firstrade_client import ( # noqa: E402 FirstradeBrokerClient, FirstradeCachedSessionError, FirstradeCredentials, ) from scripts.inspect_funds_snapshot_schema import configured_account diff --git a/scripts/print_strategy_profile_status.py b/scripts/print_strategy_profile_status.py index 2b103994..793a4fbb 100755 --- a/scripts/print_strategy_profile_status.py +++ b/scripts/print_strategy_profile_status.py @@ -7,10 +7,11 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) +for candidate in (ROOT / "src", ROOT): + if str(candidate) not in sys.path: + sys.path.insert(0, str(candidate)) -from strategy_registry import get_platform_profile_status_matrix # noqa: E402 +from firstrade_platform.strategy_registry import get_platform_profile_status_matrix # noqa: E402 def main(argv: list[str] | None = None) -> int: diff --git a/scripts/publish_archived_account_history.py b/scripts/publish_archived_account_history.py index a0f46aa2..e749bee7 100644 --- a/scripts/publish_archived_account_history.py +++ b/scripts/publish_archived_account_history.py @@ -9,15 +9,21 @@ import json import os import subprocess +import sys import urllib.parse import urllib.request +from pathlib import Path -from application.account_facts_publisher import ( +SRC_DIR = Path(__file__).resolve().parents[1] / "src" +if str(SRC_DIR) not in sys.path: + sys.path.insert(0, str(SRC_DIR)) + +from firstrade_platform.application.account_facts_publisher import ( # noqa: E402 build_firstrade_account_snapshot, load_account_facts_publish_config, publish_firstrade_account_snapshot, ) -from application.account_facts_readonly import _exact_balance_value +from firstrade_platform.application.account_facts_readonly import _exact_balance_value # noqa: E402 from scripts.inspect_funds_snapshot_schema import configured_account, history_objects diff --git a/scripts/publish_digest_before_read.py b/scripts/publish_digest_before_read.py index 941743cd..623e0016 100644 --- a/scripts/publish_digest_before_read.py +++ b/scripts/publish_digest_before_read.py @@ -8,7 +8,7 @@ from datetime import datetime, time, timedelta, timezone from zoneinfo import ZoneInfo -from notifications.digest_snapshot.digest_archive import ArchiveReader +from firstrade_platform.notifications.digest_snapshot.digest_archive import ArchiveReader SHANGHAI = ZoneInfo("Asia/Shanghai") PLATFORM = "firstrade" @@ -28,7 +28,7 @@ def publication_day(now): def _emit(env, *, now, read): - from notifications.unified import emit_candidates + from firstrade_platform.notifications.unified import emit_candidates return emit_candidates(env, now=now, read=read) @@ -94,7 +94,7 @@ def timeout(signum, frame): return 0 except (Exception, DeadlineExceeded) as error: # Never expose exception messages, private locators or credentials. - from notifications.unified import CandidateStorageError + from firstrade_platform.notifications.unified import CandidateStorageError diagnostic = ({"stage": error.stage, "error_category": error.category} if isinstance(error, CandidateStorageError) else {}) print(json.dumps({"status": "failed", "reason_code": "candidate_publication_unconfirmed", diff --git a/scripts/publish_runtime_daily.py b/scripts/publish_runtime_daily.py index d8c79fe1..34c5bc18 100644 --- a/scripts/publish_runtime_daily.py +++ b/scripts/publish_runtime_daily.py @@ -14,7 +14,7 @@ from scripts import execution_report_heartbeat as heartbeat from scripts.project_runtime_daily import PLATFORM, project_runtime_daily -from application.account_facts_publisher import _APPROVED_SYNC_URL as _FACTS_URL +from firstrade_platform.application.account_facts_publisher import _APPROVED_SYNC_URL as _FACTS_URL class _NoRedirect(HTTPRedirectHandler): diff --git a/scripts/release_cached_currency.py b/scripts/release_cached_currency.py index ce4fbf1c..8dec6012 100644 --- a/scripts/release_cached_currency.py +++ b/scripts/release_cached_currency.py @@ -14,7 +14,7 @@ from urllib.request import Request, urlopen API = "https://run.googleapis.com/v2/" -MODULE = "application/session_check_service.py" +MODULE = "src/firstrade_platform/application/session_check_service.py" ANCHOR = '"total_equity": balances.get("provider_equity"),' CURRENCY = '"currency": balances.get("currency"),' STAGE = "configuration" diff --git a/scripts/send_paper_notification_preview.py b/scripts/send_paper_notification_preview.py index 3d82d4f1..5bfb3d7f 100644 --- a/scripts/send_paper_notification_preview.py +++ b/scripts/send_paper_notification_preview.py @@ -24,10 +24,11 @@ from zoneinfo import ZoneInfo ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) +for candidate in (ROOT / "src", ROOT): + if str(candidate) not in sys.path: + sys.path.insert(0, str(candidate)) -from notifications.telegram import build_sender # noqa: E402 +from firstrade_platform.notifications.telegram import build_sender # noqa: E402 _QRS_SNAPSHOT = ROOT / "tests" / "fixtures" / "qrs_notification_716" _PREVIEW_PLATFORM_ID = "firstrade" @@ -41,7 +42,7 @@ def _require_supported_preview_profile(profile: str) -> str: """Fail when the preview profile is not enabled here, so the sample cannot go stale.""" - from strategy_registry import SUPPORTED_STRATEGY_PROFILES + from firstrade_platform.strategy_registry import SUPPORTED_STRATEGY_PROFILES if profile not in SUPPORTED_STRATEGY_PROFILES: raise RuntimeError(f"preview strategy profile {profile!r} is not enabled on Firstrade") diff --git a/scripts/verify_deployed_runtime_target_admission.py b/scripts/verify_deployed_runtime_target_admission.py index dee51a08..d22e0d78 100644 --- a/scripts/verify_deployed_runtime_target_admission.py +++ b/scripts/verify_deployed_runtime_target_admission.py @@ -12,9 +12,14 @@ import subprocess import sys from collections.abc import Mapping, Sequence +from pathlib import Path from typing import Any -from strategy_registry import FIRSTRADE_PLATFORM, resolve_strategy_definition +SRC_DIR = Path(__file__).resolve().parents[1] / "src" +if str(SRC_DIR) not in sys.path: + sys.path.insert(0, str(SRC_DIR)) + +from firstrade_platform.strategy_registry import FIRSTRADE_PLATFORM, resolve_strategy_definition # noqa: E402 class AdmissionError(ValueError): diff --git a/src/firstrade_platform/__init__.py b/src/firstrade_platform/__init__.py new file mode 100644 index 00000000..9e30100d --- /dev/null +++ b/src/firstrade_platform/__init__.py @@ -0,0 +1 @@ +"""Firstrade execution platform package.""" diff --git a/application/__init__.py b/src/firstrade_platform/application/__init__.py similarity index 100% rename from application/__init__.py rename to src/firstrade_platform/application/__init__.py diff --git a/application/account_facts_publisher.py b/src/firstrade_platform/application/account_facts_publisher.py similarity index 99% rename from application/account_facts_publisher.py rename to src/firstrade_platform/application/account_facts_publisher.py index ce911734..8fb32741 100644 --- a/application/account_facts_publisher.py +++ b/src/firstrade_platform/application/account_facts_publisher.py @@ -12,7 +12,7 @@ import requests -from application.account_facts_readonly import AccountFactsUnavailable +from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable _APPROVED_SYNC_URL = "https://qsl-strategy-switch-console.pigbibi.workers.dev/api/account-facts/sync" _TARGET_ID_RE = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?", re.ASCII) diff --git a/application/account_facts_readonly.py b/src/firstrade_platform/application/account_facts_readonly.py similarity index 99% rename from application/account_facts_readonly.py rename to src/firstrade_platform/application/account_facts_readonly.py index 06643aa3..7000b96c 100644 --- a/application/account_facts_readonly.py +++ b/src/firstrade_platform/application/account_facts_readonly.py @@ -13,7 +13,7 @@ import re from typing import Any, Callable -from application.account_payload_utils import flatten_values, get_first +from firstrade_platform.application.account_payload_utils import flatten_values, get_first _DECIMAL_RE = re.compile(r"[+-]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?", re.ASCII) _ISO_CURRENCY_RE = re.compile(r"[A-Z]{3}", re.ASCII) diff --git a/application/account_payload_utils.py b/src/firstrade_platform/application/account_payload_utils.py similarity index 100% rename from application/account_payload_utils.py rename to src/firstrade_platform/application/account_payload_utils.py diff --git a/application/broker_reconciliation.py b/src/firstrade_platform/application/broker_reconciliation.py similarity index 100% rename from application/broker_reconciliation.py rename to src/firstrade_platform/application/broker_reconciliation.py diff --git a/application/execution_receipt_adapter.py b/src/firstrade_platform/application/execution_receipt_adapter.py similarity index 100% rename from application/execution_receipt_adapter.py rename to src/firstrade_platform/application/execution_receipt_adapter.py diff --git a/application/execution_service.py b/src/firstrade_platform/application/execution_service.py similarity index 100% rename from application/execution_service.py rename to src/firstrade_platform/application/execution_service.py diff --git a/application/firstrade_client.py b/src/firstrade_platform/application/firstrade_client.py similarity index 99% rename from application/firstrade_client.py rename to src/firstrade_platform/application/firstrade_client.py index 944aacce..18d5f8f3 100644 --- a/application/firstrade_client.py +++ b/src/firstrade_platform/application/firstrade_client.py @@ -22,8 +22,8 @@ from typing import Any, Callable from urllib.parse import urlsplit -from application.account_payload_utils import flatten_values, float_or_none -from application.state_persistence import GcsStateStore +from firstrade_platform.application.account_payload_utils import flatten_values, float_or_none +from firstrade_platform.application.state_persistence import GcsStateStore _HTTP_DEBUG_LOCK = RLock() diff --git a/application/firstrade_fee_schedule.py b/src/firstrade_platform/application/firstrade_fee_schedule.py similarity index 100% rename from application/firstrade_fee_schedule.py rename to src/firstrade_platform/application/firstrade_fee_schedule.py diff --git a/application/paper_execution_admission.py b/src/firstrade_platform/application/paper_execution_admission.py similarity index 100% rename from application/paper_execution_admission.py rename to src/firstrade_platform/application/paper_execution_admission.py diff --git a/application/paper_execution_command_consumer.py b/src/firstrade_platform/application/paper_execution_command_consumer.py similarity index 100% rename from application/paper_execution_command_consumer.py rename to src/firstrade_platform/application/paper_execution_command_consumer.py diff --git a/application/rebalance_service.py b/src/firstrade_platform/application/rebalance_service.py similarity index 97% rename from application/rebalance_service.py rename to src/firstrade_platform/application/rebalance_service.py index cf1bfed0..acc4df8a 100644 --- a/application/rebalance_service.py +++ b/src/firstrade_platform/application/rebalance_service.py @@ -16,22 +16,22 @@ import pandas as pd -from application.execution_service import ( +from firstrade_platform.application.execution_service import ( execute_value_target_plan, substitute_small_safe_haven_targets_with_cash, ) -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, FirstradeCredentials, FirstradePlatformError, mask_account_id, ) -from application.runtime_broker_adapters import build_runtime_broker_adapters -from application.signal_snapshot import build_signal_snapshot -from application.state_persistence import ( +from firstrade_platform.application.runtime_broker_adapters import build_runtime_broker_adapters +from firstrade_platform.application.signal_snapshot import build_signal_snapshot +from firstrade_platform.application.state_persistence import ( GcsStateStore, build_gcs_state_store_from_env, legacy_account_state_id, ) -from application.strategy_run_persistence import ( +from firstrade_platform.application.strategy_run_persistence import ( build_strategy_run_state, claim_live_strategy_run, has_effective_live_submission_claim, @@ -41,8 +41,8 @@ read_latest_strategy_run_state, resolve_strategy_run_period, ) -from decision_mapper import map_strategy_decision_to_plan -from notifications.telegram import build_sender, build_translator, render_cycle_notification +from firstrade_platform.decision_mapper import map_strategy_decision_to_plan +from firstrade_platform.notifications.telegram import build_sender, build_translator, render_cycle_notification from quant_platform_kit.common.execution_outcomes import ( DEFAULT_EXECUTION_BLOCKING_SKIP_REASONS, filter_execution_blocking_skips, @@ -68,10 +68,10 @@ ) from quant_platform_kit.common.runtime_inputs import build_strategy_evaluation_inputs from quant_platform_kit.strategy_lifecycle.performance_monitor import try_record_platform_execution -from runtime_config_support import IBIT_SMART_DCA_PROFILE, PlatformRuntimeSettings, load_platform_runtime_settings -from runtime_execution_policy import dca_execution_unsupported_reason, notional_buy_execution_enabled +from firstrade_platform.runtime_config_support import IBIT_SMART_DCA_PROFILE, PlatformRuntimeSettings, load_platform_runtime_settings +from firstrade_platform.runtime_execution_policy import dca_execution_unsupported_reason, notional_buy_execution_enabled from us_equity_strategies.signals import resolve_external_market_signal_inputs -from strategy_runtime import load_strategy_runtime +from firstrade_platform.strategy_runtime import load_strategy_runtime LIMIT_SELL_DISCOUNT = 0.995 LIMIT_BUY_PREMIUM = 1.005 @@ -304,7 +304,7 @@ def send_and_capture(text: str) -> bool | None: def _report_unarchived_direct_coverage(result, *, settings, notification_sender=None): - from notifications.unified import alert_text, coverage_locale, cycle_kind + from firstrade_platform.notifications.unified import alert_text, coverage_locale, cycle_kind routine = cycle_kind(result) in {"routine_cycle", "order_submitted", "fill"} if routine and result.get("dry_run_only") is True: return True @@ -436,7 +436,7 @@ def publish_strategy_plugin_alerts( log_message: Callable[..., Any] = print, env_reader: Callable[[str, str | None], str | None] = os.getenv, ): - from notifications.digest_snapshot.digest_routing import immediate_plugin_signals + from firstrade_platform.notifications.digest_snapshot.digest_routing import immediate_plugin_signals return dispatch_strategy_plugin_alerts( immediate_plugin_signals(signals, mode="daily_digest"), notification_settings=settings, @@ -917,7 +917,7 @@ def acquire_submission_claim() -> bool: ), } if dispatch_plugin_alerts: - from notifications.digest_snapshot.digest_candidates import routine_observation_counts + from firstrade_platform.notifications.digest_snapshot.digest_candidates import routine_observation_counts result["routine_observation_counts"] = routine_observation_counts(strategy_plugin_signals) if execution_blocked: result["execution_blocked"] = True diff --git a/application/runtime_broker_adapters.py b/src/firstrade_platform/application/runtime_broker_adapters.py similarity index 99% rename from application/runtime_broker_adapters.py rename to src/firstrade_platform/application/runtime_broker_adapters.py index 09025c44..4faf24ec 100644 --- a/application/runtime_broker_adapters.py +++ b/src/firstrade_platform/application/runtime_broker_adapters.py @@ -9,14 +9,14 @@ import pandas as pd -from application.account_payload_utils import ( +from firstrade_platform.application.account_payload_utils import ( first_numeric_by_keywords, flatten_values, float_or_none, get_first, iter_position_rows, ) -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, StockOrderRequest, mask_account_id, diff --git a/application/session_check_service.py b/src/firstrade_platform/application/session_check_service.py similarity index 98% rename from application/session_check_service.py rename to src/firstrade_platform/application/session_check_service.py index aac53f74..e4df7ebb 100644 --- a/application/session_check_service.py +++ b/src/firstrade_platform/application/session_check_service.py @@ -9,13 +9,13 @@ from datetime import datetime, timezone from typing import Any -from application.account_payload_utils import ( +from firstrade_platform.application.account_payload_utils import ( float_or_none, get_first, iter_position_rows, selected_numeric_metrics, ) -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, FirstradeCredentials, FirstradeSafetyError, @@ -23,10 +23,10 @@ mask_account_id, suppress_firstrade_http_debug, ) -from application.state_persistence import ( +from firstrade_platform.application.state_persistence import ( GcsStateStore, build_gcs_state_store_from_env, legacy_account_state_id, ) -from strategy_registry import ( +from firstrade_platform.strategy_registry import ( FIRSTRADE_PLATFORM, resolve_strategy_definition, resolve_strategy_metadata, diff --git a/application/signal_snapshot.py b/src/firstrade_platform/application/signal_snapshot.py similarity index 100% rename from application/signal_snapshot.py rename to src/firstrade_platform/application/signal_snapshot.py diff --git a/application/state_persistence.py b/src/firstrade_platform/application/state_persistence.py similarity index 100% rename from application/state_persistence.py rename to src/firstrade_platform/application/state_persistence.py diff --git a/application/statement_reconciliation.py b/src/firstrade_platform/application/statement_reconciliation.py similarity index 99% rename from application/statement_reconciliation.py rename to src/firstrade_platform/application/statement_reconciliation.py index 2d317ee3..c56a1e19 100644 --- a/application/statement_reconciliation.py +++ b/src/firstrade_platform/application/statement_reconciliation.py @@ -23,7 +23,7 @@ from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation from typing import Any -from application.firstrade_fee_schedule import FeeSchedule, FeeScheduleError, load_fee_schedule +from firstrade_platform.application.firstrade_fee_schedule import FeeSchedule, FeeScheduleError, load_fee_schedule _CENT = Decimal("0.01") _MILLION = Decimal("1000000") diff --git a/application/strategy_run_persistence.py b/src/firstrade_platform/application/strategy_run_persistence.py similarity index 98% rename from application/strategy_run_persistence.py rename to src/firstrade_platform/application/strategy_run_persistence.py index 04054253..10af44ba 100644 --- a/application/strategy_run_persistence.py +++ b/src/firstrade_platform/application/strategy_run_persistence.py @@ -8,8 +8,8 @@ from datetime import date, datetime, timezone from typing import Any -from application.state_persistence import GcsStateStore -from application.firstrade_client import mask_account_id +from firstrade_platform.application.state_persistence import GcsStateStore +from firstrade_platform.application.firstrade_client import mask_account_id from quant_platform_kit.common.execution_outcomes import ( DEFAULT_TERMINAL_STRATEGY_RUN_STAGES, STAGE_NO_ACTION, diff --git a/decision_mapper.py b/src/firstrade_platform/decision_mapper.py similarity index 100% rename from decision_mapper.py rename to src/firstrade_platform/decision_mapper.py diff --git a/entrypoints/__init__.py b/src/firstrade_platform/entrypoints/__init__.py similarity index 100% rename from entrypoints/__init__.py rename to src/firstrade_platform/entrypoints/__init__.py diff --git a/entrypoints/cloud_run.py b/src/firstrade_platform/entrypoints/cloud_run.py similarity index 100% rename from entrypoints/cloud_run.py rename to src/firstrade_platform/entrypoints/cloud_run.py diff --git a/main.py b/src/firstrade_platform/main.py similarity index 96% rename from main.py rename to src/firstrade_platform/main.py index 5197b467..5c2b3dea 100644 --- a/main.py +++ b/src/firstrade_platform/main.py @@ -2,7 +2,7 @@ from __future__ import annotations -from notifications.telegram import build_translator +from firstrade_platform.notifications.telegram import build_translator import hashlib import json @@ -22,7 +22,7 @@ from quant_platform_kit.common.platform_runner import dispatch_due_monitors, load_monitor_targets from quant_platform_kit.common.strategy_release import build_runtime_loaded_receipt from quant_platform_kit.common.us_equity_sessions import Session, session_gate -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, FirstradeCredentials, FirstradeCachedSessionError, @@ -31,34 +31,34 @@ is_live_trading_enabled, mask_account_id, ) -from application.account_facts_readonly import ( +from firstrade_platform.application.account_facts_readonly import ( AccountFactsUnavailable, collect_firstrade_account_facts, ) -from application.account_facts_publisher import ( +from firstrade_platform.application.account_facts_publisher import ( AccountFactsPublishError, bind_account_facts_runtime_selector, build_firstrade_account_snapshot, load_account_facts_publish_config, publish_firstrade_account_snapshot, ) -from application.paper_execution_admission import ( +from firstrade_platform.application.paper_execution_admission import ( evaluate_paper_dry_run_admission, paper_dry_run_admission_requested, ) -from application.paper_execution_command_consumer import ( +from firstrade_platform.application.paper_execution_command_consumer import ( consume_due_paper_execution_commands, resolve_paper_execution_command_consumer_enabled, ) -from application.rebalance_service import run_strategy_cycle -from application.execution_receipt_adapter import ( +from firstrade_platform.application.rebalance_service import run_strategy_cycle +from firstrade_platform.application.execution_receipt_adapter import ( attach_strategy_result_execution_receipt, attach_unknown_failure_execution_receipt, is_expected_funding_skip, strategy_result_report_status, ) -from application.runtime_broker_adapters import build_runtime_broker_adapters -from application.broker_reconciliation import ( +from firstrade_platform.application.runtime_broker_adapters import build_runtime_broker_adapters +from firstrade_platform.application.broker_reconciliation import ( FirstradeReconciliationUnavailable, build_reconciliation_candidate, collect_read_only_reconciliation_observations, @@ -66,25 +66,25 @@ validate_reconciliation_candidate, validate_reconciliation_preconditions, ) -from application.session_check_service import ( +from firstrade_platform.application.session_check_service import ( archive_cached_account_facts, run_forced_session_renewal, run_session_check, ) -from notifications.telegram import build_sender +from firstrade_platform.notifications.telegram import build_sender from quant_platform_kit.common.runtime_reports import ( append_runtime_report_error, build_runtime_report_base, finalize_runtime_report, persist_runtime_report, ) -from entrypoints.cloud_run import is_market_open_now -from runtime_config_support import ( +from firstrade_platform.entrypoints.cloud_run import is_market_open_now +from firstrade_platform.runtime_config_support import ( PlatformRuntimeSettings, _runtime_target_enabled_env, load_platform_runtime_settings, resolve_telegram_token, ) -from strategy_registry import get_platform_profile_status_matrix -from strategy_runtime import load_strategy_runtime +from firstrade_platform.strategy_registry import get_platform_profile_status_matrix +from firstrade_platform.strategy_runtime import load_strategy_runtime MARKET_CALENDAR = os.getenv("FIRSTRADE_MARKET_CALENDAR", "NYSE") MARKET_TIMEZONE = os.getenv("FIRSTRADE_MARKET_TIMEZONE", "America/New_York") @@ -219,7 +219,7 @@ def _notify_runtime_error(exc: Exception) -> bool: return False message = _runtime_error_notification_message(exc) - from notifications.unified import enabled, notify_heartbeat + from firstrade_platform.notifications.unified import enabled, notify_heartbeat if enabled(): def send() -> bool: outcomes = [build_sender(token, chat_id)(message) for token, chat_id in targets] @@ -344,8 +344,8 @@ def _strategy_result_summary(result: dict[str, Any], *, dry_run: bool) -> dict[s summary["orders_skipped"] = skipped_orders if execution_notes: summary["execution_notes"] = execution_notes - from notifications.digest_snapshot.digest_candidates import cycle_evidence - from notifications.unified import known_pending_orders + from firstrade_platform.notifications.digest_snapshot.digest_candidates import cycle_evidence + from firstrade_platform.notifications.unified import known_pending_orders evidence = dict(result) if not evidence.get("execution_status") and result.get("ok") is True: evidence["execution_status"] = "completed" @@ -502,7 +502,7 @@ def persist_private_report() -> str | None: finally: report.pop("account_facts_source_binding_id", None) - from notifications.unified import notify_cycle + from firstrade_platform.notifications.unified import notify_cycle unified = bool(send_cycle_notification) try: cycle_options = { @@ -528,8 +528,8 @@ def persist_private_report() -> str | None: except Exception as persist_exc: print(f"failed to persist execution report: {persist_exc}", flush=True) if unified: - from application.rebalance_service import _publish_cycle_notification - from notifications.unified import alert_text, coverage_locale, cycle_kind + from firstrade_platform.application.rebalance_service import _publish_cycle_notification + from firstrade_platform.notifications.unified import alert_text, coverage_locale, cycle_kind routine = cycle_kind(result) in {"routine_cycle", "order_submitted", "fill"} if dry_run and routine: result["notification_consolidation"] = {"route": "preview", "candidate_persisted": False} diff --git a/notifications/__init__.py b/src/firstrade_platform/notifications/__init__.py similarity index 100% rename from notifications/__init__.py rename to src/firstrade_platform/notifications/__init__.py diff --git a/notifications/compact_adapter.py b/src/firstrade_platform/notifications/compact_adapter.py similarity index 100% rename from notifications/compact_adapter.py rename to src/firstrade_platform/notifications/compact_adapter.py diff --git a/notifications/digest_snapshot/__init__.py b/src/firstrade_platform/notifications/digest_snapshot/__init__.py similarity index 100% rename from notifications/digest_snapshot/__init__.py rename to src/firstrade_platform/notifications/digest_snapshot/__init__.py diff --git a/notifications/digest_snapshot/digest_archive.py b/src/firstrade_platform/notifications/digest_snapshot/digest_archive.py similarity index 100% rename from notifications/digest_snapshot/digest_archive.py rename to src/firstrade_platform/notifications/digest_snapshot/digest_archive.py diff --git a/notifications/digest_snapshot/digest_candidates.py b/src/firstrade_platform/notifications/digest_snapshot/digest_candidates.py similarity index 100% rename from notifications/digest_snapshot/digest_candidates.py rename to src/firstrade_platform/notifications/digest_snapshot/digest_candidates.py diff --git a/notifications/digest_snapshot/digest_routing.py b/src/firstrade_platform/notifications/digest_snapshot/digest_routing.py similarity index 100% rename from notifications/digest_snapshot/digest_routing.py rename to src/firstrade_platform/notifications/digest_snapshot/digest_routing.py diff --git a/notifications/digest_snapshot/unified_contract.py b/src/firstrade_platform/notifications/digest_snapshot/unified_contract.py similarity index 100% rename from notifications/digest_snapshot/unified_contract.py rename to src/firstrade_platform/notifications/digest_snapshot/unified_contract.py diff --git a/notifications/telegram.py b/src/firstrade_platform/notifications/telegram.py similarity index 99% rename from notifications/telegram.py rename to src/firstrade_platform/notifications/telegram.py index 66142439..e16089dc 100644 --- a/notifications/telegram.py +++ b/src/firstrade_platform/notifications/telegram.py @@ -2,7 +2,7 @@ from __future__ import annotations -from application.firstrade_client import mask_account_id +from firstrade_platform.application.firstrade_client import mask_account_id from quant_platform_kit.common.display_names import display_name from quant_platform_kit.common.operational_notification_localization import resolve_operational_notification_locale @@ -28,7 +28,7 @@ localize_price_source_label as _localize_price_source_label, present as _present, ) -from notifications.compact_adapter import adapt_compact_sections +from firstrade_platform.notifications.compact_adapter import adapt_compact_sections from quant_platform_kit.notifications.events import RenderedNotification from quant_platform_kit.common.notification_localization import ( diff --git a/notifications/unified.py b/src/firstrade_platform/notifications/unified.py similarity index 98% rename from notifications/unified.py rename to src/firstrade_platform/notifications/unified.py index 45ce75cb..a7ab0c6e 100644 --- a/notifications/unified.py +++ b/src/firstrade_platform/notifications/unified.py @@ -13,15 +13,15 @@ import os import re -from notifications.digest_snapshot import digest_archive -from notifications.digest_snapshot.digest_candidates import project_reports -from notifications.digest_snapshot.digest_routing import defer_routine_cycle_to_digest -from notifications.digest_snapshot.unified_contract import ( +from firstrade_platform.notifications.digest_snapshot import digest_archive +from firstrade_platform.notifications.digest_snapshot.digest_candidates import project_reports +from firstrade_platform.notifications.digest_snapshot.digest_routing import defer_routine_cycle_to_digest +from firstrade_platform.notifications.digest_snapshot.unified_contract import ( CandidatePersistenceError, IncidentTracker, NotificationEvent, order_identity_digest, route_notification_event, sgt_business_window, unified_notification_enabled, ) -from application.account_facts_readonly import AccountFactsUnavailable, _decimal_text +from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable, _decimal_text FLAG = "FIRSTRADE_UNIFIED_NOTIFICATION_ENABLED" TARGET_KEYS = ("platform_id", "strategy_profile", "service_name", "account_scope", diff --git a/runtime_config_support.py b/src/firstrade_platform/runtime_config_support.py similarity index 99% rename from runtime_config_support.py rename to src/firstrade_platform/runtime_config_support.py index ff64a23b..cb7a551c 100644 --- a/runtime_config_support.py +++ b/src/firstrade_platform/runtime_config_support.py @@ -29,7 +29,7 @@ resolve_runtime_target_from_env, ) from quant_platform_kit.common.live_continuity import runtime_target_permits_standard_execution -from strategy_registry import ( +from firstrade_platform.strategy_registry import ( FIRSTRADE_PLATFORM, resolve_strategy_definition, resolve_strategy_metadata, @@ -207,7 +207,7 @@ def load_platform_runtime_settings( strategy_metadata=strategy_metadata, platform_env_prefix="FIRSTRADE", env=os.environ, - repo_root=Path(__file__).resolve().parent, + repo_root=Path(__file__).resolve().parents[2], ) return PlatformRuntimeSettings( project_id=project_id_resolver(), diff --git a/runtime_execution_policy.py b/src/firstrade_platform/runtime_execution_policy.py similarity index 92% rename from runtime_execution_policy.py rename to src/firstrade_platform/runtime_execution_policy.py index 2a57b309..ecdc959d 100644 --- a/runtime_execution_policy.py +++ b/src/firstrade_platform/runtime_execution_policy.py @@ -6,7 +6,7 @@ fractional_share_execution_unsupported_reason, ) from quant_platform_kit.common.strategies import normalize_profile_name -from strategy_registry import PLATFORM_CAPABILITY_MATRIX, STRATEGY_CATALOG +from firstrade_platform.strategy_registry import PLATFORM_CAPABILITY_MATRIX, STRATEGY_CATALOG def dca_execution_unsupported_reason(strategy_profile: str) -> str | None: diff --git a/strategy_loader.py b/src/firstrade_platform/strategy_loader.py similarity index 88% rename from strategy_loader.py rename to src/firstrade_platform/strategy_loader.py index 51201b8b..d450c1ba 100644 --- a/strategy_loader.py +++ b/src/firstrade_platform/strategy_loader.py @@ -10,7 +10,12 @@ StrategyRuntimeAdapter, ) -from strategy_registry import FIRSTRADE_PLATFORM as PLATFORM, PLATFORM_POLICY, STRATEGY_CATALOG, get_platform_runtime_adapter +from firstrade_platform.strategy_registry import ( + FIRSTRADE_PLATFORM as PLATFORM, + PLATFORM_POLICY, + STRATEGY_CATALOG, + get_platform_runtime_adapter, +) def load_strategy_definition(raw_profile: str | None) -> StrategyDefinition: diff --git a/strategy_registry.py b/src/firstrade_platform/strategy_registry.py similarity index 100% rename from strategy_registry.py rename to src/firstrade_platform/strategy_registry.py diff --git a/strategy_runtime.py b/src/firstrade_platform/strategy_runtime.py similarity index 98% rename from strategy_runtime.py rename to src/firstrade_platform/strategy_runtime.py index e1f7f12b..2ce08dad 100644 --- a/strategy_runtime.py +++ b/src/firstrade_platform/strategy_runtime.py @@ -17,9 +17,9 @@ build_execution_timing_metadata, build_strategy_context_from_available_inputs, ) -from runtime_config_support import PlatformRuntimeSettings +from firstrade_platform.runtime_config_support import PlatformRuntimeSettings from us_equity_strategies.signals import resolve_external_market_signal_inputs -from strategy_loader import ( +from firstrade_platform.strategy_loader import ( load_strategy_entrypoint_for_profile, load_strategy_runtime_adapter_for_profile, ) diff --git a/tests/test_account_alert_redaction.py b/tests/test_account_alert_redaction.py index 9baacda6..337123e1 100644 --- a/tests/test_account_alert_redaction.py +++ b/tests/test_account_alert_redaction.py @@ -6,9 +6,9 @@ import pytest import requests -import main -from application.firstrade_client import FirstradeBrokerClient, FirstradeCredentials -from notifications import unified +from firstrade_platform import main +from firstrade_platform.application.firstrade_client import FirstradeBrokerClient, FirstradeCredentials +from firstrade_platform.notifications import unified class MemoryStore: @@ -91,7 +91,7 @@ def post(url, *, json, timeout): @pytest.mark.parametrize("account", ["87654321", "****4321"]) @pytest.mark.parametrize("lang", ["en", "zh"]) def test_cycle_alert_redacts_raw_and_legacy_accounts_at_log_and_transport(monkeypatch, account, lang): - from application.rebalance_service import _publish_cycle_notification + from firstrade_platform.application.rebalance_service import _publish_cycle_notification sent, logged = [], [] diff --git a/tests/test_account_facts_endpoint.py b/tests/test_account_facts_endpoint.py index c6a5957f..e5e27c51 100644 --- a/tests/test_account_facts_endpoint.py +++ b/tests/test_account_facts_endpoint.py @@ -8,10 +8,10 @@ pytest.importorskip("flask") -import main -from application.account_facts_readonly import AccountFactsUnavailable -from application.account_facts_publisher import AccountFactsPublishError -from application.firstrade_client import FirstradeCachedSessionError +from firstrade_platform import main +from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable +from firstrade_platform.application.account_facts_publisher import AccountFactsPublishError +from firstrade_platform.application.firstrade_client import FirstradeCachedSessionError def test_cached_failure_logs_correlate_without_changing_response(monkeypatch, capsys): diff --git a/tests/test_account_facts_publisher.py b/tests/test_account_facts_publisher.py index 34a838d4..dcdf5e1b 100644 --- a/tests/test_account_facts_publisher.py +++ b/tests/test_account_facts_publisher.py @@ -2,7 +2,7 @@ import pytest -from application.account_facts_publisher import ( +from firstrade_platform.application.account_facts_publisher import ( AccountFactsPublishConfig, AccountFactsPublishError, build_firstrade_account_snapshot, diff --git a/tests/test_account_facts_readonly.py b/tests/test_account_facts_readonly.py index ab4e4015..22e716d1 100644 --- a/tests/test_account_facts_readonly.py +++ b/tests/test_account_facts_readonly.py @@ -4,7 +4,7 @@ import pytest -from application.account_facts_readonly import ( +from firstrade_platform.application.account_facts_readonly import ( AccountFactsUnavailable, collect_firstrade_account_facts, ) diff --git a/tests/test_broker_reconciliation.py b/tests/test_broker_reconciliation.py index 316ad084..bbcef368 100644 --- a/tests/test_broker_reconciliation.py +++ b/tests/test_broker_reconciliation.py @@ -7,7 +7,7 @@ import pytest -from application.broker_reconciliation import ( +from firstrade_platform.application.broker_reconciliation import ( FirstradeReconciliationUnavailable, FirstradeReconciliationObservations, build_reconciliation_candidate, diff --git a/tests/test_build_market_inputs.py b/tests/test_build_market_inputs.py index 96ff38f1..a627d746 100644 --- a/tests/test_build_market_inputs.py +++ b/tests/test_build_market_inputs.py @@ -2,7 +2,7 @@ from types import SimpleNamespace -from application.rebalance_service import build_market_inputs +from firstrade_platform.application.rebalance_service import build_market_inputs class _FakeMarketDataPort: diff --git a/tests/test_cached_funds_archive.py b/tests/test_cached_funds_archive.py index 2d6d73c3..cfc31438 100644 --- a/tests/test_cached_funds_archive.py +++ b/tests/test_cached_funds_archive.py @@ -3,8 +3,8 @@ import pytest -import main -from application.account_facts_publisher import AccountFactsPublishError +from firstrade_platform import main +from firstrade_platform.application.account_facts_publisher import AccountFactsPublishError from tests.test_account_facts_endpoint import FakeClient, _configure @@ -33,7 +33,7 @@ def write_json(self, key, value): monkeypatch.setattr(main, "collect_firstrade_account_facts", lambda *a, **k: observation) monkeypatch.setattr(main, "publish_firstrade_account_snapshot", lambda *a: publishes.append(a)) # Patch the existing state-store boundary; no cloud or broker traffic. - import application.session_check_service as service + import firstrade_platform.application.session_check_service as service monkeypatch.setattr(service, "build_gcs_state_store_from_env", lambda *a: Store()) return observation, writes, publishes, client, service diff --git a/tests/test_candidate_failure_diagnostics.py b/tests/test_candidate_failure_diagnostics.py index 74b823fe..b86f5f7f 100644 --- a/tests/test_candidate_failure_diagnostics.py +++ b/tests/test_candidate_failure_diagnostics.py @@ -4,7 +4,7 @@ import pytest from google.api_core.exceptions import Forbidden -from notifications import unified +from firstrade_platform.notifications import unified from scripts import emit_unified_digest_candidates as publisher from scripts import execution_report_heartbeat as heartbeat from test_notification_consolidation import ENV, NOW, Store diff --git a/tests/test_check_fee_schedule.py b/tests/test_check_fee_schedule.py index 69e776c8..95f52651 100644 --- a/tests/test_check_fee_schedule.py +++ b/tests/test_check_fee_schedule.py @@ -9,7 +9,7 @@ import pytest -from application.firstrade_fee_schedule import DEFAULT_FEE_SCHEDULE_CONFIG +from firstrade_platform.application.firstrade_fee_schedule import DEFAULT_FEE_SCHEDULE_CONFIG from scripts import check_fee_schedule as cfs FIXTURES = Path(__file__).parent / "fixtures" / "fee_schedule_check" diff --git a/tests/test_cloud_run_entrypoint.py b/tests/test_cloud_run_entrypoint.py index f0bfb3f0..b7f39c21 100644 --- a/tests/test_cloud_run_entrypoint.py +++ b/tests/test_cloud_run_entrypoint.py @@ -1,4 +1,4 @@ -from entrypoints import cloud_run +from firstrade_platform.entrypoints import cloud_run def test_market_hours_after_close_is_closed_without_calendar_error(monkeypatch): diff --git a/tests/test_compact_notification_adapter.py b/tests/test_compact_notification_adapter.py index fe23fd2f..abd16aeb 100644 --- a/tests/test_compact_notification_adapter.py +++ b/tests/test_compact_notification_adapter.py @@ -1,4 +1,4 @@ -from notifications.compact_adapter import adapt_compact_sections +from firstrade_platform.notifications.compact_adapter import adapt_compact_sections def test_adapter_keeps_only_nonzero_holdings_and_appends_supplements(): diff --git a/tests/test_coverage_source_layout.py b/tests/test_coverage_source_layout.py index 15f1c7d8..d29a7566 100644 --- a/tests/test_coverage_source_layout.py +++ b/tests/test_coverage_source_layout.py @@ -1,9 +1,9 @@ """Verify the coverage source layout measures shipped production code. -The denominator is the repository tree minus explicitly excluded categories. -A hermetic synthetic tree proves that unexecuted in-scope lines and files -remain in the denominator while excluded test/external/build code cannot -inflate the measurement. +The denominator is the ``src/firstrade_platform`` package tree minus explicitly +excluded categories. A hermetic synthetic tree proves that unexecuted in-scope +lines and files remain in the denominator while excluded test/external/build +code cannot inflate the measurement. """ from __future__ import annotations @@ -30,6 +30,18 @@ ) CANONICAL_OMIT_CATEGORIES = ("tests/", "external/", ".venv/", "build/", "dist/") +LEGACY_ROOT_PATHS = ( + "application", + "entrypoints", + "notifications", + "decision_mapper.py", + "main.py", + "runtime_config_support.py", + "runtime_execution_policy.py", + "strategy_loader.py", + "strategy_registry.py", + "strategy_runtime.py", +) def pyproject(): @@ -46,10 +58,16 @@ def coverage_report_config(): def declared_production_sources(): data = pyproject() - modules = data["tool"]["setuptools"]["py-modules"] - include = data["tool"]["setuptools"]["packages"]["find"]["include"] - packages = sorted({p.name for pattern in include for p in ROOT.glob(pattern) if p.is_dir()}) - return modules, packages + setuptools_cfg = data["tool"]["setuptools"] + package_dir = setuptools_cfg["package-dir"] + where = setuptools_cfg["packages"]["find"]["where"] + if package_dir != {"": "src"} or where != ["src"]: + raise AssertionError(f"Unexpected setuptools src layout: {package_dir!r}, {where!r}") + src_root = ROOT / "src" + packages = sorted( + p.name for p in src_root.iterdir() if p.is_dir() and (p / "__init__.py").is_file() + ) + return packages def matches_any_omit(path, omit_patterns): @@ -61,49 +79,54 @@ def matches_any_omit(path, omit_patterns): class CoverageSourceLayoutTests(unittest.TestCase): - def test_source_is_repository_root_with_explicit_category_exclusions(self): + def test_source_is_src_package_with_explicit_category_exclusions(self): run = coverage_run_config() report = coverage_report_config() - self.assertEqual(run["source"], ["."]) + self.assertEqual(run["source"], ["src/firstrade_platform"]) self.assertTrue(report.get("include_namespace_packages")) - self.assertFalse((ROOT / "src").exists()) + self.assertTrue((ROOT / "src" / "firstrade_platform" / "__init__.py").is_file()) + for legacy_path in LEGACY_ROOT_PATHS: + self.assertFalse((ROOT / legacy_path).exists(), legacy_path) self.assertNotIn("fail_under", str(pyproject()["tool"]["coverage"])) omit = " ".join(run["omit"]) for category in CANONICAL_OMIT_CATEGORIES: self.assertIn(category, omit) def test_declared_production_paths_are_measured(self): - modules, packages = declared_production_sources() + packages = declared_production_sources() + self.assertEqual(packages, ["firstrade_platform"]) omit = coverage_run_config()["omit"] - for module in modules: - relative = f"{module}.py" - self.assertTrue((ROOT / relative).exists(), relative) - self.assertFalse(matches_any_omit(relative, omit), relative) for package in packages: - self.assertFalse(matches_any_omit(package, omit), package) + pkg_root = ROOT / "src" / package + self.assertTrue(pkg_root.is_dir(), package) + for py_file in sorted(pkg_root.rglob("*.py")): + relative = py_file.relative_to(ROOT).as_posix() + self.assertFalse(matches_any_omit(relative, omit), relative) def test_unexecuted_in_scope_files_remain_in_denominator(self): - modules, packages = declared_production_sources() + packages = declared_production_sources() + package = packages[0] run = coverage_run_config() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) - for module in modules: - (root / f"{module}.py").write_text(SYNTHETIC_MODULE, encoding="utf-8") - for package in packages: - (root / package).mkdir() - (root / packages[0] / "synthetic_service.py").write_text( + pkg_dir = root / "src" / package + (pkg_dir / "application").mkdir(parents=True) + (pkg_dir / "__init__.py").write_text("", encoding="utf-8") + (pkg_dir / "executed_mod.py").write_text(SYNTHETIC_MODULE, encoding="utf-8") + (pkg_dir / "never_imported.py").write_text(SYNTHETIC_MODULE, encoding="utf-8") + (pkg_dir / "application" / "__init__.py").write_text("", encoding="utf-8") + (pkg_dir / "application" / "synthetic_service.py").write_text( SYNTHETIC_MODULE, encoding="utf-8" ) excluded = "def never_executed():\n value = 1\n return value\n" for directory in ("tests", "external", ".venv", "build", "dist"): (root / directory).mkdir(parents=True) (root / directory / "excluded_module.py").write_text(excluded, encoding="utf-8") - imported = modules[:-1] - imports = [ - f"importlib.import_module({module!r}).executed()" for module in imported - ] (root / "runner.py").write_text( - "import importlib\n" + "\n".join(imports) + "\nprint('done')\n", + "import importlib, sys\n" + "sys.path.insert(0, 'src')\n" + f"importlib.import_module('{package}.executed_mod').executed()\n" + "print('done')\n", encoding="utf-8", ) (root / ".coveragerc").write_text( @@ -142,13 +165,13 @@ def test_unexecuted_in_scope_files_remain_in_denominator(self): for candidate in output.splitlines() if candidate and not candidate.startswith(("Name", "-", "TOTAL")) } - for module in imported: - self.assertIn(module + ".py", lines) - self.assertIn("6-7", lines[module + ".py"]) - never_imported = modules[-1] - self.assertIn(never_imported + ".py", lines) - self.assertIn("0%", lines[never_imported + ".py"]) - service_path = f"{packages[0]}/synthetic_service.py" + executed_path = f"src/{package}/executed_mod.py" + self.assertIn(executed_path, lines) + self.assertIn("6-7", lines[executed_path]) + never_imported_path = f"src/{package}/never_imported.py" + self.assertIn(never_imported_path, lines) + self.assertIn("0%", lines[never_imported_path]) + service_path = f"src/{package}/application/synthetic_service.py" self.assertIn(service_path, lines) self.assertIn("0%", lines[service_path]) for directory in ("tests", "external", ".venv", "build", "dist"): diff --git a/tests/test_daily_notification_policy.py b/tests/test_daily_notification_policy.py index 324bcaca..13d34855 100644 --- a/tests/test_daily_notification_policy.py +++ b/tests/test_daily_notification_policy.py @@ -6,8 +6,8 @@ import pytest -from notifications import unified -from notifications.digest_snapshot.digest_candidates import cycle_evidence +from firstrade_platform.notifications import unified +from firstrade_platform.notifications.digest_snapshot.digest_candidates import cycle_evidence class MemoryStore: @@ -184,8 +184,8 @@ def test_coverage_error_is_localized_without_trade_details(locale, expected): def test_routine_plugin_filter_preserves_urgent_and_counts_only_safe_routes(): - from notifications.digest_snapshot.digest_candidates import routine_observation_counts - from notifications.digest_snapshot.digest_routing import immediate_plugin_signals + from firstrade_platform.notifications.digest_snapshot.digest_candidates import routine_observation_counts + from firstrade_platform.notifications.digest_snapshot.digest_routing import immediate_plugin_signals watch = SimpleNamespace(canonical_route="watch", suggested_action="observe") urgent = SimpleNamespace(canonical_route="watch", suggested_action="observe", error="synthetic") assert immediate_plugin_signals([watch, urgent], mode="daily_digest") == (urgent,) @@ -193,7 +193,7 @@ def test_routine_plugin_filter_preserves_urgent_and_counts_only_safe_routes(): def test_archive_confirmation_requires_exact_configured_uri(monkeypatch): - from main import _report_archive_confirmed + from firstrade_platform.main import _report_archive_confirmed from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri monkeypatch.setenv("EXECUTION_REPORT_GCS_URI", "gs://synthetic/reports") monkeypatch.delenv("QSL_EXECUTION_REPORT_GCS_URI", raising=False) @@ -209,7 +209,7 @@ def test_archive_confirmation_requires_exact_configured_uri(monkeypatch): def test_direct_urgent_with_watch_reports_coverage_without_suppressing_urgent(monkeypatch): - from application.rebalance_service import _report_unarchived_direct_coverage + from firstrade_platform.application.rebalance_service import _report_unarchived_direct_coverage settings = SimpleNamespace(notify_lang="en", tg_token=None, tg_chat_id=None) monkeypatch.setenv("QSL_NOTIFY_LANG", " EN-us ") result = {"ok": False, "error": "synthetic", "routine_observation_counts": {"watch": 1}} @@ -224,7 +224,7 @@ def test_direct_urgent_with_watch_reports_coverage_without_suppressing_urgent(mo def test_direct_normal_preview_does_not_send_coverage(): - from application.rebalance_service import _report_unarchived_direct_coverage + from firstrade_platform.application.rebalance_service import _report_unarchived_direct_coverage result = {"ok": True, "dry_run_only": True, "execution_status": "dry_run", "routine_observation_counts": {"watch": 1}} sent = [] @@ -234,7 +234,7 @@ def test_direct_normal_preview_does_not_send_coverage(): def test_main_normal_preview_without_archive_does_not_send(monkeypatch): - import main + from firstrade_platform import main settings = SimpleNamespace(dry_run_only=True, tg_token="synthetic", tg_chat_id="synthetic") result = {"ok": True, "dry_run_only": True, "execution_status": "dry_run"} monkeypatch.setattr(main, "_runtime_settings", lambda **kwargs: settings) @@ -254,8 +254,8 @@ def test_main_normal_preview_without_archive_does_not_send(monkeypatch): @pytest.mark.parametrize("flag", [None, "false", "true"]) def test_actual_main_archives_before_staging_and_never_sends_routine(flag, monkeypatch): - import main - from application import rebalance_service + from firstrade_platform import main + from firstrade_platform.application import rebalance_service from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri now, result, report, env = fixtures() result["strategy_run_stage"] = "PENDING_RECONCILIATION" diff --git a/tests/test_decision_mapper.py b/tests/test_decision_mapper.py index be61eb91..a3dbcbc8 100644 --- a/tests/test_decision_mapper.py +++ b/tests/test_decision_mapper.py @@ -8,7 +8,7 @@ StrategyDecision, ) -from decision_mapper import map_strategy_decision_to_plan +from firstrade_platform.decision_mapper import map_strategy_decision_to_plan def test_applies_platform_reserved_cash_policy_to_weight_decision(): diff --git a/tests/test_execution_receipt_adapter.py b/tests/test_execution_receipt_adapter.py index f427e3f4..61a7341c 100644 --- a/tests/test_execution_receipt_adapter.py +++ b/tests/test_execution_receipt_adapter.py @@ -2,7 +2,7 @@ import unittest -from application.execution_receipt_adapter import ( +from firstrade_platform.application.execution_receipt_adapter import ( attach_strategy_result_execution_receipt, attach_unknown_failure_execution_receipt, is_expected_funding_skip, diff --git a/tests/test_execution_service.py b/tests/test_execution_service.py index cf94c08b..8ffef444 100644 --- a/tests/test_execution_service.py +++ b/tests/test_execution_service.py @@ -5,7 +5,7 @@ import pytest -from application.execution_service import ( +from firstrade_platform.application.execution_service import ( _apply_notional_cash_buffer, execute_value_target_plan, substitute_small_safe_haven_targets_with_cash, @@ -125,7 +125,7 @@ def submit_order(self, intent): @pytest.mark.parametrize("payload", [{"statusCode": 500}, {"statusCode": 200, "result": {}}]) @pytest.mark.parametrize("notional", [False, True]) def test_real_adapter_ambiguous_response_stops_cycle_pending(payload, notional): - from application.runtime_broker_adapters import build_runtime_broker_adapters + from firstrade_platform.application.runtime_broker_adapters import build_runtime_broker_adapters class LocalClient: def __init__(self): diff --git a/tests/test_firstrade_client.py b/tests/test_firstrade_client.py index e07751a8..f2199bc3 100644 --- a/tests/test_firstrade_client.py +++ b/tests/test_firstrade_client.py @@ -5,7 +5,7 @@ import pytest -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, FirstradeCachedSessionError, FirstradeCredentials, @@ -319,7 +319,7 @@ def test_client_reuses_cached_session_without_logging_in_again(tmp_path): assert second_client.read_only_transport_enabled is False assert ReusableFakeSession.login_calls == 1 - from application.account_facts_readonly import AccountFactsUnavailable, collect_firstrade_account_facts + from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable, collect_firstrade_account_facts with pytest.raises(AccountFactsUnavailable) as error: collect_firstrade_account_facts( @@ -416,7 +416,7 @@ def test_order_reads_preserve_supported_complete_payloads(wrapper, rows): def _cached_read_only_client(tmp_path, monkeypatch, *, saved_at=1000.0, account_factory=HeaderCheckingAccountData): - import application.firstrade_client as module + import firstrade_platform.application.firstrade_client as module import requests monkeypatch.setattr(module, "time", lambda: 1001.0) @@ -478,7 +478,7 @@ def test_read_only_connection_reuses_cache_without_auth_or_writes(tmp_path, monk assert store.writes == 0 assert not (tmp_path / "absent").exists() assert calls == [] - from application.account_facts_readonly import collect_firstrade_account_facts + from firstrade_platform.application.account_facts_readonly import collect_firstrade_account_facts facts = collect_firstrade_account_facts(client, expected_account="12345678") assert facts["status"] == "available" diff --git a/tests/test_forced_session_renewal.py b/tests/test_forced_session_renewal.py index e37a8879..b7ed795c 100644 --- a/tests/test_forced_session_renewal.py +++ b/tests/test_forced_session_renewal.py @@ -2,9 +2,9 @@ import pytest -from application import session_check_service -from application.firstrade_client import FirstradeCredentials, FirstradeMfaRequired, FirstradeSafetyError -from application.session_check_service import run_forced_session_renewal +from firstrade_platform.application import session_check_service +from firstrade_platform.application.firstrade_client import FirstradeCredentials, FirstradeMfaRequired, FirstradeSafetyError +from firstrade_platform.application.session_check_service import run_forced_session_renewal ORDER_METHODS = ("place_stock_order", "place_order", "submit_order", "cancel_order", "preview_order") READ_METHODS = {"connect", "select_account", "get_balances", "save_verified_session_cache"} @@ -106,7 +106,7 @@ def make(credentials, *, live_trading_enabled): def test_connect_force_login_skips_cached_session(tmp_path): - from application.firstrade_client import FirstradeBrokerClient + from firstrade_platform.application.firstrade_client import FirstradeBrokerClient events = [] @@ -134,7 +134,7 @@ def login(self): @pytest.mark.parametrize("scenario", ["success", "auto_single", "empty_balances", "wrong_account", "auto_multiple", "balances_fail", "store_false", "store_error"]) @pytest.mark.parametrize("invalid_token", [None, ("access-token", None), ("access-token", 123), ("access-token", " "), ("ftat", None), ("ftat", 123), ("ftat", " "), ("sid", None), ("sid", 123), ("sid", " ")]) def test_renewal_commits_shared_cache_only_after_account_and_balance_validation(tmp_path, scenario, invalid_token): - from application.firstrade_client import FirstradeBrokerClient, FirstradePlatformError + from firstrade_platform.application.firstrade_client import FirstradeBrokerClient, FirstradePlatformError events = [] @@ -198,7 +198,7 @@ def run(): @pytest.fixture def http_client(monkeypatch): pytest.importorskip("flask") - import main + from firstrade_platform import main def no_orders(*_a, **_k): raise AssertionError("strategy/order path reached") diff --git a/tests/test_heartbeat_archive_reader.py b/tests/test_heartbeat_archive_reader.py index b294b381..4c013021 100644 --- a/tests/test_heartbeat_archive_reader.py +++ b/tests/test_heartbeat_archive_reader.py @@ -6,7 +6,7 @@ import pytest from google.api_core.exceptions import Forbidden -from notifications import unified +from firstrade_platform.notifications import unified from test_publish_digest_before_read import ENV, PLATFORM import test_publish_digest_before_read as prepub @@ -86,7 +86,7 @@ def test_invalid_archive_json_remains_a_read_failure(client): def test_cross_month_report_in_october_is_preserved_when_november_is_empty(client): - from notifications.digest_snapshot.digest_candidates import cycle_evidence + from firstrade_platform.notifications.digest_snapshot.digest_candidates import cycle_evidence target = json.loads(ENV["RUNTIME_TARGET_JSON"]) report = {"schema_version": "runtime_report.v1", "platform": SOURCE_PLATFORM, "strategy_profile": target["strategy_profile"], "service_name": target["service_name"], diff --git a/tests/test_inspect_account_history_schema.py b/tests/test_inspect_account_history_schema.py index 9f7beb4e..6d21e9aa 100644 --- a/tests/test_inspect_account_history_schema.py +++ b/tests/test_inspect_account_history_schema.py @@ -4,7 +4,7 @@ import pytest -from application.firstrade_client import FirstradeCachedSessionError +from firstrade_platform.application.firstrade_client import FirstradeCachedSessionError from scripts import inspect_account_history_schema as module diff --git a/tests/test_market_hours_gate.py b/tests/test_market_hours_gate.py index 600c56d7..08a87e61 100644 --- a/tests/test_market_hours_gate.py +++ b/tests/test_market_hours_gate.py @@ -6,7 +6,7 @@ import pytest from quant_platform_kit.common.us_equity_sessions import Session -import main +from firstrade_platform import main def test_market_hours_gate_uses_regular_session_only(monkeypatch): diff --git a/tests/test_notification_consolidation.py b/tests/test_notification_consolidation.py index 39776171..e4e2518c 100644 --- a/tests/test_notification_consolidation.py +++ b/tests/test_notification_consolidation.py @@ -6,8 +6,8 @@ import pytest -from notifications import unified -from notifications.digest_snapshot.digest_candidates import cycle_evidence +from firstrade_platform.notifications import unified +from firstrade_platform.notifications.digest_snapshot.digest_candidates import cycle_evidence NOW = datetime(2026, 10, 17, 0, tzinfo=timezone.utc) TARGET = dict(platform_id="firstrade", strategy_profile="synthetic", service_name="synthetic-service", diff --git a/tests/test_notification_off_equivalence.py b/tests/test_notification_off_equivalence.py index e4e2fa28..39ac7011 100644 --- a/tests/test_notification_off_equivalence.py +++ b/tests/test_notification_off_equivalence.py @@ -10,9 +10,9 @@ import pytest -import main -from application.rebalance_service import _publish_cycle_notification -from notifications.telegram import render_cycle_notification +from firstrade_platform import main +from firstrade_platform.application.rebalance_service import _publish_cycle_notification +from firstrade_platform.notifications.telegram import render_cycle_notification from scripts import execution_report_heartbeat as heartbeat GOLDEN = Path(__file__).parent / "fixtures" / "notification_main_c320fa0.json" @@ -109,8 +109,8 @@ def record_all(monkeypatch): def record_broker_cycle(monkeypatch): - import application.rebalance_service as rebalance - from application.firstrade_client import FirstradeCredentials + import firstrade_platform.application.rebalance_service as rebalance + from firstrade_platform.application.firstrade_client import FirstradeCredentials from test_rebalance_service import (FakeFirstradeClient, FakeStateStore, FakeStrategyRuntime, _runtime_settings_with_persistence) calls = [] diff --git a/tests/test_notification_qrs_roundtrip.py b/tests/test_notification_qrs_roundtrip.py index d1e8c064..3a461a63 100644 --- a/tests/test_notification_qrs_roundtrip.py +++ b/tests/test_notification_qrs_roundtrip.py @@ -9,7 +9,7 @@ import pytest -from notifications import unified +from firstrade_platform.notifications import unified from test_notification_consolidation import ENV, NOW, Store, archive_read, candidate, notify, source QRS_SHA = "160933eaa376bd4297616e8affc946430be69771" diff --git a/tests/test_notification_quiet.py b/tests/test_notification_quiet.py index 555f95fc..dd119eb8 100644 --- a/tests/test_notification_quiet.py +++ b/tests/test_notification_quiet.py @@ -41,7 +41,7 @@ def mock_heartbeat(monkeypatch, payload): monkeypatch.setattr(heartbeat, '_cat_gcs_json', lambda *args, **kw: payload) sent = [] monkeypatch.setattr(heartbeat, '_send_telegram', lambda msg, **kw: sent.append(msg) or True) - from notifications import unified + from firstrade_platform.notifications import unified monkeypatch.setattr(unified, 'notify_heartbeat', lambda **kw: {'candidate_persisted': True}) return sent diff --git a/tests/test_notification_scoped_state.py b/tests/test_notification_scoped_state.py index 883d4467..26960cc9 100644 --- a/tests/test_notification_scoped_state.py +++ b/tests/test_notification_scoped_state.py @@ -4,7 +4,7 @@ import pytest -from notifications import unified +from firstrade_platform.notifications import unified from test_notification_consolidation import ENV, NOW, Store, notify, source diff --git a/tests/test_notification_storage_and_wiring.py b/tests/test_notification_storage_and_wiring.py index 2c4a69ce..ea77d3fe 100644 --- a/tests/test_notification_storage_and_wiring.py +++ b/tests/test_notification_storage_and_wiring.py @@ -10,7 +10,7 @@ import pytest -from notifications import unified +from firstrade_platform.notifications import unified from test_notification_consolidation import ENV, NOW, Store, TARGET, candidate, notify, source @@ -116,8 +116,8 @@ def test_candidate_slot_cannot_mix_accounts_even_if_misconfigured(): def test_main_on_writes_report_then_candidate_and_preserves_cycle_options(monkeypatch): - import main - import application.rebalance_service as rebalance + from firstrade_platform import main + import firstrade_platform.application.rebalance_service as rebalance class FixtureDateTime(datetime): @classmethod def now(cls, tz=None): diff --git a/tests/test_notifications.py b/tests/test_notifications.py index ecf64cf7..7f56466f 100644 --- a/tests/test_notifications.py +++ b/tests/test_notifications.py @@ -3,13 +3,11 @@ ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) -PLATFORM_KIT_SRC = ROOT.parent / "QuantPlatformKit" / "src" -if str(PLATFORM_KIT_SRC) not in sys.path: - sys.path.insert(0, str(PLATFORM_KIT_SRC)) +SRC = ROOT / "src" +if str(SRC) not in sys.path: + sys.path.insert(0, str(SRC)) -from notifications.telegram import build_sender +from firstrade_platform.notifications.telegram import build_sender class FakeRequests: diff --git a/tests/test_notifications_telegram.py b/tests/test_notifications_telegram.py index efc88970..c8d6f617 100644 --- a/tests/test_notifications_telegram.py +++ b/tests/test_notifications_telegram.py @@ -1,6 +1,6 @@ from __future__ import annotations -from notifications.telegram import render_cycle_notification, render_cycle_summary +from firstrade_platform.notifications.telegram import render_cycle_notification, render_cycle_summary def test_funding_block_reason_is_localized_in_both_notification_formats(): diff --git a/tests/test_paper_execution_admission.py b/tests/test_paper_execution_admission.py index 103a027e..5922ea5c 100644 --- a/tests/test_paper_execution_admission.py +++ b/tests/test_paper_execution_admission.py @@ -2,7 +2,7 @@ import json -from application.paper_execution_admission import ( +from firstrade_platform.application.paper_execution_admission import ( PAPER_ADMISSION_ENABLED_ENV, PAPER_EXECUTION_COMMAND_ENV, evaluate_paper_dry_run_admission, diff --git a/tests/test_paper_execution_command_consumer.py b/tests/test_paper_execution_command_consumer.py index e97b417a..d6ee7cd6 100644 --- a/tests/test_paper_execution_command_consumer.py +++ b/tests/test_paper_execution_command_consumer.py @@ -7,7 +7,7 @@ import pytest -from application.paper_execution_command_consumer import ( +from firstrade_platform.application.paper_execution_command_consumer import ( FIRSTRADE_PAPER_EXECUTION_INTENT_SCHEMA_VERSION, consume_due_paper_execution_commands, resolve_paper_execution_command_consumer_enabled, diff --git a/tests/test_paper_notification_preview.py b/tests/test_paper_notification_preview.py index d9977216..b8ec7956 100644 --- a/tests/test_paper_notification_preview.py +++ b/tests/test_paper_notification_preview.py @@ -26,6 +26,13 @@ "entrypoints", "runtime_config_support", "runtime_execution_policy", + "firstrade_platform.main", + "firstrade_platform.application", + "firstrade_platform.strategy_runtime", + "firstrade_platform.decision_mapper", + "firstrade_platform.entrypoints", + "firstrade_platform.runtime_config_support", + "firstrade_platform.runtime_execution_policy", ) _FORBIDDEN_TEXT = ( @@ -72,7 +79,7 @@ def test_build_preview_message_supports_english_locale(): def test_preview_profile_is_enabled_on_firstrade(): - from strategy_registry import SUPPORTED_STRATEGY_PROFILES + from firstrade_platform.strategy_registry import SUPPORTED_STRATEGY_PROFILES assert preview._PREVIEW_STRATEGY_PROFILE in SUPPORTED_STRATEGY_PROFILES @@ -137,7 +144,7 @@ def test_preview_script_has_no_broker_or_execution_imports(): name == forbidden or name.startswith(f"{forbidden}.") for name in imported ) - assert "notifications.telegram" in imported + assert "firstrade_platform.notifications.telegram" in imported def test_send_preview_fails_closed_without_telegram_target(monkeypatch): diff --git a/tests/test_plugin_alert_settings_characterization.py b/tests/test_plugin_alert_settings_characterization.py index fd344e5b..ec0b28ae 100644 --- a/tests/test_plugin_alert_settings_characterization.py +++ b/tests/test_plugin_alert_settings_characterization.py @@ -17,7 +17,7 @@ import pytest -import runtime_config_support as config +import firstrade_platform.runtime_config_support as config BASELINE_LOADER = r''' def load_platform_runtime_settings( @@ -46,7 +46,7 @@ def load_platform_runtime_settings( strategy_metadata=strategy_metadata, platform_env_prefix="FIRSTRADE", env=os.environ, - repo_root=Path(__file__).resolve().parent, + repo_root=Path(__file__).resolve().parents[2], ) return PlatformRuntimeSettings( project_id=project_id_resolver(), diff --git a/tests/test_publish_archived_account_history.py b/tests/test_publish_archived_account_history.py index 4d1b7cc6..fc2606fb 100644 --- a/tests/test_publish_archived_account_history.py +++ b/tests/test_publish_archived_account_history.py @@ -8,10 +8,10 @@ import pytest -from application.account_facts_publisher import ( +from firstrade_platform.application.account_facts_publisher import ( AccountFactsPublishConfig, AccountFactsPublishError, publish_firstrade_account_snapshot, ) -from application.account_facts_readonly import AccountFactsUnavailable, _decimal_text +from firstrade_platform.application.account_facts_readonly import AccountFactsUnavailable, _decimal_text from scripts import publish_archived_account_history as history diff --git a/tests/test_publish_digest_before_read.py b/tests/test_publish_digest_before_read.py index 11739332..60e586a4 100644 --- a/tests/test_publish_digest_before_read.py +++ b/tests/test_publish_digest_before_read.py @@ -146,7 +146,7 @@ def test_completed_window_uses_only_bound_funds_observation( def test_configured_currency_does_not_carry_over_to_other_target_bindings(): - from notifications.unified import _bindings + from firstrade_platform.notifications.unified import _bindings bindings = _bindings({ "DIGEST_FUNDS_SNAPSHOT_CURRENCY": "USD", @@ -258,7 +258,7 @@ def emit(*a): @pytest.mark.parametrize("stage", ["candidate_read", "candidate_write"]) def test_persistence_diagnostic_identifies_operation_without_raw_error(stage, monkeypatch, capsys): - from notifications.unified import _merge, CandidateStorageError + from firstrade_platform.notifications.unified import _merge, CandidateStorageError calls = [] class Store: def read(self, uri): @@ -286,7 +286,7 @@ def fail(*a): def test_existing_business_report_uses_native_archive_reader_and_verified_publication(client): - from notifications.digest_snapshot.digest_candidates import cycle_evidence + from firstrade_platform.notifications.digest_snapshot.digest_candidates import cycle_evidence env = {**ENV, "FIRSTRADE_UNIFIED_NOTIFICATION_ENABLED": "true", "RUNTIME_HEARTBEAT_REPORT_PLATFORM": "firstrade", "IBKR_NOTIFICATION_MARKER_GCS_URI": "gs://synthetic-candidates/markers"} diff --git a/tests/test_rebalance_service.py b/tests/test_rebalance_service.py index ea8855c6..40e1365f 100644 --- a/tests/test_rebalance_service.py +++ b/tests/test_rebalance_service.py @@ -6,18 +6,22 @@ import pytest -from application.firstrade_client import FirstradeBrokerClient, FirstradeCredentials, FirstradePlatformError -from application.rebalance_service import ( +from firstrade_platform.application.firstrade_client import ( + FirstradeBrokerClient, + FirstradeCredentials, + FirstradePlatformError, +) +from firstrade_platform.application.rebalance_service import ( _publish_cycle_notification, _runtime_metadata_with_execution_policy, run_strategy_cycle, ) -from notifications.telegram import I18N, build_translator, render_cycle_summary +from firstrade_platform.notifications.telegram import I18N, build_translator, render_cycle_summary from quant_platform_kit.common.strategy_contracts import ( PositionTarget, StrategyDecision, ) -from runtime_config_support import PlatformRuntimeSettings +from firstrade_platform.runtime_config_support import PlatformRuntimeSettings def _runtime_settings() -> PlatformRuntimeSettings: @@ -194,11 +198,11 @@ def _latest_strategy_run_payloads(store: FakeStateStore) -> list[dict]: def live_cycle(monkeypatch): client = FakeFirstradeClient(None, live_trading_enabled=True) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 9, 5, tzinfo=timezone.utc), ) @@ -229,7 +233,7 @@ def run(*, store=None, **overrides): def test_live_sell_release_uses_real_order_status_execution_fields( monkeypatch, execution_fields, expected_buy_quantity, ): - import application.rebalance_service as module + import firstrade_platform.application.rebalance_service as module class OrderReadClient(FakeFirstradeClient): get_orders = FirstradeBrokerClient.get_orders @@ -313,7 +317,7 @@ def test_live_submission_requires_enabled_persistence_and_store(live_cycle, pers def test_live_noop_without_persistence_does_not_acquire_claim(live_cycle, monkeypatch): run, client = live_cycle monkeypatch.setattr( - "application.rebalance_service.map_strategy_decision_to_plan", + "firstrade_platform.application.rebalance_service.map_strategy_decision_to_plan", lambda *_args, **_kwargs: { "allocation": {"targets": {}}, "portfolio": {}, @@ -332,7 +336,7 @@ def test_dry_run_without_persistence_only_previews(live_cycle, monkeypatch): def unexpected_claim(**_kwargs): pytest.fail("dry-run must not acquire a live claim") - monkeypatch.setattr("application.rebalance_service.claim_live_strategy_run", unexpected_claim) + monkeypatch.setattr("firstrade_platform.application.rebalance_service.claim_live_strategy_run", unexpected_claim) result = run(dry_run_only=True, persist_strategy_runs=False) assert result["strategy_run_stage"] == "DRY_RUN_COMPLETED" assert client.orders @@ -448,7 +452,7 @@ def fake_client_factory(*args, **kwargs): return client monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) @@ -499,7 +503,7 @@ def test_runtime_target_requires_exactly_one_account_selector_before_connect( ): factory_calls = [] monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: pytest.fail("strategy must not load"), ) @@ -566,7 +570,7 @@ def test_runtime_target_native_account_mismatch_stops_before_strategy_and_snapsh observed = {} strategy_calls = [] monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: strategy_calls.append(True), ) @@ -606,7 +610,7 @@ def client_factory(*args, **kwargs): def test_runtime_target_selects_exact_account_before_strategy_and_snapshot(monkeypatch): observed = {} monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) @@ -648,11 +652,11 @@ def test_unsupported_strategy_returns_before_runtime_account_validation( ): client_factory_calls = [] monkeypatch.setattr( - "application.rebalance_service.dca_execution_unsupported_reason", + "firstrade_platform.application.rebalance_service.dca_execution_unsupported_reason", lambda _profile: "Synthetic unsupported strategy", ) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: pytest.fail("strategy must not load"), ) @@ -702,15 +706,15 @@ def place_stock_order(self, request, dry_run=True, explicit_live_ack=False): store = FakeStateStore() messages = [] monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: IbitRuntime(), ) monkeypatch.setattr( - "application.rebalance_service.notional_buy_execution_enabled", + "firstrade_platform.application.rebalance_service.notional_buy_execution_enabled", lambda _profile: True, ) monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 7, 27, 19, 45, tzinfo=timezone.utc), ) @@ -803,7 +807,7 @@ def evaluate(self, **inputs): ) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: WeightTargetRuntime(), ) @@ -847,7 +851,7 @@ def evaluate(self, **inputs): ) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: WeightTargetRuntime(), ) @@ -918,7 +922,7 @@ def test_run_strategy_cycle_loads_strategy_plugin_report_and_sends_email( observed_alerts = [] monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) @@ -947,7 +951,7 @@ def fake_dispatch(signals, **kwargs): }, ) - monkeypatch.setattr("application.rebalance_service.dispatch_strategy_plugin_alerts", fake_dispatch) + monkeypatch.setattr("firstrade_platform.application.rebalance_service.dispatch_strategy_plugin_alerts", fake_dispatch) result = run_strategy_cycle( runtime_settings=settings, @@ -977,7 +981,7 @@ def test_run_strategy_cycle_strategy_plugin_load_error_is_non_blocking(monkeypat settings = _runtime_settings_with_persistence(strategy_plugin_mounts_json="{bad-json") monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) @@ -1010,11 +1014,11 @@ def test_run_strategy_cycle_dry_run_preserves_live_strategy_run_state(monkeypatc store.payloads[key] = dict(existing_state) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 5, 15, tzinfo=timezone.utc), ) @@ -1061,11 +1065,11 @@ def fake_client_factory(*args, **kwargs): return client monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 5, 15, tzinfo=timezone.utc), ) @@ -1115,11 +1119,11 @@ def fake_client_factory(*args, **kwargs): return client monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 5, 15, tzinfo=timezone.utc), ) @@ -1159,7 +1163,7 @@ def test_run_strategy_cycle_persists_live_execution_blocked_without_terminal_sta ) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FakeStrategyRuntime(), ) @@ -1219,7 +1223,7 @@ def evaluate(self, **inputs): ) monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: FundingBlockedRuntime(), ) @@ -1315,7 +1319,7 @@ def test_run_strategy_cycle_persists_live_partial_submission_as_non_terminal(mon } messages = [] monkeypatch.setattr( - "application.rebalance_service._utcnow", + "firstrade_platform.application.rebalance_service._utcnow", lambda: datetime(2026, 5, 15, tzinfo=timezone.utc), ) settings = _runtime_settings_with_persistence( @@ -1353,7 +1357,7 @@ def get_quote(self, _account, symbol): return {"symbol": symbol, "last": prices[symbol], "bid": "9.90", "ask": "10.10"} monkeypatch.setattr( - "application.rebalance_service.load_strategy_runtime", + "firstrade_platform.application.rebalance_service.load_strategy_runtime", lambda *_args, **_kwargs: PartialRuntime(), ) @@ -1683,7 +1687,7 @@ def test_render_cycle_summary_shows_retryable_execution_blocked_banner(): {"ok": True, "dry_run_only": True, "action_done": True, "submitted_orders": [{"status": "preview"}]}, ]) def test_cycle_notification_quiets_only_verified_success_and_dry_run_preview(result): - from application.rebalance_service import _should_publish_cycle_notification + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification assert not _should_publish_cycle_notification(result) @@ -1704,7 +1708,7 @@ def test_cycle_notification_quiets_only_verified_success_and_dry_run_preview(res {"pending_reconciliation": True}, ]) def test_cycle_notification_preserves_zero_order_attention(change): - from application.rebalance_service import _should_publish_cycle_notification + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification result = {"ok": True, "dry_run_only": False, "submitted_orders": [], **change} before = json.loads(json.dumps(result)) @@ -1713,7 +1717,7 @@ def test_cycle_notification_preserves_zero_order_attention(change): def test_cycle_notification_preserves_real_submission_and_existing_repeat_funding_policy(): - from application.rebalance_service import _should_publish_cycle_notification + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification assert _should_publish_cycle_notification({ "ok": True, "dry_run_only": False, @@ -1744,7 +1748,7 @@ def test_cycle_notification_preserves_real_submission_and_existing_repeat_fundin {"execution_status": "pending_reconciliation"}, ]) def test_repeat_funding_suppression_keeps_independent_new_attention(attention): - from application.rebalance_service import _should_publish_cycle_notification + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification result = { "ok": False, "error": "Strategy execution blocked; see execution_blocking_skips.", @@ -1758,7 +1762,7 @@ def test_repeat_funding_suppression_keeps_independent_new_attention(attention): def test_unrecognized_suppression_policy_keeps_existing_authority(): - from application.rebalance_service import _should_publish_cycle_notification + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification for change in ( {"strategy_plugin_error": "synthetic_error"}, @@ -1773,8 +1777,8 @@ def test_unrecognized_suppression_policy_keeps_existing_authority(): def test_native_repeat_funding_result_keeps_late_persistence_error(live_cycle, monkeypatch): - from application.execution_service import ExecutionCycleResult - from application.rebalance_service import _should_publish_cycle_notification, persist_strategy_run_state + from firstrade_platform.application.execution_service import ExecutionCycleResult + from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification, persist_strategy_run_state run, _client = live_cycle store = FakeStateStore() @@ -1783,7 +1787,7 @@ def test_native_repeat_funding_result_keeps_late_persistence_error(live_cycle, m "dry_run_only": False, } monkeypatch.setattr( - "application.rebalance_service.execute_value_target_plan", + "firstrade_platform.application.rebalance_service.execute_value_target_plan", lambda **_kwargs: ExecutionCycleResult( submitted_orders=(), skipped_orders=({"reason": "insufficient_cash_for_whole_share"},), action_done=False, @@ -1793,7 +1797,7 @@ def fail_final_funding_persistence(*, store, state, storage_account, now): if state["stage"] == "FUNDING_BLOCKED": raise RuntimeError("synthetic_final_persistence_failure") return persist_strategy_run_state(store=store, state=state, storage_account=storage_account, now=now) - monkeypatch.setattr("application.rebalance_service.persist_strategy_run_state", fail_final_funding_persistence) + monkeypatch.setattr("firstrade_platform.application.rebalance_service.persist_strategy_run_state", fail_final_funding_persistence) result = run(store=store) assert result["submitted_orders"] == [] @@ -1804,7 +1808,7 @@ def fail_final_funding_persistence(*, store, state, storage_account, now): def test_preexisting_submission_claim_still_blocks_after_display_redaction(live_cycle): - from application.strategy_run_persistence import LIVE_SUBMISSION_CLAIM_BOUNDARY + from firstrade_platform.application.strategy_run_persistence import LIVE_SUBMISSION_CLAIM_BOUNDARY run, client = live_cycle key = "strategy-runs/claims/____5678/tqqq_growth_income/2026_09.json" diff --git a/tests/test_request_handling.py b/tests/test_request_handling.py index a0914468..b4ab67c2 100644 --- a/tests/test_request_handling.py +++ b/tests/test_request_handling.py @@ -6,7 +6,7 @@ pytest.importorskip("flask") -import main +from firstrade_platform import main @pytest.fixture(autouse=True) @@ -16,8 +16,8 @@ def _assume_market_open_for_http_tests(monkeypatch, request): "platform_id": "firstrade", "strategy_profile": "ibit_smart_dca", "dry_run_only": False, })) monkeypatch.setattr(main, "get_project_id", lambda: "test-project") - monkeypatch.setattr("runtime_config_support._get_credential", lambda *_args: None) - monkeypatch.setattr("runtime_config_support._read_secret", lambda *_args: None) + monkeypatch.setattr("firstrade_platform.runtime_config_support._get_credential", lambda *_args: None) + monkeypatch.setattr("firstrade_platform.runtime_config_support._read_secret", lambda *_args: None) if request.node.name == "test_run_endpoint_skips_when_market_closed": return monkeypatch.setattr(main, "_should_skip_for_market_hours", lambda: (False, None)) diff --git a/tests/test_runtime_broker_adapters.py b/tests/test_runtime_broker_adapters.py index aebb2c7b..40a6483e 100644 --- a/tests/test_runtime_broker_adapters.py +++ b/tests/test_runtime_broker_adapters.py @@ -4,7 +4,7 @@ import pytest -from application.runtime_broker_adapters import build_runtime_broker_adapters +from firstrade_platform.application.runtime_broker_adapters import build_runtime_broker_adapters def _timestamp_ms(value: datetime) -> int: diff --git a/tests/test_runtime_config_support.py b/tests/test_runtime_config_support.py index 9bafab36..8c74b647 100644 --- a/tests/test_runtime_config_support.py +++ b/tests/test_runtime_config_support.py @@ -4,7 +4,7 @@ import pytest -from runtime_config_support import ( +from firstrade_platform.runtime_config_support import ( _default_market_signal_handoff_index_uri_from_report_bucket, _resolve_market_signal_fallback_mode, _resolve_market_signal_handoff_index_uri, diff --git a/tests/test_runtime_execution_policy.py b/tests/test_runtime_execution_policy.py index f0b912ad..e3f7830a 100644 --- a/tests/test_runtime_execution_policy.py +++ b/tests/test_runtime_execution_policy.py @@ -19,11 +19,9 @@ ) ROOT = __import__("pathlib").Path(__file__).resolve().parents[1] -QPK_SRC = ROOT.parent / "QuantPlatformKit" / "src" -if str(QPK_SRC) not in sys.path: - sys.path.insert(0, str(QPK_SRC)) -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) +SRC = ROOT / "src" +if str(SRC) not in sys.path: + sys.path.insert(0, str(SRC)) _DCA_DEFINITIONS = { "nasdaq_sp500_smart_dca": StrategyDefinition( @@ -71,17 +69,21 @@ ) _FAKE_CATALOG = StrategyCatalog(definitions=_DCA_DEFINITIONS) -_fake_registry = types.ModuleType("strategy_registry") +_fake_registry = types.ModuleType("firstrade_platform.strategy_registry") _fake_registry.PLATFORM_CAPABILITY_MATRIX = _FIRSTRADE_CAPABILITY_MATRIX _fake_registry.STRATEGY_CATALOG = _FAKE_CATALOG @pytest.fixture def notional_buy_fn(monkeypatch: pytest.MonkeyPatch): - monkeypatch.setitem(sys.modules, "strategy_registry", _fake_registry) - rep = importlib.import_module("runtime_execution_policy") + monkeypatch.setitem(sys.modules, "firstrade_platform.strategy_registry", _fake_registry) + rep = importlib.import_module("firstrade_platform.runtime_execution_policy") rep = importlib.reload(rep) - return rep.notional_buy_execution_enabled + try: + yield rep.notional_buy_execution_enabled + finally: + monkeypatch.undo() + importlib.reload(rep) @pytest.mark.parametrize( diff --git a/tests/test_runtime_notification_i18n.py b/tests/test_runtime_notification_i18n.py index 8b46bd55..ea6bb0b8 100644 --- a/tests/test_runtime_notification_i18n.py +++ b/tests/test_runtime_notification_i18n.py @@ -5,7 +5,7 @@ import pytest -from notifications.telegram import build_translator +from firstrade_platform.notifications.telegram import build_translator @pytest.mark.parametrize("locale", ["zh-CN", "zh_TW", "ZH-hans", " zh "]) @@ -14,7 +14,8 @@ def test_chinese_locale_variants_use_chinese(locale): def runtime_function(name, **overrides): - tree = ast.parse((Path(__file__).resolve().parents[1] / "main.py").read_text()) + main_path = Path(__file__).resolve().parents[1] / "src" / "firstrade_platform" / "main.py" + tree = ast.parse(main_path.read_text()) function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == name) namespace = dict(os=os, request=SimpleNamespace(method="GET", path="/main"), NOTIFY_LANG="zh-CN", SERVICE_NAME="Test service", SECRET_NAME="Test secret alias", @@ -23,7 +24,7 @@ def runtime_function(name, **overrides): t=build_translator("zh-CN")) namespace["_safe_exception_text"] = lambda exc, **kwargs: str(exc) namespace.update(overrides) - exec(compile(ast.Module(body=[function], type_ignores=[]), "main.py", "exec"), namespace) + exec(compile(ast.Module(body=[function], type_ignores=[]), str(main_path), "exec"), namespace) return namespace[name] diff --git a/tests/test_sender_receipt_identity.py b/tests/test_sender_receipt_identity.py index 78f06caf..5d8fa4be 100644 --- a/tests/test_sender_receipt_identity.py +++ b/tests/test_sender_receipt_identity.py @@ -5,9 +5,9 @@ import pytest -from notifications import unified +from firstrade_platform.notifications import unified from quant_platform_kit.notifications.unified_contract import order_identity_digest -from notifications.telegram import build_sender +from firstrade_platform.notifications.telegram import build_sender from test_notification_consolidation import ENV, NOW, TARGET, Store, source CASES = ["boolean", "boolean_false", "missing", "null", "empty", "blank", "negative_ack", "transport_ack", diff --git a/tests/test_session_check_service.py b/tests/test_session_check_service.py index c028d0cf..9f6a7939 100644 --- a/tests/test_session_check_service.py +++ b/tests/test_session_check_service.py @@ -2,8 +2,8 @@ from datetime import datetime, timezone -from application.firstrade_client import FirstradeCredentials -from application.session_check_service import build_account_funds_snapshot, run_session_check +from firstrade_platform.application.firstrade_client import FirstradeCredentials +from firstrade_platform.application.session_check_service import build_account_funds_snapshot, run_session_check class FakeClient: diff --git a/tests/test_session_renew_auth_logging.py b/tests/test_session_renew_auth_logging.py index a79196f3..464c59ba 100644 --- a/tests/test_session_renew_auth_logging.py +++ b/tests/test_session_renew_auth_logging.py @@ -11,13 +11,13 @@ from firstrade.account import FTSession from firstrade.exceptions import AccountResponseError, LoginResponseError -from application.firstrade_client import ( +from firstrade_platform.application.firstrade_client import ( FirstradeBrokerClient, FirstradeCredentials, FirstradeMfaRequired, FirstradeSafetyError, ) -from application.session_check_service import run_forced_session_renewal +from firstrade_platform.application.session_check_service import run_forced_session_renewal @pytest.mark.parametrize("failure_stage", ["login", "seed_verify", "code_verify", "account_read"]) @@ -25,7 +25,7 @@ def test_renewal_route_contains_exceptions_without_logging_secrets( tmp_path, monkeypatch, caplog, capsys, failure_stage, error_kind, ): - import main + from firstrade_platform import main # Exercise Flask's production error handling and the pinned SDK with synthetic data only. private = ("synthetic-account-private", "246802", "A" * 32, diff --git a/tests/test_signal_snapshot.py b/tests/test_signal_snapshot.py index cbb297ca..46688cd4 100644 --- a/tests/test_signal_snapshot.py +++ b/tests/test_signal_snapshot.py @@ -1,4 +1,4 @@ -from application.signal_snapshot import build_signal_snapshot +from firstrade_platform.application.signal_snapshot import build_signal_snapshot def test_includes_soxl_dynamic_volatility_fields(): diff --git a/tests/test_state_error_redaction.py b/tests/test_state_error_redaction.py index c47f45db..b18dddc2 100644 --- a/tests/test_state_error_redaction.py +++ b/tests/test_state_error_redaction.py @@ -4,7 +4,7 @@ import pytest -from application import state_persistence as state +from firstrade_platform.application import state_persistence as state @pytest.mark.parametrize("operation", ["read_json", "write_json", "create_json"]) diff --git a/tests/test_statement_reconciliation.py b/tests/test_statement_reconciliation.py index 0d7d0e05..5d789a34 100644 --- a/tests/test_statement_reconciliation.py +++ b/tests/test_statement_reconciliation.py @@ -5,12 +5,12 @@ import pytest -from application.firstrade_fee_schedule import ( +from firstrade_platform.application.firstrade_fee_schedule import ( DEFAULT_FEE_SCHEDULE_CONFIG, FeeScheduleError, load_fee_schedule, ) -from application.statement_reconciliation import ( +from firstrade_platform.application.statement_reconciliation import ( decompose_sell_fees, valuation_basis_difference, valuation_basis_report, diff --git a/tests/test_strategy_registry.py b/tests/test_strategy_registry.py index 6fa7009e..6ee7fc1f 100644 --- a/tests/test_strategy_registry.py +++ b/tests/test_strategy_registry.py @@ -1,7 +1,7 @@ from __future__ import annotations -from strategy_loader import load_strategy_runtime_adapter_for_profile -from strategy_registry import ( +from firstrade_platform.strategy_loader import load_strategy_runtime_adapter_for_profile +from firstrade_platform.strategy_registry import ( FIRSTRADE_PLATFORM, get_platform_profile_status_matrix, get_supported_profiles_for_platform, diff --git a/tests/test_strategy_run_claim.py b/tests/test_strategy_run_claim.py index 9e2353b0..14c5dbb3 100644 --- a/tests/test_strategy_run_claim.py +++ b/tests/test_strategy_run_claim.py @@ -1,10 +1,10 @@ -from application.strategy_run_persistence import ( +from firstrade_platform.application.strategy_run_persistence import ( claim_live_strategy_run, has_effective_live_submission_claim, read_live_strategy_run_claim, strategy_run_claim_key, ) -from application.state_persistence import GcsStateStore +from firstrade_platform.application.state_persistence import GcsStateStore class AtomicFakeStore: diff --git a/tests/test_strategy_runtime.py b/tests/test_strategy_runtime.py index 4ee58934..f1df37e9 100644 --- a/tests/test_strategy_runtime.py +++ b/tests/test_strategy_runtime.py @@ -1,7 +1,7 @@ from __future__ import annotations -from runtime_config_support import PlatformRuntimeSettings -from strategy_runtime import _build_runtime_overrides +from firstrade_platform.runtime_config_support import PlatformRuntimeSettings +from firstrade_platform.strategy_runtime import _build_runtime_overrides def _runtime_settings(**overrides) -> PlatformRuntimeSettings: @@ -118,7 +118,7 @@ def test_stamp_portfolio_risk_metadata_calls_qpk_helper(monkeypatch): StrategyManifest, StrategyRuntimeAdapter, ) - import strategy_runtime as strategy_runtime_module + import firstrade_platform.strategy_runtime as strategy_runtime_module class _Entrypoint: manifest = StrategyManifest( diff --git a/tests/test_telegram_token_resolution.py b/tests/test_telegram_token_resolution.py index 96280dce..d3736dc9 100644 --- a/tests/test_telegram_token_resolution.py +++ b/tests/test_telegram_token_resolution.py @@ -2,8 +2,8 @@ import pytest -import runtime_config_support -from runtime_config_support import LEGACY_TELEGRAM_TOKEN_SECRET_NAME, resolve_telegram_token +import firstrade_platform.runtime_config_support as runtime_config_support +from firstrade_platform.runtime_config_support import LEGACY_TELEGRAM_TOKEN_SECRET_NAME, resolve_telegram_token UNIFIED = "quant-sentinel-telegram-bot-token" @@ -52,7 +52,7 @@ def test_missing_everywhere_returns_none(): def test_main_get_telegram_token_prefers_injected(monkeypatch): pytest.importorskip("flask") - import main + from firstrade_platform import main seen = [] monkeypatch.setattr(runtime_config_support, "_read_secret", lambda name: seen.append(name) or "legacy") @@ -63,7 +63,7 @@ def test_main_get_telegram_token_prefers_injected(monkeypatch): def test_main_get_telegram_token_uses_configured_secret(monkeypatch): pytest.importorskip("flask") - import main + from firstrade_platform import main values = {UNIFIED: "unified", LEGACY_TELEGRAM_TOKEN_SECRET_NAME: "legacy"} monkeypatch.setattr(runtime_config_support, "_read_secret", lambda name: values.get(name)) diff --git a/tests/test_unified_notification_wiring.py b/tests/test_unified_notification_wiring.py index 16f1693b..5560e118 100644 --- a/tests/test_unified_notification_wiring.py +++ b/tests/test_unified_notification_wiring.py @@ -1,7 +1,7 @@ from types import SimpleNamespace from copy import deepcopy -from application.rebalance_service import _should_publish_cycle_notification +from firstrade_platform.application.rebalance_service import _should_publish_cycle_notification def test_confirmed_routine_orders_defer_and_failures_stay_live(monkeypatch): diff --git a/tests/test_value_target_facade_parity.py b/tests/test_value_target_facade_parity.py index dae8de82..e3721f63 100644 --- a/tests/test_value_target_facade_parity.py +++ b/tests/test_value_target_facade_parity.py @@ -6,7 +6,7 @@ import pytest -import decision_mapper +import firstrade_platform.decision_mapper as decision_mapper from value_target_parity_cases import GOLDEN_PATH, build_cases, canonical _GOLDEN = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) diff --git a/tests/value_target_parity_cases.py b/tests/value_target_parity_cases.py index e7fb41c5..ab1fd81c 100644 --- a/tests/value_target_parity_cases.py +++ b/tests/value_target_parity_cases.py @@ -299,7 +299,7 @@ def _default(value: Any) -> Any: def render_all() -> dict[str, Any]: - from decision_mapper import map_strategy_decision_to_plan + from firstrade_platform.decision_mapper import map_strategy_decision_to_plan return { name: canonical(map_strategy_decision_to_plan(**kwargs)) @@ -308,7 +308,7 @@ def render_all() -> dict[str, Any]: if __name__ == "__main__": - sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) rendered = render_all() text = json.dumps(rendered, indent=2, sort_keys=True) + "\n" if "--write" in sys.argv: diff --git a/uv.lock b/uv.lock index 79ba48d8..2937b4a2 100644 --- a/uv.lock +++ b/uv.lock @@ -418,7 +418,6 @@ dependencies = [ { name = "google-cloud-storage" }, { name = "gunicorn" }, { name = "pandas-market-calendars" }, - { name = "pytest" }, { name = "pytz" }, { name = "quant-platform-kit" }, { name = "requests" }, @@ -442,7 +441,6 @@ requires-dist = [ { name = "google-cloud-storage" }, { name = "gunicorn" }, { name = "pandas-market-calendars" }, - { name = "pytest" }, { name = "pytest", marker = "extra == 'test'" }, { name = "pytest-cov", marker = "extra == 'test'" }, { name = "pytz" },