From 4cd603806333550523bb42f3b5c71d3ac0dc2e90 Mon Sep 17 00:00:00 2001 From: Boki Date: Fri, 27 Nov 2026 00:11:50 -0500 Subject: [PATCH] refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack - Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs --- .env | 35 +- .env.dev.example | 11 +- .env.qa.example | 11 +- README.md | 48 +- apps/stock/analytics/.gitignore | 2 - apps/stock/analytics/main.py | 38 - apps/stock/analytics/requirements.txt | 18 - .../src/analysis/statistical_validation.py | 410 --- .../analytics/src/analytics/performance.py | 217 -- apps/stock/analytics/src/analytics/regime.py | 284 -- apps/stock/analytics/src/api/app.py | 63 - apps/stock/analytics/src/api/capabilities.py | 88 - .../analytics/src/api/endpoints/analytics.py | 72 - .../analytics/src/api/endpoints/models.py | 211 -- .../src/api/endpoints/optimization.py | 120 - .../analytics/src/ml/feature_engineering.py | 481 ---- .../src/optimization/portfolio_optimizer.py | 354 --- .../analytics/test/test_app_composition.py | 205 -- .../test/test_unavailable_endpoints.py | 55 - apps/stock/config/config/development.json | 2 +- apps/stock/config/package.json | 4 + apps/stock/config/src/env-safety.ts | 8 +- .../scripts/check-intraday-status.ts | 66 - .../data-ingestion/scripts/trigger-job.ts | 31 - .../src/handlers/eod/shared/types.ts | 0 .../src/handlers/qm/shared/index.ts | 4 - .../src/handlers/te/shared/index.ts | 3 - .../src/handlers/tradingview/shared/index.ts | 2 - .../src/handlers/webshare/shared/config.ts | 10 - apps/stock/data-ingestion/src/index.ts | 21 +- apps/stock/data-ingestion/src/routes/index.ts | 6 - .../src/routes/market-data.routes.ts | 147 - .../src/types/exchange.types.ts | 40 - .../data-ingestion/src/types/job-payloads.ts | 93 - .../test/test-advanced-rate-limit.ts | 99 - .../data-ingestion/test/test-intraday-flow.ts | 163 -- .../test/test-modified-functions.ts | 139 - .../data-ingestion/test/test-qm-operations.ts | 163 -- .../data-ingestion/test/test-symbol-x.ts | 122 - apps/stock/data-pipeline/package.json | 2 +- .../data-pipeline/scripts/phase1-inventory.ts | 528 ---- .../handlers/exchanges/exchanges.handler.ts | 10 - .../enhanced-sync-status.operations.ts | 29 - .../handlers/exchanges/operations/index.ts | 19 - .../src/handlers/symbols/operations/index.ts | 9 - apps/stock/data-pipeline/src/index.ts | 2 +- .../data-pipeline/src/routes/create-routes.ts | 18 +- .../src/routes/enhanced-sync.routes.ts | 161 -- apps/stock/data-pipeline/src/routes/index.ts | 5 - .../data-pipeline/src/routes/stats.routes.ts | 60 - .../data-pipeline/src/routes/sync.routes.ts | 92 - apps/stock/engine/MIGRATION.md | 3 +- apps/stock/engine/bun.lock | 17 - apps/stock/engine/package.json | 7 +- .../reference/legacy-reporting/README.md | 7 - .../legacy-reporting/metrics_calculator.rs | 669 ----- .../reference/legacy-reporting/results.rs | 266 -- apps/stock/engine/src/analytics/mod.rs | 8 +- .../engine/src/analytics/transaction_costs.rs | 355 --- .../engine/src/strategies/mean_reversion.rs | 210 -- apps/stock/engine/src/strategies/mod.rs | 2 - .../examples/advanced-risk-management.ts | 278 -- .../examples/canonical-regime-research.ts | 2 +- .../examples/debug-position-tracking.ts | 93 - .../examples/debug-rust-short-trades.ts | 130 - .../orchestrator/examples/example-runtime.ts | 70 - .../examples/force-both-trade-types.ts | 138 - .../orchestrator/examples/indicator-usage.ts | 238 -- .../examples/multi-strategy-backtest.ts | 39 - .../orchestrator/examples/show-order-flow.ts | 75 - .../examples/simple-backtest-test.ts | 92 - .../examples/test-backtest-trades.ts | 84 - .../examples/test-engine-import.ts | 32 - .../examples/test-short-trades.ts | 84 - .../examples/trace-short-positions.ts | 139 - .../examples/verify-both-trade-types.ts | 115 - apps/stock/orchestrator/package.json | 36 +- .../src/analytics/PerformanceAnalyzer.ts | 172 -- .../orchestrator/src/api/rest/analytics.ts | 67 - .../stock/orchestrator/src/api/rest/orders.ts | 140 - .../src/api/rest/paper-deployments.ts | 8 +- apps/stock/orchestrator/src/api/rest/paper.ts | 10 +- .../orchestrator/src/api/rest/positions.ts | 150 - .../orchestrator/src/api/websocket/index.ts | 198 -- .../src/backtest/BacktestEngine.ts | 181 -- .../src/backtest/BacktestMarket.ts | 128 - .../src/backtest/BacktestPlayback.ts | 181 -- .../src/backtest/BacktestReport.ts | 230 -- .../src/backtest/MarketSimulator.ts | 423 --- .../src/backtest/NativeBacktestWorker.ts | 4 +- .../src/backtest/candidate-host.ts | 2 +- .../src/backtest/candidate-protocol.ts | 2 +- .../src/backtest/candidate-sandbox.ts | 2 +- .../src/backtest/canonical-build.ts | 2 - .../src/backtest/canonical-result.ts | 2 - .../src/backtest/execution-engine.ts | 16 - .../src/backtest/native-replay.ts | 4 +- .../src/backtest/native-strategies.ts | 12 - .../src/backtest/native-worker-protocol.ts | 6 +- .../src/backtest/native-worker.ts | 4 +- .../src/backtest/report-format.ts | 121 - .../stock/orchestrator/src/backtest/result.ts | 200 -- .../src/backtest/strategy-plan.ts | 55 - .../src/backtest/strategy-runtime.ts | 6 +- .../src/backtest/typescript-result.ts | 86 - apps/stock/orchestrator/src/container.ts | 9 +- .../orchestrator/src/contracts/analytics.ts | 149 - .../src/contracts/builtin-strategy.ts | 10 - .../src/contracts/canonical-execution.ts | 2 - .../src/contracts/canonical-strategy.ts | 9 - .../src/contracts/native-replay.ts | 2 - .../src/contracts/paper-runtime.ts | 2 - .../orchestrator/src/contracts/strategies.ts | 106 - .../src/contracts/strategy-names.ts | 6 - .../src/contracts/strategy-replay.ts | 4 +- .../orchestrator/src/core/ModeManager.ts | 221 -- .../orchestrator/src/data/DataManager.ts | 307 -- .../src/data/historical-dataset.ts | 4 +- .../orchestrator/src/data/preparation.ts | 2 - .../src/data/retained-research-dataset.ts | 2 - .../execution/BacktestExecutionRepository.ts | 294 -- .../src/execution/CanonicalPaperExecution.ts | 8 +- .../PostgresCanonicalExecutionRepository.ts | 2 +- .../execution/PostgresExecutionRepository.ts | 213 -- .../src/execution/SimulationExecution.ts | 215 -- .../src/execution/StrategyRecovery.ts | 288 -- .../src/execution/canonical-paper.ts | 9 +- .../stock/orchestrator/src/execution/model.ts | 268 -- .../orchestrator/src/execution/repository.ts | 31 - .../src/execution/strategy-recovery.ts | 49 - apps/stock/orchestrator/src/index.ts | 2 +- .../src/indicators/TechnicalAnalysis.ts | 342 --- .../src/paper/CanonicalPaperRuntime.ts | 4 +- .../src/paper/PaperDeploymentHost.ts | 6 +- .../src/paper/PaperTradingManager.ts | 60 - apps/stock/orchestrator/src/paper/feed.ts | 4 +- .../src/paper/paper-deployment-custody.ts | 2 - .../src/paper/paper-host-identity.ts | 2 - .../orchestrator/src/paper/paper-host.ts | 4 +- .../orchestrator/src/paper/paper-operator.ts | 2 - .../orchestrator/src/routes/create-routes.ts | 7 +- .../src/services/AnalyticsService.ts | 197 -- .../src/services/ExecutionService.ts | 436 --- .../src/services/MarketDataService.ts | 229 -- .../src/services/StorageService.ts | 2 - .../src/services/analytics-error.ts | 14 - .../orchestrator/src/simple-container.ts | 2 +- .../src/strategies/BaseStrategy.ts | 384 --- .../src/strategies/StrategyManager.ts | 238 -- .../src/strategies/StrategyRegistry.ts | 43 - .../src/strategies/builtin-strategies.ts | 19 - .../builtin/MeanReversionStrategy.ts | 234 -- .../builtin/SmaCrossoverStrategy.ts | 310 -- .../src/strategies/canonical-builtins.ts | 6 +- .../strategies/canonical-mean-reversion.ts | 4 +- .../src/strategies/canonical-sma.ts | 4 +- .../src/strategies/checkpoint-schemas.ts | 15 - .../experimental/MLEnhancedStrategy.ts | 472 --- .../src/strategies/retained-program.ts | 2 +- .../src/strategies/strategy-config.ts | 12 - .../src/strategies/strategy-controller.ts | 4 +- .../src/strategies/strategy-decision.ts | 4 +- apps/stock/orchestrator/src/types.ts | 66 +- .../src/types/MarketMicrostructure.ts | 29 - .../orchestrator/tests/indicators.test.ts | 199 -- apps/stock/package.json | 73 - apps/stock/scripts/health-check.js | 60 - apps/stock/tsconfig.json | 19 - apps/stock/web-api/package.json | 2 +- apps/stock/web-api/src/container-setup.ts | 34 - .../src/migrations/migration-runner.ts | 97 +- apps/stock/web-api/src/routes/index.ts | 5 - apps/stock/web-api/src/types.ts | 25 - apps/stock/web-app/package.json | 3 - .../web-app/src/components/charts/index.ts | 2 - apps/stock/web-app/src/components/index.ts | 2 - .../src/components/ui/DataTable/types.ts | 66 - .../backtest/components/BacktestMetrics.tsx | 144 - .../backtest/components/MetricsCard.tsx | 38 - .../backtest/components/RunControls.tsx | 196 -- .../src/features/backtest/components/index.ts | 11 - .../src/features/charts/components/index.ts | 6 - .../src/features/charts/hooks/index.ts | 1 - .../src/features/charts/hooks/useChartData.ts | 150 - .../web-app/src/features/charts/index.ts | 3 - .../charts/services/chartDataService.ts | 241 -- .../src/features/exchanges/types/api.types.ts | 69 - .../exchanges/types/component.types.ts | 45 - .../features/exchanges/types/request.types.ts | 35 - .../src/features/symbols/components/index.ts | 3 - apps/stock/web-app/src/lib/utils/cn.ts | 6 - apps/stock/web-app/src/lib/utils/index.ts | 59 - database/mongodb/init/01-init-collections.js | 234 -- database/postgres/init/01-init-database.sql | 16 +- database/postgres/init/02-master-schema.sql | 2 - database/postgres/init/03-initial-data.sql | 1 - .../04-provider-exchange-mapping-schema.sql | 20 +- .../postgres/init/05-add-visible-column.sql | 5 +- docker-compose.dev.yml | 42 +- docker-compose.prod.yml | 51 +- docker-compose.quant.yml | 60 + docker-compose.yml | 90 +- docs/DATA-CONTRACTS.md | 19 +- docs/MILESTONES.md | 15 +- docs/PLATFORM-PLAN.md | 9 +- docs/README.md | 1 - docs/cleanup-audit.md | 50 - docs/data-pipeline/phase1-investigation.md | 4 +- docs/development/QUALITY-GATES.md | 4 +- .../architecture/decisions/001-ownership.md | 2 +- .../decisions/002-financial-policy.md | 2 +- .../decisions/003-time-and-datasets.md | 2 +- .../decisions/005-durable-cutover.md | 2 +- .../architecture/decisions/007-ai-boundary.md | 2 +- docs/development/architecture/overview.md | 2 +- docs/guide/backtest-walkthrough.md | 2 +- docs/guide/strategy-development.md | 4 +- docs/guide/system-map.md | 4 +- docs/servers.md | 16 +- knip.json | 4 - libs/LIBRARY_STANDARDS.md | 157 - libs/calculations/README.md | 35 +- libs/calculations/migration-audit.json | 408 --- libs/calculations/package.json | 3 +- libs/calculations/research/README.md | 26 - .../research/correlation-analysis.md | 1281 --------- .../research/market-statistics.md | 1038 ------- libs/calculations/research/options-pricing.md | 822 ------ .../research/portfolio-analytics.md | 604 ---- .../research/position-sizing-notes.md | 109 - libs/calculations/research/position-sizing.md | 593 ---- .../research/technical-indicators.md | 2520 ----------------- .../research/volatility-models.md | 633 ----- .../src/legacy/basic-calculations.ts | 454 --- libs/calculations/src/legacy/index.ts | 5 - .../src/legacy/performance-metrics.ts | 941 ------ libs/calculations/src/legacy/risk-metrics.ts | 482 ---- .../src/legacy/technical-indicators.ts | 1340 --------- libs/calculations/test/preservation.test.ts | 55 - libs/core/cache/src/key-generator.ts | 83 - libs/core/cache/src/namespaced-cache.ts | 2 +- libs/core/cache/test/cache.test.ts | 23 - libs/core/cache/test/key-generator.test.ts | 220 -- libs/core/cache/test/namespaced-cache.test.ts | 6 +- libs/core/config/.env.example | 50 - libs/core/config/config/default.json | 94 - libs/core/config/config/development.json | 48 - libs/core/config/config/production.json | 32 - libs/core/config/config/test.json | 42 - libs/core/config/package.json | 8 +- libs/core/config/src/cli.ts | 175 -- libs/core/config/src/config-manager.ts | 67 +- libs/core/config/src/index.ts | 36 +- libs/core/config/src/loaders/env.loader.ts | 90 +- libs/core/config/src/utils/secrets.ts | 178 -- libs/core/config/src/utils/validation.ts | 155 - libs/core/config/test/utils.test.ts | 518 ---- libs/core/di/package.json | 16 +- libs/core/di/src/awilix-container.ts | 7 - libs/core/di/src/container/builder.ts | 35 +- libs/core/di/src/container/types.ts | 9 +- libs/core/di/src/factories/index.ts | 1 - libs/core/di/src/index.ts | 6 +- libs/core/di/src/operation-context.ts | 144 - libs/core/di/src/pool-size-calculator.ts | 102 - .../src/registrations/service.registration.ts | 57 +- libs/core/di/src/service-application.ts | 95 +- libs/core/di/src/types.ts | 71 - libs/core/di/src/utils/lifecycle.ts | 1 + libs/core/di/test/awilix-container.test.ts | 76 - libs/core/di/test/container-builder.test.ts | 17 + libs/core/di/test/di.test.ts | 99 - libs/core/di/test/index.test.ts | 10 - libs/core/di/test/operation-context.test.ts | 273 -- .../core/di/test/pool-size-calculator.test.ts | 165 -- libs/core/di/test/registration.test.ts | 68 +- libs/core/di/test/service-application.test.ts | 4 +- libs/core/di/test/types.test.ts | 270 -- libs/core/event-bus/README.md | 191 -- libs/core/event-bus/package.json | 40 - libs/core/event-bus/src/event-bus.ts | 246 -- libs/core/event-bus/src/index.ts | 13 - libs/core/event-bus/src/simple-event-bus.ts | 205 -- libs/core/event-bus/src/types.ts | 111 - libs/core/event-bus/tsconfig.json | 17 - libs/core/handlers/package.json | 1 - libs/core/logger/package.json | 1 - libs/core/queue/src/batch-processor.ts | 1 + libs/core/queue/src/dlq-handler.ts | 257 -- libs/core/queue/src/index.ts | 35 - libs/core/queue/src/queue-metrics.ts | 318 --- libs/core/queue/src/types.ts | 48 - libs/core/queue/test/batch-processor.test.ts | 32 +- libs/core/queue/test/dlq-handler.test.ts | 278 -- libs/core/queue/test/queue-metrics.test.ts | 233 -- libs/core/services/package.json | 3 +- libs/core/services/src/index.ts | 1 - libs/core/types/src/backtesting.ts | 34 - libs/core/types/src/decorators.ts | 42 - libs/core/types/src/financial-statements.ts | 197 -- libs/core/types/src/helpers.ts | 22 - libs/core/types/src/index.ts | 61 +- libs/core/types/src/market-data.ts | 87 +- libs/core/types/src/options.ts | 58 - libs/core/types/src/portfolio.ts | 108 - libs/core/types/src/risk-metrics.ts | 86 - libs/core/types/src/technical-analysis.ts | 109 - libs/core/types/src/trading.ts | 62 - libs/data/mongodb/package.json | 2 - libs/data/mongodb/src/client.ts | 558 ++-- libs/data/mongodb/src/index.ts | 19 - libs/data/mongodb/src/types.ts | 145 - libs/data/mongodb/test/mongodb.test.ts | 197 -- .../mongodb/test/support/simple-mongodb.ts | 165 -- libs/data/postgres/package.json | 1 - libs/data/postgres/src/client.ts | 460 +-- libs/data/postgres/src/health.ts | 145 - libs/data/postgres/src/index.ts | 32 +- libs/data/postgres/src/migrations.ts | 113 + libs/data/postgres/src/query-builder.ts | 270 -- libs/data/postgres/src/types.ts | 194 -- libs/data/postgres/test/postgres.test.ts | 213 -- .../postgres/test/support/simple-postgres.ts | 215 -- libs/data/questdb/package.json | 1 - libs/services/browser/src/utils.ts | 0 libs/services/browser/test/browser.test.ts | 174 -- .../browser/test/support/simple-browser.ts | 166 -- .../proxy/src/simple-proxy-manager.ts | 135 - libs/services/proxy/test/proxy.test.ts | 254 -- libs/trading-runtime/src/paper-operator.ts | 2 +- libs/utils/README.md | 58 +- libs/utils/package.json | 4 +- libs/utils/src/common.ts | 17 - libs/utils/src/dateUtils.ts | 48 - libs/utils/src/index.ts | 2 - libs/utils/test/common-dates.test.ts | 117 - monitoring/prometheus.yml | 45 - package.json | 28 +- proxy-playwrite.ts | 86 - scripts/benchmark-candidate-isolation.ts | 2 +- scripts/benchmark-execution.ts | 47 - scripts/benchmark-replay.ts | 2 +- scripts/benchmark-research-pool.ts | 2 +- scripts/benchmark-sma.ts | 4 +- scripts/build-all.sh | 4 +- scripts/build-clean.sh | 53 - scripts/build-libs-turbo.sh | 44 - scripts/docker.sh | 4 + scripts/get-redis-connections.ts | 368 --- scripts/import-research-dataset.ts | 4 +- scripts/populate-ib-exchanges.ts | 0 scripts/setup-playwright.sh | 134 - scripts/test/architecture.test.ts | 189 +- scripts/test/library-boundaries.test.ts | 10 +- scripts/test/native-bindings.test.ts | 2 +- scripts/test/orchestrator-container.test.ts | 12 - scripts/test/strategy-packaging.test.ts | 2 +- scripts/test/strategy-runtime.test.ts | 2 +- scripts/test/workspace.test.ts | 7 +- scripts/verify-build.sh | 169 -- test-e2e-backtest.sh | 59 - test-queue.ts | 22 - test-rust-strategies.js | 274 -- test-typescript-strategy.js | 85 - test/contracts/canonical-runner.type-test.ts | 7 +- test/contracts/strategy-runtime.type-test.ts | 5 +- test/e2e/fixture.ts | 2 +- test/fixtures/canonical-paper.ts | 4 +- test/fixtures/canonical-regime-research.ts | 2 +- test/fixtures/canonical-result.ts | 2 +- test/fixtures/canonical-sma.ts | 2 +- test/fixtures/execution.ts | 51 - test/fixtures/native-replay-worker.ts | 2 +- test/fixtures/native-replay.ts | 2 +- test/fixtures/paper-feed.ts | 2 +- test/fixtures/paper-runtime.ts | 4 +- test/fixtures/strategy-crash-owner.ts | 56 - test/fixtures/strategy-recovery.ts | 158 -- test/integration/analytics-math.test.ts | 155 - test/integration/analytics-service.test.ts | 295 -- test/integration/analytics-ui.test.tsx | 67 +- .../integration/async-strategy-replay.test.ts | 4 +- test/integration/backtest-components.test.ts | 436 --- test/integration/backtest-ledger.test.ts | 334 --- test/integration/candidate-sandbox.test.ts | 2 +- test/integration/canonical-builtins.test.ts | 2 +- .../canonical-mean-reversion.test.ts | 6 +- .../canonical-native-report.test.ts | 4 +- .../canonical-regime-research.test.ts | 6 +- test/integration/canonical-result.test.ts | 4 +- test/integration/canonical-sma.test.ts | 10 +- .../canonical-strategy-worker.test.ts | 2 +- test/integration/canonical-workbench.test.tsx | 2 +- test/integration/dataset-preparation.test.ts | 2 +- .../dataset-source-preparation.test.ts | 2 +- test/integration/fee-funding.test.ts | 206 -- test/integration/indicator-contracts.test.ts | 2 - test/integration/ingestion-backtest.test.ts | 2 +- test/integration/intraday-storage.test.ts | 2 +- test/integration/mode-lifecycle.test.ts | 199 -- .../native-replay-projection.test.ts | 2 +- test/integration/native-replay-report.test.ts | 2 +- test/integration/native-replay.test.ts | 2 +- test/integration/order-execution.test.ts | 250 -- test/integration/paper-composition.test.ts | 2 +- test/integration/paper-feed.test.ts | 4 +- .../integration/paper-native-identity.test.ts | 2 +- test/integration/paper-routes.test.ts | 9 +- .../product-response-contracts.test.ts | 14 +- .../reproduction-comparison.test.ts | 2 +- .../retained-strategy-worker.test.ts | 4 +- test/integration/setup.js | 183 -- test/integration/setup.ts | 208 -- .../stored-dataset-preparation.test.ts | 2 +- test/integration/strategy-contracts.test.ts | 468 --- test/integration/strategy-recovery.test.ts | 203 -- test/integration/strategy-registry.test.ts | 122 - test/integration/strategy-runtime.test.ts | 2 +- test/integration/typescript-backtest.test.ts | 204 -- .../canonical-durable-backtest.test.ts | 2 +- test/postgres/canonical-paper.test.ts | 17 +- test/postgres/durable-backtest.test.ts | 2 +- test/postgres/order-execution.test.ts | 235 -- test/postgres/paper-deployments.test.ts | 4 +- test/postgres/paper-http.test.ts | 4 +- test/postgres/strategy-recovery.test.ts | 373 --- test/setup.js | 112 - test/unit/environment-safety.test.ts | 48 + tetest.ts | 35 - tools/coverage-cli/package.json | 2 - tsconfig.check.json | 3 +- tsconfig.unused.json | 14 - 432 files changed, 1247 insertions(+), 44469 deletions(-) delete mode 100644 apps/stock/analytics/.gitignore delete mode 100644 apps/stock/analytics/main.py delete mode 100644 apps/stock/analytics/requirements.txt delete mode 100644 apps/stock/analytics/src/analysis/statistical_validation.py delete mode 100644 apps/stock/analytics/src/analytics/performance.py delete mode 100644 apps/stock/analytics/src/analytics/regime.py delete mode 100644 apps/stock/analytics/src/api/app.py delete mode 100644 apps/stock/analytics/src/api/capabilities.py delete mode 100644 apps/stock/analytics/src/api/endpoints/analytics.py delete mode 100644 apps/stock/analytics/src/api/endpoints/models.py delete mode 100644 apps/stock/analytics/src/api/endpoints/optimization.py delete mode 100644 apps/stock/analytics/src/ml/feature_engineering.py delete mode 100644 apps/stock/analytics/src/optimization/portfolio_optimizer.py delete mode 100644 apps/stock/analytics/test/test_app_composition.py delete mode 100644 apps/stock/analytics/test/test_unavailable_endpoints.py delete mode 100644 apps/stock/data-ingestion/scripts/check-intraday-status.ts delete mode 100644 apps/stock/data-ingestion/scripts/trigger-job.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/eod/shared/types.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/qm/shared/index.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/te/shared/index.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/tradingview/shared/index.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/webshare/shared/config.ts delete mode 100644 apps/stock/data-ingestion/src/routes/index.ts delete mode 100644 apps/stock/data-ingestion/src/routes/market-data.routes.ts delete mode 100644 apps/stock/data-ingestion/src/types/exchange.types.ts delete mode 100644 apps/stock/data-ingestion/src/types/job-payloads.ts delete mode 100755 apps/stock/data-ingestion/test/test-advanced-rate-limit.ts delete mode 100644 apps/stock/data-ingestion/test/test-intraday-flow.ts delete mode 100644 apps/stock/data-ingestion/test/test-modified-functions.ts delete mode 100644 apps/stock/data-ingestion/test/test-qm-operations.ts delete mode 100644 apps/stock/data-ingestion/test/test-symbol-x.ts delete mode 100644 apps/stock/data-pipeline/scripts/phase1-inventory.ts delete mode 100644 apps/stock/data-pipeline/src/handlers/exchanges/operations/enhanced-sync-status.operations.ts delete mode 100644 apps/stock/data-pipeline/src/handlers/exchanges/operations/index.ts delete mode 100644 apps/stock/data-pipeline/src/handlers/symbols/operations/index.ts delete mode 100644 apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts delete mode 100644 apps/stock/data-pipeline/src/routes/index.ts delete mode 100644 apps/stock/data-pipeline/src/routes/stats.routes.ts delete mode 100644 apps/stock/data-pipeline/src/routes/sync.routes.ts delete mode 100644 apps/stock/engine/bun.lock delete mode 100644 apps/stock/engine/reference/legacy-reporting/README.md delete mode 100644 apps/stock/engine/reference/legacy-reporting/metrics_calculator.rs delete mode 100644 apps/stock/engine/reference/legacy-reporting/results.rs delete mode 100644 apps/stock/engine/src/analytics/transaction_costs.rs delete mode 100644 apps/stock/engine/src/strategies/mean_reversion.rs delete mode 100644 apps/stock/orchestrator/examples/advanced-risk-management.ts delete mode 100644 apps/stock/orchestrator/examples/debug-position-tracking.ts delete mode 100644 apps/stock/orchestrator/examples/debug-rust-short-trades.ts delete mode 100644 apps/stock/orchestrator/examples/example-runtime.ts delete mode 100644 apps/stock/orchestrator/examples/force-both-trade-types.ts delete mode 100644 apps/stock/orchestrator/examples/indicator-usage.ts delete mode 100644 apps/stock/orchestrator/examples/multi-strategy-backtest.ts delete mode 100644 apps/stock/orchestrator/examples/show-order-flow.ts delete mode 100644 apps/stock/orchestrator/examples/simple-backtest-test.ts delete mode 100644 apps/stock/orchestrator/examples/test-backtest-trades.ts delete mode 100644 apps/stock/orchestrator/examples/test-engine-import.ts delete mode 100644 apps/stock/orchestrator/examples/test-short-trades.ts delete mode 100644 apps/stock/orchestrator/examples/trace-short-positions.ts delete mode 100644 apps/stock/orchestrator/examples/verify-both-trade-types.ts delete mode 100644 apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts delete mode 100644 apps/stock/orchestrator/src/api/rest/analytics.ts delete mode 100644 apps/stock/orchestrator/src/api/rest/orders.ts delete mode 100644 apps/stock/orchestrator/src/api/rest/positions.ts delete mode 100644 apps/stock/orchestrator/src/api/websocket/index.ts delete mode 100644 apps/stock/orchestrator/src/backtest/BacktestEngine.ts delete mode 100644 apps/stock/orchestrator/src/backtest/BacktestMarket.ts delete mode 100644 apps/stock/orchestrator/src/backtest/BacktestPlayback.ts delete mode 100644 apps/stock/orchestrator/src/backtest/BacktestReport.ts delete mode 100644 apps/stock/orchestrator/src/backtest/MarketSimulator.ts delete mode 100644 apps/stock/orchestrator/src/backtest/canonical-build.ts delete mode 100644 apps/stock/orchestrator/src/backtest/canonical-result.ts delete mode 100644 apps/stock/orchestrator/src/backtest/native-strategies.ts delete mode 100644 apps/stock/orchestrator/src/backtest/report-format.ts delete mode 100644 apps/stock/orchestrator/src/backtest/result.ts delete mode 100644 apps/stock/orchestrator/src/backtest/strategy-plan.ts delete mode 100644 apps/stock/orchestrator/src/backtest/typescript-result.ts delete mode 100644 apps/stock/orchestrator/src/contracts/analytics.ts delete mode 100644 apps/stock/orchestrator/src/contracts/builtin-strategy.ts delete mode 100644 apps/stock/orchestrator/src/contracts/canonical-execution.ts delete mode 100644 apps/stock/orchestrator/src/contracts/canonical-strategy.ts delete mode 100644 apps/stock/orchestrator/src/contracts/native-replay.ts delete mode 100644 apps/stock/orchestrator/src/contracts/paper-runtime.ts delete mode 100644 apps/stock/orchestrator/src/contracts/strategies.ts delete mode 100644 apps/stock/orchestrator/src/contracts/strategy-names.ts delete mode 100644 apps/stock/orchestrator/src/core/ModeManager.ts delete mode 100644 apps/stock/orchestrator/src/data/DataManager.ts delete mode 100644 apps/stock/orchestrator/src/data/preparation.ts delete mode 100644 apps/stock/orchestrator/src/data/retained-research-dataset.ts delete mode 100644 apps/stock/orchestrator/src/execution/BacktestExecutionRepository.ts delete mode 100644 apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts delete mode 100644 apps/stock/orchestrator/src/execution/SimulationExecution.ts delete mode 100644 apps/stock/orchestrator/src/execution/StrategyRecovery.ts delete mode 100644 apps/stock/orchestrator/src/execution/model.ts delete mode 100644 apps/stock/orchestrator/src/execution/repository.ts delete mode 100644 apps/stock/orchestrator/src/execution/strategy-recovery.ts delete mode 100644 apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts delete mode 100644 apps/stock/orchestrator/src/paper/PaperTradingManager.ts delete mode 100644 apps/stock/orchestrator/src/paper/paper-deployment-custody.ts delete mode 100644 apps/stock/orchestrator/src/paper/paper-host-identity.ts delete mode 100644 apps/stock/orchestrator/src/paper/paper-operator.ts delete mode 100644 apps/stock/orchestrator/src/services/AnalyticsService.ts delete mode 100644 apps/stock/orchestrator/src/services/ExecutionService.ts delete mode 100644 apps/stock/orchestrator/src/services/MarketDataService.ts delete mode 100644 apps/stock/orchestrator/src/services/StorageService.ts delete mode 100644 apps/stock/orchestrator/src/services/analytics-error.ts delete mode 100644 apps/stock/orchestrator/src/strategies/BaseStrategy.ts delete mode 100644 apps/stock/orchestrator/src/strategies/StrategyManager.ts delete mode 100644 apps/stock/orchestrator/src/strategies/StrategyRegistry.ts delete mode 100644 apps/stock/orchestrator/src/strategies/builtin-strategies.ts delete mode 100644 apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts delete mode 100644 apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts delete mode 100644 apps/stock/orchestrator/src/strategies/checkpoint-schemas.ts delete mode 100644 apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts delete mode 100644 apps/stock/orchestrator/src/strategies/strategy-config.ts delete mode 100644 apps/stock/orchestrator/src/types/MarketMicrostructure.ts delete mode 100644 apps/stock/orchestrator/tests/indicators.test.ts delete mode 100644 apps/stock/package.json delete mode 100755 apps/stock/scripts/health-check.js delete mode 100644 apps/stock/tsconfig.json delete mode 100644 apps/stock/web-api/src/container-setup.ts delete mode 100644 apps/stock/web-api/src/routes/index.ts delete mode 100644 apps/stock/web-api/src/types.ts delete mode 100644 apps/stock/web-app/src/components/charts/index.ts delete mode 100644 apps/stock/web-app/src/components/index.ts delete mode 100644 apps/stock/web-app/src/components/ui/DataTable/types.ts delete mode 100644 apps/stock/web-app/src/features/backtest/components/BacktestMetrics.tsx delete mode 100644 apps/stock/web-app/src/features/backtest/components/MetricsCard.tsx delete mode 100644 apps/stock/web-app/src/features/backtest/components/RunControls.tsx delete mode 100644 apps/stock/web-app/src/features/backtest/components/index.ts delete mode 100644 apps/stock/web-app/src/features/charts/components/index.ts delete mode 100644 apps/stock/web-app/src/features/charts/hooks/index.ts delete mode 100644 apps/stock/web-app/src/features/charts/hooks/useChartData.ts delete mode 100644 apps/stock/web-app/src/features/charts/index.ts delete mode 100644 apps/stock/web-app/src/features/charts/services/chartDataService.ts delete mode 100644 apps/stock/web-app/src/features/exchanges/types/api.types.ts delete mode 100644 apps/stock/web-app/src/features/exchanges/types/component.types.ts delete mode 100644 apps/stock/web-app/src/features/exchanges/types/request.types.ts delete mode 100644 apps/stock/web-app/src/features/symbols/components/index.ts delete mode 100644 apps/stock/web-app/src/lib/utils/cn.ts delete mode 100644 apps/stock/web-app/src/lib/utils/index.ts delete mode 100644 database/mongodb/init/01-init-collections.js create mode 100644 docker-compose.quant.yml delete mode 100644 docs/cleanup-audit.md delete mode 100644 knip.json delete mode 100644 libs/LIBRARY_STANDARDS.md delete mode 100644 libs/calculations/migration-audit.json delete mode 100644 libs/calculations/research/README.md delete mode 100644 libs/calculations/research/correlation-analysis.md delete mode 100644 libs/calculations/research/market-statistics.md delete mode 100644 libs/calculations/research/options-pricing.md delete mode 100644 libs/calculations/research/portfolio-analytics.md delete mode 100644 libs/calculations/research/position-sizing-notes.md delete mode 100644 libs/calculations/research/position-sizing.md delete mode 100644 libs/calculations/research/technical-indicators.md delete mode 100644 libs/calculations/research/volatility-models.md delete mode 100644 libs/calculations/src/legacy/basic-calculations.ts delete mode 100644 libs/calculations/src/legacy/index.ts delete mode 100644 libs/calculations/src/legacy/performance-metrics.ts delete mode 100644 libs/calculations/src/legacy/risk-metrics.ts delete mode 100644 libs/calculations/src/legacy/technical-indicators.ts delete mode 100644 libs/calculations/test/preservation.test.ts delete mode 100644 libs/core/cache/src/key-generator.ts delete mode 100644 libs/core/cache/test/key-generator.test.ts delete mode 100644 libs/core/config/.env.example delete mode 100644 libs/core/config/config/default.json delete mode 100644 libs/core/config/config/development.json delete mode 100644 libs/core/config/config/production.json delete mode 100644 libs/core/config/config/test.json delete mode 100644 libs/core/config/src/cli.ts delete mode 100644 libs/core/config/src/utils/secrets.ts delete mode 100644 libs/core/config/src/utils/validation.ts delete mode 100644 libs/core/config/test/utils.test.ts delete mode 100644 libs/core/di/src/awilix-container.ts delete mode 100644 libs/core/di/src/factories/index.ts delete mode 100644 libs/core/di/src/operation-context.ts delete mode 100644 libs/core/di/src/pool-size-calculator.ts delete mode 100644 libs/core/di/src/types.ts delete mode 100644 libs/core/di/test/awilix-container.test.ts delete mode 100644 libs/core/di/test/operation-context.test.ts delete mode 100644 libs/core/di/test/pool-size-calculator.test.ts delete mode 100644 libs/core/di/test/types.test.ts delete mode 100644 libs/core/event-bus/README.md delete mode 100644 libs/core/event-bus/package.json delete mode 100644 libs/core/event-bus/src/event-bus.ts delete mode 100644 libs/core/event-bus/src/index.ts delete mode 100644 libs/core/event-bus/src/simple-event-bus.ts delete mode 100644 libs/core/event-bus/src/types.ts delete mode 100644 libs/core/event-bus/tsconfig.json delete mode 100644 libs/core/queue/src/dlq-handler.ts delete mode 100644 libs/core/queue/src/queue-metrics.ts delete mode 100644 libs/core/queue/test/dlq-handler.test.ts delete mode 100644 libs/core/queue/test/queue-metrics.test.ts delete mode 100644 libs/core/types/src/backtesting.ts delete mode 100644 libs/core/types/src/financial-statements.ts delete mode 100644 libs/core/types/src/options.ts delete mode 100644 libs/core/types/src/portfolio.ts delete mode 100644 libs/core/types/src/risk-metrics.ts delete mode 100644 libs/core/types/src/technical-analysis.ts delete mode 100644 libs/core/types/src/trading.ts delete mode 100644 libs/data/mongodb/test/mongodb.test.ts delete mode 100644 libs/data/mongodb/test/support/simple-mongodb.ts delete mode 100644 libs/data/postgres/src/health.ts create mode 100644 libs/data/postgres/src/migrations.ts delete mode 100644 libs/data/postgres/src/query-builder.ts delete mode 100644 libs/data/postgres/test/postgres.test.ts delete mode 100644 libs/data/postgres/test/support/simple-postgres.ts delete mode 100644 libs/services/browser/src/utils.ts delete mode 100644 libs/services/browser/test/browser.test.ts delete mode 100644 libs/services/browser/test/support/simple-browser.ts delete mode 100644 libs/services/proxy/src/simple-proxy-manager.ts delete mode 100644 libs/services/proxy/test/proxy.test.ts delete mode 100644 libs/utils/src/common.ts delete mode 100644 libs/utils/src/dateUtils.ts delete mode 100644 libs/utils/test/common-dates.test.ts delete mode 100644 monitoring/prometheus.yml delete mode 100644 proxy-playwrite.ts delete mode 100644 scripts/benchmark-execution.ts delete mode 100755 scripts/build-clean.sh delete mode 100644 scripts/build-libs-turbo.sh delete mode 100644 scripts/get-redis-connections.ts delete mode 100644 scripts/populate-ib-exchanges.ts delete mode 100755 scripts/setup-playwright.sh delete mode 100644 scripts/test/orchestrator-container.test.ts delete mode 100755 scripts/verify-build.sh delete mode 100755 test-e2e-backtest.sh delete mode 100644 test-queue.ts delete mode 100644 test-rust-strategies.js delete mode 100644 test-typescript-strategy.js delete mode 100644 test/fixtures/strategy-crash-owner.ts delete mode 100644 test/fixtures/strategy-recovery.ts delete mode 100644 test/integration/analytics-math.test.ts delete mode 100644 test/integration/analytics-service.test.ts delete mode 100644 test/integration/backtest-components.test.ts delete mode 100644 test/integration/backtest-ledger.test.ts delete mode 100644 test/integration/fee-funding.test.ts delete mode 100644 test/integration/mode-lifecycle.test.ts delete mode 100644 test/integration/order-execution.test.ts delete mode 100644 test/integration/setup.js delete mode 100644 test/integration/setup.ts delete mode 100644 test/integration/strategy-contracts.test.ts delete mode 100644 test/integration/strategy-recovery.test.ts delete mode 100644 test/integration/strategy-registry.test.ts delete mode 100644 test/integration/typescript-backtest.test.ts delete mode 100644 test/postgres/order-execution.test.ts delete mode 100644 test/postgres/strategy-recovery.test.ts delete mode 100644 test/setup.js delete mode 100644 tetest.ts delete mode 100644 tsconfig.unused.json diff --git a/.env b/.env index 36876452..858685b0 100644 --- a/.env +++ b/.env @@ -27,31 +27,31 @@ WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/ # Dragonfly/Redis Configuration DRAGONFLY_HOST=localhost -DRAGONFLY_PORT=6379 +DRAGONFLY_PORT=6380 DRAGONFLY_PASSWORD= # PostgreSQL Configuration POSTGRES_HOST=localhost -POSTGRES_PORT=5432 -POSTGRES_DATABASE=trading_bot -POSTGRES_USERNAME=trading_user -POSTGRES_PASSWORD=trading_pass_dev +POSTGRES_PORT=5433 +POSTGRES_DATABASE=trading_bot_dev +POSTGRES_USERNAME=dev_user +POSTGRES_PASSWORD=dev_pass POSTGRES_SSL=false # QuestDB Configuration QUESTDB_HOST=localhost -QUESTDB_PORT=9000 +QUESTDB_PORT=9100 QUESTDB_DB=qdb QUESTDB_USERNAME=admin QUESTDB_PASSWORD=quest # MongoDB Configuration MONGODB_HOST=localhost -MONGODB_PORT=27017 -MONGODB_DATABASE=stock -MONGODB_USERNAME=trading_admin -MONGODB_PASSWORD=trading_mongo_dev -MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin +MONGODB_PORT=27018 +MONGODB_DATABASE=stock_dev +MONGODB_USERNAME=dev_admin +MONGODB_PASSWORD=dev_mongo_pass +MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin # =========================================== # DATA PROVIDER CONFIGURATIONS @@ -154,7 +154,6 @@ SOURCE_MAPS=true # =========================================== # Docker-specific settings (used in docker-compose) -COMPOSE_PROJECT_NAME=stock-bot DOCKER_BUILDKIT=1 # =========================================== @@ -171,7 +170,11 @@ APP_DESCRIPTION="Advanced Stock Trading and Analysis Platform" # PostgreSQL DATABASE_POSTGRES_HOST=localhost -DATABASE_POSTGRES_PORT=5432 -DATABASE_POSTGRES_DATABASE=trading_bot -DATABASE_POSTGRES_USER=trading_user -DATABASE_POSTGRES_PASSWORD=trading_pass_dev +DATABASE_POSTGRES_PORT=5433 +DATABASE_POSTGRES_DATABASE=trading_bot_dev +DATABASE_POSTGRES_USER=dev_user +DATABASE_POSTGRES_PASSWORD=dev_pass +QUESTDB_HTTP_PORT=9100 +QUESTDB_PG_PORT=8813 +QUESTDB_ILP_PORT=9010 +QUEUE_ENABLE_SCHEDULED_JOBS=false diff --git a/.env.dev.example b/.env.dev.example index 117cbfdb..e5f23f70 100644 --- a/.env.dev.example +++ b/.env.dev.example @@ -36,8 +36,17 @@ MONGODB_URI=mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSou # QA MongoDB READ-ONLY connection (used by dev data-pipeline to read ingested provider data) MONGODB_READ_URI=mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock -# Dev Dragonfly / QuestDB +# Dev Dragonfly / QuestDB / Queue DRAGONFLY_HOST=localhost DRAGONFLY_PORT=6380 QUESTDB_HOST=localhost QUESTDB_PORT=9100 +QUESTDB_HTTP_PORT=9100 +QUESTDB_PG_PORT=8813 +QUESTDB_ILP_PORT=9010 +QUEUE_ENABLE_SCHEDULED_JOBS=false + +# DuckDB per-connection budget (prevents default 80% host-RAM allocation) +DUCKDB_MEMORY_LIMIT=2GB +DUCKDB_THREADS=2 +DUCKDB_TEMP_DIR=/tmp/stock-bot-duckdb-dev diff --git a/.env.qa.example b/.env.qa.example index f36e0a3b..224fd764 100644 --- a/.env.qa.example +++ b/.env.qa.example @@ -35,8 +35,17 @@ MONGODB_URI=mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?auth # Optional: restrict QA data-pipeline to read-only MongoDB credentials too # MONGODB_READ_URI=mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock -# QA Dragonfly / QuestDB +# QA Dragonfly / QuestDB / Queue DRAGONFLY_HOST=localhost DRAGONFLY_PORT=6379 QUESTDB_HOST=localhost QUESTDB_PORT=9000 +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_ILP_PORT=9009 +QUEUE_ENABLE_SCHEDULED_JOBS=true + +# DuckDB per-worker budget on quant (prevents default 80% host-RAM allocation) +DUCKDB_MEMORY_LIMIT=6GB +DUCKDB_THREADS=4 +DUCKDB_TEMP_DIR=/mnt/data/stockbot/tmp/duckdb diff --git a/README.md b/README.md index b8d2a089..931d0a4a 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ Preserve the matching image and descriptor when retaining runs for reproduction. `execution: { "kind": "isolated-candidate/v1", "warmupBars": 0 }`. Set the warmup to the maximum required by all intended parameter combinations. Use the [retained package contract](libs/core/types/src/strategy-version.ts) and -[strategy decision API](apps/stock/orchestrator/src/contracts/canonical-strategy.ts). +[strategy decision API](libs/research/src/strategy-api.ts). The entry export is a synchronous factory receiving the retained selection and returning a target-mode strategy with explicit JSON state. The CLI transpiles self-contained TypeScript inside isolation; it does not evaluate the source or install dependencies. @@ -188,14 +188,9 @@ feature engineering. Its supported subpaths expose reviewed returns, indicators, transforms and the previously tested orchestrator analytics/window math. The orchestrator now consumes that library; no database, native binding, HTTP or application service is required to import it. Existing strategy checkpoint versions and financial execution -behavior are unchanged by this relocation. - -All 105 formerly active financial calculation functions remain available behind the -explicit `@stock-bot/calculations/legacy` namespace, with unchanged executable bodies. -This is preservation, not a production-correctness endorsement. All seven previously -disabled prototypes, including unique additional indicators, survive as non-executable -source-verified research snapshots. See [the calculation contract](libs/calculations/README.md) -for supported units, undefined values, alignment and the review/promotion path. +behavior are unchanged by this relocation. See +[the calculation contract](libs/calculations/README.md) for supported units, undefined +values, alignment and validation rules. `@stock-bot/utils` retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday helpers through explicit capability subpaths. Deprecated `dateUtils` names are aliases, @@ -203,12 +198,9 @@ not an exchange holiday/session calendar. Assertions belong to `@stock-bot/invar and domain types to `@stock-bot/types`. The coverage CLI no longer declares an unused utility dependency, and unused `simple-statistics` is removed. -Only empty placeholder/redundant entry points remain removed; old numerical and Redis -test sources are retained as explicit legacy/research references rather than runnable -backups or claimed passing coverage. [The cleanup audit](docs/cleanup-audit.md) accounts -for every removal in this batch. [The utility contract](libs/utils/README.md) documents -the restored helpers and migration notes. Architecture tests enforce the ownership and -dependency boundaries without forbidding useful shared domain libraries. +[The utility contract](libs/utils/README.md) documents the general HTTP and user-agent +helpers. Architecture tests enforce the ownership and dependency boundaries without +forbidding useful shared domain libraries. ## Service contracts @@ -278,12 +270,7 @@ tests. Registering a factory does not bypass risk checks or the durable-checkpoi The experimental ML strategy remains unavailable for paper execution. Architecture tests run in `bun run check`, checking runtime dependency cycles and the -contract/domain/adapter boundaries. The run-local ledger stages only transaction writes, -indexes active work and client IDs, and binary-searches the journal; retained history is not -deep-copied for every read. Reads/writes remain detached and failed transactions publish -nothing. History is still retained in memory for the run; this is not a streaming/retention -solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark, -not an end-to-end backtest performance estimate. +contract/domain/adapter boundaries. ### Strategy parameters and indicator math @@ -380,26 +367,7 @@ Corrected analytics can change new-run results. Existing saved rows are not reca no database migration/reset is performed. Native trading algorithms and engine-specific supplemental statistics are not silently redefined by this TypeScript math refactor. -The external analytics client validates finite responses, ordered instrument/model identity, -portfolio weights and correlation matrices (including positive semidefiniteness). Requests -have a five-second timeout and one-MiB response limit. Its success cache is capped at 128 -entries with per-entry TTL; failed/expired requests never become fresh fake observations. -HTTP 503 means unavailable upstream/data; 502 means an invalid upstream response; invalid -client input remains 400. No outage produces zero risk metrics, equal portfolio weights, -an identity correlation matrix or a โ€œnormalโ€ market regime. - -The Python portfolio-performance/risk, regime, correlation, saved-backtest-analysis and -attribution endpoints currently have no observed-data adapter. They now return explicit 503 -instead of random samples or constant reports. They remain unavailable until real data is -integrated; research helpers are not production data sources. Optimization still consumes -caller-provided returns/symbols, and prediction requires an actual loaded model. TypeScript -maps their snake-case Python wire fields explicitly rather than guessing weights/identities. - Run `bun run check` for TypeScript/native checks and analytics regression fixtures. -Separately run `bun run test:analytics-api` for real FastAPI router HTTP tests. That optional -command needs Python 3.12 and `uv`; it obtains the FastAPI/HTTPX/Pydantic versions already -pinned by the Python service, without installing the research/ML runtime. It tests the router, -not full Python-service startup or a live upstream deployment. ## Backtest data integrity diff --git a/apps/stock/analytics/.gitignore b/apps/stock/analytics/.gitignore deleted file mode 100644 index 43ae0e2a..00000000 --- a/apps/stock/analytics/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -__pycache__/ -*.py[cod] diff --git a/apps/stock/analytics/main.py b/apps/stock/analytics/main.py deleted file mode 100644 index b83b704a..00000000 --- a/apps/stock/analytics/main.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -""" -Trading Analytics Service - Main entry point -""" - -import uvicorn -import logging -import os -from dotenv import load_dotenv - -# Load environment variables -load_dotenv() - -# Configure logging -logging.basicConfig( - level=logging.INFO, - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' -) - -logger = logging.getLogger(__name__) - -def main(): - """Start the analytics service""" - host = os.getenv('ANALYTICS_HOST', '0.0.0.0') - port = int(os.getenv('ANALYTICS_PORT', '3003')) - - logger.info(f"Starting Trading Analytics Service on {host}:{port}") - - uvicorn.run( - "src.api.app:app", - host=host, - port=port, - reload=os.getenv('ENV') == 'development', - log_level="info" - ) - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/apps/stock/analytics/requirements.txt b/apps/stock/analytics/requirements.txt deleted file mode 100644 index 790919f1..00000000 --- a/apps/stock/analytics/requirements.txt +++ /dev/null @@ -1,18 +0,0 @@ -fastapi==0.104.1 -uvicorn==0.24.0 -pandas==2.1.3 -numpy==1.26.2 -scipy==1.11.4 -scikit-learn==1.3.2 -cvxpy==1.4.1 -statsmodels==0.14.0 -ta==0.10.2 -plotly==5.18.0 -redis==5.0.1 -httpx==0.25.2 -pydantic==2.5.0 -python-dotenv==1.0.0 -onnxruntime==1.16.3 -psycopg2-binary==2.9.9 -sqlalchemy==2.0.23 -alembic==1.12.1 \ No newline at end of file diff --git a/apps/stock/analytics/src/analysis/statistical_validation.py b/apps/stock/analytics/src/analysis/statistical_validation.py deleted file mode 100644 index 16624191..00000000 --- a/apps/stock/analytics/src/analysis/statistical_validation.py +++ /dev/null @@ -1,410 +0,0 @@ -import numpy as np -import pandas as pd -from scipy import stats -from typing import Dict, List, Tuple, Optional -import logging -from dataclasses import dataclass -from sklearn.model_selection import TimeSeriesSplit -import warnings - -logger = logging.getLogger(__name__) - -@dataclass -class ValidationResult: - """Results from statistical validation tests""" - is_overfit: bool - confidence_level: float - psr: float # Probabilistic Sharpe Ratio - dsr: float # Deflated Sharpe Ratio - monte_carlo_percentile: float - out_of_sample_degradation: float - statistical_significance: bool - warnings: List[str] - recommendations: List[str] - -class StatisticalValidator: - """ - Statistical validation for backtesting results - Detects overfitting and validates strategy robustness - """ - - def __init__(self, min_trades: int = 30, confidence_level: float = 0.95): - self.min_trades = min_trades - self.confidence_level = confidence_level - - def validate_backtest( - self, - returns: np.ndarray, - trades: pd.DataFrame, - parameters: Dict, - market_returns: Optional[np.ndarray] = None - ) -> ValidationResult: - """ - Comprehensive validation of backtest results - """ - warnings_list = [] - recommendations = [] - - # Check minimum requirements - if len(trades) < self.min_trades: - warnings_list.append(f"Insufficient trades ({len(trades)} < {self.min_trades})") - recommendations.append("Extend backtest period or reduce trading filters") - - # Calculate key metrics - sharpe = self.calculate_sharpe_ratio(returns) - psr = self.calculate_probabilistic_sharpe_ratio(sharpe, len(returns)) - dsr = self.calculate_deflated_sharpe_ratio( - sharpe, len(returns), len(parameters) - ) - - # Monte Carlo analysis - mc_percentile = self.monte_carlo_test(returns, trades) - - # Out-of-sample testing - oos_degradation = self.out_of_sample_test(returns, trades) - - # Statistical significance tests - is_significant = self.test_statistical_significance(returns, market_returns) - - # Overfitting detection - is_overfit = self.detect_overfitting( - psr, dsr, mc_percentile, oos_degradation, len(parameters) - ) - - # Generate recommendations - if dsr < 0.95: - recommendations.append("Reduce strategy complexity or increase sample size") - if mc_percentile < 0.95: - recommendations.append("Strategy may be exploiting random patterns") - if oos_degradation > 0.5: - recommendations.append("Consider walk-forward optimization") - - return ValidationResult( - is_overfit=is_overfit, - confidence_level=1 - is_overfit * 0.5, # Simple confidence measure - psr=psr, - dsr=dsr, - monte_carlo_percentile=mc_percentile, - out_of_sample_degradation=oos_degradation, - statistical_significance=is_significant, - warnings=warnings_list, - recommendations=recommendations - ) - - def calculate_sharpe_ratio(self, returns: np.ndarray) -> float: - """Calculate annualized Sharpe ratio""" - if len(returns) == 0: - return 0.0 - - # Assume daily returns - mean_return = np.mean(returns) - std_return = np.std(returns, ddof=1) - - if std_return == 0: - return 0.0 - - # Annualize - sharpe = mean_return / std_return * np.sqrt(252) - return sharpe - - def calculate_probabilistic_sharpe_ratio( - self, - sharpe: float, - num_observations: int - ) -> float: - """ - Calculate Probabilistic Sharpe Ratio (PSR) - Adjusts for sample size and non-normality - """ - if num_observations < 2: - return 0.0 - - # Adjust for sample size - psr = stats.norm.cdf( - sharpe * np.sqrt(num_observations - 1) / - np.sqrt(1 + 0.5 * sharpe**2) - ) - - return psr - - def calculate_deflated_sharpe_ratio( - self, - sharpe: float, - num_observations: int, - num_parameters: int, - num_trials: int = 1 - ) -> float: - """ - Calculate Deflated Sharpe Ratio (DSR) - Accounts for multiple testing and parameter optimization - """ - if num_observations < num_parameters + 2: - return 0.0 - - # Expected maximum Sharpe under null hypothesis - expected_max_sharpe = np.sqrt(2 * np.log(num_trials)) / np.sqrt(num_observations) - - # Standard error of Sharpe ratio - se_sharpe = np.sqrt( - (1 + 0.5 * sharpe**2) / (num_observations - 1) - ) - - # Deflated Sharpe Ratio - dsr = (sharpe - expected_max_sharpe) / se_sharpe - - # Convert to probability - return stats.norm.cdf(dsr) - - def monte_carlo_test( - self, - returns: np.ndarray, - trades: pd.DataFrame, - num_simulations: int = 1000 - ) -> float: - """ - Monte Carlo permutation test - Tests if strategy is better than random - """ - original_sharpe = self.calculate_sharpe_ratio(returns) - - # Generate random strategies - random_sharpes = [] - - for _ in range(num_simulations): - # Randomly shuffle trade outcomes - shuffled_returns = np.random.permutation(returns) - random_sharpe = self.calculate_sharpe_ratio(shuffled_returns) - random_sharpes.append(random_sharpe) - - # Calculate percentile - percentile = np.sum(original_sharpe > np.array(random_sharpes)) / num_simulations - - return percentile - - def out_of_sample_test( - self, - returns: np.ndarray, - trades: pd.DataFrame, - test_size: float = 0.3 - ) -> float: - """ - Test performance degradation out-of-sample - """ - if len(returns) < 100: # Need sufficient data - return 0.0 - - # Split data - split_point = int(len(returns) * (1 - test_size)) - in_sample_returns = returns[:split_point] - out_sample_returns = returns[split_point:] - - # Calculate Sharpe ratios - is_sharpe = self.calculate_sharpe_ratio(in_sample_returns) - oos_sharpe = self.calculate_sharpe_ratio(out_sample_returns) - - # Calculate degradation - if is_sharpe > 0: - degradation = max(0, 1 - oos_sharpe / is_sharpe) - else: - degradation = 1.0 - - return degradation - - def test_statistical_significance( - self, - strategy_returns: np.ndarray, - market_returns: Optional[np.ndarray] = None - ) -> bool: - """ - Test if returns are statistically significant - """ - # Test against zero returns - t_stat, p_value = stats.ttest_1samp(strategy_returns, 0) - - if p_value < (1 - self.confidence_level): - return True - - # If market returns provided, test for alpha - if market_returns is not None and len(market_returns) == len(strategy_returns): - excess_returns = strategy_returns - market_returns - t_stat, p_value = stats.ttest_1samp(excess_returns, 0) - - return p_value < (1 - self.confidence_level) - - return False - - def detect_overfitting( - self, - psr: float, - dsr: float, - mc_percentile: float, - oos_degradation: float, - num_parameters: int - ) -> bool: - """ - Detect potential overfitting based on multiple criteria - """ - overfitting_score = 0 - - # Check PSR - if psr < 0.95: - overfitting_score += 1 - - # Check DSR - if dsr < 0.95: - overfitting_score += 2 # More weight on DSR - - # Check Monte Carlo - if mc_percentile < 0.95: - overfitting_score += 1 - - # Check out-of-sample degradation - if oos_degradation > 0.5: - overfitting_score += 2 - - # Check parameter count - if num_parameters > 10: - overfitting_score += 1 - - # Decision threshold - return overfitting_score >= 3 - - def walk_forward_analysis( - self, - data: pd.DataFrame, - strategy_func, - window_size: int, - step_size: int, - num_windows: int = 5 - ) -> Dict: - """ - Perform walk-forward analysis - """ - results = { - 'in_sample_sharpes': [], - 'out_sample_sharpes': [], - 'parameters': [], - 'stability_score': 0 - } - - tscv = TimeSeriesSplit(n_splits=num_windows) - - for train_idx, test_idx in tscv.split(data): - train_data = data.iloc[train_idx] - test_data = data.iloc[test_idx] - - # Optimize on training data - best_params = self.optimize_parameters(train_data, strategy_func) - results['parameters'].append(best_params) - - # Test on out-of-sample data - is_returns = strategy_func(train_data, best_params) - oos_returns = strategy_func(test_data, best_params) - - is_sharpe = self.calculate_sharpe_ratio(is_returns) - oos_sharpe = self.calculate_sharpe_ratio(oos_returns) - - results['in_sample_sharpes'].append(is_sharpe) - results['out_sample_sharpes'].append(oos_sharpe) - - # Calculate stability score - param_stability = self.calculate_parameter_stability(results['parameters']) - performance_stability = 1 - np.std(results['out_sample_sharpes']) / (np.mean(results['out_sample_sharpes']) + 1e-6) - - results['stability_score'] = (param_stability + performance_stability) / 2 - - return results - - def calculate_parameter_stability(self, parameters_list: List[Dict]) -> float: - """ - Calculate how stable parameters are across different periods - """ - if len(parameters_list) < 2: - return 1.0 - - # Convert to DataFrame for easier analysis - params_df = pd.DataFrame(parameters_list) - - # Calculate coefficient of variation for each parameter - stabilities = [] - for col in params_df.columns: - if params_df[col].dtype in [np.float64, np.int64]: - mean_val = params_df[col].mean() - std_val = params_df[col].std() - - if mean_val != 0: - cv = std_val / abs(mean_val) - stability = 1 / (1 + cv) # Convert to 0-1 scale - stabilities.append(stability) - - return np.mean(stabilities) if stabilities else 0.5 - - def optimize_parameters(self, data: pd.DataFrame, strategy_func) -> Dict: - """ - Placeholder for parameter optimization - In practice, this would use grid search, Bayesian optimization, etc. - """ - # Simple example - would be replaced with actual optimization - return {'param1': 20, 'param2': 2.0} - - def bootstrap_confidence_intervals( - self, - returns: np.ndarray, - metric_func, - confidence_level: float = 0.95, - num_samples: int = 1000 - ) -> Tuple[float, float, float]: - """ - Calculate bootstrap confidence intervals for any metric - """ - bootstrap_metrics = [] - - for _ in range(num_samples): - # Resample with replacement - sample_returns = np.random.choice(returns, size=len(returns), replace=True) - metric = metric_func(sample_returns) - bootstrap_metrics.append(metric) - - # Calculate percentiles - lower_percentile = (1 - confidence_level) / 2 - upper_percentile = 1 - lower_percentile - - lower_bound = np.percentile(bootstrap_metrics, lower_percentile * 100) - upper_bound = np.percentile(bootstrap_metrics, upper_percentile * 100) - point_estimate = metric_func(returns) - - return lower_bound, point_estimate, upper_bound - - def generate_report(self, validation_result: ValidationResult) -> str: - """ - Generate human-readable validation report - """ - report = f""" -Statistical Validation Report -============================ - -Overall Assessment: {'PASSED' if not validation_result.is_overfit else 'FAILED'} -Confidence Level: {validation_result.confidence_level:.1%} - -Key Metrics: ------------ -Probabilistic Sharpe Ratio (PSR): {validation_result.psr:.3f} -Deflated Sharpe Ratio (DSR): {validation_result.dsr:.3f} -Monte Carlo Percentile: {validation_result.monte_carlo_percentile:.1%} -Out-of-Sample Degradation: {validation_result.out_of_sample_degradation:.1%} -Statistical Significance: {'Yes' if validation_result.statistical_significance else 'No'} - -Warnings: ---------- -""" - for warning in validation_result.warnings: - report += f"- {warning}\n" - - report += """ -Recommendations: ---------------- -""" - for rec in validation_result.recommendations: - report += f"- {rec}\n" - - return report \ No newline at end of file diff --git a/apps/stock/analytics/src/analytics/performance.py b/apps/stock/analytics/src/analytics/performance.py deleted file mode 100644 index 3b7a624b..00000000 --- a/apps/stock/analytics/src/analytics/performance.py +++ /dev/null @@ -1,217 +0,0 @@ -import pandas as pd -import numpy as np -from datetime import datetime, timedelta -from typing import Dict, List, Optional, Tuple -import logging - -logger = logging.getLogger(__name__) - -class PerformanceAnalyzer: - """ - Comprehensive performance analysis for trading strategies and portfolios - """ - - def __init__(self, risk_free_rate: float = 0.02): - self.risk_free_rate = risk_free_rate - - def calculate_metrics( - self, - portfolio_id: str, - start_date: datetime, - end_date: datetime - ) -> Dict: - """ - Calculate comprehensive performance metrics - """ - # In real implementation, would fetch data from database - # For now, generate sample data - returns = self._generate_sample_returns(start_date, end_date) - - metrics = { - 'total_return': self._calculate_total_return(returns), - 'annualized_return': self._calculate_annualized_return(returns), - 'volatility': self._calculate_volatility(returns), - 'sharpe_ratio': self._calculate_sharpe_ratio(returns), - 'sortino_ratio': self._calculate_sortino_ratio(returns), - 'max_drawdown': self._calculate_max_drawdown(returns), - 'calmar_ratio': self._calculate_calmar_ratio(returns), - 'win_rate': self._calculate_win_rate(returns), - 'profit_factor': self._calculate_profit_factor(returns), - 'avg_win': np.mean(returns[returns > 0]) if any(returns > 0) else 0, - 'avg_loss': np.mean(returns[returns < 0]) if any(returns < 0) else 0, - 'total_trades': len(returns), - 'best_day': np.max(returns), - 'worst_day': np.min(returns), - 'skewness': self._calculate_skewness(returns), - 'kurtosis': self._calculate_kurtosis(returns) - } - - return metrics - - def calculate_risk_metrics( - self, - portfolio_id: str, - window: int = 252, - confidence_levels: List[float] = [0.95, 0.99] - ) -> Dict: - """ - Calculate risk metrics including VaR and CVaR - """ - # Generate sample returns - returns = self._generate_sample_returns( - datetime.now() - timedelta(days=window), - datetime.now() - ) - - risk_metrics = { - 'volatility': self._calculate_volatility(returns), - 'downside_deviation': self._calculate_downside_deviation(returns), - 'beta': self._calculate_beta(returns), # Would need market returns - 'tracking_error': 0.0, # Placeholder - } - - # Calculate VaR and CVaR for each confidence level - for confidence in confidence_levels: - var = self._calculate_var(returns, confidence) - cvar = self._calculate_cvar(returns, confidence) - risk_metrics[f'var_{int(confidence*100)}'] = var - risk_metrics[f'cvar_{int(confidence*100)}'] = cvar - - return risk_metrics - - def analyze_backtest(self, backtest_id: str) -> Dict: - """ - Analyze backtest results - """ - # In real implementation, would fetch backtest data - # For now, return comprehensive mock analysis - - return { - 'metrics': { - 'total_return': 0.156, - 'sharpe_ratio': 1.45, - 'max_drawdown': 0.087, - 'win_rate': 0.58, - 'profit_factor': 1.78 - }, - 'statistics': { - 'total_trades': 245, - 'winning_trades': 142, - 'losing_trades': 103, - 'avg_holding_period': 3.5, - 'max_consecutive_wins': 8, - 'max_consecutive_losses': 5 - }, - 'risk_analysis': { - 'var_95': 0.024, - 'cvar_95': 0.031, - 'downside_deviation': 0.018, - 'ulcer_index': 0.045 - }, - 'trade_analysis': { - 'best_trade': 0.087, - 'worst_trade': -0.043, - 'avg_win': 0.023, - 'avg_loss': -0.015, - 'largest_winner': 0.087, - 'largest_loser': -0.043 - } - } - - # Helper methods - def _generate_sample_returns(self, start_date: datetime, end_date: datetime) -> np.ndarray: - """Generate sample returns for testing""" - days = (end_date - start_date).days - # Generate returns with realistic properties - returns = np.random.normal(0.0005, 0.02, days) - # Add some autocorrelation - for i in range(1, len(returns)): - returns[i] = 0.1 * returns[i-1] + 0.9 * returns[i] - return returns - - def _calculate_total_return(self, returns: np.ndarray) -> float: - """Calculate total cumulative return""" - return np.prod(1 + returns) - 1 - - def _calculate_annualized_return(self, returns: np.ndarray) -> float: - """Calculate annualized return""" - total_return = self._calculate_total_return(returns) - years = len(returns) / 252 - return (1 + total_return) ** (1 / years) - 1 - - def _calculate_volatility(self, returns: np.ndarray) -> float: - """Calculate annualized volatility""" - return np.std(returns) * np.sqrt(252) - - def _calculate_sharpe_ratio(self, returns: np.ndarray) -> float: - """Calculate Sharpe ratio""" - excess_returns = returns - self.risk_free_rate / 252 - return np.mean(excess_returns) / np.std(excess_returns) * np.sqrt(252) - - def _calculate_sortino_ratio(self, returns: np.ndarray) -> float: - """Calculate Sortino ratio""" - excess_returns = returns - self.risk_free_rate / 252 - downside_returns = excess_returns[excess_returns < 0] - downside_std = np.std(downside_returns) if len(downside_returns) > 0 else 1e-6 - return np.mean(excess_returns) / downside_std * np.sqrt(252) - - def _calculate_max_drawdown(self, returns: np.ndarray) -> float: - """Calculate maximum drawdown""" - cumulative = (1 + returns).cumprod() - running_max = np.maximum.accumulate(cumulative) - drawdown = (cumulative - running_max) / running_max - return np.min(drawdown) - - def _calculate_calmar_ratio(self, returns: np.ndarray) -> float: - """Calculate Calmar ratio""" - annual_return = self._calculate_annualized_return(returns) - max_dd = abs(self._calculate_max_drawdown(returns)) - return annual_return / max_dd if max_dd > 0 else 0 - - def _calculate_win_rate(self, returns: np.ndarray) -> float: - """Calculate win rate""" - return np.sum(returns > 0) / len(returns) if len(returns) > 0 else 0 - - def _calculate_profit_factor(self, returns: np.ndarray) -> float: - """Calculate profit factor""" - gains = returns[returns > 0] - losses = returns[returns < 0] - total_gains = np.sum(gains) if len(gains) > 0 else 0 - total_losses = abs(np.sum(losses)) if len(losses) > 0 else 1e-6 - return total_gains / total_losses - - def _calculate_downside_deviation(self, returns: np.ndarray, mar: float = 0) -> float: - """Calculate downside deviation""" - downside_returns = returns[returns < mar] - return np.std(downside_returns) * np.sqrt(252) if len(downside_returns) > 0 else 0 - - def _calculate_var(self, returns: np.ndarray, confidence: float) -> float: - """Calculate Value at Risk""" - return np.percentile(returns, (1 - confidence) * 100) - - def _calculate_cvar(self, returns: np.ndarray, confidence: float) -> float: - """Calculate Conditional Value at Risk""" - var = self._calculate_var(returns, confidence) - return np.mean(returns[returns <= var]) - - def _calculate_beta(self, returns: np.ndarray, market_returns: Optional[np.ndarray] = None) -> float: - """Calculate beta relative to market""" - if market_returns is None: - # Generate mock market returns - market_returns = np.random.normal(0.0003, 0.015, len(returns)) - - covariance = np.cov(returns, market_returns)[0, 1] - market_variance = np.var(market_returns) - return covariance / market_variance if market_variance > 0 else 1.0 - - def _calculate_skewness(self, returns: np.ndarray) -> float: - """Calculate skewness of returns""" - mean = np.mean(returns) - std = np.std(returns) - return np.mean(((returns - mean) / std) ** 3) if std > 0 else 0 - - def _calculate_kurtosis(self, returns: np.ndarray) -> float: - """Calculate kurtosis of returns""" - mean = np.mean(returns) - std = np.std(returns) - return np.mean(((returns - mean) / std) ** 4) - 3 if std > 0 else 0 \ No newline at end of file diff --git a/apps/stock/analytics/src/analytics/regime.py b/apps/stock/analytics/src/analytics/regime.py deleted file mode 100644 index 9fd51572..00000000 --- a/apps/stock/analytics/src/analytics/regime.py +++ /dev/null @@ -1,284 +0,0 @@ -import numpy as np -import pandas as pd -from datetime import datetime, timedelta -from typing import Dict, List, Tuple -from scipy import stats -from sklearn.mixture import GaussianMixture -import logging - -logger = logging.getLogger(__name__) - -class RegimeDetector: - """ - Market regime detection using various statistical and ML methods - """ - - def __init__(self): - self.regimes = ['bull', 'bear', 'sideways', 'high_volatility', 'low_volatility'] - - def detect_current_regime(self, lookback_days: int = 60) -> Dict: - """ - Detect current market regime using multiple indicators - """ - # In real implementation, would fetch market data - # For now, generate sample data - market_data = self._generate_market_data(lookback_days) - - # Calculate various regime indicators - trend_regime = self._detect_trend_regime(market_data) - volatility_regime = self._detect_volatility_regime(market_data) - momentum_regime = self._detect_momentum_regime(market_data) - - # Combine indicators for final regime - regime, confidence = self._combine_regime_indicators( - trend_regime, - volatility_regime, - momentum_regime - ) - - return { - 'regime': regime, - 'confidence': confidence, - 'indicators': { - 'trend': trend_regime, - 'volatility': volatility_regime, - 'momentum': momentum_regime, - 'market_breadth': self._calculate_market_breadth(market_data), - 'fear_greed_index': self._calculate_fear_greed_index(market_data) - }, - 'sub_regimes': { - 'trend_strength': self._calculate_trend_strength(market_data), - 'volatility_percentile': self._calculate_volatility_percentile(market_data), - 'correlation_regime': self._detect_correlation_regime(market_data) - } - } - - def _generate_market_data(self, days: int) -> pd.DataFrame: - """Generate sample market data for testing""" - dates = pd.date_range(end=datetime.now(), periods=days, freq='D') - - # Generate correlated returns for multiple assets - n_assets = 10 - returns = np.random.multivariate_normal( - mean=[0.0005] * n_assets, - cov=np.eye(n_assets) * 0.0004 + np.ones((n_assets, n_assets)) * 0.0001, - size=days - ) - - # Create price series - prices = pd.DataFrame( - (1 + returns).cumprod(axis=0) * 100, - index=dates, - columns=[f'Asset_{i}' for i in range(n_assets)] - ) - - # Add market index - prices['Market'] = prices.mean(axis=1) - - # Add volatility index (like VIX) - prices['Volatility'] = pd.Series(returns[:, 0]).rolling(20).std() * np.sqrt(252) * 100 - - return prices - - def _detect_trend_regime(self, data: pd.DataFrame) -> Dict: - """Detect trend regime using moving averages and linear regression""" - market = data['Market'] - - # Calculate moving averages - ma_short = market.rolling(20).mean() - ma_long = market.rolling(50).mean() - - # Trend strength - current_price = market.iloc[-1] - trend_score = (current_price - ma_long.iloc[-1]) / ma_long.iloc[-1] - - # Linear regression trend - x = np.arange(len(market)) - slope, _, r_value, _, _ = stats.linregress(x, market.values) - - # Determine regime - if trend_score > 0.05 and ma_short.iloc[-1] > ma_long.iloc[-1]: - regime = 'bull' - elif trend_score < -0.05 and ma_short.iloc[-1] < ma_long.iloc[-1]: - regime = 'bear' - else: - regime = 'sideways' - - return { - 'regime': regime, - 'trend_score': trend_score, - 'slope': slope, - 'r_squared': r_value ** 2 - } - - def _detect_volatility_regime(self, data: pd.DataFrame) -> Dict: - """Detect volatility regime using GARCH-like analysis""" - returns = data['Market'].pct_change().dropna() - - # Calculate rolling volatility - vol_short = returns.rolling(10).std() * np.sqrt(252) - vol_long = returns.rolling(30).std() * np.sqrt(252) - - current_vol = vol_short.iloc[-1] - vol_percentile = stats.percentileofscore(vol_long.dropna(), current_vol) - - # Volatility regime - if vol_percentile > 75: - regime = 'high_volatility' - elif vol_percentile < 25: - regime = 'low_volatility' - else: - regime = 'normal_volatility' - - # Volatility of volatility - vol_of_vol = vol_short.rolling(20).std().iloc[-1] - - return { - 'regime': regime, - 'current_volatility': current_vol, - 'volatility_percentile': vol_percentile, - 'vol_of_vol': vol_of_vol - } - - def _detect_momentum_regime(self, data: pd.DataFrame) -> Dict: - """Detect momentum regime using RSI and rate of change""" - market = data['Market'] - - # Calculate RSI - rsi = self._calculate_rsi(market, period=14) - - # Rate of change - roc_short = (market.iloc[-1] / market.iloc[-5] - 1) * 100 - roc_long = (market.iloc[-1] / market.iloc[-20] - 1) * 100 - - # Momentum regime - if rsi > 70 and roc_short > 0: - regime = 'overbought' - elif rsi < 30 and roc_short < 0: - regime = 'oversold' - elif roc_short > 2 and roc_long > 5: - regime = 'strong_momentum' - elif roc_short < -2 and roc_long < -5: - regime = 'weak_momentum' - else: - regime = 'neutral_momentum' - - return { - 'regime': regime, - 'rsi': rsi, - 'roc_short': roc_short, - 'roc_long': roc_long - } - - def _detect_correlation_regime(self, data: pd.DataFrame) -> str: - """Detect correlation regime among assets""" - # Calculate rolling correlation - asset_returns = data.iloc[:, :-2].pct_change().dropna() - corr_matrix = asset_returns.rolling(30).corr() - - # Average pairwise correlation - n_assets = len(asset_returns.columns) - avg_corr = (corr_matrix.sum().sum() - n_assets) / (n_assets * (n_assets - 1)) - current_avg_corr = avg_corr.iloc[-1] - - if current_avg_corr > 0.7: - return 'high_correlation' - elif current_avg_corr < 0.3: - return 'low_correlation' - else: - return 'normal_correlation' - - def _calculate_rsi(self, prices: pd.Series, period: int = 14) -> float: - """Calculate RSI""" - delta = prices.diff() - gain = (delta.where(delta > 0, 0)).rolling(period).mean() - loss = (-delta.where(delta < 0, 0)).rolling(period).mean() - - rs = gain / loss - rsi = 100 - (100 / (1 + rs)) - - return rsi.iloc[-1] - - def _calculate_market_breadth(self, data: pd.DataFrame) -> float: - """Calculate market breadth (advance/decline ratio)""" - # Calculate daily returns for all assets - returns = data.iloc[:, :-2].pct_change().iloc[-1] - - advancing = (returns > 0).sum() - declining = (returns < 0).sum() - - return advancing / (advancing + declining) if (advancing + declining) > 0 else 0.5 - - def _calculate_fear_greed_index(self, data: pd.DataFrame) -> float: - """Simplified fear & greed index""" - # Combine multiple indicators - volatility = data['Volatility'].iloc[-1] - momentum = self._detect_momentum_regime(data)['roc_short'] - breadth = self._calculate_market_breadth(data) - - # Normalize and combine - vol_score = 1 - min(volatility / 40, 1) # Lower vol = higher greed - momentum_score = (momentum + 10) / 20 # Normalize to 0-1 - - fear_greed = (vol_score + momentum_score + breadth) / 3 - - return fear_greed * 100 # 0 = extreme fear, 100 = extreme greed - - def _calculate_trend_strength(self, data: pd.DataFrame) -> float: - """Calculate trend strength using ADX-like indicator""" - market = data['Market'] - - # Calculate directional movement - high = market.rolling(2).max() - low = market.rolling(2).min() - - plus_dm = (high - high.shift(1)).where(lambda x: x > 0, 0) - minus_dm = (low.shift(1) - low).where(lambda x: x > 0, 0) - - # Smooth and normalize - period = 14 - plus_di = plus_dm.rolling(period).mean() / market.rolling(period).std() - minus_di = minus_dm.rolling(period).mean() / market.rolling(period).std() - - # Calculate trend strength - dx = abs(plus_di - minus_di) / (plus_di + minus_di) - adx = dx.rolling(period).mean().iloc[-1] - - return min(adx * 100, 100) if not np.isnan(adx) else 50 - - def _calculate_volatility_percentile(self, data: pd.DataFrame) -> float: - """Calculate current volatility percentile""" - volatility_regime = self._detect_volatility_regime(data) - return volatility_regime['volatility_percentile'] - - def _combine_regime_indicators( - self, - trend: Dict, - volatility: Dict, - momentum: Dict - ) -> Tuple[str, float]: - """Combine multiple indicators to determine overall regime""" - # Simple weighted combination - regimes = [] - weights = [] - - # Trend regime - if trend['regime'] in ['bull', 'bear']: - regimes.append(trend['regime']) - weights.append(abs(trend['trend_score']) * 10) - - # Volatility regime - if volatility['regime'] == 'high_volatility': - regimes.append('high_volatility') - weights.append(volatility['volatility_percentile'] / 100) - - # Choose dominant regime - if not regimes: - return 'sideways', 0.5 - - # Weight by confidence - dominant_idx = np.argmax(weights) - regime = regimes[dominant_idx] - confidence = min(weights[dominant_idx], 1.0) - - return regime, confidence \ No newline at end of file diff --git a/apps/stock/analytics/src/api/app.py b/apps/stock/analytics/src/api/app.py deleted file mode 100644 index f06635d0..00000000 --- a/apps/stock/analytics/src/api/app.py +++ /dev/null @@ -1,63 +0,0 @@ -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware -from contextlib import asynccontextmanager -import logging - -from .endpoints import optimization, analytics, models -from . import capabilities - -# Configure logging -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - -@asynccontextmanager -async def lifespan(app: FastAPI): - # Startup - logger.info("Starting Trading Analytics Service...") - # Initialize connections, load models, etc. - yield - # Shutdown - logger.info("Shutting down Trading Analytics Service...") - -# Create FastAPI app -app = FastAPI( - title="Trading Analytics Service", - description="Complex analytics, optimization, and ML inference for trading", - version="0.1.0", - lifespan=lifespan -) - -# Configure CORS -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], # Configure appropriately for production - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -# Include routers -app.include_router(optimization.router, prefix="/optimize", tags=["optimization"]) -app.include_router(analytics.router, prefix="/analytics", tags=["analytics"]) -app.include_router(models.router, prefix="/models", tags=["models"]) - -@app.get("/") -async def root(): - return { - "service": "Trading Analytics", - "status": "available", - "version": "0.1.0" - } - -@app.get("/health") -async def health_check(): - return { - "status": "degraded", - "components": { - "performance_analyzer": {"status": "unavailable", "reason": "observed_data_not_integrated"}, - "regime_detector": {"status": "unavailable", "reason": "observed_data_not_integrated"}, - "portfolio_optimizer": capabilities.portfolio_optimizer.status(), - "model_runtime": capabilities.model_runtime.status(), - "model_upload": capabilities.model_upload.status(), - } - } diff --git a/apps/stock/analytics/src/api/capabilities.py b/apps/stock/analytics/src/api/capabilities.py deleted file mode 100644 index 0ee0e0a2..00000000 --- a/apps/stock/analytics/src/api/capabilities.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Optional runtimes are loaded on first use, independently of app/router imports.""" -from dataclasses import dataclass -import logging -from threading import Lock -from typing import Any, Callable - -from fastapi import HTTPException - -logger = logging.getLogger(__name__) - - -class LazyCapability: - def __init__(self, name: str, load: Callable[[], Any]): - self.name = name - self.load = load - self._lock = Lock() - self._value = None - self._state = "uninitialized" - self._failure = None - - def get(self): - with self._lock: - if self._state == "uninitialized": - try: - self._value = self.load() - self._state = "ready" - except Exception as error: - logger.exception("Optional capability %s could not initialize", self.name) - self._state = "unavailable" - self._failure = { - "code": "analytics_capability_unavailable", - "capability": self.name, - "reason": "missing_dependency" if isinstance(error, ImportError) else "initialization_failed", - "message": f"Optional analytics capability '{self.name}' is unavailable", - } - if isinstance(error, ImportError) and error.name: - self._failure["dependency"] = error.name - if self._failure is not None: - raise HTTPException(status_code=503, detail=dict(self._failure)) - return self._value - - def status(self): - # Health observes state; it must not load scientific runtimes as a side effect. - with self._lock: - return {"status": self._state, **(self._failure or {})} - - -@dataclass(frozen=True) -class OptimizationRuntime: - numpy: Any - optimizer: Any - - -@dataclass(frozen=True) -class ModelRuntime: - numpy: Any - onnx: Any - - -def _load_optimizer(): - import numpy - from ..optimization.portfolio_optimizer import PortfolioOptimizer - return OptimizationRuntime(numpy, PortfolioOptimizer()) - - -def _load_models(): - import numpy - import onnxruntime - return ModelRuntime(numpy, onnxruntime) - - -def _load_multipart(): - # FastAPI's File(...) would demand this package while registering the route. - from multipart.multipart import parse_options_header - return parse_options_header - - -portfolio_optimizer = LazyCapability("portfolio_optimizer", _load_optimizer) -model_runtime = LazyCapability("model_runtime", _load_models) -model_upload = LazyCapability("model_upload", _load_multipart) - - -def get_optimization_runtime(): - return portfolio_optimizer.get() - - -def get_model_runtime(): - return model_runtime.get() diff --git a/apps/stock/analytics/src/api/endpoints/analytics.py b/apps/stock/analytics/src/api/endpoints/analytics.py deleted file mode 100644 index 33053b5a..00000000 --- a/apps/stock/analytics/src/api/endpoints/analytics.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Observed-data endpoints fail closed until an actual portfolio/history adapter exists. - -Optimization and loaded-model prediction use their own caller/model inputs. These routes -must not turn random samples, placeholder attributions or constant reports into observations. -""" -from datetime import date, datetime -from typing import List, NoReturn, Optional - -from fastapi import APIRouter, HTTPException, Query - -router = APIRouter() - - -def unavailable() -> NoReturn: - raise HTTPException( - status_code=503, - detail={ - "code": "analytics_data_unavailable", - "message": "Observed portfolio, benchmark and backtest data are not integrated", - }, - ) - - -@router.get("/performance/{portfolio_id}") -async def get_performance_metrics( - portfolio_id: str, - start_date: datetime = Query(...), - end_date: datetime = Query(...), -): - if end_date <= start_date: - raise HTTPException(status_code=400, detail="end_date must follow start_date") - unavailable() - - -@router.get("/risk/{portfolio_id}") -async def get_risk_metrics(portfolio_id: str, window: int = Query(252, ge=1)): - unavailable() - - -@router.get("/regime") -async def detect_market_regime(lookback_days: int = Query(60, ge=1)): - unavailable() - - -@router.post("/correlation") -async def calculate_correlation_matrix( - symbols: List[str], - start_date: Optional[date] = None, - end_date: Optional[date] = None, - method: str = Query("pearson", pattern="^(pearson|spearman|kendall)$"), -): - if len(symbols) < 2 or len(set(symbols)) != len(symbols): - raise HTTPException(status_code=400, detail="At least two distinct symbols are required") - unavailable() - - -@router.get("/backtest/{backtest_id}") -async def analyze_backtest_results(backtest_id: str): - unavailable() - - -@router.post("/attribution") -async def performance_attribution( - portfolio_id: str, - benchmark: str, - start_date: date, - end_date: date, - method: str = Query("brinson", pattern="^(brinson|factor|risk)$"), -): - if end_date <= start_date: - raise HTTPException(status_code=400, detail="end_date must follow start_date") - unavailable() diff --git a/apps/stock/analytics/src/api/endpoints/models.py b/apps/stock/analytics/src/api/endpoints/models.py deleted file mode 100644 index 44aabb78..00000000 --- a/apps/stock/analytics/src/api/endpoints/models.py +++ /dev/null @@ -1,211 +0,0 @@ -from fastapi import APIRouter, HTTPException, Request -from starlette.datastructures import UploadFile -from starlette.exceptions import HTTPException as StarletteHTTPException -from pydantic import BaseModel -from typing import Dict, Any, List, Optional, Union -import json -import logging - -from ..capabilities import get_model_runtime, model_upload - -logger = logging.getLogger(__name__) - -router = APIRouter() - -# In-memory model storage (in production, use proper model registry) -loaded_models = {} - -class PredictionRequest(BaseModel): - model_id: str - features: Dict[str, float] - -class PredictionResponse(BaseModel): - model_id: str - prediction: float - probability: Optional[Dict[str, float]] = None - metadata: Optional[Dict[str, Any]] = None - -class ModelInfo(BaseModel): - model_id: str - name: str - version: str - type: str - input_features: List[str] - # One shape per ONNX output; dimensions may be symbolic or unspecified. - output_shape: List[List[Union[int, str, None]]] - metadata: Dict[str, Any] - -@router.post("/predict", response_model=PredictionResponse) -async def predict(request: PredictionRequest): - """ - Run inference on a loaded model - """ - try: - if request.model_id not in loaded_models: - raise HTTPException(status_code=404, detail=f"Model {request.model_id} not found") - np = get_model_runtime().numpy - - model_info = loaded_models[request.model_id] - session = model_info['session'] - - # Prepare input - input_features = model_info['input_features'] - input_array = np.array([[request.features.get(f, 0.0) for f in input_features]], dtype=np.float32) - - # Run inference - input_name = session.get_inputs()[0].name - output = session.run(None, {input_name: input_array}) - - # Process output - prediction = float(output[0][0]) - - # For classification models, get probabilities - probability = None - if model_info['type'] == 'classification' and len(output[0][0]) > 1: - probability = { - f"class_{i}": float(p) - for i, p in enumerate(output[0][0]) - } - - return PredictionResponse( - model_id=request.model_id, - prediction=prediction, - probability=probability, - metadata={ - "model_version": model_info['version'], - "timestamp": np.datetime64('now').tolist() - } - ) - - except StarletteHTTPException: - raise - except Exception as e: - logger.error(f"Prediction failed: {str(e)}") - raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}") - -@router.post("/load", openapi_extra={ - "requestBody": { - "required": True, - "content": {"multipart/form-data": {"schema": { - "type": "object", - "required": ["model_file"], - "properties": {"model_file": {"type": "string", "format": "binary"}}, - }}}, - }, -}) -async def load_model( - model_id: str, - request: Request, - metadata: str = None -): - """ - Load an ONNX model for inference - """ - try: - runtime = get_model_runtime() - model_upload.get() - # Parse only on upload, so an absent multipart package cannot block app startup. - async with request.form() as form: - model_file = form.get('model_file') - if not isinstance(model_file, UploadFile): - raise HTTPException(status_code=422, detail=[{ - "loc": ["body", "model_file"], - "msg": "A model_file upload is required", - "type": "value_error.missing", - }]) - content = await model_file.read() - - # Create ONNX session - session = runtime.onnx.InferenceSession(content) - - # Parse metadata - model_metadata = json.loads(metadata) if metadata else {} - - # Extract model info - input_features = [inp.name for inp in session.get_inputs()] - output_shape = [out.shape for out in session.get_outputs()] - - # Store model - loaded_models[model_id] = { - 'session': session, - 'input_features': model_metadata.get('feature_names', input_features), - 'type': model_metadata.get('model_type', 'regression'), - 'version': model_metadata.get('version', '1.0'), - 'metadata': model_metadata - } - - return { - "message": f"Model {model_id} loaded successfully", - "input_features": input_features, - "output_shape": output_shape - } - - except StarletteHTTPException: - raise - except Exception as e: - logger.error(f"Failed to load model: {str(e)}") - raise HTTPException(status_code=500, detail=f"Failed to load model: {str(e)}") - -@router.get("/list", response_model=List[ModelInfo]) -async def list_models(): - """ - List all loaded models - """ - models = [] - - for model_id, info in loaded_models.items(): - session = info['session'] - models.append(ModelInfo( - model_id=model_id, - name=info['metadata'].get('name', model_id), - version=info['version'], - type=info['type'], - input_features=info['input_features'], - output_shape=[out.shape for out in session.get_outputs()], - metadata=info['metadata'] - )) - - return models - -@router.delete("/{model_id}") -async def unload_model(model_id: str): - """ - Unload a model from memory - """ - if model_id not in loaded_models: - raise HTTPException(status_code=404, detail=f"Model {model_id} not found") - - del loaded_models[model_id] - - return {"message": f"Model {model_id} unloaded successfully"} - -@router.post("/batch_predict") -async def batch_predict( - model_id: str, - features: List[Dict[str, float]] -): - """ - Run batch predictions - """ - try: - if model_id not in loaded_models: - raise HTTPException(status_code=404, detail=f"Model {model_id} not found") - - predictions = [] - - for feature_set in features: - request = PredictionRequest(model_id=model_id, features=feature_set) - result = await predict(request) - predictions.append(result.dict()) - - return { - "model_id": model_id, - "predictions": predictions, - "count": len(predictions) - } - - except StarletteHTTPException: - raise - except Exception as e: - logger.error(f"Batch prediction failed: {str(e)}") - raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}") diff --git a/apps/stock/analytics/src/api/endpoints/optimization.py b/apps/stock/analytics/src/api/endpoints/optimization.py deleted file mode 100644 index 0ee44add..00000000 --- a/apps/stock/analytics/src/api/endpoints/optimization.py +++ /dev/null @@ -1,120 +0,0 @@ -from fastapi import APIRouter, HTTPException, Depends -from pydantic import BaseModel, Field -from typing import List, Optional, Dict - -from ..capabilities import OptimizationRuntime, get_optimization_runtime - -router = APIRouter() - -class OptimizationConstraints(BaseModel): - min_weight: Optional[float] = Field(0.0, ge=0.0, le=1.0) - max_weight: Optional[float] = Field(1.0, ge=0.0, le=1.0) - target_return: Optional[float] = None - max_risk: Optional[float] = None - -class PortfolioOptimizationRequest(BaseModel): - symbols: List[str] - returns: List[List[float]] - constraints: Optional[OptimizationConstraints] = None - method: str = Field("mean_variance", pattern="^(mean_variance|min_variance|max_sharpe|risk_parity|black_litterman)$") - -class PortfolioWeights(BaseModel): - symbols: List[str] - weights: List[float] - expected_return: float - expected_risk: float - sharpe_ratio: float - -@router.post("/portfolio", response_model=PortfolioWeights) -async def optimize_portfolio( - request: PortfolioOptimizationRequest, - runtime: OptimizationRuntime = Depends(get_optimization_runtime) -): - """ - Optimize portfolio weights using various methods - """ - try: - # Convert returns to numpy array - returns_array = runtime.numpy.array(request.returns) - - # Validate dimensions - if len(request.symbols) != returns_array.shape[1]: - raise HTTPException( - status_code=400, - detail="Number of symbols must match number of return columns" - ) - - # Run optimization - result = runtime.optimizer.optimize( - returns=returns_array, - method=request.method, - constraints=request.constraints.dict() if request.constraints else None - ) - - return PortfolioWeights( - symbols=request.symbols, - weights=result['weights'].tolist(), - expected_return=float(result['expected_return']), - expected_risk=float(result['expected_risk']), - sharpe_ratio=float(result['sharpe_ratio']) - ) - - except HTTPException: - raise - except ValueError as e: - raise HTTPException(status_code=400, detail=str(e)) - except Exception as e: - raise HTTPException(status_code=500, detail=f"Optimization failed: {str(e)}") - -@router.post("/efficient_frontier") -async def calculate_efficient_frontier( - request: PortfolioOptimizationRequest, - num_portfolios: int = 100, - runtime: OptimizationRuntime = Depends(get_optimization_runtime) -): - """ - Calculate the efficient frontier for a set of assets - """ - try: - returns_array = runtime.numpy.array(request.returns) - - frontier = runtime.optimizer.calculate_efficient_frontier( - returns=returns_array, - num_portfolios=num_portfolios - ) - - return { - "symbols": request.symbols, - "frontier": frontier - } - - except Exception as e: - raise HTTPException(status_code=500, detail=f"Failed to calculate efficient frontier: {str(e)}") - -@router.post("/rebalance") -async def suggest_rebalance( - current_weights: Dict[str, float], - target_weights: Dict[str, float], - constraints: Optional[Dict[str, float]] = None -): - """ - Suggest trades to rebalance portfolio from current to target weights - """ - try: - # Calculate differences - trades = {} - for symbol in target_weights: - current = current_weights.get(symbol, 0.0) - target = target_weights[symbol] - diff = target - current - - if abs(diff) > 0.001: # Ignore tiny differences - trades[symbol] = diff - - return { - "trades": trades, - "total_turnover": sum(abs(t) for t in trades.values()) - } - - except Exception as e: - raise HTTPException(status_code=500, detail=f"Rebalance calculation failed: {str(e)}") diff --git a/apps/stock/analytics/src/ml/feature_engineering.py b/apps/stock/analytics/src/ml/feature_engineering.py deleted file mode 100644 index bd0c755a..00000000 --- a/apps/stock/analytics/src/ml/feature_engineering.py +++ /dev/null @@ -1,481 +0,0 @@ -import numpy as np -import pandas as pd -from typing import Dict, List, Tuple, Optional, Union -import talib -from scipy import stats -from sklearn.preprocessing import StandardScaler, RobustScaler -import logging - -logger = logging.getLogger(__name__) - -class FeatureEngineer: - """ - Feature engineering for financial ML models - """ - - def __init__(self, lookback_periods: List[int] = None): - self.lookback_periods = lookback_periods or [5, 10, 20, 50, 100, 200] - self.scaler = RobustScaler() # Robust to outliers - self.feature_names: List[str] = [] - - def create_features( - self, - data: pd.DataFrame, - include_technical: bool = True, - include_microstructure: bool = True, - include_fundamental: bool = False, - include_sentiment: bool = False - ) -> pd.DataFrame: - """ - Create comprehensive feature set for ML models - """ - features = pd.DataFrame(index=data.index) - - # Price-based features - logger.info("Creating price-based features...") - price_features = self._create_price_features(data) - features = pd.concat([features, price_features], axis=1) - - # Technical indicators - if include_technical: - logger.info("Creating technical indicators...") - tech_features = self._create_technical_features(data) - features = pd.concat([features, tech_features], axis=1) - - # Microstructure features - if include_microstructure: - logger.info("Creating microstructure features...") - micro_features = self._create_microstructure_features(data) - features = pd.concat([features, micro_features], axis=1) - - # Fundamental features (if available) - if include_fundamental and 'earnings' in data.columns: - logger.info("Creating fundamental features...") - fund_features = self._create_fundamental_features(data) - features = pd.concat([features, fund_features], axis=1) - - # Sentiment features (if available) - if include_sentiment and 'sentiment' in data.columns: - logger.info("Creating sentiment features...") - sent_features = self._create_sentiment_features(data) - features = pd.concat([features, sent_features], axis=1) - - # Time-based features - logger.info("Creating time-based features...") - time_features = self._create_time_features(data) - features = pd.concat([features, time_features], axis=1) - - # Cross-sectional features (if multiple symbols) - if 'symbol' in data.columns and data['symbol'].nunique() > 1: - logger.info("Creating cross-sectional features...") - cross_features = self._create_cross_sectional_features(data) - features = pd.concat([features, cross_features], axis=1) - - # Store feature names - self.feature_names = features.columns.tolist() - - # Handle missing values - features = self._handle_missing_values(features) - - return features - - def _create_price_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create price-based features""" - features = pd.DataFrame(index=data.index) - - # Returns at different horizons - for period in self.lookback_periods: - features[f'returns_{period}'] = data['close'].pct_change(period) - features[f'log_returns_{period}'] = np.log(data['close'] / data['close'].shift(period)) - - # Price ratios - features['high_low_ratio'] = data['high'] / data['low'] - features['close_open_ratio'] = data['close'] / data['open'] - - # Price position in range - features['price_position'] = (data['close'] - data['low']) / (data['high'] - data['low']).replace(0, np.nan) - - # Volume-weighted metrics - if 'volume' in data.columns: - features['vwap'] = (data['close'] * data['volume']).rolling(20).sum() / data['volume'].rolling(20).sum() - features['volume_ratio'] = data['volume'] / data['volume'].rolling(20).mean() - features['dollar_volume'] = data['close'] * data['volume'] - - # Volatility measures - for period in [5, 20, 50]: - features[f'volatility_{period}'] = data['close'].pct_change().rolling(period).std() * np.sqrt(252) - features[f'realized_var_{period}'] = (data['close'].pct_change() ** 2).rolling(period).sum() - - # Price momentum - features['momentum_1m'] = data['close'] / data['close'].shift(20) - 1 - features['momentum_3m'] = data['close'] / data['close'].shift(60) - 1 - features['momentum_6m'] = data['close'] / data['close'].shift(120) - 1 - - # Relative strength - for short, long in [(10, 30), (20, 50), (50, 200)]: - features[f'rs_{short}_{long}'] = ( - data['close'].rolling(short).mean() / - data['close'].rolling(long).mean() - ) - - return features - - def _create_technical_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create technical indicator features""" - features = pd.DataFrame(index=data.index) - - # Moving averages - for period in self.lookback_periods: - sma = talib.SMA(data['close'].values, timeperiod=period) - ema = talib.EMA(data['close'].values, timeperiod=period) - features[f'sma_{period}'] = sma - features[f'ema_{period}'] = ema - features[f'price_to_sma_{period}'] = data['close'] / sma - - # Bollinger Bands - for period in [20, 50]: - upper, middle, lower = talib.BBANDS( - data['close'].values, - timeperiod=period, - nbdevup=2, - nbdevdn=2 - ) - features[f'bb_upper_{period}'] = upper - features[f'bb_lower_{period}'] = lower - features[f'bb_width_{period}'] = (upper - lower) / middle - features[f'bb_position_{period}'] = (data['close'] - lower) / (upper - lower) - - # RSI - for period in [14, 28]: - features[f'rsi_{period}'] = talib.RSI(data['close'].values, timeperiod=period) - - # MACD - macd, signal, hist = talib.MACD(data['close'].values) - features['macd'] = macd - features['macd_signal'] = signal - features['macd_hist'] = hist - - # Stochastic - slowk, slowd = talib.STOCH( - data['high'].values, - data['low'].values, - data['close'].values - ) - features['stoch_k'] = slowk - features['stoch_d'] = slowd - - # ADX (Average Directional Index) - features['adx'] = talib.ADX( - data['high'].values, - data['low'].values, - data['close'].values - ) - - # ATR (Average True Range) - for period in [14, 20]: - features[f'atr_{period}'] = talib.ATR( - data['high'].values, - data['low'].values, - data['close'].values, - timeperiod=period - ) - - # CCI (Commodity Channel Index) - features['cci'] = talib.CCI( - data['high'].values, - data['low'].values, - data['close'].values - ) - - # Williams %R - features['williams_r'] = talib.WILLR( - data['high'].values, - data['low'].values, - data['close'].values - ) - - # OBV (On Balance Volume) - if 'volume' in data.columns: - features['obv'] = talib.OBV(data['close'].values, data['volume'].values) - features['obv_ema'] = talib.EMA(features['obv'].values, timeperiod=20) - - return features - - def _create_microstructure_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create market microstructure features""" - features = pd.DataFrame(index=data.index) - - # Spread estimation (using high-low) - features['hl_spread'] = 2 * (data['high'] - data['low']) / (data['high'] + data['low']) - features['hl_spread_ma'] = features['hl_spread'].rolling(20).mean() - - # Roll's implied spread - if len(data) > 2: - returns = data['close'].pct_change() - features['roll_spread'] = 2 * np.sqrt(-returns.rolling(20).cov(returns.shift(1))) - - # Amihud illiquidity - if 'volume' in data.columns: - features['amihud'] = (returns.abs() / (data['volume'] * data['close'])).rolling(20).mean() * 1e6 - features['log_amihud'] = np.log(features['amihud'].replace(0, np.nan) + 1e-10) - - # Kyle's lambda (price impact) - if 'volume' in data.columns: - # Simplified version using rolling regression - for period in [20, 50]: - price_changes = data['close'].pct_change() - signed_volume = data['volume'] * np.sign(price_changes) - - # Rolling correlation as proxy for Kyle's lambda - features[f'kyle_lambda_{period}'] = ( - price_changes.rolling(period).corr(signed_volume) * - price_changes.rolling(period).std() / - signed_volume.rolling(period).std() - ) - - # Intraday patterns - if 'timestamp' in data.columns: - data['hour'] = pd.to_datetime(data['timestamp']).dt.hour - data['minute'] = pd.to_datetime(data['timestamp']).dt.minute - - # Time since market open (assuming 9:30 AM open) - features['minutes_since_open'] = (data['hour'] - 9) * 60 + data['minute'] - 30 - features['minutes_to_close'] = 390 - features['minutes_since_open'] # 6.5 hour day - - # Normalized time of day - features['time_of_day_norm'] = features['minutes_since_open'] / 390 - - # Order flow imbalance proxy - features['high_low_imbalance'] = (data['high'] - data['close']) / (data['close'] - data['low'] + 1e-10) - features['close_position_in_range'] = (data['close'] - data['low']) / (data['high'] - data['low'] + 1e-10) - - return features - - def _create_fundamental_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create fundamental analysis features""" - features = pd.DataFrame(index=data.index) - - # Price to earnings - if 'earnings' in data.columns: - features['pe_ratio'] = data['close'] / data['earnings'] - features['earnings_yield'] = data['earnings'] / data['close'] - features['pe_relative'] = features['pe_ratio'] / features['pe_ratio'].rolling(252).mean() - - # Price to book - if 'book_value' in data.columns: - features['pb_ratio'] = data['close'] / data['book_value'] - features['pb_relative'] = features['pb_ratio'] / features['pb_ratio'].rolling(252).mean() - - # Dividend yield - if 'dividends' in data.columns: - features['dividend_yield'] = data['dividends'].rolling(252).sum() / data['close'] - features['dividend_growth'] = data['dividends'].pct_change(252) - - # Sales/Revenue metrics - if 'revenue' in data.columns: - features['price_to_sales'] = data['close'] * data['shares_outstanding'] / data['revenue'] - features['revenue_growth'] = data['revenue'].pct_change(4) # YoY for quarterly - - # Profitability metrics - if 'net_income' in data.columns and 'total_assets' in data.columns: - features['roe'] = data['net_income'] / data['shareholders_equity'] - features['roa'] = data['net_income'] / data['total_assets'] - features['profit_margin'] = data['net_income'] / data['revenue'] - - return features - - def _create_sentiment_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create sentiment-based features""" - features = pd.DataFrame(index=data.index) - - if 'sentiment' in data.columns: - # Raw sentiment - features['sentiment'] = data['sentiment'] - features['sentiment_ma'] = data['sentiment'].rolling(20).mean() - features['sentiment_std'] = data['sentiment'].rolling(20).std() - - # Sentiment momentum - features['sentiment_change'] = data['sentiment'].pct_change(5) - features['sentiment_momentum'] = data['sentiment'] - data['sentiment'].shift(20) - - # Sentiment extremes - features['sentiment_zscore'] = ( - (data['sentiment'] - features['sentiment_ma']) / - features['sentiment_std'] - ) - - # Sentiment divergence from price - price_zscore = (data['close'] - data['close'].rolling(20).mean()) / data['close'].rolling(20).std() - features['sentiment_price_divergence'] = features['sentiment_zscore'] - price_zscore - - # News volume features - if 'news_count' in data.columns: - features['news_volume'] = data['news_count'] - features['news_volume_ma'] = data['news_count'].rolling(5).mean() - features['news_spike'] = data['news_count'] / features['news_volume_ma'] - - # Social media features - if 'twitter_mentions' in data.columns: - features['social_volume'] = data['twitter_mentions'] - features['social_momentum'] = data['twitter_mentions'].pct_change(1) - features['social_vs_avg'] = data['twitter_mentions'] / data['twitter_mentions'].rolling(20).mean() - - return features - - def _create_time_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create time-based features""" - features = pd.DataFrame(index=data.index) - - if 'timestamp' in data.columns: - timestamps = pd.to_datetime(data['timestamp']) - - # Day of week - features['day_of_week'] = timestamps.dt.dayofweek - features['is_monday'] = (features['day_of_week'] == 0).astype(int) - features['is_friday'] = (features['day_of_week'] == 4).astype(int) - - # Month - features['month'] = timestamps.dt.month - features['is_quarter_end'] = timestamps.dt.month.isin([3, 6, 9, 12]).astype(int) - features['is_year_end'] = timestamps.dt.month.eq(12).astype(int) - - # Trading day in month - features['trading_day_of_month'] = timestamps.dt.day - features['trading_day_of_year'] = timestamps.dt.dayofyear - - # Seasonality features - features['sin_day_of_year'] = np.sin(2 * np.pi * features['trading_day_of_year'] / 365) - features['cos_day_of_year'] = np.cos(2 * np.pi * features['trading_day_of_year'] / 365) - - # Options expiration week (third Friday) - features['is_opex_week'] = self._is_options_expiration_week(timestamps) - - # Fed meeting weeks (approximate) - features['is_fed_week'] = self._is_fed_meeting_week(timestamps) - - return features - - def _create_cross_sectional_features(self, data: pd.DataFrame) -> pd.DataFrame: - """Create features comparing across multiple symbols""" - features = pd.DataFrame(index=data.index) - - # Calculate market averages - market_returns = data.groupby('timestamp')['close'].mean().pct_change() - market_volume = data.groupby('timestamp')['volume'].mean() - - # Relative performance - data['returns'] = data.groupby('symbol')['close'].pct_change() - features['relative_returns'] = data['returns'] - market_returns[data['timestamp']].values - features['relative_volume'] = data['volume'] / market_volume[data['timestamp']].values - - # Sector/market correlation - for period in [20, 50]: - rolling_corr = data.groupby('symbol')['returns'].rolling(period).corr(market_returns) - features[f'market_correlation_{period}'] = rolling_corr - - # Cross-sectional momentum - features['cross_sectional_rank'] = data.groupby('timestamp')['returns'].rank(pct=True) - - return features - - def _handle_missing_values(self, features: pd.DataFrame) -> pd.DataFrame: - """Handle missing values in features""" - # Forward fill for small gaps - features = features.fillna(method='ffill', limit=5) - - # For remaining NaNs, use median of non-missing values - for col in features.columns: - if features[col].isna().any(): - median_val = features[col].median() - features[col].fillna(median_val, inplace=True) - - # Replace any infinities - features = features.replace([np.inf, -np.inf], np.nan) - features = features.fillna(0) - - return features - - def _is_options_expiration_week(self, timestamps: pd.Series) -> pd.Series: - """Identify options expiration weeks (third Friday of month)""" - # This is a simplified version - is_third_week = (timestamps.dt.day >= 15) & (timestamps.dt.day <= 21) - is_friday = timestamps.dt.dayofweek == 4 - return (is_third_week & is_friday).astype(int) - - def _is_fed_meeting_week(self, timestamps: pd.Series) -> pd.Series: - """Identify approximate Fed meeting weeks""" - # Fed typically meets 8 times per year, roughly every 6 weeks - # This is a simplified approximation - week_of_year = timestamps.dt.isocalendar().week - return (week_of_year % 6 == 0).astype(int) - - def transform_features( - self, - features: pd.DataFrame, - method: str = 'robust', - clip_outliers: bool = True, - clip_quantile: float = 0.01 - ) -> pd.DataFrame: - """ - Transform features for ML models - """ - transformed = features.copy() - - # Clip outliers if requested - if clip_outliers: - lower = features.quantile(clip_quantile) - upper = features.quantile(1 - clip_quantile) - transformed = features.clip(lower=lower, upper=upper, axis=1) - - # Scale features - if method == 'robust': - scaler = RobustScaler() - elif method == 'standard': - scaler = StandardScaler() - else: - raise ValueError(f"Unknown scaling method: {method}") - - scaled_values = scaler.fit_transform(transformed) - transformed = pd.DataFrame( - scaled_values, - index=features.index, - columns=features.columns - ) - - self.scaler = scaler - - return transformed - - def get_feature_importance( - self, - features: pd.DataFrame, - target: pd.Series, - method: str = 'mutual_info' - ) -> pd.DataFrame: - """ - Calculate feature importance scores - """ - importance_scores = {} - - if method == 'mutual_info': - from sklearn.feature_selection import mutual_info_regression - scores = mutual_info_regression(features, target) - importance_scores['mutual_info'] = scores - - elif method == 'correlation': - scores = features.corrwith(target).abs() - importance_scores['correlation'] = scores.values - - elif method == 'random_forest': - from sklearn.ensemble import RandomForestRegressor - rf = RandomForestRegressor(n_estimators=100, random_state=42) - rf.fit(features, target) - importance_scores['rf_importance'] = rf.feature_importances_ - - # Create DataFrame with results - importance_df = pd.DataFrame( - importance_scores, - index=features.columns - ).sort_values(by=list(importance_scores.keys())[0], ascending=False) - - return importance_df \ No newline at end of file diff --git a/apps/stock/analytics/src/optimization/portfolio_optimizer.py b/apps/stock/analytics/src/optimization/portfolio_optimizer.py deleted file mode 100644 index 22ac8705..00000000 --- a/apps/stock/analytics/src/optimization/portfolio_optimizer.py +++ /dev/null @@ -1,354 +0,0 @@ -import numpy as np -import pandas as pd -import cvxpy as cp -from typing import Dict, List, Optional, Tuple -import logging - -logger = logging.getLogger(__name__) - -class PortfolioOptimizer: - """ - Portfolio optimization using various methods - """ - - def __init__(self, risk_free_rate: float = 0.02): - self.risk_free_rate = risk_free_rate - - def optimize( - self, - returns: np.ndarray, - method: str = 'mean_variance', - constraints: Optional[Dict] = None - ) -> Dict: - """ - Optimize portfolio weights using specified method - """ - if method == 'mean_variance': - return self._mean_variance_optimization(returns, constraints) - elif method == 'min_variance': - return self._minimum_variance_optimization(returns, constraints) - elif method == 'max_sharpe': - return self._maximum_sharpe_optimization(returns, constraints) - elif method == 'risk_parity': - return self._risk_parity_optimization(returns) - elif method == 'black_litterman': - return self._black_litterman_optimization(returns, constraints) - else: - raise ValueError(f"Unknown optimization method: {method}") - - def _mean_variance_optimization( - self, - returns: np.ndarray, - constraints: Optional[Dict] = None - ) -> Dict: - """ - Classical Markowitz mean-variance optimization - """ - n_assets = returns.shape[1] - - # Calculate expected returns and covariance - expected_returns = np.mean(returns, axis=0) - cov_matrix = np.cov(returns.T) - - # Add small value to diagonal for numerical stability - cov_matrix += np.eye(n_assets) * 1e-6 - - # Define optimization variables - weights = cp.Variable(n_assets) - - # Define objective (maximize return - lambda * risk) - risk_aversion = 2.0 # Can be parameterized - portfolio_return = expected_returns @ weights - portfolio_risk = cp.quad_form(weights, cov_matrix) - - objective = cp.Maximize(portfolio_return - risk_aversion * portfolio_risk) - - # Define constraints - constraints_list = [ - cp.sum(weights) == 1, # Weights sum to 1 - weights >= 0, # No short selling (can be relaxed) - ] - - # Add custom constraints - if constraints: - if 'min_weight' in constraints: - constraints_list.append(weights >= constraints['min_weight']) - if 'max_weight' in constraints: - constraints_list.append(weights <= constraints['max_weight']) - if 'target_return' in constraints: - constraints_list.append(portfolio_return >= constraints['target_return']) - if 'max_risk' in constraints: - max_variance = constraints['max_risk'] ** 2 - constraints_list.append(portfolio_risk <= max_variance) - - # Solve optimization - problem = cp.Problem(objective, constraints_list) - problem.solve() - - if problem.status != 'optimal': - logger.warning(f"Optimization status: {problem.status}") - # Return equal weights as fallback - weights_array = np.ones(n_assets) / n_assets - else: - weights_array = weights.value - - # Calculate portfolio metrics - portfolio_return = expected_returns @ weights_array - portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array) - sharpe_ratio = (portfolio_return - self.risk_free_rate) / portfolio_risk - - return { - 'weights': weights_array, - 'expected_return': portfolio_return * 252, # Annualized - 'expected_risk': portfolio_risk * np.sqrt(252), # Annualized - 'sharpe_ratio': sharpe_ratio * np.sqrt(252) - } - - def _minimum_variance_optimization( - self, - returns: np.ndarray, - constraints: Optional[Dict] = None - ) -> Dict: - """ - Minimize portfolio variance - """ - n_assets = returns.shape[1] - cov_matrix = np.cov(returns.T) - cov_matrix += np.eye(n_assets) * 1e-6 - - # Define optimization - weights = cp.Variable(n_assets) - portfolio_risk = cp.quad_form(weights, cov_matrix) - - objective = cp.Minimize(portfolio_risk) - - constraints_list = [ - cp.sum(weights) == 1, - weights >= 0, - ] - - # Solve - problem = cp.Problem(objective, constraints_list) - problem.solve() - - weights_array = weights.value if problem.status == 'optimal' else np.ones(n_assets) / n_assets - - # Calculate metrics - expected_returns = np.mean(returns, axis=0) - portfolio_return = expected_returns @ weights_array - portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array) - sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk - - return { - 'weights': weights_array, - 'expected_return': portfolio_return * 252, - 'expected_risk': portfolio_risk * np.sqrt(252), - 'sharpe_ratio': sharpe_ratio * np.sqrt(252) - } - - def _maximum_sharpe_optimization( - self, - returns: np.ndarray, - constraints: Optional[Dict] = None - ) -> Dict: - """ - Maximize Sharpe ratio - """ - # This is a bit tricky as Sharpe ratio is not convex - # We use a trick: for each target return, find min variance - # Then select the portfolio with highest Sharpe - - n_assets = returns.shape[1] - expected_returns = np.mean(returns, axis=0) - cov_matrix = np.cov(returns.T) - - # Generate efficient frontier - target_returns = np.linspace( - np.min(expected_returns), - np.max(expected_returns), - 50 - ) - - best_sharpe = -np.inf - best_weights = None - - for target_ret in target_returns: - weights = cp.Variable(n_assets) - portfolio_risk = cp.quad_form(weights, cov_matrix) - - objective = cp.Minimize(portfolio_risk) - constraints_list = [ - cp.sum(weights) == 1, - weights >= 0, - expected_returns @ weights >= target_ret - ] - - problem = cp.Problem(objective, constraints_list) - problem.solve() - - if problem.status == 'optimal': - w = weights.value - ret = expected_returns @ w - risk = np.sqrt(w @ cov_matrix @ w) - sharpe = (ret - self.risk_free_rate / 252) / risk - - if sharpe > best_sharpe: - best_sharpe = sharpe - best_weights = w - - if best_weights is None: - best_weights = np.ones(n_assets) / n_assets - - # Calculate final metrics - portfolio_return = expected_returns @ best_weights - portfolio_risk = np.sqrt(best_weights @ cov_matrix @ best_weights) - - return { - 'weights': best_weights, - 'expected_return': portfolio_return * 252, - 'expected_risk': portfolio_risk * np.sqrt(252), - 'sharpe_ratio': best_sharpe * np.sqrt(252) - } - - def _risk_parity_optimization(self, returns: np.ndarray) -> Dict: - """ - Risk parity optimization - equal risk contribution - """ - n_assets = returns.shape[1] - cov_matrix = np.cov(returns.T) - - # Initial guess - equal weights - weights = np.ones(n_assets) / n_assets - - # Iterative algorithm - for _ in range(100): - # Calculate marginal risk contributions - portfolio_vol = np.sqrt(weights @ cov_matrix @ weights) - marginal_contrib = cov_matrix @ weights / portfolio_vol - contrib = weights * marginal_contrib - - # Target equal contribution - target_contrib = portfolio_vol / n_assets - - # Update weights - weights = weights * (target_contrib / contrib) - weights = weights / np.sum(weights) - - # Calculate metrics - expected_returns = np.mean(returns, axis=0) - portfolio_return = expected_returns @ weights - portfolio_risk = np.sqrt(weights @ cov_matrix @ weights) - sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk - - return { - 'weights': weights, - 'expected_return': portfolio_return * 252, - 'expected_risk': portfolio_risk * np.sqrt(252), - 'sharpe_ratio': sharpe_ratio * np.sqrt(252) - } - - def _black_litterman_optimization( - self, - returns: np.ndarray, - constraints: Optional[Dict] = None, - views: Optional[Dict] = None - ) -> Dict: - """ - Black-Litterman optimization - """ - # Simplified implementation - # In practice, would incorporate market views - - n_assets = returns.shape[1] - - # Market equilibrium weights (market cap weighted) - # For demo, use equal weights - market_weights = np.ones(n_assets) / n_assets - - # Calculate implied returns - cov_matrix = np.cov(returns.T) - risk_aversion = 2.5 - implied_returns = risk_aversion * cov_matrix @ market_weights - - # Without views, this reduces to market weights - # With views, would blend implied returns with views - - if views: - # Implement view blending - pass - - # For now, return mean-variance with implied returns - expected_returns = implied_returns - - # Run mean-variance with these returns - weights = cp.Variable(n_assets) - portfolio_return = expected_returns @ weights - portfolio_risk = cp.quad_form(weights, cov_matrix) - - objective = cp.Maximize(portfolio_return - risk_aversion * portfolio_risk) - constraints_list = [ - cp.sum(weights) == 1, - weights >= 0, - ] - - problem = cp.Problem(objective, constraints_list) - problem.solve() - - weights_array = weights.value if problem.status == 'optimal' else market_weights - - # Calculate metrics - portfolio_return = expected_returns @ weights_array - portfolio_risk = np.sqrt(weights_array @ cov_matrix @ weights_array) - sharpe_ratio = (portfolio_return - self.risk_free_rate / 252) / portfolio_risk - - return { - 'weights': weights_array, - 'expected_return': portfolio_return * 252, - 'expected_risk': portfolio_risk * np.sqrt(252), - 'sharpe_ratio': sharpe_ratio * np.sqrt(252) - } - - def calculate_efficient_frontier( - self, - returns: np.ndarray, - num_portfolios: int = 100 - ) -> List[Dict]: - """ - Calculate the efficient frontier - """ - n_assets = returns.shape[1] - expected_returns = np.mean(returns, axis=0) - cov_matrix = np.cov(returns.T) - - # Range of target returns - min_ret = np.min(expected_returns) - max_ret = np.max(expected_returns) - target_returns = np.linspace(min_ret, max_ret, num_portfolios) - - frontier = [] - - for target_ret in target_returns: - weights = cp.Variable(n_assets) - portfolio_risk = cp.quad_form(weights, cov_matrix) - - objective = cp.Minimize(portfolio_risk) - constraints_list = [ - cp.sum(weights) == 1, - weights >= 0, - expected_returns @ weights >= target_ret - ] - - problem = cp.Problem(objective, constraints_list) - problem.solve() - - if problem.status == 'optimal': - w = weights.value - risk = np.sqrt(w @ cov_matrix @ w) - - frontier.append({ - 'return': target_ret * 252, - 'risk': risk * np.sqrt(252), - 'weights': w.tolist() - }) - - return frontier \ No newline at end of file diff --git a/apps/stock/analytics/test/test_app_composition.py b/apps/stock/analytics/test/test_app_composition.py deleted file mode 100644 index ec9c90a2..00000000 --- a/apps/stock/analytics/test/test_app_composition.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Import the actual service with optional scientific dependencies unavailable.""" -import importlib -from io import BytesIO -import json -from pathlib import Path -import sys -import unittest -from types import SimpleNamespace -from unittest.mock import Mock, patch - -from fastapi.testclient import TestClient -from starlette.datastructures import FormData, UploadFile -from starlette.exceptions import HTTPException - - -class UploadForm: - def __init__(self, values): - self.form = FormData(values) - - async def __aenter__(self): - return self.form - - async def __aexit__(self, *_): - await self.form.close() - - -class AnalyticsAppComposition(unittest.TestCase): - def setUp(self): - self.path = str(Path(__file__).parents[1]) - sys.path.insert(0, self.path) - self.addCleanup(lambda: sys.path.remove(self.path)) - for name in list(sys.modules): - if name == "src" or name.startswith("src."): - del sys.modules[name] - missing = {name: None for name in ( - "numpy", "pandas", "scipy", "sklearn", "cvxpy", "onnxruntime", "multipart", - )} - self.dependencies = patch.dict(sys.modules, missing) - self.dependencies.start() - self.addCleanup(self.dependencies.stop) - self.module = importlib.import_module("src.api.app") - self.capabilities = importlib.import_module("src.api.capabilities") - self.client = self.enterContext(TestClient(self.module.app)) - - def test_actual_app_starts_without_optional_dependencies(self): - self.assertEqual(self.client.get("/").status_code, 200) - self.assertEqual(self.client.get("/models/list").json(), []) - self.assertEqual(self.client.get("/analytics/risk/P").status_code, 503) - response = self.client.post("/optimize/rebalance", json={ - "current_weights": {"A.US": 0.25}, - "target_weights": {"A.US": 0.5}, - }) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json(), {"trades": {"A.US": 0.25}, "total_turnover": 0.25}) - - def test_health_observes_uninitialized_capabilities_without_loading_them(self): - response = self.client.get("/health") - self.assertEqual(response.status_code, 200) - health = response.json() - self.assertEqual(health["status"], "degraded") - for name in ("portfolio_optimizer", "model_runtime", "model_upload"): - self.assertEqual(health["components"][name], {"status": "uninitialized"}) - for name in ("performance_analyzer", "regime_detector"): - self.assertEqual(health["components"][name], { - "status": "unavailable", "reason": "observed_data_not_integrated", - }) - for name in ("src.analytics.performance", "src.analytics.regime", "src.optimization.portfolio_optimizer"): - self.assertNotIn(name, sys.modules) - schema = self.client.get("/openapi.json").json() - upload = schema["paths"]["/models/load"]["post"]["requestBody"] - self.assertTrue(upload["required"]) - self.assertEqual(upload["content"]["multipart/form-data"]["schema"]["required"], ["model_file"]) - - def test_missing_optimizer_is_503_with_diagnostic_and_independent_health(self): - request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02]]} - loader = Mock(wraps=self.capabilities.portfolio_optimizer.load) - self.capabilities.portfolio_optimizer.load = loader - for path in ("portfolio", "efficient_frontier", "portfolio"): - response = self.client.post("/optimize/" + path, json=request) - self.assertEqual(response.status_code, 503) - self.assertEqual(response.json()["detail"], { - "code": "analytics_capability_unavailable", - "capability": "portfolio_optimizer", - "reason": "missing_dependency", - "message": "Optional analytics capability 'portfolio_optimizer' is unavailable", - "dependency": "numpy", - }) - loader.assert_called_once() - health = self.client.get("/health").json()["components"] - self.assertEqual(health["portfolio_optimizer"]["status"], "unavailable") - self.assertEqual(health["model_runtime"]["status"], "uninitialized") - self.assertEqual(self.client.get("/models/list").json(), []) - - def test_optimizer_success_is_lazy_reused_and_preserves_input_and_output(self): - arrays = SimpleNamespace(array=Mock(return_value=SimpleNamespace(shape=(2, 2)))) - optimizer = SimpleNamespace( - optimize=Mock(return_value={ - "weights": SimpleNamespace(tolist=lambda: [0.25, 0.75]), - "expected_return": 0.1, - "expected_risk": 0.2, - "sharpe_ratio": 0.5, - }), - calculate_efficient_frontier=Mock(return_value=[{"risk": 0.2, "return": 0.1}]), - ) - loader = Mock(return_value=self.capabilities.OptimizationRuntime(arrays, optimizer)) - self.capabilities.portfolio_optimizer.load = loader - self.client.get("/health") - loader.assert_not_called() - request = {"symbols": ["A.US", "B.US"], "returns": [[0.01, 0.02], [0.03, -0.01]]} - response = self.client.post("/optimize/portfolio", json=request) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json(), { - "symbols": request["symbols"], "weights": [0.25, 0.75], - "expected_return": 0.1, "expected_risk": 0.2, "sharpe_ratio": 0.5, - }) - arrays.array.assert_called_once_with(request["returns"]) - optimizer.optimize.assert_called_once_with( - returns=arrays.array.return_value, method="mean_variance", constraints=None, - ) - response = self.client.post("/optimize/efficient_frontier?num_portfolios=7", json=request) - self.assertEqual(response.status_code, 200) - optimizer.calculate_efficient_frontier.assert_called_once_with( - returns=arrays.array.return_value, num_portfolios=7, - ) - loader.assert_called_once() - self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"], {"status": "ready"}) - request["symbols"] = ["A.US"] - self.assertEqual(self.client.post("/optimize/portfolio", json=request).status_code, 400) - - def test_failed_runtime_initialization_is_not_reported_ready(self): - self.capabilities.portfolio_optimizer.load = Mock(side_effect=RuntimeError("fixture failure")) - response = self.client.post("/optimize/portfolio", json={ - "symbols": ["A.US"], "returns": [[0.01]], - }) - self.assertEqual(response.status_code, 503) - self.assertEqual(response.json()["detail"]["reason"], "initialization_failed") - self.assertEqual(self.client.get("/health").json()["components"]["portfolio_optimizer"]["status"], "unavailable") - - def test_model_absence_and_optional_model_dependencies_have_distinct_statuses(self): - self.assertEqual(self.client.post("/models/predict", json={"model_id": "missing", "features": {}}).status_code, 404) - self.assertEqual(self.client.post("/models/batch_predict?model_id=missing", json=[]).status_code, 404) - self.assertEqual(self.client.delete("/models/missing").status_code, 404) - response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")}) - self.assertEqual(response.status_code, 503) - self.assertEqual(response.json()["detail"]["capability"], "model_runtime") - self.assertEqual(self.client.get("/health").json()["components"]["model_runtime"]["status"], "unavailable") - - def test_missing_multipart_only_disables_model_upload(self): - self.capabilities.model_runtime.load = Mock(return_value=self.capabilities.ModelRuntime(None, None)) - response = self.client.post("/models/load?model_id=fixture", files={"model_file": ("model.onnx", b"fixture")}) - self.assertEqual(response.status_code, 503) - self.assertEqual(response.json()["detail"]["capability"], "model_upload") - self.assertEqual(response.json()["detail"]["reason"], "missing_dependency") - self.assertEqual(self.client.get("/models/list").json(), []) - - def test_model_upload_and_prediction_keep_the_existing_contract_with_runtime_stubs(self): - session = SimpleNamespace( - get_inputs=lambda: [SimpleNamespace(name="input")], - get_outputs=lambda: [SimpleNamespace(shape=["batch", 1, None])], - run=Mock(return_value=[[1.5]]), - ) - arrays = SimpleNamespace( - array=Mock(return_value="feature-array"), - float32="float32", - datetime64=lambda _: SimpleNamespace(tolist=lambda: "2024-01-01T00:00:00"), - ) - onnx = SimpleNamespace(InferenceSession=Mock(return_value=session)) - loader = Mock(return_value=self.capabilities.ModelRuntime(arrays, onnx)) - self.capabilities.model_runtime.load = loader - self.capabilities.model_upload.load = Mock(return_value=True) - file = UploadFile(filename="model.onnx", file=BytesIO(b"fixture")) - with patch("starlette.requests.Request.form", return_value=UploadForm({"model_file": file})): - response = self.client.post("/models/load", params={ - "model_id": "fixture", - "metadata": json.dumps({"feature_names": ["trend", "volatility"], "version": "2"}), - }) - self.assertEqual(response.status_code, 200) - self.assertTrue(file.file.closed) - onnx.InferenceSession.assert_called_once_with(b"fixture") - listed = self.client.get("/models/list") - self.assertEqual(listed.status_code, 200) - self.assertEqual(listed.json()[0]["output_shape"], [["batch", 1, None]]) - self.assertEqual(listed.json()[0]["model_id"], "fixture") - response = self.client.post("/models/predict", json={ - "model_id": "fixture", "features": {"trend": 0.4}, - }) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["prediction"], 1.5) - self.assertEqual(response.json()["metadata"]["model_version"], "2") - arrays.array.assert_called_once_with([[0.4, 0.0]], dtype="float32") - session.run.assert_called_once_with(None, {"input": "feature-array"}) - loader.assert_called_once() - response = self.client.post("/models/batch_predict?model_id=fixture", json=[{"trend": 0.1}]) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.json()["count"], 1) - self.assertEqual(self.client.delete("/models/fixture").status_code, 200) - self.assertEqual(self.client.get("/models/list").json(), []) - with patch("starlette.requests.Request.form", return_value=UploadForm({})): - self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 422) - with patch("starlette.requests.Request.form", side_effect=HTTPException(400, "Malformed form")): - self.assertEqual(self.client.post("/models/load?model_id=fixture").status_code, 400) - - -if __name__ == "__main__": - unittest.main() diff --git a/apps/stock/analytics/test/test_unavailable_endpoints.py b/apps/stock/analytics/test/test_unavailable_endpoints.py deleted file mode 100644 index 781442bd..00000000 --- a/apps/stock/analytics/test/test_unavailable_endpoints.py +++ /dev/null @@ -1,55 +0,0 @@ -"""HTTP contract tests for the observed-data routes, without loading research/ML runtimes.""" -import importlib.util -from pathlib import Path -import unittest - -from fastapi import FastAPI -from fastapi.testclient import TestClient - - -class ObservedDataEndpoints(unittest.TestCase): - @classmethod - def setUpClass(cls): - source = Path(__file__).parents[1] / "src/api/endpoints/analytics.py" - spec = importlib.util.spec_from_file_location("observed_analytics_endpoints", source) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - app = FastAPI() - app.include_router(module.router, prefix="/analytics") - cls.client = TestClient(app) - - @classmethod - def tearDownClass(cls): - cls.client.close() - - def test_missing_observed_data_is_unavailable_not_generated_financial_results(self): - requests = [ - ("GET", "/performance/P?start_date=2024-01-01T00:00:00Z&end_date=2024-02-01T00:00:00Z", None), - ("GET", "/risk/P", None), - ("GET", "/regime", None), - ("POST", "/correlation", ["A.US", "B.US"]), - ("GET", "/backtest/run", None), - ("POST", "/attribution?portfolio_id=P&benchmark=B&start_date=2024-01-01&end_date=2024-02-01", None), - ] - for method, path, body in requests: - with self.subTest(path=path): - response = self.client.request(method, "/analytics" + path, json=body) - self.assertEqual(response.status_code, 503) - self.assertEqual(response.json()["detail"]["code"], "analytics_data_unavailable") - self.assertNotIn("metrics", response.json()) - self.assertNotIn("matrix", response.json()) - - def test_invalid_ranges_and_duplicate_symbols_are_client_errors(self): - response = self.client.get("/analytics/performance/P?start_date=2024-02-01T00:00:00Z&end_date=2024-01-01T00:00:00Z") - self.assertEqual(response.status_code, 400) - response = self.client.post("/analytics/correlation", json=["A.US", "A.US"]) - self.assertEqual(response.status_code, 400) - - def test_framework_validates_dates_windows_and_request_shapes(self): - self.assertEqual(self.client.get("/analytics/risk/P?window=0").status_code, 422) - self.assertEqual(self.client.get("/analytics/performance/P").status_code, 422) - self.assertEqual(self.client.post("/analytics/correlation", json={"symbols": ["A.US", "B.US"]}).status_code, 422) - - -if __name__ == "__main__": - unittest.main() diff --git a/apps/stock/config/config/development.json b/apps/stock/config/config/development.json index 0250c566..eaedd2c1 100644 --- a/apps/stock/config/config/development.json +++ b/apps/stock/config/config/development.json @@ -22,7 +22,6 @@ }, "mongodb": { "uri": "mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin", - "readUri": "mongodb://studio_stock_bot_read@localhost:27017/stock?authSource=stock", "database": "stock_dev", "poolSize": 10 }, @@ -38,6 +37,7 @@ "db": 0 }, "queue": { + "enableScheduledJobs": false, "redis": { "host": "localhost", "port": 6380, diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index ffc744d1..e8bd81e1 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -17,6 +17,10 @@ "types": "./dist/contracts/strategy.d.ts", "default": "./dist/contracts/strategy.js" }, + "./strategy-names": { + "types": "./dist/contracts/strategy-names.d.ts", + "default": "./dist/contracts/strategy-names.js" + }, "./canonical-replay": { "types": "./dist/contracts/canonical-replay.d.ts", "default": "./dist/contracts/canonical-replay.js" diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 0646d954..9d65e22f 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -14,7 +14,9 @@ const FORBIDDEN_PROD_SECRETS = new Set([ ]); function isLoopbackHost(host?: string): boolean { - if (!host) return false; + if (!host) { + return false; + } return LOOPBACK_HOSTS.has(host.toLowerCase()); } @@ -24,7 +26,9 @@ function parseMongoTarget(uri?: string): { database?: string; username?: string; } { - if (!uri) return {}; + if (!uri) { + return {}; + } try { const parsed = new URL(uri); const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined; diff --git a/apps/stock/data-ingestion/scripts/check-intraday-status.ts b/apps/stock/data-ingestion/scripts/check-intraday-status.ts deleted file mode 100644 index 742a4b94..00000000 --- a/apps/stock/data-ingestion/scripts/check-intraday-status.ts +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env bun - -/** - * Script to check intraday crawl status - */ - -import { createTestContext } from '../src/test-utils'; -import { QMHandler } from '../src/handlers/qm/qm.handler'; - -async function checkIntradayStatus() { - const context = await createTestContext(); - const handler = new QMHandler(context.services); - - // Wait for operation registry to initialize - await new Promise(resolve => setTimeout(resolve, 1000)); - - try { - const tracker = handler.operationRegistry.getTracker('qm'); - - // Get operation stats - const stats = await tracker.getOperationStats('intraday_bars'); - console.log('Intraday Bars Operation Stats:'); - console.log('------------------------------'); - console.log(`Total symbols: ${stats.totalSymbols}`); - console.log(`Processed symbols: ${stats.processedSymbols}`); - console.log(`Successful symbols: ${stats.successfulSymbols}`); - console.log(`Failed symbols: ${stats.failedSymbols}`); - console.log(`Stale symbols: ${stats.staleSymbols}`); - console.log(`Finished crawls: ${stats.finishedCrawls || 0}`); - console.log(''); - - // Get symbols needing crawl - console.log('Symbols needing crawl (top 10):'); - console.log('--------------------------------'); - const needsCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { - limit: 10, - targetOldestDate: new Date('2020-01-01') - }); - - for (const symbol of needsCrawl) { - const crawlState = symbol.operationStatus?.crawlState; - console.log(`\n${symbol.symbol}:`); - console.log(` Status: ${symbol.operationStatus?.status || 'never run'}`); - console.log(` Last run: ${symbol.operationStatus?.lastRunAt || 'never'}`); - - if (crawlState) { - console.log(` Finished: ${crawlState.finished}`); - console.log(` Oldest date: ${crawlState.oldestDateReached || 'none'}`); - console.log(` Newest date: ${crawlState.newestDateReached || 'none'}`); - console.log(` Days processed: ${crawlState.totalDaysProcessed || 0}`); - } - - if (symbol.gaps) { - console.log(` Gaps: ${symbol.gaps.forward ? 'new data' : ''} ${symbol.gaps.backward ? 'historical' : ''}`); - } - } - - } catch (error) { - console.error('Failed to check status:', error); - } finally { - await context.cleanup(); - } -} - -// Run the check -checkIntradayStatus().catch(console.error); \ No newline at end of file diff --git a/apps/stock/data-ingestion/scripts/trigger-job.ts b/apps/stock/data-ingestion/scripts/trigger-job.ts deleted file mode 100644 index 0158c634..00000000 --- a/apps/stock/data-ingestion/scripts/trigger-job.ts +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bun - -import Redis from 'ioredis'; -import { Queue } from 'bullmq'; - -const redis = new Redis({ - host: 'localhost', - port: 6379, - db: 0, -}); - -const queue = new Queue('{data-ingestion_webshare}', { - connection: redis, -}); - -async function triggerJob() { - console.log('Triggering webshare fetch-proxies job...'); - - const job = await queue.add('fetch-proxies', { - handler: 'webshare', - operation: 'fetch-proxies', - payload: {}, - }); - - console.log(`Job ${job.id} added to queue`); - - await redis.quit(); - process.exit(0); -} - -triggerJob().catch(console.error); \ No newline at end of file diff --git a/apps/stock/data-ingestion/src/handlers/eod/shared/types.ts b/apps/stock/data-ingestion/src/handlers/eod/shared/types.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts deleted file mode 100644 index 0a055a6d..00000000 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './config'; -export * from './session-manager'; -export * from './types'; -export * from './operation-provider'; diff --git a/apps/stock/data-ingestion/src/handlers/te/shared/index.ts b/apps/stock/data-ingestion/src/handlers/te/shared/index.ts deleted file mode 100644 index f3676570..00000000 --- a/apps/stock/data-ingestion/src/handlers/te/shared/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './config'; -export * from './decode'; -export * from './types'; \ No newline at end of file diff --git a/apps/stock/data-ingestion/src/handlers/tradingview/shared/index.ts b/apps/stock/data-ingestion/src/handlers/tradingview/shared/index.ts deleted file mode 100644 index c4522537..00000000 --- a/apps/stock/data-ingestion/src/handlers/tradingview/shared/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './types'; -export * from './config'; \ No newline at end of file diff --git a/apps/stock/data-ingestion/src/handlers/webshare/shared/config.ts b/apps/stock/data-ingestion/src/handlers/webshare/shared/config.ts deleted file mode 100644 index 4d3ba822..00000000 --- a/apps/stock/data-ingestion/src/handlers/webshare/shared/config.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * WebShare Configuration Constants - */ - -export const WEBSHARE_CONFIG = { - DEFAULT_PAGE_SIZE: 100, - DEFAULT_MODE: 'direct', - DEFAULT_PAGE: 1, - TIMEOUT: 10000, -}; diff --git a/apps/stock/data-ingestion/src/index.ts b/apps/stock/data-ingestion/src/index.ts index 39af9675..f76fc371 100644 --- a/apps/stock/data-ingestion/src/index.ts +++ b/apps/stock/data-ingestion/src/index.ts @@ -3,12 +3,12 @@ * Simplified entry point using ServiceApplication framework */ +import { Browser } from '@stock-bot/browser'; import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; -import { createRoutes } from './routes/create-routes'; -// Local imports import { initializeAllHandlers } from './handlers'; +import { createRoutes } from './routes/create-routes'; // Initialize configuration with service-specific overrides const config = initializeStockConfig('dataIngestion'); @@ -29,7 +29,7 @@ const app = new ServiceApplication( serviceName: 'data-ingestion', hostname: security.hostname, enableHandlers: true, - enableScheduledJobs: true, + enableScheduledJobs: config.queue?.enableScheduledJobs ?? true, corsConfig: { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], @@ -70,6 +70,21 @@ async function createContainer(baseConfig: import('@stock-bot/config').UnifiedAp enableBrowser: true, // Data ingestion needs browser for web scraping enableProxy: true, // Data ingestion needs proxy for rate limiting }) + .withRegistrations((diContainer, validatedConfig, { asFunction }) => { + if (validatedConfig.browser) { + const browserOptions = { + headless: validatedConfig.browser.headless, + timeout: validatedConfig.browser.timeout, + }; + diContainer.register({ + browser: asFunction(({ logger: containerLogger }) => { + return new Browser(containerLogger, browserOptions); + }) + .singleton() + .disposer(browser => browser.close?.()), + }); + } + }) .build(); // This automatically initializes services return container; diff --git a/apps/stock/data-ingestion/src/routes/index.ts b/apps/stock/data-ingestion/src/routes/index.ts deleted file mode 100644 index 431445f5..00000000 --- a/apps/stock/data-ingestion/src/routes/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Routes index - exports all route modules - */ -export { exchangeRoutes } from './exchange.routes'; -export { healthRoutes } from './health.routes'; -export { createQueueRoutes } from './queue.routes'; diff --git a/apps/stock/data-ingestion/src/routes/market-data.routes.ts b/apps/stock/data-ingestion/src/routes/market-data.routes.ts deleted file mode 100644 index c0953ac5..00000000 --- a/apps/stock/data-ingestion/src/routes/market-data.routes.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Market data routes - */ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; -import { processItems } from '@stock-bot/queue'; - -const logger = getLogger('market-data-routes'); - -export function createMarketDataRoutes(container: IServiceContainer) { - const marketDataRoutes = new Hono(); - - // Market data endpoints - marketDataRoutes.get('/api/live/:symbol', async c => { - const symbol = c.req.param('symbol'); - logger.info('Live data request', { symbol }); - - try { - // Queue job for live data using Yahoo provider - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ status: 'error', message: 'Queue manager not available' }, 503); - } - - const queue = queueManager.getQueue('yahoo-finance'); - const job = await queue.add('live-data', { - handler: 'yahoo-finance', - operation: 'live-data', - payload: { symbol }, - }); - return c.json({ - status: 'success', - message: 'Live data job queued', - jobId: job.id, - symbol, - }); - } catch (error) { - logger.error('Failed to queue live data job', { symbol, error }); - return c.json({ status: 'error', message: 'Failed to queue live data job' }, 500); - } - }); - - marketDataRoutes.get('/api/historical/:symbol', async c => { - const symbol = c.req.param('symbol'); - const from = c.req.query('from'); - const to = c.req.query('to'); - - logger.info('Historical data request', { symbol, from, to }); - - try { - const fromDate = from ? new Date(from) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 days ago - const toDate = to ? new Date(to) : new Date(); // Now - - // Queue job for historical data using Yahoo provider - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ status: 'error', message: 'Queue manager not available' }, 503); - } - - const queue = queueManager.getQueue('yahoo-finance'); - const job = await queue.add('historical-data', { - handler: 'yahoo-finance', - operation: 'historical-data', - payload: { - symbol, - from: fromDate.toISOString(), - to: toDate.toISOString(), - }, - }); - - return c.json({ - status: 'success', - message: 'Historical data job queued', - jobId: job.id, - symbol, - from: fromDate, - to: toDate, - }); - } catch (error) { - logger.error('Failed to queue historical data job', { symbol, from, to, error }); - return c.json({ status: 'error', message: 'Failed to queue historical data job' }, 500); - } - }); - - // Batch processing endpoint using new queue system - marketDataRoutes.post('/api/process-symbols', async c => { - try { - const { - symbols, - provider = 'ib', - operation = 'fetch-session', - useBatching = true, - totalDelayHours = 0.0083, // ~30 seconds (30/3600 hours) - batchSize = 10, - } = await c.req.json(); - - if (!symbols || !Array.isArray(symbols) || symbols.length === 0) { - return c.json({ status: 'error', message: 'Invalid symbols array' }, 400); - } - - logger.info('Batch processing symbols', { - count: symbols.length, - provider, - operation, - useBatching, - }); - - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ status: 'error', message: 'Queue manager not available' }, 503); - } - - const result = await processItems( - symbols, - provider, - { - handler: provider, - operation, - totalDelayHours, - useBatching, - batchSize, - priority: 2, - retries: 2, - removeOnComplete: 100, - removeOnFail: 100, - }, - queueManager - ); - - return c.json({ - status: 'success', - message: 'Batch processing initiated', - result, - symbols: symbols.length, - }); - } catch (error) { - logger.error('Failed to process symbols batch', { error }); - return c.json({ status: 'error', message: 'Failed to process symbols batch' }, 500); - } - }); - - return marketDataRoutes; -} - -// Legacy export for backward compatibility -export const marketDataRoutes = createMarketDataRoutes({} as IServiceContainer); diff --git a/apps/stock/data-ingestion/src/types/exchange.types.ts b/apps/stock/data-ingestion/src/types/exchange.types.ts deleted file mode 100644 index 6fcbdd8b..00000000 --- a/apps/stock/data-ingestion/src/types/exchange.types.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Type definitions for exchange data structures - */ - -export interface IBExchange { - id: string; - country_code: string; - name: string; - code?: string; - exchange_code?: string; - currency?: string; - timezone?: string; - _id?: unknown; // MongoDB ObjectId - // Add other properties as needed -} - -export interface MasterExchangeData { - id: string; - code: string; - name: string; - country: string; - currency: string; - // Add other properties as needed -} - -export interface QMSymbol { - symbol: string; - exchange?: string; - name?: string; - type?: string; - // Add other properties as needed -} - -export interface IBSymbol { - symbol: string; - exchange: string; - name?: string; - currency?: string; - // Add other properties as needed -} diff --git a/apps/stock/data-ingestion/src/types/job-payloads.ts b/apps/stock/data-ingestion/src/types/job-payloads.ts deleted file mode 100644 index 05144b87..00000000 --- a/apps/stock/data-ingestion/src/types/job-payloads.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * Type definitions for all job payloads across data service providers - */ - -// Common result types -export interface JobResult { - success: boolean; - message: string; -} - -export interface CountableJobResult extends JobResult { - count: number; -} - -// QM Provider Types -export interface SymbolSpiderJob { - prefix: string | null; // null = root job (A-Z) - depth: number; // 1=A, 2=AA, 3=AAA, etc. - source: string; // 'qm' - maxDepth?: number; // optional max depth limit -} - -export interface CreateSessionsResult extends JobResult { - // No additional fields needed -} - -export interface SearchSymbolsResult extends CountableJobResult { - symbols?: unknown[]; // First 10 symbols as sample -} - -export interface SpiderSymbolSearchResult extends JobResult { - symbolsFound: number; - newSymbolsAdded: number; - duplicatesSkipped: number; - errors: number; - depth: number; - prefix: string | null; -} - -// IB Provider Types -export interface FetchSessionResult extends JobResult { - sessionData?: Record; -} - -export interface FetchExchangesResult extends CountableJobResult { - exchanges?: unknown[]; -} - -export interface FetchSymbolsResult extends CountableJobResult { - symbols?: unknown[]; -} - -export interface IBExchangesAndSymbolsResult extends JobResult { - exchanges: FetchExchangesResult; - symbols: FetchSymbolsResult; -} - -// Proxy Provider Types -export interface ProxyInfo { - host: string; - port: number; - protocol: 'http' | 'https' | 'socks4' | 'socks5'; - username?: string; - password?: string; - country?: string; - city?: string; - isValid?: boolean; - lastChecked?: Date; -} - -export interface FetchProxiesFromSourcesResult extends CountableJobResult { - proxies?: ProxyInfo[]; - sources: string[]; -} - -export interface CheckProxyResult extends JobResult { - proxy: ProxyInfo; - responseTime?: number; - error?: string; -} - -// WebShare Provider Types -export interface FetchWebShareProxiesResult extends CountableJobResult { - proxies?: ProxyInfo[]; - activeProxies: number; - totalQuota: number; - remainingQuota: number; -} - -// No payload job types (for operations that don't need input) -export interface NoPayload { - // Empty interface for operations that don't need payload -} diff --git a/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts b/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts deleted file mode 100755 index 5c4ff0b6..00000000 --- a/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env bun -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('test-advanced-rate-limit'); - -async function testAdvancedRateLimits() { - logger.info('Testing advanced rate limit features...'); - - const baseUrl = 'http://localhost:3001/api'; - - logger.info('\n๐Ÿ“‹ Rate Limit Configuration:'); - logger.info('Handler limits: 100pts/sec, 10k pts/hour, 100k pts/day'); - logger.info('fetch-daily-prices: 1 point per call'); - logger.info('fetch-fundamentals: 10 points per call'); - logger.info('fetch-news: 50 points per call (custom limits: 10pts/min, 100pts/hour)'); - - // First test: test-burst operation - logger.info('\n๐Ÿš€ Testing burst operation with mixed costs...'); - - const burstResponse = await fetch(`${baseUrl}/handlers/eod/operations/test-burst`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - operationsToTest: ['fetch-daily-prices', 'fetch-fundamentals', 'fetch-news'], - burstSize: 30, - }), - }); - - const burstResult = await burstResponse.json(); - logger.info('Burst test result:', burstResult); - - // Wait for jobs to process - logger.info('\nโณ Waiting 10 seconds for jobs to process...'); - await new Promise(resolve => setTimeout(resolve, 10000)); - - // Test individual operations with different costs - logger.info('\n๐Ÿ“Š Testing individual operations:'); - - // Test cheap operation (1 point) - logger.info('\n1๏ธโƒฃ Testing fetch-daily-prices (1 point each)...'); - for (let i = 0; i < 5; i++) { - const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-daily-prices`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ test: true, index: i }), - }); - logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); - } - - // Test medium cost operation (10 points) - logger.info('\n๐Ÿ”Ÿ Testing fetch-fundamentals (10 points each)...'); - for (let i = 0; i < 3; i++) { - const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-fundamentals`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ test: true, index: i }), - }); - logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); - } - - // Test expensive operation (50 points) - logger.info('\n๐Ÿ’ฐ Testing fetch-news (50 points each, custom limits)...'); - for (let i = 0; i < 2; i++) { - const response = await fetch(`${baseUrl}/handlers/eod/operations/fetch-news`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ test: true, index: i }), - }); - logger.info(`Request ${i + 1}: ${response.status} ${response.statusText}`); - } - - logger.info('\nโœ… Test completed!'); - logger.info('Check the data-ingestion service logs to see rate limiting in action.'); -} - -// Health check before running tests -async function checkService() { - try { - const response = await fetch('http://localhost:3001/health'); - if (!response.ok) { - throw new Error('Service not healthy'); - } - return true; - } catch (_error) { - logger.error('Data ingestion service not running. Start it with: bun run dev'); - return false; - } -} - -async function main() { - if (await checkService()) { - await testAdvancedRateLimits(); - } -} - -main().catch(error => { - logger.error('Test failed:', error); - process.exit(1); -}); diff --git a/apps/stock/data-ingestion/test/test-intraday-flow.ts b/apps/stock/data-ingestion/test/test-intraday-flow.ts deleted file mode 100644 index 9732f481..00000000 --- a/apps/stock/data-ingestion/test/test-intraday-flow.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Test script to verify intraday crawl data flow - */ - -import { OperationRegistry, OperationTracker } from '../src/shared/operation-manager'; -import type { DataIngestionServices } from '../src/types'; - -async function testIntradayDataFlow() { - console.log('=== Testing Intraday Data Flow ===\n'); - - // Mock services - const mockServices: DataIngestionServices = { - mongodb: { - collection: (name: string) => ({ - find: () => ({ - toArray: async () => { - console.log(`Mock: Query collection ${name}`); - if (name === 'qmSymbols') { - return [ - { - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - exchange: 'NYSE', - operations: { - intraday_bars: { - lastRunAt: new Date('2024-01-01'), - lastSuccessAt: new Date('2024-01-01'), - status: 'success', - crawlState: { - finished: false, - oldestDateReached: new Date('2023-01-01'), - newestDateReached: new Date('2024-01-01'), - lastProcessedDate: new Date('2023-06-15'), - totalDaysProcessed: 180, - }, - }, - }, - }, - ]; - } - return []; - }, - }), - createIndex: async () => ({ ok: 1 }), - }), - find: async (collection: string, filter: any, options?: any) => { - console.log(`Mock: Direct find on ${collection}`, { filter, options }); - return [ - { - symbol: 'X', - qmSearchCode: 'X:NYSE', - exchange: 'NYSE', - operations: { - intraday_bars: { - crawlState: { - finished: false, - oldestDateReached: new Date('2023-01-01'), - newestDateReached: new Date('2024-01-01'), - }, - }, - }, - }, - ]; - }, - } as any, - logger: { - info: (msg: string, data?: any) => - console.log(`[INFO] ${msg}`, JSON.stringify(data, null, 2)), - error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''), - warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''), - debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''), - }, - } as DataIngestionServices; - - // Create registry and provider - const _registry = new OperationRegistry(mockServices as any); - - // Mock provider - const mockProvider = { - getProviderConfig: () => ({ - name: 'qm', - collectionName: 'qmSymbols', - symbolField: 'qmSearchCode', - }), - getOperations: () => [ - { - name: 'intraday_bars', - type: 'intraday_crawl' as const, - defaultStaleHours: 1, - }, - ], - validateOperation: () => true, - getOperation: () => ({ name: 'intraday_bars', type: 'intraday_crawl' }), - getDefaultStaleHours: () => 1, - initialize: async () => {}, - beforeOperationUpdate: async () => {}, - afterOperationUpdate: async () => {}, - }; - - const tracker = new OperationTracker(mockServices as any, mockProvider as any); - await tracker.initialize(); - - // Test 1: Get symbols for intraday crawl - console.log('\nTest 1: Get symbols for intraday crawl with symbol filter'); - const symbols = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { - limit: 10, - targetOldestDate: new Date('2020-01-01'), - includeNewDataGaps: true, - symbolFilter: { symbol: 'X' }, - }); - - console.log(`\nFound ${symbols.length} symbols:`); - symbols.forEach(sym => { - console.log({ - symbol: sym.symbol, - qmSearchCode: sym.qmSearchCode, - exchange: sym.exchange, - gaps: sym.gaps, - crawlState: sym.operationStatus?.crawlState, - }); - }); - - // Test 2: Verify data preservation - console.log('\n\nTest 2: Verify data is preserved through mapping'); - const testSymbol = symbols[0]; - if (testSymbol) { - console.log('Original data:'); - console.log({ - symbol: testSymbol.symbol, - hasGaps: !!testSymbol.gaps, - gaps: testSymbol.gaps, - hasOperationStatus: !!testSymbol.operationStatus, - crawlState: testSymbol.operationStatus?.crawlState, - }); - - // Simulate mapping - const mapped = { - ...testSymbol, - symbol: 'X', - exchange: 'NYSE', - qmSearchCode: 'X:NYSE', - gaps: testSymbol.gaps, - operationStatus: testSymbol.operationStatus, - }; - - console.log('\nAfter mapping:'); - console.log({ - symbol: mapped.symbol, - exchange: mapped.exchange, - qmSearchCode: mapped.qmSearchCode, - hasGaps: !!mapped.gaps, - gaps: mapped.gaps, - hasOperationStatus: !!mapped.operationStatus, - crawlState: mapped.operationStatus?.crawlState, - }); - } - - console.log('\n=== Tests Complete ==='); -} - -// Run tests -testIntradayDataFlow().catch(console.error); diff --git a/apps/stock/data-ingestion/test/test-modified-functions.ts b/apps/stock/data-ingestion/test/test-modified-functions.ts deleted file mode 100644 index c5f3af41..00000000 --- a/apps/stock/data-ingestion/test/test-modified-functions.ts +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Examples of modifying existing functions to only work with symbol 'X' - */ - -import { OperationTracker } from '../src/shared/operation-manager'; - -// Example 1: Modified getStaleSymbols to only return symbol X -async function getStaleSymbolsOnlyX( - operationTracker: OperationTracker, - providerName: string, - operationName: string, - options: any = {} -) { - // Method 1: Add symbolFilter to options - const modifiedOptions = { - ...options, - symbolFilter: { symbol: 'X' }, - }; - - return operationTracker.getStaleSymbols(providerName, operationName, modifiedOptions); -} - -// Example 2: Modified sophisticated backtest function for symbol X only -async function _runSophisticatedBacktestOnlyX(orchestrator: any) { - const symbols = ['X']; // Only test symbol X - - const backtestConfig = { - symbols, - startDate: new Date('2023-01-01'), - endDate: new Date('2024-01-01'), - strategies: ['momentum', 'mean_reversion'], - // ... rest of config - }; - - return orchestrator.runBacktest(backtestConfig); -} - -// Example 3: Modified schedule function to only process symbol X -async function _scheduleOperationsOnlyX(handler: any) { - // Get all symbols that need updates, then filter for X - const staleSymbols = await handler.operationRegistry.getStaleSymbols('qm', 'price_update', { - minHoursSinceRun: 24, - limit: 1000, - }); - - // Filter to only include symbol X - const symbolXOnly = staleSymbols.filter((s: string) => s.includes('X:')); - - if (symbolXOnly.length > 0) { - const symbolData = await handler.mongodb.find('qmSymbols', { - qmSearchCode: symbolXOnly[0], - }); - - if (symbolData.length > 0) { - await handler.scheduleOperation('update-prices', { - symbol: symbolData[0].symbol, - symbolId: symbolData[0].symbolId, - qmSearchCode: symbolData[0].qmSearchCode, - }); - } - } -} - -// Example 4: Modified intraday crawl for symbol X only -async function _crawlIntradayOnlyX(handler: any) { - // Direct approach - just process symbol X - const symbolX = await handler.mongodb.findOne('qmSymbols', { symbol: 'X' }); - - if (symbolX) { - return handler.crawlIntradayData({ - symbol: symbolX.symbol, - symbolId: symbolX.symbolId, - qmSearchCode: symbolX.qmSearchCode, - mode: 'full', - targetOldestDate: new Date('2020-01-01'), - }); - } -} - -// Example 5: Test wrapper that ensures only symbol X is processed -function createSymbolXTestWrapper(originalFunction: Function) { - return async function (...args: any[]) { - // Check if first argument has symbol property - if (args[0] && typeof args[0] === 'object') { - // If it's a symbol-specific call, only proceed if symbol is X - if (args[0].symbol && args[0].symbol !== 'X') { - console.log(`Skipping symbol ${args[0].symbol} - only testing X`); - return { success: false, message: 'Test mode - only symbol X allowed' }; - } - - // If it's a batch operation, filter to only X - if (args[0].symbols && Array.isArray(args[0].symbols)) { - args[0].symbols = args[0].symbols.filter((s: string) => s === 'X'); - } - } - - // Call original function with potentially modified args - return originalFunction.apply(this, args); - }; -} - -// Example usage -async function demonstrateUsage() { - console.log('=== Demonstration of Symbol X Only Modifications ===\n'); - - // Mock tracker for demonstration - const mockTracker = { - getStaleSymbols: async (provider: string, operation: string, options: any) => { - console.log(`Getting stale symbols with options:`, options); - if (options.symbolFilter?.symbol === 'X') { - return ['X:NYSE']; - } - return ['AAPL:NASDAQ', 'GOOGL:NASDAQ', 'X:NYSE', 'MSFT:NASDAQ']; - }, - } as any; - - // Test the modified function - console.log('1. Testing getStaleSymbols with X filter:'); - const xOnlySymbols = await getStaleSymbolsOnlyX(mockTracker, 'qm', 'price_update', { - minHoursSinceRun: 24, - }); - console.log('Results:', xOnlySymbols); - - console.log('\n2. Example of wrapper usage:'); - const originalUpdate = async (input: any) => { - console.log(`Processing symbol: ${input.symbol}`); - return { success: true, symbol: input.symbol }; - }; - - const wrappedUpdate = createSymbolXTestWrapper(originalUpdate); - - await wrappedUpdate({ symbol: 'X', symbolId: 123 }); - await wrappedUpdate({ symbol: 'AAPL', symbolId: 456 }); // Will be skipped - - console.log('\n=== Demonstration Complete ==='); -} - -// Run demonstration -demonstrateUsage().catch(console.error); diff --git a/apps/stock/data-ingestion/test/test-qm-operations.ts b/apps/stock/data-ingestion/test/test-qm-operations.ts deleted file mode 100644 index 666b7026..00000000 --- a/apps/stock/data-ingestion/test/test-qm-operations.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Test script for QM operations - */ - -import { QMHandler } from '../src/handlers/qm/qm.handler'; -import type { DataIngestionServices } from '../src/types'; - -// Mock services for testing -const mockServices: Partial = { - mongodb: { - batchUpsert: async (collection: string, data: any[], uniqueKeys: string[]) => { - console.log(`Mock: Batch upsert to ${collection}`, { - recordCount: data.length, - uniqueKeys - }); - return { insertedCount: data.length, modifiedCount: 0 }; - }, - find: async (collection: string, query: any, options?: any) => { - console.log(`Mock: Find from ${collection}`, { query, options }); - // Return test symbol for testing - if (collection === 'qmSymbols' && query.symbol === 'X') { - return [{ - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - exchange: 'NYSE', - name: 'United States Steel Corporation' - }]; - } - return []; - }, - updateOne: async (collection: string, filter: any, update: any, options?: any) => { - console.log(`Mock: Update ${collection}`, { filter, update, options }); - return { modifiedCount: 1 }; - } - }, - cache: { - get: async (key: string) => { - console.log(`Mock: Cache get ${key}`); - return null; - }, - set: async (key: string, value: any, ttl?: number) => { - console.log(`Mock: Cache set ${key}`, { ttl }); - return true; - } - }, - logger: { - info: (message: string, data?: any) => { - console.log(`[INFO] ${message}`, data || ''); - }, - error: (message: string, data?: any) => { - console.error(`[ERROR] ${message}`, data || ''); - }, - warn: (message: string, data?: any) => { - console.warn(`[WARN] ${message}`, data || ''); - }, - debug: (message: string, data?: any) => { - console.debug(`[DEBUG] ${message}`, data || ''); - } - }, - // Mock operation registry - operationRegistry: { - updateOperation: async (provider: string, symbol: string, operation: string, data: any) => { - console.log(`Mock: Update operation ${provider}/${operation} for ${symbol}`, data); - return true; - }, - getStaleSymbols: async (provider: string, operation: string, options: any) => { - console.log(`Mock: Get stale symbols for ${provider}/${operation}`, options); - // Return test symbol - if (options.symbolFilter?.symbol === 'X') { - return ['X:NYSE']; - } - return []; - } - } -} as DataIngestionServices; - -async function testQMOperations() { - console.log('=== Testing QM Operations ===\n'); - - // Create handler instance - const handler = new QMHandler(mockServices); - - // Wait a bit for initialization - await new Promise(resolve => setTimeout(resolve, 1000)); - - // Test 1: Update Insiders for symbol X - console.log('Test 1: Update Insiders for symbol X'); - console.log('-------------------------------------'); - try { - const insidersResult = await handler.updateInsiders({ - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - lookbackDays: 30 - }); - console.log('Result:', JSON.stringify(insidersResult, null, 2)); - } catch (error) { - console.error('Failed:', error); - } - - console.log('\n'); - - // Test 2: Update Symbol News for symbol X - console.log('Test 2: Update Symbol News for symbol X'); - console.log('----------------------------------------'); - try { - const newsResult = await handler.updateSymbolNews({ - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - lookbackDays: 7 - }); - console.log('Result:', JSON.stringify(newsResult, null, 2)); - } catch (error) { - console.error('Failed:', error); - } - - console.log('\n'); - - // Test 3: Update General News - console.log('Test 3: Update General News'); - console.log('---------------------------'); - try { - const generalNewsResult = await handler.updateGeneralNews({ - categories: ['market', 'economy'], - lookbackMinutes: 60 - }); - console.log('Result:', JSON.stringify(generalNewsResult, null, 2)); - } catch (error) { - console.error('Failed:', error); - } - - console.log('\n'); - - // Test 4: Check available operations - console.log('Test 4: List Available Operations'); - console.log('---------------------------------'); - const operations = [ - 'create-session', - 'search-symbols', - 'update-symbol-info', - 'update-financials', - 'update-events', - 'update-filings', - 'update-prices', - 'update-intraday-bars', - 'crawl-intraday-data', - 'update-insiders', - 'update-symbol-news', - 'update-general-news' - ]; - - for (const op of operations) { - const hasOperation = typeof (handler as any)[op.replace(/-/g, '')] === 'function'; - console.log(`${op}: ${hasOperation ? 'โœ“' : 'โœ—'}`); - } - - console.log('\n=== Tests Complete ==='); -} - -// Run tests -testQMOperations().catch(console.error); \ No newline at end of file diff --git a/apps/stock/data-ingestion/test/test-symbol-x.ts b/apps/stock/data-ingestion/test/test-symbol-x.ts deleted file mode 100644 index 9c196c56..00000000 --- a/apps/stock/data-ingestion/test/test-symbol-x.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Test script specifically for symbol X operations - */ - -import '../src/handlers/qm/qm.handler'; -import { OperationTracker } from '../src/shared/operation-manager'; -import type { DataIngestionServices } from '../src/types'; - -// Simple test to check operations for symbol X -async function testSymbolXOperations() { - console.log('=== Testing Operations for Symbol X ===\n'); - - // Mock minimal services needed - const mockServices: Partial = { - mongodb: { - collection: (name: string) => ({ - find: () => ({ - toArray: async () => { - console.log(`Querying collection: ${name}`); - if (name === 'qmSymbols') { - return [ - { - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - exchange: 'NYSE', - name: 'United States Steel Corporation', - }, - ]; - } - return []; - }, - }), - findOne: async (query: any) => { - console.log(`Finding one in ${name}:`, query); - return null; - }, - updateOne: async (filter: any, update: any, _options: any) => { - console.log(`Updating ${name}:`, { filter, update }); - return { modifiedCount: 1 }; - }, - }), - find: async (collection: string, query: any) => { - console.log(`Direct find on ${collection}:`, query); - if (collection === 'qmSymbols' && query.symbol === 'X') { - return [ - { - symbol: 'X', - symbolId: 123456, - qmSearchCode: 'X:NYSE', - }, - ]; - } - return []; - }, - } as any, - logger: { - info: (msg: string, data?: any) => console.log(`[INFO] ${msg}`, data || ''), - error: (msg: string, data?: any) => console.error(`[ERROR] ${msg}`, data || ''), - warn: (msg: string, data?: any) => console.warn(`[WARN] ${msg}`, data || ''), - debug: (msg: string, data?: any) => console.debug(`[DEBUG] ${msg}`, data || ''), - }, - } as DataIngestionServices; - - // Test 1: Check stale operations for symbol X - console.log('Test 1: Get stale operations for symbol X'); - console.log('------------------------------------------'); - - const tracker = new OperationTracker(mockServices as any); - - try { - // Check each operation type - const operations = [ - 'symbol_info', - 'price_update', - 'intraday_bars', - 'financials_update_quarterly', - 'financials_update_annual', - 'events_update', - 'filings_update', - 'insiders_update', - 'news_update', - ]; - - for (const operation of operations) { - console.log(`\nChecking ${operation}:`); - - const staleSymbols = await tracker.getStaleSymbols('qm', operation, { - minHoursSinceRun: 0, // Get all symbols regardless of last run - limit: 10, - symbolFilter: { symbol: 'X' }, // Only get symbol X - }); - - console.log(`Found ${staleSymbols.length} stale symbols:`, staleSymbols); - } - } catch (error) { - console.error('Error checking stale symbols:', error); - } - - // Test 2: Check intraday crawl status for symbol X - console.log('\n\nTest 2: Check intraday crawl status for symbol X'); - console.log('------------------------------------------------'); - - try { - const symbolsForCrawl = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { - limit: 10, - symbolFilter: { symbol: 'X' }, - }); - - console.log(`Found ${symbolsForCrawl.length} symbols for intraday crawl`); - if (symbolsForCrawl.length > 0) { - console.log('Symbol details:', JSON.stringify(symbolsForCrawl[0], null, 2)); - } - } catch (error) { - console.error('Error checking intraday crawl:', error); - } - - console.log('\n=== Tests Complete ==='); -} - -// Run the test -testSymbolXOperations().catch(console.error); diff --git a/apps/stock/data-pipeline/package.json b/apps/stock/data-pipeline/package.json index c351beb3..0720c16f 100644 --- a/apps/stock/data-pipeline/package.json +++ b/apps/stock/data-pipeline/package.json @@ -6,7 +6,7 @@ "type": "module", "scripts": { "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts --outdir dist --target node --external chromium-bidi --external electron --external playwright --external playwright-core", + "build": "bun build src/index.ts --outdir dist --target node", "start": "bun dist/index.js", "test": "bun test", "clean": "rm -rf dist" diff --git a/apps/stock/data-pipeline/scripts/phase1-inventory.ts b/apps/stock/data-pipeline/scripts/phase1-inventory.ts deleted file mode 100644 index c0df12a4..00000000 --- a/apps/stock/data-pipeline/scripts/phase1-inventory.ts +++ /dev/null @@ -1,528 +0,0 @@ -import { homedir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { parseArgs, parseEnv } from 'node:util'; -import { MongoClient, type Db, type Document } from 'mongodb'; -import { Client } from 'pg'; - -const sources = ['qm', 'eod', 'ib', 'ceo'] as const; -type Source = typeof sources[number]; -type Entity = 'stock' | 'exchange' | 'country' | 'other' | 'unclassified'; -const entities: Record = { - qmSymbols: 'stock', eodSymbols: 'stock', ibSymbols: 'stock', ceoSymbols: 'stock', - qmExchanges: 'exchange', eodExchanges: 'exchange', ibExchanges: 'exchange', ceoExchanges: 'exchange', - teCountries: 'country', teIndicators: 'country', teData: 'country', teMarketData: 'country', - qmDividends: 'other', qmEarnings: 'other', qmFilings: 'other', qmFinancials: 'other', - 'qmFinancials-old': 'other', qmIntraday: 'other', qmPrices: 'other', qmSplits: 'other', - eodFinancialsOLD: 'other', eodFundamentalsOLD: 'other', eodIntraday1H: 'other', - eodIntraday1M: 'other', eodIntraday5M: 'other', eodPrices: 'other', eodSymbolChange: 'other', - ceoPosts: 'other', ceoShorts: 'other', teUrls: 'other', ttFutures: 'other', -}; -const fields = ['ticker', 'exchange', 'isin', 'figi', 'cusip', 'name', 'country', 'currency', 'mic', 'conid', 'priority'] as const; -type Field = typeof fields[number]; -type Aliases = Partial>; -const qmId = (field: string) => [ - field, 'profile.' + field, 'profile.info.' + field, 'profile.details.' + field, - 'symbolInfo.' + field, 'symbolInfo.' + field.toUpperCase(), -]; -const aliases: Record = { - qmSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'], - isin: qmId('isin'), cusip: qmId('cusip'), figi: qmId('figi'), currency: qmId('currency') }, - eodSymbols: { ticker: ['Code'], exchange: ['eodExchange', 'Exchange'], isin: ['Isin', 'ISIN'], - name: ['Name'], country: ['Country'], currency: ['Currency'], cusip: ['Cusip'], figi: ['FIGI', 'Figi'] }, - ibSymbols: { ticker: ['localSymbol', 'symbol'], exchange: ['exchangeId', 'exchange_id'], isin: ['isin'], - cusip: ['cusip'], figi: ['figi'], conid: ['conid'], name: ['description'], country: ['country'], currency: ['currency'] }, - ceoSymbols: { ticker: ['symbol'], exchange: ['exchange'], name: ['name'], country: ['countryCode'], - currency: ['currency'], isin: ['isin'], cusip: ['cusip'], figi: ['figi'] }, - qmExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'], - currency: ['currency'], mic: ['operatingMIC', 'mic'], priority: ['priority'] }, - eodExchanges: { exchange: ['Code'], mic: ['OperatingMIC'], country: ['CountryISO2', 'Country'], - currency: ['Currency'], name: ['Name'] }, - ibExchanges: { exchange: ['exchange_id', 'id'], country: ['country_code', 'country'], name: ['name'], - currency: ['currency'], mic: ['operatingMIC', 'mic'] }, - ceoExchanges: { exchange: ['exchange'], country: ['countryCode'], name: ['exchangeName', 'name'], - currency: ['currency'], mic: ['operatingMIC', 'mic'] }, -}; -const requiredFields = fields.slice(0, 8); -const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0; -const upper = (value: string) => value.toUpperCase(); -const sourceOf = (name: string) => /^(qm|eod|ib|ceo|te|tt)(?=[A-Z])/.exec(name)?.[1] ?? 'other'; -const tupleKey = (...parts: string[]) => parts.join('\u0000'); -const text = (value: unknown) => typeof value === 'string' ? value.trim() : - typeof value === 'number' && Number.isFinite(value) ? String(value) : ''; - -function assertReadStages(value: unknown): void { - if (!value || typeof value !== 'object') return; - for (const [key, child] of Object.entries(value)) { - if (key === '$' + 'out' || key === '$' + 'merge') throw Error('Aggregation stage is forbidden'); - assertReadStages(child); - } -} - -function mongoReads(db: Db) { - return { - listCollections: () => db.listCollections({}, { nameOnly: true }).toArray(), - estimatedDocumentCount: (name: string) => db.collection(name).estimatedDocumentCount(), - countDocuments: (name: string) => db.collection(name).countDocuments({}), - find: (name: string, filter: Document = {}) => ({ - limit: (n: number) => { - if (!Number.isSafeInteger(n) || n < 1 || n > 2) throw Error('Expected a bounded example query'); - return db.collection(name).find(filter).sort({ _id: 1 }).limit(n).toArray(); - }, - }), - aggregate: (name: string, stages: Document[]) => { - assertReadStages(stages); - return db.collection(name).aggregate(stages, { batchSize: 2_000 }); - }, - listIndexes: (name: string) => db.collection(name).listIndexes().toArray(), - runCommand: (command: { usersInfo: 1 }) => { - if (Object.keys(command).length !== 1 || command.usersInfo !== 1) throw Error('Expected usersInfo'); - return db.command(command, { readPreference: 'primary' }); - }, - }; -} - -type MongoReads = ReturnType; -type User = { user: string; db: string; roles: { role: string; db: string }[] }; -const readOnly = (user: User) => user.roles.length > 0 && - user.roles.every(({ role }) => role === 'read' || role === 'readAnyDatabase'); -const canRead = (user: User, db: string) => user.roles.some(role => role.role === 'readAnyDatabase' || role.db === db); - -async function mongoUsers(client: MongoClient, name: string) { - const results = await Promise.all(['admin', name].map(db => mongoReads(client.db(db)).runCommand({ usersInfo: 1 }))); - const users: User[] = results.flatMap(result => result.users.map(({ user, db, roles }: User) => ({ user, db, roles }))); - return [...new Map(users.map(user => [tupleKey(user.db, user.user), user])).values()] - .sort((a, b) => cmp(tupleKey(a.db, a.user), tupleKey(b.db, b.user))); -} - -function safeMongoUri(raw: string) { - const uri = new URL(raw); - if (!['localhost', '127.0.0.1', '[::1]'].includes(uri.hostname)) throw Error('Expected a local MongoDB host'); - return uri; -} - -async function mongoReadUri(rootUri: string, name: string, users: User[], env: Partial>) { - const available = users.filter(user => readOnly(user) && canRead(user, name)); - if (!available.length) return rootUri; - const studioEnv = Bun.file(join(homedir(), '.studio', 'test-env', 'stock-bot.env')); - const candidates = [env.PHASE1_MONGO_READ_URI, rootUri, await studioEnv.exists() - ? parseEnv(await studioEnv.text()).MONGODB_URI : undefined]; - for (const raw of candidates) { - if (!raw) continue; - const uri = safeMongoUri(raw), username = decodeURIComponent(uri.username); - const authDb = uri.searchParams.get('authSource') ?? (uri.pathname.slice(1) || 'admin'); - if (available.some(user => user.user === username && user.db === authDb)) return raw; - } - throw Error('A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI'); -} - -function trimmed(doc: Document) { - return Object.fromEntries(Object.entries(doc).map(([key, value]) => { - if (Array.isArray(value)) return [key, { length: value.length, keys: [...new Set(value.slice(0, 5).flatMap(v => - v && typeof v === 'object' ? Object.keys(v) : []))].sort(cmp) }]; - if (value && Object.getPrototypeOf(value) === Object.prototype) return [key, { keys: Object.keys(value).sort(cmp) }]; - return [key, typeof value === 'string' && value.length > 180 ? value.slice(0, 180) + 'โ€ฆ' : value]; - })); -} - -function expression(path: string) { - return { $trim: { input: { $convert: { input: '$' + path, to: 'string', onError: '', onNull: '' } } } }; -} - -const limitStages = (limit: number | null) => limit === null ? [] : [{ $limit: limit }]; - -async function fieldCoverage(mongo: MongoReads, name: string, mapping: Aliases, limit: number | null) { - const names = fields.filter(field => requiredFields.includes(field) || mapping[field]); - const group = Object.fromEntries(names.map(field => [field, { $sum: { $cond: [ - mapping[field]?.length ? { $or: mapping[field]!.map(path => ({ $ne: [expression(path), ''] })) } : false, 1, 0, - ] } }])); - const [counts] = await mongo.aggregate(name, [...limitStages(limit), - { $group: { _id: null, total: { $sum: 1 }, ...group } }]).toArray(); - const total = Number(counts?.total ?? 0); - return { total, aliases: mapping, fields: Object.fromEntries(names.map(field => { - const filled = Number(counts?.[field] ?? 0); - return [field, { filled, fraction: total ? filled / total : 0 }]; - })) }; -} - -async function inventory(mongo: MongoReads, limit: number | null, sampleMemory: () => void) { - const collections = []; - const fillRates: Record>> = {}; - const examples: Partial> = {}; - const group: Record = {}; - for (const row of (await mongo.listCollections()).sort((a, b) => cmp(a.name, b.name))) { - const name = row.name, source = sourceOf(name), entity = entities[name] ?? 'unclassified'; - const estimatedDocumentCount = await mongo.estimatedDocumentCount(name); - const countDocuments = estimatedDocumentCount < 1_000_000 ? await mongo.countDocuments(name) : null; - const indexes = (await mongo.listIndexes(name)).map(index => String(index.name)).sort(cmp); - const keyRows = await mongo.aggregate(name, [ - { $sample: { size: 200 } }, - { $project: { _id: 0, keys: { $map: { input: { $objectToArray: '$$ROOT' }, as: 'field', in: '$$field.k' } } } }, - ]).toArray(); - const topLevelKeys = [...new Set(keyRows.flatMap(value => value.keys))].sort(cmp); - (group[source] ??= []).push(name); - collections.push({ name, source, entity, estimatedDocumentCount, countDocuments, indexes, topLevelKeys }); - const seen = examples[entity] ??= []; - if (seen.length < 2 && estimatedDocumentCount) { - for (const document of await mongo.find(name).limit(2 - seen.length)) seen.push({ collection: name, document: trimmed(document) }); - } - if (aliases[name]) fillRates[name] = await fieldCoverage(mongo, name, aliases[name], limit); - sampleMemory(); - console.error('Inspected ' + name); - } - return { collections, groups: group, examples, fillRates }; -} - -const tables = [ - 'exchanges', 'symbols', 'provider_mappings', 'provider_exchange_mappings', 'sync_status', - 'master_exchanges', 'master_symbols', 'provider_symbol_mappings', -] as const; -type Mapping = { provider: string; code: string; master: string | null; verified: boolean | null; auto: boolean | null }; - -async function readPostgres(client: Client) { - await client.connect(); - await client.query('BEGIN TRANSACTION READ ONLY'); - try { - const counts: Record = {}; - for (const table of tables) { - const { rows: [row] } = await client.query('SELECT to_regclass($1) IS NOT NULL AS present', ['public.' + table]); - counts[table] = row.present - ? Number((await client.query('SELECT count(*) AS total FROM public.' + table)).rows[0].total) : 'missing'; - } - const present = (table: string) => counts[table] !== 'missing'; - const rows = async (sql: string) => (await client.query(sql)).rows; - const exchangeStatus = present('provider_exchange_mappings') ? await rows(` - SELECT provider, master_exchange_id IS NOT NULL AS mapped, verified, active, auto_mapped, count(*)::int AS total - FROM public.provider_exchange_mappings GROUP BY 1,2,3,4,5 ORDER BY 1,2,3,4,5`) : []; - const symbolStatus = present('provider_mappings') ? await rows(` - SELECT provider, verified, count(*)::int AS total - FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : []; - const confidence = present('provider_mappings') ? await rows(` - SELECT provider, confidence, count(*)::int AS total - FROM public.provider_mappings GROUP BY 1,2 ORDER BY 1,2`) : []; - const mapping: Mapping[] = present('provider_exchange_mappings') ? await rows(` - SELECT provider, provider_exchange_code AS code, master_exchange_id AS master, - verified, auto_mapped AS auto FROM public.provider_exchange_mappings - ORDER BY provider, provider_exchange_code`) : []; - return { counts, exchangeStatus, symbolStatus, confidence, mapping }; - } finally { - await client.query('ROLLBACK'); - } -} - -function mappingIndex(mapping: Mapping[]) { - const result = new Map(); - for (const row of mapping) { - const key = tupleKey(row.provider.toLowerCase(), upper(row.code.trim())), previous = result.get(key); - if (previous?.master && row.master && previous.master !== row.master) - throw Error('Conflicting master exchange mappings for a normalized provider code'); - if (!previous || row.master) result.set(key, row); - } - return result; -} - -function pathValue(document: Document, path: string): unknown { - return path.split('.').reduce((parent, key) => - parent && typeof parent === 'object' ? (parent as Document)[key] : undefined, document); -} - -function identifiers(document: Document, mapping: Aliases) { - return Object.fromEntries(fields.map(field => [field, mapping[field]?.map(path => text(pathValue(document, path))).find(Boolean) ?? ''])) as Record; -} - -function projection(mapping: Aliases) { - return Object.fromEntries(Object.values(mapping).flat().map(path => [path, 1])); -} - -function validIsin(value: string) { - if (!/^[A-Z]{2}[A-Z0-9]{9}[0-9]$/.test(value)) return false; - const digits = value.replace(/[A-Z]/g, letter => String(letter.charCodeAt(0) - 55)); - let total = 0; - for (let i = digits.length - 1; i >= 0; i--) { - const n = Number(digits[i]) * ((digits.length - i) % 2 ? 1 : 2); - total += n > 9 ? n - 9 : n; - } - return total % 10 === 0; -} - -const venues = 'US|CA|NASDAQ|NYSE|AMEX|NYSEARCA|TSX|TSE|TSXV|CSE|OTC'; -const prefix = new RegExp('^(?:' + venues + '):'); -const suffix = new RegExp(':(?:' + venues + ')$'); -function tickerKey(raw: string) { - const rules: string[] = []; - let key = raw; - for (const [rule, pattern, replacement] of [ - ['case', /[a-z]/, upper(key)], - ['venue_prefix', prefix, ''], - ['venue_suffix', suffix, ''], - ['us_dot_suffix', /\.US$/, ''], - ['share_class_separator', /^([A-Z0-9]+)[ /-]([A-Z])$/, '$1.$2'], - ['share_class_dot', /^[A-Z0-9]+\.[A-Z]$/, null], - ] as const) { - if (!pattern.test(key)) continue; - rules.push(rule); - if (replacement !== null) key = rule === 'case' ? replacement : key.replace(pattern, replacement); - } - return { key, rules }; -} - -function countryKey(value: string) { - const code = upper(value); - return ({ USA: 'US', 'UNITED STATES': 'US', 'UNITED STATES OF AMERICA': 'US', CAN: 'CA', CANADA: 'CA', - GBR: 'GB', UK: 'GB', 'UNITED KINGDOM': 'GB', AUS: 'AU', AUSTRALIA: 'AU' } as Record)[code] ?? code; -} - -const words = (name: string) => new Set(name.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []); -function similar(a: string, b: string) { - if (!a || !b) return false; - if (a === b) return true; - const one = words(a), two = words(b); - let common = 0; - for (const token of one) if (two.has(token)) common++; - return common > 0 && common / (one.size + two.size - common) >= 0.8; -} - -type Stock = [source: Source, id: unknown, exact: string, ticker: string, exchange: string, master: string, - rawIsin: string, isin: string, cusip: string, figi: string, name: string, country: string, currency: string]; -type Index = Map; -const add = (index: Index, key: string, id: number) => { - if (!key) return; - const ids = index.get(key); - if (ids) ids.push(id); - else index.set(key, [id]); -}; -const marketKey = (ticker: string, market: string) => ticker && market ? tupleKey(ticker, market) : ''; -const stocksFor = (source: Source) => source + 'Symbols'; -const exchangeFor = (source: Source) => source + 'Exchanges'; - -async function gatherStocks(mongo: MongoReads, names: Set, mapping: Map, limit: number | null, memory: () => void) { - const records: Stock[] = []; - const indices = { isin: new Map() as Index, cusip: new Map() as Index, figi: new Map() as Index, - markets: new Map() as Index, rawMarkets: new Map() as Index, currency: new Map() as Index, rawCurrency: new Map() as Index, - tickers: new Map() as Index }; - const counts = Object.fromEntries(sources.map(source => [source, { - noExchangeCode: 0, mappingMissing: 0, mappingHasNullMaster: 0, hasMaster: 0, - normalizations: {} as Record, - }])) as Record }>; - for (const source of sources) { - const name = stocksFor(source); - if (!names.has(name)) continue; - const rules = aliases[name], stats = counts[source]; - for await (const row of mongo.aggregate(name, [{ $project: projection(rules) }, ...limitStages(limit)])) { - const id = identifiers(row, rules), rawIsin = upper(id.isin); - const isin = validIsin(rawIsin) ? rawIsin : ''; - const cusip = /^[0-9A-Z*@#]{9}$/.test(upper(id.cusip)) ? upper(id.cusip) : /^(US|CA)/.test(isin) ? isin.slice(2, 11) : ''; - const figi = /^[A-Z0-9]{12}$/.test(upper(id.figi)) ? upper(id.figi) : ''; - const exchange = upper(id.exchange), mapped = mapping.get(tupleKey(source, exchange)); - if (!exchange) stats.noExchangeCode++; - else if (!mapped) stats.mappingMissing++; - else if (!mapped.master) stats.mappingHasNullMaster++; - else stats.hasMaster++; - const { key: ticker, rules: applied } = tickerKey(id.ticker); - for (const rule of applied) stats.normalizations[rule] = (stats.normalizations[rule] ?? 0) + 1; - const master = mapped?.master ?? '', currency = upper(id.currency); - const n = records.length; - records.push([source, row._id, id.ticker, ticker, exchange, master, rawIsin, isin, cusip, figi, id.name, countryKey(id.country), currency]); - add(indices.isin, isin, n); - add(indices.cusip, cusip, n); - add(indices.figi, figi, n); - add(indices.tickers, ticker, n); - add(indices.markets, marketKey(ticker, master), n); - add(indices.rawMarkets, marketKey(id.ticker, master), n); - if (master && id.name) { - add(indices.currency, marketKey(ticker, currency), n); - add(indices.rawCurrency, marketKey(id.ticker, currency), n); - } - if (n % 2048 === 0) memory(); - } - console.error('Projected ' + name); - } - return { records, indices, counts }; -} - -type StockData = Awaited>; -const tally = () => ({ total: 0, strong: 0, weak_only: 0, unmatched: 0, exact_after_trim: 0, normalized: 0 }); -type Tally = ReturnType; -const sourceBit = Object.fromEntries(sources.map((source, n) => [source, 1 << n])) as Record; - -function hitBits(records: Stock[], ids: number[] | undefined, source: Source, predicate?: (record: Stock) => boolean) { - let bits = 0; - for (const id of ids ?? []) { - const other = records[id]; - if (other[0] !== source && (!predicate || predicate(other))) bits |= sourceBit[other[0]]; - } - return bits; -} - -function countRecord(counts: Tally, mask: number, strong: number, exact: number, normal: number) { - counts.total++; - if (strong & mask) { counts.strong++; return; } - if (exact & mask) counts.exact_after_trim++; - if (normal & mask) counts.normalized++; - if ((exact | normal) & mask) counts.weak_only++; - else counts.unmatched++; -} - -function measureStocks(data: StockData, memory: () => void) { - const { records, indices, counts: coverage } = data; - const bySource = Object.fromEntries(sources.map(source => [source, tally()])) as Record; - const byPair: Record = {}; - for (const source of sources) for (const target of sources) if (source !== target) byPair[source + 'โ†’' + target] = tally(); - for (let i = 0; i < records.length; i++) { - const [source, , raw, ticker, , master, , isin, cusip, figi, name, , currency] = records[i]; - const hits = (index: Index, key: string) => key ? hitBits(records, index.get(key), source) : 0; - const strong = hits(indices.isin, isin) | hits(indices.cusip, cusip) | hits(indices.figi, figi); - const compareName = (row: Stock) => similar(name, row[10]); - const nameHits = (index: Index, ticker: string) => master && name && ticker && currency - ? hitBits(records, index.get(marketKey(ticker, currency)), source, compareName) : 0; - const exact = hits(indices.rawMarkets, marketKey(raw, master)) | nameHits(indices.rawCurrency, raw); - const normal = hits(indices.markets, marketKey(ticker, master)) | nameHits(indices.currency, ticker); - countRecord(bySource[source], 15, strong, exact, normal); - for (const target of sources) if (source !== target) - countRecord(byPair[source + 'โ†’' + target], sourceBit[target], strong, exact, normal); - if (i % 2048 === 0) memory(); - } - return { bySource, byPair, mappingCoverage: coverage }; -} - -async function measureExchanges(mongo: MongoReads, names: Set, mapping: Map, limit: number | null) { - const codes = new Map(); - for (const source of sources) { - const collection = exchangeFor(source), rules = aliases[collection]; - if (!names.has(collection)) continue; - for await (const row of mongo.aggregate(collection, [{ $project: projection(rules) }, ...limitStages(limit)])) { - const fields = identifiers(row, rules), code = upper(fields.exchange); - if (code) codes.set(tupleKey(source, code), - { source, code, mic: upper(fields.mic), country: countryKey(fields.country), name: fields.name }); - } - } - const rows = [...codes.values()]; - return Object.fromEntries(sources.map(source => { - const counts = { total: 0, strong: 0, mappedVerified: 0, mappedAuto: 0, mappedOther: 0, weak_only: 0, unmatched: 0 }; - for (const row of rows.filter(value => value.source === source)) { - counts.total++; - const mapped = mapping.get(tupleKey(source, row.code)); - if (mapped?.master) { - counts.strong++; - if (mapped.verified) counts.mappedVerified++; - else if (mapped.auto) counts.mappedAuto++; - else counts.mappedOther++; - } else if (rows.some(peer => peer.source !== source && - ((row.mic && !/^(X{4}|N\/A|-)$/.test(row.mic) && peer.mic === row.mic) || - (row.country && peer.country === row.country && similar(row.name, peer.name))))) counts.weak_only++; - else counts.unmatched++; - } - return [source, counts]; - })); -} - -type Pair = [number, number]; -type Case = { bucket: string; key: string; ids: number[] }; -const different = (a: string, b: string) => !!a && !!b && a !== b; -function trickySelection({ records, indices }: StockData) { - const cases: Case[] = []; - const idOrder = (a: number, b: number) => cmp(records[a][0], records[b][0]) || cmp(String(records[a][1]), String(records[b][1])); - const pair = (list: number[], test: (a: Stock, b: Stock) => boolean): Pair | undefined => { - if (list.length < 2) return; - const ordered = [...list].sort(idOrder); - for (let i = 0; i < ordered.length; i++) for (let j = i + 1; j < ordered.length; j++) { - const a = ordered[i], b = ordered[j]; - if (records[a][0] !== records[b][0] && test(records[a], records[b])) return [a, b]; - } - }; - const grouped = (bucket: string, index: Index, test: (a: Stock, b: Stock) => boolean) => { - let count = 0; - for (const key of [...index.keys()].sort(cmp)) { - const ids = pair(index.get(key)!, test); - if (!ids) continue; - cases.push({ bucket, key: key.replaceAll('\u0000', ' / '), ids }); - if (++count === 5) break; - } - }; - grouped('isin_currency_or_country_conflict', indices.isin, (a, b) => different(a[11], b[11]) || different(a[12], b[12])); - grouped('isin_ticker_variation', indices.isin, (a, b) => different(a[2], b[2])); - grouped('share_class_format', indices.tickers, (a, b) => - /^[A-Z0-9]+\.[A-Z]$/.test(a[3]) && different(a[2], b[2]) && [a[2], b[2]].some(value => /[ /-][A-Z]$/i.test(value))); - grouped('dual_master_exchanges', indices.isin, (a, b) => different(a[5], b[5])); - grouped('ticker_exchange_conflicting_isins', indices.markets, (a, b) => different(a[7], b[7])); - const invalid = records.flatMap((row, id) => row[6] && !row[7] ? [id] : []) - .sort((a, b) => cmp(records[a][6], records[b][6]) || cmp(records[a][2], records[b][2]) || idOrder(a, b)); - for (const id of invalid.slice(0, 5)) cases.push({ bucket: 'invalid_isin', key: records[id][6], ids: [id] }); - return cases; -} - -async function trickyDocuments(mongo: MongoReads, data: StockData) { - const output = []; - for (const { bucket, key, ids } of trickySelection(data)) { - const documents = []; - for (const i of ids) { - const [source, _id, ticker, normalizedTicker, , master] = data.records[i], collection = stocksFor(source); - const [doc] = await mongo.find(collection, { _id }).limit(1); - if (!doc) throw Error('A selected fixture disappeared during the inventory'); - documents.push({ collection, _id, ticker, normalizedTicker, resolvedMasterExchangeId: master || null, document: trimmed(doc) }); - } - output.push({ bucket, key, documents }); - } - return output; -} - -async function main() { - const started = performance.now(), generatedAt = new Date().toISOString(); - let peakRSS = 0; - const memory = () => { peakRSS = Math.max(peakRSS, process.memoryUsage.rss(), process.resourceUsage().maxRSS * 1024); }; - memory(); - const args = parseArgs({ options: { 'sample-limit': { type: 'string' } } }); - const limit = args.values['sample-limit'] === undefined ? null : Number(args.values['sample-limit']); - if (limit !== null && (!Number.isSafeInteger(limit) || limit < 1)) throw Error('Expected a positive sample limit'); - const env = parseEnv(await Bun.file(resolve(import.meta.dir, '../../../../.env')).text()); - const rootUri = env.MONGODB_URI; - if (!rootUri) throw Error('Missing MONGODB_URI'); - const parsed = safeMongoUri(rootUri), name = env.MONGODB_DATABASE || parsed.pathname.slice(1) || 'stock'; - const host = env.POSTGRES_HOST; - if (!host || !['localhost', '127.0.0.1', '::1'].includes(host)) throw Error('Expected a local Postgres host'); - const metadata = new MongoClient(rootUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 }); - const pg = new Client({ - host, port: Number(env.POSTGRES_PORT || 5432), database: env.POSTGRES_DATABASE, - user: env.POSTGRES_USERNAME, password: env.POSTGRES_PASSWORD, connectionTimeoutMillis: 5_000, - }); - let reader: MongoClient | undefined; - try { - await metadata.connect(); - const users = await mongoUsers(metadata, name); - const readUri = await mongoReadUri(rootUri, name, users, env), active = safeMongoUri(readUri); - let dbClient = metadata; - if (readUri !== rootUri) { - reader = new MongoClient(readUri, { readPreference: 'secondaryPreferred', serverSelectionTimeoutMS: 5_000 }); - await reader.connect(); - dbClient = reader; - } - const mongo = mongoReads(dbClient.db(name)); - const { mapping: rows, ...postgres } = await readPostgres(pg); - const mapping = mappingIndex(rows); - const { collections, groups, examples, fillRates } = await inventory(mongo, limit, memory); - const names = new Set(collections.map(collection => collection.name)); - const data = await gatherStocks(mongo, names, mapping, limit, memory); - const stocks = measureStocks(data, memory); - const exchanges = await measureExchanges(mongo, names, mapping, limit); - const trickyCases = await trickyDocuments(mongo, data); - memory(); - console.log(JSON.stringify({ - generatedAt, - mongo: { uriMasked: active.protocol + '//***:***@' + active.host + '/' + name, - db: name, users, readOnlyUserExists: users.some(readOnly), collectionLogin: readUri === rootUri ? 'configured' : 'read-only' }, - collections, sources: { collections: groups, examples }, fillRates, postgres, matching: { stocks, exchanges }, - trickyCases, sampleLimit: limit, runtimeMs: Math.round(performance.now() - started), peakRssMb: Math.round(peakRSS / 1048576), - })); - } finally { - await Promise.allSettled([metadata.close(), pg.end(), reader?.close()]); - } -} - -await main().catch(error => { - const safeMessages = ['Aggregation stage is forbidden', 'Expected a bounded example query', 'Expected usersInfo', - 'Expected a local MongoDB host', 'Expected a local Postgres host', 'Missing MONGODB_URI', 'Expected a positive sample limit', - 'A read-only MongoDB user exists but its URI is unavailable; supply PHASE1_MONGO_READ_URI', - 'Conflicting master exchange mappings for a normalized provider code', 'A selected fixture disappeared during the inventory']; - console.error('Inventory failed: ' + (safeMessages.includes(error?.message) ? error.message : - String(error?.name || 'Error') + (error?.code ? ' (' + String(error.code) + ')' : ''))); - process.exitCode = 1; -}); diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts index 01d6fbb3..b4e8bfd2 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -1,7 +1,6 @@ import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; import type { IServiceContainer } from '@stock-bot/services'; import { clearPostgreSQLData } from './operations/clear-postgresql-data.operations'; -import { getSyncStatus } from './operations/enhanced-sync-status.operations'; import { getExchangeStats } from './operations/exchange-stats.operations'; import { getProviderMappingStats } from './operations/provider-mapping-stats.operations'; import { syncQMExchanges } from './operations/qm-exchanges.operations'; @@ -97,15 +96,6 @@ class ExchangesHandler extends BaseHandler { this.log('info', 'Getting provider mapping statistics...'); return getProviderMappingStats({}, this); } - - /** - * Get enhanced sync status - */ - @Operation('enhanced-sync-status') - async getEnhancedSyncStatus(): Promise { - this.log('info', 'Getting enhanced sync status...'); - return getSyncStatus({}, this); - } } export { ExchangesHandler }; diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/enhanced-sync-status.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/enhanced-sync-status.operations.ts deleted file mode 100644 index 0ea9a797..00000000 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/enhanced-sync-status.operations.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import type { JobPayload, SyncStatus } from '../../../types/job-payloads'; - -const logger = getLogger('enhanced-sync-status'); - -export async function getSyncStatus( - payload: JobPayload, - container: IServiceContainer -): Promise { - logger.info('Getting comprehensive sync status...'); - - try { - const { postgres: postgresClient } = requireServices(container, 'postgres'); - const query = ` - SELECT provider, data_type as "dataType", last_sync_at as "lastSyncAt", - last_sync_count as "lastSyncCount", sync_errors as "syncErrors" - FROM sync_status - ORDER BY provider, data_type - `; - const result = await postgresClient.query(query); - - logger.info(`Retrieved sync status for ${result.rows.length} entries`); - return result.rows; - } catch (error) { - logger.error('Failed to get sync status', { error }); - throw error; - } -} diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/index.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/index.ts deleted file mode 100644 index b798ee51..00000000 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { clearPostgreSQLData } from './clear-postgresql-data.operations'; -import { getSyncStatus } from './enhanced-sync-status.operations'; -import { getExchangeStats } from './exchange-stats.operations'; -import { getProviderMappingStats } from './provider-mapping-stats.operations'; -import { syncQMExchanges } from './qm-exchanges.operations'; -import { syncAllExchanges } from './sync-all-exchanges.operations'; -import { syncIBExchanges } from './sync-ib-exchanges.operations'; -import { syncQMProviderMappings } from './sync-qm-provider-mappings.operations'; - -export const exchangeOperations = { - syncAllExchanges, - syncQMExchanges, - syncIBExchanges, - syncQMProviderMappings, - clearPostgreSQLData, - getExchangeStats, - getProviderMappingStats, - 'enhanced-sync-status': getSyncStatus, -}; diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/index.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/index.ts deleted file mode 100644 index b4b431d5..00000000 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { syncQMSymbols } from './qm-symbols.operations'; -import { getSyncStatus } from './sync-status.operations'; -import { syncSymbolsFromProvider } from './sync-symbols-from-provider.operations'; - -export const symbolOperations = { - syncQMSymbols, - syncSymbolsFromProvider, - getSyncStatus, -}; diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index 714dbbbc..98cf0e36 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -29,7 +29,7 @@ const app = new ServiceApplication( serviceName: 'data-pipeline', hostname: security.hostname, enableHandlers: true, - enableScheduledJobs: true, + enableScheduledJobs: config.queue?.enableScheduledJobs ?? true, corsConfig: { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], diff --git a/apps/stock/data-pipeline/src/routes/create-routes.ts b/apps/stock/data-pipeline/src/routes/create-routes.ts index d7012b85..087f64b7 100644 --- a/apps/stock/data-pipeline/src/routes/create-routes.ts +++ b/apps/stock/data-pipeline/src/routes/create-routes.ts @@ -1,23 +1,9 @@ -/** - * Route factory for data pipeline service - * Creates routes with access to the service container - */ - import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { createEnhancedSyncRoutes } from './enhanced-sync.routes'; +import type { IServiceContainer } from '@stock-bot/services'; import { healthRoutes } from './health.routes'; -import { createStatsRoutes } from './stats.routes'; -import { createSyncRoutes } from './sync.routes'; -export function createRoutes(container: IServiceContainer): Hono { +export function createRoutes(_container: IServiceContainer): Hono { const app = new Hono(); - - // Mount routes app.route('/health', healthRoutes); - app.route('/sync', createSyncRoutes(container)); - app.route('/sync', createEnhancedSyncRoutes(container)); - app.route('/sync/stats', createStatsRoutes(container)); - return app; } diff --git a/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts b/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts deleted file mode 100644 index a36d2422..00000000 --- a/apps/stock/data-pipeline/src/routes/enhanced-sync.routes.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; -import { parseReferenceDataResetRequest } from '@stock-bot/types'; - -const logger = getLogger('enhanced-sync-routes'); - -export function createEnhancedSyncRoutes(container: IServiceContainer) { - const enhancedSync = new Hono(); - - // Enhanced sync endpoints - enhancedSync.post('/exchanges/all', async c => { - if (c.req.query('clear') && c.req.query('clear') !== 'false') { - return c.json({ error: 'Sync is non-destructive; use the explicit maintenance reset' }, 400); - } - try { - const clearFirst = c.req.query('clear') === 'true'; - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('sync-all-exchanges', { - handler: 'exchanges', - operation: 'sync-all-exchanges', - payload: { clearFirst }, - }); - - return c.json({ success: true, jobId: job.id, message: 'Enhanced exchange sync job queued' }); - } catch (error) { - logger.error('Failed to queue enhanced exchange sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - enhancedSync.post('/provider-mappings/qm', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('sync-qm-provider-mappings', { - handler: 'exchanges', - operation: 'sync-qm-provider-mappings', - payload: {}, - }); - - return c.json({ - success: true, - jobId: job.id, - message: 'QM provider mappings sync job queued', - }); - } catch (error) { - logger.error('Failed to queue QM provider mappings sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - enhancedSync.post('/provider-mappings/ib', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('sync-ib-exchanges', { - handler: 'exchanges', - operation: 'sync-ib-exchanges', - payload: {}, - }); - - return c.json({ - success: true, - jobId: job.id, - message: 'IB exchanges sync job queued', - }); - } catch (error) { - logger.error('Failed to queue IB exchanges sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - enhancedSync.get('/status', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const symbolsQueue = queueManager.getQueue('symbols'); - - const job = await symbolsQueue.add('sync-status', { - handler: 'symbols', - operation: 'sync-status', - payload: {}, - }); - - return c.json({ success: true, jobId: job.id, message: 'Sync status job queued' }); - } catch (error) { - logger.error('Failed to queue sync status job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - enhancedSync.post('/clear/postgresql', async c => { - const input: unknown = await c.req.json().catch(() => null); - let payload; - try { - payload = parseReferenceDataResetRequest(input); - } catch (error) { - return c.json({ error: error instanceof Error ? error.message : 'Invalid reset' }, 400); - } - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('clear-postgresql-data', { - handler: 'exchanges', - operation: 'clear-postgresql-data', - payload, - }); - - return c.json({ - success: true, - jobId: job.id, - message: 'PostgreSQL data clear job queued', - }); - } catch (error) { - logger.error('Failed to queue PostgreSQL clear job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - return enhancedSync; -} diff --git a/apps/stock/data-pipeline/src/routes/index.ts b/apps/stock/data-pipeline/src/routes/index.ts deleted file mode 100644 index 24bea6fc..00000000 --- a/apps/stock/data-pipeline/src/routes/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Export all route modules -export { healthRoutes } from './health.routes'; -export { createSyncRoutes } from './sync.routes'; -export { createEnhancedSyncRoutes } from './enhanced-sync.routes'; -export { createStatsRoutes } from './stats.routes'; diff --git a/apps/stock/data-pipeline/src/routes/stats.routes.ts b/apps/stock/data-pipeline/src/routes/stats.routes.ts deleted file mode 100644 index 03c54f20..00000000 --- a/apps/stock/data-pipeline/src/routes/stats.routes.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('stats-routes'); - -export function createStatsRoutes(container: IServiceContainer) { - const stats = new Hono(); - - // Statistics endpoints - stats.get('/exchanges', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('get-exchange-stats', { - handler: 'exchanges', - operation: 'get-exchange-stats', - payload: {}, - }); - - // Wait for job to complete and return result - const result = await exchangesQueue.waitForJob(job); - return c.json(result); - } catch (error) { - logger.error('Failed to get exchange stats', { error }); - return c.json({ error: error instanceof Error ? error.message : 'Unknown error' }, 500); - } - }); - - stats.get('/provider-mappings', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('get-provider-mapping-stats', { - handler: 'exchanges', - operation: 'get-provider-mapping-stats', - payload: {}, - }); - - // Wait for job to complete and return result - const result = await exchangesQueue.waitForJob(job); - return c.json(result); - } catch (error) { - logger.error('Failed to get provider mapping stats', { error }); - return c.json({ error: error instanceof Error ? error.message : 'Unknown error' }, 500); - } - }); - - return stats; -} diff --git a/apps/stock/data-pipeline/src/routes/sync.routes.ts b/apps/stock/data-pipeline/src/routes/sync.routes.ts deleted file mode 100644 index 92e11308..00000000 --- a/apps/stock/data-pipeline/src/routes/sync.routes.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('sync-routes'); - -export function createSyncRoutes(container: IServiceContainer) { - const sync = new Hono(); - - // Manual sync trigger endpoints - sync.post('/symbols', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const symbolsQueue = queueManager.getQueue('symbols'); - - const job = await symbolsQueue.add('sync-qm-symbols', { - handler: 'symbols', - operation: 'sync-qm-symbols', - payload: {}, - }); - - return c.json({ success: true, jobId: job.id, message: 'QM symbols sync job queued' }); - } catch (error) { - logger.error('Failed to queue symbol sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - sync.post('/exchanges', async c => { - try { - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const exchangesQueue = queueManager.getQueue('exchanges'); - - const job = await exchangesQueue.add('sync-qm-exchanges', { - handler: 'exchanges', - operation: 'sync-qm-exchanges', - payload: {}, - }); - - return c.json({ success: true, jobId: job.id, message: 'QM exchanges sync job queued' }); - } catch (error) { - logger.error('Failed to queue exchange sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - sync.post('/symbols/:provider', async c => { - try { - const provider = c.req.param('provider'); - const queueManager = container.queueManager; - if (!queueManager) { - return c.json({ success: false, error: 'Queue manager not available' }, 503); - } - - const symbolsQueue = queueManager.getQueue('symbols'); - - const job = await symbolsQueue.add('sync-symbols-from-provider', { - handler: 'symbols', - operation: 'sync-symbols-from-provider', - payload: { provider }, - }); - - return c.json({ - success: true, - jobId: job.id, - message: `${provider} symbols sync job queued`, - }); - } catch (error) { - logger.error('Failed to queue provider symbol sync job', { error }); - return c.json( - { success: false, error: error instanceof Error ? error.message : 'Unknown error' }, - 500 - ); - } - }); - - return sync; -} diff --git a/apps/stock/engine/MIGRATION.md b/apps/stock/engine/MIGRATION.md index a161c9c2..1a75e9c9 100644 --- a/apps/stock/engine/MIGRATION.md +++ b/apps/stock/engine/MIGRATION.md @@ -11,7 +11,6 @@ Current research and paper execution share the authoritative Rust core in [src/f | Current financial execution | `src/financial/`, `src/api/replay.rs`, `src/api/paper.rs` | Use for canonical research and paper execution. Preserve deterministic ordering, financial invariants and recovery contracts. | | Indicators and analytical calculations | `src/indicators/`, `src/analytics/`, native risk/orderbook analytics, `libs/calculations/` | Retained capabilities. Reuse reviewed implementations and their fixtures. | | Legacy native execution and accounting | `TradingEngine`, native `BacktestEngine`, `src/core/`, `src/backtest/`, `src/positions/`, `src/risk/`, `src/strategies/` | Retained for compatibility, regression tests and existing algorithm examples. They are not an alternative execution path for current admitted research jobs. | -| Uncompiled reporting reference | [reference/legacy-reporting](reference/legacy-reporting/README.md) | Original calculation prototypes retained byte-for-byte for inspection. Incomplete and unreviewed; not a runtime API or an oracle for financial results. | The compiled `src/backtest/simple_results.rs`, `src/strategies/mean_reversion_fixed.rs`, public native constructors, and historical regression fixtures are unchanged by this cleanup. No saved dataset, strategy package, result or checkpoint is migrated or removed. @@ -28,7 +27,7 @@ Evidence baseline: `700ee09c`. Cargo's library target is `src/lib.rs`; its modul | `events.bak/mod.rs` | Removed undeclared event-bus scaffold. No current event or recovery journal uses it. | | `modes.bak/{mod,backtest,paper,live}.rs` | Removed undeclared alternate runtime, mock broker and simplistic fill/accounting implementations. These depended on the abandoned event/domain design, not the canonical matcher or any supported broker. | | `strategies/framework/mod.rs` | Removed undeclared generic strategy trait/context and no-op base strategy. It contained no concrete signal algorithm; all compiled strategies remain. | -| `backtest/metrics_calculator.rs`, `backtest/results.rs` | Moved unchanged to `reference/legacy-reporting/`. They were not declared in `backtest/mod.rs`. Retained because they contain statistical/reporting prototypes and supporting result types worth inspecting before any later reuse. | +| `backtest/metrics_calculator.rs`, `backtest/results.rs` | Removed uncompiled reporting prototypes; canonical metric calculations live in `@stock-bot/calculations`. | The archived calculator includes return, drawdown, streak and symbol-analysis logic alongside placeholder fields and incomplete methods. Moving it does not make those formulas reviewed or compilable. New calculations should enter the reviewed calculation library with explicit semantics and tests, not reactivate the abandoned financial simulator. diff --git a/apps/stock/engine/bun.lock b/apps/stock/engine/bun.lock deleted file mode 100644 index f85fdcbf..00000000 --- a/apps/stock/engine/bun.lock +++ /dev/null @@ -1,17 +0,0 @@ -{ - "lockfileVersion": 1, - "workspaces": { - "": { - "name": "@stock-bot/engine", - "devDependencies": { - "@napi-rs/cli": "^2.16.3", - "cargo-cp-artifact": "^0.1", - }, - }, - }, - "packages": { - "@napi-rs/cli": ["@napi-rs/cli@2.18.4", "", { "bin": { "napi": "scripts/index.js" } }, "sha512-SgJeA4df9DE2iAEpr3M2H0OKl/yjtg1BnRI5/JyowS71tUWhrfSu2LT0V3vlHET+g1hBVlrO60PmEXwUEKp8Mg=="], - - "cargo-cp-artifact": ["cargo-cp-artifact@0.1.9", "", { "bin": { "cargo-cp-artifact": "bin/cargo-cp-artifact.js" } }, "sha512-6F+UYzTaGB+awsTXg0uSJA1/b/B3DDJzpKVRu0UmyI7DmNeaAl2RFHuTGIN6fEgpadRxoXGb7gbC1xo4C3IdyA=="], - } -} diff --git a/apps/stock/engine/package.json b/apps/stock/engine/package.json index a0aeeb7c..8ca12236 100644 --- a/apps/stock/engine/package.json +++ b/apps/stock/engine/package.json @@ -31,13 +31,12 @@ }, "scripts": { "build": "napi build dist --dts index.d.ts --no-dts-header", - "build:debug": "npm run build --", - "build:release": "npm run build -- --release", + "build:debug": "bun run build", + "build:release": "bun run build --release", "build:napi": "bun run build --release", "test": "cargo test" }, "devDependencies": { - "@napi-rs/cli": "^2.16.3", - "cargo-cp-artifact": "^0.1" + "@napi-rs/cli": "^2.16.3" } } diff --git a/apps/stock/engine/reference/legacy-reporting/README.md b/apps/stock/engine/reference/legacy-reporting/README.md deleted file mode 100644 index 06492b7e..00000000 --- a/apps/stock/engine/reference/legacy-reporting/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Uncompiled legacy reporting reference - -These two files were moved byte-for-byte from `src/backtest/metrics_calculator.rs` and `src/backtest/results.rs` at baseline `700ee09c`. They were already outside the Rust module graph; this directory is not compiled or exported. - -`metrics_calculator.rs` retains return/volatility/risk-ratio, drawdown, streak and symbol-summary prototypes. `results.rs` retains their supporting report structures. They depend on obsolete types and contain unfinished calculations, fabricated placeholder zeros, and financial/statistical assumptions that have not passed the canonical research gates. They are reference material, not supported calculations or expected-result fixtures. - -Use the reviewed [calculation library](../../../../../libs/calculations/README.md) and canonical [financial reporting](../../src/financial/reporting.rs) for current work. If a prototype is useful, port only that calculation with explicit units, sampling/alignment/null semantics and independent fixtures. Do not import this directory into the engine or revive its old result model. diff --git a/apps/stock/engine/reference/legacy-reporting/metrics_calculator.rs b/apps/stock/engine/reference/legacy-reporting/metrics_calculator.rs deleted file mode 100644 index 71f35606..00000000 --- a/apps/stock/engine/reference/legacy-reporting/metrics_calculator.rs +++ /dev/null @@ -1,669 +0,0 @@ -use chrono::{DateTime, Utc, Datelike}; -use std::collections::HashMap; -use super::results::*; -use super::{BacktestConfig, CompletedTrade}; -use super::trade_tracker::CompletedTrade as TrackedTrade; -use crate::{Position, Side}; - -pub struct MetricsCalculator { - config: BacktestConfig, - equity_curve: Vec<(DateTime, f64)>, - trades: Vec, - fills: Vec, - positions: HashMap, -} - -impl MetricsCalculator { - pub fn new( - config: BacktestConfig, - equity_curve: Vec<(DateTime, f64)>, - trades: Vec, - fills: Vec, - positions: HashMap, - ) -> Self { - Self { - config, - equity_curve, - trades, - fills, - positions, - } - } - - pub fn calculate_all_metrics(&self) -> BacktestResult { - let start_time = Utc::now(); - let backtest_id = format!("rust-{}", start_time.timestamp_millis()); - - // Calculate comprehensive metrics - let metrics = self.calculate_metrics(); - - // Convert equity curve - let equity_points: Vec = self.equity_curve.iter() - .map(|(dt, value)| EquityPoint { - timestamp: dt.timestamp_millis(), - value: *value, - }) - .collect(); - - // Calculate drawdown curve - let drawdown_curve = self.calculate_drawdown_curve(); - - // Calculate returns - let daily_returns = self.calculate_daily_returns(); - let cumulative_returns = self.calculate_cumulative_returns(); - - // Convert trades to UI format - let trades = self.convert_fills_to_trades(); - let open_trades = self.get_open_trades(); - - // Period analysis - let monthly_returns = self.calculate_period_returns("monthly"); - let yearly_returns = self.calculate_period_returns("yearly"); - - // Symbol analysis - let symbol_analysis = self.calculate_symbol_analysis(); - - // Drawdown periods - let drawdown_periods = self.analyze_drawdown_periods(); - - // Exposure analysis - let exposure_analysis = self.calculate_exposure_analysis(); - - // Position history - let position_history = self.calculate_position_history(); - - // Trade signals (extracted from trades) - let trade_signals = self.extract_trade_signals(); - - BacktestResult { - backtest_id, - status: "completed".to_string(), - started_at: self.config.start_time.to_rfc3339(), - completed_at: Utc::now().to_rfc3339(), - execution_time_ms: (Utc::now() - start_time).num_milliseconds() as u64, - config: self.config.clone(), - metrics, - equity_curve: equity_points, - drawdown_curve, - daily_returns, - cumulative_returns, - trades, - open_trades, - trade_signals, - positions: self.positions.clone(), - position_history, - monthly_returns, - yearly_returns, - symbol_analysis, - drawdown_periods, - exposure_analysis, - ohlc_data: HashMap::new(), // Will be filled by orchestrator - error: None, - warnings: None, - } - } - - fn calculate_metrics(&self) -> BacktestMetrics { - let initial_capital = self.config.initial_capital; - let final_capital = self.equity_curve.last().map(|(_, v)| *v).unwrap_or(initial_capital); - - // Core performance - let total_return = final_capital - initial_capital; - let total_return_pct = (total_return / initial_capital) * 100.0; - let days = (self.config.end_time - self.config.start_time).num_days() as f64; - let years = days / 365.25; - let annualized_return = if years > 0.0 { - ((final_capital / initial_capital).powf(1.0 / years) - 1.0) * 100.0 - } else { - 0.0 - }; - - // Trade statistics - let total_trades = self.trades.len(); - let winning_trades = self.trades.iter().filter(|t| t.pnl > 0.0).count(); - let losing_trades = self.trades.iter().filter(|t| t.pnl < 0.0).count(); - let breakeven_trades = self.trades.iter().filter(|t| t.pnl == 0.0).count(); - - let win_rate = if total_trades > 0 { - (winning_trades as f64 / total_trades as f64) * 100.0 - } else { - 0.0 - }; - - let loss_rate = if total_trades > 0 { - (losing_trades as f64 / total_trades as f64) * 100.0 - } else { - 0.0 - }; - - // PnL calculations - let total_pnl = self.trades.iter().map(|t| t.pnl).sum::(); - let total_commission = self.trades.iter().map(|t| t.commission).sum::(); - let net_pnl = total_pnl - total_commission; - - let wins: Vec = self.trades.iter().filter(|t| t.pnl > 0.0).map(|t| t.pnl).collect(); - let losses: Vec = self.trades.iter().filter(|t| t.pnl < 0.0).map(|t| t.pnl).collect(); - - let avg_win = if !wins.is_empty() { - wins.iter().sum::() / wins.len() as f64 - } else { - 0.0 - }; - - let avg_loss = if !losses.is_empty() { - losses.iter().sum::() / losses.len() as f64 - } else { - 0.0 - }; - - let largest_win = wins.iter().cloned().fold(0.0, f64::max); - let largest_loss = losses.iter().cloned().fold(0.0, f64::min); - - let avg_trade_pnl = if total_trades > 0 { - total_pnl / total_trades as f64 - } else { - 0.0 - }; - - // Risk metrics - let returns = self.calculate_returns_series(); - let volatility = self.calculate_volatility(&returns); - let sharpe_ratio = self.calculate_sharpe_ratio(&returns, volatility); - let sortino_ratio = self.calculate_sortino_ratio(&returns); - let (max_drawdown, max_drawdown_pct, max_dd_duration) = self.calculate_max_drawdown(); - - let calmar_ratio = if max_drawdown_pct != 0.0 { - annualized_return / max_drawdown_pct.abs() - } else { - 0.0 - }; - - // Value at Risk - let (var_95, cvar_95) = self.calculate_var_cvar(&returns, 0.95); - - // Profit factor - let gross_profit = wins.iter().sum::(); - let gross_loss = losses.iter().map(|l| l.abs()).sum::(); - let profit_factor = if gross_loss > 0.0 { - gross_profit / gross_loss - } else if gross_profit > 0.0 { - f64::INFINITY - } else { - 0.0 - }; - - // Expectancy - let expectancy = avg_win * (win_rate / 100.0) - avg_loss.abs() * (loss_rate / 100.0); - let expectancy_ratio = if avg_loss != 0.0 { - expectancy / avg_loss.abs() - } else { - 0.0 - }; - - // Position statistics - let avg_trade_duration_hours = if total_trades > 0 { - self.trades.iter() - .map(|t| t.duration_seconds as f64 / 3600.0) - .sum::() / total_trades as f64 - } else { - 0.0 - }; - - let total_long_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Buy)).count(); - let total_short_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Sell)).count(); - - let long_wins = self.trades.iter() - .filter(|t| matches!(t.side, Side::Buy) && t.pnl > 0.0) - .count(); - let short_wins = self.trades.iter() - .filter(|t| matches!(t.side, Side::Sell) && t.pnl > 0.0) - .count(); - - let long_win_rate = if total_long_trades > 0 { - (long_wins as f64 / total_long_trades as f64) * 100.0 - } else { - 0.0 - }; - - let short_win_rate = if total_short_trades > 0 { - (short_wins as f64 / total_short_trades as f64) * 100.0 - } else { - 0.0 - }; - - // Trading activity - let total_volume_traded = self.trades.iter() - .map(|t| t.quantity * t.entry_price + t.quantity * t.exit_price) - .sum::(); - - let commission_pct_of_pnl = if total_pnl != 0.0 { - (total_commission / total_pnl.abs()) * 100.0 - } else { - 0.0 - }; - - // Calculate additional metrics - let downside_deviation = self.calculate_downside_deviation(&returns); - let win_loss_ratio = if avg_loss != 0.0 { - avg_win / avg_loss.abs() - } else { - 0.0 - }; - - let kelly_criterion = if win_loss_ratio > 0.0 { - (win_rate / 100.0) - ((1.0 - win_rate / 100.0) / win_loss_ratio) - } else { - 0.0 - }; - - // Streaks - let (max_wins, max_losses, current_streak) = self.calculate_streaks(); - - BacktestMetrics { - // Core Performance - total_return, - total_return_pct, - annualized_return, - total_pnl, - net_pnl, - - // Risk Metrics - sharpe_ratio, - sortino_ratio, - calmar_ratio, - max_drawdown, - max_drawdown_pct, - max_drawdown_duration_days: max_dd_duration, - volatility, - downside_deviation, - var_95, - cvar_95, - - // Trade Statistics - total_trades, - winning_trades, - losing_trades, - breakeven_trades, - win_rate, - loss_rate, - avg_win, - avg_loss, - largest_win, - largest_loss, - avg_trade_pnl, - avg_trade_duration_hours, - profit_factor, - expectancy, - expectancy_ratio, - - // Position Statistics - avg_position_size: 0.0, // TODO: Calculate from position history - max_position_size: 0.0, - avg_positions_held: 0.0, - max_concurrent_positions: 0, - total_long_trades, - total_short_trades, - long_win_rate, - short_win_rate, - - // Trading Activity - total_volume_traded, - total_commission_paid: total_commission, - commission_pct_of_pnl, - avg_daily_trades: 0.0, // TODO: Calculate - max_daily_trades: 0, - trading_days: 0, - exposure_time_pct: 0.0, - - // Efficiency Metrics - return_over_max_dd: if max_drawdown != 0.0 { - total_return / max_drawdown.abs() - } else { - 0.0 - }, - win_loss_ratio, - kelly_criterion, - ulcer_index: 0.0, // TODO: Calculate - serenity_ratio: 0.0, - lake_ratio: 0.0, - - // Monthly/Period Analysis - best_month_return: 0.0, // TODO: Calculate from monthly returns - worst_month_return: 0.0, - positive_months: 0, - negative_months: 0, - monthly_win_rate: 0.0, - avg_monthly_return: 0.0, - - // Streak Analysis - max_consecutive_wins: max_wins, - max_consecutive_losses: max_losses, - current_streak, - avg_winning_streak: 0.0, // TODO: Calculate - avg_losing_streak: 0.0, - } - } - - fn calculate_returns_series(&self) -> Vec { - let mut returns = Vec::new(); - for i in 1..self.equity_curve.len() { - let prev_value = self.equity_curve[i - 1].1; - let curr_value = self.equity_curve[i].1; - if prev_value > 0.0 { - returns.push((curr_value - prev_value) / prev_value); - } - } - returns - } - - fn calculate_volatility(&self, returns: &[f64]) -> f64 { - if returns.is_empty() { - return 0.0; - } - - let mean = returns.iter().sum::() / returns.len() as f64; - let variance = returns.iter() - .map(|r| (r - mean).powi(2)) - .sum::() / returns.len() as f64; - - // Annualize the volatility - variance.sqrt() * (252.0_f64).sqrt() - } - - fn calculate_sharpe_ratio(&self, returns: &[f64], volatility: f64) -> f64 { - if volatility == 0.0 || returns.is_empty() { - return 0.0; - } - - let mean_return = returns.iter().sum::() / returns.len() as f64; - let annualized_return = mean_return * 252.0; - let risk_free_rate = 0.02; // 2% annual risk-free rate - - (annualized_return - risk_free_rate) / volatility - } - - fn calculate_sortino_ratio(&self, returns: &[f64]) -> f64 { - if returns.is_empty() { - return 0.0; - } - - let mean_return = returns.iter().sum::() / returns.len() as f64; - let downside_deviation = self.calculate_downside_deviation(returns); - - if downside_deviation == 0.0 { - return 0.0; - } - - let annualized_return = mean_return * 252.0; - let risk_free_rate = 0.02; - - (annualized_return - risk_free_rate) / downside_deviation - } - - fn calculate_downside_deviation(&self, returns: &[f64]) -> f64 { - let negative_returns: Vec = returns.iter() - .filter(|&&r| r < 0.0) - .cloned() - .collect(); - - if negative_returns.is_empty() { - return 0.0; - } - - let mean = negative_returns.iter().sum::() / negative_returns.len() as f64; - let variance = negative_returns.iter() - .map(|r| (r - mean).powi(2)) - .sum::() / negative_returns.len() as f64; - - variance.sqrt() * (252.0_f64).sqrt() - } - - fn calculate_max_drawdown(&self) -> (f64, f64, i64) { - let mut max_drawdown = 0.0; - let mut max_drawdown_pct = 0.0; - let mut max_duration = 0i64; - let mut peak = self.config.initial_capital; - let mut peak_date = self.config.start_time; - - for (date, value) in &self.equity_curve { - if *value > peak { - peak = *value; - peak_date = *date; - } - - let drawdown = peak - value; - let drawdown_pct = (drawdown / peak) * 100.0; - - if drawdown > max_drawdown { - max_drawdown = drawdown; - max_drawdown_pct = drawdown_pct; - } - - if drawdown > 0.0 { - let duration = (*date - peak_date).num_days(); - if duration > max_duration { - max_duration = duration; - } - } - } - - (max_drawdown, max_drawdown_pct, max_duration) - } - - fn calculate_var_cvar(&self, returns: &[f64], confidence: f64) -> (f64, f64) { - if returns.is_empty() { - return (0.0, 0.0); - } - - let mut sorted_returns = returns.to_vec(); - sorted_returns.sort_by(|a, b| a.partial_cmp(b).unwrap()); - - let index = ((1.0 - confidence) * sorted_returns.len() as f64) as usize; - let var = sorted_returns[index]; - - let cvar = sorted_returns[..=index].iter().sum::() / (index + 1) as f64; - - (var * 100.0, cvar * 100.0) - } - - fn calculate_streaks(&self) -> (usize, usize, i32) { - let mut max_wins = 0; - let mut max_losses = 0; - let mut current_streak = 0; - let mut current_wins = 0; - let mut current_losses = 0; - - for trade in &self.trades { - if trade.pnl > 0.0 { - current_wins += 1; - current_losses = 0; - if current_wins > max_wins { - max_wins = current_wins; - } - current_streak = current_wins as i32; - } else if trade.pnl < 0.0 { - current_losses += 1; - current_wins = 0; - if current_losses > max_losses { - max_losses = current_losses; - } - current_streak = -(current_losses as i32); - } - } - - (max_wins, max_losses, current_streak) - } - - fn calculate_drawdown_curve(&self) -> Vec { - let mut drawdown_curve = Vec::new(); - let mut peak = self.config.initial_capital; - - for (date, value) in &self.equity_curve { - if *value > peak { - peak = *value; - } - let drawdown_pct = ((peak - value) / peak) * 100.0; - drawdown_curve.push(EquityPoint { - timestamp: date.timestamp_millis(), - value: -drawdown_pct, // Negative for visualization - }); - } - - drawdown_curve - } - - fn calculate_daily_returns(&self) -> Vec { - let mut daily_returns = Vec::new(); - - for i in 1..self.equity_curve.len() { - let prev = &self.equity_curve[i - 1]; - let curr = &self.equity_curve[i]; - - // Only include if it's a new day - if prev.0.date() != curr.0.date() { - let return_pct = ((curr.1 - prev.1) / prev.1) * 100.0; - daily_returns.push(DailyReturn { - date: curr.0.format("%Y-%m-%d").to_string(), - value: return_pct, - }); - } - } - - daily_returns - } - - fn calculate_cumulative_returns(&self) -> Vec { - let initial = self.config.initial_capital; - self.equity_curve.iter() - .map(|(date, value)| EquityPoint { - timestamp: date.timestamp_millis(), - value: ((value - initial) / initial) * 100.0, - }) - .collect() - } - - fn convert_fills_to_trades(&self) -> Vec { - self.fills.iter() - .enumerate() - .map(|(i, fill)| Trade { - id: format!("trade-{}", i), - timestamp: fill.timestamp, - symbol: fill.symbol.clone(), - side: match fill.side { - Side::Buy => "buy".to_string(), - Side::Sell => "sell".to_string(), - }, - quantity: fill.quantity, - price: fill.price, - commission: fill.commission, - pnl: None, // Individual fills don't have PnL - }) - .collect() - } - - fn get_open_trades(&self) -> Vec { - // TODO: Implement based on position tracker - Vec::new() - } - - fn calculate_period_returns(&self, period: &str) -> Vec { - // TODO: Implement monthly/yearly return calculations - Vec::new() - } - - fn calculate_symbol_analysis(&self) -> HashMap { - let mut analysis: HashMap = HashMap::new(); - - // Group trades by symbol - for trade in &self.trades { - let entry = analysis.entry(trade.symbol.clone()).or_insert(SymbolAnalysis { - symbol: trade.symbol.clone(), - total_trades: 0, - winning_trades: 0, - losing_trades: 0, - total_pnl: 0.0, - win_rate: 0.0, - avg_win: 0.0, - avg_loss: 0.0, - profit_factor: 0.0, - total_volume: 0.0, - avg_position_size: 0.0, - exposure_time_pct: 0.0, - }); - - entry.total_trades += 1; - entry.total_pnl += trade.pnl; - entry.total_volume += trade.quantity * (trade.entry_price + trade.exit_price); - - if trade.pnl > 0.0 { - entry.winning_trades += 1; - } else if trade.pnl < 0.0 { - entry.losing_trades += 1; - } - } - - // Calculate derived metrics - for (_, entry) in analysis.iter_mut() { - if entry.total_trades > 0 { - entry.win_rate = (entry.winning_trades as f64 / entry.total_trades as f64) * 100.0; - entry.avg_position_size = entry.total_volume / (entry.total_trades as f64 * 2.0); - } - - // Calculate avg win/loss - let wins: Vec = self.trades.iter() - .filter(|t| t.symbol == entry.symbol && t.pnl > 0.0) - .map(|t| t.pnl) - .collect(); - let losses: Vec = self.trades.iter() - .filter(|t| t.symbol == entry.symbol && t.pnl < 0.0) - .map(|t| t.pnl) - .collect(); - - if !wins.is_empty() { - entry.avg_win = wins.iter().sum::() / wins.len() as f64; - } - if !losses.is_empty() { - entry.avg_loss = losses.iter().sum::() / losses.len() as f64; - } - - // Profit factor - let gross_profit = wins.iter().sum::(); - let gross_loss = losses.iter().map(|l| l.abs()).sum::(); - if gross_loss > 0.0 { - entry.profit_factor = gross_profit / gross_loss; - } else if gross_profit > 0.0 { - entry.profit_factor = f64::INFINITY; - } - } - - analysis - } - - fn analyze_drawdown_periods(&self) -> Vec { - // TODO: Implement comprehensive drawdown period analysis - Vec::new() - } - - fn calculate_exposure_analysis(&self) -> ExposureAnalysis { - // TODO: Implement exposure analysis - ExposureAnalysis { - avg_gross_exposure: 0.0, - avg_net_exposure: 0.0, - max_gross_exposure: 0.0, - max_net_exposure: 0.0, - time_in_market_pct: 0.0, - long_exposure_pct: 0.0, - short_exposure_pct: 0.0, - } - } - - fn calculate_position_history(&self) -> Vec { - // TODO: Implement position history tracking - Vec::new() - } - - fn extract_trade_signals(&self) -> Vec { - // TODO: Extract signals from strategy execution - Vec::new() - } -} \ No newline at end of file diff --git a/apps/stock/engine/reference/legacy-reporting/results.rs b/apps/stock/engine/reference/legacy-reporting/results.rs deleted file mode 100644 index 26cfd33f..00000000 --- a/apps/stock/engine/reference/legacy-reporting/results.rs +++ /dev/null @@ -1,266 +0,0 @@ -use chrono::{DateTime, Utc}; -use serde::{Serialize, Deserialize}; -use std::collections::HashMap; -use crate::Position; -use super::{BacktestConfig, CompletedTrade}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BacktestMetrics { - // Core Performance Metrics - pub total_return: f64, - pub total_return_pct: f64, - pub annualized_return: f64, - pub total_pnl: f64, - pub net_pnl: f64, // After commissions - - // Risk Metrics - pub sharpe_ratio: f64, - pub sortino_ratio: f64, - pub calmar_ratio: f64, - pub max_drawdown: f64, - pub max_drawdown_pct: f64, - pub max_drawdown_duration_days: i64, - pub volatility: f64, - pub downside_deviation: f64, - pub var_95: f64, // Value at Risk 95% - pub cvar_95: f64, // Conditional VaR 95% - - // Trade Statistics - pub total_trades: usize, - pub winning_trades: usize, - pub losing_trades: usize, - pub breakeven_trades: usize, - pub win_rate: f64, - pub loss_rate: f64, - pub avg_win: f64, - pub avg_loss: f64, - pub largest_win: f64, - pub largest_loss: f64, - pub avg_trade_pnl: f64, - pub avg_trade_duration_hours: f64, - pub profit_factor: f64, - pub expectancy: f64, - pub expectancy_ratio: f64, - - // Position Statistics - pub avg_position_size: f64, - pub max_position_size: f64, - pub avg_positions_held: f64, - pub max_concurrent_positions: usize, - pub total_long_trades: usize, - pub total_short_trades: usize, - pub long_win_rate: f64, - pub short_win_rate: f64, - - // Trading Activity - pub total_volume_traded: f64, - pub total_commission_paid: f64, - pub commission_pct_of_pnl: f64, - pub avg_daily_trades: f64, - pub max_daily_trades: usize, - pub trading_days: usize, - pub exposure_time_pct: f64, - - // Efficiency Metrics - pub return_over_max_dd: f64, - pub win_loss_ratio: f64, - pub kelly_criterion: f64, - pub ulcer_index: f64, - pub serenity_ratio: f64, - pub lake_ratio: f64, - - // Monthly/Period Analysis - pub best_month_return: f64, - pub worst_month_return: f64, - pub positive_months: usize, - pub negative_months: usize, - pub monthly_win_rate: f64, - pub avg_monthly_return: f64, - - // Streak Analysis - pub max_consecutive_wins: usize, - pub max_consecutive_losses: usize, - pub current_streak: i32, // Positive for wins, negative for losses - pub avg_winning_streak: f64, - pub avg_losing_streak: f64, -} - -// Trade structure that matches web app expectations -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Trade { - pub id: String, - pub timestamp: DateTime, - pub symbol: String, - pub side: String, // "buy" or "sell" - pub quantity: f64, - pub price: f64, - pub commission: f64, - #[serde(skip_serializing_if = "Option::is_none")] - pub pnl: Option, -} - -// Equity curve point -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EquityPoint { - pub timestamp: i64, // milliseconds since epoch - pub value: f64, -} - -// Daily return data -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DailyReturn { - pub date: String, - pub value: f64, -} - -// Performance data point for charts -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PerformanceDataPoint { - pub timestamp: String, - pub portfolio_value: f64, - pub pnl: f64, - pub drawdown: f64, -} - -// Period returns (monthly, weekly, etc) -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PeriodReturn { - pub period: String, // "2024-01", "2024-W01", etc - pub start_date: String, - pub end_date: String, - pub return_pct: f64, - pub pnl: f64, - pub trades: usize, - pub win_rate: f64, -} - -// Trade analysis by symbol -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SymbolAnalysis { - pub symbol: String, - pub total_trades: usize, - pub winning_trades: usize, - pub losing_trades: usize, - pub total_pnl: f64, - pub win_rate: f64, - pub avg_win: f64, - pub avg_loss: f64, - pub profit_factor: f64, - pub total_volume: f64, - pub avg_position_size: f64, - pub exposure_time_pct: f64, -} - -// Drawdown period information -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DrawdownPeriod { - pub start_date: String, - pub end_date: String, - pub peak_value: f64, - pub trough_value: f64, - pub drawdown_pct: f64, - pub recovery_date: Option, - pub duration_days: i64, - pub recovery_days: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BacktestResult { - // Metadata - pub backtest_id: String, - pub status: String, - pub started_at: String, - pub completed_at: String, - pub execution_time_ms: u64, - - // Configuration - pub config: BacktestConfig, - - // Core Metrics - pub metrics: BacktestMetrics, - - // Time Series Data - pub equity_curve: Vec, - pub drawdown_curve: Vec, - pub daily_returns: Vec, - pub cumulative_returns: Vec, - - // Trade Data - pub trades: Vec, - pub open_trades: Vec, - pub trade_signals: Vec, - - // Position Data - pub positions: HashMap, - pub position_history: Vec, - - // Analytics - pub monthly_returns: Vec, - pub yearly_returns: Vec, - pub symbol_analysis: HashMap, - pub drawdown_periods: Vec, - pub exposure_analysis: ExposureAnalysis, - - // Market Data - pub ohlc_data: HashMap>, - - // Error Handling - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub warnings: Option>, -} - -// Trade signal for visualization -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TradeSignal { - pub timestamp: String, - pub symbol: String, - pub action: String, // "buy", "sell", "hold" - pub strength: f64, - pub reason: String, -} - -// Position snapshot for tracking -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PositionSnapshot { - pub timestamp: String, - pub positions: HashMap, - pub total_value: f64, - pub cash: f64, - pub margin_used: f64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PositionDetail { - pub symbol: String, - pub quantity: f64, - pub avg_price: f64, - pub current_price: f64, - pub market_value: f64, - pub unrealized_pnl: f64, - pub unrealized_pnl_pct: f64, -} - -// Exposure analysis -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ExposureAnalysis { - pub avg_gross_exposure: f64, - pub avg_net_exposure: f64, - pub max_gross_exposure: f64, - pub max_net_exposure: f64, - pub time_in_market_pct: f64, - pub long_exposure_pct: f64, - pub short_exposure_pct: f64, -} \ No newline at end of file diff --git a/apps/stock/engine/src/analytics/mod.rs b/apps/stock/engine/src/analytics/mod.rs index 13676a89..0f5d45aa 100644 --- a/apps/stock/engine/src/analytics/mod.rs +++ b/apps/stock/engine/src/analytics/mod.rs @@ -1,5 +1,3 @@ -pub mod market_impact; -pub mod transaction_costs; - -pub use market_impact::{MarketImpactModel, ImpactModelType, MarketImpactEstimate}; -pub use transaction_costs::{TransactionCostModel, CostComponents}; \ No newline at end of file +pub mod market_impact; + +pub use market_impact::{ImpactModelType, MarketImpactEstimate, MarketImpactModel}; diff --git a/apps/stock/engine/src/analytics/transaction_costs.rs b/apps/stock/engine/src/analytics/transaction_costs.rs deleted file mode 100644 index 8583135e..00000000 --- a/apps/stock/engine/src/analytics/transaction_costs.rs +++ /dev/null @@ -1,355 +0,0 @@ -use crate::{Side, Order, Fill, MarketMicrostructure}; -use chrono::{DateTime, Utc}; - -#[derive(Debug, Clone)] -pub struct CostComponents { - pub spread_cost: f64, - pub market_impact: f64, - pub commission: f64, - pub slippage: f64, - pub opportunity_cost: f64, - pub timing_cost: f64, - pub total_cost: f64, - pub cost_bps: f64, -} - -#[derive(Debug, Clone)] -pub struct TransactionCostAnalysis { - pub order_id: String, - pub symbol: String, - pub side: Side, - pub intended_size: f64, - pub filled_size: f64, - pub avg_fill_price: f64, - pub arrival_price: f64, - pub benchmark_price: f64, - pub cost_components: CostComponents, - pub implementation_shortfall: f64, - pub duration_ms: i64, -} - -pub struct TransactionCostModel { - commission_rate_bps: f64, - min_commission: f64, - exchange_fees_bps: f64, - regulatory_fees_bps: f64, - benchmark_type: BenchmarkType, -} - -#[derive(Debug, Clone, Copy)] -pub enum BenchmarkType { - ArrivalPrice, // Price when order was placed - VWAP, // Volume-weighted average price - TWAP, // Time-weighted average price - Close, // Closing price - MidpointAtArrival, // Mid price at order arrival -} - -impl TransactionCostModel { - pub fn new(commission_rate_bps: f64) -> Self { - Self { - commission_rate_bps, - min_commission: 1.0, - exchange_fees_bps: 0.3, // Typical exchange fees - regulatory_fees_bps: 0.1, // SEC fees etc - benchmark_type: BenchmarkType::ArrivalPrice, - } - } - - pub fn with_benchmark_type(mut self, benchmark_type: BenchmarkType) -> Self { - self.benchmark_type = benchmark_type; - self - } - - pub fn analyze_execution( - &self, - order: &Order, - fills: &[Fill], - arrival_price: f64, - benchmark_prices: &BenchmarkPrices, - microstructure: &MarketMicrostructure, - order_start_time: DateTime, - order_end_time: DateTime, - ) -> TransactionCostAnalysis { - // Calculate filled size and average price - let filled_size = fills.iter().map(|f| f.quantity).sum::(); - let total_value = fills.iter().map(|f| f.price * f.quantity).sum::(); - let avg_fill_price = if filled_size > 0.0 { - total_value / filled_size - } else { - arrival_price - }; - - // Get benchmark price based on type - let benchmark_price = match self.benchmark_type { - BenchmarkType::ArrivalPrice => arrival_price, - BenchmarkType::VWAP => benchmark_prices.vwap, - BenchmarkType::TWAP => benchmark_prices.twap, - BenchmarkType::Close => benchmark_prices.close, - BenchmarkType::MidpointAtArrival => benchmark_prices.midpoint_at_arrival, - }; - - // Calculate various cost components - let cost_components = self.calculate_cost_components( - order, - fills, - avg_fill_price, - arrival_price, - benchmark_price, - microstructure, - ); - - // Calculate implementation shortfall - let side_multiplier = match order.side { - Side::Buy => 1.0, - Side::Sell => -1.0, - }; - - let implementation_shortfall = side_multiplier * filled_size * - (avg_fill_price - arrival_price) + - side_multiplier * (order.quantity - filled_size) * - (benchmark_price - arrival_price); - - // Calculate duration - let duration_ms = (order_end_time - order_start_time).num_milliseconds(); - - TransactionCostAnalysis { - order_id: order.id.clone(), - symbol: order.symbol.clone(), - side: order.side, - intended_size: order.quantity, - filled_size, - avg_fill_price, - arrival_price, - benchmark_price, - cost_components, - implementation_shortfall, - duration_ms, - } - } - - fn calculate_cost_components( - &self, - order: &Order, - fills: &[Fill], - avg_fill_price: f64, - arrival_price: f64, - benchmark_price: f64, - microstructure: &MarketMicrostructure, - ) -> CostComponents { - let filled_size = fills.iter().map(|f| f.quantity).sum::(); - let total_value = filled_size * avg_fill_price; - - // Spread cost (crossing the spread) - let spread_cost = filled_size * avg_fill_price * microstructure.avg_spread_bps / 10000.0; - - // Market impact (price movement due to our order) - let side_multiplier = match order.side { - Side::Buy => 1.0, - Side::Sell => -1.0, - }; - let market_impact = side_multiplier * filled_size * (avg_fill_price - arrival_price); - - // Commission and fees - let gross_commission = total_value * self.commission_rate_bps / 10000.0; - let commission = gross_commission.max(self.min_commission * fills.len() as f64); - let exchange_fees = total_value * self.exchange_fees_bps / 10000.0; - let regulatory_fees = total_value * self.regulatory_fees_bps / 10000.0; - let total_fees = commission + exchange_fees + regulatory_fees; - - // Slippage (difference from benchmark) - let slippage = side_multiplier * filled_size * (avg_fill_price - benchmark_price); - - // Opportunity cost (unfilled portion) - let unfilled_size = order.quantity - filled_size; - let opportunity_cost = if unfilled_size > 0.0 { - // Cost of not executing at arrival price - side_multiplier * unfilled_size * (benchmark_price - arrival_price) - } else { - 0.0 - }; - - // Timing cost (delay cost) - let timing_cost = side_multiplier * filled_size * - (benchmark_price - arrival_price).max(0.0); - - // Total cost - let total_cost = spread_cost + market_impact.abs() + total_fees + - slippage.abs() + opportunity_cost.abs() + timing_cost; - - // Cost in basis points - let cost_bps = if total_value > 0.0 { - (total_cost / total_value) * 10000.0 - } else { - 0.0 - }; - - CostComponents { - spread_cost, - market_impact: market_impact.abs(), - commission: total_fees, - slippage: slippage.abs(), - opportunity_cost: opportunity_cost.abs(), - timing_cost, - total_cost, - cost_bps, - } - } - - pub fn calculate_pretrade_cost_estimate( - &self, - order: &Order, - microstructure: &MarketMicrostructure, - current_price: f64, - expected_fill_price: f64, - expected_fill_rate: f64, - ) -> CostComponents { - let expected_filled_size = order.quantity * expected_fill_rate; - let total_value = expected_filled_size * expected_fill_price; - - // Estimate spread cost - let spread_cost = expected_filled_size * expected_fill_price * - microstructure.avg_spread_bps / 10000.0; - - // Estimate market impact - let side_multiplier = match order.side { - Side::Buy => 1.0, - Side::Sell => -1.0, - }; - let market_impact = side_multiplier * expected_filled_size * - (expected_fill_price - current_price); - - // Calculate commission - let gross_commission = total_value * self.commission_rate_bps / 10000.0; - let commission = gross_commission.max(self.min_commission); - let exchange_fees = total_value * self.exchange_fees_bps / 10000.0; - let regulatory_fees = total_value * self.regulatory_fees_bps / 10000.0; - let total_fees = commission + exchange_fees + regulatory_fees; - - // Estimate opportunity cost for unfilled portion - let unfilled_size = order.quantity - expected_filled_size; - let opportunity_cost = if unfilled_size > 0.0 { - // Assume 10bps adverse movement for unfilled portion - unfilled_size * current_price * 0.001 - } else { - 0.0 - }; - - // No slippage or timing cost for pre-trade estimate - let slippage = 0.0; - let timing_cost = 0.0; - - // Total cost - let total_cost = spread_cost + market_impact.abs() + total_fees + opportunity_cost; - - // Cost in basis points - let cost_bps = if total_value > 0.0 { - (total_cost / total_value) * 10000.0 - } else { - 0.0 - }; - - CostComponents { - spread_cost, - market_impact: market_impact.abs(), - commission: total_fees, - slippage, - opportunity_cost, - timing_cost, - total_cost, - cost_bps, - } - } -} - -#[derive(Debug, Clone)] -pub struct BenchmarkPrices { - pub vwap: f64, - pub twap: f64, - pub close: f64, - pub midpoint_at_arrival: f64, -} - -impl Default for BenchmarkPrices { - fn default() -> Self { - Self { - vwap: 0.0, - twap: 0.0, - close: 0.0, - midpoint_at_arrival: 0.0, - } - } -} - -// Helper to track and calculate various price benchmarks -pub struct BenchmarkCalculator { - trades: Vec<(DateTime, f64, f64)>, // (time, price, volume) - quotes: Vec<(DateTime, f64, f64)>, // (time, bid, ask) -} - -impl BenchmarkCalculator { - pub fn new() -> Self { - Self { - trades: Vec::new(), - quotes: Vec::new(), - } - } - - pub fn add_trade(&mut self, time: DateTime, price: f64, volume: f64) { - self.trades.push((time, price, volume)); - } - - pub fn add_quote(&mut self, time: DateTime, bid: f64, ask: f64) { - self.quotes.push((time, bid, ask)); - } - - pub fn calculate_benchmarks( - &self, - start_time: DateTime, - end_time: DateTime, - ) -> BenchmarkPrices { - // Filter trades within time window - let window_trades: Vec<_> = self.trades.iter() - .filter(|(t, _, _)| *t >= start_time && *t <= end_time) - .cloned() - .collect(); - - // Calculate VWAP - let total_volume: f64 = window_trades.iter().map(|(_, _, v)| v).sum(); - let vwap = if total_volume > 0.0 { - window_trades.iter() - .map(|(_, p, v)| p * v) - .sum::() / total_volume - } else { - 0.0 - }; - - // Calculate TWAP - let twap = if !window_trades.is_empty() { - window_trades.iter() - .map(|(_, p, _)| p) - .sum::() / window_trades.len() as f64 - } else { - 0.0 - }; - - // Get close price (last trade) - let close = window_trades.last() - .map(|(_, p, _)| *p) - .unwrap_or(0.0); - - // Get midpoint at arrival - let midpoint_at_arrival = self.quotes.iter() - .filter(|(t, _, _)| *t <= start_time) - .last() - .map(|(_, b, a)| (b + a) / 2.0) - .unwrap_or(0.0); - - BenchmarkPrices { - vwap, - twap, - close, - midpoint_at_arrival, - } - } -} \ No newline at end of file diff --git a/apps/stock/engine/src/strategies/mean_reversion.rs b/apps/stock/engine/src/strategies/mean_reversion.rs deleted file mode 100644 index 5eb74b15..00000000 --- a/apps/stock/engine/src/strategies/mean_reversion.rs +++ /dev/null @@ -1,210 +0,0 @@ -use std::collections::HashMap; -use chrono::{DateTime, Utc}; -use serde_json::json; - -use crate::{ - MarketUpdate, MarketDataType, - backtest::{Strategy, Signal, SignalType}, -}; - -/// Mean Reversion Strategy -/// -/// This strategy identifies when a security's price deviates significantly from its -/// moving average and trades on the assumption that it will revert back to the mean. -/// -/// Entry Signals: -/// - BUY when price falls below (MA - threshold * std_dev) -/// - SELL when price rises above (MA + threshold * std_dev) -/// -/// Exit Signals: -/// - Exit long when price reaches MA -/// - Exit short when price reaches MA -pub struct MeanReversionStrategy { - name: String, - id: String, - lookback_period: usize, - entry_threshold: f64, // Number of standard deviations - exit_threshold: f64, // Typically 0 (at the mean) - position_size: f64, - - // State - price_history: HashMap>, - positions: HashMap, -} - -impl MeanReversionStrategy { - pub fn new( - name: String, - id: String, - lookback_period: usize, - entry_threshold: f64, - position_size: f64, - ) -> Self { - Self { - name, - id, - lookback_period, - entry_threshold, - exit_threshold: 0.0, // Exit at the mean - position_size, - price_history: HashMap::new(), - positions: HashMap::new(), - } - } - - fn calculate_mean(prices: &[f64]) -> f64 { - prices.iter().sum::() / prices.len() as f64 - } - - fn calculate_std_dev(prices: &[f64], mean: f64) -> f64 { - let variance = prices.iter() - .map(|p| (p - mean).powi(2)) - .sum::() / prices.len() as f64; - variance.sqrt() - } -} - -impl Strategy for MeanReversionStrategy { - fn on_market_data(&mut self, data: &MarketUpdate) -> Vec { - let mut signals = Vec::new(); - - // Only process bar data - if let MarketDataType::Bar(bar) = &data.data { - let symbol = &data.symbol; - let price = bar.close; - - // Update price history - let history = self.price_history.entry(symbol.clone()).or_insert_with(Vec::new); - history.push(price); - - // Keep only necessary history - if history.len() > self.lookback_period { - history.remove(0); - } - - // Need enough data - if history.len() >= self.lookback_period { - // Calculate statistics - let mean = Self::calculate_mean(history); - let std_dev = Self::calculate_std_dev(history, mean); - - // Calculate bands - let upper_band = mean + self.entry_threshold * std_dev; - let lower_band = mean - self.entry_threshold * std_dev; - - let current_position = self.positions.get(symbol).copied().unwrap_or(0.0); - - // Check for entry signals - if current_position == 0.0 { - if price < lower_band { - // Price is oversold, buy - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Buy, - strength: 1.0, - quantity: Some(self.position_size), - reason: Some(format!( - "Mean reversion buy: price ${:.2} < lower band ${:.2} (mean: ${:.2}, std: ${:.2})", - price, lower_band, mean, std_dev - )), - metadata: Some(json!({ - "mean": mean, - "std_dev": std_dev, - "upper_band": upper_band, - "lower_band": lower_band, - "price": price, - })), - }); - self.positions.insert(symbol.clone(), self.position_size); - } else if price > upper_band { - // Price is overbought, sell short - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Sell, - strength: 1.0, - quantity: Some(self.position_size), - reason: Some(format!( - "Mean reversion sell: price ${:.2} > upper band ${:.2} (mean: ${:.2}, std: ${:.2})", - price, upper_band, mean, std_dev - )), - metadata: Some(json!({ - "mean": mean, - "std_dev": std_dev, - "upper_band": upper_band, - "lower_band": lower_band, - "price": price, - })), - }); - self.positions.insert(symbol.clone(), -self.position_size); - } - } - // Check for exit signals - else if current_position > 0.0 { - // We're long, exit when price crosses above mean (not just touches) - // or when we hit stop loss - let stop_loss = lower_band - std_dev; // Stop loss below lower band - if price >= mean * 1.01 || price <= stop_loss { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Sell, - strength: 1.0, - quantity: Some(current_position), - reason: Some(format!( - "Mean reversion exit long: price ${:.2} {} mean ${:.2}", - price, if price >= mean * 1.01 { "crossed above" } else { "hit stop loss below" }, mean - )), - metadata: Some(json!({ - "mean": mean, - "price": price, - "exit_type": "mean_reversion", - })), - }); - self.positions.remove(symbol); - } - } else if current_position < 0.0 { - // We're short, exit when price crosses below mean - // or when we hit stop loss - let stop_loss = upper_band + std_dev; // Stop loss above upper band - if price <= mean * 0.99 || price >= stop_loss { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Buy, - strength: 1.0, - quantity: Some(current_position.abs()), - reason: Some(format!( - "Mean reversion exit short: price ${:.2} {} mean ${:.2}", - price, if price <= mean * 0.99 { "crossed below" } else { "hit stop loss above" }, mean - )), - metadata: Some(json!({ - "mean": mean, - "price": price, - "exit_type": "mean_reversion", - })), - }); - self.positions.remove(symbol); - } - } - } - } - - signals - } - - fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) { - // Position tracking is handled in on_market_data for simplicity - eprintln!("Mean reversion fill: {} {} @ {} - {}", quantity, symbol, price, side); - } - - fn get_name(&self) -> &str { - &self.name - } - - fn get_parameters(&self) -> serde_json::Value { - json!({ - "lookback_period": self.lookback_period, - "entry_threshold": self.entry_threshold, - "exit_threshold": self.exit_threshold, - "position_size": self.position_size, - }) - } -} \ No newline at end of file diff --git a/apps/stock/engine/src/strategies/mod.rs b/apps/stock/engine/src/strategies/mod.rs index 3b8c34ba..08e7d0a1 100644 --- a/apps/stock/engine/src/strategies/mod.rs +++ b/apps/stock/engine/src/strategies/mod.rs @@ -1,10 +1,8 @@ -pub mod mean_reversion; pub mod mean_reversion_fixed; pub mod momentum; pub mod pairs_trading; pub mod sma_crossover; -pub use mean_reversion::MeanReversionStrategy; pub use mean_reversion_fixed::MeanReversionFixedStrategy; pub use momentum::MomentumStrategy; pub use pairs_trading::PairsTradingStrategy; diff --git a/apps/stock/orchestrator/examples/advanced-risk-management.ts b/apps/stock/orchestrator/examples/advanced-risk-management.ts deleted file mode 100644 index 7ddb7eca..00000000 --- a/apps/stock/orchestrator/examples/advanced-risk-management.ts +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Advanced Risk Management Examples - * Demonstrates orderbook analytics, portfolio risk, and bet sizing - */ - -import { OrderbookAnalyzer, RiskAnalyzer, TradingEngine } from '@stock-bot/engine'; -import { getLogger } from '@stock-bot/logger'; - -const _logger = getLogger('AdvancedRiskExample'); - -// Example 1: Orderbook Analytics -async function orderbookAnalyticsExample() { - console.log('\n=== Orderbook Analytics Example ==='); - - const engine = new TradingEngine('paper', { startingCapital: 100000 }); - const obAnalyzer = new OrderbookAnalyzer(); - - // Update orderbook with some data - const symbol = 'AAPL'; - engine.updateQuote(symbol, 149.95, 150.05, 1000, 1200); - engine.updateQuote(symbol, 149.9, 150.1, 800, 900); - engine.updateQuote(symbol, 149.85, 150.15, 600, 700); - - // Get orderbook snapshot - const snapshotJson = engine.getOrderbookSnapshot(symbol, 10); - const _snapshot = JSON.parse(snapshotJson); - - // Analyze orderbook - const analyticsJson = obAnalyzer.analyzeOrderbook(snapshotJson); - const analytics = JSON.parse(analyticsJson); - - console.log('Orderbook Analytics:'); - console.log(` Spread: $${analytics.spread.toFixed(2)} (${analytics.spread_bps.toFixed(1)} bps)`); - console.log(` Mid Price: $${analytics.mid_price.toFixed(2)}`); - console.log(` Micro Price: $${analytics.micro_price.toFixed(2)}`); - console.log(` Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`); - console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`); - - // Calculate liquidity profile - const profileJson = obAnalyzer.calculateLiquidityProfile(snapshotJson); - const profile = JSON.parse(profileJson); - - console.log('\nLiquidity Profile:'); - console.log(` Total Bid Depth: $${profile.total_bid_depth.toFixed(2)}`); - console.log(` Total Ask Depth: $${profile.total_ask_depth.toFixed(2)}`); - - // Calculate market impact for a $10,000 buy order - const impactJson = obAnalyzer.calculateMarketImpact(snapshotJson, 10000, true); - const impact = JSON.parse(impactJson); - - console.log('\nMarket Impact ($10k buy):'); - console.log(` Avg Execution Price: $${impact.avg_execution_price.toFixed(2)}`); - console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(2)}%`); - console.log(` Slippage: $${impact.slippage.toFixed(2)}`); - console.log(` Levels Consumed: ${impact.levels_consumed}`); -} - -// Example 2: Portfolio Risk Analysis -async function portfolioRiskExample() { - console.log('\n=== Portfolio Risk Analysis Example ==='); - - const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); // $100k, 2% risk, 252 days lookback - - // Update historical returns for portfolio symbols - const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META']; - - // Simulate some returns data (in practice, load from historical data) - for (const symbol of symbols) { - const returns = generateRandomReturns(252); - riskAnalyzer.updateReturns(symbol, returns); - } - - // Current positions - const positions = [ - { symbol: 'AAPL', quantity: 100, avgPrice: 150 }, - { symbol: 'GOOGL', quantity: 50, avgPrice: 140 }, - { symbol: 'MSFT', quantity: 75, avgPrice: 380 }, - { symbol: 'AMZN', quantity: 40, avgPrice: 170 }, - { symbol: 'META', quantity: 60, avgPrice: 480 }, - ]; - - // Current prices - const prices = { - AAPL: 155, - GOOGL: 145, - MSFT: 390, - AMZN: 175, - META: 490, - }; - - // Calculate portfolio risk - const riskJson = riskAnalyzer.calculatePortfolioRisk( - JSON.stringify(positions.map(p => [p.symbol, p.quantity, p.avgPrice])), - JSON.stringify(prices) - ); - const risk = JSON.parse(riskJson); - - console.log('Portfolio Risk Metrics:'); - console.log(` VaR (95%): $${risk.total_var_95.toFixed(2)}`); - console.log(` VaR (99%): $${risk.total_var_99.toFixed(2)}`); - console.log(` CVaR (95%): $${risk.total_cvar_95.toFixed(2)}`); - - console.log('\nConcentration Metrics:'); - console.log(` Herfindahl Index: ${risk.concentration_risk.herfindahl_index.toFixed(3)}`); - console.log( - ` Effective Positions: ${risk.concentration_risk.effective_number_of_positions.toFixed(1)}` - ); - console.log( - ` Top 5 Concentration: ${(risk.concentration_risk.top_5_concentration * 100).toFixed(1)}%` - ); - - console.log('\nCorrelation Analysis:'); - console.log(` Average Correlation: ${risk.correlation_matrix.average_correlation.toFixed(3)}`); - console.log( - ` Max Correlation: ${risk.correlation_matrix.max_correlation[0]} vs ${risk.correlation_matrix.max_correlation[1]} = ${risk.correlation_matrix.max_correlation[2].toFixed(3)}` - ); - console.log(` Clustering Score: ${risk.correlation_matrix.clustering_score.toFixed(3)}`); - - console.log('\nStress Test Results:'); - for (const [scenario, loss] of Object.entries(risk.stress_test_results)) { - console.log(` ${scenario}: $${(loss as number).toFixed(2)}`); - } -} - -// Example 3: Dynamic Bet Sizing -async function betSizingExample() { - console.log('\n=== Dynamic Bet Sizing Example ==='); - - const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); - - // Scenario 1: Strong signal in trending market - console.log('\nScenario 1: Strong Signal, Trending Market'); - let positionSize = riskAnalyzer.calculatePositionSize( - 0.8, // signal_strength - 0.9, // signal_confidence - 0.015, // volatility (1.5% daily) - 0.8, // liquidity_score - 0.02, // current_drawdown (2%) - 150, // price - 145, // stop_loss - 'trending' - ); - - let size = JSON.parse(positionSize); - console.log(` Shares: ${size.shares}`); - console.log(` Notional Value: $${size.notional_value.toFixed(2)}`); - console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`); - console.log(' Adjustments:'); - for (const adj of size.adjustments) { - console.log(` ${adj.reason}: ${adj.factor.toFixed(2)}x`); - } - - // Scenario 2: Weak signal in high volatility - console.log('\nScenario 2: Weak Signal, High Volatility'); - positionSize = riskAnalyzer.calculatePositionSize( - 0.3, // signal_strength - 0.5, // signal_confidence - 0.03, // volatility (3% daily) - 0.6, // liquidity_score - 0.15, // current_drawdown (15%) - 150, // price - null, // no stop_loss - 'high_volatility' - ); - - size = JSON.parse(positionSize); - console.log(` Shares: ${size.shares}`); - console.log(` Notional Value: $${size.notional_value.toFixed(2)}`); - console.log(` % of Capital: ${(size.percent_of_capital * 100).toFixed(2)}%`); - - // Calculate optimal stop loss - const supportLevels = [148, 145, 142, 140]; - const optimalStop = riskAnalyzer.calculateOptimalStopLoss( - 150, // entry_price - 0.015, // volatility - supportLevels, - 2.5, // atr - true // is_long - ); - - console.log(`\nOptimal Stop Loss: $${optimalStop.toFixed(2)}`); -} - -// Example 4: Integrated Risk Management in Trading -async function integratedTradingExample() { - console.log('\n=== Integrated Risk Management Example ==='); - - const engine = new TradingEngine('backtest', { - startTime: Date.now() - 30 * 24 * 60 * 60 * 1000, // 30 days ago - endTime: Date.now(), - speedMultiplier: 1, - }); - - const riskAnalyzer = new RiskAnalyzer(100000, 0.02, 252); - const obAnalyzer = new OrderbookAnalyzer(); - - // Simulate a trading decision - const symbol = 'AAPL'; - - // 1. Check orderbook liquidity - engine.updateQuote(symbol, 149.95, 150.05, 5000, 5500); - const snapshot = engine.getOrderbookSnapshot(symbol, 10); - const analytics = JSON.parse(obAnalyzer.analyzeOrderbook(snapshot)); - - console.log('Pre-trade Analysis:'); - console.log(` Liquidity Score: ${analytics.liquidity_score.toFixed(2)}`); - console.log(` Spread: ${analytics.spread_bps.toFixed(1)} bps`); - console.log(` Orderbook Imbalance: ${(analytics.imbalance * 100).toFixed(1)}%`); - - // 2. Calculate position size based on current conditions - const positionSizeJson = riskAnalyzer.calculatePositionSize( - 0.7, // signal_strength - 0.8, // signal_confidence - 0.018, // volatility - analytics.liquidity_score, // from orderbook - 0.05, // current_drawdown - 150, // price - 147, // stop_loss - 'trending' - ); - - const positionSize = JSON.parse(positionSizeJson); - console.log(`\nPosition Sizing:`); - console.log(` Recommended Shares: ${positionSize.shares}`); - console.log(` Risk-Adjusted Size: ${(positionSize.risk_adjusted_size * 100).toFixed(2)}%`); - - // 3. Check market impact before placing order - const orderValue = positionSize.shares * 150; - const impact = JSON.parse(obAnalyzer.calculateMarketImpact(snapshot, orderValue, true)); - - console.log(`\nExpected Market Impact:`); - console.log(` Price Impact: ${(impact.price_impact * 100).toFixed(3)}%`); - console.log(` Expected Fill Price: $${impact.avg_execution_price.toFixed(2)}`); - - // 4. Risk check - const riskCheck = engine.checkRisk({ - id: '123', - symbol: symbol, - side: 'buy', - quantity: positionSize.shares, - orderType: 'market', - timeInForce: 'DAY', - }); - - const riskResult = JSON.parse(riskCheck); - console.log(`\nRisk Check: ${riskResult.passed ? 'PASSED' : 'FAILED'}`); - if (!riskResult.passed) { - console.log(' Violations:', riskResult.violations); - } -} - -// Helper function to generate random returns -function generateRandomReturns(length: number): number[] { - const returns: number[] = []; - for (let i = 0; i < length; i++) { - // Generate returns with mean 0.0005 (0.05%) and std dev 0.02 (2%) - const return_ = (Math.random() - 0.5) * 0.04 + 0.0005; - returns.push(return_); - } - return returns; -} - -// Run all examples -async function runExamples() { - try { - await orderbookAnalyticsExample(); - await portfolioRiskExample(); - await betSizingExample(); - await integratedTradingExample(); - } catch (error) { - console.error('Error running examples:', error); - } -} - -// Execute if running directly -if (require.main === module) { - runExamples(); -} diff --git a/apps/stock/orchestrator/examples/canonical-regime-research.ts b/apps/stock/orchestrator/examples/canonical-regime-research.ts index 8d46e851..6577cec1 100644 --- a/apps/stock/orchestrator/examples/canonical-regime-research.ts +++ b/apps/stock/orchestrator/examples/canonical-regime-research.ts @@ -1,6 +1,6 @@ import { parseFinancialDecimal } from '@stock-bot/types'; import type { NativeBacktestWorker } from '../src/backtest/NativeBacktestWorker'; -import { replayIdentitySchema } from '../src/contracts/native-replay'; +import { replayIdentitySchema } from '@stock-bot/stock-config/canonical-replay'; import { parseStrategyReplayResult, strategyReplayRequestSchema, diff --git a/apps/stock/orchestrator/examples/debug-position-tracking.ts b/apps/stock/orchestrator/examples/debug-position-tracking.ts deleted file mode 100644 index d9113cda..00000000 --- a/apps/stock/orchestrator/examples/debug-position-tracking.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -async function debugPositionTracking() { - // Create service container with detailed logging - const { - container, - storageService, - marketDataService: _marketDataService, - modeManager, - strategyManager, - } = await createExampleRuntime(); - - // Initialize backtest mode with full config - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-06-01T00:00:00Z', - endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Listen to strategy events for debugging - strategyManager.on('order', (orderEvent: unknown) => { - console.log('\n๐Ÿ“Š STRATEGY ORDER EVENT:', orderEvent); - }); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Position Tracking Debug', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-06-01T00:00:00Z', - endDate: '2023-09-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('Starting position tracking debug...\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('\n=== FINAL RESULTS ==='); - console.log(`Total Trades: ${result.metrics.totalTrades}`); - console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); - - console.log('\n=== TRADE DETAILS ==='); - let buyCount = 0; - let sellCount = 0; - - result.trades.forEach((trade, i) => { - console.log(`\nTrade ${i + 1}:`); - console.log(` Symbol: ${trade.symbol}`); - console.log(` Side: ${trade.side}`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` Quantity: ${trade.quantity}`); - console.log(` P&L: $${trade.pnl.toFixed(2)}`); - - if (trade.side === 'buy') { - buyCount++; - } else if (trade.side === 'sell') { - sellCount++; - } - }); - - console.log(`\n=== TRADE SIDE SUMMARY ===`); - console.log(`Buy trades: ${buyCount}`); - console.log(`Sell trades: ${sellCount}`); - - // Check final positions - console.log('\n=== FINAL POSITIONS ==='); - result.positions.forEach(pos => { - console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`); - }); - } catch (error) { - console.error('Debug failed:', error); - } -} - -// Run the debug -debugPositionTracking().catch(console.error); diff --git a/apps/stock/orchestrator/examples/debug-rust-short-trades.ts b/apps/stock/orchestrator/examples/debug-rust-short-trades.ts deleted file mode 100644 index 1cda8312..00000000 --- a/apps/stock/orchestrator/examples/debug-rust-short-trades.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { TradingEngine } from '@stock-bot/engine'; -import type { ClosedTrade } from '../src/backtest/native-result'; - -async function debugRustShortTrades() { - // Create engine config for backtest mode - const engineConfig = { - startTime: new Date('2023-01-01').getTime(), - endTime: new Date('2023-02-01').getTime(), - speedMultiplier: 0, - }; - - console.log('=== RUST CORE SHORT TRADE DEBUG ===\n'); - - console.log('1. Creating TradingEngine in backtest mode...'); - const engine = new TradingEngine('backtest', engineConfig); - - // Simulate opening a short position - console.log('\n2. Submitting SELL order to open short position...'); - const sellOrder = { - id: 'sell-order-001', - symbol: 'TEST', - side: 'sell', - quantity: 100, - orderType: 'market', - timeInForce: 'DAY', - }; - const sellOrderId = engine.submitOrder(sellOrder); - console.log(` Sell order ID: ${sellOrderId}`); - - // Process the sell fill - console.log('\n3. Processing SELL fill...'); - const sellFillResult = engine.processFillWithMetadata( - 'TEST', // symbol - 50.0, // price - 100, // quantity - 'sell', // side - 0.1, // commission - sellOrderId, // orderId - 'debug-strategy' // strategyId - ); - console.log(` Fill result: ${sellFillResult}`); - - // Check positions - console.log('\n4. Checking positions after SELL...'); - const positionsAfterSell = engine.getPosition('TEST'); - console.log(' Position:', positionsAfterSell); - - // Check open trades - const openTradesAfterSell = JSON.parse(engine.getOpenTrades()); - console.log(' Open trades:', openTradesAfterSell.length); - if (openTradesAfterSell.length > 0) { - console.log(' First open trade:', openTradesAfterSell[0]); - } - - // Check closed trades - const closedTradesAfterSell = JSON.parse(engine.getClosedTrades()); - console.log(' Closed trades:', closedTradesAfterSell.length); - - // Now close the short with a buy order - console.log('\n5. Submitting BUY order to close short position...'); - const buyOrder = { - id: 'buy-order-001', - symbol: 'TEST', - side: 'buy', - quantity: 100, - orderType: 'market', - timeInForce: 'DAY', - }; - const buyOrderId = engine.submitOrder(buyOrder); - console.log(` Buy order ID: ${buyOrderId}`); - - // Process the buy fill - console.log('\n6. Processing BUY fill...'); - const buyFillResult = engine.processFillWithMetadata( - 'TEST', // symbol - 48.0, // price (profit on short) - 100, // quantity - 'buy', // side - 0.1, // commission - buyOrderId, // orderId - 'debug-strategy' // strategyId - ); - console.log(` Fill result: ${buyFillResult}`); - - // Check positions after closing - console.log('\n7. Checking positions after BUY...'); - const positionsAfterBuy = engine.getPosition('TEST'); - console.log(' Position:', positionsAfterBuy); - - // Check open trades after closing - const openTradesAfterBuy = JSON.parse(engine.getOpenTrades()); - console.log(' Open trades:', openTradesAfterBuy.length); - - // Check closed trades after closing - THIS IS WHERE WE SHOULD SEE THE SHORT TRADE - const closedTradesAfterBuy = JSON.parse(engine.getClosedTrades()); - console.log(' Closed trades:', closedTradesAfterBuy.length); - - if (closedTradesAfterBuy.length > 0) { - console.log('\n8. Closed trade details:'); - closedTradesAfterBuy.forEach((trade: ClosedTrade, i: number) => { - console.log(` Trade ${i + 1}:`); - console.log(` ID: ${trade.id}`); - console.log(` Side: ${trade.side}`); - console.log(` Entry: ${trade.entry_price} @ ${trade.entry_time}`); - console.log(` Exit: ${trade.exit_price} @ ${trade.exit_time}`); - console.log(` P&L: ${trade.pnl} (${trade.pnl_percent}%)`); - console.log(` Quantity: ${trade.quantity}`); - }); - } else { - console.log('\nโŒ ERROR: No closed trades found! Short trade was not recorded.'); - } - - // Also check trade history - console.log('\n9. Trade history:'); - const tradeHistory = JSON.parse(engine.getTradeHistory()); - tradeHistory.forEach((trade: ClosedTrade, i: number) => { - console.log(` Trade ${i + 1}: ${trade.side} ${trade.quantity} @ ${trade.price}`); - }); - - // Check totals - console.log('\n10. Summary:'); - console.log(` Total trades: ${engine.getTradeCount()}`); - console.log(` Closed trades: ${engine.getClosedTradeCount()}`); - const [realizedPnl, unrealizedPnl] = engine.getTotalPnl(); - console.log(` Realized P&L: ${realizedPnl}`); - console.log(` Unrealized P&L: ${unrealizedPnl}`); -} - -// Run the debug -debugRustShortTrades().catch(console.error); diff --git a/apps/stock/orchestrator/examples/example-runtime.ts b/apps/stock/orchestrator/examples/example-runtime.ts deleted file mode 100644 index f7628106..00000000 --- a/apps/stock/orchestrator/examples/example-runtime.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { ServiceContainerBuilder } from '@stock-bot/di'; -import { ModeManager } from '../src/core/ModeManager'; -import { ExecutionService } from '../src/services/ExecutionService'; -import { MarketDataService } from '../src/services/MarketDataService'; -import { StorageService } from '../src/services/StorageService'; -import { createBuiltinStrategyRegistry } from '../src/strategies/builtin-strategies'; -import { StrategyManager } from '../src/strategies/StrategyManager'; -import type { OrchestratorServices } from '../src/types'; - -/** Legacy algorithm examples only: no queue, HTTP server, durable runs, or paper account. */ -export async function createExampleRuntime() { - const di = await new ServiceContainerBuilder() - .withOptions({ - enableCache: false, - enableQueue: false, - enableMongoDB: false, - enablePostgres: false, - enableQuestDB: false, - enableBrowser: false, - enableProxy: false, - }) - .build(); - const container = di.resolve('serviceContainer') as OrchestratorServices; - const storageService = new StorageService(container.logger, null, null, { - allowSyntheticData: true, - syntheticSeed: 42, - }); - const marketDataService: MarketDataService = new MarketDataService({ - logger: container.logger, - storage: storageService, - drainStrategies: () => strategyManager.drain(), - }); - const executionService = new ExecutionService(container, storageService, { - allowedMode: 'backtest', - }); - const registry = createBuiltinStrategyRegistry(); - const strategyManager: StrategyManager = new StrategyManager({ - logger: container.logger, - marketData: marketDataService, - execution: executionService, - createStrategy: config => registry.create(config, { modeManager, execution: executionService }), - }); - const modeManager: ModeManager = new ModeManager({ - allowedMode: 'backtest', - logger: container.logger, - marketData: marketDataService, - execution: executionService, - strategies: strategyManager, - }); - const custom = container.custom ?? {}; - if (!container.custom) { - Object.defineProperty(container, 'custom', { value: custom, enumerable: true }); - } - Object.assign(custom, { - StorageService: storageService, - MarketDataService: marketDataService, - ExecutionService: executionService, - StrategyManager: strategyManager, - ModeManager: modeManager, - }); - strategyManager.setupEventListeners(); - return { - container, - storageService, - marketDataService, - executionService, - modeManager, - strategyManager, - }; -} diff --git a/apps/stock/orchestrator/examples/force-both-trade-types.ts b/apps/stock/orchestrator/examples/force-both-trade-types.ts deleted file mode 100644 index 48dabc1d..00000000 --- a/apps/stock/orchestrator/examples/force-both-trade-types.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -// Modify the data generation to ensure we get both golden and death crosses -function generateMockDataWithBothCrosses() { - const data = []; - const startDate = new Date('2023-01-01'); - let price = 150; - - // Create 365 days of data with clear trends - for (let i = 0; i < 365; i++) { - const date = new Date(startDate); - date.setDate(date.getDate() + i); - - // Create alternating trends every ~30 days - const cycleDay = i % 60; - if (cycleDay < 30) { - // Uptrend - will create golden crosses - price += Math.random() * 2 - 0.5; // Bias upward - } else { - // Downtrend - will create death crosses - price -= Math.random() * 2 - 0.5; // Bias downward - } - - // Add some volatility - const dayChange = (Math.random() - 0.5) * 4; - price = Math.max(100, Math.min(200, price + dayChange)); - - data.push({ - timestamp: date.toISOString(), - open: price - Math.random() * 2, - high: price + Math.random() * 2, - low: price - Math.random() * 2, - close: price, - volume: Math.floor(Math.random() * 10000000) + 5000000, - }); - } - - return data; -} - -async function forceBothTradeTypes() { - // Create service container with minimal logging - const { container, storageService, marketDataService, modeManager, strategyManager } = - await createExampleRuntime(); - - // Override the mock data generation - const _originalGenerateMockData = marketDataService.generateMockData; - marketDataService.generateMockData = function ( - _symbol: string, - _startDate: string, - _endDate: string - ) { - console.log('Generating mock data with forced crossovers...'); - return generateMockDataWithBothCrosses(); - }; - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Force Both Trade Types', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('=== TESTING WITH FORCED CROSSOVERS ===\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('\n=== BACKTEST COMPLETE ==='); - console.log(`Total Trades: ${result.metrics.totalTrades}`); - - // Analyze trades - let longTrades = 0; - let shortTrades = 0; - - result.trades.forEach(trade => { - if (trade.side === 'buy') { - longTrades++; - console.log(`\nLONG trade found:`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)}`); - } else { - shortTrades++; - console.log(`\nSHORT trade found:`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)}`); - } - }); - - console.log('\n=== FINAL SUMMARY ==='); - console.log(`LONG trades: ${longTrades}`); - console.log(`SHORT trades: ${shortTrades}`); - console.log(`Total trades: ${result.metrics.totalTrades}`); - - if (longTrades > 0 && shortTrades > 0) { - console.log('\nโœ… SUCCESS: Both long and short trades are working!'); - } else { - console.log('\nโŒ ISSUE: Missing trade types'); - if (longTrades === 0) { - console.log(' - No long trades found'); - } - if (shortTrades === 0) { - console.log(' - No short trades found'); - } - } - } catch (error) { - console.error('Test failed:', error); - } -} - -// Run the test -forceBothTradeTypes().catch(console.error); diff --git a/apps/stock/orchestrator/examples/indicator-usage.ts b/apps/stock/orchestrator/examples/indicator-usage.ts deleted file mode 100644 index 908da238..00000000 --- a/apps/stock/orchestrator/examples/indicator-usage.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -/** - * Examples of using the Rust-based Technical Analysis library - */ - -import { - IncrementalIndicators, - SignalGenerator, - TechnicalAnalysis, -} from '../src/indicators/TechnicalAnalysis'; - -// Example 1: Basic indicator calculations -async function basicIndicatorExample() { - console.log('=== Basic Indicator Example ==='); - - const ta = new TechnicalAnalysis(); - - // Sample price data - const prices = [ - 100, 102, 101, 103, 105, 104, 106, 108, 107, 109, 111, 110, 112, 114, 113, 115, 117, 116, 118, - 120, - ]; - - // Calculate various indicators - const sma10 = ta.sma(prices, 10); - const ema10 = ta.ema(prices, 10); - const rsi14 = ta.rsi(prices, 14); - - console.log(`SMA(10): ${sma10.map(v => v.toFixed(2)).join(', ')}`); - console.log(`EMA(10): ${ema10.map(v => v.toFixed(2)).join(', ')}`); - console.log(`RSI(14): ${rsi14.map(v => v.toFixed(2)).join(', ')}`); - - // Latest values - console.log(`\nLatest SMA: ${TechnicalAnalysis.latest(sma10)?.toFixed(2)}`); - console.log(`Latest EMA: ${TechnicalAnalysis.latest(ema10)?.toFixed(2)}`); - console.log(`Latest RSI: ${TechnicalAnalysis.latest(rsi14)?.toFixed(2)}`); -} - -// Example 2: Real-time streaming indicators -async function streamingIndicatorExample() { - console.log('\n=== Streaming Indicator Example ==='); - - const manager = new IncrementalIndicators(); - - // Create indicators - manager.createSMA('sma_fast', 5); - manager.createSMA('sma_slow', 10); - manager.createEMA('ema', 10); - manager.createRSI('rsi', 14); - - // Simulate real-time price updates - console.log('Processing real-time price updates...'); - for (let i = 0; i < 20; i++) { - const price = 100 + Math.sin(i * 0.3) * 5 + Math.random() * 2; - - const smaFast = manager.update('sma_fast', price); - const smaSlow = manager.update('sma_slow', price); - const ema = manager.update('ema', price); - const rsi = manager.update('rsi', price); - - if (i >= 14) { - // Once we have enough data - console.log( - `Price: ${price.toFixed(2)} | SMA5: ${smaFast?.toFixed(2)} | SMA10: ${smaSlow?.toFixed(2)} | EMA: ${ema?.toFixed(2)} | RSI: ${rsi?.toFixed(2)}` - ); - } - } -} - -// Example 3: Complex indicators (MACD, Bollinger Bands, Stochastic) -async function complexIndicatorExample() { - console.log('\n=== Complex Indicator Example ==='); - - const ta = new TechnicalAnalysis(); - - // Generate more realistic price data - const generatePrices = (count: number) => { - const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = { - close: [], - high: [], - low: [], - volume: [], - }; - let basePrice = 100; - - for (let i = 0; i < count; i++) { - const change = (Math.random() - 0.5) * 2; - basePrice += change; - const high = basePrice + Math.random() * 1; - const low = basePrice - Math.random() * 1; - const close = low + Math.random() * (high - low); - - prices.close.push(close); - prices.high.push(high); - prices.low.push(low); - prices.volume.push(Math.random() * 1000000 + 500000); - } - - return prices; - }; - - const prices = generatePrices(50); - - // Calculate MACD - const macd = ta.macd(prices.close); - console.log(`MACD Line: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(3)}`); - console.log(`Signal Line: ${TechnicalAnalysis.latest(macd.signal)?.toFixed(3)}`); - console.log(`Histogram: ${TechnicalAnalysis.latest(macd.histogram)?.toFixed(3)}`); - - // Calculate Bollinger Bands - const bb = ta.bollingerBands(prices.close, 20, 2); - const currentPrice = prices.close[prices.close.length - 1]; - const bbPercent = - (currentPrice - defined(TechnicalAnalysis.latest(bb.lower))) / - (defined(TechnicalAnalysis.latest(bb.upper)) - defined(TechnicalAnalysis.latest(bb.lower))); - - console.log(`\nBollinger Bands:`); - console.log(`Upper: ${TechnicalAnalysis.latest(bb.upper)?.toFixed(2)}`); - console.log(`Middle: ${TechnicalAnalysis.latest(bb.middle)?.toFixed(2)}`); - console.log(`Lower: ${TechnicalAnalysis.latest(bb.lower)?.toFixed(2)}`); - console.log(`%B: ${(bbPercent * 100).toFixed(2)}%`); - - // Calculate Stochastic - const stoch = ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3); - console.log(`\nStochastic:`); - console.log(`%K: ${TechnicalAnalysis.latest(stoch.k)?.toFixed(2)}`); - console.log(`%D: ${TechnicalAnalysis.latest(stoch.d)?.toFixed(2)}`); - - // Calculate ATR - const atr = ta.atr(prices.high, prices.low, prices.close, 14); - console.log(`\nATR(14): ${TechnicalAnalysis.latest(atr)?.toFixed(3)}`); -} - -// Example 4: Trading signal generation -async function signalGenerationExample() { - console.log('\n=== Signal Generation Example ==='); - - const generator = new SignalGenerator(); - - // Generate trending market data - const generateTrendingPrices = (count: number, trend: 'up' | 'down' | 'sideways') => { - const prices: { close: number[]; high: number[]; low: number[]; volume: number[] } = { - close: [], - high: [], - low: [], - volume: [], - }; - let basePrice = 100; - - for (let i = 0; i < count; i++) { - const trendComponent = trend === 'up' ? 0.1 : trend === 'down' ? -0.1 : 0; - const noise = (Math.random() - 0.5) * 2; - basePrice += trendComponent + noise; - - const high = basePrice + Math.random() * 1; - const low = basePrice - Math.random() * 1; - const close = low + Math.random() * (high - low); - - prices.close.push(close); - prices.high.push(high); - prices.low.push(low); - prices.volume.push(Math.random() * 1000000 + 500000); - } - - return prices; - }; - - // Test different market conditions - const scenarios = [ - { name: 'Uptrend', data: generateTrendingPrices(50, 'up') }, - { name: 'Downtrend', data: generateTrendingPrices(50, 'down') }, - { name: 'Sideways', data: generateTrendingPrices(50, 'sideways') }, - ]; - - for (const scenario of scenarios) { - const signal = generator.generateSignals('TEST', scenario.data, Date.now()); - console.log(`\n${scenario.name} Market:`); - console.log(`Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)})`); - console.log(`Reason: ${signal.reason}`); - console.log( - `Indicators: RSI=${signal.indicators.rsi?.toFixed(2)}, MACD=${signal.indicators.macd?.toFixed(3)}` - ); - } -} - -// Example 5: Crossover detection -async function crossoverExample() { - console.log('\n=== Crossover Detection Example ==='); - - const ta = new TechnicalAnalysis(); - - // Generate price data with clear trend changes - const prices: number[] = []; - for (let i = 0; i < 100; i++) { - if (i < 30) { - prices.push(100 + i * 0.3); // Uptrend - } else if (i < 60) { - prices.push(109 - (i - 30) * 0.3); // Downtrend - } else { - prices.push(100 + (i - 60) * 0.2); // Uptrend again - } - } - - // Calculate moving averages - const fastMA = ta.sma(prices, 10); - const slowMA = ta.sma(prices, 20); - - // Detect crossovers - console.log('Checking for crossovers in the last 10 bars:'); - for (let i = Math.max(0, fastMA.length - 10); i < fastMA.length; i++) { - const fast = fastMA.slice(0, i + 1); - const slow = slowMA.slice(0, i + 1); - - if (TechnicalAnalysis.crossover(fast, slow)) { - console.log(`Bullish crossover at index ${i + 20}`); - } else if (TechnicalAnalysis.crossunder(fast, slow)) { - console.log(`Bearish crossover at index ${i + 20}`); - } - } -} - -// Run all examples -async function runExamples() { - try { - await basicIndicatorExample(); - await streamingIndicatorExample(); - await complexIndicatorExample(); - await signalGenerationExample(); - await crossoverExample(); - } catch (error) { - console.error('Error running examples:', error); - } -} - -// Execute if running directly -if (require.main === module) { - runExamples(); -} diff --git a/apps/stock/orchestrator/examples/multi-strategy-backtest.ts b/apps/stock/orchestrator/examples/multi-strategy-backtest.ts deleted file mode 100644 index b4aa860d..00000000 --- a/apps/stock/orchestrator/examples/multi-strategy-backtest.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { BacktestConfigSchema, type BacktestConfig } from '../src/types'; - -/** - * Preserved offline prototype for older strategy algorithms; not a production research route. - * Importing this example starts no services, loads no model and submits no work. - * A standalone prototype engine owns this demonstration. It does not create durable research results. - * Production research uses approved retained versions and the canonical runner. - */ -export function runMultiStrategyBacktest( - runner: Pick, - range: Pick -) { - const request = BacktestConfigSchema.parse({ - symbols: range.symbols, - startDate: range.startDate, - endDate: range.endDate, - mode: 'backtest', - name: 'SMA and mean-reversion example', - strategy: 'sma-crossover', - initialCapital: 100000, - dataFrequency: '1d', - commission: 0.001, - slippage: 0.0001, - strategies: [ - { - name: 'sma-crossover', - enabled: true, - config: { fastPeriod: 5, slowPeriod: 15, positionFraction: 0.1 }, - }, - { - name: 'mean-reversion', - enabled: true, - config: { lookbackPeriod: 20, entryThreshold: 2, exitZScore: 0.5 }, - }, - ], - }); - return runner.runBacktest(request); -} diff --git a/apps/stock/orchestrator/examples/show-order-flow.ts b/apps/stock/orchestrator/examples/show-order-flow.ts deleted file mode 100644 index 97e8607e..00000000 --- a/apps/stock/orchestrator/examples/show-order-flow.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -async function showOrderFlow() { - // Create service container - const { - container, - storageService, - marketDataService: _marketDataService, - modeManager, - strategyManager, - } = await createExampleRuntime(); - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-07-01T00:00:00Z', - endDate: '2023-08-01T00:00:00Z', // Just 1 month - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Order Flow Demo', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-07-01T00:00:00Z', - endDate: '2023-08-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('\n=== ORDER FLOW DEMONSTRATION ===\n'); - console.log('This will show the actual BUY and SELL orders being generated and executed:\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('\n=== COMPLETED TRADES (Round-trips) ==='); - console.log('Note: Each trade below represents a BUY order (entry) + SELL order (exit):\n'); - - result.trades.forEach((trade, i) => { - console.log(`Trade ${i + 1}:`); - console.log( - ` Opened with: BUY order on ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}` - ); - console.log( - ` Closed with: SELL order on ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}` - ); - console.log(` Trade type: ${trade.side === 'buy' ? 'LONG' : 'SHORT'} position`); - console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)\n`); - }); - - console.log('Summary:'); - console.log(`- Total completed trades: ${result.metrics.totalTrades}`); - console.log(`- Each trade = 1 BUY order + 1 SELL order`); - console.log(`- Total orders executed: ${result.metrics.totalTrades * 2}`); - } catch (error) { - console.error('Failed:', error); - } -} - -// Run the demo -showOrderFlow().catch(console.error); diff --git a/apps/stock/orchestrator/examples/simple-backtest-test.ts b/apps/stock/orchestrator/examples/simple-backtest-test.ts deleted file mode 100644 index 8577b3b0..00000000 --- a/apps/stock/orchestrator/examples/simple-backtest-test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -const _logger = getLogger('BacktestTest'); - -async function runSimpleBacktest() { - // Create service container - const { - container, - storageService, - marketDataService: _marketDataService, - modeManager, - strategyManager, - } = await createExampleRuntime(); - - // Initialize backtest mode with full config - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - shorter period for faster testing - const config = { - mode: 'backtest' as const, // Add mode field - name: 'SMA Crossover Test', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], // Just one symbol for simplicity - startDate: '2023-01-01T00:00:00Z', // ISO datetime format - endDate: '2024-01-01T00:00:00Z', // ISO datetime format - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('Starting backtest with configuration:', config); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('\n=== BACKTEST RESULTS ==='); - console.log(`Total Trades: ${result.metrics.totalTrades}`); - console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); - console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); - console.log(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`); - console.log(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`); - - console.log('\n=== TRADE HISTORY ==='); - if (result.trades.length === 0) { - console.log('No trades were executed!'); - } else { - result.trades.forEach((trade, i) => { - console.log(`\nTrade ${i + 1}:`); - console.log(` Symbol: ${trade.symbol}`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`); - }); - } - - // Show some equity curve data - console.log('\n=== EQUITY CURVE (first and last 5 points) ==='); - const equityCurve = result.equity; - if (equityCurve.length > 0) { - equityCurve.slice(0, 5).forEach(point => { - console.log(`${point.date}: $${point.value.toFixed(2)}`); - }); - if (equityCurve.length > 10) { - console.log('...'); - equityCurve.slice(-5).forEach(point => { - console.log(`${point.date}: $${point.value.toFixed(2)}`); - }); - } - } - } catch (error) { - console.error('Backtest failed:', error); - } -} - -// Run the test -runSimpleBacktest().catch(console.error); diff --git a/apps/stock/orchestrator/examples/test-backtest-trades.ts b/apps/stock/orchestrator/examples/test-backtest-trades.ts deleted file mode 100644 index a048f11c..00000000 --- a/apps/stock/orchestrator/examples/test-backtest-trades.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { StrategyManager } from '../src/strategies/StrategyManager'; -import { StorageService } from '../src/services/StorageService'; -import { ModeManager } from '../src/core/ModeManager'; -import { MarketDataService } from '../src/services/MarketDataService'; -import { ExecutionService } from '../src/services/ExecutionService'; -import { IServiceContainer } from '@stock-bot/di'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('BacktestTest'); - -async function runBacktestWithDetailedLogging() { - // Create service container - const container: IServiceContainer = { - logger, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container); - const strategyManager = new StrategyManager(container); - - // Set services in container - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // Set backtest mode - await modeManager.setMode('backtest', { - startTime: new Date('2020-01-01').getTime(), - endTime: new Date('2025-01-01').getTime(), - speedMultiplier: 1 - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - name: 'SMA Crossover Test', - strategy: 'sma-crossover', - symbols: ['AAPL', 'GOOGL', 'MSFT'], - startDate: '2020-01-01', - endDate: '2025-01-01', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' - }; - - logger.info('Starting backtest with configuration:', config); - - try { - const result = await backtestEngine.runBacktest(config); - - logger.info('=== BACKTEST RESULTS ==='); - logger.info(`Total Trades: ${result.metrics.totalTrades}`); - logger.info(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); - logger.info(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); - logger.info(`Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(2)}`); - logger.info(`Max Drawdown: ${result.metrics.maxDrawdown.toFixed(2)}%`); - - logger.info('\n=== TRADE HISTORY ==='); - result.trades.forEach((trade, i) => { - logger.info(`Trade ${i + 1}:`); - logger.info(` Symbol: ${trade.symbol}`); - logger.info(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - logger.info(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - logger.info(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`); - }); - - } catch (error) { - logger.error('Backtest failed:', error); - } -} - -// Run the test -runBacktestWithDetailedLogging().catch(console.error); \ No newline at end of file diff --git a/apps/stock/orchestrator/examples/test-engine-import.ts b/apps/stock/orchestrator/examples/test-engine-import.ts deleted file mode 100644 index 08c387ca..00000000 --- a/apps/stock/orchestrator/examples/test-engine-import.ts +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bun - -// Test importing the @stock-bot/engine package -import * as engine from '@stock-bot/engine'; - -console.log('Successfully imported @stock-bot/engine'); -console.log('Available exports:', Object.keys(engine)); - -// Test creating some basic objects if they're available -try { - if (engine.createBacktestEngine) { - console.log('โœ“ createBacktestEngine is available'); - } - - if (engine.createIndicator) { - console.log('โœ“ createIndicator is available'); - } - - if (engine.createRiskManager) { - console.log('โœ“ createRiskManager is available'); - } - - // List all available functions - console.log('\nAll available functions:'); - for (const [key, value] of Object.entries(engine)) { - if (typeof value === 'function') { - console.log(` - ${key}()`); - } - } -} catch (error) { - console.error('Error testing engine exports:', error); -} \ No newline at end of file diff --git a/apps/stock/orchestrator/examples/test-short-trades.ts b/apps/stock/orchestrator/examples/test-short-trades.ts deleted file mode 100644 index 1e05c958..00000000 --- a/apps/stock/orchestrator/examples/test-short-trades.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -async function testShortTrades() { - // Create service container - const { - container, - storageService, - marketDataService: _marketDataService, - modeManager, - strategyManager, - } = await createExampleRuntime(); - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Short Trade Test', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('Testing short trade recording...\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('=== BACKTEST RESULTS ==='); - console.log(`Total Trades: ${result.metrics.totalTrades}`); - console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); - console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); - - // Count long vs short trades - let longTrades = 0; - let shortTrades = 0; - - console.log('\n=== TRADE BREAKDOWN ==='); - result.trades.forEach((trade, i) => { - const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT'; - if (trade.side === 'buy') { - longTrades++; - } else { - shortTrades++; - } - - console.log(`Trade ${i + 1} (${tradeType}):`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`); - console.log(''); - }); - - console.log('=== TRADE TYPE SUMMARY ==='); - console.log(`Long trades: ${longTrades}`); - console.log(`Short trades: ${shortTrades}`); - console.log(`Total trades: ${result.metrics.totalTrades}`); - } catch (error) { - console.error('Test failed:', error); - } -} - -// Run the test -testShortTrades().catch(console.error); diff --git a/apps/stock/orchestrator/examples/trace-short-positions.ts b/apps/stock/orchestrator/examples/trace-short-positions.ts deleted file mode 100644 index 58a56dd1..00000000 --- a/apps/stock/orchestrator/examples/trace-short-positions.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import type { StrategyFill } from '../src/services/ExecutionService'; -import type { OrderRequest } from '../src/types'; -import { createExampleRuntime } from './example-runtime'; - -async function traceShortPositions() { - let orderCount = 0; - let fillCount = 0; - const orderTracker: (OrderRequest & { count: number })[] = []; - const fillTracker: StrategyFill[] = []; - - // Create service container with detailed logging - const { container, storageService, modeManager, strategyManager } = await createExampleRuntime(); - strategyManager.on('order', (event: { order: OrderRequest }) => { - orderTracker.push({ ...event.order, count: ++orderCount }); - }); - strategyManager.on('fill', (fill: StrategyFill) => { - fillCount++; - fillTracker.push(fill); - }); - - // Listen to strategy events - strategyManager.on('signal', (signal: unknown) => { - console.log('\n๐ŸŽฏ STRATEGY SIGNAL:', signal); - }); - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-06-01T00:00:00Z', - endDate: '2023-09-01T00:00:00Z', // 3 months - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Short Position Trace', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-06-01T00:00:00Z', - endDate: '2023-09-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('=== TRACING SHORT POSITION FLOW ===\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('\n=== ORDER/FILL TRACKING SUMMARY ==='); - console.log(`Total orders submitted: ${orderCount}`); - console.log(`Total fills executed: ${fillCount}`); - - // Analyze order flow - let buyOrders = 0; - let sellOrders = 0; - orderTracker.forEach(order => { - if (order.side === 'buy') { - buyOrders++; - } else { - sellOrders++; - } - }); - - console.log(`\nOrder breakdown:`); - console.log(`- BUY orders: ${buyOrders}`); - console.log(`- SELL orders: ${sellOrders}`); - - // Check for short positions - console.log('\n=== LOOKING FOR SHORT PATTERNS ==='); - console.log('(A short position starts with a SELL and closes with a BUY)\n'); - - let potentialShorts = 0; - for (let i = 0; i < orderTracker.length - 1; i++) { - if (orderTracker[i].side === 'sell') { - // Look for subsequent buy to close - for (let j = i + 1; j < orderTracker.length; j++) { - if (orderTracker[j].side === 'buy' && orderTracker[j].symbol === orderTracker[i].symbol) { - potentialShorts++; - console.log(`Potential short trade found:`); - console.log(` Open: Order #${orderTracker[i].count} (SELL)`); - console.log(` Close: Order #${orderTracker[j].count} (BUY)`); - break; - } - } - } - } - - console.log(`\nPotential short trades identified: ${potentialShorts}`); - - // Final results - console.log('\n=== BACKTEST RESULTS ==='); - console.log(`Total closed trades: ${result.metrics.totalTrades}`); - - let longTrades = 0; - let shortTrades = 0; - - result.trades.forEach((trade, i) => { - const tradeType = trade.side === 'buy' ? 'LONG' : 'SHORT'; - if (trade.side === 'buy') { - longTrades++; - } else { - shortTrades++; - } - - console.log(`\nTrade ${i + 1} (${tradeType}):`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)}`); - }); - - console.log('\n=== FINAL SUMMARY ==='); - console.log(`Long trades recorded: ${longTrades}`); - console.log(`Short trades recorded: ${shortTrades}`); - console.log(`Expected short trades (from order flow): ${potentialShorts}`); - - if (shortTrades < potentialShorts) { - console.log('\nโŒ ISSUE: Not all short trades were recorded in closed trades!'); - console.log('This suggests the Rust core trade matching logic may have an issue.'); - } - } catch (error) { - console.error('Trace failed:', error); - } -} - -// Run the trace -traceShortPositions().catch(console.error); diff --git a/apps/stock/orchestrator/examples/verify-both-trade-types.ts b/apps/stock/orchestrator/examples/verify-both-trade-types.ts deleted file mode 100644 index 41d689cd..00000000 --- a/apps/stock/orchestrator/examples/verify-both-trade-types.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { createExampleRuntime } from './example-runtime'; - -async function verifyBothTradeTypes() { - // Create service container - const { - container, - storageService, - marketDataService: _marketDataService, - modeManager, - strategyManager, - } = await createExampleRuntime(); - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL.US'], - initialCapital: 100000, - dataFrequency: '1d', - strategy: 'sma-crossover', - }); - - // Create backtest engine - const backtestEngine = new BacktestEngine(container, storageService, strategyManager); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Trade Type Verification', - strategy: 'sma-crossover', - symbols: ['AAPL.US'], - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d' as const, - speed: 'max' as const, - }; - - console.log('=== VERIFYING BOTH LONG AND SHORT TRADES ===\n'); - - try { - const result = await backtestEngine.runBacktest(config); - - console.log('=== BACKTEST COMPLETE ==='); - console.log(`Total Trades: ${result.metrics.totalTrades}`); - console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); - console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`); - - // Analyze trades - let longTrades = 0; - let shortTrades = 0; - let longPnL = 0; - let shortPnL = 0; - - console.log('\n=== DETAILED TRADE ANALYSIS ==='); - result.trades.forEach((trade, i) => { - const isLong = trade.side === 'buy'; - const tradeType = isLong ? 'LONG' : 'SHORT'; - - if (isLong) { - longTrades++; - longPnL += trade.pnl; - } else { - shortTrades++; - shortPnL += trade.pnl; - } - - console.log(`\nTrade ${i + 1}:`); - console.log(` Type: ${tradeType} position`); - console.log(` Opening side: ${trade.side.toUpperCase()}`); - console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); - console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); - console.log(` P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`); - - // Explain the trade flow - if (isLong) { - console.log(` Order flow: BUY ${trade.quantity} shares โ†’ SELL ${trade.quantity} shares`); - } else { - console.log(` Order flow: SELL ${trade.quantity} shares โ†’ BUY ${trade.quantity} shares`); - } - }); - - console.log('\n=== SUMMARY BY TRADE TYPE ==='); - console.log(`LONG trades: ${longTrades}`); - console.log(` - Total P&L from longs: $${longPnL.toFixed(2)}`); - console.log( - ` - Average P&L per long: $${longTrades > 0 ? (longPnL / longTrades).toFixed(2) : '0.00'}` - ); - - console.log(`\nSHORT trades: ${shortTrades}`); - console.log(` - Total P&L from shorts: $${shortPnL.toFixed(2)}`); - console.log( - ` - Average P&L per short: $${shortTrades > 0 ? (shortPnL / shortTrades).toFixed(2) : '0.00'}` - ); - - console.log(`\nTotal trades: ${result.metrics.totalTrades}`); - - if (longTrades === 0) { - console.log('\nโš ๏ธ WARNING: No long trades found!'); - } - if (shortTrades === 0) { - console.log('\nโš ๏ธ WARNING: No short trades found!'); - } - } catch (error) { - console.error('Test failed:', error); - } -} - -// Run the verification -verifyBothTradeTypes().catch(console.error); diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index f886767a..fb28f443 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -1,57 +1,35 @@ { "name": "@stock-bot/orchestrator", "version": "0.1.0", - "description": "Trading system orchestrator - coordinates between Rust core, data feeds, and analytics", + "description": "Trading system orchestrator โ€” canonical Rust execution and durable research/paper workers", "type": "module", "main": "dist/index.js", "scripts": { "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core", + "build": "bun build src/index.ts src/backtest/native-worker.ts src/paper/paper-host.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine", "start": "bun dist/index.js", "test": "bun test", - "test:indicators": "bun test tests/indicators.test.ts", - "example:indicators": "bun run examples/indicator-usage.ts", - "test:engine": "bun run examples/test-engine-import.ts", "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" }, "dependencies": { "@stock-bot/research": "workspace:*", "@stock-bot/calculations": "workspace:*", "decimal.js-light": "2.5.1", - "@stock-bot/engine": "*", - "@stock-bot/cache": "*", - "@stock-bot/config": "*", - "@stock-bot/di": "*", - "@stock-bot/logger": "*", - "@stock-bot/questdb": "*", - "@stock-bot/queue": "*", - "@stock-bot/shutdown": "*", - "@stock-bot/stock-config": "*", + "@stock-bot/engine": "workspace:*", + "@stock-bot/di": "workspace:*", + "@stock-bot/logger": "workspace:*", + "@stock-bot/stock-config": "workspace:*", "hono": "^4.0.0", - "socket.io": "^4.7.2", - "socket.io-client": "^4.7.2", "zod": "^3.22.0", - "uuid": "^9.0.0", - "axios": "^1.6.0", "@stock-bot/services": "workspace:*", - "@stock-bot/mongodb": "workspace:*", "@stock-bot/postgres": "workspace:*", "@stock-bot/invariants": "workspace:*", "@stock-bot/types": "workspace:*", "@stock-bot/handlers": "workspace:*", "@stock-bot/trading-runtime": "workspace:*" }, - "peerDependencies": { - "@tensorflow/tfjs-node": "^4.0.0" - }, - "peerDependenciesMeta": { - "@tensorflow/tfjs-node": { - "optional": true - } - }, "devDependencies": { "@types/node": "^20.0.0", - "typescript": "^5.0.0", - "@tensorflow/tfjs-node": "^4.0.0" + "typescript": "^5.0.0" } } diff --git a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts deleted file mode 100644 index 2de9af68..00000000 --- a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { - factorStatistics, - finite, - formatStatistic, - performanceAnalysis, - type EquityPoint, -} from '@stock-bot/calculations/analytics'; - -export interface Trade { - entryTime: Date; - exitTime: Date; - symbol: string; - side: 'long' | 'short'; - entryPrice: number; - exitPrice: number; - quantity: number; - commission: number; - pnl: number; - returnPct: number; - holdingPeriod: number; - mae: number; - mfe: number; -} -type Analysis = ReturnType; -type CoreMetrics = Analysis['metrics']; -/** Legacy report facade: percentage fields remain percentage points; the pure core uses fractions. */ -export type PerformanceMetrics = CoreMetrics; -export type FactorAttribution = ReturnType; -export interface DrawdownAnalysis { - maxDrawdown: number; - maxDrawdownDuration: number; - currentDrawdown: number; - drawdownPeriods: { - start: Date; - end: Date; - depth: number; - duration: number; - recovery: number | null; - }[]; - underwaterCurve: { date: Date; drawdown: number }[]; -} - -const percentageFields = [ - 'totalReturn', - 'annualizedReturn', - 'cagr', - 'volatility', - 'downVolatility', - 'var95', - 'cvar95', - 'winRate', -] as const; - -/** Compatibility facade over pure, shared math; observations are detached and cache invalidation is explicit. */ -export class PerformanceAnalyzer { - private equityCurve: EquityPoint[] = []; - private trades: Trade[] = []; - private benchmarkReturns?: number[]; - private analysis?: Analysis; - constructor(private readonly initialCapital = 100000) { - if (finite(initialCapital) <= 0) { - throw new Error('Initial capital must be positive'); - } - } - addEquityPoint(date: Date, value: number): void { - const timestamp = finite(date.getTime()); - finite(value); - const last = this.equityCurve[this.equityCurve.length - 1]; - if (last && timestamp < last.timestamp) { - throw new Error('Equity observations must be ordered'); - } - if (last?.timestamp === timestamp) { - last.value = value; - } else { - this.equityCurve.push({ timestamp, value }); - } - this.analysis = undefined; - } - addTrade(trade: Trade): void { - finite(trade.pnl); - finite(trade.holdingPeriod); - if (trade.holdingPeriod < 0) { - throw new Error('Holding period must be nonnegative'); - } - this.trades.push(structuredClone(trade)); - this.analysis = undefined; - } - setBenchmark(returns: number[]): void { - for (const value of returns) { - finite(value); - } - this.benchmarkReturns = [...returns]; - this.analysis = undefined; - } - private evaluate(): Analysis { - this.analysis ??= performanceAnalysis( - this.equityCurve, - this.trades, - this.initialCapital, - this.benchmarkReturns - ); - return this.analysis; - } - getAnalysis(): Analysis { - return structuredClone(this.evaluate()); - } - analyze(): PerformanceMetrics { - const metrics = { ...this.evaluate().metrics }; - for (const field of percentageFields) { - const value = metrics[field]; - if (value !== null) { - metrics[field] = finite(value * 100); - } - } - return metrics; - } - analyzeDrawdowns(): DrawdownAnalysis { - const equity = this.evaluate().equity; - return { - maxDrawdown: equity.maxDrawdown, - maxDrawdownDuration: equity.maxDrawdownDuration, - currentDrawdown: equity.currentDrawdown, - drawdownPeriods: equity.periods.map(period => ({ - ...period, - start: new Date(period.start), - end: new Date(period.end), - })), - underwaterCurve: equity.underwater.map(point => ({ - date: new Date(point.timestamp), - drawdown: point.value, - })), - }; - } - calculateFactorAttribution(benchmark: number[]): FactorAttribution { - return factorStatistics(this.evaluate().equity.dailyReturns, benchmark); - } - exportReport(metrics: PerformanceMetrics = this.analyze()): string { - const number = (value: number | null, scale = 1) => formatStatistic(value, 2, scale); - return [ - '# Performance Report', - '', - '## Summary Statistics', - '- Total Return: ' + number(metrics.totalReturn) + '%', - '- Annualized Return: ' + - number(metrics.annualizedReturn) + - (metrics.annualizedReturn === null ? '' : '%'), - '- CAGR: ' + number(metrics.cagr) + (metrics.cagr === null ? '' : '%'), - '- Volatility: ' + number(metrics.volatility) + (metrics.volatility === null ? '' : '%'), - '- Max Drawdown: ' + number(metrics.maxDrawdown, 100) + '%', - '- Sharpe Ratio: ' + number(metrics.sharpeRatio), - '- Sortino Ratio: ' + number(metrics.sortinoRatio), - '', - '## Trade Analysis', - '- Total Trades: ' + metrics.totalTrades, - '- Win Rate: ' + number(metrics.winRate) + '%', - '- Profit Factor: ' + number(metrics.profitFactor), - '- Average Win: $' + number(metrics.avgWin), - '- Average Loss: $' + number(metrics.avgLoss), - '- Expectancy: $' + number(metrics.expectancy), - '', - '## Risk Metrics', - '- VaR (95%): ' + number(metrics.var95) + (metrics.var95 === null ? '' : '%'), - '- CVaR (95%): ' + number(metrics.cvar95) + (metrics.cvar95 === null ? '' : '%'), - '- Downside Volatility: ' + - number(metrics.downVolatility) + - (metrics.downVolatility === null ? '' : '%'), - '- Tail Ratio: ' + number(metrics.tailRatio), - '- Skewness: ' + number(metrics.skewness), - '- Kurtosis: ' + number(metrics.kurtosis), - ].join('\n'); - } -} diff --git a/apps/stock/orchestrator/src/api/rest/analytics.ts b/apps/stock/orchestrator/src/api/rest/analytics.ts deleted file mode 100644 index 2521051f..00000000 --- a/apps/stock/orchestrator/src/api/rest/analytics.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { - correlationRequestSchema, - dateRangeSchema, - optimizationRequestSchema, - predictionRequestSchema, -} from '../../contracts/analytics'; -import { AnalyticsServiceError } from '../../services/analytics-error'; -import type { OrchestratorServices } from '../../types'; - -export function createAnalyticsRoutes(container: OrchestratorServices): Hono { - const app = new Hono(); - const service = () => { - const analytics = container.custom?.AnalyticsService; - if (!analytics) { - throw new AnalyticsServiceError('unavailable'); - } - return analytics; - }; - app.onError((error, c) => { - if (error instanceof z.ZodError) { - return c.json({ error: 'Invalid analytics request', details: error.issues }, 400); - } - if (error instanceof SyntaxError) { - return c.json({ error: 'Invalid JSON body' }, 400); - } - if (error instanceof AnalyticsServiceError) { - return c.json({ error: error.message, code: error.code }, error.status); - } - container.logger.error('Analytics request failed', { name: error.name }); - return c.json({ error: 'Analytics request failed' }, 500); - }); - app.get('/performance/:portfolioId', async c => { - const range = dateRangeSchema.parse({ - startDate: c.req.query('start_date'), - endDate: c.req.query('end_date'), - }); - return c.json( - await service().getPerformanceMetrics( - c.req.param('portfolioId'), - new Date(range.startDate), - new Date(range.endDate) - ) - ); - }); - app.post('/optimize', async c => { - return c.json( - await service().optimizePortfolio(optimizationRequestSchema.parse(await c.req.json())) - ); - }); - app.get('/risk/:portfolioId', async c => - c.json(await service().getRiskMetrics(c.req.param('portfolioId'))) - ); - app.get('/regime', async c => - c.json({ regime: await service().detectMarketRegime(), timestamp: new Date().toISOString() }) - ); - app.post('/correlation', async c => { - const { symbols } = correlationRequestSchema.parse(await c.req.json()); - return c.json({ symbols, matrix: await service().calculateCorrelationMatrix(symbols) }); - }); - app.post('/predict', async c => { - const { modelId, features } = predictionRequestSchema.parse(await c.req.json()); - return c.json(await service().predictWithModel(modelId, features)); - }); - return app; -} diff --git a/apps/stock/orchestrator/src/api/rest/orders.ts b/apps/stock/orchestrator/src/api/rest/orders.ts deleted file mode 100644 index 1ff2c016..00000000 --- a/apps/stock/orchestrator/src/api/rest/orders.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { ExecutionConflictError } from '../../execution/repository'; -import { ExecutionService, UnsupportedExecutionError } from '../../services/ExecutionService'; -import type { OrchestratorServices as IServiceContainer } from '../../types'; -import { OrderRequestSchema } from '../../types'; - -const OrderIdSchema = z.object({ - orderId: z.string(), -}); - -export function createOrderRoutes(container: IServiceContainer): Hono { - const app = new Hono(); - const executionService = container.custom?.ExecutionService as ExecutionService; - - // Submit new order - app.post('/', async c => { - try { - const body = await c.req.json(); - const orderRequest = OrderRequestSchema.extend({ - clientOrderId: z.string().min(1).max(256), - }).parse(body); - - const result = await executionService.submitOrder(orderRequest); - - return c.json(result, 201); - } catch (error) { - if (error instanceof ExecutionConflictError) { - return c.json({ error: error.message }, 409); - } - if (error instanceof UnsupportedExecutionError) { - return c.json({ error: error.message }, 503); - } - if (error instanceof z.ZodError) { - return c.json( - { - error: 'Invalid order request', - details: error.errors, - }, - 400 - ); - } - - container.logger.error('Error submitting order:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to submit order', - }, - 500 - ); - } - }); - - // Cancel order - app.delete('/:orderId', async c => { - try { - const { orderId } = OrderIdSchema.parse(c.req.param()); - - const success = await executionService.cancelOrder(orderId); - - if (success) { - return c.json({ message: 'Order cancelled successfully' }); - } else { - return c.json({ error: 'Order not found or already filled' }, 404); - } - } catch (error) { - container.logger.error('Error cancelling order:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to cancel order', - }, - 500 - ); - } - }); - - // Get order status - app.get('/:orderId', async c => { - try { - const { orderId } = OrderIdSchema.parse(c.req.param()); - - const status = await executionService.getOrderStatus(orderId); - - if (status) { - return c.json(status); - } else { - return c.json({ error: 'Order not found' }, 404); - } - } catch (error) { - container.logger.error('Error getting order status:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get order status', - }, - 500 - ); - } - }); - - // Batch order submission - app.post('/batch', async c => { - try { - const body = await c.req.json(); - const orders = z - .array(OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) })) - .parse(body); - - const results = await Promise.allSettled( - orders.map(order => executionService.submitOrder(order)) - ); - - const response = results.map((result, index) => ({ - order: orders[index], - result: result.status === 'fulfilled' ? result.value : { error: result.reason }, - })); - - return c.json(response, 201); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json( - { - error: 'Invalid batch order request', - details: error.errors, - }, - 400 - ); - } - - container.logger.error('Error submitting batch orders:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to submit batch orders', - }, - 500 - ); - } - }); - - return app; -} diff --git a/apps/stock/orchestrator/src/api/rest/paper-deployments.ts b/apps/stock/orchestrator/src/api/rest/paper-deployments.ts index ce198687..d3d5bef2 100644 --- a/apps/stock/orchestrator/src/api/rest/paper-deployments.ts +++ b/apps/stock/orchestrator/src/api/rest/paper-deployments.ts @@ -4,10 +4,10 @@ import { paperActivationSchema, paperHaltSchema, PaperRuntimeError, -} from '../../contracts/paper-runtime'; -import { ExecutionConflictError } from '../../execution/repository'; -import { PaperDeploymentError } from '../../paper/paper-deployment-custody'; -import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator'; +} from '@stock-bot/stock-config/paper-runtime'; +import { ExecutionConflictError } from '../../execution/canonical-paper'; +import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody'; +import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator'; import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost'; export function createPaperDeploymentHostRoutes( diff --git a/apps/stock/orchestrator/src/api/rest/paper.ts b/apps/stock/orchestrator/src/api/rest/paper.ts index 893f7720..a0271455 100644 --- a/apps/stock/orchestrator/src/api/rest/paper.ts +++ b/apps/stock/orchestrator/src/api/rest/paper.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { z } from 'zod'; -import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import { getCredentialHttpPrincipal } from '@stock-bot/di/http-security'; import { paperActivationSchema, paperConnectionSchema, @@ -8,10 +8,10 @@ import { paperHaltSchema, PaperRuntimeError, type PaperReadiness, -} from '../../contracts/paper-runtime'; -import { ExecutionConflictError } from '../../execution/repository'; -import { PaperDeploymentError } from '../../paper/paper-deployment-custody'; -import { paperAllowedOrigins, requirePaperOperator } from '../../paper/paper-operator'; +} from '@stock-bot/stock-config/paper-runtime'; +import { ExecutionConflictError } from '../../execution/canonical-paper'; +import { PaperDeploymentError } from '@stock-bot/trading-runtime/paper-deployment-custody'; +import { paperAllowedOrigins, requirePaperOperator } from '@stock-bot/trading-runtime/paper-operator'; import type { PaperDeploymentHost } from '../../paper/PaperDeploymentHost'; import type { OrchestratorServices } from '../../types'; diff --git a/apps/stock/orchestrator/src/api/rest/positions.ts b/apps/stock/orchestrator/src/api/rest/positions.ts deleted file mode 100644 index fb5edb33..00000000 --- a/apps/stock/orchestrator/src/api/rest/positions.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { defined } from '@stock-bot/invariants'; -import { ModeManager } from '../../core/ModeManager'; -import type { OrchestratorServices as IServiceContainer } from '../../types'; - -const SymbolSchema = z.object({ - symbol: z.string(), -}); - -export function createPositionRoutes(container: IServiceContainer): Hono { - const app = new Hono(); - const execution = defined(container.custom?.ExecutionService); - const positionsFromLedger = async () => - (await execution.getPositions()).map(p => ({ - symbol: p.symbol, - quantity: p.quantity, - average_price: p.averagePrice, - realized_pnl: p.realizedPnl, - unrealized_pnl: p.unrealizedPnl, - })); - const modeManager = container.custom?.ModeManager as ModeManager; - - // Get all positions - app.get('/', async c => { - try { - const positions = await positionsFromLedger(); - - return c.json({ - mode: modeManager.getCurrentMode(), - positions, - }); - } catch (error) { - container.logger.error('Error getting positions:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get positions', - }, - 500 - ); - } - }); - - // Get open positions only - app.get('/open', async c => { - try { - const positions = (await positionsFromLedger()).filter(p => p.quantity !== 0); - - return c.json({ - mode: modeManager.getCurrentMode(), - positions, - }); - } catch (error) { - container.logger.error('Error getting open positions:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get open positions', - }, - 500 - ); - } - }); - - // Get position for specific symbol - app.get('/:symbol', async c => { - try { - const { symbol } = SymbolSchema.parse(c.req.param()); - const position = (await positionsFromLedger()).find(p => p.symbol === symbol); - - if (position) { - return c.json({ - mode: modeManager.getCurrentMode(), - position, - }); - } else { - return c.json( - { - error: 'Position not found', - symbol, - }, - 404 - ); - } - } catch (error) { - container.logger.error('Error getting position:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get position', - }, - 500 - ); - } - }); - - // Get P&L summary - app.get('/pnl/summary', async c => { - try { - const account = await execution.getAccount(); - const realizedPnl = account.realizedPnl, - unrealizedPnl = account.unrealizedPnl; - - return c.json({ - mode: modeManager.getCurrentMode(), - pnl: { - realized: realizedPnl, - unrealized: unrealizedPnl, - total: realizedPnl + unrealizedPnl, - }, - timestamp: new Date().toISOString(), - }); - } catch (error) { - container.logger.error('Error getting P&L:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get P&L', - }, - 500 - ); - } - }); - - // Get risk metrics - app.get('/risk/metrics', async c => { - try { - const account = await execution.getAccount(); - const metrics = { - gross_exposure: account.grossExposure, - daily_pnl: account.dailyPnl, - position_count: Object.values(account.positions).filter(p => p.quantity !== 0).length, - limits: account.limits, - }; - - return c.json({ - mode: modeManager.getCurrentMode(), - risk: metrics, - timestamp: new Date().toISOString(), - }); - } catch (error) { - container.logger.error('Error getting risk metrics:', error); - return c.json( - { - error: error instanceof Error ? error.message : 'Failed to get risk metrics', - }, - 500 - ); - } - }); - - return app; -} diff --git a/apps/stock/orchestrator/src/api/websocket/index.ts b/apps/stock/orchestrator/src/api/websocket/index.ts deleted file mode 100644 index 9b2b8db1..00000000 --- a/apps/stock/orchestrator/src/api/websocket/index.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { Socket, Server as SocketIOServer } from 'socket.io'; -import { z } from 'zod'; -import { defined } from '@stock-bot/invariants'; -import { ModeManager } from '../../core/ModeManager'; -import { ExecutionService } from '../../services/ExecutionService'; -import { MarketDataService } from '../../services/MarketDataService'; -import { OrderRequestSchema, type OrchestratorServices as IServiceContainer } from '../../types'; - -const SubscribeSchema = z.object({ - symbols: z.array(z.string()), - dataTypes: z.array(z.enum(['quote', 'trade', 'bar'])).optional(), -}); - -const UnsubscribeSchema = z.object({ - symbols: z.array(z.string()), -}); - -export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceContainer): void { - const marketDataService = container.custom?.MarketDataService as MarketDataService; - const executionService = container.custom?.ExecutionService as ExecutionService; - const modeManager = container.custom?.ModeManager as ModeManager; - - // Track client subscriptions - const clientSubscriptions = new Map>(); - - io.on('connection', (socket: Socket) => { - container.logger.info(`WebSocket client connected: ${socket.id}`); - clientSubscriptions.set(socket.id, new Set()); - - // Send initial connection info - socket.emit('connected', { - mode: modeManager.getCurrentMode(), - timestamp: new Date().toISOString(), - }); - - // Handle market data subscriptions - socket.on('subscribe', async (data, callback?: Function) => { - try { - const { symbols, dataTypes: _dataTypes } = SubscribeSchema.parse(data); - const subscriptions = defined(clientSubscriptions.get(socket.id)); - - for (const symbol of symbols) { - await marketDataService.subscribeToSymbol(symbol); - subscriptions.add(symbol); - } - - container.logger.debug(`Client ${socket.id} subscribed to: ${symbols.join(', ')}`); - - if (callback) { - callback({ success: true, symbols }); - } - } catch (error) { - container.logger.error('Subscription error:', error); - if (callback) { - callback({ - success: false, - error: error instanceof Error ? error.message : 'Subscription failed', - }); - } - } - }); - - // Handle unsubscribe - socket.on('unsubscribe', async (data, callback?: Function) => { - try { - const { symbols } = UnsubscribeSchema.parse(data); - const subscriptions = defined(clientSubscriptions.get(socket.id)); - - for (const symbol of symbols) { - subscriptions.delete(symbol); - - // Check if any other clients are subscribed - let othersSubscribed = false; - for (const [clientId, subs] of clientSubscriptions) { - if (clientId !== socket.id && subs.has(symbol)) { - othersSubscribed = true; - break; - } - } - - if (!othersSubscribed) { - await marketDataService.unsubscribeFromSymbol(symbol); - } - } - - container.logger.debug(`Client ${socket.id} unsubscribed from: ${symbols.join(', ')}`); - - if (callback) { - callback({ success: true, symbols }); - } - } catch (error) { - container.logger.error('Unsubscribe error:', error); - if (callback) { - callback({ - success: false, - error: error instanceof Error ? error.message : 'Unsubscribe failed', - }); - } - } - }); - - // Handle order submission via WebSocket - socket.on('submitOrder', async (order, callback?: Function) => { - try { - const result = await executionService.submitOrder( - OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }).parse(order) - ); - if (callback) { - callback({ success: true, result }); - } - } catch (error) { - container.logger.error('Order submission error:', error); - if (callback) { - callback({ - success: false, - error: error instanceof Error ? error.message : 'Order submission failed', - }); - } - } - }); - - // Handle position queries - socket.on('getPositions', async (callback?: Function) => { - try { - const positions = await executionService.getPositions(); - - if (callback) { - callback({ success: true, positions }); - } - } catch (error) { - container.logger.error('Error getting positions:', error); - if (callback) { - callback({ - success: false, - error: error instanceof Error ? error.message : 'Failed to get positions', - }); - } - } - }); - - // Handle disconnection - socket.on('disconnect', async () => { - container.logger.info(`WebSocket client disconnected: ${socket.id}`); - - // Unsubscribe from all symbols for this client - const subscriptions = clientSubscriptions.get(socket.id); - if (subscriptions) { - for (const symbol of subscriptions) { - // Check if any other clients are subscribed - let othersSubscribed = false; - for (const [clientId, subs] of clientSubscriptions) { - if (clientId !== socket.id && subs.has(symbol)) { - othersSubscribed = true; - break; - } - } - - if (!othersSubscribed) { - await marketDataService.unsubscribeFromSymbol(symbol); - } - } - } - - clientSubscriptions.delete(socket.id); - }); - }); - - // Forward market data to subscribed clients - marketDataService.on('marketDataBatch', batch => { - for (const data of batch) { - for (const [clientId, subscriptions] of clientSubscriptions) { - if (subscriptions.has(data.data.symbol)) { - io.to(clientId).emit('marketData', data); - } - } - } - }); - - // Forward order updates to all clients - executionService.on('orderUpdate', update => { - io.emit('orderUpdate', update); - }); - - // Forward fills to all clients - executionService.on('fill', fill => { - io.emit('fill', fill); - }); - - // Mode change notifications - modeManager.on('modeChanged', config => { - io.emit('modeChanged', { - mode: config.mode, - timestamp: new Date().toISOString(), - }); - }); - - container.logger.info('WebSocket handlers initialized'); -} diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts deleted file mode 100644 index 1a819f12..00000000 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { EventEmitter } from 'node:events'; -import type { TradingEngine } from '@stock-bot/engine'; -import { defined } from '@stock-bot/invariants'; -import type { Logger } from '@stock-bot/services'; -import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; -import { DataManager } from '../data/DataManager'; -import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; -import { amount, decimal } from '../execution/model'; -import type { ExecutionService } from '../services/ExecutionService'; -import type { StorageService } from '../services/StorageService'; -import type { StrategyManager } from '../strategies/StrategyManager'; -import type { BacktestConfig } from '../types'; -import { BacktestMarket } from './BacktestMarket'; -import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback'; -import { BacktestReport } from './BacktestReport'; -import type { LegacyBacktestExecutionEngine } from './execution-engine'; -import { closedTradesSchema } from './native-result'; -import { backtestStrategies } from './strategy-plan'; -import type { BacktestResult } from './typescript-result'; - -export type { BacktestResult } from './typescript-result'; -const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const; - -/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */ -export class BacktestEngine extends EventEmitter implements LegacyBacktestExecutionEngine { - private playback?: BacktestPlayback; - private active?: Promise; - private completedReport?: BacktestReport; - private closing = false; - - constructor( - private readonly dependencies: { - logger: Pick; - storage: Pick; - strategies: Pick; - execution: Pick; - getTradingEngine: () => TradingEngine; - } - ) { - super(); - } - - async runBacktest(input: unknown, resolver?: DatasetResolver): Promise { - if (this.closing || this.active) { - throw new Error( - this.closing ? 'Backtest engine is shutting down' : 'Backtest already running' - ); - } - const config = parseBacktestRequest(input); - const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]); - this.playback = playback; - this.completedReport = undefined; - const work = this.execute(config, playback, resolver); - this.active = work; - try { - return await work; - } finally { - playback.finish(); - this.active = undefined; - } - } - - private async execute( - config: BacktestConfig, - playback: BacktestPlayback, - resolver?: DatasetResolver - ): Promise { - const plan = backtestStrategies(config, 'typescript'); - const { logger, storage, strategies: strategyManager, execution } = this.dependencies; - logger.info('Starting TypeScript backtest', { symbols: config.symbols }); - const dataset = await playback.read(() => - resolveDataset(storage, config, resolver, playback.signal) - ); - playback.assertRunning(); - const dataManager = new DataManager(storage); - dataManager.inspectDataset(dataset); - const strategies = plan.map(({ name, parameters, index }) => ({ - id: name + '-' + index, - name, - enabled: true, - parameters, - symbols: config.symbols, - allocation: 1 / plan.length, - })); - await strategyManager.initializeStrategies(strategies); - playback.assertRunning(); - const trading = this.dependencies.getTradingEngine(); - const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash); - const report = new BacktestReport(config, config.runId ?? randomUUID()); - await playback.process( - dataset.bars, - bar => bar.timestamp, - async bar => { - trading.advanceTime(bar.timestamp); - const data = { - type: 'bar' as const, - data: bar, - eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'), - }; - market.process(data); - await strategyManager.onMarketData(data); - report.record(bar.timestamp, (await execution.getAccount()).equity); - }, - progress => this.publishProgress(progress) - ); - playback.assertRunning(); - const closedTrades = closedTradesSchema.parse(JSON.parse(trading.getClosedTrades())); - const account = await execution.getAccount(); - playback.assertRunning(); - const positions = Object.values(account.positions) - .filter(position => position.quantity !== 0) - .map(position => { - const quote = account.quotes[position.symbol]; - const currentPrice = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice; - return { - ...position, - currentPrice, - unrealizedPnl: amount( - decimal(currentPrice).minus(position.averagePrice).times(position.quantity) - ), - }; - }); - const result = report.complete( - dataset, - closedTrades, - positions, - dataManager.getDataQualityReport() - ); - this.completedReport = report; - logger.info('TypeScript backtest completed', { trades: result.trades.length }); - return result; - } - - private publishProgress(progress: PlaybackProgress): void { - try { - this.emit('progress', progress); - } catch (error) { - this.dependencies.logger.error('Backtest progress observer failed', { error }); - } - } - - async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise { - if (this.active) { - throw new Error('Cannot export an unfinished backtest'); - } - return defined(this.completedReport, 'No completed backtest report is available').export( - format - ); - } - async pauseBacktest(): Promise { - this.playback?.pause(); - } - async resumeBacktest(): Promise { - this.playback?.resume(); - } - async stopBacktest(): Promise { - this.playback?.stop(); - } - async shutdown(): Promise { - this.closing = true; - await this.stopBacktest(); - await this.active?.catch(() => {}); - } - setSpeedMultiplier(speed: number | null): void { - if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) { - throw new Error('Backtest speed must be positive or null'); - } - this.playback?.setSpeed(speed); - } - getStatus() { - return ( - this.playback?.getStatus() ?? { - isRunning: false, - isPaused: false, - progress: 0, - currentTime: 0, - } - ); - } -} diff --git a/apps/stock/orchestrator/src/backtest/BacktestMarket.ts b/apps/stock/orchestrator/src/backtest/BacktestMarket.ts deleted file mode 100644 index 9de70280..00000000 --- a/apps/stock/orchestrator/src/backtest/BacktestMarket.ts +++ /dev/null @@ -1,128 +0,0 @@ -import type { TradingEngine } from '@stock-bot/engine'; -import { at } from '@stock-bot/invariants'; -import type { MarketData, MarketMicrostructure } from '../types'; -import { MarketSimulator } from './MarketSimulator'; - -export type BacktestMarketPort = Pick< - TradingEngine, - 'updateQuote' | 'updateTrade' | 'setMicrostructure' ->; - -/** Market projection only: orders and financial accounting still go through ExecutionService. */ -export class BacktestMarket { - private readonly simulator = new MarketSimulator(); - private readonly microstructures = new Map(); - - constructor( - private readonly engine: BacktestMarketPort, - symbols: string[], - datasetHash: string - ) { - this.simulator.resetWithSeed(Number.parseInt(datasetHash.slice(0, 8), 16)); - this.loadMarketMicrostructure(symbols); - } - - process(data: MarketData): void { - // Process through market simulator for realistic orderbook - const orderbook = this.simulator.processMarketData(data); - - if (orderbook) { - // Update trading engine with simulated orderbook - if (orderbook.bids.length > 0 && orderbook.asks.length > 0) { - this.engine.updateQuote( - orderbook.symbol, - at(orderbook.bids, 0).price, - at(orderbook.asks, 0).price, - at(orderbook.bids, 0).size, - at(orderbook.asks, 0).size - ); - } - - // Set microstructure in trading core for realistic fills - const microstructure = this.microstructures.get(orderbook.symbol); - if (microstructure && this.engine.setMicrostructure) { - this.engine.setMicrostructure(orderbook.symbol, microstructure); - } - } else { - // Fallback to simple processing - switch (data.type) { - case 'quote': - this.engine.updateQuote( - data.data.symbol, - data.data.bid, - data.data.ask, - data.data.bidSize, - data.data.askSize - ); - break; - - case 'trade': - this.engine.updateTrade( - data.data.symbol, - data.data.price, - data.data.size, - data.data.side - ); - break; - - case 'bar': { - const spread = data.data.high - data.data.low; - const spreadBps = (spread / data.data.close) * 10000; - const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000; - - this.engine.updateQuote( - data.data.symbol, - data.data.close - halfSpread, - data.data.close + halfSpread, - data.data.volume / 100, - data.data.volume / 100 - ); - break; - } - } - } - } - - private loadMarketMicrostructure(symbols: string[]): void { - // In real implementation, would load from database - // For now, create reasonable defaults based on symbol characteristics - for (const symbol of symbols) { - const microstructure: MarketMicrostructure = { - symbol, - avgSpreadBps: 3, - dailyVolume: 10_000_000, - avgTradeSize: 100, - volatility: 0.2, - tickSize: 0.01, - lotSize: 1, - intradayVolumeProfile: this.generateIntradayProfile(), - }; - - this.microstructures.set(symbol, microstructure); - this.simulator.setMicrostructure(symbol, microstructure); - } - } - - private generateIntradayProfile(): number[] { - // U-shaped intraday volume pattern - const profile = new Array(24).fill(0); - const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM - - tradingHours.forEach((hour, idx) => { - if (idx === 0 || idx === tradingHours.length - 1) { - // High volume at open and close - profile[hour] = 0.2; - } else if (idx === 1 || idx === tradingHours.length - 2) { - // Moderate volume - profile[hour] = 0.15; - } else { - // Lower midday volume - profile[hour] = 0.1; - } - }); - - // Normalize - const sum = profile.reduce((a, b) => a + b, 0); - return profile.map(v => v / sum); - } -} diff --git a/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts b/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts deleted file mode 100644 index bfb18848..00000000 --- a/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { BacktestCancelledError } from './execution-engine'; - -export interface PlaybackProgress { - processed: number; - total: number; - remaining: number; - currentTime: Date; - currentDate: string; - progress: number; -} - -/** One run's cursor and interruptible controls; independent of trading, storage and reporting. */ -export class BacktestPlayback { - private readonly controller = new AbortController(); - private wake?: () => void; - private running = true; - private paused = false; - private processed = 0; - private total = 0; - private started = false; - - constructor( - private currentTime: number, - private speed: number | null - ) { - this.validateSpeed(speed); - } - - private validateSpeed(speed: number | null): void { - if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) { - throw new Error('Backtest speed must be positive or null'); - } - } - - assertRunning(): void { - if (!this.running) { - throw new BacktestCancelledError(); - } - this.controller.signal.throwIfAborted(); - } - - get signal(): AbortSignal { - return this.controller.signal; - } - - /** Only race side-effect-free reads; late reads must never resume execution. */ - async read(load: () => Promise): Promise { - this.assertRunning(); - const { signal } = this.controller; - signal.throwIfAborted(); - let rejectAbort!: (reason: unknown) => void; - const aborted = new Promise((_resolve, reject) => { - rejectAbort = reject; - }); - const onAbort = () => rejectAbort(signal.reason); - signal.addEventListener('abort', onAbort, { once: true }); - try { - const work = Promise.resolve().then(() => { - this.assertRunning(); - return load(); - }); - return await Promise.race([work, aborted]); - } finally { - signal.removeEventListener('abort', onAbort); - } - } - - private async wait(ms?: number): Promise { - this.assertRunning(); - await new Promise(resolve => { - let timer: ReturnType | undefined; - const done = () => { - if (timer !== undefined) { - clearTimeout(timer); - } - this.wake = undefined; - resolve(); - }; - this.wake = done; - if (ms !== undefined) { - timer = setTimeout(done, ms); - } - }); - this.assertRunning(); - } - - private async ready(): Promise { - this.assertRunning(); - while (this.paused) { - await this.wait(); - } - } - - async process( - events: readonly T[], - timestamp: (event: T) => number, - consume: (event: T) => Promise, - progress: (value: PlaybackProgress) => void - ): Promise { - this.assertRunning(); - if (this.started) { - throw new Error('Backtest playback has already started'); - } - this.started = true; - this.total = events.length; - // Frozen inputs are already validated and ordered. A cursor avoids copying and shifting history. - for (const event of events) { - await this.ready(); - if (this.speed !== null) { - await this.wait(1000 / this.speed); - } - await this.ready(); - this.currentTime = timestamp(event); - await consume(event); - this.processed++; - this.assertRunning(); - const interval = this.speed === null ? 100 : Math.max(1, Math.floor(10 / this.speed)); - if (this.processed < this.total && this.processed % interval === 0) { - progress(this.progress()); - } - // Let cancellation, lease heartbeats and other accounts run even at unlimited speed. - if (this.speed === null && this.processed % 100 === 0) { - await this.wait(0); - } - } - this.assertRunning(); - progress(this.progress()); - this.assertRunning(); - } - - private progress(): PlaybackProgress { - return { - processed: this.processed, - total: this.total, - remaining: this.total - this.processed, - currentTime: new Date(this.currentTime), - currentDate: new Date(this.currentTime).toISOString(), - progress: - this.total > 0 - ? this.processed === this.total - ? 100 - : Math.min(99, Math.round((this.processed / this.total) * 100)) - : 0, - }; - } - - pause(): void { - if (!this.running) { - return; - } - this.paused = true; - this.wake?.(); - } - resume(): void { - this.paused = false; - this.wake?.(); - } - stop(): void { - this.controller.abort(new BacktestCancelledError()); - this.paused = false; - this.wake?.(); - } - finish(): void { - this.running = false; - this.paused = false; - this.wake?.(); - } - setSpeed(speed: number | null): void { - this.validateSpeed(speed); - this.speed = speed; - this.wake?.(); - } - getStatus() { - return { - isRunning: this.running, - isPaused: this.paused, - progress: this.progress().progress, - currentTime: this.currentTime, - }; - } -} diff --git a/apps/stock/orchestrator/src/backtest/BacktestReport.ts b/apps/stock/orchestrator/src/backtest/BacktestReport.ts deleted file mode 100644 index 988d6131..00000000 --- a/apps/stock/orchestrator/src/backtest/BacktestReport.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { at, defined } from '@stock-bot/invariants'; -import type { HistoricalDataset } from '@stock-bot/types'; -import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; -import type { BacktestConfig } from '../types'; -import type { ClosedTrade } from './native-result'; -import { formatReport, type ReportExport } from './report-format'; -import type { BacktestResult, OHLCBar } from './typescript-result'; - -/** Run-local observations and a detached completed report; never reads services or financial state. */ -export class BacktestReport { - private readonly equityCurve: { timestamp: number; value: number }[]; - private performanceAnalyzer?: PerformanceAnalyzer; - private snapshot?: ReportExport; - private readonly config: BacktestConfig; - - constructor( - config: BacktestConfig, - private readonly backtestId: string - ) { - this.config = structuredClone(config); - const start = Date.parse(config.startDate); - this.equityCurve = [{ timestamp: start, value: config.initialCapital }]; - this.performanceAnalyzer = new PerformanceAnalyzer(config.initialCapital); - this.performanceAnalyzer.addEquityPoint(new Date(start), config.initialCapital); - } - - record(timestamp: number, equity: number): void { - if (this.snapshot) { - throw new Error('Backtest report is already finalized'); - } - if (!Number.isFinite(timestamp) || !Number.isFinite(equity)) { - throw new Error('Invalid backtest equity observation'); - } - const last = defined(this.equityCurve[this.equityCurve.length - 1]); - if (timestamp < last.timestamp) { - throw new Error('Out-of-order backtest equity observation'); - } - defined(this.performanceAnalyzer).addEquityPoint(new Date(timestamp), equity); - if (last.timestamp === timestamp) { - last.value = equity; - } else { - this.equityCurve.push({ timestamp, value: equity }); - } - } - - complete( - dataset: HistoricalDataset, - trades: ClosedTrade[], - finalPositions: BacktestResult['positions'], - dataQuality: unknown, - completedAt = new Date().toISOString() - ): BacktestResult { - if (this.snapshot) { - throw new Error('Backtest report is already finalized'); - } - const closedTrades = structuredClone(trades); - const performance = this.calculatePerformance(closedTrades); - const analysis = defined(this.performanceAnalyzer).getAnalysis(); - const result: BacktestResult = { - // Identification - backtestId: this.backtestId, - status: 'completed' as const, - completedAt, - - // Configuration used - config: { - name: this.config.name || 'Backtest', - strategy: this.config.strategy, - symbols: this.config.symbols, - startDate: this.config.startDate, - endDate: this.config.endDate, - initialCapital: this.config.initialCapital, - commission: this.config.commission ?? 0.001, - slippage: this.config.slippage ?? 0.0001, - dataFrequency: this.config.dataFrequency || '1d', - }, - - // Performance metrics (frontend-ready) - metrics: { - totalReturn: performance.totalReturn, - sharpeRatio: performance.sharpeRatio, - maxDrawdown: performance.maxDrawdown, - winRate: performance.winRate, - totalTrades: performance.totalTrades, - profitFactor: performance.profitFactor, - profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100), - avgWin: performance.avgWin || 0, - avgLoss: performance.avgLoss || 0, - expectancy: performance.expectancy || 0, - calmarRatio: performance.calmarRatio, - sortinoRatio: performance.sortinoRatio, - annualizedReturn: performance.annualizedReturn, - cagr: performance.cagr, - }, - - // Chart data (frontend-ready format) - equity: this.equityCurve.map(point => ({ - date: new Date(point.timestamp).toISOString(), - value: point.value, - })), - - // OHLC data for charts - ohlcData: this.getOHLCData(dataset), - - // Trade history (frontend-ready) - trades: closedTrades.map(trade => ({ - id: trade.id, - symbol: trade.symbol, - entryDate: trade.entry_time, - exitDate: trade.exit_time, - entryPrice: trade.entry_price, - exitPrice: trade.exit_price, - quantity: trade.quantity, - side: trade.side === 'Buy' ? 'buy' : 'sell', - pnl: trade.pnl, - pnlPercent: trade.pnl_percent, - commission: trade.commission, - duration: trade.duration_ms, - })), - - // Final positions - positions: finalPositions.map(pos => ({ - symbol: pos.symbol, - quantity: pos.quantity, - averagePrice: pos.averagePrice, - currentPrice: pos.currentPrice || pos.averagePrice, - unrealizedPnl: pos.unrealizedPnl || 0, - realizedPnl: pos.realizedPnl || 0, - })), - - // Additional analytics - analytics: { - drawdownSeries: analysis.equity.underwater.map(point => ({ - ...point, - value: point.value * 100, - })), - dailyReturns: analysis.equity.dailyReturns.map(value => value * 100), - monthlyReturns: Object.fromEntries( - Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [ - month, - value * 100, - ]) - ), - exposureTime: this.calculateExposureTime(closedTrades), - riskMetrics: { - volatility: analysis.risk.volatility, - downsideDeviation: analysis.risk.downsideDeviation, - var95: analysis.risk.var95, - var99: analysis.risk.var99, - cvar95: analysis.risk.cvar95, - maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses, - }, - }, - }; - - this.snapshot = structuredClone({ - summary: performance, - trades: closedTrades, - equityCurve: this.equityCurve, - drawdowns: result.analytics.drawdownSeries, - dataQuality, - performanceReport: defined(this.performanceAnalyzer).exportReport(performance), - }); - // The completed snapshot is sufficient for export; do not retain the analysis input twice. - this.equityCurve.length = 0; - this.performanceAnalyzer = undefined; - return structuredClone(result); - } - - export(format: 'json' | 'csv' | 'html' = 'json'): string { - if (!this.snapshot) { - throw new Error('No completed backtest report is available'); - } - return formatReport(this.snapshot, format); - } - - private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics { - const analyzer = defined(this.performanceAnalyzer); - // Import each closed trade once, when the completed snapshot is built. - closedTrades.forEach(trade => { - analyzer.addTrade({ - entryTime: new Date(trade.entry_time), - exitTime: new Date(trade.exit_time), - symbol: trade.symbol, - side: trade.side === 'Buy' ? 'long' : 'short', - entryPrice: trade.entry_price, - exitPrice: trade.exit_price, - quantity: trade.quantity, - commission: trade.commission || 0, - pnl: trade.pnl || 0, - returnPct: trade.pnl_percent || 0, - holdingPeriod: trade.duration_ms / 60000, // Convert to minutes - mae: 0, // Not tracked yet - mfe: 0, // Not tracked yet - }); - }); - - return analyzer.analyze(); - } - - private calculateExposureTime(closedTrades: ClosedTrade[] = []): number { - if (closedTrades.length === 0) { - return 0; - } - - let totalExposureTime = 0; - for (const trade of closedTrades) { - totalExposureTime += trade.duration_ms || 0; - } - - // Use equity curve to determine actual trading period - const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0; - const endTime = - this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0; - const totalTime = endTime - startTime; - - return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0; - } - - private getOHLCData(dataset: HistoricalDataset): Record { - const grouped: Record = Object.fromEntries( - this.config.symbols.map(symbol => [symbol, []]) - ); - for (const bar of dataset.bars) { - const { timestamp, open, high, low, close, volume } = bar; - defined(grouped[bar.symbol]).push({ timestamp, open, high, low, close, volume }); - } - return grouped; - } -} diff --git a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts deleted file mode 100644 index 8437e351..00000000 --- a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts +++ /dev/null @@ -1,423 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/invariants'; -import { - type Bar, - type MarketData, - type OrderBookSnapshot, - type PriceLevel, - type Quote, - type Trade, -} from '../types'; -import { type MarketMicrostructure } from '../types/MarketMicrostructure'; - -const _logger = getLogger('MarketSimulator'); - -export interface SimulationConfig { - useHistoricalSpreads: boolean; - modelHiddenLiquidity: boolean; - includeDarkPools: boolean; - latencyMs: number; - rebateRate: number; - takeFeeRate: number; -} - -export interface LiquidityProfile { - visibleLiquidity: number; - hiddenLiquidity: number; - darkPoolLiquidity: number; - totalLiquidity: number; -} - -export class MarketSimulator { - private orderBooks: Map = new Map(); - private microstructures: Map = new Map(); - private liquidityProfiles: Map = new Map(); - private lastTrades: Map = new Map(); - private config: SimulationConfig; - private randomState = 1; - - resetWithSeed(seed: number): void { - this.randomState = seed >>> 0; - this.orderBooks.clear(); - this.microstructures.clear(); - this.liquidityProfiles.clear(); - this.lastTrades.clear(); - } - - private random(): number { - this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0; - return this.randomState / 4294967296; - } - - constructor(config: Partial = {}) { - this.config = { - useHistoricalSpreads: true, - modelHiddenLiquidity: true, - includeDarkPools: true, - latencyMs: 1, - rebateRate: -0.0002, // 2 bps rebate for providing liquidity - takeFeeRate: 0.0003, // 3 bps fee for taking liquidity - ...config, - }; - } - - setMicrostructure(symbol: string, microstructure: MarketMicrostructure): void { - this.microstructures.set(symbol, microstructure); - this.updateLiquidityProfile(symbol); - } - - processMarketData(data: MarketData): OrderBookSnapshot | null { - const { symbol } = this.getSymbolFromData(data); - - switch (data.type) { - case 'quote': - return this.updateFromQuote(symbol, data.data); - case 'trade': - return this.updateFromTrade(symbol, data.data); - case 'bar': - return this.reconstructFromBar(symbol, data.data); - default: - return null; - } - } - - private updateFromQuote(symbol: string, quote: Quote): OrderBookSnapshot { - let orderbook = this.orderBooks.get(symbol); - const microstructure = this.microstructures.get(symbol); - - if (!orderbook || !microstructure) { - // Create new orderbook - orderbook = this.createOrderBook(symbol, quote, microstructure); - } else { - // Update existing orderbook - orderbook = this.updateOrderBook(orderbook, quote, microstructure); - } - - this.orderBooks.set(symbol, orderbook); - return orderbook; - } - - private updateFromTrade(symbol: string, trade: Trade): OrderBookSnapshot | null { - const orderbook = this.orderBooks.get(symbol); - if (!orderbook) { - return null; - } - - // Update last trade - this.lastTrades.set(symbol, trade); - - // Adjust orderbook based on trade - // Large trades likely consumed liquidity - const impactFactor = Math.min(trade.size / 1000, 0.1); // Max 10% impact - - if (trade.side === 'buy') { - // Buy trade consumed ask liquidity - orderbook.asks = orderbook.asks.map((level, i) => ({ - ...level, - size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)), - })); - } else { - // Sell trade consumed bid liquidity - orderbook.bids = orderbook.bids.map((level, i) => ({ - ...level, - size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)), - })); - } - - return orderbook; - } - - private reconstructFromBar(symbol: string, bar: Bar): OrderBookSnapshot { - const microstructure = - this.microstructures.get(symbol) || this.createDefaultMicrostructure(symbol); - - // Estimate spread from high-low range - const hlSpread = (bar.high - bar.low) / bar.close; - const estimatedSpreadBps = Math.max( - microstructure.avgSpreadBps, - hlSpread * 10000 * 0.1 // 10% of HL range as spread estimate - ); - - // Create synthetic quote - const midPrice = bar.vwap || (bar.high + bar.low + bar.close) / 3; - const halfSpread = (midPrice * estimatedSpreadBps) / 20000; - - const quote: Quote = { - symbol, - timestamp: bar.timestamp, - bid: midPrice - halfSpread, - ask: midPrice + halfSpread, - bidSize: bar.volume / 100, // Rough estimate - askSize: bar.volume / 100, - }; - - return this.createOrderBook(symbol, quote, microstructure); - } - - private createOrderBook( - symbol: string, - topQuote: Quote, - microstructure?: MarketMicrostructure - ): OrderBookSnapshot { - const micro = microstructure || this.createDefaultMicrostructure(symbol); - const levels = 10; - - const bids: PriceLevel[] = []; - const asks: PriceLevel[] = []; - - // Model order book depth - for (let i = 0; i < levels; i++) { - const depthFactor = Math.exp(-i * 0.3); // Exponential decay - const _spreadMultiplier = 1 + i * 0.1; // Wider spread at deeper levels - - // Hidden liquidity modeling - const hiddenRatio = this.config.modelHiddenLiquidity - ? 1 + this.random() * 2 // 1-3x visible size hidden - : 1; - - // Bid levels - const bidPrice = topQuote.bid - i * micro.tickSize; - const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4); - bids.push({ - price: bidPrice, - size: Math.round(bidSize / micro.lotSize) * micro.lotSize, - orderCount: Math.max(1, Math.floor(bidSize / 100)), - hiddenSize: this.config.modelHiddenLiquidity ? bidSize * (hiddenRatio - 1) : undefined, - }); - - // Ask levels - const askPrice = topQuote.ask + i * micro.tickSize; - const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4); - asks.push({ - price: askPrice, - size: Math.round(askSize / micro.lotSize) * micro.lotSize, - orderCount: Math.max(1, Math.floor(askSize / 100)), - hiddenSize: this.config.modelHiddenLiquidity ? askSize * (hiddenRatio - 1) : undefined, - }); - } - - return { - symbol, - timestamp: new Date(), - bids, - asks, - lastTrade: this.lastTrades.get(symbol), - }; - } - - private updateOrderBook( - current: OrderBookSnapshot, - quote: Quote, - microstructure?: MarketMicrostructure - ): OrderBookSnapshot { - const _micro = microstructure || this.createDefaultMicrostructure(current.symbol); - - // Update top of book - if (current.bids.length > 0) { - at(current.bids, 0).price = quote.bid; - at(current.bids, 0).size = quote.bidSize; - } - - if (current.asks.length > 0) { - at(current.asks, 0).price = quote.ask; - at(current.asks, 0).size = quote.askSize; - } - - // Adjust deeper levels based on spread changes - const oldSpread = at(current.asks, 0).price - at(current.bids, 0).price; - const newSpread = quote.ask - quote.bid; - const spreadRatio = newSpread / oldSpread; - - // Update deeper levels - for (let i = 1; i < current.bids.length; i++) { - // Adjust sizes based on top of book changes - const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize); - at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2); - - // Adjust prices to maintain relative spacing - const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio; - at(current.bids, i).price = at(current.bids, i - 1).price - spacing; - } - - for (let i = 1; i < current.asks.length; i++) { - const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize); - at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2); - - const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio; - at(current.asks, i).price = at(current.asks, i - 1).price + spacing; - } - - return current; - } - - simulateMarketImpact( - symbol: string, - side: 'buy' | 'sell', - orderSize: number, - orderType: 'market' | 'limit', - limitPrice?: number - ): { - fills: Array<{ price: number; size: number; venue: string }>; - totalCost: number; - avgPrice: number; - marketImpact: number; - fees: number; - } { - const orderbook = this.orderBooks.get(symbol); - const microstructure = this.microstructures.get(symbol); - const liquidityProfile = this.liquidityProfiles.get(symbol); - - if (!orderbook) { - throw new Error(`No orderbook available for ${symbol}`); - } - - const fills: Array<{ price: number; size: number; venue: string }> = []; - let remainingSize = orderSize; - let totalCost = 0; - let fees = 0; - - // Get relevant price levels - const levels = side === 'buy' ? orderbook.asks : orderbook.bids; - const multiplier = side === 'buy' ? 1 : -1; - - // Simulate walking the book - for (const level of levels) { - if (remainingSize <= 0) { - break; - } - - // Check limit price constraint - if (limitPrice !== undefined) { - if (side === 'buy' && level.price > limitPrice) { - break; - } - if (side === 'sell' && level.price < limitPrice) { - break; - } - } - - // Calculate available liquidity including hidden - let availableSize = level.size; - if (level.hiddenSize && this.config.modelHiddenLiquidity) { - availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity - } - - const fillSize = Math.min(remainingSize, availableSize); - - // Simulate latency - price might move - if (this.config.latencyMs > 0 && orderType === 'market') { - const priceMovement = microstructure - ? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price - : 0; - level.price += priceMovement * multiplier; - } - - fills.push({ - price: level.price, - size: fillSize, - venue: 'primary', - }); - - totalCost += fillSize * level.price; - remainingSize -= fillSize; - - // Calculate fees - if (orderType === 'market') { - fees += fillSize * level.price * this.config.takeFeeRate; - } else { - // Limit orders that provide liquidity get rebate - fees += fillSize * level.price * this.config.rebateRate; - } - } - - // Dark pool execution for remaining size - if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) { - const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity; - const darkPoolSize = remainingSize * darkPoolPct * this.random(); - - if (darkPoolSize > 0) { - const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2; - fills.push({ - price: midPrice, - size: darkPoolSize, - venue: 'dark', - }); - - totalCost += darkPoolSize * midPrice; - remainingSize -= darkPoolSize; - // Dark pools typically have lower fees - fees += darkPoolSize * midPrice * 0.0001; - } - } - - // Calculate results - const filledSize = orderSize - remainingSize; - const avgPrice = filledSize > 0 ? totalCost / filledSize : 0; - - // Calculate market impact - const initialMid = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2; - const marketImpact = - filledSize > 0 - ? (Math.abs(avgPrice - initialMid) / initialMid) * 10000 // in bps - : 0; - - return { - fills, - totalCost, - avgPrice, - marketImpact, - fees, - }; - } - - private updateLiquidityProfile(symbol: string): void { - const microstructure = this.microstructures.get(symbol); - if (!microstructure) { - return; - } - - // Estimate liquidity distribution - const visiblePct = 0.3; // 30% visible - const hiddenPct = 0.5; // 50% hidden - const darkPct = 0.2; // 20% dark - - const totalDailyLiquidity = microstructure.dailyVolume; - - this.liquidityProfiles.set(symbol, { - visibleLiquidity: totalDailyLiquidity * visiblePct, - hiddenLiquidity: totalDailyLiquidity * hiddenPct, - darkPoolLiquidity: totalDailyLiquidity * darkPct, - totalLiquidity: totalDailyLiquidity, - }); - } - - private createDefaultMicrostructure(symbol: string): MarketMicrostructure { - return { - symbol, - avgSpreadBps: 5, - dailyVolume: 1000000, - avgTradeSize: 100, - volatility: 0.02, - tickSize: 0.01, - lotSize: 1, - intradayVolumeProfile: new Array(24).fill(1 / 24), - }; - } - - private getSymbolFromData(data: MarketData): { symbol: string } { - return { symbol: data.data.symbol }; - } - - getOrderBook(symbol: string): OrderBookSnapshot | undefined { - return this.orderBooks.get(symbol); - } - - getLiquidityProfile(symbol: string): LiquidityProfile | undefined { - return this.liquidityProfiles.get(symbol); - } - - reset(): void { - this.orderBooks.clear(); - this.lastTrades.clear(); - } -} diff --git a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts index 59fe006e..06acb7cb 100644 --- a/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts +++ b/apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts @@ -9,13 +9,13 @@ import { replayConfigSchema, replayIdentitySchema, replayResultFormatSchema, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { parseStrategyReplayResult, strategyReplayRequestSchema, } from '../contracts/strategy-replay'; import { removeCandidateContainer } from './candidate-sandbox'; -import { canonicalWorkerUrl } from './canonical-build'; +import { canonicalWorkerUrl } from '@stock-bot/trading-runtime/canonical-build'; import { nativeWorkerMessageSchema, nativeWorkerRequestSchema, diff --git a/apps/stock/orchestrator/src/backtest/candidate-host.ts b/apps/stock/orchestrator/src/backtest/candidate-host.ts index 0b4342cb..c6e96822 100644 --- a/apps/stock/orchestrator/src/backtest/candidate-host.ts +++ b/apps/stock/orchestrator/src/backtest/candidate-host.ts @@ -1,5 +1,5 @@ /** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */ -import { sameIdentity } from '../contracts/native-replay'; +import { sameIdentity } from '@stock-bot/stock-config/canonical-replay'; import { importRetainedProgram } from '../strategies/retained-program'; import { StrategyController } from '../strategies/strategy-controller'; import { freeze } from '../strategies/strategy-decision'; diff --git a/apps/stock/orchestrator/src/backtest/candidate-protocol.ts b/apps/stock/orchestrator/src/backtest/candidate-protocol.ts index ed7203f5..aadfbafd 100644 --- a/apps/stock/orchestrator/src/backtest/candidate-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/candidate-protocol.ts @@ -6,7 +6,7 @@ import { retainedProgramSelectionSchema, } from '@stock-bot/stock-config/candidate-execution'; import { parseFinancialStrategyDecision } from '@stock-bot/types'; -import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay'; +import { replayIdentitySchema, stepSchema, submissionSchema } from '@stock-bot/stock-config/canonical-replay'; const base = { version: z.literal(1), diff --git a/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts index bb609012..6295a391 100644 --- a/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts +++ b/apps/stock/orchestrator/src/backtest/candidate-sandbox.ts @@ -17,7 +17,7 @@ import { verifyCandidateExecution, } from '@stock-bot/trading-runtime/candidate-environment'; import { parseFinancialStrategyDecision } from '@stock-bot/types'; -import type { ReplaySubmissionOutcome } from '../contracts/native-replay'; +import type { ReplaySubmissionOutcome } from '@stock-bot/stock-config/canonical-replay'; import { candidateResponseSchema, readCandidateFrames, diff --git a/apps/stock/orchestrator/src/backtest/canonical-build.ts b/apps/stock/orchestrator/src/backtest/canonical-build.ts deleted file mode 100644 index 616b9e8a..00000000 --- a/apps/stock/orchestrator/src/backtest/canonical-build.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Shared read-only artifact inspection. */ -export * from '@stock-bot/trading-runtime/canonical-build'; diff --git a/apps/stock/orchestrator/src/backtest/canonical-result.ts b/apps/stock/orchestrator/src/backtest/canonical-result.ts deleted file mode 100644 index 4f11f3ce..00000000 --- a/apps/stock/orchestrator/src/backtest/canonical-result.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint for the shared, purely statistical report builder. */ -export * from '@stock-bot/research/results'; diff --git a/apps/stock/orchestrator/src/backtest/execution-engine.ts b/apps/stock/orchestrator/src/backtest/execution-engine.ts index 8d31cce5..581a411a 100644 --- a/apps/stock/orchestrator/src/backtest/execution-engine.ts +++ b/apps/stock/orchestrator/src/backtest/execution-engine.ts @@ -4,10 +4,6 @@ import type { CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetV2 } from '@stock-bot/types'; -import type { DatasetResolver } from '../data/historical-dataset'; -import type { BacktestConfig } from '../types'; -import type { NativeBacktestResult } from './native-result'; -import type { BacktestResult } from './typescript-result'; /** Capabilities required by the canonical durable runner. No provider loading or playback. */ export interface BacktestExecutionEngine extends Pick { @@ -26,18 +22,6 @@ export interface BacktestExecutionEngine extends Pick; } -/** Retained algorithm/playback examples only; cannot satisfy the durable runner contract. */ -export interface LegacyBacktestExecutionEngine - extends Pick { - runBacktest( - config: BacktestConfig, - dataset?: DatasetResolver - ): Promise; - pauseBacktest(): Promise; - resumeBacktest(): Promise; - setSpeedMultiplier(speed: number | null): void; -} - /** Cancellation has no result when a native worker is forcibly stopped. */ export class BacktestCancelledError extends Error { constructor() { diff --git a/apps/stock/orchestrator/src/backtest/native-replay.ts b/apps/stock/orchestrator/src/backtest/native-replay.ts index 5e368ccf..3deba790 100644 --- a/apps/stock/orchestrator/src/backtest/native-replay.ts +++ b/apps/stock/orchestrator/src/backtest/native-replay.ts @@ -32,7 +32,7 @@ import { type ReplayStep, type ReplaySubmissionOutcome, type ReplayTraceRequest, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { validateDatasetV2 } from '../data/historical-dataset-v2'; export type { @@ -47,7 +47,7 @@ export type { DecisionContext, PublishedObservation, ReplayTraceRequest, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; /** Expand Number's exact shortest lexical representation, never round toFixed. * D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */ diff --git a/apps/stock/orchestrator/src/backtest/native-strategies.ts b/apps/stock/orchestrator/src/backtest/native-strategies.ts deleted file mode 100644 index dcf91287..00000000 --- a/apps/stock/orchestrator/src/backtest/native-strategies.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { BacktestConfig } from '../types'; -import { backtestStrategies } from './strategy-plan'; - -/** Resolve and validate before fetching data, and validate again in the isolated worker. */ -export function resolveNativeStrategies(config: BacktestConfig) { - return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => { - if (!kind) { - throw new Error('Unknown native strategy: ' + name); - } - return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters }; - }); -} diff --git a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts index de8e4e7d..87b08665 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker-protocol.ts @@ -12,10 +12,10 @@ import { } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { CanonicalBacktestAnalytics } from '@stock-bot/types'; -import { replayTraceSchema } from '../contracts/native-replay'; -import type { ReplayReportResult } from '../contracts/native-replay'; +import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay'; +import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay'; import { strategyReplayRequestSchema } from '../contracts/strategy-replay'; -import { buildCanonicalBacktestReport } from './canonical-result'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; const finite = z.number().finite(); export const retainedStrategyRequestSchema = z diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index 21c4376b..edcdee3b 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -8,8 +8,8 @@ import { verifyRetainedProgramPackage, } from '../strategies/retained-program'; import { IsolatedCandidateController } from './candidate-sandbox'; -import { verifyCanonicalWorkerBuild } from './canonical-build'; -import { buildCanonicalBacktestReport } from './canonical-result'; +import { verifyCanonicalWorkerBuild } from '@stock-bot/trading-runtime/canonical-build'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import { executeReplayTrace, NativeReplaySession, diff --git a/apps/stock/orchestrator/src/backtest/report-format.ts b/apps/stock/orchestrator/src/backtest/report-format.ts deleted file mode 100644 index f2401a93..00000000 --- a/apps/stock/orchestrator/src/backtest/report-format.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { formatStatistic } from '@stock-bot/calculations/analytics'; -import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; -import type { ClosedTrade } from './native-result'; - -export interface ReportExport { - summary: PerformanceMetrics; - trades: ClosedTrade[]; - equityCurve: { timestamp: number; value: number }[]; - drawdowns: { timestamp: number; value: number }[]; - dataQuality: unknown; - performanceReport: string; -} - -export function formatReport(result: ReportExport, format: 'json' | 'csv' | 'html'): string { - switch (format) { - case 'json': - return JSON.stringify(result, null, 2); - case 'csv': - return convertToCSV(result); - case 'html': - return generateHTMLReport(result); - default: - throw new Error(`Unsupported backtest export format: ${format}`); - } -} - -function csvCell(value: string | number): string { - let text = String(value); - // Text is not a spreadsheet formula; numeric losses remain ordinary numbers. - if (typeof value === 'string' && /^[=+\-@\t\r]/.test(text)) { - text = "'" + text; - } - return /[",\r\n]/.test(text) ? '"' + text.replaceAll('"', '""') + '"' : text; -} - -function escapeHTML(value: string): string { - return value.replace( - /[&<>"']/g, - char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char - ); -} - -export function convertToCSV(result: ReportExport): string { - // Simple CSV conversion for trades - const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%']; - const rows = result.trades.map(t => [ - new Date(String(t.entry_time)).toISOString(), - t.symbol, - t.side === 'Buy' ? 'buy' : 'sell', - t.entry_price, - t.exit_price, - t.quantity, - t.pnl, - t.pnl_percent, - ]); - - return [headers, ...rows].map(row => row.map(csvCell).join(',')).join('\n'); -} - -export function generateHTMLReport(result: ReportExport): string { - return ` - - - - Backtest Report - - - -

Backtest Performance Report

- -

Summary Statistics

-
Total Return: ${result.summary.totalReturn.toFixed(2)}%
-
Sharpe Ratio: ${formatStatistic(result.summary.sharpeRatio)}
-
Max Drawdown: ${(result.summary.maxDrawdown * 100).toFixed(2)}%
-
Win Rate: ${result.summary.winRate.toFixed(1)}%
-
Total Trades: ${result.summary.totalTrades}
- -

Detailed Performance Metrics

-
${escapeHTML(result.performanceReport)}
- -

Trade History

- - - - - - - - - - - - ${result.trades - .map( - t => ` - - - - - - - - - - - ` - ) - .join('')} -
DateSymbolSideEntry PriceExit PriceQuantityP&LReturn %
${new Date(t.entry_time).toISOString().slice(0, 10)}${escapeHTML(t.symbol)}${t.side}$${t.entry_price.toFixed(2)}$${t.exit_price.toFixed(2)}${t.quantity}$${t.pnl.toFixed(2)}${t.pnl_percent.toFixed(2)}%
- - - `; -} diff --git a/apps/stock/orchestrator/src/backtest/result.ts b/apps/stock/orchestrator/src/backtest/result.ts deleted file mode 100644 index 4af65fc5..00000000 --- a/apps/stock/orchestrator/src/backtest/result.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { z } from 'zod'; -import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types'; -import { datasetManifestSchema } from '../contracts/historical'; -import type { BacktestConfig } from '../types'; -import type { NativeBacktestResult } from './native-result'; -import type { RunIdentity } from './run-repository'; -import type { BacktestResult as TypeScriptResult } from './typescript-result'; - -const finite = z.number().finite(); -const analyticsSchema = z.object({ - exposureTime: finite, - drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(), - dailyReturns: z.array(finite).optional(), - monthlyReturns: z.record(finite).optional(), - riskMetrics: z.record(finite.nullable()).optional(), -}); -/** Validate once before persistence and before publishing a terminal result. */ -export const backtestRunResultSchema: z.ZodType = z.object({ - runId: z.string().uuid(), - backtestId: z.string().uuid(), - engine: z.enum(['native', 'typescript']), - status: z.enum(['completed', 'cancelled']), - completedAt: z.string().datetime(), - config: z.object({ - name: z.string(), - strategy: z.string(), - symbols: z.array(z.string()), - startDate: z.string().datetime(), - endDate: z.string().datetime(), - initialCapital: finite, - commission: finite, - slippage: finite, - dataFrequency: z.string(), - parameters: z.record(z.unknown()), - dataset: datasetManifestSchema.optional(), - riskLimits: z - .object({ - maxPositionSize: finite, - maxOrderSize: finite, - maxDailyLoss: finite, - maxGrossExposure: finite, - maxSymbolExposure: finite, - }) - .optional(), - strategies: z - .array( - z.object({ - name: z.string(), - enabled: z.boolean(), - config: z.record(z.unknown()).optional(), - }) - ) - .optional(), - }), - metrics: z - .object({ - totalReturn: finite, - sharpeRatio: finite.nullable(), - maxDrawdown: finite, - winRate: finite, - totalTrades: finite, - profitFactor: finite.nullable(), - avgWin: finite, - avgLoss: finite, - }) - .catchall(finite.nullable()), - equity: z.array(z.object({ date: z.string(), value: finite })), - ohlcData: z.record( - z.array( - z.object({ - timestamp: finite, - open: finite, - high: finite, - low: finite, - close: finite, - volume: finite.optional(), - }) - ) - ), - trades: z.array( - z.object({ - kind: z.enum(['fill', 'closed']), - id: z.string(), - symbol: z.string(), - timestamp: z.string(), - side: z.enum(['buy', 'sell']), - price: finite, - quantity: finite, - commission: finite, - pnl: finite.optional(), - positionAfter: finite.optional(), - entryDate: z.string().optional(), - exitDate: z.string().nullable().optional(), - entryPrice: finite.optional(), - exitPrice: finite.optional(), - pnlPercent: finite.optional(), - duration: finite.optional(), - }) - ), - positions: z.array( - z.object({ - symbol: z.string(), - quantity: finite, - averagePrice: finite, - currentPrice: finite, - unrealizedPnl: finite, - realizedPnl: finite, - }) - ), - analytics: analyticsSchema, - executionTime: finite.nonnegative(), -}); - -export function normalizeBacktestResult( - raw: NativeBacktestResult | TypeScriptResult, - engine: Exclude, - config: BacktestConfig, - identity: RunIdentity, - executionTime: number, - cancelled: boolean, - dataset?: HistoricalDatasetManifest -): BacktestRunResult { - if (raw.status !== 'completed' && raw.status !== 'cancelled') { - throw new Error( - 'error' in raw && typeof raw.error === 'string' - ? raw.error - : `Backtest engine returned ${raw.status}` - ); - } - const trades = raw.trades.map(trade => - 'entryDate' in trade - ? { - ...trade, - kind: 'closed', - timestamp: trade.entryDate, - price: trade.entryPrice, - } - : { ...trade, kind: 'fill' } - ); - // Native serialization uses null for undefined ratios; do the same for TS infinities. - const metrics = Object.fromEntries( - Object.entries(raw.metrics).map(([key, value]) => [ - key, - typeof value === 'number' && !Number.isFinite(value) ? null : value, - ]) - ); - // Public returns/win rates are fractions, not percentage points. Both backends - // already report maxDrawdown as a fraction. - metrics.totalReturn = raw.metrics.totalReturn / 100; - metrics.winRate = raw.metrics.winRate / 100; - if (engine === 'typescript') { - metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills. - metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length; - } - for (const key of ['annualReturn', 'annualizedReturn', 'cagr']) { - if (typeof metrics[key] === 'number') { - metrics[key] /= 100; - } - } - const analytics = analyticsSchema.parse(raw.analytics); - analytics.exposureTime /= 100; - analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({ - ...point, - value: point.value / 100, - })); - analytics.dailyReturns = analytics.dailyReturns?.map(value => - engine === 'typescript' ? value / 100 : value - ); - if (analytics.monthlyReturns) { - analytics.monthlyReturns = Object.fromEntries( - Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100]) - ); - } - return backtestRunResultSchema.parse({ - ...raw, - ...identity, - engine, - completedAt: new Date(raw.completedAt).toISOString(), - status: cancelled ? 'cancelled' : raw.status, - executionTime, - config: { - name: config.name ?? 'Backtest', - strategy: config.strategy, - symbols: config.symbols, - startDate: config.startDate, - endDate: config.endDate, - initialCapital: config.initialCapital, - commission: config.commission ?? 0.001, - slippage: config.slippage ?? 0.0001, - dataFrequency: config.dataFrequency, - parameters: config.config ?? {}, - dataset, - riskLimits: config.riskLimits, - strategies: config.strategies, - }, - metrics, - trades, - analytics, - }); -} diff --git a/apps/stock/orchestrator/src/backtest/strategy-plan.ts b/apps/stock/orchestrator/src/backtest/strategy-plan.ts deleted file mode 100644 index f8607ac8..00000000 --- a/apps/stock/orchestrator/src/backtest/strategy-plan.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { normalizeBacktestStrategyConfig } from '@stock-bot/stock-config/backtest'; -import { - nativeParameters, - typescriptMeanReversionParameters, - typescriptSmaParameters, -} from '../contracts/strategies'; -import { builtinStrategy } from '../contracts/strategy-names'; -import type { BacktestConfig } from '../types'; - -/** One precedence rule for both backends: shared defaults, then per-strategy overrides. */ -export function backtestStrategies(config: BacktestConfig, backend: 'native' | 'typescript') { - const entries = config.strategies ?? [{ name: config.strategy, enabled: true, config: {} }]; - if (!entries.some(entry => entry.enabled)) { - throw new Error('No enabled backtest strategies'); - } - return entries - .filter(entry => entry.enabled) - .map((entry, index) => { - const kind = builtinStrategy(entry.name); - const merged = { ...config.config, ...entry.config }; - // Built-ins cross the shared execution/parameter boundary once, after merging defaults. - // Custom TypeScript factories retain their historical, factory-owned extension contract. - const input = kind - ? normalizeBacktestStrategyConfig(merged) - : { parameters: structuredClone(merged) }; - const { parameters } = input; - if (backend === 'native') { - if (!kind) { - throw new Error(`Unknown native strategy: ${entry.name}`); - } - if (input.useTypeScriptImplementation) { - throw new Error('The native engine does not execute TypeScript strategy callbacks'); - } - const parsed = nativeParameters(kind, parameters); - if ( - kind === 'pairs_trading' && - (typeof parsed.pairA !== 'string' || - typeof parsed.pairB !== 'string' || - !config.symbols.includes(parsed.pairA) || - !config.symbols.includes(parsed.pairB)) - ) { - throw new Error('Both pair instruments must be included in backtest symbols'); - } - return { name: entry.name, kind, index, parameters: parsed }; - } - const context = { ...parameters, initialCapital: config.initialCapital }; - const parsed = - kind === 'sma_crossover' - ? typescriptSmaParameters.parse(context) - : kind === 'mean_reversion' - ? typescriptMeanReversionParameters.parse(context) - : context; - return { name: entry.name, kind, index, parameters: parsed }; - }); -} diff --git a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts index 5d97117a..971f47a3 100644 --- a/apps/stock/orchestrator/src/backtest/strategy-runtime.ts +++ b/apps/stock/orchestrator/src/backtest/strategy-runtime.ts @@ -4,7 +4,7 @@ import type { DeepReadonly, StrategyDiagnosticSnapshot, StrategyProgram, -} from '../contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import { replayConfigSchema, replayIdentitySchema, @@ -12,7 +12,7 @@ import { type ReplayProjectionResult, type ReplayReportResult, type ReplayResult, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { StrategyController } from '../strategies/strategy-controller'; import { freeze } from '../strategies/strategy-decision'; import { @@ -23,7 +23,7 @@ import { type ReplayOptions, } from './native-replay'; -export type { StrategyProgram } from '../contracts/canonical-strategy'; +export type { StrategyProgram } from '@stock-bot/research/strategy-api'; export type StrategyReplayOptions = Omit; type StrategyRun = { result: Result; diff --git a/apps/stock/orchestrator/src/backtest/typescript-result.ts b/apps/stock/orchestrator/src/backtest/typescript-result.ts deleted file mode 100644 index 33c18a16..00000000 --- a/apps/stock/orchestrator/src/backtest/typescript-result.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** Internal TypeScript backend output; normalized to BacktestRunResult by the runner. */ -export interface OHLCBar { - timestamp: number; - open: number; - high: number; - low: number; - close: number; - volume: number; -} - -export interface BacktestResult { - // Identification - backtestId: string; - status: 'completed' | 'failed' | 'cancelled'; - completedAt: string; - - // Configuration - config: { - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - commission: number; - slippage: number; - dataFrequency: string; - }; - - // Performance metrics - metrics: { - totalReturn: number; - sharpeRatio: number | null; - maxDrawdown: number; - winRate: number; - totalTrades: number; - profitFactor: number | null; - profitableTrades: number; - avgWin: number; - avgLoss: number; - expectancy: number; - calmarRatio: number | null; - sortinoRatio: number | null; - annualizedReturn: number | null; - cagr: number | null; - }; - - // Chart data - equity: Array<{ date: string; value: number }>; - ohlcData: Record; - - // Trade history - trades: Array<{ - id: string; - symbol: string; - entryDate: string; - exitDate: string | null; - entryPrice: number; - exitPrice: number; - quantity: number; - side: string; - pnl: number; - pnlPercent: number; - commission: number; - duration: number; - }>; - - // Positions - positions: Array<{ - symbol: string; - quantity: number; - averagePrice: number; - currentPrice: number; - unrealizedPnl: number; - realizedPnl: number; - }>; - - // Analytics - analytics: { - drawdownSeries: { timestamp: number; value: number }[]; - dailyReturns: number[]; - monthlyReturns: Record; - exposureTime: number; - riskMetrics: Record; - }; -} diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 394bcb0f..07c755fd 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -6,14 +6,13 @@ import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRep import { assertResearchConcurrency, ResearchBacktestPool } from './backtest/ResearchBacktestPool'; import { UnavailableBacktestRunRepository } from './backtest/run-repository'; import { RustBacktestAdapter } from './backtest/RustBacktestAdapter'; -import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime'; +import type { PaperConfigurationInput, PaperRuntime } from '@stock-bot/stock-config/paper-runtime'; import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository'; import { BacktestHandler } from './handlers/backtest/backtest.handler'; import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime'; import { validatePaperConfiguration } from './paper/feed'; import { PaperDeploymentHost } from './paper/PaperDeploymentHost'; -import { AnalyticsService } from './services/AnalyticsService'; -import { StorageService } from './services/StorageService'; +import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import { createBuiltinStrategy } from './strategies/canonical-builtins'; import { stopOrchestratorWork } from './runtime'; import type { OrchestratorServices as IServiceContainer } from './types'; @@ -163,12 +162,10 @@ export async function registerOrchestratorServices( ), logger: services.logger, }); - const analytics = new AnalyticsService(services); // Both roles share canonical research. Only an explicitly configured paper // composition owns account custody; startup never activates it. Object.assign(custom, { StorageService: storageService, - AnalyticsService: analytics, BacktestRunner: runner, ...(paper ? { CanonicalPaperRuntime: paper } : {}), ...(deploymentHost ? { PaperDeploymentHost: deploymentHost } : {}), @@ -176,7 +173,6 @@ export async function registerOrchestratorServices( const canonicalContainer = container as AwilixContainer< ServiceDefinitions & { StorageService: StorageService; - AnalyticsService: AnalyticsService; CanonicalPaperRuntime: PaperRuntime; PaperDeploymentHost: PaperDeploymentHost; BacktestRunner: ResearchBacktestPool; @@ -185,7 +181,6 @@ export async function registerOrchestratorServices( >; canonicalContainer.register({ StorageService: asValue(storageService), - AnalyticsService: asValue(analytics), BacktestRunner: asValue(runner), orchestratorServices: asValue(services), ...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}), diff --git a/apps/stock/orchestrator/src/contracts/analytics.ts b/apps/stock/orchestrator/src/contracts/analytics.ts deleted file mode 100644 index d86079c9..00000000 --- a/apps/stock/orchestrator/src/contracts/analytics.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { z } from 'zod'; - -const finite = z.number().finite(); -const optionalRatio = finite.nullable(); -const symbols = z - .array(z.string().trim().min(1).max(128)) - .min(1) - .max(128) - .refine(values => new Set(values).size === values.length, 'Duplicate symbols'); -export const PerformanceMetricsSchema = z.object({ - totalReturn: finite, - sharpeRatio: optionalRatio, - sortinoRatio: optionalRatio, - maxDrawdown: finite.nonnegative(), - winRate: finite.min(0).max(1), - profitFactor: finite.nonnegative().nullable(), - avgWin: finite.nonnegative(), - avgLoss: finite.nonnegative(), - totalTrades: finite.int().nonnegative(), -}); -export type PerformanceMetrics = z.infer; -export const RiskMetricsSchema = z.object({ - currentExposure: finite.nonnegative(), - dailyPnl: finite, - positionCount: finite.int().nonnegative(), - grossExposure: finite.nonnegative(), - var95: finite.nonnegative().nullable().optional(), - cvar95: finite.nonnegative().nullable().optional(), -}); -export type RiskMetrics = z.infer; -export const dateRangeSchema = z - .object({ startDate: z.string().datetime(), endDate: z.string().datetime() }) - .refine( - value => Date.parse(value.endDate) > Date.parse(value.startDate), - 'endDate must follow startDate' - ); -export const optimizationRequestSchema = z - .object({ - symbols, - returns: z.array(z.array(finite).min(1).max(128)).min(2).max(100000), - constraints: z - .object({ - minWeight: finite.min(0).max(1).optional(), - maxWeight: finite.min(0).max(1).optional(), - targetReturn: finite.optional(), - maxRisk: finite.nonnegative().optional(), - }) - .strict() - .optional(), - }) - .strict() - .refine( - value => value.returns.every(row => row.length === value.symbols.length), - 'Returns must have one column per symbol' - ) - .refine( - value => (value.constraints?.minWeight ?? 0) <= (value.constraints?.maxWeight ?? 1), - 'Invalid weight bounds' - ) - .refine( - value => - (value.constraints?.minWeight ?? 0) * value.symbols.length <= 1 && - (value.constraints?.maxWeight ?? 1) * value.symbols.length >= 1, - 'Infeasible weight bounds' - ); -export type OptimizationParams = z.infer; -export const portfolioWeightsSchema = z - .object({ - symbols, - weights: z.array(finite.min(0).max(1)).min(1).max(128), - expected_return: finite, - expected_risk: finite.nonnegative(), - sharpe_ratio: optionalRatio, - }) - .refine( - value => - value.weights.length === value.symbols.length && - Math.abs(value.weights.reduce((sum, weight) => sum + weight, 0) - 1) <= 1e-6, - 'Invalid portfolio weights' - ); -export const correlationRequestSchema = z.object({ - symbols: symbols.refine(values => values.length >= 2, 'At least two symbols are required'), -}); -export const correlationResponseSchema = z - .object({ - symbols, - matrix: z.array(z.array(finite.min(-1).max(1)).max(128)).max(128), - }) - .refine(value => { - const size = value.symbols.length; - if (value.matrix.length !== size || value.matrix.some(row => row.length !== size)) { - return false; - } - const lower = Array.from({ length: size }, () => Array(size).fill(0)); - for (let i = 0; i < size; i++) { - if (Math.abs((value.matrix[i]?.[i] ?? 0) - 1) > 1e-8) { - return false; - } - for (let j = 0; j <= i; j++) { - const input = value.matrix[i]?.[j] ?? 0; - if (Math.abs(input - (value.matrix[j]?.[i] ?? 0)) > 1e-8) { - return false; - } - let residual = input; - for (let k = 0; k < j; k++) { - residual -= (lower[i]?.[k] ?? 0) * (lower[j]?.[k] ?? 0); - } - const row = lower[i]; - if (!row) { - return false; - } - if (i === j) { - if (residual < -1e-8) { - return false; - } - row[j] = Math.sqrt(Math.max(0, residual)); - } else { - const diagonal = lower[j]?.[j] ?? 0; - if (diagonal > 1e-8) { - row[j] = residual / diagonal; - } else if (Math.abs(residual) > 1e-8) { - return false; - } - } - } - } - return true; - }, 'Invalid correlation matrix'); -type Json = null | boolean | string | number | Json[] | { [key: string]: Json }; -const json: z.ZodType = z.lazy(() => - z.union([z.null(), z.boolean(), z.string(), finite, z.array(json), z.record(json)]) -); -export const predictionRequestSchema = z - .object({ modelId: z.string().min(1).max(128), features: z.record(finite) }) - .strict(); -export const predictionResponseSchema = z.object({ - model_id: z.string().min(1), - prediction: finite, - probability: z.record(finite.min(0).max(1)).nullable().optional(), - metadata: z.record(json).nullable().optional(), -}); -export const backtestAnalysisSchema = z.object({ - backtest_id: z.string().min(1), - metrics: z.record(optionalRatio), - statistics: z.record(optionalRatio), - risk_analysis: z.record(optionalRatio), - trade_analysis: z.record(optionalRatio), -}); -export const regimeResponseSchema = z.object({ regime: z.string().trim().min(1).max(128) }); diff --git a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts b/apps/stock/orchestrator/src/contracts/builtin-strategy.ts deleted file mode 100644 index a751a754..00000000 --- a/apps/stock/orchestrator/src/contracts/builtin-strategy.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** Compatibility export: canonical validation is shared with the research API. */ -export { - smaStrategySelectionSchema, - meanReversionStrategySelectionSchema, - builtinStrategySelectionSchema, - type SmaStrategySelection, - type MeanReversionStrategySelection, - type MeanReversionSignalParameters, - type BuiltinStrategySelection, -} from '@stock-bot/stock-config/strategy'; diff --git a/apps/stock/orchestrator/src/contracts/canonical-execution.ts b/apps/stock/orchestrator/src/contracts/canonical-execution.ts deleted file mode 100644 index 3d2d3678..00000000 --- a/apps/stock/orchestrator/src/contracts/canonical-execution.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Shared financial wire contract. */ -export * from '@stock-bot/stock-config/canonical-execution'; diff --git a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts b/apps/stock/orchestrator/src/contracts/canonical-strategy.ts deleted file mode 100644 index ad1c3773..00000000 --- a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** Compatibility type export. Authors use @stock-bot/research/strategy-api. */ -export type { - DeepReadonly, - StrategyAdmissionFeedback, - StrategyContext, - StrategyProgram, - StrategyDiagnostic, - StrategyDiagnosticSnapshot, -} from '@stock-bot/research/strategy-api'; diff --git a/apps/stock/orchestrator/src/contracts/native-replay.ts b/apps/stock/orchestrator/src/contracts/native-replay.ts deleted file mode 100644 index e9ebce46..00000000 --- a/apps/stock/orchestrator/src/contracts/native-replay.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility export: pure financial replay contracts are shared with research APIs. */ -export * from '@stock-bot/stock-config/canonical-replay'; diff --git a/apps/stock/orchestrator/src/contracts/paper-runtime.ts b/apps/stock/orchestrator/src/contracts/paper-runtime.ts deleted file mode 100644 index 8863950c..00000000 --- a/apps/stock/orchestrator/src/contracts/paper-runtime.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Shared financial wire contract. */ -export * from '@stock-bot/stock-config/paper-runtime'; diff --git a/apps/stock/orchestrator/src/contracts/strategies.ts b/apps/stock/orchestrator/src/contracts/strategies.ts deleted file mode 100644 index 81f0fe74..00000000 --- a/apps/stock/orchestrator/src/contracts/strategies.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { z } from 'zod'; -import { maxStrategyPeriod } from '@stock-bot/stock-config/strategy'; -import { instrumentIdSchema } from './historical'; -import type { BuiltinStrategy } from './strategy-names'; - -export { maxStrategyPeriod }; -const period = z.number().finite().int().min(1).max(maxStrategyPeriod); -const positive = z.number().finite().positive(); -const quantity = positive.min(1e-8).max(1e9); -const context = { - initialCapital: positive.optional(), - symbols: z.array(z.string()).optional(), -}; -const smaPeriods = { fastPeriod: period.default(5), slowPeriod: period.min(2).default(15) }; -const validSma = (value: { fastPeriod: number; slowPeriod: number }) => - value.fastPeriod < value.slowPeriod; -const smaMessage = 'SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000'; - -export const typescriptSmaParameters = z - .object({ - ...context, - ...smaPeriods, - positionFraction: positive.max(1).default(0.1), - minHoldingBars: z.number().int().min(0).max(maxStrategyPeriod).default(3), - quantity: quantity.optional(), - }) - .strict() - .refine(validSma, smaMessage); -export const nativeSmaParameters = z - .object({ ...smaPeriods, quantity: quantity.default(100) }) - .strict() - .refine(validSma, smaMessage); -export type SmaParameters = z.infer; - -export const typescriptMeanReversionParameters = z - .object({ - ...context, - lookbackPeriod: period.min(2).default(20), - trendPeriod: period.optional(), - entryThreshold: positive.default(2), - exitZScore: z.number().finite().min(0).default(0.5), - rsiPeriod: period.default(14), - rsiOversold: z.number().finite().min(0).max(100).default(30), - rsiOverbought: z.number().finite().min(0).max(100).default(70), - minNotionalVolume: z.number().finite().min(0).default(1000000), - quantity: quantity.optional(), - }) - .strict() - .refine( - value => value.exitZScore < value.entryThreshold, - 'exitZScore must be below entryThreshold' - ) - .refine( - value => value.rsiOversold < value.rsiOverbought, - 'rsiOversold must be below rsiOverbought' - ) - .refine( - value => value.trendPeriod === undefined || value.trendPeriod >= value.lookbackPeriod, - 'trendPeriod must be at least lookbackPeriod' - ) - .transform(value => ({ - ...value, - trendPeriod: value.trendPeriod ?? Math.max(50, value.lookbackPeriod), - })); -export type MeanReversionParameters = z.infer; - -const nativeMean = { - lookbackPeriod: period.min(2).default(20), - entryThreshold: positive.default(2), - // Native mean/momentum/pairs retain their existing absolute-share positionSize contract. - positionSize: quantity.default(100), -}; -export const nativeMeanReversionParameters = z.object(nativeMean).strict(); -export const nativeMomentumParameters = z - .object({ - lookbackPeriod: period.default(14), - momentumThreshold: positive.default(5), - positionSize: quantity.default(100), - }) - .strict(); -export const nativePairsParameters = z - .object({ - ...nativeMean, - pairA: instrumentIdSchema, - pairB: instrumentIdSchema, - }) - .strict() - .refine(value => value.pairA !== value.pairB, 'Pairs must use distinct instruments'); - -export function nativeParameters( - kind: BuiltinStrategy, - input: Record -): Record { - switch (kind) { - case 'sma_crossover': - return nativeSmaParameters.parse(input); - case 'mean_reversion': - return nativeMeanReversionParameters.parse(input); - case 'momentum': - return nativeMomentumParameters.parse(input); - case 'pairs_trading': - return nativePairsParameters.parse(input); - default: - throw new Error(`Unsupported native strategy: ${kind}`); - } -} diff --git a/apps/stock/orchestrator/src/contracts/strategy-names.ts b/apps/stock/orchestrator/src/contracts/strategy-names.ts deleted file mode 100644 index 7225437c..00000000 --- a/apps/stock/orchestrator/src/contracts/strategy-names.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { - normalizeStrategyName, - strategyAliases, - builtinStrategy, - type BuiltinStrategy, -} from '@stock-bot/stock-config/strategy'; diff --git a/apps/stock/orchestrator/src/contracts/strategy-replay.ts b/apps/stock/orchestrator/src/contracts/strategy-replay.ts index 872fce7b..27ba06ce 100644 --- a/apps/stock/orchestrator/src/contracts/strategy-replay.ts +++ b/apps/stock/orchestrator/src/contracts/strategy-replay.ts @@ -1,6 +1,6 @@ /** Data-only trusted built-in execution protocol; no strategy code or native imports. */ import { z } from 'zod'; -import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from './builtin-strategy'; +import { builtinStrategySelectionSchema, type BuiltinStrategySelection } from '@stock-bot/stock-config/strategy'; import { parseReplayProjectionValue, parseReplayReportValue, @@ -11,7 +11,7 @@ import { type ReplayIdentity, type ReplayOutput, type ReplayResultFormat, -} from './native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; export const strategyReplayRequestSchema = z .object({ diff --git a/apps/stock/orchestrator/src/core/ModeManager.ts b/apps/stock/orchestrator/src/core/ModeManager.ts deleted file mode 100644 index d2b34ed0..00000000 --- a/apps/stock/orchestrator/src/core/ModeManager.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { EventEmitter } from 'events'; -import { TradingEngine } from '@stock-bot/engine'; -import { defined } from '@stock-bot/invariants'; -import type { Logger } from '@stock-bot/services'; -import type { ExecutionService } from '../services/ExecutionService'; -import type { MarketDataService } from '../services/MarketDataService'; -import type { StrategyManager } from '../strategies/StrategyManager'; -import { - BacktestConfigSchema, - PaperConfigSchema, - type ModeConfig, - type TradingMode, -} from '../types'; - -const shutdownOrder = ['marketData', 'strategies', 'execution'] as const; -type LifecycleService = (typeof shutdownOrder)[number]; - -export class ModeManager extends EventEmitter { - private mode: TradingMode = 'paper'; - private config: ModeConfig | null = null; - private tradingEngine: TradingEngine | null = null; - private isInitialized = false; - constructor( - private readonly dependencies: { - allowedMode?: 'paper' | 'backtest'; - logger: Pick; - marketData: Pick; - execution: Pick; - strategies: Pick; - } - ) { - super(); - } - - async initializeMode(config: ModeConfig): Promise { - if (config.mode === 'live') { - throw new Error('Live trading is disabled: no real broker adapter exists'); - } - if (this.dependencies.allowedMode && config.mode !== this.dependencies.allowedMode) { - throw new Error( - `Runtime composition only permits ${this.dependencies.allowedMode} mode; cannot initialize ${config.mode}` - ); - } - // Validate config based on mode - switch (config.mode) { - case 'backtest': - BacktestConfigSchema.parse(config); - break; - case 'paper': - PaperConfigSchema.parse(config); - break; - } - - // Shutdown current mode if initialized - if (this.isInitialized) { - await this.shutdown(); - } - - const attempted = new Set(); - try { - this.mode = config.mode; - this.config = config; - - // Create Rust trading engine with appropriate config - const engineConfig = this.createEngineConfig(config); - this.tradingEngine = new TradingEngine(config.mode, engineConfig); - - await this.initializeServices(config, attempted); - } catch (error) { - try { - await this.shutdownServices(attempted); - } catch { - // Every cleanup was attempted; preserve the original initialization error. - } finally { - this.clearState(); - } - throw error; - } - - this.isInitialized = true; - this.emit('modeChanged', config); - - this.dependencies.logger.info(`Trading mode initialized: ${config.mode}`); - } - - private createEngineConfig(config: ModeConfig) { - switch (config.mode) { - case 'backtest': - return { - startTime: new Date(config.startDate).getTime(), - endTime: new Date(config.endDate).getTime(), - speedMultiplier: this.getSpeedMultiplier(config.speed), - initialCapital: config.initialCapital, - }; - case 'paper': - return { - startingCapital: config.startingCapital, - }; - case 'live': - return { - broker: config.broker, - accountId: config.accountId, - }; - } - } - - private getSpeedMultiplier(speed: string): number { - switch (speed) { - case 'max': - return 0; - case 'realtime': - return 1; - case '2x': - return 2; - case '5x': - return 5; - case '10x': - return 10; - default: - return 0; - } - } - - private async initializeServices( - config: ModeConfig, - attempted: Set - ): Promise { - // Register before each await: an initializer may acquire resources then fail. - // Configure execution service - attempted.add('execution'); - await this.dependencies.execution.initialize(config, defined(this.tradingEngine)); - - if (config.mode === 'paper') { - attempted.add('strategies'); - await this.dependencies.strategies.restoreStrategies(); - } - // Admission is ready before a real-time feed can deliver events. - attempted.add('marketData'); - await this.dependencies.marketData.initialize(config); - } - - private async shutdownServices(attempted: ReadonlySet): Promise { - let failed = false; - let failure: unknown; - for (const service of shutdownOrder) { - if (!attempted.has(service)) { - continue; - } - try { - await this.dependencies[service].shutdown(); - } catch (error) { - if (!failed) { - failure = error; - } - failed = true; - } - } - if (failed) { - throw failure; - } - } - - private clearState(): void { - this.tradingEngine = null; - this.config = null; - this.isInitialized = false; - } - - getCurrentMode(): TradingMode { - return this.mode; - } - - getConfig(): ModeConfig | null { - return this.config; - } - - getTradingEngine(): TradingEngine { - if (!this.tradingEngine) { - throw new Error('Trading engine not initialized'); - } - return this.tradingEngine; - } - - isBacktestMode(): boolean { - return this.mode === 'backtest'; - } - - isPaperMode(): boolean { - return this.mode === 'paper'; - } - - isLiveMode(): boolean { - return this.mode === 'live'; - } - - async transitionMode( - fromMode: TradingMode, - toMode: TradingMode, - config: ModeConfig - ): Promise { - if (config.mode !== toMode || fromMode !== this.mode) { - throw new Error('Mode transition does not match current mode or configuration'); - } - await this.initializeMode(config); - } - - async shutdown(): Promise { - if (!this.isInitialized) { - return; - } - - this.dependencies.logger.info(`Shutting down ${this.mode} mode...`); - - try { - await this.shutdownServices(new Set(shutdownOrder)); - } finally { - this.clearState(); - this.emit('shutdown'); - } - } -} diff --git a/apps/stock/orchestrator/src/data/DataManager.ts b/apps/stock/orchestrator/src/data/DataManager.ts deleted file mode 100644 index b6f52203..00000000 --- a/apps/stock/orchestrator/src/data/DataManager.ts +++ /dev/null @@ -1,307 +0,0 @@ -import { EventEmitter } from 'events'; -import { at, defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { HistoricalDataset } from '@stock-bot/types'; -import type { HistoricalBar, StorageService } from '../services/StorageService'; -import { type Bar, type MarketData } from '../types'; - -const logger = getLogger('DataManager'); - -export interface DataResolution { - interval: string; - milliseconds: number; -} - -export interface DataQualityIssue { - timestamp: Date; - symbol: string; - issue: string; - severity: 'warning' | 'error'; - details?: unknown; -} - -export class DataManager extends EventEmitter { - private static RESOLUTIONS: Record = { - tick: { interval: 'tick', milliseconds: 0 }, - '1s': { interval: '1s', milliseconds: 1000 }, - '5s': { interval: '5s', milliseconds: 5000 }, - '10s': { interval: '10s', milliseconds: 10000 }, - '30s': { interval: '30s', milliseconds: 30000 }, - '1m': { interval: '1m', milliseconds: 60000 }, - '5m': { interval: '5m', milliseconds: 300000 }, - '15m': { interval: '15m', milliseconds: 900000 }, - '30m': { interval: '30m', milliseconds: 1800000 }, - '1h': { interval: '1h', milliseconds: 3600000 }, - '4h': { interval: '4h', milliseconds: 14400000 }, - '1d': { interval: '1d', milliseconds: 86400000 }, - }; - - private dataCache: Map = new Map(); - private aggregatedCache: Map> = new Map(); - private dataQualityIssues: DataQualityIssue[] = []; - - constructor(private storageService: Pick) { - super(); - } - - async loadHistoricalData( - symbols: string[], - startDate: Date, - endDate: Date, - resolution: string = '1m', - _includeExtendedHours: boolean = false - ): Promise> { - const result = new Map(); - - for (const symbol of symbols) { - try { - // Load raw data - const data = await this.storageService.getHistoricalBars( - symbol, - startDate, - endDate, - resolution - ); - - if (!data.length) { - throw new Error(`No historical data for ${symbol}`); - } - this.recordQualityWarnings(symbol, data); - - // Storage owns validation and adjustment. Never interpolate or adjust a second time. - const marketData = this.convertToMarketData(symbol, data); - - result.set(symbol, marketData); - this.dataCache.set(`${symbol}:${resolution}`, marketData); - - logger.info(`Loaded ${marketData.length} bars for ${symbol} at ${resolution} resolution`); - } catch (error) { - logger.error(`Failed to load data for ${symbol}:`, error); - this.emit('dataError', { symbol, error }); - this.dataCache.clear(); - throw error; - } - } - - return result; - } - - /** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */ - inspectDataset(dataset: HistoricalDataset): void { - this.clearCache(); - const grouped = new Map(); - for (const bar of dataset.bars) { - let bars = grouped.get(bar.symbol); - if (!bars) { - bars = []; - grouped.set(bar.symbol, bars); - } - bars.push(bar); - } - for (const instrument of dataset.manifest.instruments) { - this.recordQualityWarnings(instrument.id, grouped.get(instrument.id) ?? []); - } - } - - private recordQualityWarnings( - symbol: string, - bars: readonly { timestamp: Date | number; close: number }[] - ): void { - bars.forEach((bar, index) => { - const previous = bars[index - 1]; - if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) { - this.dataQualityIssues.push({ - timestamp: new Date(bar.timestamp), - symbol, - issue: 'Price movement exceeds 20%; prices retained unchanged', - severity: 'warning', - }); - } - }); - } - - aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] { - const fromMs = DataManager.RESOLUTIONS[fromResolution]?.milliseconds; - const toMs = DataManager.RESOLUTIONS[toResolution]?.milliseconds; - - if (!fromMs || !toMs || fromMs >= toMs) { - throw new Error(`Cannot aggregate from ${fromResolution} to ${toResolution}`); - } - - const bars: Bar[] = []; - let currentBar: Partial | null = null; - let barStartTime = 0; - - for (const item of data) { - if (item.type !== 'bar') { - continue; - } - - const bar = item.data; - const timestamp = bar.timestamp; - const alignedTime = Math.floor(timestamp / toMs) * toMs; - - if (!currentBar || alignedTime > barStartTime) { - // Finalize previous bar - if (currentBar && currentBar.open !== undefined) { - bars.push(currentBar as Bar); - } - - // Start new bar - currentBar = { - timestamp: alignedTime, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - vwap: bar.vwap, - }; - barStartTime = alignedTime; - } else { - // Update current bar - currentBar.high = Math.max(defined(currentBar.high), bar.high); - currentBar.low = Math.min(defined(currentBar.low), bar.low); - currentBar.close = bar.close; - currentBar.volume = (currentBar.volume ?? 0) + bar.volume; - - // Recalculate VWAP if available - if (bar.vwap && currentBar.vwap) { - const totalValue = - currentBar.vwap * (defined(currentBar.volume) - bar.volume) + bar.vwap * bar.volume; - currentBar.vwap = totalValue / defined(currentBar.volume); - } - } - } - - // Add final bar - if (currentBar && currentBar.open !== undefined) { - bars.push(currentBar as Bar); - } - - return bars; - } - - downsampleData(data: MarketData[], targetPoints: number): MarketData[] { - if (data.length <= targetPoints) { - return data; - } - - // Use LTTB (Largest Triangle Three Buckets) algorithm - const downsampled: MarketData[] = []; - const bucketSize = (data.length - 2) / (targetPoints - 2); - - // Always include first point - downsampled.push(at(data, 0)); - - for (let i = 0; i < targetPoints - 2; i++) { - const bucketStart = Math.floor(i * bucketSize) + 1; - const bucketEnd = Math.floor((i + 1) * bucketSize) + 1; - - // Find point with maximum area in bucket - let maxArea = -1; - let maxAreaPoint = 0; - - const prevPoint = at(downsampled, downsampled.length - 1); - const prevTime = prevPoint.data.timestamp; - const prevPrice = this.getPrice(prevPoint); - - // Calculate average of next bucket for area calculation - const nextBucketStart = Math.floor((i + 1) * bucketSize) + 1; - let nextBucketEnd = Math.floor((i + 2) * bucketSize) + 1; - if (nextBucketEnd >= data.length) { - nextBucketEnd = data.length - 1; - } - - let avgTime = 0; - let avgPrice = 0; - for (let j = nextBucketStart; j < nextBucketEnd; j++) { - avgTime += at(data, j).data.timestamp; - avgPrice += this.getPrice(at(data, j)); - } - avgTime /= nextBucketEnd - nextBucketStart; - avgPrice /= nextBucketEnd - nextBucketStart; - - // Find point with max area - for (let j = bucketStart; j < bucketEnd && j < data.length; j++) { - const time = at(data, j).data.timestamp; - const price = this.getPrice(at(data, j)); - - // Calculate triangle area - const area = Math.abs( - (prevTime - avgTime) * (price - prevPrice) - (prevTime - time) * (avgPrice - prevPrice) - ); - - if (area > maxArea) { - maxArea = area; - maxAreaPoint = j; - } - } - - downsampled.push(at(data, maxAreaPoint)); - } - - // Always include last point - downsampled.push(at(data, data.length - 1)); - - return downsampled; - } - - private getPrice(data: MarketData): number { - switch (data.type) { - case 'bar': - return data.data.close; - case 'trade': - return data.data.price; - case 'quote': - return (data.data.bid + data.data.ask) / 2; - default: - return 0; - } - } - - private convertToMarketData(symbol: string, bars: HistoricalBar[]): MarketData[] { - return bars.map(bar => ({ - type: 'bar' as const, - data: { - symbol, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - vwap: bar.vwap, - timestamp: new Date(bar.timestamp).getTime(), - interpolated: bar.interpolated, - }, - })); - } - - getDataQualityReport(): { - totalIssues: number; - bySymbol: Record; - bySeverity: Record; - issues: DataQualityIssue[]; - } { - const bySymbol: Record = {}; - const bySeverity: Record = { warning: 0, error: 0 }; - - for (const issue of this.dataQualityIssues) { - bySymbol[issue.symbol] = (bySymbol[issue.symbol] || 0) + 1; - bySeverity[issue.severity] = (bySeverity[issue.severity] ?? 0) + 1; - } - - return { - totalIssues: this.dataQualityIssues.length, - bySymbol, - bySeverity, - issues: this.dataQualityIssues, - }; - } - - clearCache(): void { - this.dataCache.clear(); - this.aggregatedCache.clear(); - this.dataQualityIssues = []; - } -} diff --git a/apps/stock/orchestrator/src/data/historical-dataset.ts b/apps/stock/orchestrator/src/data/historical-dataset.ts index a0689335..64397ffc 100644 --- a/apps/stock/orchestrator/src/data/historical-dataset.ts +++ b/apps/stock/orchestrator/src/data/historical-dataset.ts @@ -10,9 +10,9 @@ import { type HistoricalDataset, } from '@stock-bot/types'; import { datasetBarSchema } from '../contracts/historical'; -import type { StorageService } from '../services/StorageService'; +import type { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import type { BacktestConfig } from '../types'; -import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './preparation'; +import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '@stock-bot/trading-runtime/preparation'; export type DatasetResolver = ( load: () => Promise, diff --git a/apps/stock/orchestrator/src/data/preparation.ts b/apps/stock/orchestrator/src/data/preparation.ts deleted file mode 100644 index c4719585..00000000 --- a/apps/stock/orchestrator/src/data/preparation.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ -export * from '@stock-bot/trading-runtime/preparation'; diff --git a/apps/stock/orchestrator/src/data/retained-research-dataset.ts b/apps/stock/orchestrator/src/data/retained-research-dataset.ts deleted file mode 100644 index be375c0d..00000000 --- a/apps/stock/orchestrator/src/data/retained-research-dataset.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ -export * from '@stock-bot/trading-runtime/retained-dataset'; diff --git a/apps/stock/orchestrator/src/execution/BacktestExecutionRepository.ts b/apps/stock/orchestrator/src/execution/BacktestExecutionRepository.ts deleted file mode 100644 index 22ed1b2e..00000000 --- a/apps/stock/orchestrator/src/execution/BacktestExecutionRepository.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import type { Account, StoredOrder } from './model'; -import { - ExecutionConflictError, - type ExecutionRepository, - type ExecutionTransaction, -} from './repository'; -import { - canonicalJson, - type MarketInput, - type StrategyCheckpoint, - type StrategyJournalEvent, - type StrategyOrderIntent, -} from './strategy-recovery'; - -/** Only transaction writes are staged; committed history is never copied on entry. */ -class TransactionMap { - readonly writes = new Map(); - constructor(private readonly base: Map) {} - get(key: string): T | undefined { - return this.writes.get(key) ?? this.base.get(key); - } - put(key: string, value: T): void { - this.writes.set(key, structuredClone(value)); - } - *values(): Iterable { - for (const [key, value] of this.base) { - yield this.writes.get(key) ?? value; - } - for (const [key, value] of this.writes) { - if (!this.base.has(key)) { - yield value; - } - } - } - commit(): void { - for (const [key, value] of this.writes) { - this.base.set(key, value); - } - } -} - -interface RunState { - account: Account; - orders: Map; - clients: Map; - openOrders: Set; - fills: Set; - events: Map; - journal: StrategyJournalEvent[]; - strategies: Map; - intents: Map; - pendingIntents: Set; - inputs: Map; - pendingInputs: Set; -} - -const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); -const isOpen = (order: StoredOrder) => - order.report.status === 'accepted' || order.report.status === 'partiallyFilled'; -const compareIntents = (a: StrategyOrderIntent, b: StrategyOrderIntent) => - a.sequence - b.sequence || - compareText(a.strategyId, b.strategyId) || - compareText(a.clientOrderId, b.clientOrderId); - -/** Binary search works with nonzero initial sequence numbers as well as empty journals. */ -function after(journal: StrategyJournalEvent[], cursor: number): StrategyJournalEvent | undefined { - let low = 0, - high = journal.length; - while (low < high) { - const mid = Math.floor((low + high) / 2); - if (defined(journal[mid]).sequence <= cursor) { - low = mid + 1; - } else { - high = mid; - } - } - return journal[low]; -} - -/** Iterate only active IDs plus staged writes, never the retained applied/dispatched history. */ -function* candidates(ids: Set, table: TransactionMap): Iterable { - for (const id of ids) { - const value = table.get(id); - if (value !== undefined) { - yield value; - } - } - for (const [id, value] of table.writes) { - if (!ids.has(id)) { - yield value; - } - } -} - -/** Explicit run-local backtest store, never a fallback for paper or live execution. */ -export class BacktestExecutionRepository implements ExecutionRepository { - private state?: RunState; - private tail: Promise = Promise.resolve(); - - async initialize(_id: string, account: Account): Promise { - await this.tail; - this.state = { - account: structuredClone(account), - orders: new Map(), - clients: new Map(), - openOrders: new Set(), - fills: new Set(), - events: new Map(), - journal: [], - strategies: new Map(), - intents: new Map(), - pendingIntents: new Set(), - inputs: new Map(), - pendingInputs: new Set(), - }; - } - - transact(_id: string, work: (tx: ExecutionTransaction) => Promise): Promise { - const task = this.tail.then(async () => { - const state = this.state; - if (!state) { - throw new Error('Execution account is not initialized'); - } - const account = structuredClone(state.account); - const orders = new TransactionMap(state.orders); - const clients = new TransactionMap(state.clients); - const events = new TransactionMap(state.events); - const strategies = new TransactionMap(state.strategies); - const intents = new TransactionMap(state.intents); - const inputs = new TransactionMap(state.inputs); - const fills = new Set(); - const journal: StrategyJournalEvent[] = []; - let open = true; - const assertOpen = () => { - if (!open) { - throw new Error('Execution transaction has finished'); - } - }; - try { - const result = await work({ - account, - async findOrder(id) { - assertOpen(); - const orderId = clients.get(id); - return structuredClone(orderId === undefined ? undefined : orders.get(orderId)); - }, - async getOrder(id) { - assertOpen(); - return structuredClone(orders.get(id)); - }, - async openOrders() { - assertOpen(); - return structuredClone([...candidates(state.openOrders, orders)].filter(isOpen)); - }, - async putOrder(order) { - assertOpen(); - const id = order.report.orderId; - const clientId = order.report.clientOrderId; - const existingId = clients.get(clientId); - if (existingId !== undefined && existingId !== id) { - throw new ExecutionConflictError('Client order ID already exists'); - } - const old = orders.get(id); - if (old && old.report.clientOrderId !== clientId) { - throw new ExecutionConflictError('Order client ID cannot change'); - } - orders.put(id, order); - clients.put(clientId, id); - }, - async insertFill(_orderId, fill) { - assertOpen(); - if (state.fills.has(fill.id) || fills.has(fill.id)) { - return false; - } - fills.add(fill.id); - return true; - }, - async recordEvent(id, hash) { - assertOpen(); - const previous = events.get(id); - if (previous !== undefined && previous !== hash) { - throw new ExecutionConflictError('Conflicting market event identity'); - } - if (previous !== undefined) { - return false; - } - events.put(id, hash); - return true; - }, - async appendJournal(payload) { - assertOpen(); - const sequence = (account.strategySequence ?? 0) + 1; - if (!Number.isSafeInteger(sequence)) { - throw new Error('Strategy journal sequence exhausted'); - } - account.strategySequence = sequence; - journal.push({ sequence, payload: structuredClone(payload) }); - }, - async nextJournal(cursor) { - assertOpen(); - return structuredClone(after(state.journal, cursor) ?? after(journal, cursor)); - }, - async strategies() { - assertOpen(); - return structuredClone( - [...strategies.values()].sort((a, b) => compareText(a.strategyId, b.strategyId)) - ); - }, - async putStrategy(checkpoint) { - assertOpen(); - strategies.put(checkpoint.strategyId, checkpoint); - }, - async nextIntent() { - assertOpen(); - let next: StrategyOrderIntent | undefined; - for (const intent of candidates(state.pendingIntents, intents)) { - if (intent.status === 'pending' && (!next || compareIntents(intent, next) < 0)) { - next = intent; - } - } - return structuredClone(next); - }, - async putIntent(intent) { - assertOpen(); - const old = intents.get(intent.clientOrderId); - if ( - old && - (old.strategyId !== intent.strategyId || - old.sequence !== intent.sequence || - canonicalJson(old.request) !== canonicalJson(intent.request) || - (old.status === 'dispatched' && intent.status !== 'dispatched')) - ) { - throw new ExecutionConflictError('Conflicting strategy order intent'); - } - intents.put(intent.clientOrderId, intent); - }, - async nextInput() { - assertOpen(); - let next: MarketInput | undefined; - for (const input of candidates(state.pendingInputs, inputs)) { - if (input.status === 'pending' && (!next || input.sequence < next.sequence)) { - next = input; - } - } - return structuredClone(next); - }, - async putInput(input) { - assertOpen(); - inputs.put(input.id, input); - }, - }); - // Clone anything the callback can retain before publishing any staged writes. - const detachedResult = structuredClone(result); - state.account = structuredClone(account); - for (const table of [orders, clients, events, strategies, intents, inputs]) { - table.commit(); - } - for (const [id, order] of orders.writes) { - if (isOpen(order)) { - state.openOrders.add(id); - } else { - state.openOrders.delete(id); - } - } - for (const [id, intent] of intents.writes) { - if (intent.status === 'pending') { - state.pendingIntents.add(id); - } else { - state.pendingIntents.delete(id); - } - } - for (const [id, input] of inputs.writes) { - if (input.status === 'pending') { - state.pendingInputs.add(id); - } else { - state.pendingInputs.delete(id); - } - } - for (const id of fills) { - state.fills.add(id); - } - for (const event of journal) { - state.journal.push(event); - } - return detachedResult; - } finally { - open = false; - } - }); - this.tail = task.catch(() => {}); - return task; - } -} diff --git a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts index 10234bae..d1ff0edc 100644 --- a/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts +++ b/apps/stock/orchestrator/src/execution/CanonicalPaperExecution.ts @@ -10,9 +10,9 @@ import { type CanonicalExecutionIdentity, type CanonicalMatchingConfig, type FinancialTransactionRequest, -} from '../contracts/canonical-execution'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; -import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-execution'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; +import { nativeAdmissionOrders, type DecisionContext } from '@stock-bot/stock-config/canonical-replay'; import { freeze, increment, @@ -34,7 +34,7 @@ import { type CanonicalPaperInput, type CanonicalTransaction, } from './canonical-paper'; -import { ExecutionConflictError } from './repository'; +import { ExecutionConflictError } from './canonical-paper'; const callback = new AsyncLocalStorage(); function outsideCallback() { diff --git a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts index 7677b9f2..c249cfe8 100644 --- a/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts +++ b/apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository.ts @@ -12,7 +12,7 @@ import { type CanonicalPostgres, type CanonicalTransaction, } from './canonical-paper'; -import { ExecutionConflictError } from './repository'; +import { ExecutionConflictError } from './canonical-paper'; function accountState(raw: unknown): CanonicalAccount { const result = canonicalAccountSchema.safeParse(raw); diff --git a/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts deleted file mode 100644 index 7854a431..00000000 --- a/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts +++ /dev/null @@ -1,213 +0,0 @@ -import type { PostgresClient } from '@stock-bot/services'; -import { refuseCanonicalAccount } from './canonical-paper'; -import type { Account, Fill, StoredOrder } from './model'; -import { - ExecutionConflictError, - type ExecutionRepository, - type ExecutionTransaction, -} from './repository'; -import { - canonicalJson, - type MarketInput, - type StrategyCheckpoint, - type StrategyJournalPayload, - type StrategyOrderIntent, -} from './strategy-recovery'; - -export class PostgresExecutionRepository implements ExecutionRepository { - constructor(private readonly postgres: Pick) {} - async initialize(id: string, initial: Account) { - await this.postgres.transaction(async client => { - await client.query( - `INSERT INTO simulation_accounts (id, state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING`, - [id, JSON.stringify(initial)] - ); - const result = await client.query( - 'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE', - [id] - ); - refuseCanonicalAccount(result.rows[0].state); - const account: Account = result.rows[0].state; - if (account.initialCapital !== initial.initialCapital) { - throw new ExecutionConflictError( - 'Existing account capital differs; use a new account ID, not an implicit reset' - ); - } - Object.assign(account, { - limits: initial.limits, - commission: initial.commission, - slippage: initial.slippage, - maxQuoteAgeMs: initial.maxQuoteAgeMs, - }); - await client.query('UPDATE simulation_accounts SET state = $2::jsonb WHERE id = $1', [ - id, - JSON.stringify(account), - ]); - }); - } - transact(id: string, work: (tx: ExecutionTransaction) => Promise): Promise { - return this.postgres.transaction(async client => { - const state = await client.query( - 'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE', - [id] - ); - if (!state.rows[0]) { - throw new Error('Execution account is not initialized'); - } - refuseCanonicalAccount(state.rows[0].state); - const readOrder = async (column: 'id' | 'client_order_id', key: string) => { - const result = await client.query( - `SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`, - [id, key] - ); - return result.rows[0]?.payload as StoredOrder | undefined; - }; - const result = await work({ - account: state.rows[0].state as Account, - findOrder: key => readOrder('client_order_id', key), - getOrder: key => readOrder('id', key), - async openOrders() { - const result = await client.query( - `SELECT payload FROM simulation_orders WHERE account_id = $1 AND status IN ('accepted','partiallyFilled') ORDER BY created_at,id`, - [id] - ); - return result.rows.map(r => r.payload as StoredOrder); - }, - async putOrder(order) { - await client.query( - `INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload) - VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`, - [ - order.report.orderId, - id, - order.report.clientOrderId, - order.report.status, - JSON.stringify(order), - ] - ); - }, - async insertFill(orderId: string, fill: Fill) { - const inserted = await client.query( - `INSERT INTO simulation_fills (account_id,id,order_id,payload) - VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`, - [id, fill.id, orderId, JSON.stringify(fill)] - ); - return inserted.rows.length > 0; - }, - async recordEvent(eventId, hash) { - const inserted = await client.query( - `INSERT INTO simulation_events (account_id,id,fingerprint) - VALUES ($1,$2,$3) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`, - [id, eventId, hash] - ); - if (inserted.rows.length) { - return true; - } - const previous = await client.query( - 'SELECT fingerprint FROM simulation_events WHERE account_id = $1 AND id = $2', - [id, eventId] - ); - if (previous.rows[0]?.fingerprint !== hash) { - throw new ExecutionConflictError('Conflicting market event identity'); - } - return false; - }, - async appendJournal(payload: StrategyJournalPayload) { - const account = state.rows[0].state as Account; - const sequence = (account.strategySequence ?? 0) + 1; - if (!Number.isSafeInteger(sequence)) { - throw new Error('Strategy journal sequence exhausted'); - } - account.strategySequence = sequence; - await client.query( - 'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)', - [id, sequence, JSON.stringify(payload)] - ); - }, - async nextJournal(cursor) { - const result = await client.query( - 'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence LIMIT 1', - [id, cursor] - ); - const row = result.rows[0]; - if (!row) { - return undefined; - } - const sequence = Number(row.sequence); - if (!Number.isSafeInteger(sequence)) { - throw new Error('Invalid strategy journal sequence'); - } - return { sequence, payload: row.payload as StrategyJournalPayload }; - }, - async strategies() { - const result = await client.query( - 'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"', - [id] - ); - return result.rows.map(row => row.payload as StrategyCheckpoint); - }, - async putStrategy(checkpoint) { - await client.query( - `INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb) - ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`, - [id, checkpoint.strategyId, JSON.stringify(checkpoint)] - ); - }, - async nextIntent() { - const result = await client.query( - `SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence,strategy_id COLLATE "C",client_order_id COLLATE "C" LIMIT 1`, - [id] - ); - return result.rows[0]?.payload as StrategyOrderIntent | undefined; - }, - async putIntent(intent) { - const previous = await client.query( - 'SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND client_order_id = $2', - [id, intent.clientOrderId] - ); - const old = previous.rows[0]?.payload as StrategyOrderIntent | undefined; - if ( - old && - (old.strategyId !== intent.strategyId || - old.sequence !== intent.sequence || - canonicalJson(old.request) !== canonicalJson(intent.request) || - (old.status === 'dispatched' && intent.status !== 'dispatched')) - ) { - throw new ExecutionConflictError('Conflicting strategy order intent'); - } - await client.query( - `INSERT INTO simulation_strategy_intents (account_id,client_order_id,strategy_id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5,$6::jsonb) - ON CONFLICT (account_id,client_order_id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`, - [ - id, - intent.clientOrderId, - intent.strategyId, - intent.sequence, - intent.status, - JSON.stringify(intent), - ] - ); - }, - async nextInput() { - const result = await client.query( - `SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1`, - [id] - ); - return result.rows[0]?.payload as MarketInput | undefined; - }, - async putInput(input) { - await client.query( - `INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb) - ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`, - [id, input.id, input.sequence, input.status, JSON.stringify(input)] - ); - }, - }); - await client.query( - 'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1', - [id, JSON.stringify(state.rows[0].state)] - ); - return result; - }); - } -} diff --git a/apps/stock/orchestrator/src/execution/SimulationExecution.ts b/apps/stock/orchestrator/src/execution/SimulationExecution.ts deleted file mode 100644 index 88c37ed9..00000000 --- a/apps/stock/orchestrator/src/execution/SimulationExecution.ts +++ /dev/null @@ -1,215 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { defined } from '@stock-bot/invariants'; -import type { OrderRequest } from '../types'; -import { - amount, - applyFill, - decimal, - fillPrice, - fingerprint, - riskViolations, - terminal, - type Account, - type ExecutionChange, - type Fill, - type Quote, - type StoredOrder, -} from './model'; -import { ExecutionConflictError, type ExecutionTransaction } from './repository'; - -export interface ExecutionClock { - now(quote?: Quote): number; - isBacktest(): boolean; -} - -/** Transaction-scoped simulation rules; the caller owns commit, serialization and publication. */ -export class SimulationExecution { - constructor(private readonly clock: ExecutionClock) {} - - rollDay(account: Account, time: number) { - const day = new Date(time).toISOString().slice(0, 10); - if (day > account.day || (this.clock.isBacktest() && !Object.keys(account.quotes).length)) { - account.day = day; - account.dailyPnl = 0; - } - } - private async assertRecovered(tx: ExecutionTransaction) { - if ( - (await tx.nextInput()) || - (await tx.nextIntent()) || - (await tx.strategies()).some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0)) - ) { - throw new ExecutionConflictError( - 'Strategy recovery backlog must drain before new order admission' - ); - } - } - async journalChange(tx: ExecutionTransaction, change: ExecutionChange) { - if (change.report.strategyId) { - await tx.appendJournal({ - kind: 'execution', - report: change.report, - fills: change.fills, - account: structuredClone(tx.account), - }); - } - } - async acceptOrder( - tx: ExecutionTransaction, - request: OrderRequest, - strategyId?: string, - internal = false - ): Promise { - const hash = fingerprint(request, strategyId); - const existing = await tx.findOrder(defined(request.clientOrderId)); - if (existing) { - if (existing.fingerprint !== hash) { - throw new ExecutionConflictError('Client order ID reused with a different request'); - } - return { report: existing.report, fills: [] }; - } - if (!internal) { - await this.assertRecovered(tx); - } - const quote = tx.account.quotes[request.symbol]; - const timestamp = this.clock.now(quote); - this.rollDay(tx.account, timestamp); - const order: StoredOrder = { - request, - fingerprint: hash, - policy: { commission: tx.account.commission, slippage: tx.account.slippage }, - report: { - orderId: randomUUID(), - clientOrderId: defined(request.clientOrderId), - strategyId: strategyId, - symbol: request.symbol, - side: request.side, - quantity: request.quantity, - status: 'accepted', - fills: [], - timestamp, - }, - }; - const invalid = !['market', 'limit'].includes(request.orderType) - ? 'Unsupported order type' - : !['DAY', 'GTC', 'IOC', 'FOK'].includes(request.timeInForce) - ? 'Unsupported time in force' - : request.orderType === 'limit' && - (!request.limitPrice || !Number.isFinite(request.limitPrice) || request.limitPrice <= 0) - ? 'Valid limit price required' - : !quote || - timestamp - quote.timestamp > tx.account.maxQuoteAgeMs || - quote.timestamp > timestamp - ? 'Missing, stale, or future market quote' - : undefined; - const price = quote && !invalid ? fillPrice(order, quote) : 0; - const violations = invalid - ? [invalid] - : riskViolations( - tx.account, - request, - await tx.openOrders(), - price, - timestamp, - order.policy.commission - ); - if (violations.length) { - order.report.status = 'rejected'; - order.report.rejectionReason = violations.join('; '); - } - await tx.putOrder(order); // Fill FK and acknowledgement are in the same transaction. - const fills = - order.report.status === 'rejected' || !quote - ? [] - : await this.fill(tx, order, quote, await tx.openOrders()); - await tx.putOrder(order); - const change = { report: order.report, fills }; - await this.journalChange(tx, change); - return change; - } - async fill( - tx: ExecutionTransaction, - order: StoredOrder, - quote: Quote, - reservations: StoredOrder[] - ): Promise { - if (terminal(order.report.status)) { - return []; - } - const request = order.request; - if ( - request.timeInForce === 'DAY' && - new Date(order.report.timestamp).toISOString().slice(0, 10) !== - new Date(quote.timestamp).toISOString().slice(0, 10) - ) { - order.report.status = 'cancelled'; - return []; - } - const crosses = - request.orderType === 'market' || - (request.side === 'buy' - ? quote.ask <= defined(request.limitPrice) - : quote.bid >= defined(request.limitPrice)); - const remaining = amount( - decimal(request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0)) - ); - const available = request.side === 'buy' ? quote.askSize : quote.bidSize; - const quantity = crosses ? Math.min(remaining, available) : 0; - if (!quantity || (request.timeInForce === 'FOK' && quantity < remaining)) { - if (request.timeInForce === 'IOC' || request.timeInForce === 'FOK') { - order.report.status = 'cancelled'; - } - return []; - } - const price = fillPrice(order, quote); - const violations = riskViolations( - tx.account, - { ...request, quantity: remaining }, - reservations.filter(o => o.report.orderId !== order.report.orderId), - price, - this.clock.now(quote), - order.policy.commission - ); - if (violations.length) { - order.report.status = 'cancelled'; - order.report.rejectionReason = violations.join('; '); - return []; - } - const fill = { - id: order.report.orderId + ':' + quote.eventId, - price, - quantity, - commission: amount(decimal(quantity).times(price).times(order.policy.commission)), - timestamp: quote.timestamp, - pnl: 0, - }; - const projected = structuredClone(tx.account); - const applied = applyFill(projected, request.symbol, request.side, fill); - if (!(await tx.insertFill(order.report.orderId, applied))) { - return []; - } - // Keep the same quote object so consumed liquidity is persisted with the accounting change. - Object.assign(tx.account, { ...projected, quotes: tx.account.quotes }); - if (order.report.strategyId) { - const book = (tx.account.strategyPositions[order.report.strategyId] ??= {}); - book[request.symbol] = amount( - decimal(book[request.symbol] ?? 0).plus(request.side === 'buy' ? quantity : -quantity) - ); - } - // Store the actual delta, not cumulative realized P&L. - // The returned fill is also appended to the durable report in this transaction. - order.report.fills.push(applied); - if (request.side === 'buy') { - quote.askSize = amount(decimal(quote.askSize).minus(quantity)); - } else { - quote.bidSize = amount(decimal(quote.bidSize).minus(quantity)); - } - order.report.status = - quantity >= remaining - ? 'filled' - : request.timeInForce === 'IOC' - ? 'cancelled' - : 'partiallyFilled'; - return [applied]; - } -} diff --git a/apps/stock/orchestrator/src/execution/StrategyRecovery.ts b/apps/stock/orchestrator/src/execution/StrategyRecovery.ts deleted file mode 100644 index a2cfbc7d..00000000 --- a/apps/stock/orchestrator/src/execution/StrategyRecovery.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { AsyncLocalStorage } from 'node:async_hooks'; -import { OrderRequestSchema, type OrderRequest } from '../types'; -import { accountMetrics, identity, type Account, type ExecutionChange } from './model'; -import { ExecutionConflictError, type ExecutionTransaction } from './repository'; -import { - canonicalJson, - strategyConfigHash, - type RecoverableStrategy, - type StrategyCheckpoint, - type StrategyOrderIntent, -} from './strategy-recovery'; - -/** Explicit ports keep recovery independent of the service container and storage adapters. */ -export interface StrategyRecoveryRuntime { - accountId(): string; - isBacktest(): boolean; - serialized(work: () => Promise): Promise; - transact(work: (tx: ExecutionTransaction) => Promise): Promise; - dispatch(tx: ExecutionTransaction, intent: StrategyOrderIntent): Promise; - publish(change: ExecutionChange): Promise; - consumeMarketInput(): Promise; - observationFailed(error: unknown): void; -} - -/** Owns checkpoints, decision scopes and outbox replay; never opens a nested transaction. */ -export class StrategyRecovery { - private readonly decision = new AsyncLocalStorage<{ - account: Account; - strategyId: string; - intents: StrategyOrderIntent[]; - sequence: number; - open: boolean; - observations: (() => void)[]; - }>(); - constructor(private readonly runtime: StrategyRecoveryRuntime) {} - - assertExternalIO(): void { - if (this.decision.getStore()) { - throw new Error( - 'Strategy callbacks cannot perform repository I/O; use the decision account view and order intents' - ); - } - } - - decisionAccount() { - const context = this.decision.getStore(); - if (!context) { - return undefined; - } - if (!context.open) { - throw new Error('Strategy evaluation has finished'); - } - return { ...structuredClone(context.account), ...accountMetrics(context.account) }; - } - - captureStrategyOrder(request: OrderRequest, strategyId: string): void { - const context = this.decision.getStore(); - if (!context?.open || context.strategyId !== strategyId) { - throw new Error('Strategy orders require an active checkpoint transaction'); - } - const order = OrderRequestSchema.parse(request); - if (!order.clientOrderId) { - throw new Error('Strategy intent requires a stable client order ID'); - } - if (context.intents.some(intent => intent.clientOrderId === order.clientOrderId)) { - throw new ExecutionConflictError('Duplicate intent in one decision'); - } - context.intents.push({ - strategyId, - clientOrderId: order.clientOrderId, - sequence: context.sequence, - request: order, - status: 'pending', - }); - } - afterStrategyCommit(observation: () => void): void { - const context = this.decision.getStore(); - if (!context?.open) { - throw new Error('No active strategy decision'); - } - context.observations.push(observation); - } - async getRecoveryStatus() { - return this.runtime.transact(async tx => ({ - accountId: this.runtime.accountId(), - pendingInputs: !!(await tx.nextInput()), - pendingIntents: !!(await tx.nextIntent()), - strategies: (await tx.strategies()).map(s => ({ - strategyId: s.strategyId, - enabled: s.enabled, - version: s.version, - cursor: s.cursor, - journalTail: tx.account.strategySequence ?? 0, - lag: (tx.account.strategySequence ?? 0) - s.cursor, - })), - })); - } - - async registerStrategy(strategy: RecoverableStrategy): Promise { - const config = structuredClone(strategy.getConfig()); - const version = - strategy.getCheckpointVersion() ?? - (this.runtime.isBacktest() ? 'run-local-unversioned' : undefined); - if (!version) { - throw new Error('Paper strategies require a versioned checkpoint contract'); - } - const hash = strategyConfigHash(config, version); - const initialState = JSON.parse(canonicalJson(strategy.captureCheckpoint())); - strategy.restoreCheckpoint(initialState); - const saved = await this.runtime.serialized(() => - this.runtime.transact(async tx => { - const existing = (await tx.strategies()).find(s => s.strategyId === config.id); - if (existing && (existing.version !== version || existing.configHash !== hash)) { - throw new ExecutionConflictError( - 'Strategy configuration/checkpoint version changed; use an explicit new strategy ID' - ); - } - const checkpoint: StrategyCheckpoint = existing ?? { - strategyId: config.id, - config, - configHash: hash, - version, - enabled: true, - cursor: tx.account.strategySequence ?? 0, - state: initialState, - }; - strategy.restoreCheckpoint(checkpoint.state); - await tx.putStrategy({ ...checkpoint, enabled: true }); - return checkpoint; - }) - ); - strategy.restoreCheckpoint(saved.state); - } - - async registeredStrategies() { - return this.runtime.transact(async tx => - (await tx.strategies()).map(s => ({ ...s.config, enabled: s.enabled })) - ); - } - async pauseStrategy(strategyId: string) { - await this.runtime.serialized(() => - this.runtime.transact(async tx => { - const checkpoint = (await tx.strategies()).find(s => s.strategyId === strategyId); - if (checkpoint) { - await tx.putStrategy({ ...checkpoint, enabled: false }); - } - }) - ); - } - - /** Account row locks serialize owners. Restore before EVERY step, not just startup. */ - async recoverStrategies(strategies: RecoverableStrategy[]): Promise { - await this.runtime.serialized(async () => { - const byId = new Map(strategies.map(strategy => [strategy.getConfig().id, strategy])); - const enabled = await this.runtime.transact(async tx => - (await tx.strategies()).filter(s => s.enabled) - ); - for (const checkpoint of enabled) { - const strategy = byId.get(checkpoint.strategyId); - if (!strategy) { - throw new ExecutionConflictError( - 'An enabled strategy must be restored before processing its account' - ); - } - const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned'; - if ( - checkpoint.version !== version || - checkpoint.configHash !== strategyConfigHash(strategy.getConfig(), version) - ) { - throw new ExecutionConflictError('Strategy checkpoint definition mismatch'); - } - } - while (true) { - const dispatched = await this.runtime.transact(async tx => { - const intent = await tx.nextIntent(); - if (!intent) { - return undefined; - } - const change = await this.runtime.dispatch(tx, intent); - await tx.putIntent({ ...intent, status: 'dispatched', orderId: change.report.orderId }); - return change; - }); - if (dispatched) { - await this.runtime.publish(dispatched); - continue; - } - let progressed = false; - const registrations = await this.runtime.transact(tx => tx.strategies()); - for (const registration of registrations.filter(s => s.enabled)) { - const strategy = byId.get(registration.strategyId); - if (!strategy) { - throw new ExecutionConflictError( - 'An enabled strategy must be restored before processing its account' - ); - } - let before = strategy.captureCheckpoint(); - let observations: (() => void)[] = []; - try { - const advanced = await this.runtime.transact(async tx => { - const checkpoint = (await tx.strategies()).find( - s => s.strategyId === registration.strategyId - ); - if (!checkpoint?.enabled) { - return false; - } - const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned'; - if ( - strategyConfigHash(strategy.getConfig(), version) !== checkpoint.configHash || - checkpoint.version !== version - ) { - throw new ExecutionConflictError('Strategy checkpoint definition mismatch'); - } - strategy.restoreCheckpoint(checkpoint.state); - before = checkpoint.state; - const event = await tx.nextJournal(checkpoint.cursor); - if (!event) { - return false; - } - const context = { - account: event.payload.account, - strategyId: checkpoint.strategyId, - intents: [] as StrategyOrderIntent[], - sequence: event.sequence, - open: true, - observations: [] as (() => void)[], - }; - try { - await this.decision.run(context, async () => { - const payload = event.payload; - if ( - payload.kind === 'market' && - payload.recipients.includes(checkpoint.strategyId) && - strategy.getConfig().symbols.includes(payload.market.data.symbol) - ) { - await strategy.onMarketData({ - ...payload.market, - eventId: identity(payload.market), - }); - } else if ( - payload.kind === 'execution' && - payload.report.strategyId === checkpoint.strategyId - ) { - for (const fill of payload.fills) { - await strategy.onFill({ - ...fill, - orderId: payload.report.orderId, - symbol: payload.report.symbol, - side: payload.report.side, - strategyId: checkpoint.strategyId, - }); - } - await strategy.onOrderUpdate(payload.report); - } - }); - } finally { - context.open = false; - } - const state = JSON.parse(canonicalJson(strategy.captureCheckpoint())); - await tx.putStrategy({ ...checkpoint, cursor: event.sequence, state }); - for (const intent of context.intents) { - await tx.putIntent(intent); - } - observations = context.observations; - return true; - }); - progressed ||= advanced; - for (const observe of observations) { - try { - observe(); - } catch (error) { - this.runtime.observationFailed(error); - } - } - } catch (error) { - strategy.restoreCheckpoint(before); - throw error; - } - } - if (progressed) { - continue; - } - if (!(await this.runtime.consumeMarketInput())) { - break; - } - } - }); - } -} diff --git a/apps/stock/orchestrator/src/execution/canonical-paper.ts b/apps/stock/orchestrator/src/execution/canonical-paper.ts index 7d865147..0498fa4f 100644 --- a/apps/stock/orchestrator/src/execution/canonical-paper.ts +++ b/apps/stock/orchestrator/src/execution/canonical-paper.ts @@ -6,13 +6,13 @@ import { canonicalExecutionCheckpointSchema, financialTransactionResultSchema, matchingCommandSchema, -} from '../contracts/canonical-execution'; +} from '@stock-bot/stock-config/canonical-execution'; import { nativeFinancialViewSchema, nativeManagedOrderSchema, stepSchema, -} from '../contracts/native-replay'; -import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime'; +} from '@stock-bot/stock-config/canonical-replay'; +import { paperConfigurationSchema, paperConnectionSchema } from '@stock-bot/stock-config/paper-runtime'; import { metadataSchema, stateCopy } from '../strategies/strategy-decision'; const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); @@ -195,7 +195,8 @@ export interface CanonicalExecutionRepository { transact(accountId: string, work: (tx: CanonicalTransaction) => Promise): Promise; } export type CanonicalPostgres = Pick; -export { compareEventKeys } from '../contracts/canonical-execution'; +export class ExecutionConflictError extends Error {} +export { compareEventKeys } from '@stock-bot/stock-config/canonical-execution'; /** Legacy callers must never reinterpret any version of a canonical envelope. */ export function refuseCanonicalAccount(state: unknown): void { if (state && typeof state === 'object' && 'kind' in state) { diff --git a/apps/stock/orchestrator/src/execution/model.ts b/apps/stock/orchestrator/src/execution/model.ts deleted file mode 100644 index 65dbb1ed..00000000 --- a/apps/stock/orchestrator/src/execution/model.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { createHash } from 'node:crypto'; -import Decimal from 'decimal.js-light'; -import { defined } from '@stock-bot/invariants'; -import type { MarketData, OrderRequest } from '../types'; - -export interface RiskLimits { - maxPositionSize: number; - maxOrderSize: number; - maxDailyLoss: number; - maxGrossExposure: number; - maxSymbolExposure: number; -} -export const defaultRiskLimits: RiskLimits = { - maxPositionSize: 10000, - maxOrderSize: 1000, - maxDailyLoss: 5000, - maxGrossExposure: 200000, - maxSymbolExposure: 50000, -}; -export interface Fill { - id: string; - price: number; - quantity: number; - commission: number; - timestamp: number; - pnl: number; -} -export interface ExecutionReport { - orderId: string; - clientOrderId: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected'; - fills: Fill[]; - rejectionReason?: string; - timestamp: number; - strategyId?: string; -} -/** A committed order report and only the new fills from that transaction. */ -export interface ExecutionChange { - report: ExecutionReport; - fills: Fill[]; -} -export interface Position { - symbol: string; - quantity: number; - averagePrice: number; - realizedPnl: number; -} -export interface Quote { - bid: number; - ask: number; - bidSize: number; - askSize: number; - timestamp: number; - eventId: string; -} -export interface Account { - /** Account-row-locked journal sequence, safe integer checked before increment. */ - strategySequence?: number; - inputSequence?: number; - admittedTimes?: Record; - initialCapital: number; - cash: number; - realizedPnl: number; - dailyPnl: number; - day: string; - commission: number; - slippage: number; - limits: RiskLimits; - maxQuoteAgeMs: number; - positions: Record; - quotes: Record; - strategyPositions: Record>; -} -export interface StoredOrder { - request: OrderRequest; - report: ExecutionReport; - fingerprint: string; - policy: { commission: number; slippage: number }; -} -export const terminal = (status: ExecutionReport['status']) => - ['filled', 'cancelled', 'rejected'].includes(status); -type DecimalValue = ConstructorParameters[0]; -export const decimal = (value: DecimalValue) => new Decimal(value); -export function amount(value: DecimalValue) { - const result = decimal(value).toDecimalPlaces(8).toNumber(); - if (!Number.isFinite(result)) { - throw new Error('Non-finite accounting value'); - } - return result; -} -export function identity(data: MarketData): string { - return data.eventId ?? createHash('sha256').update(JSON.stringify(data)).digest('hex'); -} -export function fingerprint(order: OrderRequest, strategyId?: string) { - return JSON.stringify([ - order.symbol, - order.side, - order.quantity, - order.orderType, - order.limitPrice ?? null, - order.stopPrice ?? null, - order.timeInForce, - strategyId ?? null, - ]); -} -export function applyFill( - account: Account, - symbol: string, - side: 'buy' | 'sell', - fill: Omit -): Fill { - const old = account.positions[symbol] ?? { symbol, quantity: 0, averagePrice: 0, realizedPnl: 0 }; - const signed = decimal(fill.quantity).times(side === 'buy' ? 1 : -1); - const next = decimal(old.quantity).plus(signed); - const closes = old.quantity !== 0 && Math.sign(old.quantity) !== Math.sign(signed.toNumber()); - const closed = closes ? Math.min(Math.abs(old.quantity), fill.quantity) : 0; - const pnl = amount( - decimal(fill.price) - .minus(old.averagePrice) - .times(closed) - .times(Math.sign(old.quantity)) - .minus(fill.commission) - ); - let averagePrice = old.averagePrice; - if (next.isZero()) { - averagePrice = 0; - } else if (!closes) { - averagePrice = amount( - decimal(old.averagePrice) - .times(Math.abs(old.quantity)) - .plus(decimal(fill.price).times(fill.quantity)) - .div(next.abs()) - ); - } else if (Math.sign(next.toNumber()) !== Math.sign(old.quantity)) { - averagePrice = fill.price; - } - account.positions[symbol] = { - symbol, - quantity: amount(next), - averagePrice, - realizedPnl: amount(decimal(old.realizedPnl).plus(pnl)), - }; - account.cash = amount( - decimal(account.cash).minus(signed.times(fill.price)).minus(fill.commission) - ); - account.realizedPnl = amount(decimal(account.realizedPnl).plus(pnl)); - account.dailyPnl = amount(decimal(account.dailyPnl).plus(pnl)); - return { ...fill, pnl }; -} -export function accountMetrics(account: Account) { - let marketValue = decimal(0), - grossExposure = decimal(0), - unrealized = decimal(0); - for (const position of Object.values(account.positions)) { - const quote = account.quotes[position.symbol]; - const mark = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice; - marketValue = marketValue.plus(decimal(position.quantity).times(mark)); - grossExposure = grossExposure.plus(decimal(position.quantity).abs().times(mark)); - unrealized = unrealized.plus( - decimal(mark).minus(position.averagePrice).times(position.quantity) - ); - } - return { - cash: account.cash, - realizedPnl: account.realizedPnl, - unrealizedPnl: amount(unrealized), - equity: amount(decimal(account.cash).plus(marketValue)), - grossExposure: amount(grossExposure), - dailyPnl: account.dailyPnl, - }; -} -/** The same stored pricing policy values both fills and their unpaid commissions. */ -export function fillPrice(order: StoredOrder, quote: Quote) { - const raw = - order.request.side === 'buy' - ? quote.ask * (1 + order.policy.slippage) - : quote.bid * (1 - order.policy.slippage); - return amount( - order.request.orderType === 'limit' - ? order.request.side === 'buy' - ? Math.min(raw, defined(order.request.limitPrice)) - : Math.max(raw, defined(order.request.limitPrice)) - : raw - ); -} -/** Quantities are shares; exposure/loss limits are account-currency notional amounts. */ -export function riskViolations( - account: Account, - request: OrderRequest, - reservations: StoredOrder[], - price: number, - timestamp: number, - commission: number -): string[] { - const violations: string[] = []; - if (request.quantity > account.limits.maxOrderSize) { - violations.push('Order quantity limit'); - } - const current = account.positions[request.symbol]?.quantity ?? 0; - const signed = request.side === 'buy' ? request.quantity : -request.quantity; - const reducing = current * signed < 0 && Math.abs(signed) <= Math.abs(current); - if (account.dailyPnl <= -account.limits.maxDailyLoss && !reducing) { - violations.push('Daily loss limit'); - } - const quantities = new Map(); - for (const p of Object.values(account.positions)) { - quantities.set(p.symbol, { long: p.quantity, short: p.quantity }); - } - const proposed = current + signed; - quantities.set(request.symbol, { long: proposed, short: proposed }); - // Paid fees already reduce equity. Reserve only the remaining, unpaid liability. - let unpaidFees = decimal(amount(decimal(request.quantity).times(price).times(commission))); - for (const order of reservations) { - if (terminal(order.report.status)) { - continue; - } - const qty = amount( - decimal(order.request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0)) - ); - const quote = account.quotes[order.request.symbol]; - if (quote) { - unpaidFees = unpaidFees.plus( - amount(decimal(qty).times(fillPrice(order, quote)).times(order.policy.commission)) - ); - } - const q = quantities.get(order.request.symbol) ?? { long: 0, short: 0 }; - if (order.request.side === 'buy') { - q.long = amount(decimal(q.long).plus(qty)); - } else { - q.short = amount(decimal(q.short).minus(qty)); - } - quantities.set(order.request.symbol, q); - } - let gross = decimal(0); - for (const [symbol, q] of quantities) { - const quantity = Math.max(Math.abs(q.long), Math.abs(q.short)); - if (!quantity) { - continue; - } - const quote = account.quotes[symbol]; - if (quote && timestamp - quote.timestamp > account.maxQuoteAgeMs && !reducing) { - violations.push(`Stale valuation for ${symbol}`); - } - const mark = symbol === request.symbol ? Math.max(price, quote?.ask ?? price) : quote?.ask; - if (!mark || !Number.isFinite(mark)) { - violations.push(`Missing valuation for ${symbol}`); - continue; - } - const exposure = decimal(quantity).times(mark); - if (quantity > account.limits.maxPositionSize && !(reducing && symbol === request.symbol)) { - violations.push(`Position quantity limit: ${symbol}`); - } - if (exposure.gt(account.limits.maxSymbolExposure) && !(reducing && symbol === request.symbol)) { - violations.push(`Symbol notional limit: ${symbol}`); - } - gross = gross.plus(exposure); - } - if (gross.gt(account.limits.maxGrossExposure) && !reducing) { - violations.push('Gross notional limit'); - } - if (gross.plus(unpaidFees).gt(Math.max(0, accountMetrics(account).equity)) && !reducing) { - violations.push('Unlevered capital exposure limit'); - } - return violations; -} diff --git a/apps/stock/orchestrator/src/execution/repository.ts b/apps/stock/orchestrator/src/execution/repository.ts deleted file mode 100644 index eae5b83b..00000000 --- a/apps/stock/orchestrator/src/execution/repository.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { Account, Fill, StoredOrder } from './model'; -import type { - MarketInput, - StrategyCheckpoint, - StrategyJournalEvent, - StrategyJournalPayload, - StrategyOrderIntent, -} from './strategy-recovery'; - -export interface ExecutionTransaction { - account: Account; - findOrder(clientOrderId: string): Promise; - getOrder(orderId: string): Promise; - openOrders(): Promise; - putOrder(order: StoredOrder): Promise; - insertFill(orderId: string, fill: Fill): Promise; - recordEvent(eventId: string, fingerprint: string): Promise; - appendJournal(payload: StrategyJournalPayload): Promise; - nextJournal(cursor: number): Promise; - strategies(): Promise; - putStrategy(checkpoint: StrategyCheckpoint): Promise; - putIntent(intent: StrategyOrderIntent): Promise; - nextIntent(): Promise; - nextInput(): Promise; - putInput(input: MarketInput): Promise; -} -export interface ExecutionRepository { - initialize(accountId: string, initial: Account): Promise; - transact(accountId: string, work: (tx: ExecutionTransaction) => Promise): Promise; -} -export class ExecutionConflictError extends Error {} diff --git a/apps/stock/orchestrator/src/execution/strategy-recovery.ts b/apps/stock/orchestrator/src/execution/strategy-recovery.ts deleted file mode 100644 index 508d4642..00000000 --- a/apps/stock/orchestrator/src/execution/strategy-recovery.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { createHash } from 'node:crypto'; -import { canonicalJson } from '../canonical-json'; -import type { MarketData, OrderRequest, StrategyConfig } from '../types'; -import type { Account, ExecutionReport, Fill } from './model'; - -export { canonicalJson } from '../canonical-json'; -export function strategyConfigHash(config: StrategyConfig, version: string): string { - const { enabled: _enabled, ...definition } = config; - return createHash('sha256').update(canonicalJson({ definition, version })).digest('hex'); -} -export type StrategyJournalPayload = { account: Account } & ( - | { kind: 'market'; market: MarketData; recipients: string[] } - | { kind: 'execution'; report: ExecutionReport; fills: Fill[] } -); -export type StrategyJournalEvent = { sequence: number; payload: StrategyJournalPayload }; -export interface MarketInput { - id: string; - sequence: number; - market: MarketData; - status: 'pending' | 'applied'; -} -export interface StrategyCheckpoint { - strategyId: string; - config: StrategyConfig; - configHash: string; - version: string; - enabled: boolean; - cursor: number; - state: unknown; -} -export interface StrategyOrderIntent { - clientOrderId: string; - strategyId: string; - sequence: number; - request: OrderRequest; - status: 'pending' | 'dispatched'; - orderId?: string; -} -export interface RecoverableStrategy { - getConfig(): Readonly; - getCheckpointVersion(): string | undefined; - captureCheckpoint(): unknown; - restoreCheckpoint(state: unknown): void; - onMarketData(data: MarketData): Promise; - onFill( - fill: Fill & { orderId: string; symbol: string; side: 'buy' | 'sell'; strategyId?: string } - ): Promise; - onOrderUpdate(report: ExecutionReport): Promise; -} diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index 7367f1f9..216551db 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -5,7 +5,7 @@ import { Hono } from 'hono'; import { cors } from 'hono/cors'; -import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di'; +import { createHttpSecurity, httpSecurityOptions } from '@stock-bot/di/http-security'; import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; diff --git a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts b/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts deleted file mode 100644 index c85b7f52..00000000 --- a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts +++ /dev/null @@ -1,342 +0,0 @@ -import { - IncrementalEMA, - IncrementalRSI, - IncrementalSMA, - TechnicalIndicators, -} from '@stock-bot/engine'; -import { at } from '@stock-bot/invariants'; - -export interface MacdResult { - macd: number[]; - signal: number[]; - histogram: number[]; -} -export interface BollingerBandsResult { - middle: number[]; - upper: number[]; - lower: number[]; -} -export interface StochasticResult { - k: number[]; - d: number[]; -} - -/** - * Wrapper class for the Rust TA library with TypeScript-friendly interfaces - */ -export class TechnicalAnalysis { - private indicators: TechnicalIndicators; - - constructor() { - this.indicators = new TechnicalIndicators(); - } - - // Simple indicators - sma(values: number[], period: number): number[] { - return this.indicators.calculateSma(values, period); - } - - ema(values: number[], period: number): number[] { - return this.indicators.calculateEma(values, period); - } - - rsi(values: number[], period: number): number[] { - return this.indicators.calculateRsi(values, period); - } - - atr(high: number[], low: number[], close: number[], period: number): number[] { - return this.indicators.calculateAtr(high, low, close, period); - } - - // Complex indicators with parsed results - macd(values: number[], fastPeriod = 12, slowPeriod = 26, signalPeriod = 9): MacdResult { - const result = this.indicators.calculateMacd(values, fastPeriod, slowPeriod, signalPeriod); - return JSON.parse(result); - } - - bollingerBands(values: number[], period = 20, stdDev = 2): BollingerBandsResult { - const result = this.indicators.calculateBollingerBands(values, period, stdDev); - return JSON.parse(result); - } - - stochastic( - high: number[], - low: number[], - close: number[], - kPeriod = 14, - dPeriod = 3, - smoothK = 1 - ): StochasticResult { - const result = this.indicators.calculateStochastic(high, low, close, kPeriod, dPeriod, smoothK); - return JSON.parse(result); - } - - // Helper to get the latest value from an indicator array - static latest(values: number[]): number | undefined { - return values[values.length - 1]; - } - - // Helper to check for crossovers - static crossover(series1: number[], series2: number[]): boolean { - if (series1.length < 2 || series2.length < 2) { - return false; - } - const prev1 = at(series1, series1.length - 2); - const curr1 = at(series1, series1.length - 1); - const prev2 = at(series2, series2.length - 2); - const curr2 = at(series2, series2.length - 1); - return prev1 <= prev2 && curr1 > curr2; - } - - static crossunder(series1: number[], series2: number[]): boolean { - if (series1.length < 2 || series2.length < 2) { - return false; - } - const prev1 = at(series1, series1.length - 2); - const curr1 = at(series1, series1.length - 1); - const prev2 = at(series2, series2.length - 2); - const curr2 = at(series2, series2.length - 1); - return prev1 >= prev2 && curr1 < curr2; - } -} - -/** - * Incremental indicator manager for streaming data - */ -export class IncrementalIndicators { - private indicators: Map = new Map(); - - createSMA(key: string, period: number): IncrementalSMA { - const indicator = new IncrementalSMA(period); - this.indicators.set(key, indicator); - return indicator; - } - - createEMA(key: string, period: number): IncrementalEMA { - const indicator = new IncrementalEMA(period); - this.indicators.set(key, indicator); - return indicator; - } - - createRSI(key: string, period: number): IncrementalRSI { - const indicator = new IncrementalRSI(period); - this.indicators.set(key, indicator); - return indicator; - } - - get(key: string): IncrementalSMA | IncrementalEMA | IncrementalRSI | undefined { - return this.indicators.get(key); - } - - update(key: string, value: number): number | null { - const indicator = this.indicators.get(key); - if (!indicator) { - throw new Error(`Indicator ${key} not found`); - } - return indicator.update(value); - } - - current(key: string): number | null { - const indicator = this.indicators.get(key); - if (!indicator) { - throw new Error(`Indicator ${key} not found`); - } - return indicator.current(); - } - - reset(key: string): void { - const indicator = this.indicators.get(key); - if (indicator && 'reset' in indicator) { - indicator.reset(); - } - } - - entries() { - return this.indicators.entries(); - } - - deletePrefix(prefix: string): void { - for (const key of this.indicators.keys()) { - if (key.startsWith(prefix)) { - this.indicators.delete(key); - } - } - } - - resetAll(): void { - this.indicators.forEach(indicator => { - if ('reset' in indicator) { - indicator.reset(); - } - }); - } -} - -/** - * Signal generator using technical indicators - */ -export interface TradingSignal { - symbol: string; - timestamp: number; - action: 'BUY' | 'SELL' | 'HOLD'; - strength: number; // 0-1 - indicators: Record; - reason: string; -} - -export class SignalGenerator { - private ta: TechnicalAnalysis; - - constructor() { - this.ta = new TechnicalAnalysis(); - } - - /** - * Generate signals based on multiple indicators - */ - generateSignals( - symbol: string, - prices: { - close: number[]; - high: number[]; - low: number[]; - volume: number[]; - }, - timestamp: number - ): TradingSignal { - const indicators: Record = {}; - let buySignals = 0; - let sellSignals = 0; - let totalWeight = 0; - const reasons: string[] = []; - - // RSI signals - if (prices.close.length >= 14) { - const rsi = this.ta.rsi(prices.close, 14); - const currentRsi = TechnicalAnalysis.latest(rsi); - if (currentRsi !== undefined) { - indicators.rsi = currentRsi; - if (currentRsi < 30) { - buySignals += 2; - totalWeight += 2; - reasons.push('RSI oversold'); - } else if (currentRsi > 70) { - sellSignals += 2; - totalWeight += 2; - reasons.push('RSI overbought'); - } else { - totalWeight += 1; - } - } - } - - // MACD signals - if (prices.close.length >= 26) { - const macd = this.ta.macd(prices.close); - const currentMacd = TechnicalAnalysis.latest(macd.macd); - const currentSignal = TechnicalAnalysis.latest(macd.signal); - const currentHistogram = TechnicalAnalysis.latest(macd.histogram); - - if (currentMacd !== undefined && currentSignal !== undefined) { - indicators.macd = currentMacd; - indicators.macdSignal = currentSignal; - indicators.macdHistogram = currentHistogram || 0; - - if (TechnicalAnalysis.crossover(macd.macd, macd.signal)) { - buySignals += 3; - totalWeight += 3; - reasons.push('MACD bullish crossover'); - } else if (TechnicalAnalysis.crossunder(macd.macd, macd.signal)) { - sellSignals += 3; - totalWeight += 3; - reasons.push('MACD bearish crossover'); - } else { - totalWeight += 1; - } - } - } - - // Bollinger Bands signals - if (prices.close.length >= 20) { - const bb = this.ta.bollingerBands(prices.close, 20, 2); - const currentPrice = at(prices.close, prices.close.length - 1); - const currentUpper = TechnicalAnalysis.latest(bb.upper); - const currentLower = TechnicalAnalysis.latest(bb.lower); - const currentMiddle = TechnicalAnalysis.latest(bb.middle); - - if (currentUpper && currentLower && currentMiddle) { - indicators.bbUpper = currentUpper; - indicators.bbLower = currentLower; - indicators.bbMiddle = currentMiddle; - - const bbPercent = (currentPrice - currentLower) / (currentUpper - currentLower); - indicators.bbPercent = bbPercent; - - if (bbPercent < 0.2) { - buySignals += 2; - totalWeight += 2; - reasons.push('Near lower Bollinger Band'); - } else if (bbPercent > 0.8) { - sellSignals += 2; - totalWeight += 2; - reasons.push('Near upper Bollinger Band'); - } else { - totalWeight += 1; - } - } - } - - // Stochastic signals - if (prices.high.length >= 14 && prices.low.length >= 14 && prices.close.length >= 14) { - const stoch = this.ta.stochastic(prices.high, prices.low, prices.close, 14, 3, 3); - const currentK = TechnicalAnalysis.latest(stoch.k); - const currentD = TechnicalAnalysis.latest(stoch.d); - - if (currentK !== undefined && currentD !== undefined) { - indicators.stochK = currentK; - indicators.stochD = currentD; - - if (currentK < 20 && currentD < 20) { - buySignals += 1; - totalWeight += 1; - reasons.push('Stochastic oversold'); - } else if (currentK > 80 && currentD > 80) { - sellSignals += 1; - totalWeight += 1; - reasons.push('Stochastic overbought'); - } else { - totalWeight += 1; - } - } - } - - // Determine overall signal - let action: 'BUY' | 'SELL' | 'HOLD' = 'HOLD'; - let strength = 0; - - if (totalWeight > 0) { - const buyStrength = buySignals / totalWeight; - const sellStrength = sellSignals / totalWeight; - - if (buyStrength > 0.5) { - action = 'BUY'; - strength = buyStrength; - } else if (sellStrength > 0.5) { - action = 'SELL'; - strength = sellStrength; - } else { - action = 'HOLD'; - strength = Math.max(buyStrength, sellStrength); - } - } - - return { - symbol, - timestamp, - action, - strength, - indicators, - reason: reasons.join('; ') || 'No clear signal', - }; - } -} diff --git a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts index 5770c2c8..ac7175c8 100644 --- a/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts +++ b/apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from 'node:crypto'; import type { PaperDeploymentBinding } from '@stock-bot/stock-config/paper-deployments'; import { canonicalJson } from '../canonical-json'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import { paperActivationSchema, paperConnectionSchema, @@ -13,7 +13,7 @@ import { type PaperFrameInput, type PaperReadiness, type PaperRuntime, -} from '../contracts/paper-runtime'; +} from '@stock-bot/stock-config/paper-runtime'; import type { CanonicalAccount, CanonicalExecutionRepository, diff --git a/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts index 538340cf..c52aeaa6 100644 --- a/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts +++ b/apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts @@ -1,6 +1,6 @@ import { z } from 'zod'; import type { PaperDeploymentStatus } from '@stock-bot/stock-config/paper-deployments'; -import type { PaperReadiness, PaperRuntime } from '../contracts/paper-runtime'; +import type { PaperReadiness, PaperRuntime } from '@stock-bot/stock-config/paper-runtime'; import type { CanonicalExecutionRepository, CanonicalPostgres } from '../execution/canonical-paper'; import { authorizedPaperPackage, @@ -8,9 +8,9 @@ import { paperHash, readPaperDeployment, verifyPaperEvidenceCustody, -} from './paper-deployment-custody'; +} from '@stock-bot/trading-runtime/paper-deployment-custody'; import type { createPromotedPaperRuntime } from './paper-host'; -import { paperHostUrl, readPaperHostIdentity } from './paper-host-identity'; +import { paperHostUrl, readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity'; export const unboundPaperReadiness = (reason = 'deployment-not-bound'): PaperReadiness => ({ configured: false, diff --git a/apps/stock/orchestrator/src/paper/PaperTradingManager.ts b/apps/stock/orchestrator/src/paper/PaperTradingManager.ts deleted file mode 100644 index deedd9bf..00000000 --- a/apps/stock/orchestrator/src/paper/PaperTradingManager.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { EventEmitter } from 'node:events'; -import type { ExecutionService } from '../services/ExecutionService'; -import type { MarketDataService } from '../services/MarketDataService'; -import type { StorageService } from '../services/StorageService'; -import type { OrchestratorServices, OrderRequest } from '../types'; - -/** Compatibility facade: no independent simulator, balance, or position book. */ -export class PaperTradingManager extends EventEmitter { - constructor( - _container: OrchestratorServices, - _storage: StorageService, - _market: MarketDataService, - private readonly execution: ExecutionService, - _initialBalance = 100000 - ) { - super(); - } - executeOrder(order: OrderRequest) { - return this.execution.submitOrder(order); - } - updateMarketPrice( - symbol: string, - bid: number, - ask: number, - eventId: string, - timestamp: number, - size: number - ) { - return this.execution.onMarketData({ - type: 'quote', - eventId, - data: { symbol, bid, ask, bidSize: size, askSize: size, timestamp }, - }); - } - getAccount() { - return this.execution.getAccount(); - } - getAllPositions() { - return this.execution.getPositions(); - } - async getPosition(symbol: string) { - return (await this.getAllPositions()).find(p => p.symbol === symbol); - } - async getPerformanceMetrics() { - const account = await this.getAccount(); - return { - cash: account.cash, - currentEquity: account.equity, - netPnl: account.realizedPnl + account.unrealizedPnl, - realizedPnl: account.realizedPnl, - unrealizedPnl: account.unrealizedPnl, - }; - } - checkPendingOrders() { - throw new Error('Pending orders are processed only by ordered market events'); - } - reset() { - throw new Error('Implicit paper account reset is disabled; use a new account ID'); - } -} diff --git a/apps/stock/orchestrator/src/paper/feed.ts b/apps/stock/orchestrator/src/paper/feed.ts index 02cd6f5d..f442da56 100644 --- a/apps/stock/orchestrator/src/paper/feed.ts +++ b/apps/stock/orchestrator/src/paper/feed.ts @@ -6,14 +6,14 @@ import { compareEventKeys, matchingCommandSchema, type CanonicalMatchingCommand, -} from '../contracts/canonical-execution'; +} from '@stock-bot/stock-config/canonical-execution'; import { paperFrameSchema, PaperRuntimeError, type PaperConfiguration, type PaperFrame, type PaperFrameInput, -} from '../contracts/paper-runtime'; +} from '@stock-bot/stock-config/paper-runtime'; import type { CanonicalAccount, CanonicalPaperInput } from '../execution/canonical-paper'; type Observation = PaperFrame['observations'][number]; diff --git a/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts b/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts deleted file mode 100644 index bdf86147..00000000 --- a/apps/stock/orchestrator/src/paper/paper-deployment-custody.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ -export * from '@stock-bot/trading-runtime/paper-deployment-custody'; diff --git a/apps/stock/orchestrator/src/paper/paper-host-identity.ts b/apps/stock/orchestrator/src/paper/paper-host-identity.ts deleted file mode 100644 index ede54088..00000000 --- a/apps/stock/orchestrator/src/paper/paper-host-identity.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Shared read-only artifact inspection. */ -export * from '@stock-bot/trading-runtime/paper-host-identity'; diff --git a/apps/stock/orchestrator/src/paper/paper-host.ts b/apps/stock/orchestrator/src/paper/paper-host.ts index fd6b2918..fc6aa03a 100644 --- a/apps/stock/orchestrator/src/paper/paper-host.ts +++ b/apps/stock/orchestrator/src/paper/paper-host.ts @@ -5,8 +5,8 @@ import type { StrategyVersionPackage } from '@stock-bot/types'; import type { CanonicalExecutionRepository } from '../execution/canonical-paper'; import { importRetainedProgram } from '../strategies/retained-program'; import { CanonicalPaperRuntime } from './CanonicalPaperRuntime'; -import { retainedPaperDeployment } from './paper-deployment-custody'; -import { verifyPaperHostBuild } from './paper-host-identity'; +import { retainedPaperDeployment } from '@stock-bot/trading-runtime/paper-deployment-custody'; +import { verifyPaperHostBuild } from '@stock-bot/trading-runtime/paper-host-identity'; /** Caller must have verified the immutable operator promotion and current permission before calling. */ export async function createPromotedPaperRuntime(options: { diff --git a/apps/stock/orchestrator/src/paper/paper-operator.ts b/apps/stock/orchestrator/src/paper/paper-operator.ts deleted file mode 100644 index 4af8480f..00000000 --- a/apps/stock/orchestrator/src/paper/paper-operator.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ -export * from '@stock-bot/trading-runtime/paper-operator'; diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index 10873897..34cd3758 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -1,14 +1,12 @@ import { Hono } from 'hono'; -import type { Server as SocketIOServer } from 'socket.io'; import { orchestratorDiagnosticSchema, paperDiagnosticSchema, } from '@stock-bot/stock-config/diagnostics'; -import { createAnalyticsRoutes } from '../api/rest/analytics'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { createBacktestRoutes } from '../api/rest/backtest'; import { createPaperRoutes } from '../api/rest/paper'; import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments'; -import { readCanonicalBuildIdentity } from '../backtest/canonical-build'; import type { OrchestratorServices as IServiceContainer } from '../types'; /** @@ -16,7 +14,7 @@ import type { OrchestratorServices as IServiceContainer } from '../types'; */ export function createRoutes( services: IServiceContainer, - _io?: SocketIOServer, + _io?: unknown, origins?: readonly string[] ): Hono { const app = new Hono(); @@ -106,7 +104,6 @@ export function createRoutes( ); app.route('/api/orders', unavailable); app.route('/api/positions', unavailable); - app.route('/api/analytics', createAnalyticsRoutes(services)); app.route('/api/backtest', createBacktestRoutes(services)); // Add request logging middleware diff --git a/apps/stock/orchestrator/src/services/AnalyticsService.ts b/apps/stock/orchestrator/src/services/AnalyticsService.ts deleted file mode 100644 index 35605d19..00000000 --- a/apps/stock/orchestrator/src/services/AnalyticsService.ts +++ /dev/null @@ -1,197 +0,0 @@ -import axios, { type AxiosRequestConfig } from 'axios'; -import { z } from 'zod'; -import { - backtestAnalysisSchema, - correlationRequestSchema, - correlationResponseSchema, - dateRangeSchema, - optimizationRequestSchema, - PerformanceMetricsSchema, - portfolioWeightsSchema, - predictionRequestSchema, - predictionResponseSchema, - regimeResponseSchema, - RiskMetricsSchema, - type OptimizationParams, -} from '../contracts/analytics'; -import type { OrchestratorServices } from '../types'; -import { AnalyticsServiceError } from './analytics-error'; - -export interface AnalyticsTransport { - request(config: AxiosRequestConfig): Promise<{ data: unknown }>; -} - -/** Validated, bounded upstream access. Failure is never a fabricated financial observation. */ -export class AnalyticsService { - private readonly client: AnalyticsTransport; - private readonly now: () => number; - private readonly analyticsUrl: string; - private readonly timeoutMs: number; - private readonly cache = new Map(); - constructor( - private readonly container: Pick, - options: { - client?: AnalyticsTransport; - now?: () => number; - baseUrl?: string; - timeoutMs?: number; - } = {} - ) { - this.client = options.client ?? axios; - this.now = options.now ?? Date.now; - this.analyticsUrl = - options.baseUrl ?? process.env.ANALYTICS_SERVICE_URL ?? 'http://localhost:3003'; - this.timeoutMs = options.timeoutMs ?? 5000; - if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 60000) { - throw new Error('Analytics timeout must be an integer between 1 and 60000 ms'); - } - } - async getPerformanceMetrics(portfolioId: string, startDate: Date, endDate: Date) { - const range = dateRangeSchema.parse({ - startDate: startDate.toISOString(), - endDate: endDate.toISOString(), - }); - return this.fetch( - '/analytics/performance/' + encodeURIComponent(portfolioId), - PerformanceMetricsSchema, - { - params: { start_date: range.startDate, end_date: range.endDate }, - cacheKey: JSON.stringify(['performance', portfolioId, range]), - ttl: 60000, - } - ); - } - async getRiskMetrics(portfolioId: string) { - return this.fetch('/analytics/risk/' + encodeURIComponent(portfolioId), RiskMetricsSchema, { - cacheKey: JSON.stringify(['risk', portfolioId]), - ttl: 60000, - }); - } - async optimizePortfolio(input: OptimizationParams) { - const request = optimizationRequestSchema.parse(input); - const constraints = request.constraints; - const raw = await this.fetch( - '/optimize/portfolio', - portfolioWeightsSchema.refine( - value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols), - 'Portfolio symbol identity mismatch' - ), - { - data: { - symbols: request.symbols, - returns: request.returns, - constraints: constraints - ? { - min_weight: constraints.minWeight ?? 0, - max_weight: constraints.maxWeight ?? 1, - target_return: constraints.targetReturn, - max_risk: constraints.maxRisk, - } - : undefined, - }, - } - ); - return { - symbols: raw.symbols, - weights: raw.weights, - expectedReturn: raw.expected_return, - expectedRisk: raw.expected_risk, - sharpeRatio: raw.sharpe_ratio, - }; - } - async detectMarketRegime(): Promise { - const result = await this.fetch('/analytics/regime', regimeResponseSchema, { - cacheKey: 'regime', - ttl: 300000, - }); - return result.regime; - } - async calculateCorrelationMatrix(symbols: string[]): Promise { - const request = correlationRequestSchema.parse({ symbols }); - const response = await this.fetch( - '/analytics/correlation', - correlationResponseSchema.refine( - value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols), - 'Correlation symbol identity mismatch' - ), - { data: request.symbols } - ); - return response.matrix; - } - async runBacktestAnalysis(backtestId: string) { - return this.fetch( - '/analytics/backtest/' + encodeURIComponent(backtestId), - backtestAnalysisSchema.refine( - value => value.backtest_id === backtestId, - 'Backtest identity mismatch' - ) - ); - } - async predictWithModel(modelId: string, features: Record) { - const request = predictionRequestSchema.parse({ modelId, features }); - return this.fetch( - '/models/predict', - predictionResponseSchema.refine( - value => value.model_id === request.modelId, - 'Model identity mismatch' - ), - { data: { model_id: request.modelId, features: request.features } } - ); - } - private async fetch( - path: string, - schema: z.ZodType, - options: { - data?: unknown; - params?: Record; - cacheKey?: string; - ttl?: number; - } = {} - ): Promise { - const key = options.cacheKey; - const cached = key ? this.cache.get(key) : undefined; - if (cached && this.now() < cached.expiresAt) { - return schema.parse(structuredClone(cached.data)); - } - if (key) { - this.cache.delete(key); - } - let response: { data: unknown }; - try { - response = await this.client.request({ - url: this.analyticsUrl + path, - method: options.data === undefined ? 'GET' : 'POST', - params: options.params, - data: options.data, - timeout: this.timeoutMs, - maxContentLength: 1048576, - }); - } catch { - this.container.logger.error('Analytics upstream unavailable', { path }); - throw new AnalyticsServiceError('unavailable'); - } - const parsed = schema.safeParse(response.data); - if (!parsed.success) { - this.container.logger.error('Invalid analytics upstream response', { path }); - throw new AnalyticsServiceError('invalid-response'); - } - if (key) { - for (const [entry, value] of this.cache) { - if (this.now() >= value.expiresAt) { - this.cache.delete(entry); - } - } - if (this.cache.size >= 128) { - const oldest = this.cache.keys().next().value; - if (oldest !== undefined) { - this.cache.delete(oldest); - } - } - this.cache.set(key, { - data: structuredClone(parsed.data), - expiresAt: this.now() + (options.ttl ?? 60000), - }); - } - return structuredClone(parsed.data); - } -} diff --git a/apps/stock/orchestrator/src/services/ExecutionService.ts b/apps/stock/orchestrator/src/services/ExecutionService.ts deleted file mode 100644 index 77fefdf7..00000000 --- a/apps/stock/orchestrator/src/services/ExecutionService.ts +++ /dev/null @@ -1,436 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto'; -import { EventEmitter } from 'node:events'; -import type { TradingEngine } from '@stock-bot/engine'; -import { defined } from '@stock-bot/invariants'; -import { BacktestExecutionRepository } from '../execution/BacktestExecutionRepository'; -import { - accountMetrics, - amount, - decimal, - defaultRiskLimits, - identity, - terminal, - type Account, - type ExecutionChange, - type ExecutionReport, - type Fill, - type Quote, -} from '../execution/model'; -import { PostgresExecutionRepository } from '../execution/PostgresExecutionRepository'; -import { ExecutionConflictError, type ExecutionRepository } from '../execution/repository'; -import { SimulationExecution } from '../execution/SimulationExecution'; -import type { RecoverableStrategy } from '../execution/strategy-recovery'; -import { StrategyRecovery } from '../execution/StrategyRecovery'; -import { - MarketDataSchema, - ModeConfigSchema, - OrderRequestSchema, - type MarketData, - type ModeConfig, - type OrchestratorServices, - type OrderRequest, -} from '../types'; -import type { StorageService } from './StorageService'; - -export type { ExecutionReport, Fill } from '../execution/model'; -export type StrategyOrderUpdate = ExecutionReport; -export interface StrategyFill extends Fill { - orderId: string; - symbol: string; - side: 'buy' | 'sell'; - strategyId?: string; - positionUpdate?: unknown; -} -export class UnsupportedExecutionError extends Error {} - -/** Sole runtime order gateway. Paper state commits atomically; backtests opt into a run-local ledger. */ -export class ExecutionService extends EventEmitter { - private repository?: ExecutionRepository; - private accountId = ''; - private mode: 'paper' | 'backtest' | undefined; - private engine?: TradingEngine; - private observer?: (report: ExecutionReport, fills: StrategyFill[]) => Promise; - private tail: Promise = Promise.resolve(); - private closing = false; - private readonly simulation: SimulationExecution; - private readonly recovery: StrategyRecovery; - requiresDurableCheckpoint(): boolean { - return this.mode === 'paper'; - } - constructor( - private readonly container: OrchestratorServices, - _storage: StorageService, - private readonly options: { - repository?: ExecutionRepository; - clock?: () => number; - allowedMode?: 'paper' | 'backtest'; - } = {} - ) { - super(); - this.simulation = new SimulationExecution({ - now: quote => this.now(quote), - isBacktest: () => this.mode === 'backtest', - }); - this.recovery = new StrategyRecovery({ - accountId: () => this.accountId, - isBacktest: () => this.mode === 'backtest', - serialized: work => this.serialized(work), - transact: work => this.store().transact(this.accountId, work), - dispatch: (tx, intent) => - this.simulation.acceptOrder(tx, intent.request, intent.strategyId, true), - publish: change => this.publish(change), - consumeMarketInput: () => this.consumeMarketInput(), - observationFailed: error => - this.container.logger.error('Strategy observation failed after checkpoint commit', { - error, - }), - }); - } - - setObserver(observer: (report: ExecutionReport, fills: StrategyFill[]) => Promise) { - this.observer = observer; - } - async initialize(input: ModeConfig, engine: TradingEngine): Promise { - const config = ModeConfigSchema.parse(input); - if (config.mode === 'live') { - throw new UnsupportedExecutionError( - 'Live trading is disabled: no real broker adapter exists' - ); - } - if (this.options.allowedMode && config.mode !== this.options.allowedMode) { - throw new UnsupportedExecutionError( - `Runtime composition only permits ${this.options.allowedMode} mode; cannot initialize ${config.mode}` - ); - } - await this.tail; - this.closing = false; - this.mode = undefined; - const repository = - this.options.repository ?? - (config.mode === 'backtest' - ? new BacktestExecutionRepository() - : this.container.postgres - ? new PostgresExecutionRepository(this.container.postgres) - : undefined); - if (!repository) { - throw new UnsupportedExecutionError( - 'Paper execution requires the PostgreSQL simulation ledger' - ); - } - if (config.mode === 'paper' && repository instanceof BacktestExecutionRepository) { - throw new UnsupportedExecutionError('Run-local storage cannot back a paper account'); - } - const now = this.options.clock?.() ?? Date.now(); - const initialCapital = config.mode === 'paper' ? config.startingCapital : config.initialCapital; - const account: Account = { - initialCapital, - cash: initialCapital, - realizedPnl: 0, - dailyPnl: 0, - day: new Date(now).toISOString().slice(0, 10), - commission: config.commission ?? 0.001, - slippage: config.slippage ?? 0.0001, - limits: config.riskLimits ?? { ...defaultRiskLimits }, - maxQuoteAgeMs: - config.mode === 'paper' ? (config.maxQuoteAgeMs ?? 60000) : Number.MAX_SAFE_INTEGER, - positions: {}, - quotes: {}, - strategyPositions: {}, - }; - const id = - config.mode === 'paper' - ? (config.accountId ?? 'paper-default') - : (config.runId ?? randomUUID()); - await repository.initialize(id, account); - this.repository = repository; - this.accountId = id; - this.mode = config.mode; - this.engine = engine; - engine.updateRiskLimits(account.limits); - } - private serialized(work: () => Promise): Promise { - const result = this.tail.then(work); - this.tail = result.catch(() => {}); - return result; - } - private store() { - this.recovery.assertExternalIO(); - if (!this.repository || !this.mode || this.closing) { - throw new UnsupportedExecutionError( - 'Execution gateway is not initialized or is shutting down' - ); - } - return this.repository; - } - private now(quote?: Quote) { - return this.mode === 'backtest' - ? (quote?.timestamp ?? 0) - : (this.options.clock?.() ?? Date.now()); - } - async submitOrder( - input: OrderRequest, - context: { strategyId?: string } = {} - ): Promise { - this.recovery.assertExternalIO(); - const request = OrderRequestSchema.parse(input); - // The API must supply stable IDs for retried requests; strategy IDs are derived from source events. - request.clientOrderId ??= randomUUID(); - return this.serialized(async () => { - const change = await this.store().transact(this.accountId, async tx => { - return this.simulation.acceptOrder(tx, request, context.strategyId); - }); - await this.publish(change); - return change.report; - }); - } - /** Durable admission precedes processing; a strategy failure cannot discard later inputs. */ - async enqueueMarketData(input: MarketData): Promise { - const data = MarketDataSchema.parse(input); - return this.serialized(() => - this.store().transact(this.accountId, async tx => { - const key = identity(data); - const hash = createHash('sha256').update(JSON.stringify(data)).digest('hex'); - if (!(await tx.recordEvent(key, hash))) { - return false; - } - const quote = this.quoteFor(data); - const previous = - tx.account.admittedTimes?.[data.data.symbol] ?? - tx.account.quotes[data.data.symbol]?.timestamp; - if (previous !== undefined && quote.timestamp < previous) { - throw new ExecutionConflictError('Out-of-order market data'); - } - if (this.mode === 'paper' && !this.freshQuote(tx.account, quote)) { - throw new Error('Stale or future market data'); - } - const sequence = (tx.account.inputSequence ?? 0) + 1; - if (!Number.isSafeInteger(sequence)) { - throw new Error('Market input sequence exhausted'); - } - tx.account.inputSequence = sequence; - (tx.account.admittedTimes ??= {})[data.data.symbol] = quote.timestamp; - await tx.putInput({ id: key, sequence, market: data, status: 'pending' }); - return true; - }) - ); - } - - async onMarketData(input: MarketData): Promise { - const admitted = await this.enqueueMarketData(input); - await this.serialized(async () => { - while (await this.consumeMarketInput()) { - /* drain unblocked inputs */ - } - }); - return admitted; - } - - private quoteFor(data: MarketData): Quote { - const quote: Quote = - data.type === 'quote' - ? { ...data.data, eventId: identity(data) } - : { - bid: data.type === 'bar' ? data.data.close : data.data.price, - ask: data.type === 'bar' ? data.data.close : data.data.price, - bidSize: data.type === 'bar' ? data.data.volume : data.data.size, - askSize: data.type === 'bar' ? data.data.volume : data.data.size, - timestamp: data.data.timestamp, - eventId: identity(data), - }; - if ( - ![quote.bid, quote.ask, quote.bidSize, quote.askSize, quote.timestamp].every( - Number.isFinite - ) || - quote.bid <= 0 || - quote.ask < quote.bid || - quote.bidSize < 0 || - quote.askSize < 0 - ) { - throw new Error('Invalid market quote/liquidity'); - } - return quote; - } - private freshQuote(account: Account, quote: Quote) { - const now = this.now(quote); - return quote.timestamp <= now && now - quote.timestamp <= account.maxQuoteAgeMs; - } - - private async consumeMarketInput(): Promise { - const outcome = await this.store().transact(this.accountId, async tx => { - const registrations = await tx.strategies(); - if ( - (await tx.nextIntent()) || - registrations.some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0)) - ) { - return undefined; - } - const input = await tx.nextInput(); - if (!input) { - return undefined; - } - const data = input.market, - quote = this.quoteFor(data); - this.simulation.rollDay(tx.account, quote.timestamp); - tx.account.quotes[data.data.symbol] = quote; - const orders = await tx.openOrders(), - changes: ExecutionChange[] = []; - for (const order of orders) { - const before = order.report.status; - const expired = - order.request.timeInForce === 'DAY' && - new Date(order.report.timestamp).toISOString().slice(0, 10) < - new Date(quote.timestamp).toISOString().slice(0, 10); - if (expired) { - order.report.status = 'cancelled'; - } - // Recovery must not fill paper orders on quotes that have become stale. - const fills = - !expired && - order.request.symbol === data.data.symbol && - this.freshQuote(tx.account, quote) - ? await this.simulation.fill(tx, order, quote, orders) - : []; - await tx.putOrder(order); - if (fills.length || before !== order.report.status) { - const change = { report: order.report, fills }; - changes.push(change); - await this.simulation.journalChange(tx, change); - } - } - await tx.appendJournal({ - kind: 'market', - market: data, - recipients: registrations.filter(s => s.enabled).map(s => s.strategyId), - account: structuredClone(tx.account), - }); - await tx.putInput({ ...input, status: 'applied' }); - return changes; - }); - if (!outcome) { - return false; - } - for (const change of outcome) { - await this.publish(change); - } - return true; - } - async cancelOrder(id: string): Promise { - return this.serialized(async () => { - const change = await this.store().transact(this.accountId, async tx => { - const order = await tx.getOrder(id); - if (!order || terminal(order.report.status)) { - return undefined; - } - order.report.status = 'cancelled'; - await tx.putOrder(order); - const change = { report: order.report, fills: [] }; - await this.simulation.journalChange(tx, change); - return change; - }); - if (change) { - await this.publish(change); - } - return !!change; - }); - } - async getOrderStatus(id: string) { - return this.store().transact( - this.accountId, - async tx => (await tx.getOrder(id))?.report ?? null - ); - } - async getAccount() { - const decisionAccount = this.recovery.decisionAccount(); - if (decisionAccount) { - return decisionAccount; - } - return this.store().transact(this.accountId, async tx => ({ - ...tx.account, - ...accountMetrics(tx.account), - })); - } - async getStrategySnapshot(id: string) { - return this.store().transact(this.accountId, async tx => ({ - positions: tx.account.strategyPositions[id] ?? {}, - orders: (await tx.openOrders()).filter(o => o.report.strategyId === id), - })); - } - async getPositions() { - const account = await this.getAccount(); - return Object.values(account.positions).map(p => ({ - ...p, - unrealizedPnl: amount( - decimal( - account.quotes[p.symbol] - ? (defined(account.quotes[p.symbol]).bid + defined(account.quotes[p.symbol]).ask) / 2 - : p.averagePrice - ) - .minus(p.averagePrice) - .times(p.quantity) - ), - })); - } - captureStrategyOrder(request: OrderRequest, strategyId: string): void { - this.recovery.captureStrategyOrder(request, strategyId); - } - afterStrategyCommit(observation: () => void): void { - this.recovery.afterStrategyCommit(observation); - } - getRecoveryStatus() { - return this.recovery.getRecoveryStatus(); - } - registerStrategy(strategy: RecoverableStrategy): Promise { - return this.recovery.registerStrategy(strategy); - } - registeredStrategies() { - return this.recovery.registeredStrategies(); - } - pauseStrategy(strategyId: string): Promise { - return this.recovery.pauseStrategy(strategyId); - } - recoverStrategies(strategies: RecoverableStrategy[]): Promise { - return this.recovery.recoverStrategies(strategies); - } - private async publish(change: ExecutionChange) { - const fills = change.fills.map(fill => ({ - ...fill, - orderId: change.report.orderId, - symbol: change.report.symbol, - side: change.report.side, - strategyId: change.report.strategyId, - })); - // Native analytics is a run-local projection only. Paper positions always read the SQL ledger. - if (this.mode === 'backtest') { - for (const fill of fills) { - defined(this.engine).advanceTime(fill.timestamp); - defined(this.engine).processFillWithMetadata( - fill.symbol, - fill.price, - fill.quantity, - fill.side, - fill.commission, - fill.orderId, - fill.strategyId ?? null - ); - } - } - try { - await this.observer?.(change.report, fills); - this.emit('orderUpdate', change.report); - for (const fill of fills) { - this.emit('fill', fill); - } - } catch (error) { - this.container.logger.error('Execution observer failed after commit', { error }); - } - } - async routeOrderToExchange(_order: OrderRequest, _exchange: string): Promise { - throw new UnsupportedExecutionError('Exchange/broker routing is disabled'); - } - async shutdown() { - this.closing = true; - await this.tail; - this.mode = undefined; - this.engine = undefined; - } -} diff --git a/apps/stock/orchestrator/src/services/MarketDataService.ts b/apps/stock/orchestrator/src/services/MarketDataService.ts deleted file mode 100644 index 42d95647..00000000 --- a/apps/stock/orchestrator/src/services/MarketDataService.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { EventEmitter } from 'events'; -import { io, Socket } from 'socket.io-client'; -import { defined } from '@stock-bot/invariants'; -import type { Logger } from '@stock-bot/services'; -import { - BarSchema, - MarketDataSchema, - QuoteSchema, - TradeSchema, - type MarketData, - type ModeConfig, -} from '../types'; -import type { StorageService } from './StorageService'; - -export class MarketDataService extends EventEmitter { - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private dataIngestionSocket: Socket | null = null; - private subscriptions = new Set(); - private batchBuffer: MarketData[] = []; - private batchTimer: NodeJS.Timeout | null = null; - private readonly BATCH_SIZE = 100; - private readonly BATCH_INTERVAL_MS = 50; - constructor( - private readonly dependencies: { - logger: Pick; - storage: Pick; - drainStrategies: () => Promise; - } - ) { - super(); - } - - async initialize(config: ModeConfig): Promise { - this.mode = config.mode; - - if (config.mode !== 'backtest') { - // Connect to data-ingestion service for real-time data - await this.connectToDataIngestion(); - } - } - - private async connectToDataIngestion(): Promise { - const dataIngestionUrl = process.env.DATA_INGESTION_URL || 'http://localhost:3001'; - - this.dataIngestionSocket = io(dataIngestionUrl, { - transports: ['websocket'], - reconnection: true, - reconnectionAttempts: 5, - reconnectionDelay: 1000, - }); - - this.dataIngestionSocket.on('connect', () => { - this.dependencies.logger.info('Connected to data-ingestion service'); - // Re-subscribe to symbols - this.subscriptions.forEach(symbol => { - defined(this.dataIngestionSocket).emit('subscribe', { symbol }); - }); - }); - - this.dataIngestionSocket.on('disconnect', () => { - this.dependencies.logger.warn('Disconnected from data-ingestion service'); - }); - - this.dataIngestionSocket.on('marketData', data => { - this.handleMarketData(data); - }); - - this.dataIngestionSocket.on('error', error => { - this.dependencies.logger.error('Data ingestion socket error:', error); - }); - } - - async subscribeToSymbol(symbol: string): Promise { - this.subscriptions.add(symbol); - - if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) { - this.dataIngestionSocket.emit('subscribe', { symbol }); - } - - this.dependencies.logger.debug(`Subscribed to ${symbol}`); - } - - async unsubscribeFromSymbol(symbol: string): Promise { - this.subscriptions.delete(symbol); - - if (this.mode !== 'backtest' && this.dataIngestionSocket?.connected) { - this.dataIngestionSocket.emit('unsubscribe', { symbol }); - } - - this.dependencies.logger.debug(`Unsubscribed from ${symbol}`); - } - - ingest(input: unknown): void { - this.handleMarketData(input); - } - async flush(): Promise { - this.processBatch(); - await this.dependencies.drainStrategies(); - } - private handleMarketData(input: unknown): void { - try { - if (!input || typeof input !== 'object') { - throw new Error('Invalid market data'); - } - const data = input as Record; - // Validate and transform data - let marketData: MarketData; - - if ('type' in data && 'data' in data) { - marketData = MarketDataSchema.parse(data); - } else if (data.bid !== undefined && data.ask !== undefined) { - const quote = QuoteSchema.parse({ - symbol: data.symbol, - bid: data.bid, - ask: data.ask, - bidSize: data.bidSize || data.bid_size || 0, - askSize: data.askSize || data.ask_size || 0, - timestamp: data.timestamp || Date.now(), - }); - marketData = { type: 'quote', data: quote }; - } else if (data.price !== undefined && data.size !== undefined) { - const trade = TradeSchema.parse({ - symbol: data.symbol, - price: data.price, - size: data.size, - side: data.side || 'buy', - timestamp: data.timestamp || Date.now(), - }); - marketData = { type: 'trade', data: trade }; - } else if (data.open !== undefined && data.close !== undefined) { - const bar = BarSchema.parse({ - symbol: data.symbol, - open: data.open, - high: data.high, - low: data.low, - close: data.close, - volume: data.volume, - vwap: data.vwap, - timestamp: data.timestamp || Date.now(), - }); - marketData = { type: 'bar', data: bar }; - } else { - this.dependencies.logger.warn('Unknown market data format:', data); - return; - } - - // Add to batch buffer - if (typeof data.eventId === 'string') { - marketData.eventId = data.eventId; - } - this.batchBuffer.push(marketData); - - // Process batch if size threshold reached - if (this.batchBuffer.length >= this.BATCH_SIZE) { - this.processBatch(); - } else if (!this.batchTimer) { - // Set timer for time-based batching - this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS); - } - } catch (error) { - this.dependencies.logger.error('Error handling market data:', error); - } - } - - private processBatch(): void { - if (this.batchBuffer.length === 0) { - return; - } - - // Clear timer - if (this.batchTimer) { - clearTimeout(this.batchTimer); - this.batchTimer = null; - } - - // Emit batch - const batch = [...this.batchBuffer]; - this.batchBuffer = []; - - this.emit('marketDataBatch', batch); - } - - async loadHistoricalData( - symbols: string[], - startTime: Date, - endTime: Date, - interval = '1m' - ): Promise { - const { storage } = this.dependencies; - const groups = await Promise.all( - symbols.map(async symbol => { - const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval); - return bars.map( - (bar): MarketData => ({ - type: 'bar', - data: { - symbol, - timestamp: bar.timestamp.getTime(), - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - vwap: bar.vwap, - }, - }) - ); - }) - ); - return groups.flat().sort((a, b) => a.data.timestamp - b.data.timestamp); - } - - async shutdown(): Promise { - // Clear batch timer - if (this.batchTimer) { - clearTimeout(this.batchTimer); - this.batchTimer = null; - } - - // Disconnect from data ingestion - if (this.dataIngestionSocket) { - this.dataIngestionSocket.disconnect(); - this.dataIngestionSocket = null; - } - - await this.flush(); - this.subscriptions.clear(); - } -} diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts deleted file mode 100644 index feb242ca..00000000 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */ -export * from '@stock-bot/trading-runtime/historical-storage'; diff --git a/apps/stock/orchestrator/src/services/analytics-error.ts b/apps/stock/orchestrator/src/services/analytics-error.ts deleted file mode 100644 index 8027b2aa..00000000 --- a/apps/stock/orchestrator/src/services/analytics-error.ts +++ /dev/null @@ -1,14 +0,0 @@ -export class AnalyticsServiceError extends Error { - readonly status: 502 | 503; - readonly code: 'analytics_unavailable' | 'analytics_invalid_response'; - constructor(reason: 'unavailable' | 'invalid-response') { - super( - reason === 'unavailable' - ? 'Analytics service is unavailable' - : 'Analytics service returned an invalid response' - ); - this.name = 'AnalyticsServiceError'; - this.status = reason === 'unavailable' ? 503 : 502; - this.code = reason === 'unavailable' ? 'analytics_unavailable' : 'analytics_invalid_response'; - } -} diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index fe97537d..c6571704 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -1,7 +1,7 @@ import { ServiceContainerBuilder } from '@stock-bot/di'; import type { StockAppConfig } from '@stock-bot/stock-config'; import { assertResearchConcurrency } from './backtest/ResearchBacktestPool'; -import { paperConfigurationSchema } from './contracts/paper-runtime'; +import { paperConfigurationSchema } from '@stock-bot/stock-config/paper-runtime'; import { assertSupportedComposition, registerOrchestratorServices, diff --git a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts b/apps/stock/orchestrator/src/strategies/BaseStrategy.ts deleted file mode 100644 index eea74ccf..00000000 --- a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts +++ /dev/null @@ -1,384 +0,0 @@ -import { EventEmitter } from 'events'; -import { createHash } from 'node:crypto'; -import { z } from 'zod'; -import { defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { ModeManager } from '../core/ModeManager'; -import { identity } from '../execution/model'; -import type { - ExecutionService, - StrategyFill, - StrategyOrderUpdate, -} from '../services/ExecutionService'; -import { - OrderRequestSchema, - type MarketData, - type OrderRequest, - type StrategyConfig, -} from '../types'; - -const logger = getLogger('BaseStrategy'); -const finite = z.number().finite(); -const checkpointSchema = z.object({ - version: z.literal(1), - positions: z.array(z.tuple([z.string(), finite])), - pendingOrders: z.array(z.tuple([z.string(), OrderRequestSchema])), - seenFills: z.array(z.string()).max(2048), - performance: z.object({ - trades: finite.nonnegative(), - wins: finite.nonnegative(), - losses: finite.nonnegative(), - totalPnl: finite, - maxDrawdown: finite, - currentDrawdown: finite, - peakEquity: finite, - }), - indicators: z.unknown(), -}); - -export interface Signal { - type: 'buy' | 'sell' | 'close'; - symbol: string; - strength: number; // -1 to 1 - reason?: string; - metadata?: Record; -} - -export abstract class BaseStrategy extends EventEmitter { - protected config: StrategyConfig; - protected isActive = false; - private eventIdentity?: string; - private readonly seenFills = new Set(); - setMarketEvent(eventId: string) { - this.eventIdentity = eventId; - } - protected positions = new Map(); - protected pendingOrders = new Map(); - protected performance = { - trades: 0, - wins: 0, - losses: 0, - totalPnl: 0, - maxDrawdown: 0, - currentDrawdown: 0, - peakEquity: 0, - }; - - constructor( - config: StrategyConfig, - protected modeManager: ModeManager, - protected executionService: ExecutionService - ) { - super(); - this.config = structuredClone(config); - } - - async initialize(): Promise { - logger.info(`Initializing strategy: ${this.config.name}`); - const snapshot = await this.executionService.getStrategySnapshot(this.config.id); - this.positions = new Map( - Object.entries(snapshot.positions).filter(([, quantity]) => quantity !== 0) - ); - this.pendingOrders = new Map( - snapshot.orders.map(order => [order.report.orderId, order.request]) - ); - // Subscribe to symbols - for (const symbol of this.config.symbols) { - // Note: In real implementation, would subscribe through market data service - logger.debug(`Strategy ${this.config.id} subscribed to ${symbol}`); - } - } - - async start(): Promise { - this.isActive = true; - logger.info(`Started strategy: ${this.config.name}`); - await this.onStart(); - } - - async stop(): Promise { - this.isActive = false; - await this.executionService.pauseStrategy(this.config.id); - - // Cancel pending orders - for (const [orderId, _order] of this.pendingOrders) { - await this.executionService.cancelOrder(orderId); - } - this.pendingOrders.clear(); - - logger.info(`Stopped strategy: ${this.config.name}`); - await this.onStop(); - } - - async shutdown(): Promise { - await this.suspend(); - this.removeAllListeners(); - logger.info(`Shutdown strategy: ${this.config.name}`); - } - /** Process shutdown is not an instruction to cancel durable orders or erase indicators. */ - async suspend(): Promise { - this.isActive = false; - } - getCheckpointVersion(): string | undefined { - return undefined; - } - protected captureIndicators(): unknown { - return null; - } - protected restoreIndicators(state: unknown): void { - if (state !== null) { - throw new Error('Unexpected checkpoint state for a stateless strategy'); - } - } - captureCheckpoint(): unknown { - return { - version: 1, - positions: [...this.positions], - pendingOrders: [...this.pendingOrders], - seenFills: [...this.seenFills].slice(-2048), - performance: { ...this.performance }, - indicators: this.captureIndicators(), - }; - } - restoreCheckpoint(input: unknown): void { - const state = checkpointSchema.parse(input); - this.restoreIndicators(state.indicators); - this.positions = new Map(state.positions); - this.pendingOrders = new Map(state.pendingOrders); - this.seenFills.clear(); - for (const id of state.seenFills) { - this.seenFills.add(id); - } - this.performance = state.performance; - } - - // Market data handling - async onMarketData(data: MarketData): Promise { - if (!this.isActive) { - logger.info( - `[BaseStrategy] Strategy ${this.config.id} received market data but is not active` - ); - return; - } - - this.eventIdentity = identity(data); - // Update any indicators or state - this.updateIndicators(data); - - // Generate signals - const signal = await this.generateSignal(data); - - if (signal) { - this.executionService.afterStrategyCommit(() => { - this.emit('signal', signal); - }); - - // Convert signal to order if strong enough - const order = await this.signalToOrder(signal); - if (order) { - const clientOrderId = createHash('sha256') - .update(JSON.stringify([this.config.id, this.eventIdentity, order])) - .digest('hex'); - this.executionService.captureStrategyOrder({ ...order, clientOrderId }, this.config.id); - } - } - } - - async onMarketDataBatch(batch: MarketData[]): Promise { - // Default implementation processes individually - // Strategies can override for more efficient batch processing - for (const data of batch) { - await this.onMarketData(data); - } - } - - getConfig(): Readonly { - return structuredClone(this.config); - } - - hasOrder(orderId: string): boolean { - return this.pendingOrders.has(orderId); - } - - // Order and fill handling - async onOrderUpdate(update: StrategyOrderUpdate): Promise { - logger.debug(`Strategy ${this.config.id} order update:`, update); - - if (['filled', 'rejected', 'cancelled'].includes(update.status)) { - this.pendingOrders.delete(update.orderId); - } else { - this.pendingOrders.set(update.orderId, { - symbol: update.symbol, - side: update.side, - quantity: update.quantity, - orderType: 'market', - timeInForce: 'DAY', - }); - } - } - - async onOrderError(order: OrderRequest, error: unknown): Promise { - logger.error(`Strategy ${this.config.id} order error:`, error); - // Strategies can override to handle errors - } - - async onFill(fill: StrategyFill): Promise { - if (this.seenFills.has(fill.id)) { - return; - } - this.seenFills.add(fill.id); - if (this.seenFills.size > 2048) { - this.seenFills.delete(defined(this.seenFills.values().next().value)); - } - const quantity = - (this.positions.get(fill.symbol) ?? 0) + - (fill.side === 'buy' ? fill.quantity : -fill.quantity); - if (Math.abs(quantity) < 1e-8) { - this.positions.delete(fill.symbol); - } else { - this.positions.set(fill.symbol, quantity); - } - // Update performance metrics - this.performance.trades++; - - if ((fill.pnl ?? 0) > 0) { - this.performance.wins++; - } else if ((fill.pnl ?? 0) < 0) { - this.performance.losses++; - } - - this.performance.totalPnl += fill.pnl ?? 0; - - // Update drawdown - const currentEquity = this.getEquity(); - if (currentEquity > this.performance.peakEquity) { - this.performance.peakEquity = currentEquity; - this.performance.currentDrawdown = 0; - } else { - this.performance.currentDrawdown = - this.performance.peakEquity > 0 - ? (this.performance.peakEquity - currentEquity) / this.performance.peakEquity - : 0; - this.performance.maxDrawdown = Math.max( - this.performance.maxDrawdown, - this.performance.currentDrawdown - ); - } - } - - // Configuration - async updateConfig(updates: Partial): Promise { - if (this.isActive) { - throw new Error( - 'Active strategy configuration is immutable; use an explicit new strategy ID' - ); - } - this.config = this.validateConfig(structuredClone({ ...this.config, ...updates })); - logger.info(`Updated config for strategy ${this.config.id}`); - - // Strategies can override to handle specific config changes - this.onConfigUpdate(updates); - } - - // Helper methods - isInterestedInSymbol(symbol: string): boolean { - return this.config.symbols.includes(symbol); - } - - hasPosition(symbol: string): boolean { - return this.positions.has(symbol) && Math.abs(defined(this.positions.get(symbol))) > 0.0001; - } - - getPosition(symbol: string): number { - return this.positions.get(symbol) || 0; - } - - getPerformance() { - const winRate = - this.performance.trades > 0 ? (this.performance.wins / this.performance.trades) * 100 : 0; - - return { - ...this.performance, - winRate, - averagePnl: - this.performance.trades > 0 ? this.performance.totalPnl / this.performance.trades : 0, - }; - } - - protected getEquity(): number { - // Get initial capital from config parameters or default - const initialCapital = Number(this.config.parameters?.initialCapital ?? 100000); - return initialCapital + this.performance.totalPnl; - } - - protected async signalToOrder(signal: Signal): Promise { - // Only act on strong signals - if (Math.abs(signal.strength) < 0.7) { - return null; - } - - // Check if we already have a position - const currentPosition = this.getPosition(signal.symbol); - - // Use quantity from signal metadata if provided - const quantity = - typeof signal.metadata?.quantity === 'number' - ? signal.metadata.quantity - : this.calculatePositionSize(signal); - - logger.info( - `[BaseStrategy] Converting signal to order: ${signal.type} ${quantity} ${signal.symbol}, current position: ${currentPosition}` - ); - - // Simple logic - can be overridden by specific strategies - if (signal.type === 'buy') { - // Allow buying to open long or close short - return { - symbol: signal.symbol, - side: 'buy', - quantity: quantity, - orderType: 'market', - timeInForce: 'DAY', - }; - } else if (signal.type === 'sell') { - // Allow selling to close long or open short - return { - symbol: signal.symbol, - side: 'sell', - quantity: quantity, - orderType: 'market', - timeInForce: 'DAY', - }; - } else if (signal.type === 'close' && currentPosition !== 0) { - return { - symbol: signal.symbol, - side: currentPosition > 0 ? 'sell' : 'buy', - quantity: Math.abs(currentPosition), - orderType: 'market', - timeInForce: 'DAY', - }; - } - - return null; - } - - protected calculatePositionSize(signal: Signal): number { - // Simple fixed size - strategies should override with proper position sizing - const baseSize = 100; // 100 shares - const allocation = this.config.allocation || 1.0; - - return Math.floor(baseSize * allocation * Math.abs(signal.strength)); - } - - // Abstract methods that strategies must implement - protected abstract updateIndicators(data: MarketData): void; - protected abstract generateSignal(data: MarketData): Promise; - - // Optional hooks for strategies to override - protected onStart(): void | Promise {} - protected onStop(): void | Promise {} - protected onConfigUpdate(_updates: Partial): void {} - /** Validate before assignment, so a rejected inactive edit cannot poison the current definition. */ - protected validateConfig(config: StrategyConfig): StrategyConfig { - return config; - } -} diff --git a/apps/stock/orchestrator/src/strategies/StrategyManager.ts b/apps/stock/orchestrator/src/strategies/StrategyManager.ts deleted file mode 100644 index 9efcbe93..00000000 --- a/apps/stock/orchestrator/src/strategies/StrategyManager.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { EventEmitter } from 'events'; -import type { Logger } from '@stock-bot/services'; -import type { ExecutionService } from '../services/ExecutionService'; -import { type MarketData, type StrategyConfig } from '../types'; -import type { BaseStrategy, Signal } from './BaseStrategy'; - -export class StrategyManager extends EventEmitter { - private strategies = new Map(); - private activeStrategies = new Set(); - private delivery: Promise = Promise.resolve(); - private listening = false; - private recoveryTimer?: ReturnType; - private readonly onBatch = (batch: MarketData[]) => { - void this.deliverBatch(batch).catch(error => - this.dependencies.logger.error('Market delivery failed', { error }) - ); - }; - - constructor( - private readonly dependencies: { - logger: Pick; - marketData: Pick; - execution: Pick< - ExecutionService, - | 'requiresDurableCheckpoint' - | 'enqueueMarketData' - | 'recoverStrategies' - | 'registeredStrategies' - | 'registerStrategy' - | 'pauseStrategy' - >; - createStrategy: (config: StrategyConfig) => BaseStrategy | Promise; - } - ) { - super(); - } - - setupEventListeners(): void { - if (this.listening) { - return; - } - this.listening = true; - const { marketData: marketDataService, execution: executionService } = this.dependencies; - marketDataService.on('marketDataBatch', this.onBatch); - // Financial notifications are journal inputs, not volatile observer callbacks. - this.recoveryTimer = setInterval(() => { - if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) { - void this.recover().catch(error => - this.dependencies.logger.error('Strategy recovery remains pending', { error }) - ); - } - }, 1000); - this.recoveryTimer.unref(); - } - - private deliverBatch(batch: MarketData[]): Promise { - const work = this.delivery - .catch(() => {}) - .then(async () => { - const { execution } = this.dependencies; - const failures: unknown[] = []; - for (const data of batch) { - try { - await execution.enqueueMarketData(data); - } catch (error) { - failures.push(error); - } - } - await execution.recoverStrategies( - this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id)) - ); - if (failures.length) { - throw new AggregateError(failures, 'Some market inputs were rejected'); - } - }); - this.delivery = work; - return work; - } - - recover(): Promise { - const work = this.delivery - .catch(() => {}) - .then(() => - this.dependencies.execution.recoverStrategies( - this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id)) - ) - ); - this.delivery = work; - return work; - } - - async drain(): Promise { - await this.delivery; - } - - async initializeStrategies(configs: StrategyConfig[]): Promise { - if (new Set(configs.map(config => config.id)).size !== configs.length) { - throw new Error('Duplicate strategy IDs'); - } - // Clear existing strategies - for (const [_id, strategy] of this.strategies) { - await strategy.shutdown(); - } - this.strategies.clear(); - this.activeStrategies.clear(); - this.setupEventListeners(); - - // Initialize new strategies - for (const config of configs) { - try { - const strategy = await this.createStrategy(config); - this.strategies.set(config.id, strategy); - - if (config.enabled) { - await this.enableStrategy(config.id); - } - - this.dependencies.logger.info(`Initialized strategy: ${config.name} (${config.id})`); - } catch (error) { - this.dependencies.logger.error(`Failed to initialize strategy ${config.name}:`, error); - throw error; - } - } - await this.recover(); - } - async restoreStrategies(): Promise { - this.setupEventListeners(); - const configs = await this.dependencies.execution.registeredStrategies(); - if (configs.length) { - await this.initializeStrategies(configs); - } - } - async attachStrategy(strategy: BaseStrategy): Promise { - this.setupEventListeners(); - const config = strategy.getConfig(); - if (this.strategies.has(config.id)) { - throw new Error('Strategy ID already attached'); - } - this.strategies.set(config.id, strategy); - await this.enableStrategy(config.id); - await this.recover(); - } - - private async createStrategy(config: StrategyConfig): Promise { - const strategy = await this.dependencies.createStrategy(config); - - // Set up strategy event handlers - strategy.on('signal', signal => { - this.handleStrategySignal(config.id, signal); - }); - - strategy.on('error', (error: Error) => { - this.dependencies.logger.error(`Strategy ${config.id} error:`, error); - }); - - return strategy; - } - - async enableStrategy(strategyId: string): Promise { - const strategy = this.strategies.get(strategyId); - if (!strategy) { - throw new Error(`Strategy ${strategyId} not found`); - } - - const { execution } = this.dependencies; - if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) { - throw new Error('Paper strategies require a versioned checkpoint contract'); - } - await strategy.initialize(); - await strategy.start(); // Start the strategy to make it active - try { - await execution.registerStrategy(strategy); - } catch (error) { - await strategy.suspend(); - throw error; - } - this.activeStrategies.add(strategyId); - this.dependencies.logger.info(`Enabled strategy: ${strategyId}`); - } - - async disableStrategy(strategyId: string): Promise { - const strategy = this.strategies.get(strategyId); - if (!strategy) { - throw new Error(`Strategy ${strategyId} not found`); - } - - // Disable pauses new decisions; pending orders/intents remain explicit ledger work. - await this.dependencies.execution.pauseStrategy(strategyId); - await strategy.suspend(); - this.activeStrategies.delete(strategyId); - this.dependencies.logger.info(`Disabled strategy: ${strategyId}`); - } - - private async handleStrategySignal(strategyId: string, signal: Signal): Promise { - this.dependencies.logger.info(`Strategy ${strategyId} generated signal:`, signal); - // Signals are informational - strategies will convert strong signals to orders - } - - async onMarketData(data: MarketData): Promise { - await this.deliverBatch([data]); - } - - getActiveStrategies(): string[] { - return Array.from(this.activeStrategies); - } - - getStrategy(strategyId: string): BaseStrategy | undefined { - return this.strategies.get(strategyId); - } - - getAllStrategies(): BaseStrategy[] { - return Array.from(this.strategies.values()); - } - - async shutdown(): Promise { - this.dependencies.logger.info('Shutting down strategy manager...'); - - this.dependencies.marketData.off('marketDataBatch', this.onBatch); - this.listening = false; - if (this.recoveryTimer) { - clearInterval(this.recoveryTimer); - this.recoveryTimer = undefined; - } - try { - await this.drain(); - } catch (error) { - this.dependencies.logger.error('Leaving durable strategy backlog for restart', { error }); - } - // Disable all strategies - for (const strategyId of this.activeStrategies) { - await this.strategies.get(strategyId)?.suspend(); - } - - // Clear all strategies - this.strategies.clear(); - this.activeStrategies.clear(); - } -} diff --git a/apps/stock/orchestrator/src/strategies/StrategyRegistry.ts b/apps/stock/orchestrator/src/strategies/StrategyRegistry.ts deleted file mode 100644 index caaf4c77..00000000 --- a/apps/stock/orchestrator/src/strategies/StrategyRegistry.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { normalizeStrategyName } from '../contracts/strategy-names'; -import type { ModeManager } from '../core/ModeManager'; -import type { ExecutionService } from '../services/ExecutionService'; -import type { StrategyConfig } from '../types'; -import type { BaseStrategy } from './BaseStrategy'; - -export interface StrategyDependencies { - modeManager: ModeManager; - execution: ExecutionService; -} -export type StrategyFactory = ( - config: StrategyConfig, - dependencies: StrategyDependencies -) => BaseStrategy | Promise; - -/** Registration belongs to composition; strategy lifecycle belongs to the manager. */ -export class StrategyRegistry { - private readonly factories = new Map(); - - register(names: readonly string[], factory: StrategyFactory): this { - const keys = names.map(normalizeStrategyName); - if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) { - throw new Error('Strategy aliases must be nonempty and distinct'); - } - for (const key of keys) { - if (this.factories.has(key)) { - throw new Error(`Strategy alias already registered: ${key}`); - } - } - for (const key of keys) { - this.factories.set(key, factory); - } - return this; - } - - async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise { - const factory = this.factories.get(normalizeStrategyName(config.name)); - if (!factory) { - throw new Error(`Unknown strategy: ${config.name}`); - } - return factory(config, dependencies); - } -} diff --git a/apps/stock/orchestrator/src/strategies/builtin-strategies.ts b/apps/stock/orchestrator/src/strategies/builtin-strategies.ts deleted file mode 100644 index b92ce673..00000000 --- a/apps/stock/orchestrator/src/strategies/builtin-strategies.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { strategyAliases } from '../contracts/strategy-names'; -import { StrategyRegistry } from './StrategyRegistry'; - -/** Lazy factories avoid loading every strategy (and ML dependency) at startup. */ -export function createBuiltinStrategyRegistry(): StrategyRegistry { - return new StrategyRegistry() - .register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => { - const { MeanReversionStrategy } = await import('./builtin/MeanReversionStrategy'); - return new MeanReversionStrategy(config, modeManager, execution); - }) - .register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => { - const { SmaCrossoverStrategy } = await import('./builtin/SmaCrossoverStrategy'); - return new SmaCrossoverStrategy(config, modeManager, execution); - }) - .register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => { - const { MLEnhancedStrategy } = await import('./experimental/MLEnhancedStrategy'); - return new MLEnhancedStrategy(config, modeManager, execution); - }); -} diff --git a/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts b/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts deleted file mode 100644 index 0595cec6..00000000 --- a/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts +++ /dev/null @@ -1,234 +0,0 @@ -import { z } from 'zod'; -import { - trailingMean, - trailingPopulationDeviation, - trailingSimpleRsi, -} from '@stock-bot/calculations/indicators'; -import { at, defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { MeanReversionParameters } from '../../contracts/strategies'; -import type { ModeManager } from '../../core/ModeManager'; -import type { ExecutionService } from '../../services/ExecutionService'; -import type { StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; -import { priceHistoryState } from '../checkpoint-schemas'; -import { meanReversionConfig } from '../strategy-config'; - -const logger = getLogger('MeanReversionStrategy'); - -interface MeanReversionIndicators { - mean: number; - trendMean: number; - stdDev: number; - zScore: number; - rsi: number; -} - -/** Versioned implementation used by the built-in mean-reversion aliases. */ -export class MeanReversionStrategy extends BaseStrategy { - private priceHistory = new Map(); - private indicators = new Map(); - override getCheckpointVersion() { - return 'mean-reversion/v2'; - } - protected override captureIndicators() { - return { priceHistory: [...this.priceHistory], indicators: [...this.indicators] }; - } - protected override restoreIndicators(input: unknown) { - const finite = z.number().finite(); - const state = z - .object({ - priceHistory: priceHistoryState(this.historyCapacity), - indicators: z.array( - z.tuple([ - z.string(), - z.object({ - mean: finite, - trendMean: finite, - stdDev: finite, - zScore: finite, - rsi: finite, - }), - ]) - ), - }) - .strict() - .parse(input); - this.priceHistory = new Map(state.priceHistory); - this.indicators = new Map(state.indicators); - } - - private settings: MeanReversionParameters; - constructor( - config: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - const validated = meanReversionConfig(config); - super(validated, modeManager, executionService); - this.settings = validated.parameters; - } - - protected override validateConfig(config: StrategyConfig): StrategyConfig { - const validated = meanReversionConfig(config); - this.settings = validated.parameters; - return validated; - } - private get historyCapacity(): number { - return Math.max( - this.settings.lookbackPeriod * 3, - this.settings.trendPeriod, - this.settings.rsiPeriod + 1 - ); - } - protected override calculatePositionSize(signal: Signal): number { - return this.settings.quantity ?? super.calculatePositionSize(signal); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const symbol = data.data.symbol; - const price = data.data.close; - - // Update price history - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, []); - } - - const history = defined(this.priceHistory.get(symbol)); - history.push(price); - - // Keep only needed history - if (history.length > this.historyCapacity) { - history.shift(); - } - - // Calculate indicators if we have enough data - if (history.length >= Math.max(this.settings.lookbackPeriod, this.settings.rsiPeriod + 1)) { - const indicators = this.calculateIndicators(history); - this.indicators.set(symbol, indicators); - } - } - - private calculateIndicators(prices: number[]): MeanReversionIndicators { - const len = prices.length; - - const mean = defined(trailingMean(prices, this.settings.lookbackPeriod)); - const trendMean = trailingMean(prices, this.settings.trendPeriod) ?? mean; - const stdDev = defined(trailingPopulationDeviation(prices, this.settings.lookbackPeriod)); - - // Calculate Z-score - const currentPrice = at(prices, len - 1); - const zScore = stdDev > 0 ? (currentPrice - mean) / stdDev : 0; - - // Calculate RSI - const rsi = this.calculateRSI(prices, this.settings.rsiPeriod); - - return { mean, trendMean, stdDev, zScore, rsi }; - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const symbol = data.data.symbol; - const indicators = this.indicators.get(symbol); - - if (!indicators) { - return null; - } - - // Check volume filter - if (data.data.volume * data.data.close < this.settings.minNotionalVolume) { - return null; - } - - const position = this.getPosition(symbol); - const { zScore, rsi, mean, trendMean } = indicators; - - // Entry signals - if (position === 0) { - // Long entry: Oversold conditions - if ( - zScore < -this.settings.entryThreshold && - rsi < this.settings.rsiOversold && - mean > trendMean - ) { - return { - type: 'buy', - symbol, - strength: Math.min(Math.abs(zScore) / 3, 1), - reason: `Mean reversion long: Z-score ${zScore.toFixed(2)}, RSI ${rsi.toFixed(0)}`, - metadata: { indicators }, - }; - } - - // Short entry: Overbought conditions - if ( - zScore > this.settings.entryThreshold && - rsi > this.settings.rsiOverbought && - mean < trendMean - ) { - return { - type: 'sell', - symbol, - strength: Math.min(Math.abs(zScore) / 3, 1), - reason: `Mean reversion short: Z-score ${zScore.toFixed(2)}, RSI ${rsi.toFixed(0)}`, - metadata: { indicators }, - }; - } - } - - // Exit signals - if (position > 0) { - // Exit long: Price reverted to mean or stop loss - if (zScore > -this.settings.exitZScore || zScore > this.settings.entryThreshold) { - return { - type: 'close', - symbol, - strength: 1, - reason: `Exit long: Z-score ${zScore.toFixed(2)}`, - metadata: { indicators }, - }; - } - } else if (position < 0) { - // Exit short: Price reverted to mean or stop loss - if (zScore < this.settings.exitZScore || zScore < -this.settings.entryThreshold) { - return { - type: 'close', - symbol, - strength: 1, - reason: `Exit short: Z-score ${zScore.toFixed(2)}`, - metadata: { indicators }, - }; - } - } - - return null; - } - - private calculateRSI(prices: number[], period: number = 14): number { - // v2 uses rolling simple averages and flat=100, NOT the new Wilder contract. - return trailingSimpleRsi(prices, period, 100) ?? 50; - } - - protected override onStart(): void { - logger.info(`Mean Reversion Strategy started with symbols: ${this.config.symbols.join(', ')}`); - } - - protected override onStop(): void { - logger.info('Mean Reversion Strategy stopped'); - // Clear indicators - this.priceHistory.clear(); - this.indicators.clear(); - } - - protected override onConfigUpdate(updates: Partial): void { - logger.info('Mean Reversion Strategy config updated:', updates); - } -} diff --git a/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts b/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts deleted file mode 100644 index 2d27e8a8..00000000 --- a/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { SmaParameters } from '../../contracts/strategies'; -import type { ModeManager } from '../../core/ModeManager'; -import { movingAverageCrossover } from '@stock-bot/calculations/indicators'; -import type { ExecutionService, StrategyFill } from '../../services/ExecutionService'; -import type { StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; -import { crossoverCheckpointSchema } from '../checkpoint-schemas'; -import { smaConfig } from '../strategy-config'; - -const logger = getLogger('SimpleMovingAverageCrossover'); - -export class SmaCrossoverStrategy extends BaseStrategy { - private priceHistory = new Map(); - private lastSignalBar = new Map(); - private barCount = new Map(); - private totalSignals = 0; - private lastCrossoverType = new Map(); - override getCheckpointVersion() { - return 'sma-crossover-fixed/v2'; - } - protected override captureIndicators() { - return { - priceHistory: [...this.priceHistory], - lastSignalBar: [...this.lastSignalBar], - barCount: [...this.barCount], - totalSignals: this.totalSignals, - lastCrossoverType: [...this.lastCrossoverType], - }; - } - protected override restoreIndicators(input: unknown) { - const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input); - this.priceHistory = new Map(state.priceHistory); - this.lastSignalBar = new Map(state.lastSignalBar); - this.barCount = new Map(state.barCount); - this.totalSignals = state.totalSignals; - this.lastCrossoverType = new Map(state.lastCrossoverType); - } - - private settings: SmaParameters; - private readonly DEBUG_INTERVAL = 10; - - constructor( - config: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - const validated = smaConfig(config); - super(validated, modeManager, executionService); - this.settings = validated.parameters; - logger.info( - `SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}` - ); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const symbol = data.data.symbol; - const price = data.data.close; - - // Initialize or get price history - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, []); - this.barCount.set(symbol, 0); - logger.info(`๐Ÿ“Š Starting to track ${symbol} @ ${price.toFixed(2)}`); - } - - const history = defined(this.priceHistory.get(symbol)); - history.push(price); - - // Increment bar count - const currentBar = (this.barCount.get(symbol) || 0) + 1; - this.barCount.set(symbol, currentBar); - - // Keep only needed history - if (history.length > this.settings.slowPeriod * 2) { - history.shift(); - } - - // Log when we have enough data to start trading - if (history.length === this.settings.slowPeriod + 1) { - logger.info(`โœ… ${symbol} now has enough history (${history.length} bars) to start trading`); - } - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const symbol = data.data.symbol; - const history = this.priceHistory.get(symbol); - - if (!history || history.length < this.settings.slowPeriod) { - return null; - } - - const currentPrice = data.data.close; - const timestamp = data.data.timestamp; - const currentBar = this.barCount.get(symbol) || 0; - - const crossover = movingAverageCrossover( - history, - this.settings.fastPeriod, - this.settings.slowPeriod - ); - if (!crossover) { - return null; - } - const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover; - - // Get current position - const currentPosition = this.getPosition(symbol); - - // Track last signal bar - const lastSignalBar = this.lastSignalBar.get(symbol) || 0; - const barsSinceLastSignal = currentBar - lastSignalBar; - - // Calculate MA difference for debugging - const maDiff = fastMA - slowMA; - const maDiffPct = (maDiff / slowMA) * 100; - - // Debug logging every N bars - if (currentBar % this.DEBUG_INTERVAL === 0 || goldenCross || deathCross) { - logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`); - logger.info(` Price: $${currentPrice.toFixed(2)}`); - logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`); - logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`); - logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); - logger.info(` Position: ${currentPosition} shares`); - logger.info(` Bars since last signal: ${barsSinceLastSignal}`); - - if (goldenCross) { - logger.info(` ๐ŸŸข GOLDEN CROSS DETECTED!`); - } - if (deathCross) { - logger.info(` ๐Ÿ”ด DEATH CROSS DETECTED!`); - } - } - - // Store crossover type for position management - if (goldenCross) { - this.lastCrossoverType.set(symbol, 'golden'); - } else if (deathCross) { - this.lastCrossoverType.set(symbol, 'death'); - } - - // Check if we should enter a position based on the current trend - const lastCrossover = this.lastCrossoverType.get(symbol); - - if (currentPosition === 0 && barsSinceLastSignal >= this.settings.minHoldingBars) { - // No position - check if we should enter based on last crossover - if (lastCrossover === 'golden' && fastMA > slowMA) { - // Trend is still bullish after golden cross - open long - logger.info(`๐ŸŸข Opening LONG position - Bullish trend after golden cross`); - logger.info(` Current position: 0 shares`); - - const positionSize = await this.calculateCrossoverPositionSize(currentPrice); - logger.info(` Opening long position: ${positionSize} shares`); - - const signal: Signal = { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Bullish trend - Opening long position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'trend_long', - price: currentPrice, - quantity: positionSize, - }, - }; - - this.lastSignalBar.set(symbol, currentBar); - this.totalSignals++; - logger.info(`๐Ÿ‘‰ Total signals generated: ${this.totalSignals}`); - return signal; - } else if (lastCrossover === 'death' && fastMA < slowMA) { - // Trend is still bearish after death cross - open short - logger.info(`๐Ÿ”ด Opening SHORT position - Bearish trend after death cross`); - logger.info(` Current position: 0 shares`); - - const positionSize = await this.calculateCrossoverPositionSize(currentPrice); - logger.info(` Opening short position: ${positionSize} shares`); - - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Bearish trend - Opening short position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'trend_short', - price: currentPrice, - quantity: positionSize, - }, - }; - - this.lastSignalBar.set(symbol, currentBar); - this.totalSignals++; - logger.info(`๐Ÿ‘‰ Total signals generated: ${this.totalSignals}`); - return signal; - } - } - - // Handle crossovers for position changes - if (goldenCross) { - logger.info(`๐ŸŸข Golden cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - if (currentPosition < 0) { - // Close short position - logger.info(` Closing short position of ${Math.abs(currentPosition)} shares`); - const signal: Signal = { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Closing short position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'golden', - price: currentPrice, - quantity: Math.abs(currentPosition), - }, - }; - - this.lastSignalBar.set(symbol, currentBar); - this.totalSignals++; - logger.info(`๐Ÿ‘‰ Total signals generated: ${this.totalSignals}`); - return signal; - } - } else if (deathCross) { - logger.info(`๐Ÿ”ด Death cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - if (currentPosition > 0) { - // Close long position - logger.info(` Closing long position of ${currentPosition} shares`); - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Closing long position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'death', - price: currentPrice, - quantity: currentPosition, - }, - }; - - this.lastSignalBar.set(symbol, currentBar); - this.totalSignals++; - logger.info(`๐Ÿ‘‰ Total signals generated: ${this.totalSignals}`); - return signal; - } - } - - return null; - } - - protected override validateConfig(config: StrategyConfig): StrategyConfig { - const validated = smaConfig(config); - this.settings = validated.parameters; - return validated; - } - - private async calculateCrossoverPositionSize(price: number): Promise { - if (this.settings.quantity !== undefined) { - return this.settings.quantity; - } - const accountBalance = (await this.executionService.getAccount()).equity; - const positionValue = accountBalance * this.settings.positionFraction; - const shares = Math.floor(positionValue / price); - - logger.debug( - `Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}` - ); - - return Math.max(1, shares); // At least 1 share - } - - protected onOrderFilled(fill: StrategyFill): void { - const { symbol, side, quantity, price } = fill; - - logger.info(`โœ… ${side.toUpperCase()} filled: ${symbol} - ${quantity} shares @ ${price}`); - - // Update our internal position tracking to match - // This is redundant with BaseStrategy but helps with debugging - const currentPosition = this.getPosition(symbol); - logger.info(` Position after fill: ${currentPosition} shares`); - } -} diff --git a/apps/stock/orchestrator/src/strategies/canonical-builtins.ts b/apps/stock/orchestrator/src/strategies/canonical-builtins.ts index 8fa312d8..a0954973 100644 --- a/apps/stock/orchestrator/src/strategies/canonical-builtins.ts +++ b/apps/stock/orchestrator/src/strategies/canonical-builtins.ts @@ -2,9 +2,9 @@ import type { HistoricalDatasetManifestV2 } from '@stock-bot/types'; import { builtinStrategySelectionSchema, type BuiltinStrategySelection, -} from '../contracts/builtin-strategy'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; -import type { ReplayConfig } from '../contracts/native-replay'; +} from '@stock-bot/stock-config/strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; +import type { ReplayConfig } from '@stock-bot/stock-config/canonical-replay'; import { createMeanReversionStrategy } from './canonical-mean-reversion'; import { createSmaStrategy } from './canonical-sma'; diff --git a/apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts b/apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts index ca121778..6efc7fbb 100644 --- a/apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts +++ b/apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts @@ -6,8 +6,8 @@ import { meanReversionStrategySelectionSchema, type MeanReversionSignalParameters, type MeanReversionStrategySelection, -} from '../contracts/builtin-strategy'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; +} from '@stock-bot/stock-config/strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import { wholeShareTarget } from './canonical-sizing'; const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); diff --git a/apps/stock/orchestrator/src/strategies/canonical-sma.ts b/apps/stock/orchestrator/src/strategies/canonical-sma.ts index a2a76414..b00f8391 100644 --- a/apps/stock/orchestrator/src/strategies/canonical-sma.ts +++ b/apps/stock/orchestrator/src/strategies/canonical-sma.ts @@ -4,8 +4,8 @@ import { parseFinancialDecimal, type FinancialDecimal } from '@stock-bot/types'; import { smaStrategySelectionSchema, type SmaStrategySelection, -} from '../contracts/builtin-strategy'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; +} from '@stock-bot/stock-config/strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import { wholeShareTarget } from './canonical-sizing'; const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER); diff --git a/apps/stock/orchestrator/src/strategies/checkpoint-schemas.ts b/apps/stock/orchestrator/src/strategies/checkpoint-schemas.ts deleted file mode 100644 index 6d4bf473..00000000 --- a/apps/stock/orchestrator/src/strategies/checkpoint-schemas.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { z } from 'zod'; - -export const priceHistoryState = (capacity: number) => - z.array(z.tuple([z.string(), z.array(z.number().finite().positive()).max(capacity)])); -export const barCounterState = z.array(z.tuple([z.string(), z.number().int().nonnegative()])); -export const crossoverCheckpointSchema = (capacity: number) => - z - .object({ - priceHistory: priceHistoryState(capacity), - barCount: barCounterState, - lastSignalBar: barCounterState, - totalSignals: z.number().int().nonnegative(), - lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])), - }) - .strict(); diff --git a/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts b/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts deleted file mode 100644 index 0aeca65a..00000000 --- a/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts +++ /dev/null @@ -1,472 +0,0 @@ -import type * as tf from '@tensorflow/tfjs-node'; -import { at, defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import { TechnicalAnalysis } from '../../indicators/TechnicalAnalysis'; -import type { StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; - -const logger = getLogger('MLEnhancedStrategy'); - -interface MLModelConfig { - modelPath?: string; - features: string[]; - lookbackPeriod: number; - updateFrequency: number; // How often to retrain in minutes - minTrainingSize: number; -} - -/** Optional run-local experiment; deliberately lacks a durable paper checkpoint contract. */ -export class MLEnhancedStrategy extends BaseStrategy { - private tensorflow: typeof tf | undefined; - private get tf(): typeof tf { - return defined(this.tensorflow, 'ML strategy has not been started'); - } - private model: tf.LayersModel | null = null; - private featureBuffer: Map = new Map(); - private predictions: Map = new Map(); - private lastUpdate: number = 0; - private trainingData: { features: number[][]; labels: number[] } = { features: [], labels: [] }; - - // Feature extractors - private indicators: Map< - string, - { - prices: number[]; - volumes: number[]; - returns: number[]; - sma20: number; - sma50: number; - rsi: number; - macd: number; - signal: number; - volatility20?: number; - } - > = new Map(); - - // ML Configuration - private mlConfig: MLModelConfig = { - features: [ - 'returns_20', - 'returns_50', - 'volatility_20', - 'rsi_14', - 'volume_ratio', - 'price_position', - 'macd_signal', - ], - lookbackPeriod: 50, - updateFrequency: 1440, // Daily - minTrainingSize: 1000, - }; - - protected override async onStart(): Promise { - logger.info('ML Enhanced Strategy starting...'); - this.tensorflow = await import('@tensorflow/tfjs-node'); - - // Try to load existing model - if (this.mlConfig.modelPath) { - try { - this.model = await this.tf.loadLayersModel(`file://${this.mlConfig.modelPath}`); - logger.info('Loaded existing ML model'); - } catch (_error) { - logger.warn('Could not load model, will train new one'); - } - } - - // Initialize feature buffers for each symbol - this.config.symbols.forEach(symbol => { - this.featureBuffer.set(symbol, []); - this.indicators.set(symbol, { - prices: [], - volumes: [], - returns: [], - sma20: 0, - sma50: 0, - rsi: 50, - macd: 0, - signal: 0, - }); - }); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const symbol = data.data.symbol; - const indicators = this.indicators.get(symbol); - if (!indicators) { - return; - } - - // Update price and volume history - indicators.prices.push(data.data.close); - indicators.volumes.push(data.data.volume); - - if (indicators.prices.length > 200) { - indicators.prices.shift(); - indicators.volumes.shift(); - } - - // Calculate returns - if (indicators.prices.length >= 2) { - const ret = - (data.data.close - at(indicators.prices, indicators.prices.length - 2)) / - at(indicators.prices, indicators.prices.length - 2); - indicators.returns.push(ret); - - if (indicators.returns.length > 50) { - indicators.returns.shift(); - } - } - - // Update technical indicators - if (indicators.prices.length >= 20) { - indicators.sma20 = this.calculateSMA(indicators.prices, 20); - indicators.volatility20 = this.calculateVolatility(indicators.returns, 20); - } - - if (indicators.prices.length >= 50) { - indicators.sma50 = this.calculateSMA(indicators.prices, 50); - } - - if (indicators.prices.length >= 14) { - indicators.rsi = this.calculateRSI(indicators.prices, 14); - } - - // Extract features - const features = this.extractFeatures(symbol, data); - if (features) { - const buffer = defined(this.featureBuffer.get(symbol)); - buffer.push(features); - - if (buffer.length > this.mlConfig.lookbackPeriod) { - buffer.shift(); - } - - // Make prediction if we have enough data - if (buffer.length === this.mlConfig.lookbackPeriod && this.model) { - this.makePrediction(symbol, buffer); - } - } - - // Check if we should update the model - const now = Date.now(); - if (now - this.lastUpdate > this.mlConfig.updateFrequency * 60 * 1000) { - this.updateModel(); - this.lastUpdate = now; - } - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const symbol = data.data.symbol; - const prediction = this.predictions.get(symbol); - - if (!prediction || Math.abs(prediction) < 0.01) { - return null; // No strong signal - } - - const position = this.getPosition(symbol); - const indicators = this.indicators.get(symbol); - - // Risk management checks - const volatility = indicators?.volatility20 || 0.02; - const maxPositionRisk = 0.02; // 2% max risk per position - const _positionSize = this.calculateMLPositionSize(volatility, maxPositionRisk); - - // Generate signals based on ML predictions - if (prediction > 0.02 && position <= 0) { - // Strong bullish prediction - return { - type: 'buy', - symbol, - strength: Math.min(prediction * 50, 1), // Scale prediction to 0-1 - reason: `ML prediction: ${(prediction * 100).toFixed(2)}% expected return`, - metadata: { - prediction, - confidence: this.calculateConfidence(symbol), - features: this.getLatestFeatures(symbol), - }, - }; - } else if (prediction < -0.02 && position >= 0) { - // Strong bearish prediction - return { - type: 'sell', - symbol, - strength: Math.min(Math.abs(prediction) * 50, 1), - reason: `ML prediction: ${(prediction * 100).toFixed(2)}% expected return`, - metadata: { - prediction, - confidence: this.calculateConfidence(symbol), - features: this.getLatestFeatures(symbol), - }, - }; - } else if (position !== 0 && Math.sign(position) !== Math.sign(prediction)) { - // Exit if prediction reverses - return { - type: 'close', - symbol, - strength: 1, - reason: 'ML prediction reversed', - metadata: { prediction }, - }; - } - - return null; - } - - private extractFeatures(symbol: string, data: MarketData): number[] | null { - if (data.type !== 'bar') { - return null; - } - const indicators = this.indicators.get(symbol); - if (!indicators || indicators.prices.length < 50) { - return null; - } - - const features: number[] = []; - - // Price returns - const currentPrice = at(indicators.prices, indicators.prices.length - 1); - features.push(currentPrice / at(indicators.prices, indicators.prices.length - 20) - 1); // 20-day return - features.push(currentPrice / at(indicators.prices, indicators.prices.length - 50) - 1); // 50-day return - - // Volatility - features.push(indicators.volatility20 || 0); - - // RSI - features.push((indicators.rsi - 50) / 50); // Normalize to -1 to 1 - - // Volume ratio - const avgVolume = indicators.volumes.slice(-20).reduce((a: number, b: number) => a + b, 0) / 20; - features.push(data.data.volume / avgVolume - 1); - - // Price position in daily range - const pricePosition = (data.data.close - data.data.low) / (data.data.high - data.data.low); - features.push(pricePosition * 2 - 1); // Normalize to -1 to 1 - - // MACD signal - if (indicators.macd && indicators.signal) { - features.push((indicators.macd - indicators.signal) / currentPrice); - } else { - features.push(0); - } - - // Store for training - if (indicators.returns.length >= 21) { - const futureReturn = at(indicators.returns, indicators.returns.length - 1); - this.trainingData.features.push([...features]); - this.trainingData.labels.push(futureReturn); - - // Limit training data size - if (this.trainingData.features.length > 10000) { - this.trainingData.features.shift(); - this.trainingData.labels.shift(); - } - } - - return features; - } - - private async makePrediction(symbol: string, featureBuffer: number[][]): Promise { - if (!this.model) { - return; - } - - try { - // Prepare input tensor - const input = this.tf.tensor3d([featureBuffer]); - - // Make prediction - const prediction = (await this.model.predict(input)) as tf.Tensor; - const value = at(await prediction.data(), 0); - - this.predictions.set(symbol, value); - - // Cleanup tensors - input.dispose(); - prediction.dispose(); - } catch (error) { - logger.error('ML prediction error:', error); - } - } - - private async updateModel(): Promise { - if (this.trainingData.features.length < this.mlConfig.minTrainingSize) { - logger.info('Not enough training data yet'); - return; - } - - logger.info('Updating ML model...'); - - try { - // Create or update model - if (!this.model) { - this.model = this.createModel(); - } - - // Prepare training data - const features = this.tf.tensor2d(this.trainingData.features); - const labels = this.tf.tensor1d(this.trainingData.labels); - - // Train model - await this.model.fit(features, labels, { - epochs: 50, - batchSize: 32, - validationSplit: 0.2, - shuffle: true, - callbacks: { - onEpochEnd: (epoch, logs) => { - if (epoch % 10 === 0) { - logger.debug(`Epoch ${epoch}: loss = ${logs?.loss?.toFixed(4)}`); - } - }, - }, - }); - - logger.info('Model updated successfully'); - - // Cleanup tensors - features.dispose(); - labels.dispose(); - - // Save model if path provided - if (this.mlConfig.modelPath) { - await this.model.save(`file://${this.mlConfig.modelPath}`); - } - } catch (error) { - logger.error('Model update error:', error); - } - } - - private createModel(): tf.LayersModel { - const model = this.tf.sequential({ - layers: [ - // LSTM layer for sequence processing - this.tf.layers.lstm({ - units: 64, - returnSequences: true, - inputShape: [this.mlConfig.lookbackPeriod, this.mlConfig.features.length], - }), - this.tf.layers.dropout({ rate: 0.2 }), - - // Second LSTM layer - this.tf.layers.lstm({ - units: 32, - returnSequences: false, - }), - this.tf.layers.dropout({ rate: 0.2 }), - - // Dense layers - this.tf.layers.dense({ - units: 16, - activation: 'relu', - }), - this.tf.layers.dropout({ rate: 0.1 }), - - // Output layer - this.tf.layers.dense({ - units: 1, - activation: 'tanh', // Output between -1 and 1 - }), - ], - }); - - model.compile({ - optimizer: this.tf.train.adam(0.001), - loss: 'meanSquaredError', - metrics: ['mae'], - }); - - return model; - } - - private calculateConfidence(symbol: string): number { - // Simple confidence based on prediction history accuracy - // In practice, would track actual vs predicted returns - const prediction = this.predictions.get(symbol) || 0; - return Math.min(Math.abs(prediction) * 10, 1); - } - - private getLatestFeatures(symbol: string): Record { - const buffer = this.featureBuffer.get(symbol); - if (!buffer || buffer.length === 0) { - return {}; - } - - const latest = at(buffer, buffer.length - 1); - return { - returns_20: at(latest, 0), - returns_50: at(latest, 1), - volatility_20: at(latest, 2), - rsi_normalized: at(latest, 3), - volume_ratio: at(latest, 4), - price_position: at(latest, 5), - macd_signal: at(latest, 6), - }; - } - - private calculateSMA(values: number[], period: number): number { - return values.slice(-period).reduce((sum, value) => sum + value, 0) / period; - } - - private calculateRSI(values: number[], period: number): number { - return TechnicalAnalysis.latest(new TechnicalAnalysis().rsi(values, period)) ?? 50; - } - - private calculateVolatility(returns: number[], period: number): number { - if (returns.length < period) { - return 0; - } - - const recentReturns = returns.slice(-period); - const mean = recentReturns.reduce((a, b) => a + b, 0) / period; - const variance = recentReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / period; - - return Math.sqrt(variance * 252); // Annualized - } - - private calculateMLPositionSize(volatility: number, _maxRisk: number): number { - // Kelly-inspired position sizing with volatility adjustment - const targetVolatility = 0.15; // 15% annual target - const volAdjustment = targetVolatility / volatility; - - return Math.min(volAdjustment, 2.0); // Max 2x leverage - } - - protected override onStop(): void { - logger.info('ML Enhanced Strategy stopped'); - - // Save final model if configured - if (this.model && this.mlConfig.modelPath) { - this.model - .save(`file://${this.mlConfig.modelPath}`) - .then(() => logger.info('Model saved')) - .catch(err => logger.error('Failed to save model:', err)); - } - - // Cleanup - this.featureBuffer.clear(); - this.predictions.clear(); - this.indicators.clear(); - if (this.model) { - this.model.dispose(); - } - } - - protected override onConfigUpdate( - updates: Partial & { mlConfig?: Partial } - ): void { - logger.info('ML Enhanced Strategy config updated:', updates); - - if (updates.mlConfig) { - this.mlConfig = { ...this.mlConfig, ...updates.mlConfig }; - } - } -} diff --git a/apps/stock/orchestrator/src/strategies/retained-program.ts b/apps/stock/orchestrator/src/strategies/retained-program.ts index 080f4522..70872487 100644 --- a/apps/stock/orchestrator/src/strategies/retained-program.ts +++ b/apps/stock/orchestrator/src/strategies/retained-program.ts @@ -6,7 +6,7 @@ import { } from '@stock-bot/stock-config/candidate-execution'; import { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package'; import type { StrategyVersionPackage } from '@stock-bot/types'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import { freeze } from './strategy-decision'; export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution'; diff --git a/apps/stock/orchestrator/src/strategies/strategy-config.ts b/apps/stock/orchestrator/src/strategies/strategy-config.ts deleted file mode 100644 index 5f6cf7cc..00000000 --- a/apps/stock/orchestrator/src/strategies/strategy-config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { - typescriptMeanReversionParameters, - typescriptSmaParameters, -} from '../contracts/strategies'; -import type { StrategyConfig } from '../types'; - -export function smaConfig(config: StrategyConfig) { - return { ...config, parameters: typescriptSmaParameters.parse(config.parameters) }; -} -export function meanReversionConfig(config: StrategyConfig) { - return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) }; -} diff --git a/apps/stock/orchestrator/src/strategies/strategy-controller.ts b/apps/stock/orchestrator/src/strategies/strategy-controller.ts index 801eef08..f13bce4f 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-controller.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-controller.ts @@ -6,14 +6,14 @@ import type { StrategyDiagnostic, StrategyDiagnosticSnapshot, StrategyProgram, -} from '../contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import { nativeAdmissionOrders, type DecisionContext, type PublishedObservation, type ReplayIdentity, type ReplaySubmissionOutcome, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { freeze, increment, diff --git a/apps/stock/orchestrator/src/strategies/strategy-decision.ts b/apps/stock/orchestrator/src/strategies/strategy-decision.ts index ca5d91e7..b65b4ee1 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-decision.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-decision.ts @@ -7,12 +7,12 @@ import type { StrategyAdmissionFeedback, StrategyDiagnostic, StrategyProgram, -} from '../contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import type { DecisionContext, nativeAdmissionOrders, PublishedObservation, -} from '../contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; export function freeze(value: T): DeepReadonly { if (value && typeof value === 'object' && !Object.isFrozen(value)) { diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index fd5fe860..a089e172 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -4,11 +4,9 @@ import { BacktestConfigSchema, RiskLimitsSchema } from '@stock-bot/stock-config/ export { BacktestConfigSchema, RiskLimitsSchema }; export type { BacktestConfig } from '@stock-bot/stock-config/backtest'; -// Trading modes export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']); export type TradingMode = z.infer; -// Mode configurations export const PaperConfigSchema = z.object({ mode: z.literal('paper'), startingCapital: z.number().positive(), @@ -48,14 +46,8 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [ export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & { custom?: Partial<{ BacktestRunner: import('./backtest/ResearchBacktestPool').ResearchBacktestRuntime; - StorageService: import('./services/StorageService').StorageService; - MarketDataService: import('./services/MarketDataService').MarketDataService; - ExecutionService: import('./services/ExecutionService').ExecutionService; - AnalyticsService: import('./services/AnalyticsService').AnalyticsService; - StrategyManager: import('./strategies/StrategyManager').StrategyManager; - PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager; - ModeManager: import('./core/ModeManager').ModeManager; - CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime; + StorageService: import('@stock-bot/trading-runtime/historical-storage').StorageService; + CanonicalPaperRuntime: import('@stock-bot/stock-config/paper-runtime').PaperRuntime; PaperDeploymentHost: import('./paper/PaperDeploymentHost').PaperDeploymentHost; }>; }; @@ -63,7 +55,6 @@ export type { BacktestResult } from './backtest/RustBacktestAdapter'; export type ModeConfig = z.infer; -// Market data types export const QuoteSchema = z.object({ symbol: z.string(), bid: z.number(), @@ -114,56 +105,3 @@ export type MarketData = z.infer; export type Quote = z.infer; export type Trade = z.infer; export type Bar = z.infer; - -// Order types -export const OrderSideSchema = z.enum(['buy', 'sell']); -export const OrderTypeSchema = z.enum(['market', 'limit', 'stop', 'stop_limit']); -export const TimeInForceSchema = z.enum(['DAY', 'GTC', 'IOC', 'FOK']); - -export const OrderRequestSchema = z.object({ - symbol: z.string().trim().min(1).max(50), - side: OrderSideSchema, - quantity: z.number().finite().min(1e-8).max(1e9), - orderType: OrderTypeSchema, - limitPrice: z.number().finite().positive().optional(), - stopPrice: z.number().finite().positive().optional(), - timeInForce: TimeInForceSchema.default('DAY'), - clientOrderId: z.string().min(1).max(256).optional(), -}); - -export type OrderRequest = z.infer; - -// Position types -export const PositionSchema = z.object({ - symbol: z.string(), - quantity: z.number(), - averagePrice: z.number(), - realizedPnl: z.number(), - unrealizedPnl: z.number(), - totalCost: z.number(), - lastUpdate: z.string().datetime(), -}); - -export type Position = z.infer; - -// Strategy types -export const StrategyConfigSchema = z.object({ - id: z.string(), - name: z.string(), - enabled: z.boolean(), - parameters: z.record(z.unknown()), - symbols: z.array(z.string()), - allocation: z.number().min(0).max(1), -}); - -export type StrategyConfig = z.infer; - -export { PerformanceMetricsSchema, RiskMetricsSchema } from './contracts/analytics'; -export type { PerformanceMetrics, RiskMetrics } from './contracts/analytics'; - -// Re-export specialized types -export type { - MarketMicrostructure, - PriceLevel, - OrderBookSnapshot, -} from './types/MarketMicrostructure'; diff --git a/apps/stock/orchestrator/src/types/MarketMicrostructure.ts b/apps/stock/orchestrator/src/types/MarketMicrostructure.ts deleted file mode 100644 index d49029ce..00000000 --- a/apps/stock/orchestrator/src/types/MarketMicrostructure.ts +++ /dev/null @@ -1,29 +0,0 @@ -export interface MarketMicrostructure { - symbol: string; - avgSpreadBps: number; - dailyVolume: number; - avgTradeSize: number; - volatility: number; - tickSize: number; - lotSize: number; - intradayVolumeProfile: number[]; // 24 hourly buckets as percentages -} - -export interface PriceLevel { - price: number; - size: number; - orderCount?: number; - hiddenSize?: number; // For modeling iceberg orders -} - -export interface OrderBookSnapshot { - symbol: string; - timestamp: Date; - bids: PriceLevel[]; - asks: PriceLevel[]; - lastTrade?: { - price: number; - size: number; - side: 'buy' | 'sell'; - }; -} \ No newline at end of file diff --git a/apps/stock/orchestrator/tests/indicators.test.ts b/apps/stock/orchestrator/tests/indicators.test.ts deleted file mode 100644 index 9014a317..00000000 --- a/apps/stock/orchestrator/tests/indicators.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { beforeEach, describe, expect, it } from 'bun:test'; -import { IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine'; -import { - IncrementalIndicators, - SignalGenerator, - TechnicalAnalysis, -} from '../src/indicators/TechnicalAnalysis'; - -describe('Technical Analysis Library', () => { - let ta: TechnicalAnalysis; - let _indicators: TechnicalIndicators; - - beforeEach(() => { - ta = new TechnicalAnalysis(); - _indicators = new TechnicalIndicators(); - }); - - describe('Simple Moving Average', () => { - it('should calculate SMA correctly', () => { - const values = [10, 12, 13, 14, 15, 16, 17, 18, 19, 20]; - const sma = ta.sma(values, 5); - - expect(sma).toHaveLength(6); // 10 values - 5 period + 1 - expect(sma[0]).toBeCloseTo(12.8); // (10+12+13+14+15)/5 - expect(sma[5]).toBeCloseTo(18); // (16+17+18+19+20)/5 - }); - - it('should handle incremental SMA updates', () => { - const incSMA = new IncrementalSMA(3); - - expect(incSMA.update(10)).toBeNull(); - expect(incSMA.update(12)).toBeNull(); - expect(incSMA.update(14)).toBeCloseTo(12); // (10+12+14)/3 - expect(incSMA.update(16)).toBeCloseTo(14); // (12+14+16)/3 - expect(incSMA.current()).toBeCloseTo(14); - }); - }); - - describe('Exponential Moving Average', () => { - it('should calculate EMA correctly', () => { - const values = [10, 12, 13, 14, 15, 16, 17, 18, 19, 20]; - const ema = ta.ema(values, 5); - - expect(ema).toHaveLength(6); - expect(ema[0]).toBeGreaterThan(0); - expect(ema[ema.length - 1]).toBeGreaterThan(ema[0]); - }); - }); - - describe('RSI', () => { - it('should calculate RSI correctly', () => { - const values = [ - 44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.1, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61, - 46.28, 46.28, 46.0, 46.03, 46.41, 46.22, 45.64, - ]; - const rsi = ta.rsi(values, 14); - - expect(rsi).toHaveLength(7); // 20 values - 14 period + 1 - expect(rsi[rsi.length - 1]).toBeGreaterThan(0); - expect(rsi[rsi.length - 1]).toBeLessThan(100); - }); - - it('should identify overbought/oversold conditions', () => { - // Trending up values should give high RSI - const uptrend = Array.from({ length: 20 }, (_, i) => 100 + i); - const rsiUp = ta.rsi(uptrend, 14); - expect(rsiUp[rsiUp.length - 1]).toBeGreaterThan(70); - - // Trending down values should give low RSI - const downtrend = Array.from({ length: 20 }, (_, i) => 100 - i); - const rsiDown = ta.rsi(downtrend, 14); - expect(rsiDown[rsiDown.length - 1]).toBeLessThan(30); - }); - }); - - describe('MACD', () => { - it('should calculate MACD components correctly', () => { - const values = Array.from({ length: 50 }, (_, i) => 100 + Math.sin(i * 0.1) * 10); - const macd = ta.macd(values); - - expect(macd.macd).toHaveLength(39); // 50 - 26 + 1 - 9 + 1 - expect(macd.signal).toHaveLength(39); - expect(macd.histogram).toHaveLength(39); - - // Histogram should be the difference between MACD and signal - expect(macd.histogram[0]).toBeCloseTo(macd.macd[0] - macd.signal[0]); - }); - }); - - describe('Bollinger Bands', () => { - it('should calculate bands correctly', () => { - const values = Array.from({ length: 30 }, (_, _i) => 100 + Math.random() * 10); - const bb = ta.bollingerBands(values, 20, 2); - - expect(bb.middle).toHaveLength(11); // 30 - 20 + 1 - expect(bb.upper).toHaveLength(11); - expect(bb.lower).toHaveLength(11); - - // Upper should be above middle, lower should be below - for (let i = 0; i < bb.middle.length; i++) { - expect(bb.upper[i]).toBeGreaterThan(bb.middle[i]); - expect(bb.lower[i]).toBeLessThan(bb.middle[i]); - } - }); - }); - - describe('ATR', () => { - it('should calculate ATR correctly', () => { - const high = [48.7, 48.72, 48.9, 48.87, 48.82, 49.05, 49.2, 49.35, 49.92, 50.19]; - const low = [47.79, 48.14, 48.39, 48.37, 48.24, 48.64, 48.94, 48.86, 49.5, 49.87]; - const close = [48.16, 48.61, 48.75, 48.63, 48.74, 49.03, 49.07, 49.32, 49.91, 50.13]; - - const atr = ta.atr(high, low, close, 5); - - expect(atr).toHaveLength(5); // 10 - 5 - 1 + 1 - expect(atr.every(v => v > 0)).toBe(true); - }); - }); - - describe('Stochastic', () => { - it('should calculate Stochastic correctly', () => { - const high = Array.from({ length: 20 }, () => Math.random() * 10 + 100); - const low = Array.from({ length: 20 }, (_, i) => high[i] - Math.random() * 5); - const close = Array.from({ length: 20 }, (_, i) => (high[i] + low[i]) / 2); - - const stoch = ta.stochastic(high, low, close, 14, 3, 3); - - expect(stoch.k.length).toBeGreaterThan(0); - expect(stoch.d.length).toBeGreaterThan(0); - - // %K and %D should be between 0 and 100 - expect(stoch.k.every(v => v >= 0 && v <= 100)).toBe(true); - expect(stoch.d.every(v => v >= 0 && v <= 100)).toBe(true); - }); - }); - - describe('Signal Generator', () => { - it('should generate trading signals based on indicators', () => { - const generator = new SignalGenerator(); - - // Create synthetic price data - const prices = { - close: Array.from({ length: 50 }, (_, i) => 100 + Math.sin(i * 0.2) * 10), - high: Array.from({ length: 50 }, (_, i) => 102 + Math.sin(i * 0.2) * 10), - low: Array.from({ length: 50 }, (_, i) => 98 + Math.sin(i * 0.2) * 10), - volume: Array.from({ length: 50 }, () => 1000000), - }; - - const signal = generator.generateSignals('TEST', prices, Date.now()); - - expect(signal.symbol).toBe('TEST'); - expect(['BUY', 'SELL', 'HOLD']).toContain(signal.action); - expect(signal.strength).toBeGreaterThanOrEqual(0); - expect(signal.strength).toBeLessThanOrEqual(1); - expect(signal.indicators).toBeDefined(); - expect(signal.reason).toBeDefined(); - }); - }); - - describe('Incremental Indicators Manager', () => { - it('should manage multiple incremental indicators', () => { - const manager = new IncrementalIndicators(); - - manager.createSMA('fast', 10); - manager.createSMA('slow', 20); - manager.createRSI('rsi', 14); - - // Update all indicators with same value - for (let i = 0; i < 25; i++) { - const value = 100 + i; - manager.update('fast', value); - manager.update('slow', value); - manager.update('rsi', value); - } - - expect(manager.current('fast')).toBeDefined(); - expect(manager.current('slow')).toBeDefined(); - expect(manager.current('rsi')).toBeDefined(); - - // RSI should be high for uptrending values - const rsiValue = manager.current('rsi'); - expect(rsiValue).toBeGreaterThan(70); - }); - }); - - describe('Crossover Detection', () => { - it('should detect crossovers correctly', () => { - const series1 = [10, 11, 12, 13, 14]; - const series2 = [12, 12, 12, 12, 12]; - - expect(TechnicalAnalysis.crossover(series1, series2)).toBe(true); - expect(TechnicalAnalysis.crossunder(series2, series1)).toBe(true); - - const series3 = [15, 14, 13, 12, 11]; - expect(TechnicalAnalysis.crossunder(series3, series2)).toBe(true); - expect(TechnicalAnalysis.crossover(series2, series3)).toBe(true); - }); - }); -}); diff --git a/apps/stock/package.json b/apps/stock/package.json deleted file mode 100644 index 015f6d88..00000000 --- a/apps/stock/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "@stock-bot/stock-app", - "version": "1.0.0", - "private": true, - "description": "Stock trading bot application", - "scripts": { - "dev": "turbo run dev", - "dev:ingestion": "cd data-ingestion && bun run dev", - "dev:pipeline": "cd data-pipeline && bun run dev", - "dev:api": "cd web-api && bun run dev", - "dev:web": "cd web-app && bun run dev", - "dev:backend": "turbo run dev --filter=\"@stock-bot/data-*\" --filter=\"@stock-bot/web-api\"", - "dev:frontend": "turbo run dev --filter=\"@stock-bot/web-app\"", - "build": "echo 'Stock apps built via parent turbo'", - "build:config": "cd config && bun run build", - "build:services": "turbo run build --filter=\"@stock-bot/data-*\" --filter=\"@stock-bot/web-*\"", - "build:ingestion": "cd data-ingestion && bun run build", - "build:pipeline": "cd data-pipeline && bun run build", - "build:api": "cd web-api && bun run build", - "build:web": "cd web-app && bun run build", - "start": "turbo run start --filter=\"@stock-bot/data-*\" --filter=\"@stock-bot/web-api\"", - "start:all": "turbo run start", - "start:ingestion": "cd data-ingestion && bun start", - "start:pipeline": "cd data-pipeline && bun start", - "start:api": "cd web-api && bun start", - "clean": "turbo run clean", - "clean:all": "turbo run clean && rm -rf node_modules", - "clean:ingestion": "cd data-ingestion && rm -rf dist node_modules", - "clean:pipeline": "cd data-pipeline && rm -rf dist node_modules", - "clean:api": "cd web-api && rm -rf dist node_modules", - "clean:web": "cd web-app && rm -rf dist node_modules", - "clean:config": "cd config && rm -rf dist node_modules", - "test": "turbo run test", - "test:all": "turbo run test", - "test:config": "cd config && bun test", - "test:services": "turbo run test --filter=\"@stock-bot/data-*\" --filter=\"@stock-bot/web-*\"", - "test:ingestion": "cd data-ingestion && bun test", - "test:pipeline": "cd data-pipeline && bun test", - "test:api": "cd web-api && bun test", - "lint": "turbo run lint", - "lint:all": "turbo run lint", - "lint:config": "cd config && bun run lint", - "lint:services": "turbo run lint --filter=\"@stock-bot/data-*\" --filter=\"@stock-bot/web-*\"", - "lint:ingestion": "cd data-ingestion && bun run lint", - "lint:pipeline": "cd data-pipeline && bun run lint", - "lint:api": "cd web-api && bun run lint", - "lint:web": "cd web-app && bun run lint", - "install:all": "bun install", - "docker:build": "docker-compose build", - "docker:up": "docker-compose up", - "docker:down": "docker-compose down", - "db:migrate": "cd data-ingestion && bun run db:migrate", - "db:seed": "cd data-ingestion && bun run db:seed", - "health:check": "bun scripts/health-check.js" - }, - "devDependencies": { - "@types/node": "^20.11.0", - "typescript": "^5.3.3", - "turbo": "^2.5.4" - }, - "workspaces": [ - "config", - "data-ingestion", - "data-pipeline", - "web-api", - "web-app" - ], - "engines": { - "node": ">=18.0.0", - "bun": ">=1.1.0" - }, - "packageManager": "bun@1.2.17" -} diff --git a/apps/stock/scripts/health-check.js b/apps/stock/scripts/health-check.js deleted file mode 100755 index 62c05e93..00000000 --- a/apps/stock/scripts/health-check.js +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env node - -const http = require('http'); -const services = [ - { name: 'Data Ingestion', port: 2001 }, - { name: 'Data Pipeline', port: 2002 }, - { name: 'Web API', port: 2003 }, -]; - -console.log('๐Ÿฅ Stock Bot Health Check\n'); - -async function checkService(service) { - return new Promise((resolve) => { - const options = { - hostname: 'localhost', - port: service.port, - path: '/health', - method: 'GET', - timeout: 5000, - }; - - const req = http.request(options, (res) => { - if (res.statusCode === 200) { - resolve({ ...service, status: 'โœ… Healthy', code: res.statusCode }); - } else { - resolve({ ...service, status: 'โš ๏ธ Unhealthy', code: res.statusCode }); - } - }); - - req.on('error', (err) => { - resolve({ ...service, status: 'โŒ Offline', error: err.message }); - }); - - req.on('timeout', () => { - req.destroy(); - resolve({ ...service, status: 'โฑ๏ธ Timeout', error: 'Request timed out' }); - }); - - req.end(); - }); -} - -async function checkAllServices() { - const results = await Promise.all(services.map(checkService)); - - results.forEach((result) => { - console.log(`${result.name.padEnd(15)} ${result.status}`); - if (result.error) { - console.log(` ${result.error}`); - } - }); - - const allHealthy = results.every(r => r.status === 'โœ… Healthy'); - - console.log('\n' + (allHealthy ? 'โœ… All services are healthy!' : 'โš ๏ธ Some services need attention')); - - process.exit(allHealthy ? 0 : 1); -} - -checkAllServices(); \ No newline at end of file diff --git a/apps/stock/tsconfig.json b/apps/stock/tsconfig.json deleted file mode 100644 index 6be8e35f..00000000 --- a/apps/stock/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "baseUrl": "../..", - "paths": { - "@stock-bot/*": ["libs/*/src"], - "@stock-bot/stock-config": ["apps/stock/config/src"], - "@stock-bot/stock-config/*": ["apps/stock/config/src/*"] - } - }, - "references": [ - { "path": "./config" }, - { "path": "./data-ingestion" }, - { "path": "./data-pipeline" }, - { "path": "./web-api" }, - { "path": "./web-app" }, - { "path": "./orchestrator"} - ] -} \ No newline at end of file diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index cafb0925..49466448 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -6,7 +6,7 @@ "type": "module", "scripts": { "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts --outdir dist --target node --external chromium-bidi --external electron --external playwright --external playwright-core", + "build": "bun build src/index.ts --outdir dist --target node", "start": "bun dist/index.js", "test": "bun test", "clean": "rm -rf dist" diff --git a/apps/stock/web-api/src/container-setup.ts b/apps/stock/web-api/src/container-setup.ts deleted file mode 100644 index 0937aad6..00000000 --- a/apps/stock/web-api/src/container-setup.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Service Container Setup for Web API - * Configures dependency injection for the web API service - */ - -import type { UnifiedAppConfig } from '@stock-bot/config'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('web-api-container'); - -/** - * Configure the service container for web API workloads - */ -export function setupServiceContainer( - config: UnifiedAppConfig, - container: IServiceContainer -): IServiceContainer { - logger.info('Configuring web API service container...'); - - // Web API specific configuration - // This service mainly reads data, so smaller pool sizes are fine - const poolSizes = { - mongodb: config.environment === 'production' ? 20 : 10, - postgres: config.environment === 'production' ? 30 : 15, - cache: config.environment === 'production' ? 20 : 10, - }; - - logger.info('Web API pool sizes configured', poolSizes); - - // The container is already configured with connections - // Just return it with our logging - return container; -} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index e8242b4e..98c4422d 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -1,107 +1,18 @@ -import { existsSync, readdirSync, readFileSync } from 'fs'; -import { fileURLToPath } from 'node:url'; -import { dirname, join } from 'path'; -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { runPostgresMigrations } from '@stock-bot/postgres'; +import type { IServiceContainer } from '@stock-bot/services'; const logger = getLogger('migration-runner'); export async function runMigrations(container: IServiceContainer): Promise { - logger.info('Migration runner called'); - logger.info('Container type', { type: typeof container }); - logger.info('Container postgres available', { available: !!container.postgres }); - if (!container.postgres) { logger.warn('PostgreSQL not available, skipping migrations'); - logger.info('Container keys:', Object.keys(container)); return; } try { - await container.postgres.transaction(async client => { - // All startup migrations share one database-scoped lock on this transaction's client. - // PostgreSQL releases it on commit/rollback, including when startup fails. - await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]); - - // Create migrations table if it doesn't exist - await client.query(` - CREATE TABLE IF NOT EXISTS migrations ( - id SERIAL PRIMARY KEY, - filename VARCHAR(255) NOT NULL UNIQUE, - executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() - ) - `); - - // Get list of migration files from database/postgres/init while holding the lock. - let directory = dirname(fileURLToPath(import.meta.url)); - while (!existsSync(join(directory, 'database', 'postgres', 'init'))) { - const parent = dirname(directory); - if (parent === directory) { - throw new Error('Cannot locate PostgreSQL migrations'); - } - directory = parent; - } - const migrationsDir = join(directory, 'database', 'postgres', 'init'); - logger.info('Looking for migrations', { directory: migrationsDir }); - - const files = readdirSync(migrationsDir) - .filter( - f => - f.endsWith('.sql') && - (f.startsWith('001_') || - f === '09-backtest-run-contract.sql' || - f === '10-durable-backtest-dispatch.sql' || - f === '11-simulation-execution-ledger.sql' || - f === '12-historical-datasets.sql' || - f === '13-strategy-recovery.sql' || - f === '14-backtest-submission.sql' || - f === '15-canonical-paper-intents.sql' || - f === '16-strategy-catalog.sql' || - f === '17-research-retention.sql' || - f === '18-backtest-strategy-versions.sql' || - f === '19-canonical-research.sql' || - f === '20-research-workspace.sql' || - f === '21-run-reproduction.sql' || - f === '22-experiments.sql' || - f === '23-experiment-retries.sql' || - f === '24-chronological-validation.sql' || - f === '25-walk-forward.sql' || - f === '26-cost-sensitivity.sql' || - f === '27-research-evidence-sources.sql' || - f === '28-research-agents.sql' || - f === '29-isolated-candidates.sql' || - f === '30-paper-deployments.sql' || - f === '31-research-agent-project-links.sql' || - f === '32-candidate-parameter-defaults.sql' || - f === '33-candidate-decimal-normalization.sql') - ) // Explicit additive migration allowlist; never replay destructive init migrations - .sort(); - - logger.info('Found migration files:', files); - - for (const file of files) { - // Check and apply using the same locked client, not another pooled connection. - const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]); - - if (result.rows.length === 0) { - logger.info(`Running migration: ${file}`); - - // Read and execute migration - const sql = readFileSync(join(migrationsDir, file), 'utf8'); - await client.query(sql); - await client.query( - 'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING', - [file] - ); - - logger.info(`Migration applied: ${file}`); - } else { - logger.debug(`Migration already executed: ${file}`); - } - } - }); - - logger.info('All migrations completed successfully'); + const applied = await runPostgresMigrations(container.postgres, { track: 'research' }); + logger.info('All migrations completed successfully', { appliedCount: applied.length }); } catch (error) { logger.error('Migration failed', { error }); throw error; diff --git a/apps/stock/web-api/src/routes/index.ts b/apps/stock/web-api/src/routes/index.ts deleted file mode 100644 index 61bb46eb..00000000 --- a/apps/stock/web-api/src/routes/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Routes index - exports all route modules - */ -export { createExchangeRoutes } from './exchange.routes'; -export { healthRoutes } from './health.routes'; diff --git a/apps/stock/web-api/src/types.ts b/apps/stock/web-api/src/types.ts deleted file mode 100644 index 83d5e66f..00000000 --- a/apps/stock/web-api/src/types.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Web API Service Types - * Defines required services for web API handlers - */ - -import type { ServiceTypes } from '@stock-bot/services'; - -/** - * Services required by web API handlers - * Makes specific services non-nullable since they're always enabled - */ -export type WebApiServices = ServiceTypes & { - // Always required services - logger: NonNullable; - mongodb: NonNullable; - postgres: NonNullable; - cache: NonNullable; - queue: NonNullable; - queueManager: NonNullable; - // Optional services remain optional - browser: ServiceTypes['browser']; - proxy: ServiceTypes['proxy']; - questdb: ServiceTypes['questdb']; - globalCache: ServiceTypes['globalCache']; -}; diff --git a/apps/stock/web-app/package.json b/apps/stock/web-app/package.json index 807f397d..a3672c8b 100644 --- a/apps/stock/web-app/package.json +++ b/apps/stock/web-app/package.json @@ -14,14 +14,11 @@ "@stock-bot/calculations": "workspace:*", "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", - "@hookform/resolvers": "^3.3.4", "@tanstack/react-table": "^8.21.3", "clsx": "^2.1.1", - "date-fns": "^3.3.1", "lightweight-charts": "^4.1.3", "react": "^18.2.0", "react-dom": "^18.2.0", - "react-hook-form": "^7.49.3", "react-router-dom": "^7.6.2", "react-virtuoso": "^4.12.8", "recharts": "^2.10.4", diff --git a/apps/stock/web-app/src/components/charts/index.ts b/apps/stock/web-app/src/components/charts/index.ts deleted file mode 100644 index 69a7bfff..00000000 --- a/apps/stock/web-app/src/components/charts/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { Chart } from './Chart'; -export type { ChartProps, ChartData } from './Chart'; \ No newline at end of file diff --git a/apps/stock/web-app/src/components/index.ts b/apps/stock/web-app/src/components/index.ts deleted file mode 100644 index a0c91ea0..00000000 --- a/apps/stock/web-app/src/components/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './ui'; -export * from './layout'; diff --git a/apps/stock/web-app/src/components/ui/DataTable/types.ts b/apps/stock/web-app/src/components/ui/DataTable/types.ts deleted file mode 100644 index 98e02041..00000000 --- a/apps/stock/web-app/src/components/ui/DataTable/types.ts +++ /dev/null @@ -1,66 +0,0 @@ -import type { ReactNode } from 'react'; - -export interface TableColumn> { - id: string; - header: string; - accessorKey?: keyof T; - accessorFn?: (row: T) => unknown; - cell?: (props: { getValue: () => unknown; row: { original: T } }) => ReactNode; - sortable?: boolean; - filterable?: boolean; - groupable?: boolean; - width?: number; - minWidth?: number; - maxWidth?: number; - enableResizing?: boolean; -} - -export interface TableConfig { - enableSorting?: boolean; - enableFiltering?: boolean; - enableGrouping?: boolean; - enableColumnResizing?: boolean; - enableRowSelection?: boolean; - manualPagination?: boolean; - pageSize?: number; -} - -export interface VirtualTableProps { - data: T[]; - columns: TableColumn[]; - height?: number; - width?: number; - rowHeight?: number; - headerHeight?: number; - config?: TableConfig; - loading?: boolean; - onRowClick?: (row: T) => void; - className?: string; -} - -export interface FilterCondition { - column: string; - operator: - | 'equals' - | 'contains' - | 'startsWith' - | 'endsWith' - | 'gt' - | 'lt' - | 'gte' - | 'lte' - | 'between' - | 'in'; - value: string | number | boolean | null; - value2?: string | number | boolean | null; // For 'between' operator -} - -export interface SortingState { - id: string; - desc: boolean; -} - -export interface GroupingState { - groupBy: string[]; - aggregations?: Record; -} diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestMetrics.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestMetrics.tsx deleted file mode 100644 index f562e74d..00000000 --- a/apps/stock/web-app/src/features/backtest/components/BacktestMetrics.tsx +++ /dev/null @@ -1,144 +0,0 @@ -import type { BacktestResult } from '../types/backtest.types'; -import { MetricsCard } from './MetricsCard'; - -interface BacktestMetricsProps { - result: BacktestResult | null; - isLoading: boolean; -} - -const ratioLabel = (value: number | null | undefined) => - typeof value === 'number' && Number.isFinite(value) ? value.toFixed(2) : 'N/A'; - -// Full detailed metrics view - can be used as a separate page/view if needed -export function BacktestMetrics({ result, isLoading }: BacktestMetricsProps) { - if (isLoading) { - return ( -
- {[...Array(6)].map((_, i) => ( -
-
-
-
- ))} -
- ); - } - - if (!result) { - return ( -
-

Run a backtest to see performance metrics.

-
- ); - } - - const { metrics } = result; - - return ( -
-
- = 0 ? 'up' : 'down'} - /> - 0 - ? 'up' - : 'down' - } - /> - - 0.5 ? 'up' : 'down'} - /> - - 1 - ? 'up' - : 'down' - } - /> -
- -
-
-

Trade Statistics

-
-
- Profitable Trades - - {metrics.profitableTrades ?? 0} - -
-
- Average Win - - ${(metrics.avgWin ?? 0).toFixed(2)} - -
-
- Average Loss - - ${Math.abs(metrics.avgLoss ?? 0).toFixed(2)} - -
-
- Expectancy - = 0 ? 'text-success' : 'text-error'}`} - > - ${(metrics.expectancy ?? 0).toFixed(2)} - -
-
-
- -
-

Risk Metrics

-
-
- Calmar Ratio - - {ratioLabel(metrics.calmarRatio)} - -
-
- Sortino Ratio - - {ratioLabel(metrics.sortinoRatio)} - -
-
- Exposure Time - - {typeof result.analytics?.exposureTime === 'number' - ? `${(result.analytics.exposureTime * 100).toFixed(1)}%` - : 'N/A'} - -
-
-
-
-
- ); -} diff --git a/apps/stock/web-app/src/features/backtest/components/MetricsCard.tsx b/apps/stock/web-app/src/features/backtest/components/MetricsCard.tsx deleted file mode 100644 index e9883ba6..00000000 --- a/apps/stock/web-app/src/features/backtest/components/MetricsCard.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { ArrowUpIcon, ArrowDownIcon } from '@heroicons/react/24/solid'; - -interface MetricsCardProps { - title: string; - value: string; - trend?: 'up' | 'down'; - subtitle?: string; -} - -export function MetricsCard({ title, value, trend, subtitle }: MetricsCardProps) { - return ( -
-

{title}

-
-

- {value} -

- {trend && ( - - {trend === 'up' ? - : - - } - - )} -
- {subtitle && ( -

{subtitle}

- )} -
- ); -} \ No newline at end of file diff --git a/apps/stock/web-app/src/features/backtest/components/RunControls.tsx b/apps/stock/web-app/src/features/backtest/components/RunControls.tsx deleted file mode 100644 index 778354b0..00000000 --- a/apps/stock/web-app/src/features/backtest/components/RunControls.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { - BackwardIcon, - ForwardIcon, - PauseIcon, - PlayIcon, - StopIcon, -} from '@heroicons/react/24/solid'; -import { useState } from 'react'; -import { at } from '@stock-bot/invariants'; -import type { Run } from '../services/backtestApiV2'; - -interface RunControlsProps { - run: Run; - onPause: () => void; - onResume: () => void; - onCancel: () => void; - onSpeedChange: (speed: number) => void; -} - -export function RunControls({ run, onPause, onResume, onCancel, onSpeedChange }: RunControlsProps) { - const [speedMultiplier, setSpeedMultiplier] = useState(run.speedMultiplier ?? 1000); - - const handleSpeedChange = (speed: number) => { - setSpeedMultiplier(speed); - onSpeedChange(speed); - }; - - const speedOptions = [ - { value: 0.1, label: '0.1x' }, - { value: 0.5, label: '0.5x' }, - { value: 1, label: '1x' }, - { value: 2, label: '2x' }, - { value: 5, label: '5x' }, - { value: 10, label: '10x' }, - { value: 50, label: '50x' }, - { value: 100, label: '100x' }, - { value: 1000, label: 'Max' }, - ]; - - const formatDate = (date?: string) => { - if (!date) { - return '-'; - } - return new Date(date).toLocaleString(); - }; - - const formatDuration = () => { - if (!run.startedAt) { - return '00:00'; - } - const start = new Date(run.startedAt).getTime(); - const current = Date.now(); - const duration = current - start; - - const seconds = Math.floor(duration / 1000); - const minutes = Math.floor(seconds / 60); - const hours = Math.floor(minutes / 60); - - if (hours > 0) { - return `${hours.toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`; - } else { - return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`; - } - }; - - return ( -
-

Run Control

- -
- {/* Progress Bar */} -
-
- Progress - {run.progress.toFixed(1)}% -
-
-
-
-
-
-
- - {/* Control Buttons */} -
- {run.status === 'running' ? ( - - ) : run.status === 'paused' ? ( - - ) : null} - - {(run.status === 'running' || run.status === 'paused') && ( - - )} -
- - {/* Speed Control */} - {run.status === 'running' && ( -
- -
- - - - - -
-
- )} - - {/* Run Info */} -
-
- Status: - - {run.status.charAt(0).toUpperCase() + run.status.slice(1)} - -
-
- Duration: - {formatDuration()} -
- {run.currentDate && ( -
- Current Date: - - {formatDate(run.currentDate)} - -
- )} - {run.error && ( -
- Error: - {run.error} -
- )} -
-
-
- ); -} diff --git a/apps/stock/web-app/src/features/backtest/components/index.ts b/apps/stock/web-app/src/features/backtest/components/index.ts deleted file mode 100644 index 06a90b82..00000000 --- a/apps/stock/web-app/src/features/backtest/components/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { BacktestConfiguration } from './BacktestConfiguration'; -export { MetricsCard } from './MetricsCard'; -export { RunsListWithMetrics } from './RunsListWithMetrics'; -export { CompactPerformanceMetrics } from './CompactPerformanceMetrics'; -export { PositionsSummary } from './PositionsSummary'; -export { ChartContainer } from './ChartContainer'; -export { BacktestChart } from './BacktestChart'; -export { BacktestMetrics } from './BacktestMetrics'; -export { BacktestPlayback } from './BacktestPlayback'; -export { BacktestTrades } from './BacktestTrades'; -export { RunControlsCompact } from './RunControlsCompact'; \ No newline at end of file diff --git a/apps/stock/web-app/src/features/charts/components/index.ts b/apps/stock/web-app/src/features/charts/components/index.ts deleted file mode 100644 index 3c9ed01d..00000000 --- a/apps/stock/web-app/src/features/charts/components/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { SymbolChart } from './SymbolChart'; -export { ChartToolbar } from './ChartToolbar'; -export { IndicatorSelector } from './IndicatorSelector'; -export { IndicatorList } from './IndicatorList'; -export { IndicatorSettings } from './IndicatorSettings'; -export { ChartOverlay } from './ChartOverlay'; \ No newline at end of file diff --git a/apps/stock/web-app/src/features/charts/hooks/index.ts b/apps/stock/web-app/src/features/charts/hooks/index.ts deleted file mode 100644 index 2ce0ad51..00000000 --- a/apps/stock/web-app/src/features/charts/hooks/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { useChartData } from './useChartData'; \ No newline at end of file diff --git a/apps/stock/web-app/src/features/charts/hooks/useChartData.ts b/apps/stock/web-app/src/features/charts/hooks/useChartData.ts deleted file mode 100644 index 129f402d..00000000 --- a/apps/stock/web-app/src/features/charts/hooks/useChartData.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { useEffect, useRef, useState } from 'react'; -import { browserLog } from '@/utils/browserLog'; -import { ChartDataService } from '../services/chartDataService'; -import type { CandlestickData, ChartInterval, MarketData } from '../types'; - -interface UseChartDataOptions { - symbol: string; - interval: ChartInterval; - enableRealtime?: boolean; -} - -export function useChartData({ symbol, interval, enableRealtime = true }: UseChartDataOptions) { - const [data, setData] = useState([]); - const [marketData, setMarketData] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const [error, setError] = useState(null); - - const unsubscribeRef = useRef<(() => void) | null>(null); - - // Fetch historical data - useEffect(() => { - let cancelled = false; - - const fetchData = async () => { - try { - setIsLoading(true); - setError(null); - - const { start, end } = ChartDataService.getDefaultDateRange(interval); - const historicalData = await ChartDataService.getHistoricalData( - symbol, - interval, - start, - end - ); - - if (!cancelled) { - setData(historicalData); - } - - // Fetch current market data - const currentData = await ChartDataService.getRealtimeData(symbol); - if (!cancelled) { - setMarketData(currentData); - } - } catch (err) { - if (!cancelled) { - setError(err instanceof Error ? err.message : 'Failed to load chart data'); - } - } finally { - if (!cancelled) { - setIsLoading(false); - } - } - }; - - fetchData(); - - return () => { - cancelled = true; - }; - }, [symbol, interval]); - - // Subscribe to real-time updates - useEffect(() => { - if (!enableRealtime || isLoading || error) { - return; - } - - const handleRealtimeUpdate = (newCandle: CandlestickData) => { - setData(prevData => { - const lastCandle = prevData[prevData.length - 1]; - - // Check if this is an update to the current candle or a new one - if (lastCandle && lastCandle.time === newCandle.time) { - // Update existing candle - return [...prevData.slice(0, -1), newCandle]; - } else { - // Add new candle - return [...prevData, newCandle]; - } - }); - - // Update market data - setMarketData(prev => { - if (!prev) { - return prev; - } - - const change = newCandle.close - (prev.previousClose || prev.price); - const changePercent = (change / (prev.previousClose || prev.price)) * 100; - - return { - ...prev, - price: newCandle.close, - change, - changePercent, - high: Math.max(prev.high, newCandle.high), - low: Math.min(prev.low, newCandle.low), - volume: prev.volume + (newCandle.volume || 0), - timestamp: new Date().toISOString(), - }; - }); - }; - - const handleError = (error: Error) => { - browserLog.error('Real-time data error:', error); - }; - - unsubscribeRef.current = ChartDataService.subscribeToRealtime( - symbol, - handleRealtimeUpdate, - handleError - ); - - return () => { - if (unsubscribeRef.current) { - unsubscribeRef.current(); - unsubscribeRef.current = null; - } - }; - }, [symbol, enableRealtime, isLoading, error]); - - const refresh = async () => { - const { start, end } = ChartDataService.getDefaultDateRange(interval); - - try { - setIsLoading(true); - const newData = await ChartDataService.getHistoricalData(symbol, interval, start, end); - setData(newData); - - const currentData = await ChartDataService.getRealtimeData(symbol); - setMarketData(currentData); - - setError(null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to refresh data'); - } finally { - setIsLoading(false); - } - }; - - return { - data, - marketData, - isLoading, - error, - refresh, - }; -} diff --git a/apps/stock/web-app/src/features/charts/index.ts b/apps/stock/web-app/src/features/charts/index.ts deleted file mode 100644 index d873ad13..00000000 --- a/apps/stock/web-app/src/features/charts/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { ChartPage } from './ChartPage'; -export * from './types'; -export * from './components'; \ No newline at end of file diff --git a/apps/stock/web-app/src/features/charts/services/chartDataService.ts b/apps/stock/web-app/src/features/charts/services/chartDataService.ts deleted file mode 100644 index 47c861ba..00000000 --- a/apps/stock/web-app/src/features/charts/services/chartDataService.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; -import type { CandlestickData, ChartInterval, MarketData } from '../types'; - -const API_BASE = `${API_BASE_URL}/api/market-data`; - -export class ChartDataService { - static async getHistoricalData( - symbol: string, - interval: ChartInterval, - startDate?: Date, - endDate?: Date - ): Promise { - const params = new URLSearchParams({ - symbol, - interval, - ...(startDate && { start: startDate.toISOString() }), - ...(endDate && { end: endDate.toISOString() }), - }); - - const response = await fetch(`${API_BASE}/historical?${params}`); - - if (!response.ok) { - throw new Error('Failed to fetch historical data'); - } - - const data: unknown = await response.json(); - if (!Array.isArray(data)) { - throw new Error('Invalid historical market data'); - } - - // Transform data to match lightweight-charts format - const candlestickData: CandlestickData[] = data.map((input: unknown) => { - if (typeof input !== 'object' || input === null) { - throw new Error('Invalid historical candle'); - } - const candle = input as Record; - const open = candle.open, - high = candle.high, - low = candle.low, - close = candle.close, - volume = candle.volume; - if ( - typeof open !== 'number' || - typeof high !== 'number' || - typeof low !== 'number' || - typeof close !== 'number' || - ![open, high, low, close].every(Number.isFinite) || - (volume !== undefined && (typeof volume !== 'number' || !Number.isFinite(volume))) - ) { - throw new Error('Invalid historical candle prices'); - } - // Convert time to Unix timestamp in seconds - let time: number; - const rawTime = candle.timestamp || candle.time; - - if (typeof rawTime === 'string') { - // If it's a date string, parse it - time = Math.floor(new Date(rawTime).getTime() / 1000); - } else if (typeof rawTime === 'number') { - // If it's already a number, check if it's in milliseconds or seconds - time = rawTime > 9999999999 ? Math.floor(rawTime / 1000) : rawTime; - } else { - // Default to current time if invalid - throw new Error('Missing historical candle timestamp'); - } - - if (!Number.isFinite(time)) { - throw new Error('Invalid historical candle timestamp'); - } - return { - time, - open, - high, - low, - close, - volume, - }; - }); - - // Sort by time and remove duplicates - const sortedData = candlestickData.sort((a, b) => a.time - b.time); - - // Remove duplicates by keeping only the last entry for each timestamp - const uniqueData = sortedData.reduce((acc: CandlestickData[], current) => { - const lastItem = acc[acc.length - 1]; - - if (!lastItem || current.time !== lastItem.time) { - acc.push(current); - } else { - // Replace with current if duplicate timestamp - acc[acc.length - 1] = current; - } - - return acc; - }, []); - - return uniqueData; - } - - static async getRealtimeData(symbol: string): Promise { - const response = await fetch(`${API_BASE}/quote/${symbol}`); - - if (!response.ok) { - throw new Error('Failed to fetch market data'); - } - - return response.json(); - } - - static async searchSymbols( - query: string - ): Promise> { - const response = await fetch(`${API_BASE}/search?q=${encodeURIComponent(query)}`); - - if (!response.ok) { - throw new Error('Failed to search symbols'); - } - - return response.json(); - } - - // WebSocket connection for real-time updates - static subscribeToRealtime( - symbol: string, - onUpdate: (data: CandlestickData) => void, - onError?: (error: Error) => void - ): () => void { - const ws = new WebSocket(`ws://localhost:3000/ws/market-data`); - let isConnected = false; - - ws.onopen = () => { - isConnected = true; - // Subscribe to symbol - ws.send( - JSON.stringify({ - type: 'subscribe', - symbol, - }) - ); - }; - - ws.onmessage = event => { - try { - const data = JSON.parse(event.data); - if (data.symbol === symbol) { - // Convert timestamp to Unix seconds - let time: number; - if (typeof data.timestamp === 'string') { - time = Math.floor(new Date(data.timestamp).getTime() / 1000); - } else if (typeof data.timestamp === 'number') { - time = data.timestamp > 9999999999 ? Math.floor(data.timestamp / 1000) : data.timestamp; - } else { - time = Math.floor(Date.now() / 1000); - } - - onUpdate({ - time, - open: data.open, - high: data.high, - low: data.low, - close: data.close, - volume: data.volume, - }); - } - } catch (error) { - onError?.(error as Error); - } - }; - - ws.onerror = _error => { - onError?.(new Error('WebSocket error')); - }; - - ws.onclose = () => { - isConnected = false; - }; - - // Return cleanup function - return () => { - if (isConnected) { - ws.send( - JSON.stringify({ - type: 'unsubscribe', - symbol, - }) - ); - } - ws.close(); - }; - } - - // Convert interval to milliseconds for calculations - static intervalToMs(interval: ChartInterval): number { - const map: Record = { - '1m': 60 * 1000, - '5m': 5 * 60 * 1000, - '15m': 15 * 60 * 1000, - '30m': 30 * 60 * 1000, - '1h': 60 * 60 * 1000, - '4h': 4 * 60 * 60 * 1000, - '1d': 24 * 60 * 60 * 1000, - '1w': 7 * 24 * 60 * 60 * 1000, - '1M': 30 * 24 * 60 * 60 * 1000, - }; - return map[interval] || map['1d']; - } - - // Get appropriate date range for interval - static getDefaultDateRange(interval: ChartInterval): { start: Date; end: Date } { - const end = new Date(); - const start = new Date(); - - switch (interval) { - case '1m': - case '5m': - start.setHours(start.getHours() - 24); // 24 hours - break; - case '15m': - case '30m': - start.setDate(start.getDate() - 7); // 1 week - break; - case '1h': - start.setDate(start.getDate() - 30); // 1 month - break; - case '4h': - start.setMonth(start.getMonth() - 3); // 3 months - break; - case '1d': - start.setFullYear(start.getFullYear() - 1); // 1 year - break; - case '1w': - start.setFullYear(start.getFullYear() - 3); // 3 years - break; - case '1M': - start.setFullYear(start.getFullYear() - 10); // 10 years - break; - } - - return { start, end }; - } -} diff --git a/apps/stock/web-app/src/features/exchanges/types/api.types.ts b/apps/stock/web-app/src/features/exchanges/types/api.types.ts deleted file mode 100644 index 342536ce..00000000 --- a/apps/stock/web-app/src/features/exchanges/types/api.types.ts +++ /dev/null @@ -1,69 +0,0 @@ -// API Response types -export interface ApiResponse { - success: boolean; - data?: T; - error?: string; - message?: string; - total?: number; -} - -// Base entity types -export interface BaseEntity { - id: string; - created_at: string; - updated_at: string; -} - -export interface ProviderMapping extends BaseEntity { - provider: string; - provider_exchange_code: string; - provider_exchange_name: string; - master_exchange_id: string; - country_code: string | null; - currency: string | null; - confidence: number; - active: boolean; - verified: boolean; - auto_mapped: boolean; - master_exchange_code?: string; - master_exchange_name?: string; - master_exchange_active?: boolean; -} - -export interface Exchange extends BaseEntity { - code: string; - name: string; - country: string; - currency: string; - active: boolean; - visible: boolean; - provider_mapping_count: string; - active_mapping_count: string; - verified_mapping_count: string; - providers: string | null; - provider_mappings: ProviderMapping[]; -} - -export interface ExchangeDetails { - exchange: Exchange; - provider_mappings: ProviderMapping[]; -} - -export interface ProviderExchange { - provider_exchange_code: string; - provider_exchange_name: string; - country_code: string | null; - currency: string | null; - symbol_count: number | null; -} - -export interface ExchangeStats { - total_exchanges: string; - active_exchanges: string; - countries: string; - currencies: string; - total_provider_mappings: string; - active_provider_mappings: string; - verified_provider_mappings: string; - providers: string; -} diff --git a/apps/stock/web-app/src/features/exchanges/types/component.types.ts b/apps/stock/web-app/src/features/exchanges/types/component.types.ts deleted file mode 100644 index d6af0d6f..00000000 --- a/apps/stock/web-app/src/features/exchanges/types/component.types.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Component-specific types -export interface EditingCell { - id: string; - field: string; -} - -export interface AddProviderMappingDialogState { - exchangeId: string; - exchangeName: string; -} - -export interface DeleteDialogState { - exchangeId: string; - exchangeName: string; - providerMappingCount: number; -} - -export interface FormErrors { - [key: string]: string; -} - -// Dialog props interfaces -export interface BaseDialogProps { - isOpen: boolean; - onClose: () => void; -} - -export interface AddExchangeDialogProps extends BaseDialogProps { - onCreateExchange: (request: import('./request.types').CreateExchangeRequest) => Promise; -} - -export interface AddProviderMappingDialogProps extends BaseDialogProps { - exchangeId: string; - exchangeName: string; - onCreateMapping: ( - request: import('./request.types').CreateProviderMappingRequest - ) => Promise; -} - -export interface DeleteExchangeDialogProps extends BaseDialogProps { - exchangeId: string; - exchangeName: string; - providerMappingCount: number; - onConfirmDelete: (exchangeId: string) => Promise; -} diff --git a/apps/stock/web-app/src/features/exchanges/types/request.types.ts b/apps/stock/web-app/src/features/exchanges/types/request.types.ts deleted file mode 100644 index efd15534..00000000 --- a/apps/stock/web-app/src/features/exchanges/types/request.types.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Request types for API calls -export interface CreateExchangeRequest { - code: string; - name: string; - country: string; - currency: string; - active?: boolean; -} - -export interface UpdateExchangeRequest { - name?: string; - active?: boolean; - visible?: boolean; - country?: string; - currency?: string; -} - -export interface CreateProviderMappingRequest { - provider: string; - provider_exchange_code: string; - provider_exchange_name?: string; - master_exchange_id: string; - country_code?: string; - currency?: string; - confidence?: number; - active?: boolean; - verified?: boolean; -} - -export interface UpdateProviderMappingRequest { - active?: boolean; - verified?: boolean; - confidence?: number; - master_exchange_id?: string; -} diff --git a/apps/stock/web-app/src/features/symbols/components/index.ts b/apps/stock/web-app/src/features/symbols/components/index.ts deleted file mode 100644 index 0857f492..00000000 --- a/apps/stock/web-app/src/features/symbols/components/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { SymbolsFilter } from './SymbolsFilter'; -export { SymbolsTable } from './SymbolsTable'; -export { MultiSelect } from './MultiSelect'; \ No newline at end of file diff --git a/apps/stock/web-app/src/lib/utils/cn.ts b/apps/stock/web-app/src/lib/utils/cn.ts deleted file mode 100644 index 2819a830..00000000 --- a/apps/stock/web-app/src/lib/utils/cn.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { clsx, type ClassValue } from 'clsx'; -import { twMerge } from 'tailwind-merge'; - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)); -} diff --git a/apps/stock/web-app/src/lib/utils/index.ts b/apps/stock/web-app/src/lib/utils/index.ts deleted file mode 100644 index 483f89a6..00000000 --- a/apps/stock/web-app/src/lib/utils/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -export * from './cn'; - -/** - * Format currency values - */ -export function formatCurrency(value: number, currency = 'USD'): string { - return new Intl.NumberFormat('en-US', { - style: 'currency', - currency, - minimumFractionDigits: 2, - maximumFractionDigits: 2, - }).format(value); -} - -/** - * Format percentage values - */ -export function formatPercentage(value: number, decimals = 2): string { - return `${value >= 0 ? '+' : ''}${value.toFixed(decimals)}%`; -} - -/** - * Format large numbers with K, M, B suffixes - */ -export function formatNumber(num: number): string { - if (num >= 1e9) { - return (num / 1e9).toFixed(1) + 'B'; - } - if (num >= 1e6) { - return (num / 1e6).toFixed(1) + 'M'; - } - if (num >= 1e3) { - return (num / 1e3).toFixed(1) + 'K'; - } - return num.toString(); -} - -/** - * Get color class based on numeric value (profit/loss) - */ -export function getValueColor(value: number): string { - if (value > 0) { - return 'text-success'; - } - if (value < 0) { - return 'text-danger'; - } - return 'text-text-secondary'; -} - -/** - * Truncate text to specified length - */ -export function truncateText(text: string, length: number): string { - if (text.length <= length) { - return text; - } - return text.slice(0, length) + '...'; -} diff --git a/database/mongodb/init/01-init-collections.js b/database/mongodb/init/01-init-collections.js deleted file mode 100644 index 8be438c9..00000000 --- a/database/mongodb/init/01-init-collections.js +++ /dev/null @@ -1,234 +0,0 @@ -// MongoDB Initialization Script for Trading Bot -// This script creates collections and indexes for sentiment and document storage - -// Switch to the trading_documents database -db = db.getSiblingDB('stock'); - -// // Create collections with validation schemas - -// Sentiment Analysis Collection -// db.createCollection('sentiment_analysis', { -// validator: { -// $jsonSchema: { -// bsonType: 'object', -// required: ['symbol', 'source', 'timestamp', 'sentiment_score'], -// properties: { -// symbol: { -// bsonType: 'string', -// description: 'Stock symbol (e.g., AAPL, GOOGL)' -// }, -// source: { -// bsonType: 'string', -// description: 'Data source (news, social, earnings_call, etc.)' -// }, -// timestamp: { -// bsonType: 'date', -// description: 'When the sentiment was recorded' -// }, -// sentiment_score: { -// bsonType: 'double', -// minimum: -1.0, -// maximum: 1.0, -// description: 'Sentiment score between -1 (negative) and 1 (positive)' -// }, -// confidence: { -// bsonType: 'double', -// minimum: 0.0, -// maximum: 1.0, -// description: 'Confidence level of the sentiment analysis' -// }, -// text_snippet: { -// bsonType: 'string', -// description: 'Original text that was analyzed' -// }, -// metadata: { -// bsonType: 'object', -// description: 'Additional metadata about the sentiment source' -// } -// } -// } -// } -// }); - -// // Raw Documents Collection (for news articles, social media posts, etc.) -// db.createCollection('raw_documents', { -// validator: { -// $jsonSchema: { -// bsonType: 'object', -// required: ['source', 'document_type', 'timestamp', 'content'], -// properties: { -// source: { -// bsonType: 'string', -// description: 'Document source (news_api, twitter, reddit, etc.)' -// }, -// document_type: { -// bsonType: 'string', -// enum: ['news_article', 'social_post', 'earnings_transcript', 'research_report', 'press_release'], -// description: 'Type of document' -// }, -// timestamp: { -// bsonType: 'date', -// description: 'When the document was created/published' -// }, -// symbols: { -// bsonType: 'array', -// items: { -// bsonType: 'string' -// }, -// description: 'Array of stock symbols mentioned in the document' -// }, -// title: { -// bsonType: 'string', -// description: 'Document title or headline' -// }, -// content: { -// bsonType: 'string', -// description: 'Full document content' -// }, -// url: { -// bsonType: 'string', -// description: 'Original URL of the document' -// }, -// author: { -// bsonType: 'string', -// description: 'Document author or source account' -// }, -// processed: { -// bsonType: 'bool', -// description: 'Whether this document has been processed for sentiment' -// }, -// metadata: { -// bsonType: 'object', -// description: 'Additional document metadata' -// } -// } -// } -// } -// }); - -// // Market Events Collection (for significant market events and their impact) -// db.createCollection('market_events', { -// validator: { -// $jsonSchema: { -// bsonType: 'object', -// required: ['event_type', 'timestamp', 'description'], -// properties: { -// event_type: { -// bsonType: 'string', -// enum: ['earnings', 'merger', 'acquisition', 'ipo', 'dividend', 'split', 'regulatory', 'economic_indicator'], -// description: 'Type of market event' -// }, -// timestamp: { -// bsonType: 'date', -// description: 'When the event occurred or was announced' -// }, -// symbols: { -// bsonType: 'array', -// items: { -// bsonType: 'string' -// }, -// description: 'Stock symbols affected by this event' -// }, -// description: { -// bsonType: 'string', -// description: 'Event description' -// }, -// impact_score: { -// bsonType: 'double', -// minimum: -5.0, -// maximum: 5.0, -// description: 'Expected market impact score' -// }, -// source_documents: { -// bsonType: 'array', -// items: { -// bsonType: 'objectId' -// }, -// description: 'References to raw_documents that reported this event' -// } -// } -// } -// } -// }); - -// // Create indexes for efficient querying - -// // Sentiment Analysis indexes -// db.sentiment_analysis.createIndex({ symbol: 1, timestamp: -1 }); -// db.sentiment_analysis.createIndex({ source: 1, timestamp: -1 }); -// db.sentiment_analysis.createIndex({ timestamp: -1 }); -// db.sentiment_analysis.createIndex({ symbol: 1, source: 1, timestamp: -1 }); - -// // Raw Documents indexes -// db.raw_documents.createIndex({ symbols: 1, timestamp: -1 }); -// db.raw_documents.createIndex({ source: 1, timestamp: -1 }); -// db.raw_documents.createIndex({ document_type: 1, timestamp: -1 }); -// db.raw_documents.createIndex({ processed: 1, timestamp: -1 }); -// db.raw_documents.createIndex({ timestamp: -1 }); - -// // Market Events indexes -// db.market_events.createIndex({ symbols: 1, timestamp: -1 }); -// db.market_events.createIndex({ event_type: 1, timestamp: -1 }); -// db.market_events.createIndex({ timestamp: -1 }); - -// // Insert some sample data for testing - -// // Sample sentiment data -// db.sentiment_analysis.insertMany([ -// { -// symbol: 'AAPL', -// source: 'news_analysis', -// timestamp: new Date(), -// sentiment_score: 0.75, -// confidence: 0.89, -// text_snippet: 'Apple reports strong quarterly earnings...', -// metadata: { -// article_id: 'news_001', -// provider: 'financial_news_api' -// } -// }, -// { -// symbol: 'GOOGL', -// source: 'social_media', -// timestamp: new Date(), -// sentiment_score: -0.25, -// confidence: 0.67, -// text_snippet: 'Concerns about Google AI regulation...', -// metadata: { -// platform: 'twitter', -// engagement_score: 450 -// } -// } -// ]); - -// // Sample raw document -// db.raw_documents.insertOne({ -// source: 'financial_news_api', -// document_type: 'news_article', -// timestamp: new Date(), -// symbols: ['AAPL', 'MSFT'], -// title: 'Tech Giants Show Strong Q4 Performance', -// content: 'Apple and Microsoft both reported better than expected earnings for Q4...', -// url: 'https://example.com/tech-earnings-q4', -// author: 'Financial Reporter', -// processed: true, -// metadata: { -// word_count: 850, -// readability_score: 0.75 -// } -// }); - -// // Sample market event -// db.market_events.insertOne({ -// event_type: 'earnings', -// timestamp: new Date(), -// symbols: ['AAPL'], -// description: 'Apple Q4 2024 Earnings Report', -// impact_score: 2.5, -// source_documents: [] -// }); - -print('MongoDB initialization completed successfully!'); -print('Created collections: sentiment_analysis, raw_documents, market_events'); -print('Created indexes for efficient querying'); -print('Inserted sample data for testing'); diff --git a/database/postgres/init/01-init-database.sql b/database/postgres/init/01-init-database.sql index acd43b36..6e92d3c9 100644 --- a/database/postgres/init/01-init-database.sql +++ b/database/postgres/init/01-init-database.sql @@ -1,13 +1,3 @@ --- Initialize main database and user --- This runs first when PostgreSQL container starts - --- Create main database if it doesn't exist -SELECT 'CREATE DATABASE trading_bot' -WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'trading_bot')\gexec - --- Connect to the trading_bot database -\c trading_bot; - --- Create extensions we'll need -CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -CREATE EXTENSION IF NOT EXISTS "pg_trgm"; -- For fuzzy string matching \ No newline at end of file +-- Initialize extensions in the active target database (POSTGRES_DB) +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; +CREATE EXTENSION IF NOT EXISTS "pg_trgm"; diff --git a/database/postgres/init/02-master-schema.sql b/database/postgres/init/02-master-schema.sql index 895687e7..80ba8b3f 100644 --- a/database/postgres/init/02-master-schema.sql +++ b/database/postgres/init/02-master-schema.sql @@ -1,6 +1,4 @@ -- Simple Master Schema for Symbol Resolution --- Connect to trading_bot database -\c trading_bot; -- Exchanges Table CREATE TABLE IF NOT EXISTS exchanges ( diff --git a/database/postgres/init/03-initial-data.sql b/database/postgres/init/03-initial-data.sql index c414ffc2..5961205b 100644 --- a/database/postgres/init/03-initial-data.sql +++ b/database/postgres/init/03-initial-data.sql @@ -1,5 +1,4 @@ -- Insert initial reference data -\c trading_bot; -- Insert basic exchanges to start with INSERT INTO exchanges (code, name, country, currency) VALUES diff --git a/database/postgres/init/04-provider-exchange-mapping-schema.sql b/database/postgres/init/04-provider-exchange-mapping-schema.sql index bba44a70..66f3f835 100644 --- a/database/postgres/init/04-provider-exchange-mapping-schema.sql +++ b/database/postgres/init/04-provider-exchange-mapping-schema.sql @@ -1,10 +1,20 @@ -- Enhanced Schema with Provider Exchange Mappings --- Connect to trading_bot database -\c trading_bot; --- First, rename is_active to active in existing tables -ALTER TABLE IF EXISTS exchanges RENAME COLUMN is_active TO active; -ALTER TABLE IF EXISTS symbols RENAME COLUMN is_active TO active; +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'exchanges' AND column_name = 'is_active' + ) THEN + ALTER TABLE exchanges RENAME COLUMN is_active TO active; + END IF; + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'symbols' AND column_name = 'is_active' + ) THEN + ALTER TABLE symbols RENAME COLUMN is_active TO active; + END IF; +END $$; -- Provider Exchange Mappings Table -- Maps provider-specific exchange codes to our master exchanges diff --git a/database/postgres/init/05-add-visible-column.sql b/database/postgres/init/05-add-visible-column.sql index 53e1b7bf..d3d5597e 100644 --- a/database/postgres/init/05-add-visible-column.sql +++ b/database/postgres/init/05-add-visible-column.sql @@ -1,6 +1,4 @@ -- Add visible column to exchanges table --- Connect to trading_bot database -\c trading_bot; -- Add visible column to exchanges table with default true ALTER TABLE exchanges @@ -13,7 +11,8 @@ UPDATE exchanges SET visible = true WHERE visible IS NULL; CREATE INDEX IF NOT EXISTS idx_exchanges_visible ON exchanges(visible); -- Update the exchange_provider_summary view to include visibility -CREATE OR REPLACE VIEW exchange_provider_summary AS +DROP VIEW IF EXISTS exchange_provider_summary; +CREATE VIEW exchange_provider_summary AS SELECT e.code as master_code, e.name as master_name, diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 46ce1dc8..55f6cb56 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -12,15 +12,17 @@ name: stock-bot-dev services: dragonfly: - image: docker.dragonflydb.io/dragonflydb/dragonfly:latest + image: docker.dragonflydb.io/dragonflydb/dragonfly:v1.30.3 container_name: stock-bot-dev-dragonfly + mem_limit: 1536m ports: - '127.0.0.1:6380:6379' command: - dragonfly - --logtostderr - - --maxmemory=512mb - - --save_schedule="" + - --maxmemory=1gb + - --proactor_threads=2 + - --save_schedule= - --bind=0.0.0.0 - --default_lua_flags=allow-undeclared-keys volumes: @@ -35,13 +37,23 @@ services: - stock-bot-dev-network postgres: - image: postgres:16-alpine + image: postgres:16.9-alpine container_name: stock-bot-dev-postgres + mem_limit: 2g + shm_size: 512m environment: POSTGRES_DB: trading_bot_dev POSTGRES_USER: dev_user POSTGRES_PASSWORD: dev_pass POSTGRES_INITDB_ARGS: '--encoding=UTF-8' + command: + - postgres + - -c + - shared_buffers=512MB + - -c + - work_mem=32MB + - -c + - maintenance_work_mem=256MB ports: - '127.0.0.1:5433:5432' volumes: @@ -57,8 +69,13 @@ services: - stock-bot-dev-network mongodb: - image: mongo:7-jammy + image: mongo:7.0.21-jammy container_name: stock-bot-dev-mongodb + mem_limit: 3g + ulimits: + nofile: + soft: 262144 + hard: 262144 environment: MONGO_INITDB_ROOT_USERNAME: dev_admin MONGO_INITDB_ROOT_PASSWORD: dev_mongo_pass @@ -79,8 +96,13 @@ services: - stock-bot-dev-network questdb: - image: questdb/questdb:latest + image: questdb/questdb:10.2.0 container_name: stock-bot-dev-questdb + mem_limit: 4g + ulimits: + nofile: + soft: 1048576 + hard: 1048576 ports: - '127.0.0.1:9100:9000' - '127.0.0.1:8813:8812' @@ -89,6 +111,14 @@ services: - questdb_dev_data:/var/lib/questdb environment: - QDB_TELEMETRY_ENABLED=false + - QDB_RAM_USAGE_LIMIT_BYTES=2147483648 + - JAVA_OPTS=-Xms512m -Xmx1g + healthcheck: + test: ['CMD-SHELL', 'curl -fsS http://127.0.0.1:9003/status >/dev/null 2>&1 || exit 1'] + interval: 30s + timeout: 10s + retries: 3 + start_period: 15s restart: unless-stopped networks: - stock-bot-dev-network diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 21e2e99a..ced20e15 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -1,19 +1,22 @@ -# Production Infrastructure Template (for dedicated production server deployment) +# Production Execution Infrastructure Template (isolated 9900K host โ€” 32 GB RAM) # Provide secrets via a host-managed .env.prod file (never commit production credentials). +# Host prerequisite: sysctl vm.max_map_count >= 1048576 (/etc/sysctl.d/99-stockbot.conf) # Usage: docker compose --env-file .env.prod -f docker-compose.prod.yml up -d name: stock-bot-prod services: dragonfly: - image: docker.dragonflydb.io/dragonflydb/dragonfly:latest + image: docker.dragonflydb.io/dragonflydb/dragonfly:v1.30.3 container_name: stock-bot-prod-dragonfly + mem_limit: 3g ports: - '${BIND_HOST:-127.0.0.1}:${DRAGONFLY_PORT:-6379}:6379' command: - dragonfly - --logtostderr - - --maxmemory=${DRAGONFLY_MAXMEMORY:-8gb} + - --maxmemory=${DRAGONFLY_MAXMEMORY:-2gb} + - --proactor_threads=${DRAGONFLY_THREADS:-4} - --requirepass=${DRAGONFLY_PASSWORD:?DRAGONFLY_PASSWORD is required} - --bind=0.0.0.0 - --default_lua_flags=allow-undeclared-keys @@ -21,7 +24,7 @@ services: - dragonfly_prod_data:/data restart: unless-stopped healthcheck: - test: ['CMD-SHELL', 'redis-cli -a "$DRAGONFLY_PASSWORD" ping'] + test: ['CMD-SHELL', 'redis-cli -a "$$DRAGONFLY_PASSWORD" ping'] interval: 30s timeout: 10s retries: 3 @@ -31,13 +34,25 @@ services: - stock-bot-prod-network postgres: - image: postgres:16-alpine + image: postgres:16.9-alpine container_name: stock-bot-prod-postgres + mem_limit: 4g + shm_size: 1g environment: POSTGRES_DB: ${POSTGRES_DATABASE:-trading_bot_prod} POSTGRES_USER: ${POSTGRES_USERNAME:?POSTGRES_USERNAME is required} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} POSTGRES_INITDB_ARGS: '--encoding=UTF-8' + command: + - postgres + - -c + - shared_buffers=1GB + - -c + - effective_cache_size=3GB + - -c + - work_mem=32MB + - -c + - maintenance_work_mem=256MB ports: - '${BIND_HOST:-127.0.0.1}:${POSTGRES_PORT:-5432}:5432' volumes: @@ -45,7 +60,7 @@ services: - ./database/postgres/init:/docker-entrypoint-initdb.d restart: unless-stopped healthcheck: - test: ['CMD-SHELL', 'pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB"'] + test: ['CMD-SHELL', 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"'] interval: 30s timeout: 10s retries: 3 @@ -53,15 +68,20 @@ services: - stock-bot-prod-network mongodb: - image: mongo:7-jammy + image: mongo:7.0.21-jammy container_name: stock-bot-prod-mongodb + mem_limit: 6g + ulimits: + nofile: + soft: 262144 + hard: 262144 environment: MONGO_INITDB_ROOT_USERNAME: ${MONGODB_USERNAME:?MONGODB_USERNAME is required} MONGO_INITDB_ROOT_PASSWORD: ${MONGODB_PASSWORD:?MONGODB_PASSWORD is required} MONGO_INITDB_DATABASE: ${MONGODB_DATABASE:-stock} ports: - '${BIND_HOST:-127.0.0.1}:${MONGODB_PORT:-27017}:27017' - command: --wiredTigerCacheSizeGB ${MONGODB_CACHE_GB:-16} + command: --wiredTigerCacheSizeGB ${MONGODB_CACHE_GB:-4} volumes: - mongodb_prod_data:/data/db - ./database/mongodb/init:/docker-entrypoint-initdb.d @@ -75,8 +95,13 @@ services: - stock-bot-prod-network questdb: - image: questdb/questdb:latest + image: questdb/questdb:10.2.0 container_name: stock-bot-prod-questdb + mem_limit: 8g + ulimits: + nofile: + soft: 1048576 + hard: 1048576 ports: - '${BIND_HOST:-127.0.0.1}:${QUESTDB_PORT:-9000}:9000' - '${BIND_HOST:-127.0.0.1}:${QUESTDB_PG_PORT:-8812}:8812' @@ -85,6 +110,14 @@ services: - questdb_prod_data:/var/lib/questdb environment: - QDB_TELEMETRY_ENABLED=false + - QDB_RAM_USAGE_LIMIT_BYTES=${QDB_RAM_USAGE_LIMIT_BYTES:-4294967296} + - JAVA_OPTS=-Xms1g -Xmx2g + healthcheck: + test: ['CMD-SHELL', 'curl -fsS http://127.0.0.1:9003/status >/dev/null 2>&1 || exit 1'] + interval: 30s + timeout: 10s + retries: 3 + start_period: 15s restart: unless-stopped networks: - stock-bot-prod-network diff --git a/docker-compose.quant.yml b/docker-compose.quant.yml new file mode 100644 index 00000000..ef3dac50 --- /dev/null +++ b/docker-compose.quant.yml @@ -0,0 +1,60 @@ +# `quant` (10.0.0.51 โ€” i9-12900K, 125 GiB RAM, 4 TB SN850X NVMe) Compose Overlay +# Usage on quant: +# docker compose --env-file .env.quant -f docker-compose.yml -f docker-compose.quant.yml up -d +# +# Required host sysctl (/etc/sysctl.d/99-stockbot.conf): +# vm.max_map_count = 1048576 +# +# Memory allocation summary (125 GiB total, ~24 GiB reserved unallocated for Linux NVMe page cache): +# MongoDB: 24g (WiredTiger 16g during bulk ETL, override MONGODB_CACHE_GB=8 during steady research) +# QuestDB: 28g (QDB_RAM_USAGE_LIMIT_BYTES=20g + JVM 4g) +# PostgreSQL: 10g (shared_buffers=4g, shm_size=2g) +# Dragonfly: 5g (maxmemory=4g, 4 proactor threads) +# Monitoring: 4g (Prometheus + Loki + Grafana + Admin UIs) +# App/DuckDB: 30g (host/container workers: DUCKDB_MEMORY_LIMIT=6GB, DUCKDB_THREADS=4) + +services: + dragonfly: + mem_limit: 5g + cpus: '4.0' + ports: !override + - '${QUANT_BIND_HOST:-10.0.0.51}:6379:6379' + + postgres: + mem_limit: 10g + shm_size: 2g + cpus: '8.0' + ports: !override + - '${QUANT_BIND_HOST:-10.0.0.51}:5432:5432' + + questdb: + mem_limit: 28g + cpus: '12.0' + ulimits: + nofile: + soft: 1048576 + hard: 1048576 + environment: + - QDB_TELEMETRY_ENABLED=false + - QDB_RAM_USAGE_LIMIT_BYTES=21474836480 + - QDB_SHARED_WORKER_COUNT=8 + - JAVA_OPTS=-Xms2g -Xmx4g + ports: !override + - '${QUANT_BIND_HOST:-10.0.0.51}:9000:9000' + - '${QUANT_BIND_HOST:-10.0.0.51}:8812:8812' + - '${QUANT_BIND_HOST:-10.0.0.51}:9009:9009' + + mongodb: + mem_limit: 24g + cpus: '8.0' + ulimits: + nofile: + soft: 1048576 + hard: 1048576 + command: --wiredTigerCacheSizeGB ${MONGODB_CACHE_GB:-16} + ports: !override + - '${QUANT_BIND_HOST:-10.0.0.51}:27017:27017' + + pgadmin: + ports: !override + - '${QUANT_BIND_HOST:-10.0.0.51}:5050:80' diff --git a/docker-compose.yml b/docker-compose.yml index d2a5e9fc..aee09ff5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,25 +1,22 @@ # QA Infrastructure Stack (existing live volumes: stock-bot_mongodb_data, stock-bot_postgres_data, etc.) # WARNING: Do NOT run `docker compose down -v` against this file โ€” mongodb_data holds the full ingested dataset. # For isolated local development, use `docker-compose.dev.yml` (ports 5433, 27018, 6380, 9100). -services: # Dragonfly - Redis replacement for caching and events +# Host prerequisite for QuestDB 10.2.0: sysctl vm.max_map_count >= 1048576 (/etc/sysctl.d/99-stockbot.conf) +name: stock-bot + +services: + # Dragonfly - Redis replacement for caching and BullMQ queues dragonfly: - image: docker.dragonflydb.io/dragonflydb/dragonfly:latest + image: docker.dragonflydb.io/dragonflydb/dragonfly:v1.30.3 container_name: trading-bot-dragonfly + mem_limit: 5g ports: - '127.0.0.1:6379:6379' - deploy: - resources: - limits: - cpus: '4.0' # Use up to 4 CPU cores - memory: 8G # Use up to 8GB RAM - reservations: - cpus: '2.0' # Reserve at least 2 CPU cores - memory: 4G # Reserve at least 4GB RAM command: - dragonfly - --logtostderr - - --maxmemory=8gb - - --proactor_threads=8 + - --maxmemory=4gb + - --proactor_threads=4 - --bind=0.0.0.0 - --admin_port=6380 - --cluster_mode=emulated @@ -39,15 +36,27 @@ services: # Dragonfly - Redis replacement for caching and events networks: - trading-bot-network - # PostgreSQL - Operational data (orders, positions, strategies) + # PostgreSQL 16.9 - Security master, trial_ledger, backtests, research & vault state postgres: - image: postgres:16-alpine + image: postgres:16.9-alpine container_name: trading-bot-postgres + mem_limit: 10g + shm_size: 2g environment: POSTGRES_DB: trading_bot POSTGRES_USER: trading_user POSTGRES_PASSWORD: trading_pass_dev POSTGRES_INITDB_ARGS: '--encoding=UTF-8' + command: + - postgres + - -c + - shared_buffers=4GB + - -c + - effective_cache_size=16GB + - -c + - work_mem=64MB + - -c + - maintenance_work_mem=1GB ports: - '127.0.0.1:5432:5432' volumes: @@ -62,33 +71,51 @@ services: # Dragonfly - Redis replacement for caching and events networks: - trading-bot-network - # QuestDB - Time-series data (OHLCV, indicators, performance) + # QuestDB 10.2.0 - Intraday 1m/5m/1h & hot streaming bars (PARTITION BY MONTH) questdb: - image: questdb/questdb:latest + image: questdb/questdb:10.2.0 container_name: trading-bot-questdb + mem_limit: 28g + ulimits: + nofile: + soft: 1048576 + hard: 1048576 ports: - - '127.0.0.1:9000:9000' # Web console + - '127.0.0.1:9000:9000' # Web console & REST - '127.0.0.1:8812:8812' # PostgreSQL wire protocol - '127.0.0.1:9009:9009' # InfluxDB line protocol volumes: - questdb_data:/var/lib/questdb environment: - QDB_TELEMETRY_ENABLED=false + - QDB_RAM_USAGE_LIMIT_BYTES=21474836480 + - JAVA_OPTS=-Xms2g -Xmx4g + healthcheck: + test: ['CMD-SHELL', 'curl -fsS http://127.0.0.1:9003/status >/dev/null 2>&1 || exit 1'] + interval: 30s + timeout: 10s + retries: 3 + start_period: 20s restart: unless-stopped networks: - trading-bot-network - # MongoDB - Document storage (sentiment, raw docs, unstructured data) + # MongoDB 7.0.21 - Raw provider corpus (~638 GB; read-only to data-pipeline) mongodb: - image: mongo:7-jammy + image: mongo:7.0.21-jammy container_name: trading-bot-mongodb + mem_limit: 24g + ulimits: + nofile: + soft: 1048576 + hard: 1048576 environment: MONGO_INITDB_ROOT_USERNAME: trading_admin MONGO_INITDB_ROOT_PASSWORD: trading_mongo_dev MONGO_INITDB_DATABASE: stock ports: - '127.0.0.1:27017:27017' - command: --wiredTigerCacheSizeGB 20 + command: --wiredTigerCacheSizeGB ${MONGODB_CACHE_GB:-16} volumes: - mongodb_data:/data/db - ./database/mongodb/init:/docker-entrypoint-initdb.d @@ -99,10 +126,13 @@ services: # Dragonfly - Redis replacement for caching and events timeout: 10s retries: 3 networks: - - trading-bot-network # Redis Insight - GUI for Dragonfly debugging + - trading-bot-network + + # Redis Insight - GUI for Dragonfly debugging redis-insight: - image: redislabs/redisinsight:latest + image: redis/redisinsight:2.68 container_name: trading-bot-redis-insight + mem_limit: 512m ports: - '127.0.0.1:8001:5540' depends_on: @@ -113,8 +143,9 @@ services: # Dragonfly - Redis replacement for caching and events # PgAdmin - PostgreSQL GUI pgadmin: - image: dpage/pgadmin4:latest + image: dpage/pgadmin4:9.4 container_name: trading-bot-pgadmin + mem_limit: 768m environment: PGADMIN_DEFAULT_EMAIL: admin@tradingbot.com PGADMIN_DEFAULT_PASSWORD: admin123 @@ -132,8 +163,9 @@ services: # Dragonfly - Redis replacement for caching and events # Mongo Express - MongoDB GUI mongo-express: - image: mongo-express:latest + image: mongo-express:1.0.2-20-alpine3.19 container_name: trading-bot-mongo-express + mem_limit: 512m environment: ME_CONFIG_MONGODB_ADMINUSERNAME: trading_admin ME_CONFIG_MONGODB_ADMINPASSWORD: trading_mongo_dev @@ -151,8 +183,9 @@ services: # Dragonfly - Redis replacement for caching and events # Prometheus - Metrics collection prometheus: - image: prom/prometheus:latest + image: prom/prometheus:v3.4.0 container_name: trading-bot-prometheus + mem_limit: 1g ports: - '127.0.0.1:9090:9090' volumes: @@ -161,6 +194,7 @@ services: # Dragonfly - Redis replacement for caching and events command: - '--config.file=/etc/prometheus/prometheus.yml' - '--storage.tsdb.path=/prometheus' + - '--storage.tsdb.retention.time=15d' - '--web.console.libraries=/etc/prometheus/console_libraries' - '--web.console.templates=/etc/prometheus/consoles' - '--web.enable-lifecycle' @@ -172,6 +206,7 @@ services: # Dragonfly - Redis replacement for caching and events loki: image: grafana/loki:2.9.2 container_name: trading-bot-loki + mem_limit: 768m ports: - '127.0.0.1:3100:3100' volumes: @@ -186,10 +221,12 @@ services: # Dragonfly - Redis replacement for caching and events restart: unless-stopped networks: - trading-bot-network + # Grafana - Visualization for logs and metrics grafana: image: grafana/grafana:10.2.0 container_name: trading-bot-grafana + mem_limit: 512m ports: - '127.0.0.1:3000:3000' environment: @@ -209,8 +246,9 @@ services: # Dragonfly - Redis replacement for caching and events # Bull Board - Queue monitoring bull-board: - image: venatum/bull-board:latest + image: venatum/bull-board:3.3.1 container_name: trading-bot-bull-board + mem_limit: 256m ports: - '127.0.0.1:3001:3000' environment: diff --git a/docs/DATA-CONTRACTS.md b/docs/DATA-CONTRACTS.md index efe4cb2a..f84ef7aa 100644 --- a/docs/DATA-CONTRACTS.md +++ b/docs/DATA-CONTRACTS.md @@ -129,7 +129,18 @@ Plus `resolution_conflict`, `override` (keyed by `(source, source_id, valid_from ### A. DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/`) -All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `TIMESTAMPTZ` (`ts`, `known_at`), and explicit `known_at_source`: +All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `TIMESTAMPTZ` (`ts`, `known_at`), and explicit `known_at_source`. + +- **Bulk ETL rule (`tools/curate-etl`):** Multi-hundred-million and multi-billion-row collections (`eodPrices` `846M`, `eodIntraday1M` `3.40B`, `eodIntraday5M` `1.08B`, `qmFilings` `30.5M`) are curated via a dedicated Rust binary in the Cargo workspace (`mongodb::bson::RawDocumentBuf` zero-copy BSON cursors + in-RAM `provider_mapping`/`qmSplits` lookup tables + `rayon` sharded `parquet`/ILP writers)โ€”**never** through single-threaded JS/Node object-allocation loops. +- **DuckDB connection budget:** Every `MarketDataStore` (TS) and `stockbot.data` (Python) DuckDB instance must execute at connection open: + ```sql + SET memory_limit = '6GB'; + SET threads = 4; + SET temp_directory = '/mnt/data/stockbot/tmp/duckdb'; + ``` + (overridable via env on local dev, e.g. `2GB`/`2` threads) so concurrent campaign workers never inherit DuckDB's default `80%` host-RAM (`~100 GiB`) ceiling. + +Schemas: - **`bars_1d/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, session_date DATE, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume DOUBLE, vwap DOUBLE, currency VARCHAR, source VARCHAR, known_at TIMESTAMPTZ)` โ€” strictly raw OHLC and **un-adjusted** share `volume`, sorted by `(listing_id, session_date)`. - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. @@ -146,7 +157,9 @@ All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `T ### B. QuestDB `10.2.0` (Intraday & Live Streaming) -Image pinned to `questdb/questdb:10.2.0`. `listing_id` is stored as decimal string inside `SYMBOL CAPACITY 65536 NOCACHE` and converted to `number` (`INT32`) at the `MarketDataStore` adapter boundary: +Image pinned to `questdb/questdb:10.2.0`. Host kernel must enforce `vm.max_map_count >= 1048576` (`/etc/sysctl.d/99-stockbot.conf`), container `ulimits.nofile` set to `1048576`, and off-heap memory bounded via `QDB_RAM_USAGE_LIMIT_BYTES=21474836480` (`20 GiB`) + JVM `-Xms2g -Xmx4g` inside a `28g` container `mem_limit` on `quant`. + +`listing_id` is stored as decimal string inside `SYMBOL CAPACITY 65536 NOCACHE` and converted to `number` (`INT32`) at the `MarketDataStore` adapter boundary. `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions / `~3,780` files across 22.5 years at `~13.2M` rows/month, vs. `~5,670` partitions / `~79,000` files under `PARTITION BY DAY`โ€”cutting 1-year `W2` cold partition seeks from 252 to 12 while keeping live monthly WAL `< 40 MB`): ```sql CREATE TABLE IF NOT EXISTS bars_1m ( @@ -161,7 +174,7 @@ CREATE TABLE IF NOT EXISTS bars_1m ( source SYMBOL CAPACITY 8 CACHE, -- 'eod_unadj' | 'qm_raw' | 'ib_live' known_at TIMESTAMP, ts TIMESTAMP -) TIMESTAMP(ts) PARTITION BY DAY WAL +) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id); CREATE TABLE IF NOT EXISTS fx_1m ( diff --git a/docs/MILESTONES.md b/docs/MILESTONES.md index 751e45f7..36a4289c 100644 --- a/docs/MILESTONES.md +++ b/docs/MILESTONES.md @@ -37,6 +37,9 @@ Actionable build tracker for turning Stock Bot into the AI algo research & IB li - [ ] **Purge hardcoded credentials & close `sb-research.*` holdout leak:** - Rotate and remove the hardcoded Webshare proxy URL in `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` (read from env only) and extend `scripts/audit-secrets.ts` to catch `http(s)://user:pass@` literals; also fix `fetch-symbols.action.ts:108` (`ib_symbols` โ†’ `ibSymbols`). - Remove `GET /api/v2/datasets/canonical/:hash/export` from `sb-research.*` permissions in `apps/stock/web-api/src/services/research-agents.service.ts:51` and scope agent `GET` routes to granted projects/templates. +- [ ] **Pin container tags, kernel limits & `quant` RAM caps:** + - Replace all `:latest` / floating tags in `docker-compose*.yml` with exact pinned versions (`questdb:10.2.0`, `postgres:16.9-alpine`, `mongo:7.0.21-jammy`, `dragonfly:v1.30.3`, etc.). + - Configure `shm_size` (`2g` on `quant`, `512m` in dev) for PostgreSQL 16 parallel workers, `ulimits.nofile = 1048576` on QuestDB/MongoDB, `/etc/sysctl.d/99-stockbot.conf` (`vm.max_map_count = 1048576`) on `quant`, and hard `mem_limit` + engine caps in `docker-compose.quant.yml` (reserving `~24 GiB` of `125 GiB` for OS page cache). ### Exit Criteria 1. `CARGO_BUILD_JOBS=2 bun run check` passes all 11 gates (`0` errors, `0` warnings). @@ -57,13 +60,14 @@ Actionable build tracker for turning Stock Bot into the AI algo research & IB li - Implement Pass 2 normalization (fix `provider-symbol.ts` for IB `exchangeId`/`description`; ticker root/suffix parser; ISIN Luhn validator + CUSIPโ†’ISIN derivation; precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`). - Implement Pass 3 two-stage matching (Stage A: global ISIN/CUSIP โ†’ `instrument`; Stage B: EOD/QM venue โ†’ `listing`, IB `conid` attached at `(instrument_id, currency)`, temporal bar-span overlap required on Tier 3/4 ticker matches) + Pass 6 OTC delisting chains (`SIVB` โ†’ `SIVBQ`). - Implement Pass 4 batch 25-date cross-sectional price cross-check (`{ date: { $in: sampleDates } }`) and export US+CA match & conflict report + `override` seed file. -- [ ] **Step 2 Core โ€” Daily, Corporate Actions, FX & Events (`Parquet + DuckDB`):** +- [ ] **Step 2 Core โ€” Zero-Copy Rust Bulk ETL + Daily, Actions, FX & Events (`Parquet + DuckDB`):** + - Build `tools/curate-etl` in the Cargo workspace (`mongodb::bson::RawDocumentBuf` zero-copy BSON cursors + preloaded in-RAM `provider_mapping`/`qmSplits` tables + `rayon` sharded Zstd `parquet` writer) so `846M` `eodPrices` rows (and `3.40B` `eodIntraday1M` rows in `M2`) never iterate through single-threaded JS object loops. - Curate `bars_1d` (un-adjusting `eodPrices.volume` via `qmSplits` and cross-checking `qmPrices.sharevolume`). - Curate `corporate_actions` & `adj_factors` (`qmSplits` excluding `1:1` no-ops, `qmDividends` ignoring bogus `usdFxRate: 1`, plus OTC continuation & `-30%`/`-100%` Shumway terminal delisting events). - Curate `fx_1d` (`CAD.FOREX` 1971โ€“2025 + `teMarketData.USDCAD` through 2026). - Curate `events` (`qmFilings` UTC-converted `timefiled` + form groups; `qmEarnings` linked to `qmFilings` or lagged to `16:05 ET` when `announceTime == 'N/A'`) and `shorts` (`ceoShorts` with `+4` Canadian business-day `known_at` lag). - [ ] **`MarketDataStore` + Rolling 6-Month Vault + `trial_ledger`:** - - Implement `MarketDataStore` (TS) and `stockbot.data` (Python) over DuckDB + Parquet with mandatory `known_at <= asOf` and `ts < VAULT_CUTOFF_TS` (`max_ingested_ts - 6 months`) enforcement. + - Implement `MarketDataStore` (TS) and `stockbot.data` (Python) over DuckDB + Parquet with mandatory `known_at <= asOf`, `ts < VAULT_CUTOFF_TS` (`max_ingested_ts - 6 months`), and per-connection `SET memory_limit = '6GB'; SET threads = 4; SET temp_directory = ...` enforcement. - Add PostgreSQL `trial_ledger` and `vault_evaluations` tables (protected by `reject_research_evidence_mutation()`) + canonical DSR ($\hat{N}$ effective trials) in `@stock-bot/calculations` (see [VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)). - [ ] **Signal Analyzer + `marimo` Workspace:** - Implement `analyze_signal` and `event_study` (IC, rank-IC, quantile spreads, turnover, pre/post-2023 recency split, Newey-West $t$-stat, automatic `trial_ledger` write). @@ -88,8 +92,8 @@ Actionable build tracker for turning Stock Bot into the AI algo research & IB li - Materialize 2D `(period_end, known_at)` deduplicated wide snapshots + TTM features (`fundamentals_pit`). - Curate `ceoPosts` (`14.8M`) separating `bot == "1"` newswires from retail posts and guarding `edited != null` text timestamps; curate lagged `teData` regime series. - [ ] **Intraday Curation (`QuestDB 10.2.0`):** - - Pin `questdb/questdb:10.2.0` in `docker-compose*.yml`; replace legacy `libs/data/questdb` (`LATEST BY` โ†’ `LATEST ON`, parameterized PG queries, ILP batch writer). - - Load split-unadjusted `eodIntraday1M` (US 2003โ€“2025), raw `qmIntraday` (CA/US 2024โ€“2025), and `CAD.FOREX` `1m` (`5.2M` bars) into `bars_1m` and `fx_1m` (`listing_id SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS(ts, listing_id)`). + - Replace legacy `libs/data/questdb` (`LATEST BY` โ†’ `LATEST ON`, parameterized PGWire queries, ILP v2 batch writer); verify `vm.max_map_count >= 1048576` and `ulimits.nofile = 1048576` on `quant` before bulk load. + - Extend `tools/curate-etl` with sharded multi-socket ILP v2 writers to stream split-unadjusted `eodIntraday1M` (`3.40B` rows, US 2003โ€“2025), raw `qmIntraday` (CA/US 2024โ€“2025), and `CAD.FOREX` `1m` (`5.2M` bars) into **`PARTITION BY MONTH`** `bars_1m` (`270` partitions across 22.5y) and `fx_1m` (`listing_id SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS(ts, listing_id)`). - [ ] **Versioned Feature Library (`D04` reopened):** - Build declarative SQL/Polars batch runner writing versioned `(listing_id, ts, known_at, value)` columns + `register_signal(...)` SDK entrypoint. @@ -108,9 +112,10 @@ Actionable build tracker for turning Stock Bot into the AI algo research & IB li - [ ] **Tier 1 Columnar Screener:** - Vectorized Polars/DuckDB portfolio sweep (`signal ร— universe ร— rebalance ร— cost`), writing full $M_{T \times N}$ return matrices to `trial_ledger` and computing CSCV PBO ($S = 16$). - [ ] **Tier 2 Rust `financial/` Multi-Asset Upgrades (`apps/stock/engine/src/financial/*`):** + - **Task 1 โ€” Retire JSON-over-Postgres/IPC/N-API bar path (prerequisite):** Store only `(hash, manifest, parquet_paths)` in `backtest_datasets` (retiring the `255 MB`-capped `payload JSONB` blob), pass only the manifest + read-only Parquet paths through `NativeBacktestWorker` IPC and N-API so Rust `parquet`/`arrow-rs` reads columns directly with zero JS bar objects, replace per-bar JSON stdio in `candidate-sandbox.ts` with compact Arrow IPC / `Float64Array` barrier frames, remove `serde_json::Value` triple-parsing from bulk payloads in `api/canonical.rs`, and lift single-series TS gates in `native-worker.ts`. - **Atomic timestamp-slice marks (`F06`):** Update all marks at timestamp `t` before checking `RiskAccount` daily-loss/drawdown latches. - **Simultaneous `Target` sell-netting:** Credit haircut-adjusted pending `Sell` proceeds toward same-barrier `Buy` reservations in `MatchingAccount::submit`. - - **Feature side-channel & Arrow loader:** Pass precomputed `features` into `Replay` decision barriers and `StrategyContext`; load bars/features from Parquet/Arrow paths instead of Postgres `JSONB` snapshots; remove duplicate `serde_json::Value` parse in `api/canonical.rs`; lift single-series TS gates in `native-worker.ts` and `candidate-sandbox.ts`. + - **Feature side-channel:** Pass precomputed `features` columns into `Replay` decision barriers and `StrategyContext`. - **Long/short, multi-currency Margin & corporate actions:** Signed positions/targets + borrow fee accrual; `BTreeMap` (`USD`/`CAD` cash & negative margin-loan interest + `FXCONV` sweeps + tradable FX pairs); ex-date splits, cash dividends, TSX/TSXV `100/500/1000` board-lot rounding, and OTC/Shumway delisting liquidations. - [ ] **Validation Suite & Engine Consolidation:** - Add Purged Walk-Forward & CPCV (`purge = horizon + warmup`, `embargo = max(5d, 0.01 * T)`), parameter stability surface, capacity (ADV participation), and US/CA factor exposure (`MKT`, `SMB`, `HML`, `MOM`). diff --git a/docs/PLATFORM-PLAN.md b/docs/PLATFORM-PLAN.md index bf8dcc6b..dacbb6e5 100644 --- a/docs/PLATFORM-PLAN.md +++ b/docs/PLATFORM-PLAN.md @@ -150,7 +150,7 @@ APP (web-app): Lab (+ marimo) ยท Agents ยท Strategies ยท Data ยท Trading ยท Mark | Layer | Owns | Language | | --- | --- | --- | | `data-ingestion` | Provider crawlers โ†’ raw MongoDB (scheduled jobs disabled outside dedicated ingester) | TypeScript | -| `data-pipeline` | Entity resolution, split/volume un-adjustment, PIT curation, batch features โ†’ Postgres + Parquet + QuestDB | TypeScript + Python/DuckDB batch | +| `data-pipeline` + `curate-etl` | Entity resolution & orchestration (TS), zero-copy BSON bulk bar ETL (`tools/curate-etl` in Rust), PIT/feature batch jobs โ†’ Postgres + Parquet + QuestDB | TypeScript + Rust (`RawDocumentBuf`/Arrow/ILP) + Python/DuckDB | | Research kernel | Single API + MCP server enforcing vault cutoff, budgets, trial ledger, and canonical metrics | TypeScript (`web-api` / `orchestrator` / `@stock-bot/calculations`) | | Engine | Authoritative accounting, multi-currency margin ledger, corporate actions, fills, risk, replay | Rust (`apps/stock/engine/src/financial`) | | Python SDK + marimo | Exploration, Signal Analyzer, Event Study, Tier 1 columnar screener, feature batch definitions | Python (`polars`, `duckdb`, `marimo`) | @@ -176,9 +176,10 @@ Full schemas and SQL contracts live in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)* ### Access rules & performance targets 1. **One access contract (`MarketDataStore` in TS, `stockbot.data` in Python).** Every non-vault call enforces `ts < VAULT_CUTOFF_TS` and `known_at <= asOf` inside the adapter. No raw-SQL escape hatch is exposed to agents; human localhost sessions may query read-only pre-vault DuckDB views. -2. **Storage hygiene.** +2. **Storage & memory hygiene.** - `MarketDataStore` and Parquet expose `listing_id` as `INT32`; inside QuestDB `10.2.0`, `listing_id` is stored as `SYMBOL CAPACITY 65536 NOCACHE` so `LATEST ON` backward partition scans and `ASOF JOIN` fast paths work without JVM heap bloat. - - Sealed `>90d` QuestDB `bars_1m` partitions may be compressed in-place (`ALTER TABLE bars_1m CONVERT PARTITION TO PARQUET`) if NVMe capacity requires it; recent partitions remain native mmap. + - QuestDB `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions across 22.5y instead of `~5,670` daily partitions) with host `vm.max_map_count >= 1048576`, `ulimits.nofile = 1048576`, and `QDB_RAM_USAGE_LIMIT_BYTES` capped (`20 GiB` on `quant`). Sealed `>90d` monthly partitions may be compressed in-place (`ALTER TABLE bars_1m CONVERT PARTITION TO PARQUET`) if NVMe capacity requires it; recent partitions remain native mmap. + - Every DuckDB connection explicitly sets `memory_limit = '6GB'`, `threads = 4`, and `temp_directory` on `quant` (instead of DuckDB's `80%` host-RAM default), leaving `~24 GiB` of `quant`'s `125 GiB` unallocated for Linux NVMe page cache. 3. **Measured storage targets on `quant` (`12900K`, SN850X NVMe):** - **W1:** 20y US+CA daily universe (~15k active+delisted listings, ~45M bars) + 1 signal IC/quantile scan: **`< 3 s` warm / `< 8 s` cold**. - **W2:** 1 listing, 1y of `1m` bars (~100kโ€“200k rows) from QuestDB: **`< 250 ms` warm / `< 1 s` cold**. @@ -264,7 +265,7 @@ Extends the existing 8-decimal Rust kernel (retiring legacy `f64` `BacktestEngin - **Atomic timestamp-slice marking (`F06` fix):** Apply all instrument marks at timestamp `t` before evaluating `RiskAccount` portfolio drawdown/daily-loss latches so hedged long/short moves never trigger false intermediate halts. - **Simultaneous target rebalancing:** Credit haircut-adjusted pending `Sell` proceeds against same-barrier `Buy` reservations in `MatchingAccount::submit` so fully invested cross-sectional rotations execute cleanly in one barrier. -- **Feature side-channel & Arrow loading:** Load market bars + precomputed `features` directly from Parquet/Arrow into Rust (eliminating PostgreSQL's 1 GB `JSONB` snapshot ceiling and removing double `serde_json::Value` parsing in `api/canonical.rs`), triggering JS/sandbox callbacks **only on declared rebalance barriers**. +- **Zero-JSON market-data path & Feature side-channel:** Eliminate the 8ร— JSON/Zod/IPC/N-API bar path (`backtest_datasets.payload` `255 MB` `JSONB` ceiling, `structuredClone`, `fork({ serialization: 'json' })`, and `api/canonical.rs` triple `serde_json::Value` parse). Retain only `(hash, manifest, parquet_paths)` in PostgreSQL, read Parquet/Arrow columns directly inside Rust `Replay`, restrict `canonical.rs` `keys_match` to small control/config envelopes, and stream multi-asset decision-barrier slices to `candidate-sandbox.ts` as compact **Arrow IPC / flat `Float64Array` binary frames** on declared rebalance barriers. - **Long/short, multi-currency margin & corporate actions:** Signed quantities/targets, short borrow fee accrual, `BTreeMap` (`USD` + `CAD` cash/margin balances with IB benchmark+spread interest on negative balances, plus tradable FX pairs), ex-date split share adjustments, cash dividend postings, TSX/TSXV board-lot sizing (`100`/`500`/`1,000` shares), and OTC/Shumway delisting liquidations. ### Validation suite, Trial Ledger & 6-Month Vault diff --git a/docs/README.md b/docs/README.md index 7b20c7a9..0157ab05 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,7 +29,6 @@ These documents describe **what is already implemented and running in code today | **[guide/code-reading.md](guide/code-reading.md)** | Function-level call paths across `web-api`, `orchestrator`, and `engine` | | **[backtest-datasets.md](backtest-datasets.md)** | Current v2 retained dataset snapshot preparation, hashing, and local export | | **[data-pipeline/phase1-investigation.md](data-pipeline/phase1-investigation.md)** | Measured 31-collection QA MongoDB inventory, identifier coverage, and cross-provider tricky cases | -| **[cleanup-audit.md](cleanup-audit.md)** | Separation between reviewed `@stock-bot/calculations` core and preserved `/legacy` functions | --- diff --git a/docs/cleanup-audit.md b/docs/cleanup-audit.md deleted file mode 100644 index bce95cb0..00000000 --- a/docs/cleanup-audit.md +++ /dev/null @@ -1,50 +0,0 @@ -# Shared-library cleanup: preservation and removal audit - -This records the shared-library cleanup following `ccce401`. It does not -claim to audit every deletion from the earlier execution/strategy refactors. The first -pass inferred that no current imports meant no future value; that was too broad for a -trading/feature-engineering repository. This revision separates capabilities by ownership -and readiness instead of deleting them on usage alone. - -| Previously removed item | Current disposition | -| ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Active basic calculations, technical indicators, risk and performance modules | All 105 exported functions preserved in `libs/calculations/src/legacy/`, with original executable bodies. Explicit `@stock-bot/calculations/legacy` entry; not endorsed as reviewed core. | -| Tested orchestrator equity/return/trade/performance and window math | Moved into supported `@stock-bot/calculations/analytics` and `/indicators`; report/strategy consumers migrated. No strategy checkpoint/version changes. | -| Generic OHLCV extraction, features, grouping/filtering and timestamps | All 13 helpers restored to `@stock-bot/calculations/market-data`. SMA/return formulas delegate to reviewed core; invalid-input, VWAP and grouping behavior hardened as documented. | -| Seven `.disabled` math modules | Full original sources preserved as verified Markdown research snapshots, including unique indicators and numerical prototypes. Not activated or silently labeled production-ready. | -| `POSITION_SIZING_FIXES.md` | Preserved as historical research notes with an explicit warning that its correctness/production claims were not independently verified. | -| Proxy URL and sleep helpers | Restored to `@stock-bot/utils/common` and named root exports. | -| Date helpers | Restored to `@stock-bot/utils/dates`: validated UTC weekday/date functions; old `dateUtils` names retained as deprecated aliases. Not an exchange/holiday calendar. UTC semantics replace the old environment-dependent local calendar arithmetic. | -| `utils` assertion facade | Remains removed. `at`/`defined` are unchanged in `@stock-bot/invariants`; all consumers import the actual owner. This removes a duplicate entry point, not the functionality. | -| Domain-type re-exports through the calculation barrel | Domain types remain unchanged in `@stock-bot/types`; callers import the owner, rather than maintaining another re-export layer. | -| Empty `analyzePortfolio` API | Remains removed: it returned empty objects and implemented no calculation. Real legacy/research portfolio functions are preserved above. | -| Old generic utility test file | Its 21 existing cases were split into 13 market-data tests and 8 common/date tests at the owning packages, with UTC assertions and new boundary tests. No executed behavior coverage was discarded merely for being unused by apps. | -| `connection-manager.test.ts.old` and `redis-cache.test.ts.old` | Remain removed as `.old` files; full source/scenarios preserved in cache test references. These were not run by the test runner. They contain 27 and 47 cases, respectively, and are not all equivalent to the active tests. Some target absent APIs; the connection-manager suite is skipped and has broken mock names. No passing coverage is claimed. | -| Old handler-registry singleton implementation | Remains removed. The metadata/configuration/service/scheduling registry lives in `@stock-bot/handler-registry`; no imports used the `.old` singleton. Reintroducing it would create another registry authority. | -| `simple-statistics`, unused utility dependencies/references in orchestrator/coverage CLI, and config/cache/type dependencies in general utilities | Remain removed. No live imports required them. The orchestrator now declares the actual calculation workspace; the calculation package has no infrastructure/native dependencies. | - -## Preservation evidence and readiness - -[The calculation inventory](../libs/calculations/migration-audit.json) records every -previously exported math function, source provenance, legacy AST hashes and research -source hashes. Tests verify all 105 legacy exports and their unchanged executable bodies, -and all seven research snapshots. This proves source/capability preservation, **not** -algorithmic correctness. The reviewed core is tested separately; legacy functions can -still contain zero/Infinity fallbacks, inconsistent conventions or incomplete formulas. - -[The calculation contract](../libs/calculations/README.md) specifies supported units, -warm-up/alignment, invalid-result policies and the promotion path for legacy/research -functions. [Research concerns](../libs/calculations/research/README.md) identify known -limitations before reuse. Supported stock application code cannot import the legacy -tier, and no supported math module can load it transitively. - -The retired Redis test sources are retained as -[connection-manager scenarios](../libs/core/cache/test/references/connection-manager-tests.md) -and [cache scenarios](../libs/core/cache/test/references/redis-cache-tests.md). Their -valid assertions should be ported with correct public contracts and isolated fixtures; -archived source is deliberately not counted in any test totals. - -This revision does not change cache production code, trading/execution behavior, -persisted data, environment files or WCAG. General date helpers and OHLCV edge-case -contracts are the explicit behavior corrections noted above; old legacy math remains -unchanged and opt-in. diff --git a/docs/data-pipeline/phase1-investigation.md b/docs/data-pipeline/phase1-investigation.md index 8c5f48c8..0388b81c 100644 --- a/docs/data-pipeline/phase1-investigation.md +++ b/docs/data-pipeline/phase1-investigation.md @@ -295,8 +295,8 @@ The deterministic selection produced **25 candidates** across 5 buckets. The sam [`libs/core/queue/src/queue-manager.ts`](../../libs/core/queue/src/queue-manager.ts) ยท [`libs/core/handlers/src/index.ts`](../../libs/core/handlers/src/index.ts) ยท [`apps/stock/data-pipeline/src/handlers/index.ts`](../../apps/stock/data-pipeline/src/handlers/index.ts) ยท [`apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts) ยท [`apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts) - **HTTP API**. Hono routers delegate to services. [`apps/stock/web-api/package.json`](../../apps/stock/web-api/package.json) ยท [`apps/stock/web-api/src/routes/exchange.routes.ts`](../../apps/stock/web-api/src/routes/exchange.routes.ts) ยท [`apps/stock/web-api/src/routes/pipeline.routes.ts`](../../apps/stock/web-api/src/routes/pipeline.routes.ts) -- **Tests**. The pipeline package runs Bun tests. The Mongo workspace has an example Bun test suite. - [`apps/stock/data-pipeline/package.json`](../../apps/stock/data-pipeline/package.json) ยท [`libs/data/mongodb/test/mongodb.test.ts`](../../libs/data/mongodb/test/mongodb.test.ts) +- **Tests**. The pipeline package and environment safety suite run Bun tests. + [`apps/stock/data-pipeline/package.json`](../../apps/stock/data-pipeline/package.json) ยท [`test/unit/environment-safety.test.ts`](../../test/unit/environment-safety.test.ts) - **Web app**. React and Vite, with the application split into feature folders. [`apps/stock/web-app/package.json`](../../apps/stock/web-app/package.json) ยท [`apps/stock/web-app/vite.config.ts`](../../apps/stock/web-app/vite.config.ts) ยท [`apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx`](../../apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx) diff --git a/docs/development/QUALITY-GATES.md b/docs/development/QUALITY-GATES.md index cc5a8e29..3c3ce22e 100644 --- a/docs/development/QUALITY-GATES.md +++ b/docs/development/QUALITY-GATES.md @@ -26,7 +26,7 @@ Timing/risk policy regressions also include adjacent_open_zero_latency, positive ## G2 โ€” Durability and recovery -Existing [order execution](../../test/postgres/order-execution.test.ts), [strategy recovery](../../test/postgres/strategy-recovery.test.ts) and [durable backtest](../../test/postgres/durable-backtest.test.ts) cases are mandatory for touching those boundaries. Inject failures before/after decision, intent, fill, snapshot, result commits and publication. Verify stale attempt fencing, duplicate IDs, pending inputs, cancellation and restore-before-each-decision. Recovery must preserve per-effect context, not just final balances. +Existing [canonical paper](../../test/postgres/canonical-paper.test.ts), [canonical paper crash](../../test/postgres/canonical-paper-crash.test.ts) and [durable backtest](../../test/postgres/durable-backtest.test.ts) cases are mandatory for touching those boundaries. Inject failures before/after decision, intent, fill, snapshot, result commits and publication. Verify stale attempt fencing, duplicate IDs, pending inputs, cancellation and restore-before-each-decision. Recovery must preserve per-effect context, not just final balances. No tests against a development trading account/database. `bun run test:postgres` requires a disposable `stock_bot_safety*` database and dedicated Redis DB15 via `PIPELINE_TEST_DATABASE_URL` and `BACKTEST_TEST_REDIS_URL`. Provision/start containers only when execution and resource use are authorized. @@ -56,7 +56,7 @@ bun run check bun run test:postgres ``` -`bun run check` runs build/types/contracts/tooling/utils/calculations/integration/native/lint and secret audit; it **does not include** disposable PostgreSQL, browser E2E or Python analytics. Run `bun run test:e2e` separately for the web workbench and `bun run test:analytics-api` if Python API behavior is touched. Native command is `cargo test -p engine --lib --offline`; missing dependencies are a reported blocker, not a pass. +`bun run check` runs build/types/contracts/tooling/utils/calculations/integration/native/lint and secret audit; it **does not include** disposable PostgreSQL or browser E2E. Run `bun run test:e2e` separately for the web workbench. Native command is `cargo test -p engine --lib --offline`; missing dependencies are a reported blocker, not a pass. The browser gate requires a built checkout, explicit `PIPELINE_TEST_DATABASE_URL` pointing to a disposable `stock_bot_safety*` database, dedicated Redis DB15 in `BACKTEST_TEST_REDIS_URL`, and Chromium. Install the pinned browser explicitly with `bun run test:e2e:install` if missing; do not install browsers implicitly during checks. The command rebuilds the frontend for same-origin production use. It exercises authenticated HTTP/WebSocket routes, durable dispatch and SQL persistence with deterministic UI fixtures plus an actual native smoke run. Fixture results are not financial-correctness evidence. Never use a development trading database or queue. diff --git a/docs/development/architecture/decisions/001-ownership.md b/docs/development/architecture/decisions/001-ownership.md index 86db1e46..3f9e5416 100644 --- a/docs/development/architecture/decisions/001-ownership.md +++ b/docs/development/architecture/decisions/001-ownership.md @@ -8,7 +8,7 @@ TypeScript owns product/application logic, strategy authoring, signal/regime com ## Rationale and evidence -Current TypeScript [applyFill](../../../../apps/stock/orchestrator/src/execution/model.ts#L108) and Rust [process_fill](../../../../apps/stock/engine/src/backtest/engine.rs#L426) are competing authorities. Consolidation removes behavioral drift; moving all authoring to Rust would reduce flexibility without proving a throughput benefit. +Historical TypeScript `applyFill` (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup) and Rust [process_fill](../../../../apps/stock/engine/src/backtest/engine.rs#L426) were competing authorities. Consolidation removes behavioral drift; moving all authoring to Rust would reduce flexibility without proving a throughput benefit. ## Alternatives and tradeoffs diff --git a/docs/development/architecture/decisions/002-financial-policy.md b/docs/development/architecture/decisions/002-financial-policy.md index 2e8e1713..08861a37 100644 --- a/docs/development/architecture/decisions/002-financial-policy.md +++ b/docs/development/architecture/decisions/002-financial-policy.md @@ -18,7 +18,7 @@ C03 only adds unpaid-fee liability to the **existing non-reducing gross-capital ## Evidence / alternative costs -[TS amount/cost basis](../../../../apps/stock/orchestrator/src/execution/model.ts#L81), [aggregate owner attribution problem](../../../../apps/stock/orchestrator/src/execution/model.ts#L108), [native fill broadcast](../../../../apps/stock/engine/src/backtest/engine.rs#L489). Exact postings fix arithmetic, not market modeling. A full multicurrency double-entry/margin/borrow engine is not required for v1. +Historical TS amount/cost basis and aggregate owner attribution (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup), [native fill broadcast](../../../../apps/stock/engine/src/backtest/engine.rs#L489). Exact postings fix arithmetic, not market modeling. A full multicurrency double-entry/margin/borrow engine is not required for v1. ## Migration and tests diff --git a/docs/development/architecture/decisions/003-time-and-datasets.md b/docs/development/architecture/decisions/003-time-and-datasets.md index 0c0ffdfd..c506452c 100644 --- a/docs/development/architecture/decisions/003-time-and-datasets.md +++ b/docs/development/architecture/decisions/003-time-and-datasets.md @@ -18,7 +18,7 @@ Status: **approved by owner, 2026-10-22** (explicit โ€œyesโ€ to ADR-002/003/004 ## Evidence and rationale -[Current same-event execution](../../../../apps/stock/engine/src/backtest/engine.rs#L249), [bar-close bid/ask](../../../../apps/stock/orchestrator/src/services/ExecutionService.ts#L224), [v1 timestamp contract](../../../../libs/core/types/src/historical-data.ts#L90), [invented VWAP](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230). +[Current same-event execution](../../../../apps/stock/engine/src/backtest/engine.rs#L249), historical bar-close bid/ask (`orchestrator/src/services/ExecutionService.ts`, retired in pre-M0 cleanup), [v1 timestamp contract](../../../../libs/core/types/src/historical-data.ts#L90), [invented VWAP](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230). ## Alternatives / tradeoffs diff --git a/docs/development/architecture/decisions/005-durable-cutover.md b/docs/development/architecture/decisions/005-durable-cutover.md index 2762c2ec..761dcfee 100644 --- a/docs/development/architecture/decisions/005-durable-cutover.md +++ b/docs/development/architecture/decisions/005-durable-cutover.md @@ -14,7 +14,7 @@ TS owns SQL custody, not independent accounting. No native/DB two-phase commit a ## Decision durability -Preserve [restore-before-each-step and intent transactions](../../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [account locks and duplicate/conflict handling](../../../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts#L46), and existing failure tests. Paper strategy contexts use committed event views; never substitute a later account state. Restore RNG/decision cursors along with checkpoint state. +Preserve durable step recovery, account locks, and duplicate/conflict handling in [canonical paper execution custody](../../../../apps/stock/orchestrator/src/execution/canonical-paper.ts), along with existing failure tests. Paper strategy contexts use committed event views; never substitute a later account state. Restore RNG/decision cursors along with checkpoint state. All currently supported paper order policies must be preserved or a migration explicitly refused. F05 covers market/limit and DAY/GTC/IOC/FOK; do not silently drop IOC/FOK at cutover. diff --git a/docs/development/architecture/decisions/007-ai-boundary.md b/docs/development/architecture/decisions/007-ai-boundary.md index 5b18ef9c..8674dc13 100644 --- a/docs/development/architecture/decisions/007-ai-boundary.md +++ b/docs/development/architecture/decisions/007-ai-boundary.md @@ -16,7 +16,7 @@ The first isolation profile is a local Linux x86_64 Docker scratch image contain ## Evidence -[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. [Current registry dependencies](../../../../apps/stock/orchestrator/src/strategies/StrategyRegistry.ts#L7) expose execution services that the new decision API must not expose. +[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. Historical `StrategyRegistry.ts` (retired in pre-M0 cleanup) exposed execution services that the new decision API must not expose. ## Alternatives / tradeoffs diff --git a/docs/development/architecture/overview.md b/docs/development/architecture/overview.md index e3e370ce..8cdd4f7f 100644 --- a/docs/development/architecture/overview.md +++ b/docs/development/architecture/overview.md @@ -31,7 +31,7 @@ flowchart LR WS --> UI ``` -Evidence: [transactional submission](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [dataset freeze](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190), [recovery](../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [shared mode mutation](../../../apps/stock/orchestrator/src/container.ts#L101). +Evidence: [transactional submission](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [dataset freeze](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190), legacy `StrategyRecovery.ts` (retired in pre-M0 cleanup), [container composition](../../../apps/stock/orchestrator/src/container.ts). ## Target: one product, one financial core diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index 15446fe8..f7257ecd 100644 --- a/docs/guide/backtest-walkthrough.md +++ b/docs/guide/backtest-walkthrough.md @@ -86,7 +86,7 @@ If a run ends with an open position, Rust values the remaining position using it ## 5. Save and inspect the result -Rust returns financial facts, including orders, fills, positions and valuation. [`buildCanonicalBacktestReport()`](../../apps/stock/orchestrator/src/backtest/canonical-result.ts) derives statistical analysis from those facts without replacing the ledger. Unavailable metrics retain an explicit reason; an absent win rate or benchmark comparison is not zero performance. +Rust returns financial facts, including orders, fills, positions and valuation. [`buildCanonicalBacktestReport()`](../../libs/research/src/results.ts) derives statistical analysis from those facts without replacing the ledger. Unavailable metrics retain an explicit reason; an absent win rate or benchmark comparison is not zero performance. `BacktestRunner` validates the result and commits it through [`PostgresBacktestRunRepository`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts). Completion notifications follow persistence. The browser's [CanonicalResults](../../apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx) and [ResultProvenance](../../apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx) render this saved record. Reloading the page reads the same run; it does not rerun the simulation. WebSocket updates help refresh the display, but the database owns status and results. diff --git a/docs/guide/strategy-development.md b/docs/guide/strategy-development.md index 5582cf71..60170d77 100644 --- a/docs/guide/strategy-development.md +++ b/docs/guide/strategy-development.md @@ -33,7 +33,7 @@ Keep history in explicit state, use engine time instead of `Date.now()`, and avo ## A minimal callback shape -Import author types from `@stock-bot/research/strategy-api`. This subpath contains only types; it exposes no native sessions, execution controllers, brokers, or storage services. Existing host imports of `contracts/canonical-strategy.ts` remain compatible. +Import author types from `@stock-bot/research/strategy-api`. This subpath contains only types; it exposes no native sessions, execution controllers, brokers, or storage services. This simple callback requests one share when its series is fresh. It demonstrates the authoring contract; it is not a validated investment strategy or a ready-to-upload candidate package. @@ -89,7 +89,7 @@ The built-ins use [wholeShareTarget](../../apps/stock/orchestrator/src/strategie The strategy combines these values into entry and exit decisions and remembers desired exposure through partial execution. Keep a new feature or filter similarly explicit. Reuse the [calculation library](../../libs/calculations/README.md); do not create another ledger or fill calculator. No universal signal framework is required to add a second condition. -For a first change, follow one parameter from [the built-in selection schemas](../../apps/stock/orchestrator/src/contracts/builtin-strategy.ts), through the calculation and decision, into the [regime fixture](../../test/fixtures/canonical-regime-research.ts). Add a small test with known prices and expected targets before trying larger datasets. Compare the filter on/off under identical inputs using [the existing comparison example](../../apps/stock/orchestrator/examples/canonical-regime-research.ts). A favorable comparison still needs held-out validation. +For a first change, follow one parameter from [the built-in selection schemas](../../apps/stock/config/src/contracts/builtin-strategy.ts), through the calculation and decision, into the [regime fixture](../../test/fixtures/canonical-regime-research.ts). Add a small test with known prices and expected targets before trying larger datasets. Compare the filter on/off under identical inputs using [the existing comparison example](../../apps/stock/orchestrator/examples/canonical-regime-research.ts). A favorable comparison still needs held-out validation. ## From source code to a saved candidate diff --git a/docs/guide/system-map.md b/docs/guide/system-map.md index 0e0b66f2..ffcc273b 100644 --- a/docs/guide/system-map.md +++ b/docs/guide/system-map.md @@ -56,7 +56,7 @@ An untrusted candidate strategy gets another boundary: [candidate-sandbox.ts](.. There are two different kinds of data worth keeping separate: 1. **Provider storage changes over time.** For example, the [EOD intraday action](../../apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts) upserts bars into MongoDB collections such as `eodIntraday1M`. These are source records, not a reproducible experiment by themselves. -2. **A retained dataset identifies exact research input.** [Stored-source preparation](../../apps/stock/web-api/src/services/stored-dataset-preparation.ts) reads a declared range through [StorageService](../../apps/stock/orchestrator/src/services/StorageService.ts). It requires explicit metadata, converts rows into a v2 dataset, and previews its hash. [Dataset preparation](../../apps/stock/web-api/src/services/dataset-preparation.service.ts) verifies that same hash when retaining it. [Retention](../../apps/stock/orchestrator/src/data/retained-research-dataset.ts) saves the validated bars and manifest in PostgreSQL `backtest_datasets`. +2. **A retained dataset identifies exact research input.** [Stored-source preparation](../../apps/stock/web-api/src/services/stored-dataset-preparation.ts) reads a declared range through [StorageService](../../libs/trading-runtime/src/historical-storage.ts). It requires explicit metadata, converts rows into a v2 dataset, and previews its hash. [Dataset preparation](../../apps/stock/web-api/src/services/dataset-preparation.service.ts) verifies that same hash when retaining it. [Retention](../../libs/trading-runtime/src/retained-dataset.ts) saves the validated bars and manifest in PostgreSQL `backtest_datasets`. Runs select that retained content by hash. A later provider correction therefore does not silently change an earlier run's input. Importing an explicit complete dataset is another route into the same validation and retention boundary. @@ -70,7 +70,7 @@ The stored-source adapter currently accepts **one raw EOD intraday series at `1m | **MongoDB** | Provider records and ingestion history, including the EOD bars used by stored-source preparation. Required for that ingestion/preparation path, not for replay of an already retained snapshot. | | **Redis-compatible storage** | BullMQ job delivery and service caches. The durable research run and its result remain in PostgreSQL. See [BacktestDispatcher](../../apps/stock/web-api/src/services/BacktestDispatcher.ts). | | **QuestDB** | An existing time-series adapter and historical storage route. The current web API, ingestion and pipeline entrypoints explicitly disable it in their container composition. Do not add it to the required retained-dataset research path just because the adapter exists. | -| **Local build artifacts** | Native binary, worker bundle and retained strategy package identities are verified before execution. They supply executable code; they are not another account database. See [canonical-build.ts](../../apps/stock/orchestrator/src/backtest/canonical-build.ts). | +| **Local build artifacts** | Native binary, worker bundle and retained strategy package identities are verified before execution. They supply executable code; they are not another account database. See [canonical-build.ts](../../libs/trading-runtime/src/canonical-build.ts). | DI owns each service/global/proxy cache transport and closes only that container's connections. Their key prefixes and cache DB1 remain unchanged; queue data uses DB0 and each QueueManager diff --git a/docs/servers.md b/docs/servers.md index 4585c240..75cb280a 100644 --- a/docs/servers.md +++ b/docs/servers.md @@ -37,6 +37,20 @@ All 16 containers run from `/mnt/data/stockbot` (`docker compose --env-file .env | | `loki` / `prometheus` | `3100` / `9090` | Centralized logs (`promtail`) & metrics | | | `pgadmin` / `mongo-express` | `5050` / `8081` | Database admin UIs (LAN-only) | +### 2.1 `quant` (`125 GiB` RAM) Memory, Shared-Memory & Kernel Budget + +Enforced via [docker-compose.quant.yml](../docker-compose.quant.yml) + `/etc/sysctl.d/99-stockbot.conf` (`vm.max_map_count = 1048576`): + +| Component | Engine-Internal Cap | Container `mem_limit` | Required OS / Container Settings | +| --- | --- | --- | --- | +| **MongoDB `7.0.21`** (`stock`) | `--wiredTigerCacheSizeGB 16` (`8` outside bulk ETL) | `24g` | `ulimits.nofile = 1048576` | +| **QuestDB `10.2.0`** | `QDB_RAM_USAGE_LIMIT_BYTES=21474836480` (`20 GiB`), JVM `-Xms2g -Xmx4g` | `28g` | `ulimits.nofile = 1048576`, host `vm.max_map_count >= 1048576`, `bars_1m` `PARTITION BY MONTH` | +| **PostgreSQL `16.9`** (`trading_bot`) | `shared_buffers=4GB`, `effective_cache_size=16GB`, `work_mem=64MB`, `maintenance_work_mem=1GB` | `10g` | **`shm_size: 2g`** (prevents `64m` `/dev/shm` parallel hash-join/index errors) | +| **Dragonfly `v1.30.3`** | `--maxmemory=4gb --proactor_threads=4` | `5g` | Emulated cluster / hashtag locks | +| **DuckDB + Workers + `web-api`** | `SET memory_limit='6GB'; SET threads=4; SET temp_directory='/mnt/data/stockbot/tmp/duckdb'` per worker | `30g` total | Prevents DuckDB's default `80%` host-RAM (`~100 GiB`) per-worker allocation | +| **Monitoring & Admin** | Prometheus `--storage.tsdb.retention.time=15d` | `4g` total | Pinned versions across Prometheus, Loki, Grafana, Admin UIs | +| **Linux OS Page Cache** | โ€” | **~24 GiB unallocated** | Keeps hot SN850X NVMe Parquet & QuestDB `mmap` pages resident | + --- ## 3. Local Development vs `quant` Separation @@ -47,7 +61,7 @@ All 16 containers run from `/mnt/data/stockbot` (`docker compose --env-file .env | **`qa` (`quant`)** | `docker-compose.yml` + `docker-compose.quant.yml` | `10.0.0.51:5432` (`trading_bot`) | `10.0.0.51:27017` (`stock`) | `10.0.0.51:27017` (`stock`, `MONGODB_READ_URI` for `data-pipeline`) | `10.0.0.51:6379` | `10.0.0.51:9000` | | **Paper / Live (`9900K`)** | `docker-compose.prod.yml` (`M5`) | Isolated execution DB | None | Curated artifact pull only | Local `:6379` | Local `:9000` (90d hot window) | -> **Offline Local Snapshot:** The workstation's pre-migration Docker containers (`trading-bot-*`) are intentionally stopped with their local Docker volumes preserved untouched as a cold local fallback. +> **Side-by-Side Local Execution:** On the `91 GiB` workstation, `docker-compose.dev.yml` (`stock-bot-dev-*` on `5433`/`27018`/`6380`/`9100`) and `docker-compose.yml` (`trading-bot-*` local QA stack on `5432`/`27017`/`6379`/`9000`) use non-overlapping ports, networks, and volume namespaces so both stacks run simultaneously without conflict (`./scripts/docker.sh start --dev && ./scripts/docker.sh start --qa`). --- diff --git a/knip.json b/knip.json deleted file mode 100644 index b0c336fa..00000000 --- a/knip.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "entry": ["src/index.ts"], - "project": ["src/**/*.ts"] -} diff --git a/libs/LIBRARY_STANDARDS.md b/libs/LIBRARY_STANDARDS.md deleted file mode 100644 index 5b78cbb6..00000000 --- a/libs/LIBRARY_STANDARDS.md +++ /dev/null @@ -1,157 +0,0 @@ -# Library Standards and Patterns - -This document defines the standardized patterns for all libraries in the @stock-bot ecosystem. - -## Export Patterns - -### Standard: Named Exports Only - -All libraries should use **named exports only**. Default exports have been removed for consistency and better tree-shaking. - -**Example:** -```typescript -// โœ… Good - Named exports -export { createCache } from './cache'; -export type { CacheOptions } from './types'; - -// โŒ Bad - Default export -export default createCache; -``` - -## Initialization Patterns - -Libraries follow different initialization patterns based on their purpose: - -### 1. Singleton with Global State -**Use for:** Global services that should have only one instance (config, logger) - -**Example:** Config library -```typescript -let configInstance: ConfigManager | null = null; - -export function initializeConfig(): AppConfig { - if (!configInstance) { - configInstance = new ConfigManager(); - } - return configInstance.initialize(); -} - -export function getConfig(): AppConfig { - if (!configInstance) { - throw new Error('Config not initialized'); - } - return configInstance.get(); -} -``` - -### 2. Factory with Registry -**Use for:** Services that need instance reuse based on configuration (cache, logger instances) - -**Example:** Cache library -```typescript -const cacheInstances = new Map(); - -export function createCache(options: CacheOptions): CacheProvider { - if (options.shared) { - const key = generateKey(options); - if (cacheInstances.has(key)) { - return cacheInstances.get(key)!; - } - const cache = new RedisCache(options); - cacheInstances.set(key, cache); - return cache; - } - return new RedisCache(options); -} -``` - -### 3. Pure Factory Functions -**Use for:** Services that need creation logic beyond simple instantiation - -**Example:** Event bus with configuration processing -```typescript -export function createEventBus(config: EventBusConfig): EventBus { - // Process config, set defaults, etc. - const processedConfig = { ...defaultConfig, ...config }; - return new EventBus(processedConfig); -} -``` - -**Note:** Simple instantiation doesn't need factories - use direct class instantiation or DI container. - -### 4. Direct Class Exports -**Use for:** Simple utilities or services managed by DI container - -**Example:** MongoDB library -```typescript -export { MongoDBClient } from './client'; -// No factory function - let DI container handle instantiation -``` - -### 5. Singleton Classes -**Use for:** Manager classes that coordinate multiple instances - -**Example:** QueueManager -```typescript -export class QueueManager { - private static instance: QueueManager | null = null; - - static initialize(config: QueueConfig): QueueManager { - if (!QueueManager.instance) { - QueueManager.instance = new QueueManager(config); - } - return QueueManager.instance; - } - - static getInstance(): QueueManager { - if (!QueueManager.instance) { - throw new Error('QueueManager not initialized'); - } - return QueueManager.instance; - } -} -``` - -## Pattern Selection Guide - -Choose the initialization pattern based on these criteria: - -| Pattern | When to Use | Examples | -|---------|-------------|----------| -| **Singleton with Global State** | - One instance per process
- Stateful configuration
- Process-wide settings | config, logger setup | -| **Factory with Registry** | - Multiple instances with same config should share
- Connection pooling
- Resource optimization | cache, logger instances | -| **Pure Factory** | - Complex initialization logic
- Configuration processing needed
- Defaults to apply | event bus (if needed) | -| **Direct Class Export** | - DI container manages lifecycle
- Simple initialization
- No special setup needed | database clients (MongoDB, PostgreSQL, QuestDB), utilities | -| **Singleton Class** | - Coordinates multiple resources
- Central management point
- Graceful shutdown needed | QueueManager, ConnectionManager | - -## Additional Standards - -### Error Handling -- All libraries should throw descriptive errors -- Consider creating custom error classes for domain-specific errors -- Always include context in error messages - -### Configuration -- Accept configuration through constructor/factory parameters -- Validate configuration using Zod schemas -- Provide sensible defaults where appropriate - -### Testing -- All libraries must have unit tests -- Use consistent test file naming: `*.test.ts` -- Mock external dependencies - -### Documentation -- Every library must have a README.md -- Include usage examples -- Document all public APIs with JSDoc - -### TypeScript -- Export all public types -- Use strict TypeScript settings -- Avoid `any` types - -### Dependencies -- Minimize external dependencies -- Use exact versions for critical dependencies -- Document peer dependencies clearly \ No newline at end of file diff --git a/libs/calculations/README.md b/libs/calculations/README.md index d50a1ef8..d4a28db7 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -62,38 +62,6 @@ The application-level `PerformanceAnalyzer` remains a reporting facade. The nati dependency of this library. Native and legacy indicators can have different seeding, smoothing and warm-up conventions: they are not interchangeable without parity tests. -## Preserved legacy APIs - -All **105 previously active calculation functions** are retained, not deleted, behind -one explicit opt-in entry: - -```ts -import { basic, indicators, performance, risk } from '@stock-bot/calculations/legacy'; -``` - -The four original modules are preserved with unchanged executable bodies and their -original function names. These are migration/research APIs, **not newly validated -production APIs**. Known concerns include zero/Infinity fallbacks, incompatible ratio -units, different indicator seeding/smoothing, drawdown definitions and simplified -attribution/MWRR. Do not introduce these into supported stock execution. Prefer the -reviewed core, and promote additional functions with documented contracts and golden, -invalid-input, warm-up/alignment and batch/incremental parity tests as applicable. - -[migration-audit.json](migration-audit.json) inventories every original exported function, -its disposition and source provenance (`ccce401`). Regression tests verify the legacy -AST hashes and export lists; that proves preservation, not financial correctness. - -## Preserved research - -All seven formerly `.disabled` modules are retained as source-verified Markdown research -snapshots in [research/](research/README.md), including their unique indicators. They -were never active package exports and are not activated by this change. Some contain -placeholders, unseeded randomness or partial numerical methods. They are not compiled, -published or importable code. Extract and validate useful functions before promotion. - -The empty `analyzePortfolio` convenience placeholder was not restored. Removing a -placeholder API does not remove the real portfolio/research implementations above. - ## Verify ```sh @@ -104,5 +72,4 @@ bun run check The root gate builds/type-checks this workspace and runs its regressions. The integration suite retains native/window parity, strategy recovery and analytics golden fixtures. -Architecture checks keep infrastructure and application adapters out of the library, -and prevent supported app code from loading the legacy/research tier. +Architecture checks keep infrastructure and application adapters out of the library. diff --git a/libs/calculations/migration-audit.json b/libs/calculations/migration-audit.json deleted file mode 100644 index 7175727a..00000000 --- a/libs/calculations/migration-audit.json +++ /dev/null @@ -1,408 +0,0 @@ -{ - "sourceCommit": "ccce401", - "modules": [ - { - "original": "libs/utils/src/calculations/basic-calculations.ts", - "status": "legacy-api", - "destination": "src/legacy/basic-calculations.ts", - "sourceSha256": "366b46cd207316409bcb281b62cadac92792a97981b40fc31f65c59513149d7a", - "astSha256": "68b64fcb0a00367d16a92f8f39eef6f4856c04bdc2fa8f070252d3e4c002c506", - "functions": [ - "accruedInterest", - "annualizeReturn", - "annualizeVolatility", - "bondConvexity", - "bondPrice", - "bondYield", - "cagr", - "capitalAssetPricingModel", - "cleanPrice", - "compoundInterest", - "degreeOfFinancialLeverage", - "degreeOfOperatingLeverage", - "degreeOfTotalLeverage", - "dirtyPrice", - "dividendDiscountModel", - "dollarDuration", - "economicValueAdded", - "effectiveAnnualRate", - "futureValue", - "hurdleRate", - "internalRateOfReturn", - "logReturn", - "macaulayDuration", - "modifiedDuration", - "netPresentValue", - "paybackPeriod", - "percentageChange", - "presentValue", - "simpleReturn", - "weightedAverageCostOfCapital" - ] - }, - { - "original": "libs/utils/src/calculations/technical-indicators.ts", - "status": "legacy-api", - "destination": "src/legacy/technical-indicators.ts", - "sourceSha256": "7792daec5b77cc5f6c5e5f8735e1d8798f9b00090e103a837e4eb187e6a4f38e", - "astSha256": "d3e84dde74368e641e6b05df0a189e8d1451c42991e6c9e30aac638f5b8d17d9", - "functions": [ - "accumulationDistribution", - "adx", - "aroon", - "atr", - "balanceOfPower", - "bollingerBands", - "cci", - "chaikinMoneyFlow", - "chandeMomentumOscillator", - "coppockCurve", - "donchianChannels", - "easeOfMovement", - "ema", - "ichimoku", - "keltnerChannels", - "klingerVolumeOscillator", - "macd", - "massIndex", - "mfi", - "momentum", - "obv", - "parabolicSAR", - "pivotPoints", - "priceOscillator", - "roc", - "rsi", - "sma", - "stochastic", - "stochasticRSI", - "tema", - "trix", - "ultimateOscillator", - "vortexIndicator", - "vwma", - "williamsR", - "wma" - ] - }, - { - "original": "libs/utils/src/calculations/risk-metrics.ts", - "status": "legacy-api", - "destination": "src/legacy/risk-metrics.ts", - "sourceSha256": "7916a60801b0ea57b6f258d1137f41ce78b4acce91e64e54399cb5146b764220", - "astSha256": "12a636e2dd2c4768389fafedac8102967321869add25eecae2ff9271e9593139", - "functions": [ - "alpha", - "annualizedVolatility", - "beta", - "calculateRiskMetrics", - "conditionalValueAtRisk", - "downsideDeviation", - "kurtosis", - "maxDrawdown", - "parametricVaR", - "riskAdjustedReturn", - "riskContribution", - "sharpeRatio", - "skewness", - "trackingError", - "treynorRatio", - "ulcerIndex", - "valueAtRisk", - "volatility" - ] - }, - { - "original": "libs/utils/src/calculations/performance-metrics.ts", - "status": "legacy-api", - "destination": "src/legacy/performance-metrics.ts", - "sourceSha256": "3333c4a285a94ab40ca1fb537166ef8f820431cfdd7afeb3bcf74d64d40f861f", - "astSha256": "dd39e4a594d06d752263c4ecc5e90e816c87ac32b825e6da11dcc3ffb2c707ea", - "functions": [ - "analyzeDrawdowns", - "analyzeReturns", - "analyzeTradePerformance", - "calculateRollingAlpha", - "calculateRollingBeta", - "calculateRollingMetrics", - "calculateStrategyMetrics", - "calmarRatio", - "captureRatio", - "gainToPainRatio", - "informationRatio", - "jensensAlpha", - "martinRatio", - "moneyWeightedRateOfReturn", - "omegaRatio", - "sortinoRatio", - "sterlingRatio", - "strategyPerformanceAttribution", - "tailRatio", - "timeWeightedRateOfReturn", - "ulcerPerformanceIndex" - ] - }, - { - "original": "libs/utils/src/calculations/correlation-analysis.ts.disabled", - "status": "research-reference", - "destination": "research/correlation-analysis.md", - "sourceSha256": "5add7ae799098f19502a57a14682f2207fffe568d96584c28cc896439354b4df", - "functions": [ - "autocorrelation", - "correlationMatrix", - "correlationRegimeAnalysis", - "covarianceMatrix", - "crossCorrelation", - "dccModel", - "distanceCorrelation", - "grangerCausalityTest", - "kendallTau", - "mutualInformation", - "partialCorrelation", - "pearsonCorrelation", - "rollingCorrelation", - "spearmanCorrelation", - "tailCorrelation" - ] - }, - { - "original": "libs/utils/src/calculations/market-statistics.ts.disabled", - "status": "research-reference", - "destination": "research/market-statistics.md", - "sourceSha256": "4bd442052d2d2997f9f78b884b3ccb4793df4ec5eb512f824fddad013920318b", - "functions": [ - "ImplementationShortfall", - "IntradayPatterns", - "LiquidityMetrics", - "MarketImpact", - "MarketStress", - "OrderBookImbalance", - "PriceDiscovery", - "RealizedSpread", - "TWAP", - "VWAP", - "adverseSelectionComponent", - "amihudIlliquidity", - "amihudIlliquidityHFT", - "cumulativeVolumeDelta", - "deltaNeutralHedgingRatio", - "gammaScalpingRange", - "garmanKlassVolatility", - "identifyMarketRegime", - "inventoryRiskComponent", - "kyleLambda", - "marketOrderRatio", - "optimalOrderSize", - "probabilityInformedTrading", - "quoteAge", - "rollSpreadEstimator", - "tickRule", - "tradeClassification", - "volumeConcentrationHHI", - "volumeOrderImbalance", - "volumeProfile", - "yangZhangVolatility" - ] - }, - { - "original": "libs/utils/src/calculations/options-pricing.ts.disabled", - "status": "research-reference", - "destination": "research/options-pricing.md", - "sourceSha256": "199004579a57c196c87230684717a559b1c95c6ef1e6c7cda7ab33852abfcb52", - "functions": [ - "binomialOptionPricing", - "blackScholes", - "blackScholesWithGreeks", - "butterfly", - "calculateGreeks", - "calculateImpliedVolatility", - "calculateOptionPortfolioRisk", - "calculateStrategyGreeks", - "callBreakeven", - "callProbabilityOfProfit", - "condor", - "impliedVolatility", - "interpolateVolatilitySurface", - "monteCarloOptionPricing", - "putBreakeven", - "putProbabilityOfProfit", - "straddle", - "strangle" - ] - }, - { - "original": "libs/utils/src/calculations/portfolio-analytics.ts.disabled", - "status": "research-reference", - "destination": "research/portfolio-analytics.md", - "sourceSha256": "547b7df19c8fffc73736a6a5e6080f7de81bdfb6132080565b728651ae9e4bf2", - "functions": [ - "blackLittermanOptimization", - "calculateEfficientFrontier", - "calculatePortfolioMetrics", - "calculatePortfolioReturns", - "calculatePortfolioVariance", - "calculateRebalancing", - "calculateRiskContributions", - "famaFrenchAnalysis", - "findMinimumVariancePortfolio", - "markowitzOptimization", - "performanceAttribution", - "riskParityOptimization" - ] - }, - { - "original": "libs/utils/src/calculations/position-sizing.ts.disabled", - "status": "research-reference", - "destination": "research/position-sizing.md", - "sourceSha256": "23815464ab33ebed0e597e2b3c35499c59ed3d2788d9e06bcd3a4878fda540f1", - "functions": [ - "atrBasedPositionSize", - "calculatePortfolioHeat", - "correlationAdjustedPositionSize", - "dynamicPositionSize", - "equalWeightPositionSize", - "expectancyPositionSize", - "fixedFractionalPositionSize", - "fixedRiskPositionSize", - "fractionalKellyPositionSize", - "kellyPositionSize", - "liquidityConstrainedPositionSize", - "monteCarloPositionSize", - "multiTimeframePositionSize", - "optimalFPositionSize", - "riskParityPositionSize", - "secureFPositionSize", - "sharpeOptimizedPositionSize", - "validatePositionSize", - "volatilityAdjustedPositionSize", - "volatilityTargetPositionSize" - ] - }, - { - "original": "libs/utils/src/calculations/technical-indicators.ts.disabled", - "status": "research-reference", - "destination": "research/technical-indicators.md", - "sourceSha256": "603ef0b619c52e7388e1121993d628821e9c65e30e5d28cb34a1fd6f60eeeacc", - "functions": [ - "accumulationDistribution", - "adx", - "aroon", - "atr", - "atrTrailingStops", - "balanceOfPower", - "bollingerBands", - "cci", - "centerOfGravity", - "chaikinADRange", - "chaikinMoneyFlow", - "chaikinOscillator", - "chandeMomentumOscillator", - "chandelierExit", - "coppockCurve", - "coppockRange", - "correlationCoefficient", - "deMarker", - "detrendedPriceOscillator", - "directionalMovementIndex", - "donchianChannels", - "donchianWidth", - "easeOfMovement", - "elderDisk", - "elderRay", - "eldersCloud", - "eldersForceIndex", - "eldersSafeZoneStops", - "eldersThermometer", - "ema", - "forceIndex", - "fractalChaosBands", - "fractalEfficiency", - "guppyMultipleMovingAverage", - "highLowIndex", - "highLowRange", - "hilbertTransformInstantaneousTrendline", - "historicalVolatility", - "ichimokuCloud", - "intradayIntensityIndex", - "kama", - "keltnerChannels", - "klingerOscillator", - "knowSureThing", - "linearRegressionIndicator", - "macd", - "marketFacilitationIndex", - "massIndex", - "medianPrice", - "medianPriceRange", - "mfi", - "momentum", - "momentumFromCurrentPrice", - "moneyFlowChaikinOscillator", - "moneyFlowIndexRange", - "moneyFlowMultiplier", - "movingAverageEnvelope", - "negativeVolumeIndex", - "normalizedAverageTrueRange", - "obv", - "onBalanceVolumeMean", - "onBalanceVolumeOscillator", - "parabolicSAR", - "percentagePriceOscillator", - "pivotPoints", - "positiveVolumeIndex", - "prettyGoodOscillator", - "priceVolumeTrend", - "primeNumberOscillator", - "projectionBands", - "projectionOscillator", - "qStick", - "rainbowOscillator", - "rangeActionVerificationIndex", - "relativeStrength", - "relativeVigorIndex", - "relativeVolatilityIndex", - "roc", - "rocFromCurrentPrice", - "rsi", - "schaffTrendCycle", - "sma", - "standardDeviation", - "stochRSIFast", - "stochRSIFull", - "stochastic", - "stochasticRSI", - "trix", - "trueStrengthIndex", - "twiggsMoneyFlow", - "typicalPrice", - "typicalPriceRange", - "ultimateMovingAverage", - "ultimateOscillator", - "verticalHorizontalFilter", - "volumeOscillator", - "volumeRateOfChange", - "vwma", - "williamsR" - ] - }, - { - "original": "libs/utils/src/calculations/volatility-models.ts.disabled", - "status": "research-reference", - "destination": "research/volatility-models.md", - "sourceSha256": "c84b4088b9251ecbc6e8a6306d90db78b2beebd82bdcfd5b21e009225cd4e0f8", - "functions": [ - "calculateEWMAVolatility", - "calculateRealizedVolatility", - "calculateVolatilityRisk", - "calculateVolatilitySmile", - "calculateVolatilityTermStructure", - "calculateYangZhangVolatility", - "estimateGARCH", - "estimateHestonParameters", - "forecastVolatilityEWMA", - "identifyVolatilityRegimes", - "parkinsonVolatility" - ] - } - ] -} diff --git a/libs/calculations/package.json b/libs/calculations/package.json index 125f8b78..7330790b 100644 --- a/libs/calculations/package.json +++ b/libs/calculations/package.json @@ -11,8 +11,7 @@ "./analytics": "./src/analytics/index.ts", "./indicators": "./src/indicators/index.ts", "./market-data": "./src/market-data.ts", - "./returns": "./src/returns.ts", - "./legacy": "./src/legacy/index.ts" + "./returns": "./src/returns.ts" }, "scripts": { "build": "tsc", diff --git a/libs/calculations/research/README.md b/libs/calculations/research/README.md deleted file mode 100644 index 382e9f3f..00000000 --- a/libs/calculations/research/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Research references, not runtime APIs - -These source snapshots preserve **all seven previously disabled calculation modules** -from `ccce401`, including functions not present in the active indicator module. Markdown -keeps their former non-executable status explicit. Their source hashes are verified by -the calculation preservation tests; this does not validate their algorithms. - -| Snapshot | Review concerns before promotion | -| ------------------------------------------------ | ------------------------------------------------------------------------------- | -| [Correlation analysis](correlation-analysis.md) | Random permutation tests and approximate inference/matrix methods | -| [Market statistics](market-statistics.md) | Hard-coded market cap/stress estimates and simplified microstructure outputs | -| [Options pricing](options-pricing.md) | Unseeded Monte Carlo, convergence fallbacks and logging | -| [Portfolio analytics](portfolio-analytics.md) | Equal-weight optimizer baselines, zero factor estimates, incomplete attribution | -| [Position sizing](position-sizing.md) | Unseeded simulation/search; old production-readiness claims were unsupported | -| [Additional indicators](technical-indicators.md) | Duplicates plus unique indicators and a placeholder Hilbert transform | -| [Volatility models](volatility-models.md) | Simplified Yangโ€“Zhang/Heston estimates and random shocks | - -[Historical position-sizing notes](position-sizing-notes.md) retain the old formula and -validation discussion without endorsing its production-readiness claims. - -To promote a function: define its inputs, units, undefined-result policy and temporal -alignment; remove synthetic results, implicit clock access and unseeded randomness; -add an independently checked fixture and edge-case tests; then expose a deliberate -supported subpath. Keep approximate research explicitly labeled rather than treating -an importable function as proof of correctness. Supported code must not depend on these -references or the legacy namespace. diff --git a/libs/calculations/research/correlation-analysis.md b/libs/calculations/research/correlation-analysis.md deleted file mode 100644 index 70d5a95e..00000000 --- a/libs/calculations/research/correlation-analysis.md +++ /dev/null @@ -1,1281 +0,0 @@ -# correlation-analysis research snapshot - -Source: `ccce401:libs/utils/src/calculations/correlation-analysis.ts.disabled`. - -Contains random permutation tests and simplified statistical/numerical approximations. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Correlation Analysis Module - * - * Provides comprehensive correlation and covariance analysis tools for financial time series. - * Includes correlation matrices, rolling correlations, regime-dependent correlations, - * and advanced correlation modeling techniques. - */ - -export interface CorrelationResult { - correlation: number; - pValue: number; - significance: boolean; - confidenceInterval?: [number, number]; -} - -export interface CorrelationMatrix { - matrix: number[][]; - labels: string[]; - eigenvalues: number[]; - eigenvectors: number[][]; - conditionNumber: number; -} - -export interface RollingCorrelationResult { - correlations: number[]; - timestamps: Date[]; - average: number; - volatility: number; - min: number; - max: number; -} - -export interface CovarianceMatrix { - matrix: number[][]; - labels: string[]; - volatilities: number[]; - correlations: number[][]; - eigenvalues: number[]; - determinant: number; -} - -export interface CorrelationBreakdown { - linear: number; - nonlinear: number; - tail: number; - rank: number; -} - -export interface DynamicCorrelationModel { - parameters: number[]; - correlations: number[]; - logLikelihood: number; - aic: number; - bic: number; -} - -/** - * Calculate Pearson correlation coefficient between two time series - */ -export function pearsonCorrelation(x: number[], y: number[]): CorrelationResult { - if (x.length !== y.length || x.length < 2) { - throw new Error('Arrays must have same length and at least 2 observations'); - } - - const n = x.length; - const sumX = x.reduce((a, b) => a + b, 0); - const sumY = y.reduce((a, b) => a + b, 0); - const sumXY = x.reduce((sum, xi, i) => { - const yi = y[i]; - return yi !== undefined ? sum + xi * yi : sum; - }, 0); - const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0); - const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 0); - - const numerator = n * sumXY - sumX * sumY; - const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY)); - - const correlation = denominator === 0 ? 0 : numerator / denominator; - - // Calculate statistical significance (t-test) - const df = n - 2; - const tStat = correlation * Math.sqrt(df / (1 - correlation * correlation)); - const pValue = 2 * (1 - studentTCDF(Math.abs(tStat), df)); - const significance = pValue < 0.05; - - // Calculate confidence interval (Fisher transformation) - const z = 0.5 * Math.log((1 + correlation) / (1 - correlation)); - const seZ = 1 / Math.sqrt(n - 3); - const zLower = z - 1.96 * seZ; - const zUpper = z + 1.96 * seZ; - const confidenceInterval: [number, number] = [ - (Math.exp(2 * zLower) - 1) / (Math.exp(2 * zLower) + 1), - (Math.exp(2 * zUpper) - 1) / (Math.exp(2 * zUpper) + 1), - ]; - - return { - correlation, - pValue, - significance, - confidenceInterval, - }; -} - -/** - * Calculate Spearman rank correlation coefficient - */ -export function spearmanCorrelation(x: number[], y: number[]): CorrelationResult { - if (x.length !== y.length || x.length < 2) { - throw new Error('Arrays must have same length and at least 2 observations'); - } - - // Convert to ranks - const xRanks = getRanks(x); - const yRanks = getRanks(y); - - return pearsonCorrelation(xRanks, yRanks); -} - -/** - * Calculate Kendall's tau correlation coefficient - */ -export function kendallTau(x: number[], y: number[]): CorrelationResult { - if (x.length !== y.length || x.length < 2) { - throw new Error('Arrays must have same length and at least 2 observations'); - } - - const n = x.length; - let concordant = 0; - let discordant = 0; - - for (let i = 0; i < n - 1; i++) { - for (let j = i + 1; j < n; j++) { - const xi = x[i]; - const xj = x[j]; - const yi = y[i]; - const yj = y[j]; - - if (xi !== undefined && xj !== undefined && yi !== undefined && yj !== undefined) { - const xDiff = xi - xj; - const yDiff = yi - yj; - - if (xDiff * yDiff > 0) { - concordant++; - } else if (xDiff * yDiff < 0) { - discordant++; - } - } - } - } - - const correlation = (concordant - discordant) / ((n * (n - 1)) / 2); - - // Approximate p-value for large samples - const variance = (2 * (2 * n + 5)) / (9 * n * (n - 1)); - const z = correlation / Math.sqrt(variance); - const pValue = 2 * (1 - normalCDF(Math.abs(z))); - const significance = pValue < 0.05; - - return { - correlation, - pValue, - significance, - }; -} - -/** - * Calculate correlation matrix for multiple time series - */ -export function correlationMatrix( - data: number[][], - labels: string[] = [], - method: 'pearson' | 'spearman' | 'kendall' = 'pearson' -): CorrelationMatrix { - const n = data.length; - - if (labels.length === 0) { - labels = Array.from({ length: n }, (_, i) => `Series${i + 1}`); - } - - const matrix: number[][] = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (i === j) { - matrix[i]![j] = 1; - } else { - const dataI = data[i]; - const dataJ = data[j]; - if (dataI && dataJ) { - let corrResult: CorrelationResult; - switch (method) { - case 'spearman': - corrResult = spearmanCorrelation(dataI, dataJ); - break; - case 'kendall': - corrResult = kendallTau(dataI, dataJ); - break; - default: - corrResult = pearsonCorrelation(dataI, dataJ); - } - matrix[i]![j] = corrResult.correlation; - } - } - } - } - - // Calculate eigenvalues and eigenvectors - const { eigenvalues, eigenvectors } = eigenDecomposition(matrix); - - // Calculate condition number - const conditionNumber = - Math.max(...eigenvalues) / Math.min(...eigenvalues.filter(x => x > 1e-10)); - - return { - matrix, - labels, - eigenvalues, - eigenvectors, - conditionNumber, - }; -} - -/** - * Calculate rolling correlation between two time series - */ -export function rollingCorrelation( - x: number[], - y: number[], - window: number, - timestamps?: Date[] -): RollingCorrelationResult { - if (x.length !== y.length || window > x.length) { - throw new Error('Invalid input parameters'); - } - - const correlations: number[] = []; - const resultTimestamps: Date[] = []; - - for (let i = window - 1; i < x.length; i++) { - const xWindow = x.slice(i - window + 1, i + 1); - const yWindow = y.slice(i - window + 1, i + 1); - - const corr = pearsonCorrelation(xWindow, yWindow).correlation; - correlations.push(corr); - - if (timestamps) { - resultTimestamps.push(timestamps[i]); - } else { - resultTimestamps.push(new Date(i)); - } - } - - const average = correlations.reduce((a, b) => a + b, 0) / correlations.length; - const variance = - correlations.reduce((sum, corr) => sum + Math.pow(corr - average, 2), 0) / correlations.length; - const volatility = Math.sqrt(variance); - const min = Math.min(...correlations); - const max = Math.max(...correlations); - - return { - correlations, - timestamps: resultTimestamps, - average, - volatility, - min, - max, - }; -} - -/** - * Calculate covariance matrix - */ -export function covarianceMatrix(data: number[][], labels: string[] = []): CovarianceMatrix { - const n = data.length; - - if (labels.length === 0) { - labels = Array.from({ length: n }, (_, i) => `Series${i + 1}`); - } - - // Calculate means - const means = data.map(series => series.reduce((a, b) => a + b, 0) / series.length); - - // Calculate covariance matrix - const matrix: number[][] = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - const m = data[0].length; // Number of observations - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - let covariance = 0; - for (let k = 0; k < m; k++) { - covariance += (data[i][k] - means[i]) * (data[j][k] - means[j]); - } - matrix[i][j] = covariance / (m - 1); - } - } - - // Calculate volatilities (standard deviations) - const volatilities = data.map((series, i) => Math.sqrt(matrix[i][i])); - - // Calculate correlation matrix from covariance matrix - const correlations: number[][] = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - correlations[i][j] = matrix[i][j] / (volatilities[i] * volatilities[j]); - } - } - - // Calculate eigenvalues - const { eigenvalues } = eigenDecomposition(matrix); - - // Calculate determinant - const determinant = eigenvalues.reduce((prod, val) => prod * val, 1); - - return { - matrix, - labels, - volatilities, - correlations, - eigenvalues, - determinant, - }; -} - -/** - * Calculate partial correlation controlling for other variables - */ -export function partialCorrelation( - x: number[], - y: number[], - controls: number[][] -): CorrelationResult { - // Use matrix operations to calculate partial correlation - const n = x.length; - const k = controls.length; - - // Build design matrix - const X = Array(n) - .fill(null) - .map(() => Array(k + 1).fill(1)); - for (let i = 0; i < n; i++) { - for (let j = 0; j < k; j++) { - X[i][j + 1] = controls[j][i]; - } - } - - // Calculate residuals for x and y after regressing on controls - const xResiduals = residuals(x, X); - const yResiduals = residuals(y, X); - - return pearsonCorrelation(xResiduals, yResiduals); -} - -/** - * Test for correlation regime changes - */ -export function correlationRegimeAnalysis( - x: number[], - y: number[], - window: number = 60 -): { - regimes: { start: number; end: number; correlation: number }[]; - breakpoints: number[]; - stability: number; -} { - const rollingCorr = rollingCorrelation(x, y, window); - const correlations = rollingCorr.correlations; - - // Detect regime changes using CUSUM test - const breakpoints: number[] = []; - const threshold = 2.0; // CUSUM threshold - - let cusum = 0; - const mean = correlations.reduce((a, b) => a + b, 0) / correlations.length; - - for (let i = 1; i < correlations.length; i++) { - cusum += correlations[i] - mean; - if (Math.abs(cusum) > threshold) { - breakpoints.push(i); - cusum = 0; - } - } - - // Build regimes - const regimes: { start: number; end: number; correlation: number }[] = []; - let start = 0; - - for (const breakpoint of breakpoints) { - const regimeCorr = correlations.slice(start, breakpoint); - const avgCorr = regimeCorr.reduce((a, b) => a + b, 0) / regimeCorr.length; - - regimes.push({ - start, - end: breakpoint, - correlation: avgCorr, - }); - start = breakpoint; - } - - // Add final regime - if (start < correlations.length) { - const regimeCorr = correlations.slice(start); - const avgCorr = regimeCorr.reduce((a, b) => a + b, 0) / regimeCorr.length; - - regimes.push({ - start, - end: correlations.length, - correlation: avgCorr, - }); - } - - // Calculate stability measure - const regimeVariances = regimes.map(regime => { - const regimeCorr = correlations.slice(regime.start, regime.end); - const mean = regime.correlation; - return regimeCorr.reduce((sum, corr) => sum + Math.pow(corr - mean, 2), 0) / regimeCorr.length; - }); - - const stability = 1 / (1 + regimeVariances.reduce((a, b) => a + b, 0) / regimeVariances.length); - - return { - regimes, - breakpoints, - stability, - }; -} - -/** - * Calculate tail correlation using copula methods - */ -export function tailCorrelation( - x: number[], - y: number[], - threshold: number = 0.05 -): { - upperTail: number; - lowerTail: number; - symmetric: boolean; -} { - const n = x.length; - const upperThreshold = 1 - threshold; - const lowerThreshold = threshold; - - // Convert to uniform marginals - const xRanks = getRanks(x).map(rank => rank / n); - const yRanks = getRanks(y).map(rank => rank / n); - - // Upper tail correlation - let upperCount = 0; - let upperTotal = 0; - - for (let i = 0; i < n; i++) { - if (xRanks[i] > upperThreshold) { - upperTotal++; - if (yRanks[i] > upperThreshold) { - upperCount++; - } - } - } - - const upperTail = upperTotal > 0 ? upperCount / upperTotal : 0; - - // Lower tail correlation - let lowerCount = 0; - let lowerTotal = 0; - - for (let i = 0; i < n; i++) { - if (xRanks[i] < lowerThreshold) { - lowerTotal++; - if (yRanks[i] < lowerThreshold) { - lowerCount++; - } - } - } - - const lowerTail = lowerTotal > 0 ? lowerCount / lowerTotal : 0; - - // Test for symmetry - const symmetric = Math.abs(upperTail - lowerTail) < 0.1; - - return { - upperTail, - lowerTail, - symmetric, - }; -} - -/** - * Dynamic Conditional Correlation (DCC) model estimation - */ -export function dccModel( - data: number[][], - maxIter: number = 100, - tolerance: number = 1e-6 -): DynamicCorrelationModel { - const n = data.length; - const T = data[0].length; - - // Initialize parameters [alpha, beta] - const params = [0.01, 0.95]; - - // Standardize data (assume unit variance for simplicity) - const standardizedData = data.map(series => { - const mean = series.reduce((a, b) => a + b, 0) / series.length; - const variance = - series.reduce((sum, x) => sum + Math.pow(x - mean, 2), 0) / (series.length - 1); - const std = Math.sqrt(variance); - return series.map(x => (x - mean) / std); - }); - - let correlations: number[] = []; - let logLikelihood = -Infinity; - - for (let iter = 0; iter < maxIter; iter++) { - const [alpha, beta] = params; - - // Calculate dynamic correlations - correlations = []; - - // Initialize with unconditional correlation - const unconditionalCorr = pearsonCorrelation( - standardizedData[0], - standardizedData[1] - ).correlation; - let Qt = unconditionalCorr; - - let newLogLikelihood = 0; - - for (let t = 1; t < T; t++) { - // Update correlation - const prevShock = standardizedData[0][t - 1] * standardizedData[1][t - 1]; - Qt = (1 - alpha - beta) * unconditionalCorr + alpha * prevShock + beta * Qt; - - correlations.push(Qt); - - // Add to log-likelihood - const det = 1 - Qt * Qt; - if (det > 0) { - newLogLikelihood -= 0.5 * Math.log(det); - newLogLikelihood -= - (0.5 * - (Math.pow(standardizedData[0][t], 2) + - Math.pow(standardizedData[1][t], 2) - - 2 * Qt * standardizedData[0][t] * standardizedData[1][t])) / - det; - } - } - - // Check convergence - if (Math.abs(newLogLikelihood - logLikelihood) < tolerance) { - break; - } - - logLikelihood = newLogLikelihood; - - // Simple gradient update (in practice, use more sophisticated optimization) - params[0] = Math.max(0.001, Math.min(0.999, params[0] + 0.001)); - params[1] = Math.max(0.001, Math.min(0.999 - params[0], params[1] + 0.001)); - } - - // Calculate information criteria - const k = 2; // Number of parameters - const aic = -2 * logLikelihood + 2 * k; - const bic = -2 * logLikelihood + k * Math.log(T); - - return { - parameters: params, - correlations, - logLikelihood, - aic, - bic, - }; -} - -/** - * Test for Granger causality in correlations - */ -export function grangerCausalityTest( - x: number[], - y: number[], - maxLag: number = 5 -): { - xCausesY: { fStatistic: number; pValue: number; significant: boolean }; - yCausesX: { fStatistic: number; pValue: number; significant: boolean }; - optimalLag: number; -} { - let bestLag = 1; - let minAIC = Infinity; - - // Find optimal lag - for (let lag = 1; lag <= maxLag; lag++) { - const aic = varModel(x, y, lag).aic; - if (aic < minAIC) { - minAIC = aic; - bestLag = lag; - } - } - - // Test x -> y causality - const fullModel = varModel(x, y, bestLag); - const restrictedModelY = arModel(y, bestLag); - - const fStatX = - (restrictedModelY.rss - fullModel.rssY) / - bestLag / - (fullModel.rssY / (x.length - 2 * bestLag - 1)); - const pValueX = 1 - fCDF(fStatX, bestLag, x.length - 2 * bestLag - 1); - - // Test y -> x causality - const restrictedModelX = arModel(x, bestLag); - - const fStatY = - (restrictedModelX.rss - fullModel.rssX) / - bestLag / - (fullModel.rssX / (x.length - 2 * bestLag - 1)); - const pValueY = 1 - fCDF(fStatY, bestLag, x.length - 2 * bestLag - 1); - - return { - xCausesY: { - fStatistic: fStatX, - pValue: pValueX, - significant: pValueX < 0.05, - }, - yCausesX: { - fStatistic: fStatY, - pValue: pValueY, - significant: pValueY < 0.05, - }, - optimalLag: bestLag, - }; -} -/** - * Calculate Distance Correlation - */ -export function distanceCorrelation(x: number[], y: number[]): CorrelationResult { - if (x.length !== y.length || x.length < 2) { - throw new Error('Arrays must have same length and at least 2 observations'); - } - - const n = x.length; - - // Calculate distance matrices - const a = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - const b = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - const xi = x[i]; - const xj = x[j]; - const yi = y[i]; - const yj = y[j]; - if (xi !== undefined && xj !== undefined && yi !== undefined && yj !== undefined) { - a[i]![j] = Math.abs(xi - xj); - b[i]![j] = Math.abs(yi - yj); - } - } - } - - // Calculate double centered distance matrices - const aMeanRow = a.map(row => row.reduce((sum, val) => sum + val, 0) / n); - const bMeanRow = b.map(row => row.reduce((sum, val) => sum + val, 0) / n); - const aMeanTotal = aMeanRow.reduce((sum, val) => sum + val, 0) / n; - const bMeanTotal = bMeanRow.reduce((sum, val) => sum + val, 0) / n; - - const A = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - const B = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - A[i][j] = a[i][j] - aMeanRow[i] - aMeanRow[j] + aMeanTotal; - B[i][j] = b[i][j] - bMeanRow[i] - bMeanRow[j] + bMeanTotal; - } - } - - // Calculate distance covariance and variances - let dcov = 0; - let dvarX = 0; - let dvarY = 0; - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - dcov += A[i][j] * B[i][j]; - dvarX += A[i][j] * A[i][j]; - dvarY += B[i][j] * B[i][j]; - } - } - - dcov = Math.sqrt(dcov / (n * n)); - dvarX = Math.sqrt(dvarX / (n * n)); - dvarY = Math.sqrt(dvarY / (n * n)); - - const correlation = dvarX * dvarY === 0 ? 0 : dcov / Math.sqrt(dvarX * dvarY); - - // Approximate p-value (permutation test) - let pValue = 1; - const numPermutations = 100; - - for (let p = 0; p < numPermutations; p++) { - const yPermuted = shuffleArray([...y]); - const bPermuted = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - bPermuted[i][j] = Math.abs(yPermuted[i] - yPermuted[j]); - } - } - - const bMeanRowPermuted = bPermuted.map(row => row.reduce((sum, val) => sum + val, 0) / n); - const bMeanTotalPermuted = bMeanRowPermuted.reduce((sum, val) => sum + val, 0) / n; - - const BPermuted = Array(n) - .fill(null) - .map(() => Array(n).fill(0)); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - BPermuted[i][j] = - bPermuted[i][j] - bMeanRowPermuted[i] - bMeanRowPermuted[j] + bMeanTotalPermuted; - } - } - - let dcovPermuted = 0; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - dcovPermuted += A[i][j] * BPermuted[i][j]; - } - } - dcovPermuted = Math.sqrt(dcovPermuted / (n * n)); - - if (dcovPermuted >= dcov) { - pValue++; - } - } - - pValue /= numPermutations + 1; - const significance = pValue < 0.05; - - return { - correlation, - pValue, - significance, - }; -} - -/** - * Calculate Mutual Information - */ -export function mutualInformation( - x: number[], - y: number[], - numBins: number = 10 -): CorrelationResult { - if (x.length !== y.length || x.length < 2) { - throw new Error('Arrays must have same length and at least 2 observations'); - } - - const n = x.length; - - // Calculate histograms - const xMin = Math.min(...x); - const xMax = Math.max(...x); - const yMin = Math.min(...y); - const yMax = Math.max(...y); - - const xBinWidth = (xMax - xMin) / numBins; - const yBinWidth = (yMax - yMin) / numBins; - - const jointHistogram = Array(numBins) - .fill(null) - .map(() => Array(numBins).fill(0)); - const xHistogram = Array(numBins).fill(0); - const yHistogram = Array(numBins).fill(0); - - for (let i = 0; i < n; i++) { - const xBin = Math.floor((x[i] - xMin) / xBinWidth); - const yBin = Math.floor((y[i] - yMin) / yBinWidth); - - if (xBin >= 0 && xBin < numBins && yBin >= 0 && yBin < numBins) { - jointHistogram[xBin][yBin]++; - xHistogram[xBin]++; - yHistogram[yBin]++; - } - } - - // Calculate probabilities - const jointProbabilities = jointHistogram.map(row => row.map(count => count / n)); - const xProbabilities = xHistogram.map(count => count / n); - const yProbabilities = yHistogram.map(count => count / n); - - // Calculate mutual information - let mi = 0; - for (let i = 0; i < numBins; i++) { - for (let j = 0; j < numBins; j++) { - if (jointProbabilities[i][j] > 0 && xProbabilities[i] > 0 && yProbabilities[j] > 0) { - mi += - jointProbabilities[i][j] * - Math.log(jointProbabilities[i][j] / (xProbabilities[i] * yProbabilities[j])); - } - } - } - - const correlation = mi; // Use MI as correlation measure - - // Approximate p-value (permutation test) - let pValue = 1; - const numPermutations = 100; - - for (let p = 0; p < numPermutations; p++) { - const yPermuted = shuffleArray([...y]); - let miPermuted = 0; - - const jointHistogramPermuted = Array(numBins) - .fill(null) - .map(() => Array(numBins).fill(0)); - - for (let i = 0; i < n; i++) { - const xBin = Math.floor((x[i] - xMin) / xBinWidth); - const yBin = Math.floor((yPermuted[i] - yMin) / yBinWidth); - - if (xBin >= 0 && xBin < numBins && yBin >= 0 && yBin < numBins) { - jointHistogramPermuted[xBin][yBin]++; - } - } - - const jointProbabilitiesPermuted = jointHistogramPermuted.map(row => - row.map(count => count / n) - ); - - for (let i = 0; i < numBins; i++) { - for (let j = 0; j < numBins; j++) { - if ( - jointProbabilitiesPermuted[i][j] > 0 && - xProbabilities[i] > 0 && - yProbabilities[j] > 0 - ) { - miPermuted += - jointProbabilitiesPermuted[i][j] * - Math.log(jointProbabilitiesPermuted[i][j] / (xProbabilities[i] * yProbabilities[j])); - } - } - } - - if (miPermuted >= mi) { - pValue++; - } - } - - pValue /= numPermutations + 1; - const significance = pValue < 0.05; - - return { - correlation, - pValue, - significance, - }; -} - -/** - * Calculate Cross-Correlation - */ -export function crossCorrelation(x: number[], y: number[], maxLag: number): number[] { - const n = x.length; - if (n !== y.length) { - throw new Error('Arrays must have the same length'); - } - - const correlations: number[] = []; - - for (let lag = -maxLag; lag <= maxLag; lag++) { - let sum = 0; - let count = 0; - - for (let i = 0; i < n; i++) { - const yIndex = i + lag; - - if (yIndex >= 0 && yIndex < n) { - sum += (x[i] - average(x)) * (y[yIndex] - average(y)); - count++; - } - } - - const stdX = Math.sqrt(x.reduce((sum, xi) => sum + Math.pow(xi - average(x), 2), 0) / (n - 1)); - const stdY = Math.sqrt(y.reduce((sum, yi) => sum + Math.pow(yi - average(y), 2), 0) / (n - 1)); - - const correlation = count > 0 ? sum / ((count - 1) * stdX * stdY) : 0; - correlations.push(correlation); - } - - return correlations; -} - -/** - * Calculate Autocorrelation - */ -export function autocorrelation(x: number[], lag: number): number { - const n = x.length; - if (lag >= n) { - throw new Error('Lag must be less than the length of the array'); - } - - let sum = 0; - for (let i = lag; i < n; i++) { - sum += (x[i] - average(x)) * (x[i - lag] - average(x)); - } - - const std = Math.sqrt(x.reduce((sum, xi) => sum + Math.pow(xi - average(x), 2), 0) / (n - 1)); - return sum / ((n - lag - 1) * std * std); -} - -/** - * Helper function to shuffle an array (Fisher-Yates shuffle) - */ -function shuffleArray(array: T[]): T[] { - const newArray = [...array]; - for (let i = newArray.length - 1; i > 0; i--) { - const j = Math.floor(Math.random() * (i + 1)); - [newArray[i], newArray[j]] = [newArray[j], newArray[i]]; - } - return newArray; -} - -/** - * Helper function to calculate the average of an array of numbers - */ -function average(arr: number[]): number { - if (arr.length === 0) { - return 0; - } - return arr.reduce((a, b) => a + b, 0) / arr.length; -} - -function getRanks(arr: number[]): number[] { - const sorted = arr.map((val, idx) => ({ val, idx })).sort((a, b) => a.val - b.val); - const ranks = new Array(arr.length); - - for (let i = 0; i < sorted.length; i++) { - ranks[sorted[i].idx] = i + 1; - } - - return ranks; -} - -function studentTCDF(t: number, df: number): number { - // Approximation for Student's t CDF - const x = df / (t * t + df); - return 1 - 0.5 * betaIncomplete(df / 2, 0.5, x); -} - -function normalCDF(z: number): number { - return 0.5 * (1 + erf(z / Math.sqrt(2))); -} - -function erf(x: number): number { - // Approximation of error function - const a1 = 0.254829592; - const a2 = -0.284496736; - const a3 = 1.421413741; - const a4 = -1.453152027; - const a5 = 1.061405429; - const p = 0.3275911; - - const sign = x >= 0 ? 1 : -1; - x = Math.abs(x); - - const t = 1.0 / (1.0 + p * x); - const y = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x); - - return sign * y; -} - -function betaIncomplete(a: number, b: number, x: number): number { - // Better approximation of incomplete beta function - if (x === 0) { - return 0; - } - if (x === 1) { - return 1; - } - - // Use continued fraction approximation (Lentz's algorithm) - const fpmin = 1e-30; - const maxIter = 200; - const eps = 3e-7; - - const bt = Math.exp( - gammaLn(a + b) - gammaLn(a) - gammaLn(b) + a * Math.log(x) + b * Math.log(1 - x) - ); - - if (x < (a + 1) / (a + b + 2)) { - return (bt * betaContinuedFraction(a, b, x)) / a; - } else { - return 1 - (bt * betaContinuedFraction(b, a, 1 - x)) / b; - } - - function betaContinuedFraction(a: number, b: number, x: number): number { - let c = 1; - let d = 1 - ((a + b) * x) / (a + 1); - if (Math.abs(d) < fpmin) { - d = fpmin; - } - d = 1 / d; - let h = d; - - for (let m = 1; m <= maxIter; m++) { - const m2 = 2 * m; - const aa = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2)); - d = 1 + aa * d; - if (Math.abs(d) < fpmin) { - d = fpmin; - } - c = 1 + aa / c; - if (Math.abs(c) < fpmin) { - c = fpmin; - } - d = 1 / d; - h *= d * c; - - const bb = (-(a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1)); - d = 1 + bb * d; - if (Math.abs(d) < fpmin) { - d = fpmin; - } - c = 1 + bb / c; - if (Math.abs(c) < fpmin) { - c = fpmin; - } - d = 1 / d; - const del = d * c; - h *= del; - - if (Math.abs(del - 1) < eps) { - break; - } - } - - return h; - } - - function gammaLn(xx: number): number { - const stp = 2.50662827465; - const coeffs = [ - 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, - 0.1208650973866179e-2, -0.5395239384953e-5, - ]; - - let x = xx - 1; - let tmp = x + 5.5; - tmp -= (x + 0.5) * Math.log(tmp); - let ser = 1.000000000190015; - - for (let j = 0; j < 6; j++) { - x += 1; - ser += coeffs[j] / x; - } - - return -tmp + Math.log(stp * ser); - } -} - -function eigenDecomposition(matrix: number[][]): { - eigenvalues: number[]; - eigenvectors: number[][]; -} { - // Simplified eigenvalue decomposition (for symmetric matrices) - const n = matrix.length; - - // Power iteration for largest eigenvalue - const eigenvalues: number[] = []; - const eigenvectors: number[][] = []; - - for (let k = 0; k < Math.min(n, 3); k++) { - // Calculate first 3 eigenvalues - let v = Array(n).fill(1 / Math.sqrt(n)); - let lambda = 0; - - for (let iter = 0; iter < 100; iter++) { - const Av = matrix.map(row => row.reduce((sum, val, i) => sum + val * v[i], 0)); - const newLambda = Av.reduce((sum, val, i) => sum + val * v[i], 0); - const norm = Math.sqrt(Av.reduce((sum, val) => sum + val * val, 0)); - - if (norm === 0) { - break; - } - - v = Av.map(val => val / norm); - - if (Math.abs(newLambda - lambda) < 1e-10) { - break; - } - lambda = newLambda; - } - - eigenvalues.push(lambda); - eigenvectors.push([...v]); - - // Deflate matrix for next eigenvalue - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - matrix[i][j] -= lambda * v[i] * v[j]; - } - } - } - - return { eigenvalues, eigenvectors }; -} - -function residuals(y: number[], X: number[][]): number[] { - // Simple linear regression to calculate residuals - const n = y.length; - const k = X[0].length; - - // Calculate (X'X)^-1 X' y - const XtX = Array(k) - .fill(null) - .map(() => Array(k).fill(0)); - const Xty = Array(k).fill(0); - - // X'X - for (let i = 0; i < k; i++) { - for (let j = 0; j < k; j++) { - for (let t = 0; t < n; t++) { - XtX[i][j] += X[t][i] * X[t][j]; - } - } - } - - // X'y - for (let i = 0; i < k; i++) { - for (let t = 0; t < n; t++) { - Xty[i] += X[t][i] * y[t]; - } - } - - // Solve for beta (simplified - assumes invertible) - const beta = solveLinearSystem(XtX, Xty); - - // Calculate residuals - const residuals: number[] = []; - for (let t = 0; t < n; t++) { - let fitted = 0; - for (let i = 0; i < k; i++) { - fitted += X[t][i] * beta[i]; - } - residuals.push(y[t] - fitted); - } - - return residuals; -} - -function solveLinearSystem(A: number[][], b: number[]): number[] { - // Gaussian elimination (simplified) - const n = A.length; - const augmented = A.map((row, i) => [...row, b[i]]); - - // Forward elimination - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - const factor = augmented[j][i] / augmented[i][i]; - for (let k = i; k <= n; k++) { - augmented[j][k] -= factor * augmented[i][k]; - } - } - } - - // Back substitution - const x = Array(n).fill(0); - for (let i = n - 1; i >= 0; i--) { - x[i] = augmented[i][n]; - for (let j = i + 1; j < n; j++) { - x[i] -= augmented[i][j] * x[j]; - } - x[i] /= augmented[i][i]; - } - - return x; -} - -function varModel( - x: number[], - y: number[], - lag: number -): { - rssX: number; - rssY: number; - aic: number; -} { - // Simplified VAR model calculation - const n = x.length - lag; - - // Build design matrix - const X = Array(n) - .fill(null) - .map(() => Array(2 * lag + 1).fill(1)); - const yX = Array(n).fill(0); - const yY = Array(n).fill(0); - - for (let t = 0; t < n; t++) { - yX[t] = x[t + lag]; - yY[t] = y[t + lag]; - - for (let l = 0; l < lag; l++) { - X[t][1 + l] = x[t + lag - 1 - l]; - X[t][1 + lag + l] = y[t + lag - 1 - l]; - } - } - - // Calculate residuals for both equations - const residualsX = residuals(yX, X); - const residualsY = residuals(yY, X); - - const rssX = residualsX.reduce((sum, r) => sum + r * r, 0); - const rssY = residualsY.reduce((sum, r) => sum + r * r, 0); - - const k = 2 * lag + 1; - const aic = n * Math.log(rssX + rssY) + 2 * k; - - return { rssX, rssY, aic }; -} - -function arModel(y: number[], lag: number): { rss: number } { - const n = y.length - lag; - - // Build design matrix - const X = Array(n) - .fill(null) - .map(() => Array(lag + 1).fill(1)); - const yVec = Array(n).fill(0); - - for (let t = 0; t < n; t++) { - yVec[t] = y[t + lag]; - - for (let l = 0; l < lag; l++) { - X[t][1 + l] = y[t + lag - 1 - l]; - } - } - - const res = residuals(yVec, X); - const rss = res.reduce((sum, r) => sum + r * r, 0); - - return { rss }; -} - -function fCDF(f: number, df1: number, df2: number): number { - // Approximation for F distribution CDF - if (f <= 0) { - return 0; - } - if (f === Infinity) { - return 1; - } - - const x = df2 / (df2 + df1 * f); - return 1 - betaIncomplete(df2 / 2, df1 / 2, x); -} -``` diff --git a/libs/calculations/research/market-statistics.md b/libs/calculations/research/market-statistics.md deleted file mode 100644 index 79352392..00000000 --- a/libs/calculations/research/market-statistics.md +++ /dev/null @@ -1,1038 +0,0 @@ -# market-statistics research snapshot - -Source: `ccce401:libs/utils/src/calculations/market-statistics.ts.disabled`. - -Contains fixed correlation stress, estimated market cap, and simplified spread/impact outputs. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Market Statistics and Microstructure Analysis - * Tools for analyzing market behavior, liquidity, and trading patterns - */ - -// Local interface definition to avoid circular dependency -interface OHLCVData { - open: number; - high: number; - low: number; - close: number; - volume: number; - timestamp: Date; -} - -export interface LiquidityMetrics { - bidAskSpread: number; - relativeSpread: number; - effectiveSpread: number; - priceImpact: number; - marketDepth: number; - turnoverRatio: number; - volumeWeightedSpread: number; -} - -export interface MarketMicrostructure { - tickSize: number; - averageTradeSize: number; - tradingFrequency: number; - marketImpactCoefficient: number; - informationShare: number; - orderImbalance: number; -} - -export interface TradingSessionStats { - openPrice: number; - closePrice: number; - highPrice: number; - lowPrice: number; - volume: number; - vwap: number; - numberOfTrades: number; - averageTradeSize: number; - volatility: number; -} - -export interface MarketRegime { - regime: 'trending' | 'ranging' | 'volatile' | 'quiet'; - confidence: number; - trendDirection?: 'up' | 'down'; - volatilityLevel: 'low' | 'medium' | 'high'; -} - -/** - * Volume Weighted Average Price (VWAP) - */ -export function VWAP(ohlcv: OHLCVData[]): number[] { - if (ohlcv.length === 0) { - return []; - } - - const vwap: number[] = []; - let cumulativeVolumePrice = 0; - let cumulativeVolume = 0; - - for (const candle of ohlcv) { - const typicalPrice = (candle.high + candle.low + candle.close) / 3; - cumulativeVolumePrice += typicalPrice * candle.volume; - cumulativeVolume += candle.volume; - - vwap.push(cumulativeVolume > 0 ? cumulativeVolumePrice / cumulativeVolume : typicalPrice); - } - - return vwap; -} - -/** - * Time Weighted Average Price (TWAP) - */ -export function TWAP(prices: number[], timeWeights?: number[]): number { - if (prices.length === 0) { - return 0; - } - - if (!timeWeights) { - return prices.reduce((sum, price) => sum + price, 0) / prices.length; - } - - if (prices.length !== timeWeights.length) { - throw new Error('Prices and time weights arrays must have the same length'); - } - - const totalWeight = timeWeights.reduce((sum, weight) => sum + weight, 0); - const weightedSum = prices.reduce((sum, price, index) => sum + price * timeWeights[index], 0); - - return totalWeight > 0 ? weightedSum / totalWeight : 0; -} - -/** - * market impact of trades - */ -export function MarketImpact( - trades: Array<{ price: number; volume: number; side: 'buy' | 'sell'; timestamp: Date }>, - benchmarkPrice: number -): { - temporaryImpact: number; - permanentImpact: number; - totalImpact: number; - priceImprovement: number; -} { - if (trades.length === 0) { - return { - temporaryImpact: 0, - permanentImpact: 0, - totalImpact: 0, - priceImprovement: 0, - }; - } - - const volumeWeightedPrice = - trades.reduce((sum, trade) => sum + trade.price * trade.volume, 0) / - trades.reduce((sum, trade) => sum + trade.volume, 0); - - const totalImpact = (volumeWeightedPrice - benchmarkPrice) / benchmarkPrice; - - // Simplified impact calculation - const temporaryImpact = totalImpact * 0.6; // Temporary component - const permanentImpact = totalImpact * 0.4; // Permanent component - - const priceImprovement = - trades.reduce((sum, trade) => { - const improvement = - trade.side === 'buy' - ? Math.max(0, benchmarkPrice - trade.price) - : Math.max(0, trade.price - benchmarkPrice); - return sum + improvement * trade.volume; - }, 0) / trades.reduce((sum, trade) => sum + trade.volume, 0); - - return { - temporaryImpact, - permanentImpact, - totalImpact, - priceImprovement, - }; -} - -/** - * liquidity metrics - */ -export function LiquidityMetrics( - ohlcv: OHLCVData[], - bidPrices: number[], - askPrices: number[], - bidSizes: number[], - askSizes: number[] -): LiquidityMetrics { - if (ohlcv.length === 0 || bidPrices.length === 0) { - return { - bidAskSpread: 0, - relativeSpread: 0, - effectiveSpread: 0, - priceImpact: 0, - marketDepth: 0, - turnoverRatio: 0, - volumeWeightedSpread: 0, - }; - } - - // Average bid-ask spread - const spreads = bidPrices.map((bid, index) => askPrices[index] - bid); - const bidAskSpread = spreads.reduce((sum, spread) => sum + spread, 0) / spreads.length; - - // Relative spread - const midPrices = bidPrices.map((bid, index) => (bid + askPrices[index]) / 2); - const averageMidPrice = midPrices.reduce((sum, mid) => sum + mid, 0) / midPrices.length; - const relativeSpread = averageMidPrice > 0 ? bidAskSpread / averageMidPrice : 0; - - // Market depth - const averageBidSize = bidSizes.reduce((sum, size) => sum + size, 0) / bidSizes.length; - const averageAskSize = askSizes.reduce((sum, size) => sum + size, 0) / askSizes.length; - const marketDepth = (averageBidSize + averageAskSize) / 2; - - // Turnover ratio - const averageVolume = ohlcv.reduce((sum, candle) => sum + candle.volume, 0) / ohlcv.length; - const averagePrice = ohlcv.reduce((sum, candle) => sum + candle.close, 0) / ohlcv.length; - const marketCap = averagePrice * 1000000; // Simplified market cap - const turnoverRatio = marketCap > 0 ? (averageVolume * averagePrice) / marketCap : 0; - - return { - bidAskSpread, - relativeSpread: relativeSpread * 100, // Convert to percentage - effectiveSpread: bidAskSpread * 0.8, // Simplified effective spread - priceImpact: relativeSpread * 2, // Simplified price impact - marketDepth, - turnoverRatio: turnoverRatio * 100, // Convert to percentage - volumeWeightedSpread: bidAskSpread, // Simplified - }; -} - -/** - * Identify market regimes - */ -export function identifyMarketRegime( - ohlcv: OHLCVData[], - lookbackPeriod: number = 20 -): MarketRegime { - if (ohlcv.length < lookbackPeriod) { - return { - regime: 'quiet', - confidence: 0, - volatilityLevel: 'low', - }; - } - - const recentData = ohlcv.slice(-lookbackPeriod); - const prices = recentData.map(candle => candle.close); - const volumes = recentData.map(candle => candle.volume); - // returns and volatility - const returns = []; - for (let i = 1; i < prices.length; i++) { - returns.push((prices[i] - prices[i - 1]) / prices[i - 1]); - } - - const volatility = calculateVolatility(returns); - const averageVolume = volumes.reduce((sum, vol) => sum + vol, 0) / volumes.length; - - // Trend analysis - const firstPrice = prices[0]; - const lastPrice = prices[prices.length - 1]; - const trendStrength = Math.abs((lastPrice - firstPrice) / firstPrice); - - // Determine volatility level - let volatilityLevel: 'low' | 'medium' | 'high'; - if (volatility < 0.01) { - volatilityLevel = 'low'; - } else if (volatility < 0.03) { - volatilityLevel = 'medium'; - } else { - volatilityLevel = 'high'; - } - - // Determine regime - let regime: 'trending' | 'ranging' | 'volatile' | 'quiet'; - let confidence = 0; - let trendDirection: 'up' | 'down' | undefined; - - if (volatility < 0.005) { - regime = 'quiet'; - confidence = 0.8; - } else if (volatility > 0.04) { - regime = 'volatile'; - confidence = 0.7; - } else if (trendStrength > 0.05) { - regime = 'trending'; - trendDirection = lastPrice > firstPrice ? 'up' : 'down'; - confidence = Math.min(0.9, trendStrength * 10); - } else { - regime = 'ranging'; - confidence = 0.6; - } - - return { - regime, - confidence, - trendDirection, - volatilityLevel, - }; -} - -/** - * order book imbalance - */ -export function OrderBookImbalance( - bidPrices: number[], - askPrices: number[], - bidSizes: number[], - askSizes: number[], - levels: number = 5 -): number { - const levelsToAnalyze = Math.min(levels, bidPrices.length, askPrices.length); - - let totalBidVolume = 0; - let totalAskVolume = 0; - - for (let i = 0; i < levelsToAnalyze; i++) { - totalBidVolume += bidSizes[i]; - totalAskVolume += askSizes[i]; - } - - const totalVolume = totalBidVolume + totalAskVolume; - - if (totalVolume === 0) { - return 0; - } - - return (totalBidVolume - totalAskVolume) / totalVolume; -} - -/** - * intraday patterns - */ -export function IntradayPatterns(ohlcv: OHLCVData[]): { - hourlyReturns: { [hour: number]: number }; - hourlyVolatility: { [hour: number]: number }; - hourlyVolume: { [hour: number]: number }; - openingGap: number; - closingDrift: number; -} { - const hourlyData: { [hour: number]: { returns: number[]; volumes: number[] } } = {}; - - // Initialize hourly buckets - for (let hour = 0; hour < 24; hour++) { - hourlyData[hour] = { returns: [], volumes: [] }; - } - - // Aggregate data by hour - for (let i = 1; i < ohlcv.length; i++) { - const hour = ohlcv[i].timestamp.getHours(); - const return_ = (ohlcv[i].close - ohlcv[i - 1].close) / ohlcv[i - 1].close; - - hourlyData[hour].returns.push(return_); - hourlyData[hour].volumes.push(ohlcv[i].volume); - } - - // statistics for each hour - const hourlyReturns: { [hour: number]: number } = {}; - const hourlyVolatility: { [hour: number]: number } = {}; - const hourlyVolume: { [hour: number]: number } = {}; - - for (let hour = 0; hour < 24; hour++) { - const data = hourlyData[hour]; - hourlyReturns[hour] = - data.returns.length > 0 - ? data.returns.reduce((sum, ret) => sum + ret, 0) / data.returns.length - : 0; - - hourlyVolatility[hour] = calculateVolatility(data.returns); - - hourlyVolume[hour] = - data.volumes.length > 0 - ? data.volumes.reduce((sum, vol) => sum + vol, 0) / data.volumes.length - : 0; - } - // opening gap and closing drift - const openingGap = ohlcv.length > 1 ? (ohlcv[1].open - ohlcv[0].close) / ohlcv[0].close : 0; - - const lastCandle = ohlcv[ohlcv.length - 1]; - const closingDrift = (lastCandle.close - lastCandle.open) / lastCandle.open; - - return { - hourlyReturns, - hourlyVolatility, - hourlyVolume, - openingGap, - closingDrift, - }; -} - -/** - * price discovery metrics - */ -export function PriceDiscovery( - prices1: number[], // Prices from market 1 - prices2: number[] // Prices from market 2 -): { - informationShare1: number; - informationShare2: number; - priceLeadLag: number; // Positive if market 1 leads - cointegrationStrength: number; -} { - if (prices1.length !== prices2.length || prices1.length < 2) { - return { - informationShare1: 0.5, - informationShare2: 0.5, - priceLeadLag: 0, - cointegrationStrength: 0, - }; - } - - // returns - const returns1 = []; - const returns2 = []; - - for (let i = 1; i < prices1.length; i++) { - returns1.push((prices1[i] - prices1[i - 1]) / prices1[i - 1]); - returns2.push((prices2[i] - prices2[i - 1]) / prices2[i - 1]); - } - // correlations with lags - const correlation0 = calculateCorrelation(returns1, returns2); - const correlation1 = - returns1.length > 1 ? calculateCorrelation(returns1.slice(1), returns2.slice(0, -1)) : 0; - const correlationMinus1 = - returns1.length > 1 ? calculateCorrelation(returns1.slice(0, -1), returns2.slice(1)) : 0; - - // Price lead-lag (simplified) - const priceLeadLag = correlation1 - correlationMinus1; - - // Information shares (simplified Hasbrouck methodology) - const variance1 = calculateVariance(returns1); - const variance2 = calculateVariance(returns2); - const covariance = calculateCovariance(returns1, returns2); - - const totalVariance = variance1 + variance2 + 2 * covariance; - const informationShare1 = totalVariance > 0 ? (variance1 + covariance) / totalVariance : 0.5; - const informationShare2 = 1 - informationShare1; - - // Cointegration strength (simplified) - const cointegrationStrength = Math.abs(correlation0); - - return { - informationShare1, - informationShare2, - priceLeadLag, - cointegrationStrength, - }; -} - -/** - * market stress indicators - */ -export function MarketStress( - ohlcv: OHLCVData[], - lookbackPeriod: number = 20 -): { - stressLevel: 'low' | 'medium' | 'high' | 'extreme'; - volatilityStress: number; - liquidityStress: number; - correlationStress: number; - overallStress: number; -} { - if (ohlcv.length < lookbackPeriod) { - return { - stressLevel: 'low', - volatilityStress: 0, - liquidityStress: 0, - correlationStress: 0, - overallStress: 0, - }; - } - - const recentData = ohlcv.slice(-lookbackPeriod); - const returns = []; - const volumes = []; - - for (let i = 1; i < recentData.length; i++) { - returns.push((recentData[i].close - recentData[i - 1].close) / recentData[i - 1].close); - volumes.push(recentData[i].volume); - } - // Volatility stress - const volatility = calculateVolatility(returns); - const volatilityStress = Math.min(1, volatility / 0.05); // Normalize to 5% daily vol - - // Liquidity stress (volume-based) - const averageVolume = volumes.reduce((sum, vol) => sum + vol, 0) / volumes.length; - const volumeVariability = calculateVolatility(volumes.map(vol => vol / averageVolume)); - const liquidityStress = Math.min(1, volumeVariability); - - // Correlation stress (simplified - would need multiple assets) - const correlationStress = 0.3; // Placeholder - - // Overall stress - const overallStress = volatilityStress * 0.4 + liquidityStress * 0.3 + correlationStress * 0.3; - - let stressLevel: 'low' | 'medium' | 'high' | 'extreme'; - if (overallStress < 0.25) { - stressLevel = 'low'; - } else if (overallStress < 0.5) { - stressLevel = 'medium'; - } else if (overallStress < 0.75) { - stressLevel = 'high'; - } else { - stressLevel = 'extreme'; - } - - return { - stressLevel, - volatilityStress, - liquidityStress, - correlationStress, - overallStress, - }; -} - -/** - * realized spread - */ -export function RealizedSpread( - trades: Array<{ price: number; side: 'buy' | 'sell'; timestamp: Date }>, - midPrices: number[], - timeWindow: number = 5 // minutes -): number { - if (trades.length === 0 || midPrices.length === 0) { - return 0; - } - - let totalSpread = 0; - let count = 0; - - for (const trade of trades) { - // Find corresponding mid price - const midPrice = midPrices[0]; // Simplified - should match by timestamp - - const spread = - trade.side === 'buy' ? 2 * (trade.price - midPrice) : 2 * (midPrice - trade.price); - - totalSpread += spread; - count++; - } - - return count > 0 ? totalSpread / count : 0; -} - -/** - * implementation shortfall - */ -export function ImplementationShortfall( - decisionPrice: number, - executionPrices: number[], - volumes: number[], - commissions: number[], - marketImpact: number[] -): { - totalShortfall: number; - delayComponent: number; - marketImpactComponent: number; - timingComponent: number; - commissionComponent: number; -} { - if (executionPrices.length !== volumes.length) { - throw new Error('Execution prices and volumes must have same length'); - } - - const totalVolume = volumes.reduce((sum, vol) => sum + vol, 0); - const weightedExecutionPrice = - executionPrices.reduce((sum, price, i) => sum + price * volumes[i], 0) / totalVolume; - - const totalCommissions = commissions.reduce((sum, comm) => sum + comm, 0); - const totalMarketImpact = marketImpact.reduce((sum, impact, i) => sum + impact * volumes[i], 0); - - const delayComponent = weightedExecutionPrice - decisionPrice; - const marketImpactComponent = totalMarketImpact / totalVolume; - const timingComponent = 0; // Simplified - would need benchmark price evolution - const commissionComponent = totalCommissions / totalVolume; - - const totalShortfall = - delayComponent + marketImpactComponent + timingComponent + commissionComponent; - - return { - totalShortfall, - delayComponent, - marketImpactComponent, - timingComponent, - commissionComponent, - }; -} - -/** - * Amihud Illiquidity Measure (price impact per unit of volume) - */ -export function amihudIlliquidity(ohlcv: OHLCVData[], lookbackPeriod: number = 252): number { - if (ohlcv.length < lookbackPeriod) { - return 0; - } - - const recentData = ohlcv.slice(-lookbackPeriod); - let illiquiditySum = 0; - let validDays = 0; - - for (const candle of recentData) { - if (candle.volume > 0) { - const dailyReturn = Math.abs((candle.close - candle.open) / candle.open); - const dollarVolume = candle.volume * candle.close; - - if (dollarVolume > 0) { - illiquiditySum += dailyReturn / dollarVolume; - validDays++; - } - } - } - - return validDays > 0 ? (illiquiditySum / validDays) * 1000000 : 0; // Scale to millions -} - -/** - * Roll's Spread Estimator (effective spread from serial covariance) - */ -export function rollSpreadEstimator(prices: number[]): number { - if (prices.length < 3) { - return 0; - } - - // Calculate price changes - const priceChanges: number[] = []; - for (let i = 1; i < prices.length; i++) { - priceChanges.push(prices[i] - prices[i - 1]); - } - - // Calculate serial covariance - let covariance = 0; - for (let i = 1; i < priceChanges.length; i++) { - covariance += priceChanges[i] * priceChanges[i - 1]; - } - covariance /= priceChanges.length - 1; - - // Roll's estimator: spread = 2 * sqrt(-covariance) - const spread = covariance < 0 ? 2 * Math.sqrt(-covariance) : 0; - - return spread; -} - -/** - * Kyle's Lambda (price impact coefficient) - */ -export function kyleLambda( - priceChanges: number[], - orderFlow: number[] // Signed order flow (positive for buys, negative for sells) -): number { - if (priceChanges.length !== orderFlow.length || priceChanges.length < 2) { - return 0; - } - - // Calculate regression: priceChange = lambda * orderFlow + error - const n = priceChanges.length; - const meanPrice = priceChanges.reduce((sum, p) => sum + p, 0) / n; - const meanFlow = orderFlow.reduce((sum, f) => sum + f, 0) / n; - - let numerator = 0; - let denominator = 0; - - for (let i = 0; i < n; i++) { - const priceDeviation = priceChanges[i] - meanPrice; - const flowDeviation = orderFlow[i] - meanFlow; - - numerator += priceDeviation * flowDeviation; - denominator += flowDeviation * flowDeviation; - } - - return denominator > 0 ? numerator / denominator : 0; -} - -/** - * Probability of Informed Trading (PIN) - simplified version - */ -export function probabilityInformedTrading( - buyVolumes: number[], - sellVolumes: number[], - period: number = 20 -): number { - if (buyVolumes.length !== sellVolumes.length || buyVolumes.length < period) { - return 0; - } - - const recentBuys = buyVolumes.slice(-period); - const recentSells = sellVolumes.slice(-period); - - let totalImbalance = 0; - let totalVolume = 0; - - for (let i = 0; i < period; i++) { - const imbalance = Math.abs(recentBuys[i] - recentSells[i]); - const volume = recentBuys[i] + recentSells[i]; - - totalImbalance += imbalance; - totalVolume += volume; - } - - // Simplified PIN estimate based on order imbalance - return totalVolume > 0 ? totalImbalance / totalVolume : 0; -} - -/** - * Herfindahl-Hirschman Index for Volume Concentration - */ -export function volumeConcentrationHHI(exchanges: Array<{ name: string; volume: number }>): number { - if (exchanges.length === 0) { - return 0; - } - - const totalVolume = exchanges.reduce((sum, exchange) => sum + exchange.volume, 0); - - if (totalVolume === 0) { - return 0; - } - - let hhi = 0; - for (const exchange of exchanges) { - const marketShare = exchange.volume / totalVolume; - hhi += marketShare * marketShare; - } - - return hhi * 10000; // Scale to 0-10000 range -} -/** - * Volume Profile - */ -export function volumeProfile( - ohlcv: OHLCVData[], - priceLevels: number -): { [price: number]: number } { - const profile: { [price: number]: number } = {}; - - if (ohlcv.length === 0) { - return profile; - } - - const minPrice = Math.min(...ohlcv.map(candle => candle.low)); - const maxPrice = Math.max(...ohlcv.map(candle => candle.high)); - const priceRange = maxPrice - minPrice; - const priceIncrement = priceRange / priceLevels; - - for (let i = 0; i < priceLevels; i++) { - const priceLevel = minPrice + i * priceIncrement; - profile[priceLevel] = 0; - } - - for (const candle of ohlcv) { - const typicalPrice = (candle.high + candle.low + candle.close) / 3; - const priceLevel = - minPrice + Math.floor((typicalPrice - minPrice) / priceIncrement) * priceIncrement; - if (profile[priceLevel] !== undefined) { - profile[priceLevel] += candle.volume; - } - } - - return profile; -} - -/** - * Delta Neutral Hedging Ratio - */ -export function deltaNeutralHedgingRatio(optionDelta: number): number { - return -optionDelta; -} - -/** - * Gamma Scalping Range - */ -export function gammaScalpingRange(gamma: number, theta: number, timeIncrement: number): number { - return Math.sqrt((2 * Math.abs(theta) * timeIncrement) / gamma); -} - -/** - * Optimal Order Size (based on market impact) - */ -export function optimalOrderSize(alpha: number, lambda: number): number { - return alpha / (2 * lambda); -} - -/** - * Adverse Selection Component of the Spread - */ -export function adverseSelectionComponent( - probabilityOfInformedTrader: number, - spread: number -): number { - return probabilityOfInformedTrader * spread; -} - -/** - * Inventory Risk Component of the Spread - */ -export function inventoryRiskComponent( - inventoryHoldingCost: number, - orderArrivalRate: number -): number { - return inventoryHoldingCost * Math.sqrt(orderArrivalRate); -} - -/** - * Quote Age - */ -export function quoteAge(lastUpdate: Date): number { - return Date.now() - lastUpdate.getTime(); -} - -/** - * Trade Classification (Lee-Ready algorithm) - */ -export function tradeClassification( - tradePrice: number, - bidPrice: number, - askPrice: number, - previousTradePrice: number -): 'buy' | 'sell' | 'unknown' { - if (tradePrice > askPrice) { - return 'buy'; - } else if (tradePrice < bidPrice) { - return 'sell'; - } else if (tradePrice >= previousTradePrice) { - return 'buy'; - } else { - return 'sell'; - } -} - -/** - * Tick Rule - */ -export function tickRule( - tradePrice: number, - previousTradePrice: number -): 'buy' | 'sell' | 'unknown' { - if (tradePrice > previousTradePrice) { - return 'buy'; - } else if (tradePrice < previousTradePrice) { - return 'sell'; - } else { - return 'unknown'; - } -} - -/** - * Amihud's Lambda Variation with High-Frequency Data - */ -export function amihudIlliquidityHFT( - priceChanges: number[], - dollarVolumes: number[], - timeDeltas: number[] -): number { - let illiquiditySum = 0; - let validTrades = 0; - - for (let i = 0; i < priceChanges.length; i++) { - if (dollarVolumes[i] > 0 && timeDeltas[i] > 0) { - illiquiditySum += Math.abs(priceChanges[i]) / (dollarVolumes[i] * timeDeltas[i]); - validTrades++; - } - } - - return validTrades > 0 ? illiquiditySum / validTrades : 0; -} - -/** - * Garman-Klass Volatility - */ -export function garmanKlassVolatility( - openPrices: number[], - highPrices: number[], - lowPrices: number[], - closePrices: number[] -): number { - if ( - openPrices.length !== highPrices.length || - openPrices.length !== lowPrices.length || - openPrices.length !== closePrices.length || - openPrices.length < 2 - ) { - return 0; - } - - let sumSquaredTerm1 = 0; - let sumSquaredTerm2 = 0; - const sumSquaredTerm3 = 0; - - for (let i = 0; i < openPrices.length; i++) { - const logHO = Math.log(highPrices[i] / openPrices[i]); - const logLO = Math.log(lowPrices[i] / openPrices[i]); - const logCO = Math.log(closePrices[i] / openPrices[i]); - - sumSquaredTerm1 += 0.5 * (logHO * logHO + logLO * logLO); - sumSquaredTerm2 += -(2 * Math.log(2) - 1) * (logCO * logCO); - } - - const garmanKlassVariance = (1 / openPrices.length) * (sumSquaredTerm1 + sumSquaredTerm2); - return Math.sqrt(garmanKlassVariance); -} - -/** - * Yang-Zhang Volatility - */ -export function yangZhangVolatility( - openPrices: number[], - highPrices: number[], - lowPrices: number[], - closePrices: number[], - previousClosePrices: number[] -): number { - if ( - openPrices.length !== highPrices.length || - openPrices.length !== lowPrices.length || - openPrices.length !== closePrices.length || - openPrices.length !== previousClosePrices.length || - openPrices.length < 2 - ) { - return 0; - } - - const k = 0.34 / (1.34 + (openPrices.length + 1) / (previousClosePrices.length - 1)); - - let sumSquaredTerm1 = 0; - let sumSquaredTerm2 = 0; - let sumSquaredTerm3 = 0; - - for (let i = 0; i < openPrices.length; i++) { - const overnightReturn = Math.log(openPrices[i] / previousClosePrices[i]); - const openToHigh = Math.log(highPrices[i] / openPrices[i]); - const openToLow = Math.log(lowPrices[i] / openPrices[i]); - const closeToOpen = Math.log(closePrices[i] / openPrices[i]); - - sumSquaredTerm1 += overnightReturn * overnightReturn; - sumSquaredTerm2 += openToHigh * openToHigh; - sumSquaredTerm3 += openToLow * openToLow; - } - - const variance = sumSquaredTerm1 + k * sumSquaredTerm2 + (1 - k) * sumSquaredTerm3; - return Math.sqrt(variance); -} - -/** - * Volume Order Imbalance (VOI) - */ -export function volumeOrderImbalance(buyVolumes: number[], sellVolumes: number[]): number[] { - if (buyVolumes.length !== sellVolumes.length) { - return []; - } - - const voi: number[] = []; - for (let i = 0; i < buyVolumes.length; i++) { - voi.push(buyVolumes[i] - sellVolumes[i]); - } - return voi; -} - -/** - * Cumulative Volume Delta (CVD) - */ -export function cumulativeVolumeDelta(buyVolumes: number[], sellVolumes: number[]): number[] { - if (buyVolumes.length !== sellVolumes.length) { - return []; - } - - const cvd: number[] = []; - let cumulativeDelta = 0; - for (let i = 0; i < buyVolumes.length; i++) { - cumulativeDelta += buyVolumes[i] - sellVolumes[i]; - cvd.push(cumulativeDelta); - } - return cvd; -} - -/** - * Market Order Ratio - */ -export function marketOrderRatio(marketOrders: number[], limitOrders: number[]): number[] { - if (marketOrders.length !== limitOrders.length) { - return []; - } - - const ratios: number[] = []; - for (let i = 0; i < marketOrders.length; i++) { - const totalOrders = marketOrders[i] + limitOrders[i]; - ratios.push(totalOrders > 0 ? marketOrders[i] / totalOrders : 0); - } - return ratios; -} - -/** - * Helper function to calculate the average of an array of numbers - */ - -function average(arr: number[]): number { - if (arr.length === 0) { - return 0; - } - return arr.reduce((a, b) => a + b, 0) / arr.length; -} - -function calculateVolatility(returns: number[]): number { - if (returns.length < 2) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1); - - return Math.sqrt(variance); -} - -function calculateCorrelation(x: number[], y: number[]): number { - if (x.length !== y.length || x.length < 2) { - return 0; - } - - const n = x.length; - const meanX = x.reduce((sum, val) => sum + val, 0) / n; - const meanY = y.reduce((sum, val) => sum + val, 0) / n; - - let numerator = 0; - let sumXSquared = 0; - let sumYSquared = 0; - - for (let i = 0; i < n; i++) { - const xDiff = x[i] - meanX; - const yDiff = y[i] - meanY; - - numerator += xDiff * yDiff; - sumXSquared += xDiff * xDiff; - sumYSquared += yDiff * yDiff; - } - - const denominator = Math.sqrt(sumXSquared * sumYSquared); - - return denominator > 0 ? numerator / denominator : 0; -} - -function calculateVariance(values: number[]): number { - if (values.length < 2) { - return 0; - } - - const mean = values.reduce((sum, val) => sum + val, 0) / values.length; - return values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / (values.length - 1); -} - -function calculateCovariance(x: number[], y: number[]): number { - if (x.length !== y.length || x.length < 2) { - return 0; - } - - const n = x.length; - const meanX = x.reduce((sum, val) => sum + val, 0) / n; - const meanY = y.reduce((sum, val) => sum + val, 0) / n; - - return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1); -} -``` diff --git a/libs/calculations/research/options-pricing.md b/libs/calculations/research/options-pricing.md deleted file mode 100644 index fe74c591..00000000 --- a/libs/calculations/research/options-pricing.md +++ /dev/null @@ -1,822 +0,0 @@ -# options-pricing research snapshot - -Source: `ccce401:libs/utils/src/calculations/options-pricing.ts.disabled`. - -Contains unseeded Monte Carlo sampling and volatility-convergence fallbacks/logging. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Options Pricing Models - * Implementation of various options pricing models and Greeks calculations - */ - -export interface OptionParameters { - spotPrice: number; - strikePrice: number; - timeToExpiry: number; // in years - riskFreeRate: number; - volatility: number; - dividendYield?: number; -} - -export interface OptionPricing { - callPrice: number; - putPrice: number; - intrinsicValueCall: number; - intrinsicValuePut: number; - timeValueCall: number; - timeValuePut: number; -} - -export interface GreeksCalculation { - delta: number; - gamma: number; - theta: number; - vega: number; - rho: number; -} - -export interface ImpliedVolatilityResult { - impliedVolatility: number; - iterations: number; - converged: boolean; -} - -/** - * Black-Scholes option pricing model - */ -export function blackScholes(params: OptionParameters): OptionPricing { - const { - spotPrice, - strikePrice, - timeToExpiry, - riskFreeRate, - volatility, - dividendYield = 0, - } = params; - - if (timeToExpiry <= 0) { - const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0); - const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0); - - return { - callPrice: intrinsicValueCall, - putPrice: intrinsicValuePut, - intrinsicValueCall, - intrinsicValuePut, - timeValueCall: 0, - timeValuePut: 0, - }; - } - - const d1 = - (Math.log(spotPrice / strikePrice) + - (riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) / - (volatility * Math.sqrt(timeToExpiry)); - const d2 = d1 - volatility * Math.sqrt(timeToExpiry); - - const nd1 = normalCDF(d1); - const nd2 = normalCDF(d2); - const nMinusd1 = normalCDF(-d1); - const nMinusd2 = normalCDF(-d2); - - const callPrice = - spotPrice * Math.exp(-dividendYield * timeToExpiry) * nd1 - - strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2; - - const putPrice = - strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nMinusd2 - - spotPrice * Math.exp(-dividendYield * timeToExpiry) * nMinusd1; - - const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0); - const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0); - - const timeValueCall = callPrice - intrinsicValueCall; - const timeValuePut = putPrice - intrinsicValuePut; - - return { - callPrice, - putPrice, - intrinsicValueCall, - intrinsicValuePut, - timeValueCall, - timeValuePut, - }; -} - -export function impliedVolatility( - price: number, - S: number, - K: number, - T: number, - r: number, - isCall = true -): number { - // โ€ฆNewtonโ€“Raphson on ฯƒ to match blackScholesPrice - let sigma = 0.2; // Initial guess for volatility - const tolerance = 1e-6; - const maxIterations = 100; - let iteration = 0; - let priceDiff = 1; // Initialize to a non-zero value - while (Math.abs(priceDiff) > tolerance && iteration < maxIterations) { - const params: OptionParameters = { - spotPrice: S, - strikePrice: K, - timeToExpiry: T, - riskFreeRate: r, - volatility: sigma, - }; - - const calculatedPrice = isCall ? blackScholes(params).callPrice : blackScholes(params).putPrice; - priceDiff = calculatedPrice - price; - - // Calculate Vega - const greeks = calculateGreeks(params, isCall ? 'call' : 'put'); - const vega = greeks.vega * 100; // Convert from percentage to absolute - - if (vega === 0) { - break; // Avoid division by zero - } - - sigma -= priceDiff / vega; // Update volatility estimate - iteration++; - } - if (iteration === maxIterations) { - console.warn('Implied volatility calculation did not converge'); - } - - if (sigma < 0) { - console.warn('Calculated implied volatility is negative, returning 0'); - return 0; - } - - if (sigma > 10) { - console.warn('Calculated implied volatility is too high, returning 10'); - return 10; // Cap at a reasonable maximum - } - if (isNaN(sigma)) { - console.warn('Calculated implied volatility is NaN, returning 0'); - return 0; - } - return sigma; -} - -/** - * Calculate option Greeks using Black-Scholes model - */ -export function calculateGreeks( - params: OptionParameters, - optionType: 'call' | 'put' = 'call' -): GreeksCalculation { - const { - spotPrice, - strikePrice, - timeToExpiry, - riskFreeRate, - volatility, - dividendYield = 0, - } = params; - - if (timeToExpiry <= 0) { - return { - delta: - optionType === 'call' - ? spotPrice > strikePrice - ? 1 - : 0 - : spotPrice < strikePrice - ? -1 - : 0, - gamma: 0, - theta: 0, - vega: 0, - rho: 0, - }; - } - - const d1 = - (Math.log(spotPrice / strikePrice) + - (riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) / - (volatility * Math.sqrt(timeToExpiry)); - const d2 = d1 - volatility * Math.sqrt(timeToExpiry); - - const nd1 = normalCDF(d1); - const nd2 = normalCDF(d2); - const npd1 = normalPDF(d1); - - // Delta - const callDelta = Math.exp(-dividendYield * timeToExpiry) * nd1; - const putDelta = Math.exp(-dividendYield * timeToExpiry) * (nd1 - 1); - const delta = optionType === 'call' ? callDelta : putDelta; - - // Gamma (same for calls and puts) - const gamma = - (Math.exp(-dividendYield * timeToExpiry) * npd1) / - (spotPrice * volatility * Math.sqrt(timeToExpiry)); - - // Theta - const term1 = - -(spotPrice * npd1 * volatility * Math.exp(-dividendYield * timeToExpiry)) / - (2 * Math.sqrt(timeToExpiry)); - const term2Call = riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2; - const term2Put = - -riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2); - const term3 = - dividendYield * - spotPrice * - Math.exp(-dividendYield * timeToExpiry) * - (optionType === 'call' ? nd1 : normalCDF(-d1)); - - const theta = - optionType === 'call' ? (term1 - term2Call + term3) / 365 : (term1 + term2Put + term3) / 365; - - // Vega (same for calls and puts) - const vega = - (spotPrice * Math.exp(-dividendYield * timeToExpiry) * npd1 * Math.sqrt(timeToExpiry)) / 100; - - // Rho - const callRho = (strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * nd2) / 100; - const putRho = - (-strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2)) / 100; - const rho = optionType === 'call' ? callRho : putRho; - - return { - delta, - gamma, - theta, - vega, - rho, - }; -} - -/** - * Calculate implied volatility using Newton-Raphson method - */ -export function calculateImpliedVolatility( - marketPrice: number, - spotPrice: number, - strikePrice: number, - timeToExpiry: number, - riskFreeRate: number, - optionType: 'call' | 'put' = 'call', - dividendYield: number = 0, - initialGuess: number = 0.2, - tolerance: number = 1e-6, - maxIterations: number = 100 -): ImpliedVolatilityResult { - let volatility = initialGuess; - let iterations = 0; - let converged = false; - - for (let i = 0; i < maxIterations; i++) { - iterations = i + 1; - - const params: OptionParameters = { - spotPrice, - strikePrice, - timeToExpiry, - riskFreeRate, - volatility, - dividendYield, - }; - - const pricing = blackScholes(params); - const theoreticalPrice = optionType === 'call' ? pricing.callPrice : pricing.putPrice; - - const priceDiff = theoreticalPrice - marketPrice; - - if (Math.abs(priceDiff) < tolerance) { - converged = true; - break; - } - - // Calculate vega for Newton-Raphson - const greeks = calculateGreeks(params, optionType); - const vega = greeks.vega * 100; // Convert back from percentage - - if (Math.abs(vega) < 1e-10) { - break; // Avoid division by zero - } - - volatility = volatility - priceDiff / vega; - - // Keep volatility within reasonable bounds - volatility = Math.max(0.001, Math.min(volatility, 10)); - } - - return { - impliedVolatility: volatility, - iterations, - converged, - }; -} - -/** - * Binomial option pricing model - */ -export function binomialOptionPricing( - params: OptionParameters, - optionType: 'call' | 'put' = 'call', - americanStyle: boolean = false, - steps: number = 100 -): OptionPricing { - const { - spotPrice, - strikePrice, - timeToExpiry, - riskFreeRate, - volatility, - dividendYield = 0, - } = params; - - const dt = timeToExpiry / steps; - const u = Math.exp(volatility * Math.sqrt(dt)); - const d = 1 / u; - const p = (Math.exp((riskFreeRate - dividendYield) * dt) - d) / (u - d); - const discount = Math.exp(-riskFreeRate * dt); - - // Create price tree - const stockPrices: number[][] = []; - for (let i = 0; i <= steps; i++) { - stockPrices[i] = []; - for (let j = 0; j <= i; j++) { - stockPrices[i][j] = spotPrice * Math.pow(u, i - j) * Math.pow(d, j); - } - } - - // Calculate option values at expiration - const optionValues: number[][] = []; - for (let i = 0; i <= steps; i++) { - optionValues[i] = []; - } - - for (let j = 0; j <= steps; j++) { - if (optionType === 'call') { - optionValues[steps][j] = Math.max(stockPrices[steps][j] - strikePrice, 0); - } else { - optionValues[steps][j] = Math.max(strikePrice - stockPrices[steps][j], 0); - } - } - - // Work backwards through the tree - for (let i = steps - 1; i >= 0; i--) { - for (let j = 0; j <= i; j++) { - // European option value - const holdValue = - discount * (p * optionValues[i + 1][j] + (1 - p) * optionValues[i + 1][j + 1]); - - if (americanStyle) { - // American option - can exercise early - const exerciseValue = - optionType === 'call' - ? Math.max(stockPrices[i][j] - strikePrice, 0) - : Math.max(strikePrice - stockPrices[i][j], 0); - - optionValues[i][j] = Math.max(holdValue, exerciseValue); - } else { - optionValues[i][j] = holdValue; - } - } - } - - const price = optionValues[0][0]; - const intrinsicValue = - optionType === 'call' - ? Math.max(spotPrice - strikePrice, 0) - : Math.max(strikePrice - spotPrice, 0); - const timeValue = price - intrinsicValue; - - if (optionType === 'call') { - return { - callPrice: price, - putPrice: 0, // Not calculated - intrinsicValueCall: intrinsicValue, - intrinsicValuePut: 0, - timeValueCall: timeValue, - timeValuePut: 0, - }; - } else { - return { - callPrice: 0, // Not calculated - putPrice: price, - intrinsicValueCall: 0, - intrinsicValuePut: intrinsicValue, - timeValueCall: 0, - timeValuePut: timeValue, - }; - } -} - -/** - * Monte Carlo option pricing - */ -export function monteCarloOptionPricing( - params: OptionParameters, - optionType: 'call' | 'put' = 'call', - numSimulations: number = 100000 -): OptionPricing { - const { - spotPrice, - strikePrice, - timeToExpiry, - riskFreeRate, - volatility, - dividendYield = 0, - } = params; - - let totalPayoff = 0; - - for (let i = 0; i < numSimulations; i++) { - // Generate random price path - const z = boxMullerTransform(); - const finalPrice = - spotPrice * - Math.exp( - (riskFreeRate - dividendYield - 0.5 * volatility * volatility) * timeToExpiry + - volatility * Math.sqrt(timeToExpiry) * z - ); - - // Calculate payoff - const payoff = - optionType === 'call' - ? Math.max(finalPrice - strikePrice, 0) - : Math.max(strikePrice - finalPrice, 0); - - totalPayoff += payoff; - } - - const averagePayoff = totalPayoff / numSimulations; - const price = averagePayoff * Math.exp(-riskFreeRate * timeToExpiry); - - const intrinsicValue = - optionType === 'call' - ? Math.max(spotPrice - strikePrice, 0) - : Math.max(strikePrice - spotPrice, 0); - const timeValue = price - intrinsicValue; - - if (optionType === 'call') { - return { - callPrice: price, - putPrice: 0, - intrinsicValueCall: intrinsicValue, - intrinsicValuePut: 0, - timeValueCall: timeValue, - timeValuePut: 0, - }; - } else { - return { - callPrice: 0, - putPrice: price, - intrinsicValueCall: 0, - intrinsicValuePut: intrinsicValue, - timeValueCall: 0, - timeValuePut: timeValue, - }; - } -} - -/** - * Calculate option portfolio risk metrics - */ -export function calculateOptionPortfolioRisk( - positions: Array<{ - optionType: 'call' | 'put'; - quantity: number; - params: OptionParameters; - }> -): { - totalDelta: number; - totalGamma: number; - totalTheta: number; - totalVega: number; - totalRho: number; - portfolioValue: number; -} { - let totalDelta = 0; - let totalGamma = 0; - let totalTheta = 0; - let totalVega = 0; - let totalRho = 0; - let portfolioValue = 0; - - for (const position of positions) { - const greeks = calculateGreeks(position.params, position.optionType); - const pricing = blackScholes(position.params); - const optionPrice = position.optionType === 'call' ? pricing.callPrice : pricing.putPrice; - - totalDelta += greeks.delta * position.quantity; - totalGamma += greeks.gamma * position.quantity; - totalTheta += greeks.theta * position.quantity; - totalVega += greeks.vega * position.quantity; - totalRho += greeks.rho * position.quantity; - portfolioValue += optionPrice * position.quantity; - } - - return { - totalDelta, - totalGamma, - totalTheta, - totalVega, - totalRho, - portfolioValue, - }; -} - -/** - * Volatility surface interpolation - */ -export function interpolateVolatilitySurface( - strikes: number[], - expiries: number[], - volatilities: number[][], - targetStrike: number, - targetExpiry: number -): number { - // Simplified bilinear interpolation - // In production, use more sophisticated interpolation methods - - // Find surrounding points - let strikeIndex = 0; - let expiryIndex = 0; - - for (let i = 0; i < strikes.length - 1; i++) { - if (targetStrike >= strikes[i] && targetStrike <= strikes[i + 1]) { - strikeIndex = i; - break; - } - } - - for (let i = 0; i < expiries.length - 1; i++) { - if (targetExpiry >= expiries[i] && targetExpiry <= expiries[i + 1]) { - expiryIndex = i; - break; - } - } - - // Bilinear interpolation - const x1 = strikes[strikeIndex]; - const x2 = strikes[strikeIndex + 1]; - const y1 = expiries[expiryIndex]; - const y2 = expiries[expiryIndex + 1]; - - const q11 = volatilities[expiryIndex][strikeIndex]; - const q12 = volatilities[expiryIndex + 1][strikeIndex]; - const q21 = volatilities[expiryIndex][strikeIndex + 1]; - const q22 = volatilities[expiryIndex + 1][strikeIndex + 1]; - - const wx = (targetStrike - x1) / (x2 - x1); - const wy = (targetExpiry - y1) / (y2 - y1); - - return q11 * (1 - wx) * (1 - wy) + q21 * wx * (1 - wy) + q12 * (1 - wx) * wy + q22 * wx * wy; -} - -// Helper functions - -/** - * Normal cumulative distribution function - */ -function normalCDF(x: number): number { - return 0.5 * (1 + erf(x / Math.sqrt(2))); -} - -/** - * Normal probability density function - */ -function normalPDF(x: number): number { - return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI); -} - -/** - * Error function approximation - */ -function erf(x: number): number { - // Abramowitz and Stegun approximation - const a1 = 0.254829592; - const a2 = -0.284496736; - const a3 = 1.421413741; - const a4 = -1.453152027; - const a5 = 1.061405429; - const p = 0.3275911; - - const sign = x >= 0 ? 1 : -1; - x = Math.abs(x); - - const t = 1.0 / (1.0 + p * x); - const y = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x); - - return sign * y; -} - -/** - * Box-Muller transformation for normal random numbers - */ -function boxMullerTransform(): number { - let u1 = Math.random(); - const u2 = Math.random(); - - // Ensure u1 is not zero - while (u1 === 0) { - u1 = Math.random(); - } - - return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2); -} - -/** - * Prices a straddle option strategy - */ -export function straddle(params: OptionParameters): { - callPrice: number; - putPrice: number; - strategyCost: number; -} { - const callOption = blackScholes(params); - const putOption = blackScholes(params); - const strategyCost = callOption.callPrice + putOption.putPrice; - - return { - callPrice: callOption.callPrice, - putPrice: putOption.putPrice, - strategyCost: strategyCost, - }; -} - -/** - * Prices a strangle option strategy - */ -export function strangle( - callParams: OptionParameters, - putParams: OptionParameters -): { callPrice: number; putPrice: number; strategyCost: number } { - const callOption = blackScholes(callParams); - const putOption = blackScholes(putParams); - const strategyCost = callOption.callPrice + putOption.putPrice; - - return { - callPrice: callOption.callPrice, - putPrice: putOption.putPrice, - strategyCost: strategyCost, - }; -} - -/** - * Prices a butterfly option strategy - */ -export function butterfly( - lowerStrikeParams: OptionParameters, - middleStrikeParams: OptionParameters, - upperStrikeParams: OptionParameters -): { - lowerCallPrice: number; - middleCallPrice: number; - upperCallPrice: number; - strategyCost: number; -} { - const lowerCall = blackScholes(lowerStrikeParams); - const middleCall = blackScholes(middleStrikeParams); - const upperCall = blackScholes(upperStrikeParams); - - const strategyCost = lowerCall.callPrice - 2 * middleCall.callPrice + upperCall.callPrice; - - return { - lowerCallPrice: lowerCall.callPrice, - middleCallPrice: middleCall.callPrice, - upperCallPrice: upperCall.callPrice, - strategyCost: strategyCost, - }; -} - -/** - * Prices a condor option strategy - */ -export function condor( - lowerStrikeParams: OptionParameters, - middleLowerStrikeParams: OptionParameters, - middleUpperStrikeParams: OptionParameters, - upperStrikeParams: OptionParameters -): { - lowerCallPrice: number; - middleLowerCallPrice: number; - middleUpperCallPrice: number; - upperCallPrice: number; - strategyCost: number; -} { - const lowerCall = blackScholes(lowerStrikeParams); - const middleLowerCall = blackScholes(middleLowerStrikeParams); - const middleUpperCall = blackScholes(middleUpperStrikeParams); - const upperCall = blackScholes(upperStrikeParams); - - const strategyCost = - lowerCall.callPrice - - middleLowerCall.callPrice - - middleUpperCall.callPrice + - upperCall.callPrice; - - return { - lowerCallPrice: lowerCall.callPrice, - middleLowerCallPrice: middleLowerCall.callPrice, - middleUpperCallPrice: middleUpperCall.callPrice, - upperCallPrice: upperCall.callPrice, - strategyCost: strategyCost, - }; -} - -/** - * Calculates combined Greeks for an option strategy - */ -export function calculateStrategyGreeks( - positions: Array<{ - optionType: 'call' | 'put'; - quantity: number; - params: OptionParameters; - }> -): GreeksCalculation { - let totalDelta = 0; - let totalGamma = 0; - let totalTheta = 0; - let totalVega = 0; - let totalRho = 0; - - for (const position of positions) { - const greeks = calculateGreeks(position.params, position.optionType); - - totalDelta += greeks.delta * position.quantity; - totalGamma += greeks.gamma * position.quantity; - totalTheta += greeks.theta * position.quantity; - totalVega += greeks.vega * position.quantity; - totalRho += greeks.rho * position.quantity; - } - - return { - delta: totalDelta, - gamma: totalGamma, - theta: totalTheta, - vega: totalVega, - rho: totalRho, - }; -} - -/** - * Black-Scholes option pricing model with greeks - */ -export function blackScholesWithGreeks( - params: OptionParameters, - optionType: 'call' | 'put' = 'call' -): { pricing: OptionPricing; greeks: GreeksCalculation } { - const pricing = blackScholes(params); - const greeks = calculateGreeks(params, optionType); - return { pricing, greeks }; -} - -/** - * Calculates the breakeven point for a call option at expiration - */ -export function callBreakeven(strikePrice: number, callPrice: number): number { - return strikePrice + callPrice; -} - -/** - * Calculates the breakeven point for a put option at expiration - */ -export function putBreakeven(strikePrice: number, putPrice: number): number { - return strikePrice - putPrice; -} - -/** - * Estimates the probability of profit for a call option at expiration - */ -export function callProbabilityOfProfit( - spotPrice: number, - strikePrice: number, - timeToExpiry: number, - riskFreeRate: number, - volatility: number -): number { - const d1 = - (Math.log(spotPrice / strikePrice) + - (riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) / - (volatility * Math.sqrt(timeToExpiry)); - return normalCDF(d1); -} - -/** - * Estimates the probability of profit for a put option at expiration - */ -export function putProbabilityOfProfit( - spotPrice: number, - strikePrice: number, - timeToExpiry: number, - riskFreeRate: number, - volatility: number -): number { - const d1 = - (Math.log(spotPrice / strikePrice) + - (riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) / - (volatility * Math.sqrt(timeToExpiry)); - return 1 - normalCDF(d1); -} -``` diff --git a/libs/calculations/research/portfolio-analytics.md b/libs/calculations/research/portfolio-analytics.md deleted file mode 100644 index e19c1705..00000000 --- a/libs/calculations/research/portfolio-analytics.md +++ /dev/null @@ -1,604 +0,0 @@ -# portfolio-analytics research snapshot - -Source: `ccce401:libs/utils/src/calculations/portfolio-analytics.ts.disabled`. - -Contains equal-weight optimization baselines, zero factor estimates and incomplete attribution. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Portfolio Analytics - * Advanced portfolio analysis and optimization tools - */ - -import { OHLCVData, PriceData } from './index'; - -export interface PortfolioPosition { - symbol: string; - shares: number; - price: number; - value: number; - weight: number; -} - -export interface PortfolioAnalysis { - totalValue: number; - totalReturn: number; - volatility: number; - sharpeRatio: number; - maxDrawdown: number; - var95: number; - beta: number; - alpha: number; - treynorRatio: number; - informationRatio: number; - trackingError: number; -} - -export interface AssetAllocation { - symbol: string; - targetWeight: number; - currentWeight: number; - difference: number; - rebalanceAmount: number; -} - -export interface PortfolioOptimizationResult { - weights: number[]; - expectedReturn: number; - volatility: number; - sharpeRatio: number; - symbols: string[]; -} - -/** - * Calculate portfolio value and weights - */ -export function calculatePortfolioMetrics(positions: PortfolioPosition[]): { - totalValue: number; - weights: number[]; - concentrationRisk: number; -} { - const totalValue = positions.reduce((sum, pos) => sum + pos.value, 0); - const weights = positions.map(pos => pos.value / totalValue); - - // Calculate Herfindahl-Hirschman Index for concentration risk - const concentrationRisk = weights.reduce((sum, weight) => sum + weight * weight, 0); - - return { - totalValue, - weights, - concentrationRisk, - }; -} - -/** - * Calculate portfolio returns from position returns - */ -export function calculatePortfolioReturns(assetReturns: number[][], weights: number[]): number[] { - if (assetReturns.length === 0 || weights.length !== assetReturns[0].length) { - return []; - } - - const portfolioReturns: number[] = []; - - for (let i = 0; i < assetReturns.length; i++) { - let portfolioReturn = 0; - for (let j = 0; j < weights.length; j++) { - portfolioReturn += weights[j] * assetReturns[i][j]; - } - portfolioReturns.push(portfolioReturn); - } - - return portfolioReturns; -} - -/** - * Mean-Variance Optimization (Markowitz) - */ -export function markowitzOptimization( - expectedReturns: number[], - covarianceMatrix: number[][], - riskFreeRate: number = 0.02, - riskAversion: number = 1 -): PortfolioOptimizationResult { - const n = expectedReturns.length; - - // Simplified optimization using equal weights as baseline - // In production, use proper quadratic programming solver - const weights = new Array(n).fill(1 / n); - - const expectedReturn = weights.reduce((sum, weight, i) => sum + weight * expectedReturns[i], 0); - - // Calculate portfolio variance - let portfolioVariance = 0; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j]; - } - } - - const volatility = Math.sqrt(portfolioVariance); - const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0; - - return { - weights, - expectedReturn, - volatility, - sharpeRatio, - symbols: [], // Would be filled with actual symbols - }; -} - -/** - * Black-Litterman Model - */ -export function blackLittermanOptimization( - marketCaps: number[], - covarianceMatrix: number[][], - views: Array<{ assets: number[]; expectedReturn: number; confidence: number }>, - riskAversion: number = 3, - riskFreeRate: number = 0.02 -): PortfolioOptimizationResult { - const n = marketCaps.length; - - // Calculate market weights - const totalMarketCap = marketCaps.reduce((sum, cap) => sum + cap, 0); - const marketWeights = marketCaps.map(cap => cap / totalMarketCap); - - // Implied equilibrium returns - const equilibriumReturns: number[] = []; - for (let i = 0; i < n; i++) { - let equilibriumReturn = 0; - for (let j = 0; j < n; j++) { - equilibriumReturn += riskAversion * covarianceMatrix[i][j] * marketWeights[j]; - } - equilibriumReturns.push(equilibriumReturn); - } - - // Simplified BL implementation - in production use proper matrix operations - const weights = [...marketWeights]; // Start with market weights - - const expectedReturn = weights.reduce( - (sum, weight, i) => sum + weight * equilibriumReturns[i], - 0 - ); - - let portfolioVariance = 0; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j]; - } - } - - const volatility = Math.sqrt(portfolioVariance); - const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0; - - return { - weights, - expectedReturn, - volatility, - sharpeRatio, - symbols: [], - }; -} - -/** - * Risk Parity Portfolio - */ -export function riskParityOptimization(covarianceMatrix: number[][]): PortfolioOptimizationResult { - const n = covarianceMatrix.length; - - // Start with equal weights - let weights = new Array(n).fill(1 / n); - - // Iterative optimization for equal risk contribution - const maxIterations = 100; - const tolerance = 1e-8; - - for (let iter = 0; iter < maxIterations; iter++) { - const riskContributions = calculateRiskContributions(weights, covarianceMatrix); - const totalRisk = Math.sqrt(calculatePortfolioVariance(weights, covarianceMatrix)); - const targetRiskContribution = totalRisk / n; - - let converged = true; - const newWeights = [...weights]; - - for (let i = 0; i < n; i++) { - const diff = riskContributions[i] - targetRiskContribution; - if (Math.abs(diff) > tolerance) { - converged = false; - // Simple adjustment - in production use proper optimization - newWeights[i] *= 1 - (diff / totalRisk) * 0.1; - } - } - - // Normalize weights - const sum = newWeights.reduce((s, w) => s + w, 0); - weights = newWeights.map(w => w / sum); - - if (converged) { - break; - } - } - - const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix); - const volatility = Math.sqrt(portfolioVariance); - - return { - weights, - expectedReturn: 0, // Not calculated for risk parity - volatility, - sharpeRatio: 0, - symbols: [], - }; -} - -/** - * Calculate risk contributions for each asset - */ -export function calculateRiskContributions( - weights: number[], - covarianceMatrix: number[][] -): number[] { - const n = weights.length; - const riskContributions: number[] = []; - - const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix); - const portfolioVolatility = Math.sqrt(portfolioVariance); - - for (let i = 0; i < n; i++) { - let marginalContribution = 0; - for (let j = 0; j < n; j++) { - marginalContribution += weights[j] * covarianceMatrix[i][j]; - } - - const riskContribution = (weights[i] * marginalContribution) / portfolioVolatility; - riskContributions.push(riskContribution); - } - - return riskContributions; -} - -/** - * Calculate portfolio variance - */ -export function calculatePortfolioVariance( - weights: number[], - covarianceMatrix: number[][] -): number { - const n = weights.length; - let variance = 0; - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - variance += weights[i] * weights[j] * covarianceMatrix[i][j]; - } - } - - return variance; -} - -/** - * Portfolio rebalancing analysis - */ -export function calculateRebalancing( - currentPositions: PortfolioPosition[], - targetWeights: number[], - totalValue: number -): AssetAllocation[] { - if (currentPositions.length !== targetWeights.length) { - throw new Error('Number of positions must match number of target weights'); - } - - return currentPositions.map((position, index) => { - const currentWeight = position.value / totalValue; - const targetWeight = targetWeights[index]; - const difference = targetWeight - currentWeight; - const rebalanceAmount = difference * totalValue; - - return { - symbol: position.symbol, - targetWeight, - currentWeight, - difference, - rebalanceAmount, - }; - }); -} - -/** - * Factor model analysis (Fama-French) - */ -export function famaFrenchAnalysis( - portfolioReturns: number[], - marketReturns: number[], - smbReturns: number[], // Small minus Big - hmlReturns: number[], // High minus Low - riskFreeRate: number = 0.02 -): { - alpha: number; - marketBeta: number; - sizeBeta: number; - valueBeta: number; - rSquared: number; -} { - const n = portfolioReturns.length; - - // Excess returns - const excessPortfolioReturns = portfolioReturns.map(r => r - riskFreeRate); - const excessMarketReturns = marketReturns.map(r => r - riskFreeRate); - - // Simple linear regression (in production, use proper multiple regression) - const meanExcessPortfolio = excessPortfolioReturns.reduce((sum, r) => sum + r, 0) / n; - const meanExcessMarket = excessMarketReturns.reduce((sum, r) => sum + r, 0) / n; - const meanSMB = smbReturns.reduce((sum, r) => sum + r, 0) / n; - const meanHML = hmlReturns.reduce((sum, r) => sum + r, 0) / n; - - // Calculate market beta - let covariance = 0; - let marketVariance = 0; - - for (let i = 0; i < n; i++) { - const portfolioDiff = excessPortfolioReturns[i] - meanExcessPortfolio; - const marketDiff = excessMarketReturns[i] - meanExcessMarket; - - covariance += portfolioDiff * marketDiff; - marketVariance += marketDiff * marketDiff; - } - - const marketBeta = marketVariance > 0 ? covariance / marketVariance : 0; - const alpha = meanExcessPortfolio - marketBeta * meanExcessMarket; - - return { - alpha, - marketBeta, - sizeBeta: 0, // Simplified - would need proper regression - valueBeta: 0, // Simplified - would need proper regression - rSquared: 0, // Simplified - would need proper regression - }; -} - -/** - * Portfolio performance attribution - */ -export function performanceAttribution( - portfolioReturns: number[], - benchmarkReturns: number[], - sectorWeights: number[][], - sectorReturns: number[][] -): { - totalActiveReturn: number; - allocationEffect: number; - selectionEffect: number; - interactionEffect: number; -} { - const n = portfolioReturns.length; - - const portfolioReturn = portfolioReturns.reduce((sum, r) => sum + r, 0) / n; - const benchmarkReturn = benchmarkReturns.reduce((sum, r) => sum + r, 0) / n; - const totalActiveReturn = portfolioReturn - benchmarkReturn; - - // Simplified attribution analysis - let allocationEffect = 0; - let selectionEffect = 0; - let interactionEffect = 0; - - // This would require proper implementation with sector-level analysis - // For now, return the total active return distributed equally - allocationEffect = totalActiveReturn * 0.4; - selectionEffect = totalActiveReturn * 0.4; - interactionEffect = totalActiveReturn * 0.2; - - return { - totalActiveReturn, - allocationEffect, - selectionEffect, - interactionEffect, - }; -} - -/** - * Calculate Efficient Frontier points - */ -export function calculateEfficientFrontier( - returns: number[][], // Array of return series for each asset - symbols: string[], - riskFreeRate: number = 0.02, - numPoints: number = 50 -): Array<{ - weights: number[]; - expectedReturn: number; - volatility: number; - sharpeRatio: number; -}> { - if (returns.length !== symbols.length || returns.length < 2) { - return []; - } - - const n = returns.length; - const results: Array<{ - weights: number[]; - expectedReturn: number; - volatility: number; - sharpeRatio: number; - }> = []; - - // Calculate expected returns and covariance matrix - const expectedReturns = returns.map( - assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length - ); - - const covarianceMatrix = calculateCovarianceMatrix(returns); - - // Generate target returns from min to max expected return - const minReturn = Math.min(...expectedReturns); - const maxReturn = Math.max(...expectedReturns); - const returnStep = (maxReturn - minReturn) / (numPoints - 1); - - for (let i = 0; i < numPoints; i++) { - const targetReturn = minReturn + i * returnStep; - - // Find minimum variance portfolio for target return using quadratic programming (simplified) - const weights = findMinimumVarianceWeights(expectedReturns, covarianceMatrix, targetReturn); - - if (weights && weights.length === n) { - const portfolioReturn = weights.reduce((sum, w, j) => sum + w * expectedReturns[j], 0); - const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix); - const portfolioVolatility = Math.sqrt(portfolioVariance); - const sharpeRatio = - portfolioVolatility > 0 ? (portfolioReturn - riskFreeRate) / portfolioVolatility : 0; - - results.push({ - weights, - expectedReturn: portfolioReturn, - volatility: portfolioVolatility, - sharpeRatio, - }); - } - } - - return results.sort((a, b) => a.volatility - b.volatility); -} - -/** - * Find Minimum Variance Portfolio - */ -export function findMinimumVariancePortfolio( - returns: number[][], - symbols: string[] -): PortfolioOptimizationResult | null { - if (returns.length !== symbols.length || returns.length < 2) { - return null; - } - - const covarianceMatrix = calculateCovarianceMatrix(returns); - const n = returns.length; - - // For minimum variance portfolio: w = (ฮฃ^-1 * 1) / (1' * ฮฃ^-1 * 1) - // Simplified implementation using equal weights as starting point - const weights = new Array(n).fill(1 / n); - - // Iterative optimization (simplified) - for (let iter = 0; iter < 100; iter++) { - const gradient = calculateVarianceGradient(weights, covarianceMatrix); - const stepSize = 0.01; - - // Update weights - for (let i = 0; i < n; i++) { - weights[i] -= stepSize * gradient[i]; - } - - // Normalize weights to sum to 1 - const weightSum = weights.reduce((sum, w) => sum + w, 0); - for (let i = 0; i < n; i++) { - weights[i] = Math.max(0, weights[i] / weightSum); - } - } - - const expectedReturns = returns.map( - assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length - ); - - const portfolioReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0); - const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix); - const portfolioVolatility = Math.sqrt(portfolioVariance); - const sharpeRatio = portfolioVolatility > 0 ? portfolioReturn / portfolioVolatility : 0; - - return { - weights, - expectedReturn: portfolioReturn, - volatility: portfolioVolatility, - sharpeRatio, - symbols, - }; -} - -// Helper functions for portfolio optimization - -function calculateCovarianceMatrix(returns: number[][]): number[][] { - const n = returns.length; - const matrix: number[][] = []; - - for (let i = 0; i < n; i++) { - matrix[i] = []; - for (let j = 0; j < n; j++) { - matrix[i][j] = calculateCovariance(returns[i], returns[j]); - } - } - - return matrix; -} - -function calculateCovariance(x: number[], y: number[]): number { - if (x.length !== y.length || x.length < 2) { - return 0; - } - - const n = x.length; - const meanX = x.reduce((sum, val) => sum + val, 0) / n; - const meanY = y.reduce((sum, val) => sum + val, 0) / n; - - return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1); -} - -// calculatePortfolioVariance is already exported above - -function calculateVarianceGradient(weights: number[], covarianceMatrix: number[][]): number[] { - const n = weights.length; - const gradient: number[] = []; - - for (let i = 0; i < n; i++) { - let grad = 0; - for (let j = 0; j < n; j++) { - grad += 2 * weights[j] * covarianceMatrix[i][j]; - } - gradient[i] = grad; - } - - return gradient; -} - -function findMinimumVarianceWeights( - expectedReturns: number[], - covarianceMatrix: number[][], - targetReturn: number -): number[] | null { - const n = expectedReturns.length; - - // Simplified implementation - in practice would use quadratic programming solver - // Start with equal weights and adjust - const weights = new Array(n).fill(1 / n); - - // Iterative adjustment to meet target return constraint - for (let iter = 0; iter < 50; iter++) { - const currentReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0); - const returnDiff = targetReturn - currentReturn; - - if (Math.abs(returnDiff) < 0.001) { - break; - } - - // Adjust weights proportionally to expected returns - const totalExpectedReturn = expectedReturns.reduce((sum, r) => sum + Math.abs(r), 0); - - for (let i = 0; i < n; i++) { - const adjustment = (returnDiff * Math.abs(expectedReturns[i])) / totalExpectedReturn; - weights[i] = Math.max(0, weights[i] + adjustment * 0.1); - } - - // Normalize weights - const weightSum = weights.reduce((sum, w) => sum + w, 0); - if (weightSum > 0) { - for (let i = 0; i < n; i++) { - weights[i] /= weightSum; - } - } - } - - return weights; -} -``` diff --git a/libs/calculations/research/position-sizing-notes.md b/libs/calculations/research/position-sizing-notes.md deleted file mode 100644 index 587b0527..00000000 --- a/libs/calculations/research/position-sizing-notes.md +++ /dev/null @@ -1,109 +0,0 @@ -# Historical position-sizing notes - -Original: `ccce401:libs/utils/POSITION_SIZING_FIXES.md`. - -The following notes are retained as research context. Their claims of mathematical -correctness and production readiness were not independently established and are not -endorsements. The implementation remains in the non-executable position-sizing snapshot. -Use the package promotion checklist before adopting any formula or validation claim. - ---- - -# Position Sizing Calculations - Fixed Issues Summary - -## Issues Identified and Fixed: - -### 1. **Duplicate Kelly Function** โœ… FIXED -- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures -- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface - -### 2. **Incorrect Kelly Criterion Formula** โœ… FIXED -- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)` -- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio` -- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate - -### 3. **Missing Input Validation** โœ… FIXED -- **Problem**: Functions didn't validate inputs (zero/negative values) -- **Solution**: Added comprehensive input validation to all functions -- **Examples**: - - Check for `accountSize <= 0`, `riskPercentage <= 0` - - Validate `winRate` is between 0 and 1 - - Ensure prices and volatilities are positive - -### 4. **ATR Position Sizing Units Error** โœ… FIXED -- **Problem**: Function returned risk amount instead of shares -- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares) - -### 5. **Flawed Monte Carlo Simulation** โœ… FIXED -- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns -- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio - -### 6. **Redundant Liquidity Calculations** โœ… FIXED -- **Problem**: Unnecessary conversions between shares and dollar values -- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares` - -### 7. **Risk Parity Not Using Target Risk** โœ… FIXED -- **Problem**: `targetRisk` parameter was ignored in calculations -- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)` - -### 8. **Missing Safety Constraints** โœ… FIXED -- **Problem**: No caps on leverage or volatility ratios -- **Solution**: Added reasonable caps: - - Volatility targeting: max 2x leverage - - Volatility adjustment: max 3x leverage - - Kelly fraction: max 25% with safety factor - -### 9. **Correlation Risk Calculation Error** โœ… FIXED -- **Problem**: Correlation risk calculation didn't consider relative position sizes -- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment - -### 10. **Integer Share Handling** โœ… FIXED -- **Problem**: Functions returned fractional shares -- **Solution**: Added `Math.floor()` to return whole shares where appropriate - -## Mathematical Validation Examples: - -### Fixed Risk Position Sizing: -``` -Account: $100,000, Risk: 2%, Entry: $100, Stop: $95 -Risk Amount: $100,000 ร— 0.02 = $2,000 -Risk Per Share: |$100 - $95| = $5 -Position Size: $2,000 รท $5 = 400 shares โœ… -``` - -### Kelly Criterion (Corrected): -``` -Win Rate: 60%, Avg Win: $150, Avg Loss: $100 -Win/Loss Ratio: $150 รท $100 = 1.5 -Kelly Fraction: (1.5 ร— 0.6 - 0.4) รท 1.5 = 0.333 -With Safety Factor (25%): 0.333 ร— 0.25 = 0.083 -Position: $100,000 ร— 0.083 = $8,333 โœ… -``` - -### Volatility Targeting: -``` -Price: $100, Asset Vol: 20%, Target Vol: 10% -Volatility Ratio: 10% รท 20% = 0.5 -Position Value: $100,000 ร— 0.5 = $50,000 -Position Size: $50,000 รท $100 = 500 shares โœ… -``` - -## Edge Cases Now Handled: -- โœ… Zero or negative account sizes -- โœ… Equal entry and stop loss prices -- โœ… Zero volatility assets -- โœ… Negative expectancy strategies -- โœ… Extreme correlation values -- โœ… Division by zero scenarios -- โœ… Invalid win rates (โ‰ค0 or โ‰ฅ1) - -## Additional Improvements: -- โœ… Consistent return types (whole shares vs. dollar amounts) -- โœ… Proper TypeScript interfaces for all parameters -- โœ… Comprehensive JSDoc documentation -- โœ… Mathematical formulas verified against financial literature -- โœ… Safety factors to prevent over-leveraging -- โœ… Portfolio-level risk management functions - -All position sizing calculations are now mathematically correct, properly validated, and production-ready! - diff --git a/libs/calculations/research/position-sizing.md b/libs/calculations/research/position-sizing.md deleted file mode 100644 index 344461b4..00000000 --- a/libs/calculations/research/position-sizing.md +++ /dev/null @@ -1,593 +0,0 @@ -# position-sizing research snapshot - -Source: `ccce401:libs/utils/src/calculations/position-sizing.ts.disabled`. - -Contains unseeded Monte Carlo search and unqualified production-ready claims in its old notes. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Position Sizing Calculations - * Risk-based position sizing methods for trading strategies - */ - -export interface PositionSizeParams { - accountSize: number; - riskPercentage: number; - entryPrice: number; - stopLoss: number; - leverage?: number; -} - -export interface KellyParams { - winRate: number; - averageWin: number; - averageLoss: number; -} - -export interface VolatilityParams { - price: number; - volatility: number; - targetVolatility: number; - lookbackDays: number; -} - -/** - * Calculate position size based on fixed risk percentage - */ -export function fixedRiskPositionSize(params: PositionSizeParams): number { - const { accountSize, riskPercentage, entryPrice, stopLoss, leverage = 1 } = params; - - // Input validation - if (accountSize <= 0 || riskPercentage <= 0 || entryPrice <= 0 || leverage <= 0) { - return 0; - } - if (entryPrice === stopLoss) { - return 0; - } - - const riskAmount = accountSize * (riskPercentage / 100); - const riskPerShare = Math.abs(entryPrice - stopLoss); - const basePositionSize = riskAmount / riskPerShare; - - return Math.floor(basePositionSize * leverage); -} - -/** - * Calculate position size using Kelly Criterion - */ -export function kellyPositionSize(params: KellyParams, accountSize: number): number { - const { winRate, averageWin, averageLoss } = params; - - // Validate inputs - if (averageLoss === 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0) { - return 0; - } - - const lossRate = 1 - winRate; - const winLossRatio = averageWin / Math.abs(averageLoss); - - // Correct Kelly formula: f = (bp - q) / b - // where: b = win/loss ratio, p = win rate, q = loss rate - const kellyFraction = (winRate * winLossRatio - lossRate) / winLossRatio; - - // Cap Kelly fraction to prevent over-leveraging (max 25% of Kelly recommendation) - const cappedKelly = Math.max(0, Math.min(kellyFraction * 0.25, 0.25)); - - return accountSize * cappedKelly; -} - -/** - * Calculate fractional Kelly position size (more conservative) - */ -export function fractionalKellyPositionSize( - params: KellyParams, - accountSize: number, - fraction: number = 0.25 -): number { - // Input validation - if (fraction <= 0 || fraction > 1) { - return 0; - } - - const fullKelly = kellyPositionSize(params, accountSize); - return fullKelly * fraction; -} - -/** - * Calculate position size based on volatility targeting - */ -export function volatilityTargetPositionSize( - params: VolatilityParams, - accountSize: number -): number { - const { price, volatility, targetVolatility } = params; - - // Input validation - if (volatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) { - return 0; - } - - const volatilityRatio = targetVolatility / volatility; - const basePositionValue = accountSize * Math.min(volatilityRatio, 2); // Cap at 2x leverage - - return Math.floor(basePositionValue / price); -} - -/** - * Calculate equal weight position size - */ -export function equalWeightPositionSize( - accountSize: number, - numberOfPositions: number, - price: number -): number { - // Input validation - if (numberOfPositions <= 0 || price <= 0 || accountSize <= 0) { - return 0; - } - - const positionValue = accountSize / numberOfPositions; - return Math.floor(positionValue / price); -} - -/** - * Calculate position size based on Average True Range (ATR) - */ -export function atrBasedPositionSize( - accountSize: number, - riskPercentage: number, - atrValue: number, - atrMultiplier: number = 2, - price: number -): number { - if (atrValue === 0 || price === 0) { - return 0; - } - - const riskAmount = accountSize * (riskPercentage / 100); - const stopDistance = atrValue * atrMultiplier; - const positionSize = riskAmount / stopDistance; - - // Return position size in shares, not dollars - return Math.floor(positionSize); -} - -/** - * Calculate position size using Van Tharp's expectancy - */ -export function expectancyPositionSize( - accountSize: number, - winRate: number, - averageWin: number, - averageLoss: number, - maxRiskPercentage: number = 2 -): number { - // Input validation - if (accountSize <= 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0 || averageLoss === 0) { - return 0; - } - - const expectancy = winRate * averageWin - (1 - winRate) * Math.abs(averageLoss); - - if (expectancy <= 0) { - return 0; - } - - // Scale position size based on expectancy relative to average loss - // Higher expectancy relative to risk allows for larger position - const expectancyRatio = expectancy / Math.abs(averageLoss); - const riskPercentage = Math.min(expectancyRatio * 0.5, maxRiskPercentage); - - const positionValue = accountSize * (riskPercentage / 100); - return positionValue; -} - -/** - * Calculate optimal position size using Monte Carlo simulation - */ -export function monteCarloPositionSize( - accountSize: number, - historicalReturns: number[], - simulations: number = 1000, - confidenceLevel: number = 0.95 -): number { - if (historicalReturns.length === 0) { - return 0; - } - - const outcomes: number[] = []; - const mean = historicalReturns.reduce((sum, ret) => sum + ret, 0) / historicalReturns.length; - const variance = - historicalReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / - historicalReturns.length; - const stdDev = Math.sqrt(variance); - - // Test different position sizes (as fraction of account) - const testFractions = [0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25]; - let optimalFraction = 0; - let bestSharpe = -Infinity; - - for (const fraction of testFractions) { - const simOutcomes: number[] = []; - - for (let i = 0; i < simulations; i++) { - let portfolioValue = accountSize; - - // Simulate trades over a period - for (let j = 0; j < 50; j++) { - // 50 trades - const randomReturn = - historicalReturns[Math.floor(Math.random() * historicalReturns.length)]; - const positionReturn = randomReturn * fraction; - portfolioValue = portfolioValue * (1 + positionReturn); - } - - simOutcomes.push(portfolioValue); - } - - // Calculate Sharpe ratio for this fraction - const avgOutcome = simOutcomes.reduce((sum, val) => sum + val, 0) / simOutcomes.length; - const returns = simOutcomes.map(val => (val - accountSize) / accountSize); - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const returnStdDev = Math.sqrt( - returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / returns.length - ); - - const sharpe = returnStdDev > 0 ? avgReturn / returnStdDev : -Infinity; - - if (sharpe > bestSharpe) { - bestSharpe = sharpe; - optimalFraction = fraction; - } - } - - return accountSize * optimalFraction; -} - -/** - * Calculate position size based on Sharpe ratio optimization - */ -export function sharpeOptimizedPositionSize( - accountSize: number, - expectedReturn: number, - volatility: number, - riskFreeRate: number = 0.02, - maxLeverage: number = 3 -): number { - // Input validation - if (volatility <= 0 || accountSize <= 0 || expectedReturn <= riskFreeRate || maxLeverage <= 0) { - return 0; - } - // Kelly criterion with Sharpe ratio optimization - const excessReturn = expectedReturn - riskFreeRate; - const kellyFraction = excessReturn / (volatility * volatility); - - // Apply maximum leverage constraint - const constrainedFraction = Math.max(0, Math.min(kellyFraction, maxLeverage)); - - return accountSize * constrainedFraction; -} - -/** - * Fixed fractional position sizing - */ -export function fixedFractionalPositionSize( - accountSize: number, - riskPercentage: number, - stopLossPercentage: number, - price: number -): number { - // Input validation - if (stopLossPercentage <= 0 || price <= 0 || riskPercentage <= 0 || accountSize <= 0) { - return 0; - } - - const riskAmount = accountSize * (riskPercentage / 100); - const stopLossAmount = price * (stopLossPercentage / 100); - - return Math.floor(riskAmount / stopLossAmount); -} - -/** - * Volatility-adjusted position sizing - */ -export function volatilityAdjustedPositionSize( - accountSize: number, - targetVolatility: number, - assetVolatility: number, - price: number -): number { - // Input validation - if (assetVolatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) { - return 0; - } - - const volatilityRatio = targetVolatility / assetVolatility; - const cappedRatio = Math.min(volatilityRatio, 3); // Cap at 3x leverage - const positionValue = accountSize * cappedRatio; - - return Math.floor(positionValue / price); -} - -/** - * Calculate position size with correlation adjustment - */ -export function correlationAdjustedPositionSize( - basePositionSize: number, - existingPositions: Array<{ size: number; correlation: number }>, - maxCorrelationRisk: number = 0.3 -): number { - if (existingPositions.length === 0 || basePositionSize <= 0) { - return basePositionSize; - } - - // Calculate portfolio correlation risk - // This should consider the correlation between the new position and existing ones - const totalCorrelationRisk = existingPositions.reduce((total, position) => { - // Weight correlation by position size relative to new position - const relativeSize = position.size / (basePositionSize + position.size); - return total + relativeSize * Math.abs(position.correlation); - }, 0); - - // Adjust position size based on correlation risk - const correlationAdjustment = Math.max(0.1, 1 - totalCorrelationRisk / maxCorrelationRisk); - - return Math.floor(basePositionSize * correlationAdjustment); -} - -/** - * Calculate portfolio heat (total risk across all positions) - */ -export function calculatePortfolioHeat( - positions: Array<{ value: number; risk: number }>, - accountSize: number -): number { - // Input validation - if (accountSize <= 0 || positions.length === 0) { - return 0; - } - - const totalRisk = positions.reduce((sum, position) => { - // Ensure risk values are positive - return sum + Math.max(0, position.risk); - }, 0); - - return Math.min((totalRisk / accountSize) * 100, 100); // Cap at 100% -} - -/** - * Dynamic position sizing based on market conditions - */ -export function dynamicPositionSize( - basePositionSize: number, - marketVolatility: number, - normalVolatility: number, - drawdownLevel: number, - maxDrawdownThreshold: number = 0.1 -): number { - // Input validation - if (basePositionSize <= 0 || marketVolatility <= 0 || normalVolatility <= 0) { - return 0; - } - if (drawdownLevel < 0 || maxDrawdownThreshold <= 0) { - return basePositionSize; - } - - // Volatility adjustment - reduce size when volatility is high - const volatilityAdjustment = Math.min(normalVolatility / marketVolatility, 2); // Cap at 2x - - // Drawdown adjustment - reduce size as drawdown increases - const normalizedDrawdown = Math.min(drawdownLevel / maxDrawdownThreshold, 1); - const drawdownAdjustment = Math.max(0.1, 1 - normalizedDrawdown); - - const adjustedSize = basePositionSize * volatilityAdjustment * drawdownAdjustment; - return Math.floor(Math.max(0, adjustedSize)); -} - -/** - * Calculate maximum position size based on liquidity - */ -export function liquidityConstrainedPositionSize( - desiredPositionSize: number, - averageDailyVolume: number, - maxVolumePercentage: number = 0.05, - price: number -): number { - if (averageDailyVolume === 0 || price === 0) { - return 0; - } - - const maxShares = averageDailyVolume * maxVolumePercentage; - - return Math.min(desiredPositionSize, maxShares); -} - -/** - * Multi-timeframe position sizing - */ -export function multiTimeframePositionSize( - accountSize: number, - shortTermSignal: number, // -1 to 1 - mediumTermSignal: number, // -1 to 1 - longTermSignal: number, // -1 to 1 - baseRiskPercentage: number = 1 -): number { - // Input validation - if (accountSize <= 0 || baseRiskPercentage <= 0) { - return 0; - } - - // Clamp signals to valid range - const clampedShort = Math.max(-1, Math.min(1, shortTermSignal)); - const clampedMedium = Math.max(-1, Math.min(1, mediumTermSignal)); - const clampedLong = Math.max(-1, Math.min(1, longTermSignal)); - - // Weight the signals (long-term gets higher weight) - const weightedSignal = clampedShort * 0.2 + clampedMedium * 0.3 + clampedLong * 0.5; - - // Adjust risk based on signal strength - const adjustedRisk = baseRiskPercentage * Math.abs(weightedSignal); - - return accountSize * (adjustedRisk / 100); -} - -/** - * Risk parity position sizing - */ -export function riskParityPositionSize( - assets: Array<{ volatility: number; price: number }>, - targetRisk: number, - accountSize: number -): number[] { - if (assets.length === 0) { - return []; - } - - // Calculate inverse volatility weights - const totalInverseVol = assets.reduce((sum, asset) => { - if (asset.volatility === 0) { - return sum; - } - return sum + 1 / asset.volatility; - }, 0); - - if (totalInverseVol === 0) { - return assets.map(() => 0); - } - - return assets.map(asset => { - if (asset.volatility === 0 || asset.price === 0) { - return 0; - } - // Calculate weight based on inverse volatility - const weight = 1 / asset.volatility / totalInverseVol; - - // The weight itself already accounts for risk parity - // We just need to scale by target risk once - const positionValue = accountSize * weight * targetRisk; - return Math.floor(positionValue / asset.price); - }); -} - -/** - * Validate position size against risk limits - */ -export function validatePositionSize( - positionSize: number, - price: number, - accountSize: number, - maxPositionPercentage: number = 10, - maxLeverage: number = 1 -): { isValid: boolean; adjustedSize: number; violations: string[] } { - const violations: string[] = []; - let adjustedSize = positionSize; - - // Check maximum position percentage - const positionValue = positionSize * price; - const positionPercentage = (positionValue / accountSize) * 100; - - if (positionPercentage > maxPositionPercentage) { - violations.push(`Position exceeds maximum ${maxPositionPercentage}% of account`); - adjustedSize = (accountSize * maxPositionPercentage) / 100 / price; - } - - // Check leverage limits - const leverage = positionValue / accountSize; - if (leverage > maxLeverage) { - violations.push(`Position exceeds maximum leverage of ${maxLeverage}x`); - adjustedSize = Math.min(adjustedSize, (accountSize * maxLeverage) / price); - } - - // Check minimum position size - if (adjustedSize < 1 && adjustedSize > 0) { - violations.push('Position size too small (less than 1 share)'); - adjustedSize = 0; - } - - return { - isValid: violations.length === 0, - adjustedSize: Math.max(0, adjustedSize), - violations, - }; -} - -/** - * Optimal F position sizing (Ralph Vince's method) - */ -export function optimalFPositionSize( - accountSize: number, - historicalReturns: number[], - maxIterations: number = 100 -): number { - if (historicalReturns.length === 0 || accountSize <= 0) { - return 0; - } - - // Convert returns to P&L per unit - const pnlValues = historicalReturns.map(ret => ret * 1000); // Assuming $1000 per unit - - let bestF = 0; - let bestTWR = 0; // Terminal Wealth Relative - - // Test different f values (0.01 to 1.00) - for (let f = 0.01; f <= 1.0; f += 0.01) { - let twr = 1.0; - let valid = true; - - for (const pnl of pnlValues) { - const hpr = 1 + (f * pnl) / 1000; // Holding Period Return - - if (hpr <= 0) { - valid = false; - break; - } - - twr *= hpr; - } - - if (valid && twr > bestTWR) { - bestTWR = twr; - bestF = f; - } - } - - // Apply safety factor - const safeF = bestF * 0.75; // 75% of optimal f for safety - - return accountSize * safeF; -} - -/** - * Secure F position sizing (safer version of Optimal F) - */ -export function secureFPositionSize( - accountSize: number, - historicalReturns: number[], - confidenceLevel: number = 0.95 -): number { - if (historicalReturns.length === 0 || accountSize <= 0) { - return 0; - } - - // Sort returns to find worst-case scenarios - const sortedReturns = [...historicalReturns].sort((a, b) => a - b); - const worstCaseIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length); - const worstCaseReturn = sortedReturns[worstCaseIndex]; - - // Calculate maximum position size that won't bankrupt at confidence level - const maxLoss = Math.abs(worstCaseReturn); - const maxRiskPercentage = 0.02; // Never risk more than 2% on worst case - - if (maxLoss === 0) { - return accountSize * 0.1; - } // Default to 10% if no historical losses - - const secureF = Math.min(maxRiskPercentage / maxLoss, 0.25); // Cap at 25% - - return accountSize * secureF; -} -``` diff --git a/libs/calculations/research/technical-indicators.md b/libs/calculations/research/technical-indicators.md deleted file mode 100644 index f4a7a39c..00000000 --- a/libs/calculations/research/technical-indicators.md +++ /dev/null @@ -1,2520 +0,0 @@ -# technical-indicators research snapshot - -Source: `ccce401:libs/utils/src/calculations/technical-indicators.ts.disabled`. - -Contains additional indicator prototypes as well as duplicate indicators and a placeholder Hilbert transform. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Technical Indicators - * Comprehensive set of technical analysis indicators - */ - -import type { OHLCV, HasOHLC } from '@stock-bot/types'; - -/** - * Simple Moving Average - */ -export function sma(values: number[], period: number): number[] { - if (period > values.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < values.length; i++) { - const sum = values.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - result.push(sum / period); - } - - return result; -} - -/** - * Exponential Moving Average - */ -export function ema(values: number[], period: number): number[] { - if (period > values.length) { - return []; - } - - const result: number[] = []; - const multiplier = 2 / (period + 1); - - // Start with SMA for first value - let ema = values.slice(0, period).reduce((a, b) => a + b, 0) / period; - result.push(ema); - - for (let i = period; i < values.length; i++) { - const value = values[i]; - if (value !== undefined) { - ema = value * multiplier + ema * (1 - multiplier); - result.push(ema); - } - } - - return result; -} - -/** - * Relative Strength Index (RSI) - */ -export function rsi(prices: number[], period: number = 14): number[] { - if (period >= prices.length) { - return []; - } - - const gains: number[] = []; - const losses: number[] = []; - - // Calculate gains and losses - for (let i = 1; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - 1]; - if (current !== undefined && previous !== undefined) { - const change = current - previous; - gains.push(change > 0 ? change : 0); - losses.push(change < 0 ? Math.abs(change) : 0); - } - } - - const result: number[] = []; - - // Calculate RSI - for (let i = period - 1; i < gains.length; i++) { - const avgGain = gains.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0) / period; - const avgLoss = losses.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0) / period; - - if (avgLoss === 0) { - result.push(100); - } else { - const rs = avgGain / avgLoss; - const rsiValue = 100 - 100 / (1 + rs); - result.push(rsiValue); - } - } - - return result; -} - -/** - * Moving Average Convergence Divergence (MACD) - */ -export function macd( - prices: number[], - fastPeriod: number = 12, - slowPeriod: number = 26, - signalPeriod: number = 9 -): { macd: number[]; signal: number[]; histogram: number[] } { - const fastEMA = ema(prices, fastPeriod); - const slowEMA = ema(prices, slowPeriod); - - const macdLine: number[] = []; - const startIndex = slowPeriod - fastPeriod; - - for (let i = 0; i < fastEMA.length - startIndex; i++) { - const fastValue = fastEMA[i + startIndex]; - const slowValue = slowEMA[i]; - if (fastValue !== undefined && slowValue !== undefined) { - macdLine.push(fastValue - slowValue); - } - } - - const signalLine = ema(macdLine, signalPeriod); - const histogram: number[] = []; - - const signalStartIndex = signalPeriod - 1; - for (let i = 0; i < signalLine.length; i++) { - const macdValue = macdLine[i + signalStartIndex]; - const signalValue = signalLine[i]; - if (macdValue !== undefined && signalValue !== undefined) { - histogram.push(macdValue - signalValue); - } - } - - return { - macd: macdLine, - signal: signalLine, - histogram: histogram, - }; -} - -/** - * Bollinger Bands - */ -export function bollingerBands( - prices: number[], - period: number = 20, - standardDeviations: number = 2 -): { upper: number[]; middle: number[]; lower: number[] } { - const middle = sma(prices, period); - const upper: number[] = []; - const lower: number[] = []; - - for (let i = period - 1; i < prices.length; i++) { - const slice = prices.slice(i - period + 1, i + 1); - const mean = slice.reduce((a, b) => a + b, 0) / period; - const variance = slice.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / period; - const stdDev = Math.sqrt(variance); - - const middleValue = middle[i - period + 1]; - if (middleValue !== undefined) { - upper.push(middleValue + standardDeviations * stdDev); - lower.push(middleValue - standardDeviations * stdDev); - } - } - - return { upper, middle, lower }; -} - -/** - * Average True Range (ATR) - */ -export function atr(ohlcv: OHLCV[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const trueRanges: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]; - const previous = ohlcv[i - 1]; - if (current && previous) { - const high = current.high; - const low = current.low; - const prevClose = previous.close; - - const tr = Math.max(high - low, Math.abs(high - prevClose), Math.abs(low - prevClose)); - trueRanges.push(tr); - } - } - - return sma(trueRanges, period); -} - -/** - * Stochastic Oscillator - */ -export function stochastic( - ohlcv: OHLCV[], - kPeriod: number = 14, - dPeriod: number = 3 -): { k: number[]; d: number[] } { - if (kPeriod >= ohlcv.length) { - return { k: [], d: [] }; - } - - const kValues: number[] = []; - - for (let i = kPeriod - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - kPeriod + 1, i + 1); - const highest = Math.max(...slice.map(d => d.high)); - const lowest = Math.min(...slice.map(d => d.low)); - const current = ohlcv[i]; - if (!current) continue; - const currentClose = current.close; - - if (highest === lowest) { - kValues.push(50); // Avoid division by zero - } else { - const kValue = ((currentClose - lowest) / (highest - lowest)) * 100; - kValues.push(kValue); - } - } - - const dValues = sma(kValues, dPeriod); - - return { k: kValues, d: dValues }; -} - -/** - * Williams %R - */ -export function williamsR(ohlcv: T[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highest = Math.max(...slice.map(d => d.high)); - const lowest = Math.min(...slice.map(d => d.low)); - const currentBar = ohlcv[i]; - if (!currentBar) continue; - const currentClose = currentBar.close; - - if (highest === lowest) { - result.push(-50); // Avoid division by zero - } else { - const wrValue = ((highest - currentClose) / (highest - lowest)) * -100; - result.push(wrValue); - } - } - - return result; -} - -/** - * Commodity Channel Index (CCI) - */ -export function cci(ohlcv: T[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const typicalPrices = ohlcv.map(d => (d.high + d.low + d.close) / 3); - const smaTP = sma(typicalPrices, period); - const result: number[] = []; - - for (let i = 0; i < smaTP.length; i++) { - const slice = typicalPrices.slice(i, i + period); - const mean = smaTP[i]; - if (mean === undefined) continue; - const meanDeviation = slice.reduce((sum, value) => sum + Math.abs(value - mean), 0) / period; - const typicalPrice = typicalPrices[i + period - 1]; - if (typicalPrice === undefined) continue; - - if (meanDeviation === 0) { - result.push(0); - } else { - const cciValue = (typicalPrice - mean) / (0.015 * meanDeviation); - result.push(cciValue); - } - } - - return result; -} - -/** - * Momentum - */ -export function momentum(prices: number[], period: number = 10): number[] { - if (period >= prices.length) { - return []; - } - - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - period]; - if (current !== undefined && previous !== undefined) { - const momentum = current - previous; - result.push(momentum); - } - } - - return result; -} - -/** - * Rate of Change (ROC) - */ -export function roc(prices: number[], period: number = 10): number[] { - if (period >= prices.length) { - return []; - } - - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - period]; - if (current !== undefined && previous !== undefined) { - if (previous === 0) { - result.push(0); - } else { - const rocValue = ((current - previous) / previous) * 100; - result.push(rocValue); - } - } - } - - return result; -} - -/** - * Money Flow Index (MFI) - */ -export function mfi(ohlcv: OHLCV[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const typicalPrices = ohlcv.map(d => (d.high + d.low + d.close) / 3); - const moneyFlows = ohlcv.map((d, i) => typicalPrices[i] * d.volume); - - const result: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let positiveFlow = 0; - let negativeFlow = 0; - - for (let j = i - period + 1; j <= i; j++) { - if (j > 0) { - const currentTP = typicalPrices[j]; - const prevTP = typicalPrices[j - 1]; - const currentMF = moneyFlows[j]; - if (currentTP !== undefined && prevTP !== undefined && currentMF !== undefined) { - if (currentTP > prevTP) { - positiveFlow += currentMF; - } else if (currentTP < prevTP) { - negativeFlow += currentMF; - } - } - } - } - - if (negativeFlow === 0) { - result.push(100); - } else { - const mfiRatio = positiveFlow / negativeFlow; - const mfiValue = 100 - 100 / (1 + mfiRatio); - result.push(mfiValue); - } - } - - return result; -} - -/** - * On-Balance Volume (OBV) - */ -export function obv(ohlcv: OHLCV[]): number[] { - if (ohlcv.length === 0) { - return []; - } - - const first = ohlcv[0]; - if (!first) return []; - const result: number[] = [first.volume]; - - for (let i = 1; i < ohlcv.length; i++) { - const prev = ohlcv[i - 1]; - const curr = ohlcv[i]; - if (!prev || !curr) continue; - - const lastValue = result[result.length - 1]; - if (lastValue === undefined) continue; - - if (curr.close > prev.close) { - result.push(lastValue + curr.volume); - } else if (curr.close < prev.close) { - result.push(lastValue - curr.volume); - } else { - result.push(lastValue); - } - } - - return result; -} - -/** - * Accumulation/Distribution Line - */ -export function accumulationDistribution(ohlcv: OHLCV[]): number[] { - if (ohlcv.length === 0) { - return []; - } - - const result: number[] = []; - let adLine = 0; - - for (const candle of ohlcv) { - if (candle.high === candle.low) { - // Avoid division by zero - result.push(adLine); - continue; - } - - const moneyFlowMultiplier = - (candle.close - candle.low - (candle.high - candle.close)) / (candle.high - candle.low); - const moneyFlowVolume = moneyFlowMultiplier * candle.volume; - adLine += moneyFlowVolume; - result.push(adLine); - } - - return result; -} - -/** - * Chaikin Money Flow (CMF) - */ -export function chaikinMoneyFlow(ohlcv: OHLCV[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const adValues: number[] = []; - - for (const candle of ohlcv) { - if (candle.high === candle.low) { - adValues.push(0); - } else { - const moneyFlowMultiplier = - (candle.close - candle.low - (candle.high - candle.close)) / (candle.high - candle.low); - const moneyFlowVolume = moneyFlowMultiplier * candle.volume; - adValues.push(moneyFlowVolume); - } - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const sumAD = adValues.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - const sumVolume = ohlcv.slice(i - period + 1, i + 1).reduce((a, b) => a + b.volume, 0); - - if (sumVolume === 0) { - result.push(0); - } else { - result.push(sumAD / sumVolume); - } - } - - return result; -} - -/** - * Parabolic SAR - */ -export function parabolicSAR( - ohlcv: OHLCV[], - step: number = 0.02, - maxStep: number = 0.2 -): number[] { - if (ohlcv.length < 2) { - return []; - } - - const first = ohlcv[0]; - if (!first) return []; - - const result: number[] = []; - let trend = 1; // 1 for uptrend, -1 for downtrend - let acceleration = step; - let extremePoint = first.high; - let sar = first.low; - - result.push(sar); - - for (let i = 1; i < ohlcv.length; i++) { - const curr = ohlcv[i]; - const prev = ohlcv[i - 1]; - if (!curr || !prev) continue; - - // Calculate new SAR - sar = sar + acceleration * (extremePoint - sar); - - if (trend === 1) { - // Uptrend - if (curr.low <= sar) { - // Trend reversal - trend = -1; - sar = extremePoint; - extremePoint = curr.low; - acceleration = step; - } else { - if (curr.high > extremePoint) { - extremePoint = curr.high; - acceleration = Math.min(acceleration + step, maxStep); - } - // Ensure SAR doesn't exceed previous lows - const prevPrev = i > 1 ? ohlcv[i - 2] : null; - sar = Math.min(sar, prev.low, prevPrev ? prevPrev.low : prev.low); - } - } else { - // Downtrend - if (curr.high >= sar) { - // Trend reversal - trend = 1; - sar = extremePoint; - extremePoint = curr.high; - acceleration = step; - } else { - if (curr.low < extremePoint) { - extremePoint = curr.low; - acceleration = Math.min(acceleration + step, maxStep); - } - // Ensure SAR doesn't exceed previous highs - const prevPrev = i > 1 ? ohlcv[i - 2] : null; - sar = Math.max(sar, prev.high, prevPrev ? prevPrev.high : prev.high); - } - } - - result.push(sar); - } - - return result; -} - -/** - * Aroon Indicator - */ -export function aroon(ohlcv: OHLCV[], period: number = 14): { up: number[]; down: number[] } { - if (period >= ohlcv.length) { - return { up: [], down: [] }; - } - - const up: number[] = []; - const down: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - - // Find highest high and lowest low positions - let highestIndex = 0; - let lowestIndex = 0; - - for (let j = 1; j < slice.length; j++) { - const current = slice[j]; - const highest = slice[highestIndex]; - const lowest = slice[lowestIndex]; - if (current && highest && lowest) { - if (current.high > highest.high) { - highestIndex = j; - } - if (current.low < lowest.low) { - lowestIndex = j; - } - } - } - - const aroonUp = ((period - 1 - highestIndex) / (period - 1)) * 100; - const aroonDown = ((period - 1 - lowestIndex) / (period - 1)) * 100; - - up.push(aroonUp); - down.push(aroonDown); - } - - return { up, down }; -} - -/** - * Average Directional Movement Index (ADX) and Directional Movement Indicators (DMI) - */ -export function adx( - ohlcv: OHLCV[], - period: number = 14 -): { adx: number[]; plusDI: number[]; minusDI: number[] } { - if (period >= ohlcv.length) { - return { adx: [], plusDI: [], minusDI: [] }; - } - - const trueRanges: number[] = []; - const plusDM: number[] = []; - const minusDM: number[] = []; - - // Calculate True Range and Directional Movements - for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]; - const previous = ohlcv[i - 1]; - if (!current || !previous) continue; - - // True Range - const tr = Math.max( - current.high - current.low, - Math.abs(current.high - previous.close), - Math.abs(current.low - previous.close) - ); - trueRanges.push(tr); - - // Directional Movements - const highDiff = current.high - previous.high; - const lowDiff = previous.low - current.low; - - const plusDMValue = highDiff > lowDiff && highDiff > 0 ? highDiff : 0; - const minusDMValue = lowDiff > highDiff && lowDiff > 0 ? lowDiff : 0; - - plusDM.push(plusDMValue); - minusDM.push(minusDMValue); - } - - // Calculate smoothed averages - const atrValues = sma(trueRanges, period); - const smoothedPlusDM = sma(plusDM, period); - const smoothedMinusDM = sma(minusDM, period); - - const plusDI: number[] = []; - const minusDI: number[] = []; - const dx: number[] = []; - - // Calculate DI+ and DI- - for (let i = 0; i < atrValues.length; i++) { - const atr = atrValues[i]; - const plusDMSmoothed = smoothedPlusDM[i]; - const minusDMSmoothed = smoothedMinusDM[i]; - if (atr === undefined || plusDMSmoothed === undefined || minusDMSmoothed === undefined) continue; - - const diPlus = atr > 0 ? (plusDMSmoothed / atr) * 100 : 0; - const diMinus = atr > 0 ? (minusDMSmoothed / atr) * 100 : 0; - - plusDI.push(diPlus); - minusDI.push(diMinus); - - // Calculate DX - const diSum = diPlus + diMinus; - const dxValue = diSum > 0 ? (Math.abs(diPlus - diMinus) / diSum) * 100 : 0; - dx.push(dxValue); - } - - // Calculate ADX (smoothed DX) - const adxValues = sma(dx, period); - - return { - adx: adxValues, - plusDI: plusDI.slice(period - 1), - minusDI: minusDI.slice(period - 1), - }; -} - -/** - * Volume Weighted Moving Average (VWMA) - */ -export function vwma(ohlcv: OHLCV[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - - let totalVolumePrice = 0; - let totalVolume = 0; - - for (const candle of slice) { - const typicalPrice = (candle.high + candle.low + candle.close) / 3; - totalVolumePrice += typicalPrice * candle.volume; - totalVolume += candle.volume; - } - - const vwmaValue = totalVolume > 0 ? totalVolumePrice / totalVolume : 0; - result.push(vwmaValue); - } - - return result; -} - -/** - * Pivot Points (Standard) - */ -export function pivotPoints(ohlcv: OHLCV[]): Array<{ - pivot: number; - resistance1: number; - resistance2: number; - resistance3: number; - support1: number; - support2: number; - support3: number; -}> { - if (ohlcv.length === 0) { - return []; - } - - const result: Array<{ - pivot: number; - resistance1: number; - resistance2: number; - resistance3: number; - support1: number; - support2: number; - support3: number; - }> = []; - - for (let i = 0; i < ohlcv.length; i++) { - const candle = ohlcv[i]; - - // Calculate pivot point - const pivot = (candle.high + candle.low + candle.close) / 3; - - // Calculate resistance and support levels - const resistance1 = 2 * pivot - candle.low; - const support1 = 2 * pivot - candle.high; - - const resistance2 = pivot + (candle.high - candle.low); - const support2 = pivot - (candle.high - candle.low); - - const resistance3 = candle.high + 2 * (pivot - candle.low); - const support3 = candle.low - 2 * (candle.high - pivot); - - result.push({ - pivot, - resistance1, - resistance2, - resistance3, - support1, - support2, - support3, - }); - } - - return result; -} - -/** - * Ichimoku Cloud - */ -export function ichimokuCloud( - ohlcv: OHLCV[], - tenkanSenPeriod: number = 9, - kijunSenPeriod: number = 26, - senkouSpanBPeriod: number = 52 -): { - tenkanSen: number[]; - kijunSen: number[]; - senkouSpanA: number[]; - senkouSpanB: number[]; - chikouSpan: number[]; -} { - const { high, low, close } = { - high: ohlcv.map(item => item.high), - low: ohlcv.map(item => item.low), - close: ohlcv.map(item => item.close), - }; - - const tenkanSen = calculateTenkanSen(high, low, tenkanSenPeriod); - const kijunSen = calculateKijunSen(high, low, kijunSenPeriod); - const senkouSpanA = calculateSenkouSpanA(tenkanSen, kijunSen); - const senkouSpanB = calculateSenkouSpanB(high, low, senkouSpanBPeriod); - const chikouSpan = calculateChikouSpan(close, kijunSenPeriod); - - return { - tenkanSen, - kijunSen, - senkouSpanA, - senkouSpanB, - chikouSpan, - }; - - function calculateTenkanSen(high: number[], low: number[], period: number): number[] { - const tenkanSen: number[] = []; - for (let i = period - 1; i < high.length; i++) { - const sliceHigh = high.slice(i - period + 1, i + 1); - const sliceLow = low.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...sliceHigh); - const lowestLow = Math.min(...sliceLow); - tenkanSen.push((highestHigh + lowestLow) / 2); - } - return tenkanSen; - } - - function calculateKijunSen(high: number[], low: number[], period: number): number[] { - const kijunSen: number[] = []; - for (let i = period - 1; i < high.length; i++) { - const sliceHigh = high.slice(i - period + 1, i + 1); - const sliceLow = low.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...sliceHigh); - const lowestLow = Math.min(...sliceLow); - kijunSen.push((highestHigh + lowestLow) / 2); - } - return kijunSen; - } - - function calculateSenkouSpanA(tenkanSen: number[], kijunSen: number[]): number[] { - const senkouSpanA: number[] = []; - for (let i = 0; i < tenkanSen.length; i++) { - senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2); - } - return senkouSpanA; - } - - function calculateSenkouSpanB(high: number[], low: number[], period: number): number[] { - const senkouSpanB: number[] = []; - for (let i = period - 1; i < high.length; i++) { - const sliceHigh = high.slice(i - period + 1, i + 1); - const sliceLow = low.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...sliceHigh); - const lowestLow = Math.min(...sliceLow); - senkouSpanB.push((highestHigh + lowestLow) / 2); - } - return senkouSpanB; - } - - function calculateChikouSpan(close: number[], period: number): number[] { - const chikouSpan: number[] = []; - for (let i = 0; i < close.length - period; i++) { - chikouSpan.push(close[i]); - } - return chikouSpan; - } -} - -/** - * Keltner Channels - */ -export function keltnerChannels( - ohlcv: OHLCV[], - period: number = 20, - multiplier: number = 2 -): { - upper: number[]; - middle: number[]; - lower: number[]; -} { - const atrValues = atr(ohlcv, period); - const middle = sma( - ohlcv.map(item => (item.high + item.low + item.close) / 3), - period - ); - const upper: number[] = []; - const lower: number[] = []; - - for (let i = 0; i < middle.length; i++) { - upper.push(middle[i] + multiplier * atrValues[i]); - lower.push(middle[i] - multiplier * atrValues[i]); - } - - return { - upper, - middle, - lower, - }; -} - -/** - * Donchian Channels - */ -export function donchianChannels( - ohlcv: OHLCV[], - period: number = 20 -): { - upper: number[]; - middle: number[]; - lower: number[]; -} { - const upper: number[] = []; - const lower: number[] = []; - const middle: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...slice.map(item => item.high)); - const lowestLow = Math.min(...slice.map(item => item.low)); - - upper.push(highestHigh); - lower.push(lowestLow); - middle.push((highestHigh + lowestLow) / 2); - } - - return { - upper, - middle, - lower, - }; -} - -/** - * Elder-Ray Index - */ -export function elderRay( - ohlcv: OHLCV[], - period: number = 13 -): { - bullPower: number[]; - bearPower: number[]; -} { - const closePrices = ohlcv.map(item => item.close); - const emaValues = ema(closePrices, period); - const bullPower: number[] = []; - const bearPower: number[] = []; - - // Adjust the indexing to ensure we're matching the correct EMA value with each candle - for (let i = period - 1; i < ohlcv.length; i++) { - // Using the proper index for the EMA values which are aligned with closePrices - // Since ema() returns values starting from the period-th element - const emaIndex = i - (period - 1); - if (emaIndex >= 0 && emaIndex < emaValues.length) { - bullPower.push(ohlcv[i].high - emaValues[emaIndex]); - bearPower.push(ohlcv[i].low - emaValues[emaIndex]); - } - } - - return { - bullPower, - bearPower, - }; -} - -/** - * Force Index - */ -export function forceIndex(ohlcv: OHLCV[], period: number = 13): number[] { - const forceIndexValues: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const change = ohlcv[i].close - ohlcv[i - 1].close; - const volume = ohlcv[i].volume; - forceIndexValues.push(change * volume); - } - - const smaValues = sma(forceIndexValues, period); - return smaValues; -} - -/** - * Moving Average Envelope - */ -export function movingAverageEnvelope( - prices: number[], - period: number = 20, - percentage: number = 0.05 -): { - upper: number[]; - lower: number[]; - middle: number[]; -} { - const middle = sma(prices, period); - const upper: number[] = middle.map(value => value * (1 + percentage)); - const lower: number[] = middle.map(value => value * (1 - percentage)); - - return { - upper, - lower, - middle, - }; -} - -/** - * High-Low Index - */ -export function highLowIndex(ohlcv: OHLCV[], period: number = 14): number[] { - const highLowIndexValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let newHighs = 0; - let newLows = 0; - - for (let j = i - period; j <= i; j++) { - if (ohlcv[j].close === Math.max(...ohlcv.slice(i - period, i + 1).map(item => item.close))) { - newHighs++; - } - if (ohlcv[j].close === Math.min(...ohlcv.slice(i - period, i + 1).map(item => item.close))) { - newLows++; - } - } - - highLowIndexValues.push(((newHighs - newLows) / (newHighs + newLows)) * 100); - } - - return highLowIndexValues; -} - -/** - * Coppock Curve - */ -export function coppockCurve( - prices: number[], - longPeriod: number = 14, - shortPeriod: number = 11, - weightedMovingAveragePeriod: number = 10 -): number[] { - const rocLong = roc(prices, longPeriod); - const rocShort = roc(prices, shortPeriod); - - const sumROC: number[] = rocLong.map((value, index) => value + rocShort[index]); - - return sma(sumROC, weightedMovingAveragePeriod); -} - -/** - * Ease of Movement (EMV) - */ -export function easeOfMovement(ohlcv: OHLCV[], period: number = 14): number[] { - const emv: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const distance = - (ohlcv[i].high + ohlcv[i].low) / 2 - (ohlcv[i - 1].high + ohlcv[i - 1].low) / 2; - const boxRatio = ohlcv[i].volume / 100000000 / (ohlcv[i].high - ohlcv[i].low); // Scale volume to avoid very small numbers - - emv.push(distance / boxRatio); - } - - return sma(emv, period); -} - -/** - * Mass Index - */ -export function massIndex( - ohlcv: OHLCV[], - period: number = 9, - emaPeriod: number = 25 -): number[] { - const singleEma: number[] = ema( - ohlcv.map(item => item.high - item.low), - emaPeriod - ); - const doubleEma: number[] = ema(singleEma, emaPeriod); - - const massIndexValues: number[] = []; - for (let i = period; i < doubleEma.length; i++) { - let sum = 0; - for (let j = i - period; j < i; j++) { - sum += singleEma[j] / doubleEma[j]; - } - massIndexValues.push(sum); - } - - return massIndexValues; -} - -/** - * Ultimate Oscillator - */ -export function ultimateOscillator( - ohlcv: OHLCV[], - shortPeriod: number = 7, - mediumPeriod: number = 14, - longPeriod: number = 28 -): number[] { - const ultimateOscillatorValues: number[] = []; - - for (let i = longPeriod; i < ohlcv.length; i++) { - let trueRangeSum = 0; - let buyingPressureSum = 0; - - for (let j = i; j > 0 && j >= i - longPeriod; j--) { - const trueRange = Math.max( - ohlcv[j].high - ohlcv[j].low, - Math.abs(ohlcv[j].high - ohlcv[j - 1].close), - Math.abs(ohlcv[j].low - ohlcv[j - 1].close) - ); - - const buyingPressure = ohlcv[j].close - Math.min(ohlcv[j].low, ohlcv[j - 1].close); - - trueRangeSum += trueRange; - buyingPressureSum += buyingPressure; - } - - const ultimateOscillatorValue = - (100 * - ((4 * buyingPressureSum) / trueRangeSum + - (2 * buyingPressureSum) / trueRangeSum + - buyingPressureSum / trueRangeSum)) / - 7; - - ultimateOscillatorValues.push(ultimateOscillatorValue); - } - - return ultimateOscillatorValues; -} - -/** - * Schaff Trend Cycle (STC) - */ -export function schaffTrendCycle( - prices: number[], - period: number = 10, - fastMAPeriod: number = 23, - slowMAPeriod: number = 50 -): number[] { - const macdValues = macd(prices, fastMAPeriod, slowMAPeriod); - const maxValue = Math.max(...macdValues.macd); - const minValue = Math.min(...macdValues.macd); - - const kValues: number[] = macdValues.macd.map( - value => ((value - minValue) / (maxValue - minValue)) * 100 - ); - const dValues: number[] = sma(kValues, period); - - return dValues; -} - -/** - * Hilbert Transform - Instantaneous Trendline - */ -export function hilbertTransformInstantaneousTrendline(prices: number[]): number[] { - // This is a placeholder. A full Hilbert Transform implementation is complex. - // Requires significantly more code and signal processing knowledge. - // Returning a simple moving average as a substitute. - return sma(prices, 20); -} - -/** - * Relative Volatility Index (RVI) - */ -export function relativeVolatilityIndex(ohlcv: OHLCV[], period: number = 14): number[] { - const rviValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let highCloseSum = 0; - let lowCloseSum = 0; - - for (let j = i; j > 0 && j >= i - period; j--) { - highCloseSum += Math.pow(ohlcv[j].high - ohlcv[j].close, 2); - lowCloseSum += Math.pow(ohlcv[j].low - ohlcv[j].close, 2); - } - - const highCloseStdDev = Math.sqrt(highCloseSum / period); - const lowCloseStdDev = Math.sqrt(lowCloseSum / period); - - const rviValue = (100 * highCloseStdDev) / (highCloseStdDev + lowCloseStdDev); - rviValues.push(rviValue); - } - - return rviValues; -} - -/** - * Chande Momentum Oscillator (CMO) - */ -export function chandeMomentumOscillator(prices: number[], period: number = 14): number[] { - const cmoValues: number[] = []; - - for (let i = period; i < prices.length; i++) { - let sumOfGains = 0; - let sumOfLosses = 0; - - for (let j = i; j > 0 && j >= i - period; j--) { - const change = prices[j] - prices[j - 1]; - if (change > 0) { - sumOfGains += change; - } else { - sumOfLosses += Math.abs(change); - } - } - - const cmoValue = (100 * (sumOfGains - sumOfLosses)) / (sumOfGains + sumOfLosses); - cmoValues.push(cmoValue); - } - - return cmoValues; -} - -/** - * Detrended Price Oscillator (DPO) - */ -export function detrendedPriceOscillator(prices: number[], period: number = 20): number[] { - const dpoValues: number[] = []; - const smaValues = sma(prices, period); - - for (let i = period; i < prices.length; i++) { - const dpoValue = prices[i - Math.floor(period / 2) - 1] - smaValues[i - period]; - dpoValues.push(dpoValue); - } - - return dpoValues; -} - -/** - * Fractal Chaos Bands - */ -export function fractalChaosBands( - ohlcv: OHLCV[], - period: number = 20 -): { upper: number[]; lower: number[] } { - const upper: number[] = []; - const lower: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...slice.map(item => item.high)); - const lowestLow = Math.min(...slice.map(item => item.low)); - - upper.push(highestHigh); - lower.push(lowestLow); - } - - return { - upper, - lower, - }; -} - -/** - * Know Sure Thing (KST) Oscillator - */ -export function knowSureThing( - prices: number[], - rocPeriod1: number = 10, - rocPeriod2: number = 15, - rocPeriod3: number = 20, - rocPeriod4: number = 30, - smaPeriod1: number = 10, - smaPeriod2: number = 10, - smaPeriod3: number = 10, - smaPeriod4: number = 15 -): number[] { - const roc1 = roc(prices, rocPeriod1); - const roc2 = roc(prices, rocPeriod2); - const roc3 = roc(prices, rocPeriod3); - const roc4 = roc(prices, rocPeriod4); - - const sma1 = sma(roc1, smaPeriod1); - const sma2 = sma(roc2, smaPeriod2); - const sma3 = sma(roc3, smaPeriod3); - const sma4 = sma(roc4, smaPeriod4); - - const kstValues: number[] = []; - - for (let i = 0; i < sma1.length; i++) { - const kstValue = sma1[i] + sma2[i] + sma3[i] + sma4[i]; - kstValues.push(kstValue); - } - - return kstValues; -} - -/** - * Percentage Price Oscillator (PPO) - */ -export function percentagePriceOscillator( - prices: number[], - fastPeriod: number = 12, - slowPeriod: number = 26 -): number[] { - const fastEMA = ema(prices, fastPeriod); - const slowEMA = ema(prices, slowPeriod); - - const ppoValues: number[] = []; - - for (let i = 0; i < fastEMA.length; i++) { - const ppoValue = ((fastEMA[i] - slowEMA[i]) / slowEMA[i]) * 100; - ppoValues.push(ppoValue); - } - - return ppoValues; -} - -/** - * Price Volume Trend (PVT) - */ -export function priceVolumeTrend(ohlcv: OHLCV[]): number[] { - const pvtValues: number[] = [0]; // Initialize with 0 - - for (let i = 1; i < ohlcv.length; i++) { - const change = (ohlcv[i].close - ohlcv[i - 1].close) / ohlcv[i - 1].close; - const pvtValue = pvtValues[i - 1] + change * ohlcv[i].volume; - pvtValues.push(pvtValue); - } - - return pvtValues; -} - -/** - * Q Stick - */ -export function qStick(ohlcv: OHLCV[], period: number = 10): number[] { - const qStickValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let sum = 0; - for (let j = i; j > 0 && j >= i - period; j--) { - sum += ohlcv[j].close - ohlcv[j].open; - } - qStickValues.push(sum / period); - } - - return qStickValues; -} - -/** - * TRIX (Triple Exponentially Smoothed Average) - */ -export function trix(prices: number[], period: number = 18): number[] { - const ema1 = ema(prices, period); - const ema2 = ema(ema1, period); - const ema3 = ema(ema2, period); - - const trixValues: number[] = []; - - for (let i = 1; i < ema3.length; i++) { - const trixValue = ((ema3[i] - ema3[i - 1]) / ema3[i - 1]) * 100; - trixValues.push(trixValue); - } - - return trixValues; -} - -/** - * Vertical Horizontal Filter (VHF) - */ -export function verticalHorizontalFilter(ohlcv: OHLCV[], period: number = 28): number[] { - const vhfValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highestHigh = Math.max(...slice.map(item => item.high)); - const lowestLow = Math.min(...slice.map(item => item.low)); - const closeChanges: number[] = []; - - for (let j = 1; j < slice.length; j++) { - closeChanges.push(Math.abs(slice[j].close - slice[j - 1].close)); - } - - const sumOfCloseChanges = closeChanges.reduce((a, b) => a + b, 0); - const vhfValue = (highestHigh - lowestLow) / sumOfCloseChanges; - vhfValues.push(vhfValue); - } - - return vhfValues; -} - -/** - * Volume Rate of Change (VROC) - */ -export function volumeRateOfChange(ohlcv: OHLCV[], period: number = 10): number[] { - const vrocValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - if (ohlcv[i - period].volume === 0) { - vrocValues.push(0); // Avoid division by zero - } else { - const vrocValue = - ((ohlcv[i].volume - ohlcv[i - period].volume) / ohlcv[i - period].volume) * 100; - vrocValues.push(vrocValue); - } - } - - return vrocValues; -} - -/** - * Average True Range Trailing Stops - * Calculates trailing stop levels based on ATR - */ -export function atrTrailingStops( - ohlcv: OHLCV[], - period: number = 14, - multiplier: number = 3 -): { - longStop: number[]; - shortStop: number[]; -} { - const atrValues = atr(ohlcv, period); - const longStop: number[] = []; - const shortStop: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - longStop.push(ohlcv[i].low - multiplier * atrValues[i - period]); - shortStop.push(ohlcv[i].high + multiplier * atrValues[i - period]); - } - - return { - longStop, - shortStop, - }; -} - -/** - * Elder's Force Index - * Measures the strength of a trend by combining price and volume - */ -export function eldersForceIndex(ohlcv: OHLCV[], period: number = 13): number[] { - const forceIndexValues: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const change = ohlcv[i].close - ohlcv[i - 1].close; - const volume = ohlcv[i].volume; - forceIndexValues.push(change * volume); - } - - return ema(forceIndexValues, period); -} - -/** - * Ultimate Oscillator - */ -export function trueStrengthIndex( - prices: number[], - longPeriod: number = 25, - shortPeriod: number = 13, - signalPeriod: number = 9 -): number[] { - const priceChanges: number[] = []; - for (let i = 1; i < prices.length; i++) { - priceChanges.push(prices[i] - prices[i - 1]); - } - - const smoothedMomentum = ema(priceChanges, shortPeriod); - const doubleSmoothedMomentum = ema(smoothedMomentum, longPeriod); - - const absoluteMomentum = priceChanges.map(Math.abs); - const smoothedAbsoluteMomentum = ema(absoluteMomentum, shortPeriod); - const doubleSmoothedAbsoluteMomentum = ema(smoothedAbsoluteMomentum, longPeriod); - - const tsiValues: number[] = []; - for (let i = longPeriod; i < prices.length - 1; i++) { - tsiValues.push( - (doubleSmoothedMomentum[i - longPeriod] / doubleSmoothedAbsoluteMomentum[i - longPeriod]) * - 100 - ); - } - - return tsiValues; -} - -/** - * Money Flow Multiplier - * Calculates the Money Flow Multiplier - */ -export function moneyFlowMultiplier(ohlcv: OHLCV[]): number[] { - return ohlcv.map( - candle => - (candle.close - candle.low - (candle.high - candle.close)) / (candle.high - candle.low) - ); -} - -/** - * Positive Volume Index (PVI) - */ -export function positiveVolumeIndex(ohlcv: OHLCV[], initialValue: number = 1000): number[] { - const pviValues: number[] = [initialValue]; - - for (let i = 1; i < ohlcv.length; i++) { - if (ohlcv[i].volume > ohlcv[i - 1].volume) { - const change = (ohlcv[i].close - ohlcv[i - 1].close) / ohlcv[i - 1].close; - pviValues.push(pviValues[i - 1] + pviValues[i - 1] * change); - } else { - pviValues.push(pviValues[i - 1]); - } - } - - return pviValues; -} - -/** - * Negative Volume Index (NVI) - */ -export function negativeVolumeIndex(ohlcv: OHLCV[], initialValue: number = 1000): number[] { - const nviValues: number[] = [initialValue]; - - for (let i = 1; i < ohlcv.length; i++) { - if (ohlcv[i].volume < ohlcv[i - 1].volume) { - const change = (ohlcv[i].close - ohlcv[i - 1].close) / ohlcv[i - 1].close; - nviValues.push(nviValues[i - 1] + nviValues[i - 1] * change); - } else { - nviValues.push(nviValues[i - 1]); - } - } - - return nviValues; -} - -/** - * Typical Price - * Calculates the typical price for each period - */ -export function typicalPrice(ohlcv: OHLCV[]): number[] { - return ohlcv.map(candle => (candle.high + candle.low + candle.close) / 3); -} - -/** - * Median Price - * Calculates the median price for each period - */ -export function medianPrice(ohlcv: OHLCV[]): number[] { - return ohlcv.map(candle => (candle.high + candle.low) / 2); -} - -/** - * On Balance Volume Mean (OBV Mean) - * Calculates the mean of the On Balance Volume (OBV) values. - */ -export function onBalanceVolumeMean(ohlcv: OHLCV[], period: number = 14): number[] { - const obvValues = obv(ohlcv); - return sma(obvValues, period); -} - -/** - * Kaufman's Adaptive Moving Average (KAMA) - */ -export function kama( - prices: number[], - period: number = 10, - fastPeriod: number = 2, - slowPeriod: number = 30 -): number[] { - const kamaValues: number[] = []; - - if (prices.length <= period) { - return kamaValues; - } - - // Calculate the initial KAMA using SMA - const firstSMA = prices.slice(0, period).reduce((sum, price) => sum + price, 0) / period; - let kama = firstSMA; - kamaValues.push(kama); - - // Constants for the calculation - const fastConst = 2 / (fastPeriod + 1); - const slowConst = 2 / (slowPeriod + 1); - - for (let i = period; i < prices.length; i++) { - // Calculate direction - the numerator of the efficiency ratio - const direction = Math.abs(prices[i] - prices[i - period]); - - // Calculate volatility - the denominator of the efficiency ratio - let volatility = 0; - for (let j = i - period + 1; j <= i; j++) { - volatility += Math.abs(prices[j] - prices[j - 1]); - } - - // Calculate efficiency ratio (ER) - // Handle the case where volatility is zero to avoid division by zero - const er = volatility === 0 ? 1 : Math.min(direction / volatility, 1); - - // Calculate smoothing constant (SC) - const sc = Math.pow(er * (fastConst - slowConst) + slowConst, 2); - - // Calculate KAMA - kama = kama + sc * (prices[i] - kama); - kamaValues.push(kama); - } - - return kamaValues; -} - -/** - * DeMarker - */ -export function deMarker(ohlcv: OHLCV[], period: number = 14): number[] { - const deMax: number[] = []; - const deMin: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - deMax.push(ohlcv[i].high > ohlcv[i - 1].high ? ohlcv[i].high - ohlcv[i - 1].high : 0); - deMin.push(ohlcv[i].low < ohlcv[i - 1].low ? ohlcv[i - 1].low - ohlcv[i].low : 0); - } - - const sumDeMax = sma(deMax, period); - const sumDeMin = sma(deMin, period); - - const deMarkerValues: number[] = []; - for (let i = period; i < ohlcv.length; i++) { - deMarkerValues.push(sumDeMax[i - period] / (sumDeMax[i - period] + sumDeMin[i - period])); - } - - return deMarkerValues; -} - -/** - * Elder's SafeZone Stops - */ -export function eldersSafeZoneStops( - ohlcv: OHLCV[], - atrPeriod: number = 20, - percentageRisk: number = 2 -): { longStop: number[]; shortStop: number[] } { - const atrValues = atr(ohlcv, atrPeriod); - const longStop: number[] = []; - const shortStop: number[] = []; - - for (let i = atrPeriod; i < ohlcv.length; i++) { - longStop.push(ohlcv[i].low - atrValues[i - atrPeriod] * (percentageRisk / 100)); - shortStop.push(ohlcv[i].high + atrValues[i - atrPeriod] * (percentageRisk / 100)); - } - - return { - longStop, - shortStop, - }; -} - -/** - * Projection Oscillator - */ -export function projectionOscillator(ohlcv: OHLCV[], period: number = 14): number[] { - const projectionOscillatorValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let highestHigh = ohlcv[i - period].high; - let lowestLow = ohlcv[i - period].low; - - for (let j = i - period; j < i; j++) { - if (ohlcv[j].high > highestHigh) { - highestHigh = ohlcv[j].high; - } - if (ohlcv[j].low < lowestLow) { - lowestLow = ohlcv[j].low; - } - } - - const projectionOscillatorValue = - ((ohlcv[i].close - lowestLow) / (highestHigh - lowestLow)) * 100; - projectionOscillatorValues.push(projectionOscillatorValue); - } - - return projectionOscillatorValues; -} - -/** - * Twiggs Money Flow - */ -export function twiggsMoneyFlow(ohlcv: OHLCV[]): number[] { - const twiggsMoneyFlowValues: number[] = []; - - for (let i = 0; i < ohlcv.length; i++) { - const moneyFlowVolume = - ohlcv[i].volume * - ((ohlcv[i].close - ohlcv[i].low - (ohlcv[i].high - ohlcv[i].close)) / - (ohlcv[i].high - ohlcv[i].low)); - twiggsMoneyFlowValues.push(moneyFlowVolume); - } - - return twiggsMoneyFlowValues; -} - -/** - * Relative Strength - * Compares the performance of one asset to another - */ -export function relativeStrength( - prices1: number[], - prices2: number[], - period: number = 14 -): number[] { - const rsValues: number[] = []; - const sma1 = sma(prices1, period); - const sma2 = sma(prices2, period); - - for (let i = 0; i < sma1.length; i++) { - rsValues.push(sma1[i] / sma2[i]); - } - - return rsValues; -} - -/** - * Correlation Coefficient - * Measures the statistical relationship between two assets - */ -export function correlationCoefficient( - prices1: number[], - prices2: number[], - period: number = 14 -): number[] { - const correlationValues: number[] = []; - - for (let i = period; i < prices1.length; i++) { - const slice1 = prices1.slice(i - period, i); - const slice2 = prices2.slice(i - period, i); - - const mean1 = slice1.reduce((a, b) => a + b, 0) / period; - const mean2 = slice2.reduce((a, b) => a + b, 0) / period; - - let sumXY = 0; - let sumX2 = 0; - let sumY2 = 0; - - for (let j = 0; j < period; j++) { - sumXY += (slice1[j] - mean1) * (slice2[j] - mean2); - sumX2 += Math.pow(slice1[j] - mean1, 2); - sumY2 += Math.pow(slice2[j] - mean2, 2); - } - - const correlation = sumXY / (Math.sqrt(sumX2) * Math.sqrt(sumY2)); - correlationValues.push(correlation); - } - - return correlationValues; -} - -/** - * Coppock Range - * Calculates the range between high and low Coppock values - */ -export function coppockRange( - prices: number[], - longPeriod: number = 14, - shortPeriod: number = 11, - wmaPeriod: number = 10 -): { high: number[]; low: number[] } { - const coppockValues = coppockCurve(prices, longPeriod, shortPeriod, wmaPeriod); - const highValues: number[] = []; - const lowValues: number[] = []; - - for (let i = 1; i < coppockValues.length; i++) { - highValues.push(Math.max(coppockValues[i], coppockValues[i - 1])); - lowValues.push(Math.min(coppockValues[i], coppockValues[i - 1])); - } - - return { - high: highValues, - low: lowValues, - }; -} - -/** - * Chaikin Oscillator - * Calculates the difference between two moving averages of the Accumulation/Distribution Line - */ -export function chaikinOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 3, - slowPeriod: number = 10 -): number[] { - const adlValues = accumulationDistribution(ohlcv); - const fastMA = ema(adlValues, fastPeriod); - const slowMA = ema(adlValues, slowPeriod); - - const chaikinOscillatorValues: number[] = []; - for (let i = 0; i < fastMA.length; i++) { - chaikinOscillatorValues.push(fastMA[i] - slowMA[i]); - } - - return chaikinOscillatorValues; -} - -/** - * Prime Number Oscillator - * Uses prime numbers to create an oscillator - */ -export function primeNumberOscillator(prices: number[], period: number = 14): number[] { - const primeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]; // First 14 prime numbers - const pnoValues: number[] = []; - - for (let i = period; i < prices.length; i++) { - let sum = 0; - for (let j = 0; j < period; j++) { - sum += prices[i - j] * primeNumbers[j]; - } - pnoValues.push(sum); - } - - return pnoValues; -} - -/** - * Fractal Efficiency - * Measures the efficiency of price movement based on fractal dimension - */ -export function fractalEfficiency(ohlcv: OHLCV[], period: number = 20): number[] { - const fractalEfficiencyValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let netDistance = 0; - for (let j = i; j > i - period; j--) { - netDistance += Math.sqrt(Math.pow(ohlcv[j].close - ohlcv[j - 1].close, 2)); - } - - const straightLineDistance = Math.sqrt(Math.pow(ohlcv[i].close - ohlcv[i - period].close, 2)); - const fractalEfficiencyValue = straightLineDistance / netDistance; - fractalEfficiencyValues.push(fractalEfficiencyValue); - } - - return fractalEfficiencyValues; -} - -/** - * Market Facilitation Index (MFI) - */ -export function marketFacilitationIndex(ohlcv: OHLCV[]): number[] { - const mfiValues: number[] = []; - - for (let i = 0; i < ohlcv.length; i++) { - const range = ohlcv[i].high - ohlcv[i].low; - const mfiValue = range / ohlcv[i].volume; - mfiValues.push(mfiValue); - } - - return mfiValues; -} - -/** - * Elder-Disk - * Combination of Elder-Ray and Force Index - */ -export function elderDisk(ohlcv: OHLCV[], period: number = 13): number[] { - const { bullPower, bearPower } = elderRay(ohlcv, period); - const forceIndexValues = forceIndex(ohlcv, period); - - const elderDiskValues: number[] = []; - for (let i = 0; i < bullPower.length; i++) { - elderDiskValues.push(bullPower[i] + bearPower[i] + forceIndexValues[i]); - } - - return elderDiskValues; -} - -/** - * Relative Vigor Index (RVI) - */ -export function relativeVigorIndex(ohlcv: OHLCV[], period: number = 10): number[] { - const rviValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let sumNumerator = 0; - let sumDenominator = 0; - - for (let j = i; j > i - period; j--) { - sumNumerator += (ohlcv[j].close - ohlcv[j].open) * (ohlcv[j].high - ohlcv[j].low); - sumDenominator += (ohlcv[j].high - ohlcv[j].low) * (ohlcv[j].high - ohlcv[j].low); - } - - const rviValue = sumDenominator !== 0 ? sumNumerator / sumDenominator : 0; - rviValues.push(rviValue); - } - - return rviValues; -} - -/** - * Balance of Power (BOP) - */ -export function balanceOfPower(ohlcv: OHLCV[]): number[] { - const bopValues: number[] = []; - - for (let i = 0; i < ohlcv.length; i++) { - const range = ohlcv[i].high - ohlcv[i].low; - const bopValue = range !== 0 ? (ohlcv[i].close - ohlcv[i].open) / range : 0; - bopValues.push(bopValue); - } - - return bopValues; -} - -/** - * Stochastic RSI - * Combines Stochastic Oscillator and RSI to provide overbought/oversold signals - */ -export function stochasticRSI( - prices: number[], - rsiPeriod: number = 14, - stochasticPeriod: number = 14, - smoothPeriod: number = 3 -): { k: number[]; d: number[] } { - const rsiValues = rsi(prices, rsiPeriod); - return stochastic( - rsiValues.map(rsi => ({ high: rsi, low: rsi, close: rsi, open: rsi, volume: 0 }) as OHLCV), - stochasticPeriod, - smoothPeriod - ); -} - -/** - * StochRSI Fast - */ -export function stochRSIFast( - prices: number[], - rsiPeriod: number = 14, - stochasticPeriod: number = 14 -): { k: number[]; d: number[] } { - const rsiValues = rsi(prices, rsiPeriod); - return stochastic( - rsiValues.map(rsi => ({ high: rsi, low: rsi, close: rsi, open: rsi, volume: 0 }) as OHLCV), - stochasticPeriod, - 1 - ); -} - -/** - * StochRSI Full - */ -export function stochRSIFull( - prices: number[], - rsiPeriod: number = 14, - stochasticPeriod: number = 14, - kSmoothPeriod: number = 3, - dSmoothPeriod: number = 3 -): { k: number[]; d: number[] } { - const rsiValues = rsi(prices, rsiPeriod); - const { k } = stochastic( - rsiValues.map(rsi => ({ high: rsi, low: rsi, close: rsi, open: rsi, volume: 0 }) as OHLCV), - stochasticPeriod, - kSmoothPeriod - ); - const d = sma(k, dSmoothPeriod); - return { k, d }; -} - -/** - * Normalized Average True Range (NATR) - */ -export function normalizedAverageTrueRange(ohlcv: OHLCV[], period: number = 14): number[] { - const atrValues = atr(ohlcv, period); - const natrValues: number[] = []; - - for (let i = 0; i < atrValues.length; i++) { - natrValues.push((atrValues[i] / ohlcv[i].close) * 100); - } - - return natrValues; -} - -/** - * Pretty Good Oscillator (PGO) - */ -export function prettyGoodOscillator(ohlcv: OHLCV[], period: number = 14): number[] { - const pgoValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let sumHighLow = 0; - let sumCloseOpen = 0; - - for (let j = i; j > i - period; j--) { - sumHighLow += ohlcv[j].high - ohlcv[j].low; - sumCloseOpen += ohlcv[j].close - ohlcv[j].open; - } - - const pgoValue = sumHighLow !== 0 ? sumCloseOpen / sumHighLow : 0; - pgoValues.push(pgoValue); - } - - return pgoValues; -} - -/** - * Intraday Intensity Index (III) - */ -export function intradayIntensityIndex(ohlcv: OHLCV[]): number[] { - const iiiValues: number[] = []; - - for (let i = 0; i < ohlcv.length; i++) { - const volume = ohlcv[i].volume; - const range = ohlcv[i].high - ohlcv[i].low; - const iiiValue = - range !== 0 ? ((2 * ohlcv[i].close - ohlcv[i].high - ohlcv[i].low) / range) * volume : 0; - iiiValues.push(iiiValue); - } - - return iiiValues; -} - -/** - * Money Flow Chaikin A/D Oscillator - * Uses the Chaikin A/D line to create an oscillator - */ -export function moneyFlowChaikinOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 3, - slowPeriod: number = 10 -): number[] { - const adlValues = accumulationDistribution(ohlcv); - const fastMA = ema(adlValues, fastPeriod); - const slowMA = ema(adlValues, slowPeriod); - - const moneyFlowChaikinOscillatorValues: number[] = []; - for (let i = 0; i < fastMA.length; i++) { - moneyFlowChaikinOscillatorValues.push(fastMA[i] - slowMA[i]); - } - - return moneyFlowChaikinOscillatorValues; -} - -/** - * Elder's Thermometer - * Uses high and low prices to gauge market temperature - */ -export function eldersThermometer(ohlcv: OHLCV[], period: number = 20): number[] { - const eldersThermometerValues: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let sumOfHighs = 0; - let sumOfLows = 0; - - for (let j = i; j > i - period; j--) { - sumOfHighs += ohlcv[j].high; - sumOfLows += ohlcv[j].low; - } - - const averageHigh = sumOfHighs / period; - const averageLow = sumOfLows / period; - const thermometerValue = averageHigh - averageLow; - eldersThermometerValues.push(thermometerValue); - } - - return eldersThermometerValues; -} - -/** - * High-Low Range - * Calculates the range between high and low prices - */ -export function highLowRange(ohlcv: OHLCV[]): number[] { - return ohlcv.map(candle => candle.high - candle.low); -} - -/** - * Typical Price Range - * Calculates the range of typical prices - */ -export function typicalPriceRange(ohlcv: OHLCV[]): number[] { - const typicalPrices = typicalPrice(ohlcv); - const typicalPriceRangeValues: number[] = []; - - for (let i = 1; i < typicalPrices.length; i++) { - typicalPriceRangeValues.push(typicalPrices[i] - typicalPrices[i - 1]); - } - - return typicalPriceRangeValues; -} - -/** - * Median Price Range - * Calculates the range of median prices - */ -export function medianPriceRange(ohlcv: OHLCV[]): number[] { - const medianPrices = medianPrice(ohlcv); - const medianPriceRangeValues: number[] = []; - - for (let i = 1; i < medianPrices.length; i++) { - medianPriceRangeValues.push(medianPrices[i] - medianPrices[i - 1]); - } - - return medianPriceRangeValues; -} - -/** - * Center of Gravity - */ -export function centerOfGravity(prices: number[], period: number = 10): number[] { - const cogValues: number[] = []; - - for (let i = period; i < prices.length; i++) { - let weightedSum = 0; - let sumOfWeights = 0; - - for (let j = 1; j <= period; j++) { - weightedSum += j * prices[i - period + j]; - sumOfWeights += j; - } - - const cogValue = weightedSum / sumOfWeights; - cogValues.push(cogValue); - } - - return cogValues; -} - -/** - * Linear Regression Indicator - */ -export function linearRegressionIndicator(prices: number[], period: number = 14): number[] { - const lriValues: number[] = []; - - if (prices.length < period) { - return lriValues; - } - - for (let i = period; i < prices.length; i++) { - const slice = prices.slice(i - period, i); - - // Calculate means for normalization (increases numerical stability) - const meanX = (period + 1) / 2; // Mean of 1,2,3,...,period - let meanY = 0; - for (let j = 0; j < period; j++) { - meanY += slice[j]; - } - meanY /= period; - - // Calculate covariance and variance with normalized data - let covariance = 0; - let variance = 0; - - for (let j = 0; j < period; j++) { - const xDiff = j + 1 - meanX; - const yDiff = slice[j] - meanY; - - covariance += xDiff * yDiff; - variance += xDiff * xDiff; - } - - // Avoid division by zero - const slope = variance !== 0 ? covariance / variance : 0; - const intercept = meanY - slope * meanX; - - // Calculate the predicted value at the end of the period - const lriValue = slope * period + intercept; - lriValues.push(lriValue); - } - - return lriValues; -} - -/** - * Standard Deviation - * Calculates the standard deviation of a set of values - */ -export function standardDeviation(prices: number[], period: number = 20): number[] { - const stdDevValues: number[] = []; - const smaValues = sma(prices, period); - - for (let i = period - 1; i < prices.length; i++) { - const slice = prices.slice(i - period + 1, i + 1); - const mean = smaValues[i - period + 1]; - let sumOfSquaredDifferences = 0; - - for (const price of slice) { - sumOfSquaredDifferences += Math.pow(price - mean, 2); - } - - const variance = sumOfSquaredDifferences / period; - const stdDevValue = Math.sqrt(variance); - stdDevValues.push(stdDevValue); - } - - return stdDevValues; -} - -/** - * Chaikin A/D Range - * Calculates the range of the Chaikin A/D line - */ -export function chaikinADRange(ohlcv: OHLCV[]): number[] { - const adValues = accumulationDistribution(ohlcv); - const adRangeValues: number[] = []; - - for (let i = 1; i < adValues.length; i++) { - adRangeValues.push(adValues[i] - adValues[i - 1]); - } - - return adRangeValues; -} - -/** - * Volume Oscillator - * Compares two moving averages of volume - */ -export function volumeOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 5, - slowPeriod: number = 10 -): number[] { - const volumes = ohlcv.map(candle => candle.volume); - const fastMA = sma(volumes, fastPeriod); - const slowMA = sma(volumes, slowPeriod); - - const volumeOscillatorValues: number[] = []; - for (let i = 0; i < fastMA.length; i++) { - volumeOscillatorValues.push(((fastMA[i] - slowMA[i]) / slowMA[i]) * 100); - } - - return volumeOscillatorValues; -} - -/** - * Money Flow Index Range - * Calculates the range of the Money Flow Index - */ -export function moneyFlowIndexRange(ohlcv: OHLCV[], period: number = 14): number[] { - const mfiValues = mfi(ohlcv, period); - const mfiRangeValues: number[] = []; - - for (let i = 1; i < mfiValues.length; i++) { - mfiRangeValues.push(mfiValues[i] - mfiValues[i - 1]); - } - - return mfiRangeValues; -} - -/** - * On Balance Volume Oscillator - * Calculates the oscillator of the On Balance Volume - */ -export function onBalanceVolumeOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 5, - slowPeriod: number = 10 -): number[] { - const obvValues = obv(ohlcv); - const fastMA = sma(obvValues, fastPeriod); - const slowMA = sma(obvValues, slowPeriod); - - const obvOscillatorValues: number[] = []; - for (let i = 0; i < fastMA.length; i++) { - obvOscillatorValues.push(((fastMA[i] - slowMA[i]) / slowMA[i]) * 100); - } - - return obvOscillatorValues; -} - -/** - * Klinger Oscillator - */ -export function klingerOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 34, - slowPeriod: number = 55 -): number[] { - if (ohlcv.length < 2) { - return []; - } - - // Calculate volume force - const volumeForce: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]; - const previous = ohlcv[i - 1]; - - // Calculate typical prices - const typicalPriceCurrent = (current.high + current.low + current.close) / 3; - const typicalPricePrevious = (previous.high + previous.low + previous.close) / 3; - - // Determine trend - const trend = typicalPriceCurrent > typicalPricePrevious ? 1 : -1; - - // Calculate volume force - const force = trend * ohlcv[i].volume * Math.abs(typicalPriceCurrent - typicalPricePrevious); - volumeForce.push(force); - } - - // Calculate fast and slow EMAs of the volume force - const fastEMA = ema(volumeForce, fastPeriod); - const slowEMA = ema(volumeForce, slowPeriod); - - // Calculate Klinger Oscillator - const klingerOscillatorValues: number[] = []; - - // Both EMAs should have the same starting point - const startIndex = Math.abs(fastEMA.length - slowEMA.length); - const shorterEMA = fastEMA.length < slowEMA.length ? fastEMA : slowEMA; - const longerEMA = fastEMA.length < slowEMA.length ? slowEMA : fastEMA; - - for (let i = 0; i < shorterEMA.length; i++) { - if (fastEMA.length < slowEMA.length) { - klingerOscillatorValues.push(shorterEMA[i] - longerEMA[i + startIndex]); - } else { - klingerOscillatorValues.push(longerEMA[i + startIndex] - shorterEMA[i]); - } - } - - return klingerOscillatorValues; -} - -/** - * Directional Movement Index (DMI) - */ -export function directionalMovementIndex( - ohlcv: OHLCV[], - period: number = 14 -): { plusDI: number[]; minusDI: number[] } { - const { plusDI, minusDI } = adx(ohlcv, period); - return { plusDI, minusDI }; -} - -/** - * Elder's Cloud - */ -export function eldersCloud( - ohlcv: OHLCV[], - period: number = 20 -): { upper: number[]; lower: number[] } { - const emaValues = ema( - ohlcv.map(item => item.close), - period - ); - const atrValues = atr(ohlcv, period); - const upper: number[] = []; - const lower: number[] = []; - - for (let i = 0; i < emaValues.length; i++) { - upper.push(emaValues[i] + atrValues[i]); - lower.push(emaValues[i] - atrValues[i]); - } - - return { - upper, - lower, - }; -} - -/** - * Ultimate Moving Average (UMA) - */ -export function ultimateMovingAverage( - prices: number[], - fastPeriod: number = 7, - mediumPeriod: number = 14, - slowPeriod: number = 28 -): number[] { - const fastMA = sma(prices, fastPeriod); - const mediumMA = sma(prices, mediumPeriod); - const slowMA = sma(prices, slowPeriod); - - const umaValues: number[] = []; - for (let i = 0; i < fastMA.length; i++) { - umaValues.push((fastMA[i] + mediumMA[i] + slowMA[i]) / 3); - } - - return umaValues; -} - -/** - * Rainbow Oscillator - */ -export function rainbowOscillator( - prices: number[], - numberOfMAs: number = 7, - periodIncrement: number = 5 -): number[] { - const maValues: number[][] = []; - for (let i = 1; i <= numberOfMAs; i++) { - maValues.push(sma(prices, i * periodIncrement)); - } - - const rainbowOscillatorValues: number[] = []; - for (let i = 0; i < maValues[0].length; i++) { - let sum = 0; - for (let j = 0; j < numberOfMAs; j++) { - sum += maValues[j][i]; - } - rainbowOscillatorValues.push(sum / numberOfMAs); - } - - return rainbowOscillatorValues; -} - -/** - * Guppy Multiple Moving Average (GMMA) - */ -export function guppyMultipleMovingAverage( - prices: number[], - shortTermPeriods: number[] = [3, 5, 8, 10, 12, 15], - longTermPeriods: number[] = [30, 35, 40, 45, 50, 60] -): { shortTermMAs: number[][]; longTermMAs: number[][] } { - const shortTermMAs: number[][] = []; - const longTermMAs: number[][] = []; - - for (const period of shortTermPeriods) { - shortTermMAs.push(sma(prices, period)); - } - - for (const period of longTermPeriods) { - longTermMAs.push(sma(prices, period)); - } - - return { shortTermMAs, longTermMAs }; -} - -/** - * Historical Volatility - */ -export function historicalVolatility(prices: number[], period: number = 20): number[] { - const logReturns: number[] = []; - for (let i = 1; i < prices.length; i++) { - logReturns.push(Math.log(prices[i] / prices[i - 1])); - } - - const stdDevs = standardDeviation(logReturns, period); - const historicalVolatilityValues: number[] = []; - - for (const stdDev of stdDevs) { - historicalVolatilityValues.push(stdDev * Math.sqrt(252)); // Annualize - } - - return historicalVolatilityValues; -} - -/** - * Donchian Width - */ -export function donchianWidth(ohlcv: OHLCV[], period: number = 20): number[] { - const { upper, lower } = donchianChannels(ohlcv, period); - const donchianWidthValues: number[] = []; - - for (let i = 0; i < upper.length; i++) { - donchianWidthValues.push(upper[i] - lower[i]); - } - - return donchianWidthValues; -} - -/** - * Chandelier Exit - */ -export function chandelierExit( - ohlcv: OHLCV[], - period: number = 22, - multiplier: number = 3 -): { long: number[]; short: number[] } { - const atrValues = atr(ohlcv, period); - const long: number[] = []; - const short: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period, i); - const highestHigh = Math.max(...slice.map(item => item.high)); - const lowestLow = Math.min(...slice.map(item => item.low)); - - long.push(highestHigh - multiplier * atrValues[i - period]); - short.push(lowestLow + multiplier * atrValues[i - period]); - } - - return { long, short }; -} - -/** - * Projection Bands - */ -export function projectionBands( - ohlcv: OHLCV[], - period: number = 14, - stdDevMultiplier: number = 2 -): { upper: number[]; lower: number[] } { - const projectionOscillatorValues = projectionOscillator(ohlcv, period); - const stdDevValues = standardDeviation(projectionOscillatorValues, period); - const upper: number[] = []; - const lower: number[] = []; - - for (let i = 0; i < projectionOscillatorValues.length; i++) { - upper.push(projectionOscillatorValues[i] + stdDevMultiplier * stdDevValues[i]); - lower.push(projectionOscillatorValues[i] - stdDevMultiplier * stdDevValues[i]); - } - - return { upper, lower }; -} - -/** - * Range Action Verification Index (RAVI) - */ -export function rangeActionVerificationIndex( - prices: number[], - longPeriod: number = 65, - shortPeriod: number = 10 -): number[] { - const longMA = sma(prices, longPeriod); - const shortMA = sma(prices, shortPeriod); - - const raviValues: number[] = []; - for (let i = 0; i < longMA.length; i++) { - raviValues.push(((shortMA[i] - longMA[i]) / longMA[i]) * 100); - } - - return raviValues; -} - -/** - * Momentum from Current Price - * Calculates momentum using the current price and a previous price. Reduces lag compared to using moving averages. - */ -export function momentumFromCurrentPrice(prices: number[], period: number = 10): number[] { - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - const momentum = prices[i] - prices[i - period]; - result.push(momentum); - } - - return result; -} - -/** - * Rate of Change from Current Price (ROC) - * Calculates ROC using the current price. - */ -export function rocFromCurrentPrice(prices: number[], period: number = 10): number[] { - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - if (prices[i - period] === 0) { - result.push(0); - } else { - const rocValue = ((prices[i] - prices[i - period]) / prices[i - period]) * 100; - result.push(rocValue); - } - } - - return result; -} -``` diff --git a/libs/calculations/research/volatility-models.md b/libs/calculations/research/volatility-models.md deleted file mode 100644 index 5d379e38..00000000 --- a/libs/calculations/research/volatility-models.md +++ /dev/null @@ -1,633 +0,0 @@ -# volatility-models research snapshot - -Source: `ccce401:libs/utils/src/calculations/volatility-models.ts.disabled`. - -Contains simplified Yangโ€“Zhang/Heston estimates and unseeded random shocks. - -This preserves previously disabled research, not a supported or executable package API. -Review formulas, contracts, determinism and fixtures before porting any function into `src/`. -The code below is the original source, unchanged. - -```ts -/** - * Volatility Models - * Advanced volatility modeling and forecasting tools - */ - -// Local interface definition to avoid circular dependency -interface OHLCVData { - open: number; - high: number; - low: number; - close: number; - volume: number; - timestamp: Date; -} - -export interface GARCHParameters { - omega: number; // Constant term - alpha: number; // ARCH parameter - beta: number; // GARCH parameter - logLikelihood: number; - aic: number; - bic: number; -} - -export interface VolatilityEstimates { - closeToClose: number; - parkinson: number; - garmanKlass: number; - rogersSatchell: number; - yangZhang: number; -} - -export interface VolatilityRegime { - regime: number; - startDate: Date; - endDate: Date; - averageVolatility: number; - observations: number; -} - -export interface VolatilityTerm { - maturity: number; // Days to maturity - impliedVolatility: number; - confidence: number; -} - -export interface HestonParameters { - kappa: number; // Mean reversion speed - theta: number; // Long-term variance - sigma: number; // Volatility of variance - rho: number; // Correlation - v0: number; // Initial variance - logLikelihood: number; -} - -/** - * Calculate realized volatility using different estimators - */ -export function calculateRealizedVolatility( - ohlcv: OHLCVData[], - annualizationFactor: number = 252 -): VolatilityEstimates { - if (ohlcv.length < 2) { - throw new Error('Need at least 2 observations for volatility calculation'); - } - - const n = ohlcv.length; - let closeToCloseSum = 0; - let parkinsonSum = 0; - let garmanKlassSum = 0; - let rogersSatchellSum = 0; - let yangZhangSum = 0; - - // Calculate log returns and volatility estimators - for (let i = 1; i < n; i++) { - const prev = ohlcv[i - 1]; - const curr = ohlcv[i]; - - // Close-to-close - const logReturn = Math.log(curr.close / prev.close); - closeToCloseSum += logReturn * logReturn; - - // Parkinson estimator - const logHighLow = Math.log(curr.high / curr.low); - parkinsonSum += logHighLow * logHighLow; - - // Garman-Klass estimator - const logOpenClose = Math.log(curr.close / curr.open); - garmanKlassSum += - 0.5 * logHighLow * logHighLow - (2 * Math.log(2) - 1) * logOpenClose * logOpenClose; - - // Rogers-Satchell estimator - const logHighOpen = Math.log(curr.high / curr.open); - const logHighClose = Math.log(curr.high / curr.close); - const logLowOpen = Math.log(curr.low / curr.open); - const logLowClose = Math.log(curr.low / curr.close); - rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose; - - // Yang-Zhang estimator components - const overnight = Math.log(curr.open / prev.close); - yangZhangSum += overnight * overnight + rogersSatchellSum / i; // Simplified for brevity - } - - return { - closeToClose: Math.sqrt((closeToCloseSum / (n - 1)) * annualizationFactor), - parkinson: Math.sqrt((parkinsonSum / (n - 1) / (4 * Math.log(2))) * annualizationFactor), - garmanKlass: Math.sqrt((garmanKlassSum / (n - 1)) * annualizationFactor), - rogersSatchell: Math.sqrt((rogersSatchellSum / (n - 1)) * annualizationFactor), - yangZhang: Math.sqrt((yangZhangSum / (n - 1)) * annualizationFactor), - }; -} - -/** - * Estimate GARCH(1,1) model parameters - */ -export function estimateGARCH( - returns: number[], - maxIterations: number = 100, - tolerance: number = 1e-6 -): GARCHParameters { - const n = returns.length; - - // Initial parameter estimates - let omega = 0.01; - let alpha = 0.05; - let beta = 0.9; - - // Calculate unconditional variance - const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n; - const unconditionalVar = - returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1); - - let logLikelihood = -Infinity; - - for (let iter = 0; iter < maxIterations; iter++) { - const variances: number[] = [unconditionalVar]; - let newLogLikelihood = 0; - - // Calculate conditional variances - for (let t = 1; t < n; t++) { - const prevVar = variances[t - 1]; - const prevReturn = returns[t - 1] - meanReturn; - const currentVar = omega + alpha * prevReturn * prevReturn + beta * prevVar; - variances.push(Math.max(currentVar, 1e-8)); // Ensure positive variance - - // Add to log-likelihood - const currentReturn = returns[t] - meanReturn; - newLogLikelihood -= - 0.5 * - (Math.log(2 * Math.PI) + - Math.log(currentVar) + - (currentReturn * currentReturn) / currentVar); - } - - // Check for convergence - if (Math.abs(newLogLikelihood - logLikelihood) < tolerance) { - break; - } - - logLikelihood = newLogLikelihood; - - // Simple gradient update (in practice, use more sophisticated optimization) - const gradientStep = 0.001; - omega = Math.max(0.001, omega + gradientStep); - alpha = Math.max(0.001, Math.min(0.999, alpha + gradientStep)); - beta = Math.max(0.001, Math.min(0.999 - alpha, beta + gradientStep)); - } - - // Calculate information criteria - const k = 3; // Number of parameters - const aic = -2 * logLikelihood + 2 * k; - const bic = -2 * logLikelihood + k * Math.log(n); - - return { - omega, - alpha, - beta, - logLikelihood, - aic, - bic, - }; -} - -/** - * Calculate EWMA volatility - */ -export function calculateEWMAVolatility( - returns: number[], - lambda: number = 0.94, - annualizationFactor: number = 252 -): number[] { - const n = returns.length; - const volatilities: number[] = []; - - // Initialize with sample variance - const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n; - let variance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1); - - for (let t = 0; t < n; t++) { - if (t > 0) { - const prevReturn = returns[t - 1] - meanReturn; - variance = lambda * variance + (1 - lambda) * prevReturn * prevReturn; - } - volatilities.push(Math.sqrt(variance * annualizationFactor)); - } - - return volatilities; -} - -/** - * Identify volatility regimes - */ -export function identifyVolatilityRegimes( - returns: number[], - numRegimes: number = 3, - windowSize: number = 60 -): VolatilityRegime[] { - // Calculate rolling volatility - const rollingVol: number[] = []; - const timestamps: Date[] = []; - - for (let i = windowSize - 1; i < returns.length; i++) { - const window = returns.slice(i - windowSize + 1, i + 1); - const mean = window.reduce((sum, r) => sum + r, 0) / window.length; - const variance = - window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1); - rollingVol.push(Math.sqrt(variance * 252)); // Annualized - timestamps.push(new Date(Date.now() + i * 24 * 60 * 60 * 1000)); // Mock timestamps - } - - // Simple k-means clustering on absolute returns - const absReturns = returns.map(ret => Math.abs(ret)); - const sortedReturns = [...absReturns].sort((a, b) => a - b); - - // Define regime thresholds - const thresholds: number[] = []; - for (let i = 1; i < numRegimes; i++) { - const index = Math.floor((i / numRegimes) * sortedReturns.length); - thresholds.push(sortedReturns[index]); - } - - // Classify returns into regimes - const regimeSequence = absReturns.map(absRet => { - for (let i = 0; i < thresholds.length; i++) { - if (absRet <= thresholds[i]) { - return i; - } - } - return numRegimes - 1; - }); - - // Calculate regime statistics - const regimes: VolatilityRegime[] = []; - for (let regime = 0; regime < numRegimes; regime++) { - const regimeIndices = regimeSequence - .map((r, idx) => (r === regime ? idx : -1)) - .filter(idx => idx !== -1); - - if (regimeIndices.length > 0) { - const regimeVolatilities = regimeIndices.map(idx => - idx < rollingVol.length ? rollingVol[idx] : 0 - ); - const avgVol = - regimeVolatilities.reduce((sum, vol) => sum + vol, 0) / regimeVolatilities.length; - - regimes.push({ - regime, - startDate: new Date(Date.now()), - endDate: new Date(Date.now() + regimeIndices.length * 24 * 60 * 60 * 1000), - averageVolatility: avgVol, - observations: regimeIndices.length, - }); - } - } - - return regimes; -} - -/** - * Calculate volatility term structure - */ -export function calculateVolatilityTermStructure( - spotVol: number, - maturities: number[], - meanReversion: number = 0.5 -): VolatilityTerm[] { - return maturities.map(maturity => { - // Simple mean reversion model for term structure - const timeToMaturity = maturity / 365; // Convert to years - const termVolatility = spotVol * Math.exp(-meanReversion * timeToMaturity); - - return { - maturity, - impliedVolatility: Math.max(termVolatility, 0.01), // Floor at 1% - confidence: Math.exp(-timeToMaturity), // Confidence decreases with maturity - }; - }); -} - -/** - * Calculate volatility smile/skew parameters - */ -export function calculateVolatilitySmile( - strikes: number[], - spotPrice: number, - impliedVols: number[] -): { - atmVolatility: number; - skew: number; - convexity: number; - riskReversal: number; -} { - if (strikes.length !== impliedVols.length || strikes.length < 3) { - throw new Error('Need at least 3 strikes with corresponding implied volatilities'); - } - - // Find ATM volatility - const atmIndex = strikes.reduce( - (closest, strike, idx) => - Math.abs(strike - spotPrice) < Math.abs(strikes[closest] - spotPrice) ? idx : closest, - 0 - ); - const atmVolatility = impliedVols[atmIndex]; - - // Calculate skew (derivative at ATM) - let skew = 0; - if (atmIndex > 0 && atmIndex < strikes.length - 1) { - const deltaStrike = strikes[atmIndex + 1] - strikes[atmIndex - 1]; - const deltaVol = impliedVols[atmIndex + 1] - impliedVols[atmIndex - 1]; - skew = deltaVol / deltaStrike; - } - - // Calculate convexity (second derivative) - let convexity = 0; - if (atmIndex > 0 && atmIndex < strikes.length - 1) { - const h = strikes[atmIndex + 1] - strikes[atmIndex]; - convexity = - (impliedVols[atmIndex + 1] - 2 * impliedVols[atmIndex] + impliedVols[atmIndex - 1]) / (h * h); - } - - // Risk reversal (put-call vol difference) - const otmPutIndex = strikes.findIndex(strike => strike < spotPrice * 0.9); - const otmCallIndex = strikes.findIndex(strike => strike > spotPrice * 1.1); - let riskReversal = 0; - - if (otmPutIndex !== -1 && otmCallIndex !== -1) { - riskReversal = impliedVols[otmCallIndex] - impliedVols[otmPutIndex]; - } - - return { - atmVolatility, - skew, - convexity, - riskReversal, - }; -} - -/** - * Estimate Heston stochastic volatility model parameters - */ -export function estimateHestonParameters( - returns: number[], - maxIterations: number = 100 -): HestonParameters { - const n = returns.length; - - if (n < 10) { - throw new Error('Need at least 10 observations for Heston parameter estimation'); - } - - // Initial parameter estimates - let kappa = 2.0; // Mean reversion speed - let theta = 0.04; // Long-term variance - let sigma = 0.3; // Volatility of variance - let rho = -0.5; // Correlation - let v0 = 0.04; // Initial variance - - // Calculate sample statistics for initialization - const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n; - const sampleVariance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1); - - theta = sampleVariance; - v0 = sampleVariance; - - let logLikelihood = -Infinity; - - for (let iter = 0; iter < maxIterations; iter++) { - let newLogLikelihood = 0; - let currentVariance = v0; - - for (let t = 1; t < n; t++) { - const dt = 1.0; // Assuming daily data - const prevReturn = returns[t - 1]; - - // Euler discretization of variance process - const dW1 = Math.random() - 0.5; // Simplified random shock - const dW2 = rho * dW1 + Math.sqrt(1 - rho * rho) * (Math.random() - 0.5); - - const varianceChange = - kappa * (theta - currentVariance) * dt + - sigma * Math.sqrt(Math.max(currentVariance, 0)) * dW2; - - currentVariance = Math.max(currentVariance + varianceChange, 0.001); - - // Log-likelihood contribution (simplified) - const expectedReturn = meanReturn; - const variance = currentVariance; - - if (variance > 0) { - newLogLikelihood -= 0.5 * Math.log(2 * Math.PI * variance); - newLogLikelihood -= (0.5 * Math.pow(returns[t] - expectedReturn, 2)) / variance; - } - } - - // Check for convergence - if (Math.abs(newLogLikelihood - logLikelihood) < 1e-6) { - break; - } - - logLikelihood = newLogLikelihood; - - // Simple parameter updates (in practice, use maximum likelihood estimation) - const learningRate = 0.001; - kappa = Math.max(0.1, Math.min(10, kappa + learningRate)); - theta = Math.max(0.001, Math.min(1, theta + learningRate)); - sigma = Math.max(0.01, Math.min(2, sigma + learningRate)); - rho = Math.max(-0.99, Math.min(0.99, rho + learningRate * 0.1)); - v0 = Math.max(0.001, Math.min(1, v0 + learningRate)); - } - - return { - kappa, - theta, - sigma, - rho, - v0, - logLikelihood, - }; -} - -/** - * Calculate volatility risk metrics - */ -export function calculateVolatilityRisk( - returns: number[], - confidenceLevel: number = 0.05 -): { - volatilityVaR: number; - expectedShortfall: number; - maxVolatility: number; - volatilityVolatility: number; -} { - // Calculate rolling volatilities - const windowSize = 30; - const volatilities: number[] = []; - - for (let i = windowSize - 1; i < returns.length; i++) { - const window = returns.slice(i - windowSize + 1, i + 1); - const mean = window.reduce((sum, r) => sum + r, 0) / window.length; - const variance = - window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1); - volatilities.push(Math.sqrt(variance * 252)); // Annualized - } - - // Sort volatilities for VaR calculation - const sortedVols = [...volatilities].sort((a, b) => b - a); // Descending order - const varIndex = Math.floor(confidenceLevel * sortedVols.length); - const volatilityVaR = sortedVols[varIndex]; - - // Expected shortfall (average of worst volatilities) - const esVols = sortedVols.slice(0, varIndex + 1); - const expectedShortfall = esVols.reduce((sum, vol) => sum + vol, 0) / esVols.length; - - // Maximum volatility - const maxVolatility = Math.max(...volatilities); - - // Volatility of volatility - const meanVol = volatilities.reduce((sum, vol) => sum + vol, 0) / volatilities.length; - const volVariance = - volatilities.reduce((sum, vol) => sum + Math.pow(vol - meanVol, 2), 0) / - (volatilities.length - 1); - const volatilityVolatility = Math.sqrt(volVariance); - - return { - volatilityVaR, - expectedShortfall, - maxVolatility, - volatilityVolatility, - }; -} - -/** - * Fix Yang-Zhang volatility calculation - */ -export function calculateYangZhangVolatility( - ohlcv: OHLCVData[], - annualizationFactor: number = 252 -): number { - if (ohlcv.length < 2) { - throw new Error('Need at least 2 observations for Yang-Zhang volatility calculation'); - } - - const n = ohlcv.length; - let overnightSum = 0; - let openToCloseSum = 0; - let rogersSatchellSum = 0; - - for (let i = 1; i < n; i++) { - const prev = ohlcv[i - 1]; - const curr = ohlcv[i]; - - // Overnight return (close to open) - const overnight = Math.log(curr.open / prev.close); - overnightSum += overnight * overnight; - - // Open to close return - const openToClose = Math.log(curr.close / curr.open); - openToCloseSum += openToClose * openToClose; - - // Rogers-Satchell component - const logHighOpen = Math.log(curr.high / curr.open); - const logHighClose = Math.log(curr.high / curr.close); - const logLowOpen = Math.log(curr.low / curr.open); - const logLowClose = Math.log(curr.low / curr.close); - rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose; - } - - // Yang-Zhang estimator - const k = 0.34 / (1.34 + (n + 1) / (n - 1)); // Drift adjustment factor - const yangZhangVariance = - overnightSum / (n - 1) + - (k * openToCloseSum) / (n - 1) + - ((1 - k) * rogersSatchellSum) / (n - 1); - - return Math.sqrt(yangZhangVariance * annualizationFactor); -} - -/** - * Parkinson volatility estimator - */ -export function parkinsonVolatility(ohlcv: OHLCVData[], annualizationFactor: number = 252): number { - if (ohlcv.length < 2) { - return 0; - } - const sum = ohlcv.slice(1).reduce((acc, curr) => { - const range = Math.log(curr.high / curr.low); - return acc + range * range; - }, 0); - return Math.sqrt((sum / (ohlcv.length - 1)) * annualizationFactor); -} - -/** - * Black-Scholes option pricing model - */ -function blackScholes( - spotPrice: number, - strikePrice: number, - timeToExpiry: number, - volatility: number, - riskFreeRate: number, - optionType: 'call' | 'put' -): number { - const d1 = - (Math.log(spotPrice / strikePrice) + - (riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) / - (volatility * Math.sqrt(timeToExpiry)); - const d2 = d1 - volatility * Math.sqrt(timeToExpiry); - - if (optionType === 'call') { - return ( - spotPrice * normalCDF(d1) - - strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(d2) - ); - } else { - return ( - strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2) - - spotPrice * normalCDF(-d1) - ); - } -} - -/** - * Normal cumulative distribution function - */ -function normalCDF(x: number): number { - const a1 = 0.254829592; - const a2 = -0.284496736; - const a3 = 1.421060743; - const a4 = -1.453152027; - const a5 = 1.061405429; - const p = 0.3275911; - - const sign = x < 0 ? -1 : 1; - const absX = Math.abs(x); - const t = 1 / (1 + p * absX); - const y = - 1 - - (a1 * t + a2 * t * t + a3 * t * t * t + a4 * t * t * t * t + a5 * t * t * t * t * t) * - Math.exp((-absX * absX) / 2); - - return 0.5 * (1 + sign * y); -} - -/** - * Forecast volatility using EWMA - */ -export function forecastVolatilityEWMA( - volatilities: number[], - lambda: number = 0.94, - forecastHorizon: number = 1 -): number { - if (volatilities.length === 0) { - return 0; - } - - let forecast = volatilities[volatilities.length - 1]; - for (let i = 0; i < forecastHorizon; i++) { - forecast = lambda * forecast + (1 - lambda) * forecast; // Using the last value as the long-term average - } - return forecast; -} -``` diff --git a/libs/calculations/src/legacy/basic-calculations.ts b/libs/calculations/src/legacy/basic-calculations.ts deleted file mode 100644 index 8cae2d52..00000000 --- a/libs/calculations/src/legacy/basic-calculations.ts +++ /dev/null @@ -1,454 +0,0 @@ -/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ -/** - * Basic Financial Calculations - * Core mathematical functions for financial analysis - */ - -/** - * Calculate percentage change between two values - */ -export function percentageChange(oldValue: number, newValue: number): number { - if (oldValue === 0) { - return 0; - } - return ((newValue - oldValue) / oldValue) * 100; -} - -/** - * Calculate simple return - */ -export function simpleReturn(initialPrice: number, finalPrice: number): number { - if (initialPrice === 0) { - return 0; - } - return (finalPrice - initialPrice) / initialPrice; -} - -/** - * Calculate logarithmic return - */ -export function logReturn(initialPrice: number, finalPrice: number): number { - if (initialPrice <= 0 || finalPrice <= 0) { - return 0; - } - return Math.log(finalPrice / initialPrice); -} - -/** - * Calculate compound annual growth rate (CAGR) - */ -export function cagr(startValue: number, endValue: number, years: number): number { - if (years <= 0 || startValue <= 0 || endValue <= 0) { - return 0; - } - return Math.pow(endValue / startValue, 1 / years) - 1; -} - -/** - * Calculate annualized return from periodic returns - */ -export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number { - return Math.pow(1 + periodicReturn, periodsPerYear) - 1; -} - -/** - * Calculate annualized volatility from periodic returns - */ -export function annualizeVolatility(periodicVolatility: number, periodsPerYear: number): number { - return periodicVolatility * Math.sqrt(periodsPerYear); -} - -/** - * Calculate present value - */ -export function presentValue(futureValue: number, rate: number, periods: number): number { - return futureValue / Math.pow(1 + rate, periods); -} - -/** - * Calculate future value - */ -export function futureValue(presentValue: number, rate: number, periods: number): number { - return presentValue * Math.pow(1 + rate, periods); -} - -/** - * Calculate net present value of cash flows - */ -export function netPresentValue(cashFlows: number[], discountRate: number): number { - return cashFlows.reduce((npv, cashFlow, index) => { - return npv + cashFlow / Math.pow(1 + discountRate, index); - }, 0); -} - -/** - * Calculate internal rate of return (IRR) using Newton-Raphson method - */ -export function internalRateOfReturn( - cashFlows: number[], - guess: number = 0.1, - maxIterations: number = 100 -): number { - let rate = guess; - - for (let i = 0; i < maxIterations; i++) { - let npv = 0; - let dnpv = 0; - - for (let j = 0; j < cashFlows.length; j++) { - const cashFlow = cashFlows[j]; - if (cashFlow !== undefined) { - npv += cashFlow / Math.pow(1 + rate, j); - dnpv += (-j * cashFlow) / Math.pow(1 + rate, j + 1); - } - } - - if (Math.abs(npv) < 1e-10) { - break; - } - if (Math.abs(dnpv) < 1e-10) { - break; - } - - rate = rate - npv / dnpv; - } - - return rate; -} - -/** - * Calculate payback period - */ -export function paybackPeriod(initialInvestment: number, cashFlows: number[]): number { - let cumulativeCashFlow = 0; - - for (let i = 0; i < cashFlows.length; i++) { - const cashFlow = cashFlows[i]; - if (cashFlow !== undefined) { - cumulativeCashFlow += cashFlow; - if (cumulativeCashFlow >= initialInvestment) { - return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow; - } - } - } - - return -1; // Never pays back -} - -/** - * Calculate compound interest - */ -export function compoundInterest( - principal: number, - rate: number, - periods: number, - compoundingFrequency: number = 1 -): number { - return principal * Math.pow(1 + rate / compoundingFrequency, compoundingFrequency * periods); -} - -/** - * Calculate effective annual rate - */ -export function effectiveAnnualRate(nominalRate: number, compoundingFrequency: number): number { - return Math.pow(1 + nominalRate / compoundingFrequency, compoundingFrequency) - 1; -} - -/** - * Calculate bond price given yield - */ -export function bondPrice( - faceValue: number, - couponRate: number, - yieldToMaturity: number, - periodsToMaturity: number, - paymentsPerYear: number = 2 -): number { - const couponPayment = (faceValue * couponRate) / paymentsPerYear; - const discountRate = yieldToMaturity / paymentsPerYear; - - let price = 0; - - // Present value of coupon payments - for (let i = 1; i <= periodsToMaturity; i++) { - price += couponPayment / Math.pow(1 + discountRate, i); - } - - // Present value of face value - price += faceValue / Math.pow(1 + discountRate, periodsToMaturity); - - return price; -} - -/** - * Calculate bond yield given price (Newton-Raphson approximation) - */ -export function bondYield( - price: number, - faceValue: number, - couponRate: number, - periodsToMaturity: number, - paymentsPerYear: number = 2, - guess: number = 0.05 -): number { - let yield_ = guess; - const maxIterations = 100; - const tolerance = 1e-8; - - for (let i = 0; i < maxIterations; i++) { - const calculatedPrice = bondPrice( - faceValue, - couponRate, - yield_, - periodsToMaturity, - paymentsPerYear - ); - const diff = calculatedPrice - price; - - if (Math.abs(diff) < tolerance) { - break; - } - - // Numerical derivative - const delta = 0.0001; - const priceUp = bondPrice( - faceValue, - couponRate, - yield_ + delta, - periodsToMaturity, - paymentsPerYear - ); - const derivative = (priceUp - calculatedPrice) / delta; - - if (Math.abs(derivative) < tolerance) { - break; - } - - yield_ = yield_ - diff / derivative; - } - - return yield_; -} - -/** - * Calculate duration (Macaulay duration) - */ -export function macaulayDuration( - faceValue: number, - couponRate: number, - yieldToMaturity: number, - periodsToMaturity: number, - paymentsPerYear: number = 2 -): number { - const couponPayment = (faceValue * couponRate) / paymentsPerYear; - const discountRate = yieldToMaturity / paymentsPerYear; - const bondPriceValue = bondPrice( - faceValue, - couponRate, - yieldToMaturity, - periodsToMaturity, - paymentsPerYear - ); - - let weightedTime = 0; - - // Weighted time of coupon payments - for (let i = 1; i <= periodsToMaturity; i++) { - const presentValue = couponPayment / Math.pow(1 + discountRate, i); - weightedTime += (i * presentValue) / bondPriceValue; - } - - // Weighted time of face value - const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity); - weightedTime += (periodsToMaturity * faceValuePV) / bondPriceValue; - - return weightedTime / paymentsPerYear; // Convert to years -} - -/** - * Calculate modified duration - */ -export function modifiedDuration( - faceValue: number, - couponRate: number, - yieldToMaturity: number, - periodsToMaturity: number, - paymentsPerYear: number = 2 -): number { - const macDuration = macaulayDuration( - faceValue, - couponRate, - yieldToMaturity, - periodsToMaturity, - paymentsPerYear - ); - return macDuration / (1 + yieldToMaturity / paymentsPerYear); -} - -/** - * Calculate bond convexity - */ -export function bondConvexity( - faceValue: number, - couponRate: number, - yieldToMaturity: number, - periodsToMaturity: number, - paymentsPerYear: number = 2 -): number { - const couponPayment = (faceValue * couponRate) / paymentsPerYear; - const discountRate = yieldToMaturity / paymentsPerYear; - - let convexity = 0; - const bondPriceValue = bondPrice( - faceValue, - couponRate, - yieldToMaturity, - periodsToMaturity, - paymentsPerYear - ); - - for (let i = 1; i <= periodsToMaturity; i++) { - const presentValue = couponPayment / Math.pow(1 + discountRate, i); - convexity += (i * (i + 1) * presentValue) / Math.pow(1 + discountRate, 2); - } - - const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity); - convexity += - (periodsToMaturity * (periodsToMaturity + 1) * faceValuePV) / Math.pow(1 + discountRate, 2); - - return convexity / (bondPriceValue * paymentsPerYear * paymentsPerYear); -} - -/** - * Calculate dollar duration - */ -export function dollarDuration( - faceValue: number, - couponRate: number, - yieldToMaturity: number, - periodsToMaturity: number, - paymentsPerYear: number = 2, - basisPointChange: number = 0.01 // 1 basis point = 0.01% -): number { - const modifiedDur = modifiedDuration( - faceValue, - couponRate, - yieldToMaturity, - periodsToMaturity, - paymentsPerYear - ); - const bondPriceValue = bondPrice( - faceValue, - couponRate, - yieldToMaturity, - periodsToMaturity, - paymentsPerYear - ); - return modifiedDur * bondPriceValue * basisPointChange; -} - -/** - * Calculate accrued interest - */ -export function accruedInterest( - faceValue: number, - couponRate: number, - daysSinceLastCoupon: number, - daysInCouponPeriod: number -): number { - return faceValue * couponRate * (daysSinceLastCoupon / daysInCouponPeriod); -} - -/** - * Calculate clean price - */ -export function cleanPrice(dirtyPrice: number, accruedInterestValue: number): number { - return dirtyPrice - accruedInterestValue; -} - -/** - * Calculate dirty price - */ -export function dirtyPrice(cleanPriceValue: number, accruedInterestValue: number): number { - return cleanPriceValue + accruedInterestValue; -} - -/** - * Calculate dividend discount model (DDM) - */ -export function dividendDiscountModel( - currentDividend: number, - growthRate: number, - discountRate: number -): number { - if (discountRate <= growthRate) { - return NaN; - } // Indeterminate - return (currentDividend * (1 + growthRate)) / (discountRate - growthRate); -} - -/** - * Calculate weighted average cost of capital (WACC) - */ -export function weightedAverageCostOfCapital( - costOfEquity: number, - costOfDebt: number, - equityWeight: number, - debtWeight: number, - taxRate: number -): number { - return equityWeight * costOfEquity + debtWeight * costOfDebt * (1 - taxRate); -} - -/** - * Calculate capital asset pricing model (CAPM) - */ -export function capitalAssetPricingModel( - riskFreeRate: number, - beta: number, - marketRiskPremium: number -): number { - return riskFreeRate + beta * marketRiskPremium; -} - -/** - * Calculate hurdle rate - */ -export function hurdleRate(costOfCapital: number, riskPremium: number): number { - return costOfCapital + riskPremium; -} - -/** - * Calculate degree of operating leverage (DOL) - */ -export function degreeOfOperatingLeverage( - contributionMargin: number, - operatingIncome: number -): number { - return contributionMargin / operatingIncome; -} - -/** - * Calculate degree of financial leverage (DFL) - */ -export function degreeOfFinancialLeverage(ebit: number, earningsBeforeTax: number): number { - return ebit / earningsBeforeTax; -} - -/** - * Calculate degree of total leverage (DTL) - */ -export function degreeOfTotalLeverage(dol: number, dfl: number): number { - return dol * dfl; -} - -/** - * Calculate economic value added (EVA) - */ -export function economicValueAdded( - netOperatingProfitAfterTax: number, - capitalInvested: number, - wacc: number -): number { - return netOperatingProfitAfterTax - capitalInvested * wacc; -} diff --git a/libs/calculations/src/legacy/index.ts b/libs/calculations/src/legacy/index.ts deleted file mode 100644 index f4925f75..00000000 --- a/libs/calculations/src/legacy/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** Opt-in historical APIs, not aliases for the reviewed core. See the package migration notes. */ -export * as basic from './basic-calculations'; -export * as indicators from './technical-indicators'; -export * as risk from './risk-metrics'; -export * as performance from './performance-metrics'; diff --git a/libs/calculations/src/legacy/performance-metrics.ts b/libs/calculations/src/legacy/performance-metrics.ts deleted file mode 100644 index 36437ee8..00000000 --- a/libs/calculations/src/legacy/performance-metrics.ts +++ /dev/null @@ -1,941 +0,0 @@ -/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ -import { ulcerIndex } from './risk-metrics'; - -/** - * Performance Metrics and Analysis - * Comprehensive performance measurement tools for trading strategies and portfolios - */ - -// import type { PortfolioMetrics } from '@stock-bot/types'; - -// Define PortfolioMetrics locally until it's added to types library -export interface PortfolioMetrics { - totalValue: number; - totalReturn: number; - totalReturnPercent: number; - dailyReturn: number; - dailyReturnPercent: number; - maxDrawdown: number; - sharpeRatio: number; - beta: number; - alpha: number; - volatility: number; -} - -export interface TradePerformance { - totalTrades: number; - winningTrades: number; - losingTrades: number; - winRate: number; - averageWin: number; - averageLoss: number; - largestWin: number; - largestLoss: number; - profitFactor: number; - expectancy: number; - averageTradeReturn: number; - consecutiveWins: number; - consecutiveLosses: number; -} - -export interface DrawdownAnalysis { - maxDrawdown: number; - maxDrawdownDuration: number; - averageDrawdown: number; - drawdownPeriods: Array<{ - start: Date; - end: Date; - duration: number; - magnitude: number; - }>; -} - -export interface ReturnAnalysis { - totalReturn: number; - annualizedReturn: number; - compoundAnnualGrowthRate: number; - volatility: number; - annualizedVolatility: number; - skewness: number; - kurtosis: number; - bestMonth: number; - worstMonth: number; - positiveMonths: number; - negativeMonths: number; -} - -/** - * Calculate comprehensive trade performance metrics - */ -export function analyzeTradePerformance( - trades: Array<{ pnl: number; date: Date }> -): TradePerformance { - if (trades.length === 0) { - return { - totalTrades: 0, - winningTrades: 0, - losingTrades: 0, - winRate: 0, - averageWin: 0, - averageLoss: 0, - largestWin: 0, - largestLoss: 0, - profitFactor: 0, - expectancy: 0, - averageTradeReturn: 0, - consecutiveWins: 0, - consecutiveLosses: 0, - }; - } - - const winningTrades = trades.filter(trade => trade.pnl > 0); - const losingTrades = trades.filter(trade => trade.pnl < 0); - - const totalWins = winningTrades.reduce((sum, trade) => sum + trade.pnl, 0); - const totalLosses = Math.abs(losingTrades.reduce((sum, trade) => sum + trade.pnl, 0)); - - const averageWin = winningTrades.length > 0 ? totalWins / winningTrades.length : 0; - const averageLoss = losingTrades.length > 0 ? totalLosses / losingTrades.length : 0; - - const largestWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.pnl)) : 0; - const largestLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.pnl)) : 0; - - const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0; - const winRate = winningTrades.length / trades.length; - const expectancy = winRate * averageWin - (1 - winRate) * averageLoss; - - const totalPnL = trades.reduce((sum, trade) => sum + trade.pnl, 0); - const averageTradeReturn = totalPnL / trades.length; - - // Calculate consecutive wins/losses - let consecutiveWins = 0; - let consecutiveLosses = 0; - let currentWinStreak = 0; - let currentLossStreak = 0; - - for (const trade of trades) { - if (trade.pnl > 0) { - currentWinStreak++; - currentLossStreak = 0; - consecutiveWins = Math.max(consecutiveWins, currentWinStreak); - } else if (trade.pnl < 0) { - currentLossStreak++; - currentWinStreak = 0; - consecutiveLosses = Math.max(consecutiveLosses, currentLossStreak); - } - } - - return { - totalTrades: trades.length, - winningTrades: winningTrades.length, - losingTrades: losingTrades.length, - winRate, - averageWin, - averageLoss, - largestWin, - largestLoss, - profitFactor, - expectancy, - averageTradeReturn, - consecutiveWins, - consecutiveLosses, - }; -} - -/** - * Analyze drawdown characteristics - */ -export function analyzeDrawdowns( - equityCurve: Array<{ value: number; date: Date }> -): DrawdownAnalysis { - if (equityCurve.length < 2) { - return { - maxDrawdown: 0, - maxDrawdownDuration: 0, - averageDrawdown: 0, - drawdownPeriods: [], - }; - } - - const first = equityCurve[0]; - if (!first) { - return { maxDrawdown: 0, maxDrawdownDuration: 0, averageDrawdown: 0, drawdownPeriods: [] }; - } - - let peak = first.value; - let peakDate = first.date; - let maxDrawdown = 0; - let maxDrawdownDuration = 0; - - const drawdownPeriods: Array<{ - start: Date; - end: Date; - duration: number; - magnitude: number; - }> = []; - - let currentDrawdownStart: Date | null = null; - const drawdowns: number[] = []; - - for (let i = 1; i < equityCurve.length; i++) { - const current = equityCurve[i]; - if (!current) { - continue; - } - - if (current.value > peak) { - // New peak - end any current drawdown - if (currentDrawdownStart) { - const prev = equityCurve[i - 1]; - if (!prev) { - continue; - } - - const drawdownMagnitude = (peak - prev.value) / peak; - const duration = Math.floor( - (prev.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24) - ); - - drawdownPeriods.push({ - start: currentDrawdownStart, - end: prev.date, - duration, - magnitude: drawdownMagnitude, - }); - - drawdowns.push(drawdownMagnitude); - maxDrawdownDuration = Math.max(maxDrawdownDuration, duration); - currentDrawdownStart = null; - } - - peak = current.value; - peakDate = current.date; - } else { - // In drawdown - if (!currentDrawdownStart) { - currentDrawdownStart = peakDate; - } - - const drawdown = (peak - current.value) / peak; - maxDrawdown = Math.max(maxDrawdown, drawdown); - } - } - - // Handle ongoing drawdown - if (currentDrawdownStart) { - const lastPoint = equityCurve[equityCurve.length - 1]; - if (!lastPoint) { - return { maxDrawdown, maxDrawdownDuration, averageDrawdown: 0, drawdownPeriods }; - } - - const drawdownMagnitude = (peak - lastPoint.value) / peak; - const duration = Math.floor( - (lastPoint.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24) - ); - - drawdownPeriods.push({ - start: currentDrawdownStart, - end: lastPoint.date, - duration, - magnitude: drawdownMagnitude, - }); - - drawdowns.push(drawdownMagnitude); - maxDrawdownDuration = Math.max(maxDrawdownDuration, duration); - } - - const averageDrawdown = - drawdowns.length > 0 ? drawdowns.reduce((sum, dd) => sum + dd, 0) / drawdowns.length : 0; - - return { - maxDrawdown, - maxDrawdownDuration, - averageDrawdown, - drawdownPeriods, - }; -} - -/** - * Analyze return characteristics - */ -export function analyzeReturns( - returns: Array<{ return: number; date: Date }>, - periodsPerYear: number = 252 -): ReturnAnalysis { - if (returns.length === 0) { - return { - totalReturn: 0, - annualizedReturn: 0, - compoundAnnualGrowthRate: 0, - volatility: 0, - annualizedVolatility: 0, - skewness: 0, - kurtosis: 0, - bestMonth: 0, - worstMonth: 0, - positiveMonths: 0, - negativeMonths: 0, - }; - } - - const returnValues = returns.map(r => r.return); - - // Calculate basic statistics - const totalReturn = returnValues.reduce((product, ret) => product * (1 + ret), 1) - 1; - const averageReturn = returnValues.reduce((sum, ret) => sum + ret, 0) / returnValues.length; - const annualizedReturn = Math.pow(1 + averageReturn, periodsPerYear) - 1; - - // Calculate CAGR - const years = returns.length / periodsPerYear; - const cagr = years > 0 ? Math.pow(1 + totalReturn, 1 / years) - 1 : 0; - - // Calculate volatility - const variance = - returnValues.reduce((sum, ret) => sum + Math.pow(ret - averageReturn, 2), 0) / - (returnValues.length - 1); - const volatility = Math.sqrt(variance); - const annualizedVolatility = volatility * Math.sqrt(periodsPerYear); - - // Calculate skewness and kurtosis - const skewness = calculateSkewness(returnValues); - const kurtosis = calculateKurtosis(returnValues); - - // Monthly analysis - const monthlyReturns = aggregateMonthlyReturns(returns); - const bestMonth = monthlyReturns.length > 0 ? Math.max(...monthlyReturns) : 0; - const worstMonth = monthlyReturns.length > 0 ? Math.min(...monthlyReturns) : 0; - const positiveMonths = monthlyReturns.filter(ret => ret > 0).length; - const negativeMonths = monthlyReturns.filter(ret => ret < 0).length; - - return { - totalReturn, - annualizedReturn, - compoundAnnualGrowthRate: cagr, - volatility, - annualizedVolatility, - skewness, - kurtosis, - bestMonth, - worstMonth, - positiveMonths, - negativeMonths, - }; -} - -/** - * Calculate rolling performance metrics - */ -export function calculateRollingMetrics( - returns: number[], - windowSize: number, - metricType: 'sharpe' | 'volatility' | 'return' = 'sharpe' -): number[] { - if (returns.length < windowSize) { - return []; - } - - const rollingMetrics: number[] = []; - - for (let i = windowSize - 1; i < returns.length; i++) { - const window = returns.slice(i - windowSize + 1, i + 1); - - switch (metricType) { - case 'sharpe': - rollingMetrics.push(calculateSharpeRatio(window)); - break; - case 'volatility': - rollingMetrics.push(calculateVolatility(window)); - break; - case 'return': { - const avgReturn = window.reduce((sum, ret) => sum + ret, 0) / window.length; - rollingMetrics.push(avgReturn); - break; - } - } - } - - return rollingMetrics; -} - -/** - * Calculate performance attribution - */ -export function strategyPerformanceAttribution( - portfolioReturns: number[], - benchmarkReturns: number[], - sectorWeights: number[], - sectorReturns: number[] -): { - allocationEffect: number; - selectionEffect: number; - interactionEffect: number; - totalActiveReturn: number; -} { - if (portfolioReturns.length !== benchmarkReturns.length) { - throw new Error('Portfolio and benchmark returns must have same length'); - } - - const portfolioReturn = - portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length; - const benchmarkReturn = - benchmarkReturns.reduce((sum, ret) => sum + ret, 0) / benchmarkReturns.length; - - let allocationEffect = 0; - let selectionEffect = 0; - let interactionEffect = 0; - - for (let i = 0; i < sectorWeights.length; i++) { - const portfolioWeight = sectorWeights[i]; - const sectorReturn = sectorReturns[i]; - if (portfolioWeight === undefined || sectorReturn === undefined) { - continue; - } - - const benchmarkWeight = 1 / sectorWeights.length; // Assuming equal benchmark weights - - // Allocation effect: (portfolio weight - benchmark weight) * (benchmark sector return - benchmark return) - allocationEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - benchmarkReturn); - - // Selection effect: benchmark weight * (portfolio sector return - benchmark sector return) - selectionEffect += benchmarkWeight * (sectorReturn - sectorReturn); // Simplified - - // Interaction effect: (portfolio weight - benchmark weight) * (portfolio sector return - benchmark sector return) - interactionEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - sectorReturn); // Simplified - } - - const totalActiveReturn = portfolioReturn - benchmarkReturn; - - return { - allocationEffect, - selectionEffect, - interactionEffect, - totalActiveReturn, - }; -} - -/** - * Calculate Omega ratio - */ -export function omegaRatio(returns: number[], threshold: number = 0): number { - if (returns.length === 0) { - return 0; - } - - const gains = returns - .filter(ret => ret > threshold) - .reduce((sum, ret) => sum + (ret - threshold), 0); - const losses = returns - .filter(ret => ret < threshold) - .reduce((sum, ret) => sum + Math.abs(ret - threshold), 0); - - return losses === 0 ? Infinity : gains / losses; -} - -/** - * Calculate gain-to-pain ratio - */ -export function gainToPainRatio(returns: number[]): number { - if (returns.length === 0) { - return 0; - } - - const totalGain = returns.reduce((sum, ret) => sum + ret, 0); - const totalPain = returns.filter(ret => ret < 0).reduce((sum, ret) => sum + Math.abs(ret), 0); - - return totalPain === 0 ? (totalGain > 0 ? Infinity : 0) : totalGain / totalPain; -} - -/** - * Calculate Martin ratio (modified Sharpe with downside deviation) - */ -export function martinRatio(returns: number[], riskFreeRate: number = 0): number { - if (returns.length === 0) { - return 0; - } - - const averageReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const downsideReturns = returns.filter(ret => ret < riskFreeRate); - - if (downsideReturns.length === 0) { - return Infinity; - } - - const downsideDeviation = Math.sqrt( - downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length - ); - - return downsideDeviation === 0 ? Infinity : (averageReturn - riskFreeRate) / downsideDeviation; -} - -/** - * Calculate comprehensive portfolio metrics - */ -export function calculateStrategyMetrics( - equityCurve: Array<{ value: number; date: Date }>, - benchmarkReturns?: number[], - riskFreeRate: number = 0.02 -): PortfolioMetrics { - if (equityCurve.length < 2) { - return { - totalValue: 0, - totalReturn: 0, - totalReturnPercent: 0, - dailyReturn: 0, - dailyReturnPercent: 0, - maxDrawdown: 0, - sharpeRatio: 0, - beta: 0, - alpha: 0, - volatility: 0, - }; - } - - const returns = []; - for (let i = 1; i < equityCurve.length; i++) { - const current = equityCurve[i]; - const previous = equityCurve[i - 1]; - if (!current || !previous) { - continue; - } - - const ret = (current.value - previous.value) / previous.value; - returns.push(ret); - } - - const lastPoint = equityCurve[equityCurve.length - 1]; - const firstPoint = equityCurve[0]; - if (!lastPoint || !firstPoint) { - return { - totalValue: 0, - totalReturn: 0, - totalReturnPercent: 0, - dailyReturn: 0, - dailyReturnPercent: 0, - maxDrawdown: 0, - sharpeRatio: 0, - beta: 0, - alpha: 0, - volatility: 0, - }; - } - - const totalValue = lastPoint.value; - const totalReturn = totalValue - firstPoint.value; - const totalReturnPercent = (totalReturn / firstPoint.value) * 100; - - const dailyReturn = returns[returns.length - 1] || 0; - const dailyReturnPercent = dailyReturn * 100; - - const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown; - const sharpeRatio = calculateSharpeRatio(returns, riskFreeRate); - const volatility = calculateVolatility(returns); - - let beta = 0; - let alpha = 0; - - if (benchmarkReturns && benchmarkReturns.length === returns.length) { - beta = calculateBeta(returns, benchmarkReturns); - alpha = calculateAlpha(returns, benchmarkReturns, riskFreeRate); - } - - return { - totalValue, - totalReturn, - totalReturnPercent, - dailyReturn, - dailyReturnPercent, - maxDrawdown, - sharpeRatio, - beta, - alpha, - volatility, - }; -} - -/** - * Calculate Calmar Ratio - */ -export function calmarRatio( - returns: number[], - equityCurve: Array<{ value: number; date: Date }>, - riskFreeRate: number = 0 -): number { - const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown; - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - - return maxDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / maxDrawdown; -} - -/** - * Calculate Sterling Ratio - */ -export function sterlingRatio( - returns: number[], - equityCurve: Array<{ value: number; date: Date }>, - riskFreeRate: number = 0 -): number { - const averageDrawdown = analyzeDrawdowns(equityCurve).averageDrawdown; - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - - return averageDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / averageDrawdown; -} - -/** - * Calculate Information Ratio - */ -export function informationRatio(portfolioReturns: number[], benchmarkReturns: number[]): number { - if (portfolioReturns.length !== benchmarkReturns.length) { - throw new Error('Portfolio and benchmark returns must have the same length.'); - } - - const excessReturns = portfolioReturns.map((portfolioReturn, index) => { - const benchmark = benchmarkReturns[index]; - return benchmark !== undefined ? portfolioReturn - benchmark : 0; - }); - const trackingError = calculateVolatility(excessReturns); - const avgExcessReturn = excessReturns.reduce((sum, ret) => sum + ret, 0) / excessReturns.length; - - return trackingError === 0 ? 0 : avgExcessReturn / trackingError; -} - -// Treynor Ratio is already exported from risk-metrics - -/** - * Calculate Jensen's Alpha (same as Alpha, but included for clarity) - */ -export function jensensAlpha( - portfolioReturns: number[], - marketReturns: number[], - riskFreeRate: number -): number { - return calculateAlpha(portfolioReturns, marketReturns, riskFreeRate); -} - -/** - * Calculate Capture Ratio (Up Capture and Down Capture) - */ -export function captureRatio( - portfolioReturns: number[], - benchmarkReturns: number[] -): { upCaptureRatio: number; downCaptureRatio: number } { - let upCapture = 0; - let downCapture = 0; - let upMarketPeriods = 0; - let downMarketPeriods = 0; - - for (let i = 0; i < portfolioReturns.length; i++) { - const benchmarkReturn = benchmarkReturns[i]; - const portfolioReturn = portfolioReturns[i]; - if (benchmarkReturn === undefined || portfolioReturn === undefined) { - continue; - } - - if (benchmarkReturn > 0) { - upCapture += portfolioReturn; - upMarketPeriods++; - } else if (benchmarkReturn < 0) { - downCapture += portfolioReturn; - downMarketPeriods++; - } - } - - const upCaptureRatio = - upMarketPeriods > 0 - ? upCapture / - upMarketPeriods / - (benchmarkReturns.filter(r => r > 0).reduce((sum, r) => sum + r, 0) / upMarketPeriods) - : 0; - const downCaptureRatio = - downMarketPeriods > 0 - ? downCapture / - downMarketPeriods / - (benchmarkReturns.filter(r => r < 0).reduce((sum, r) => sum + r, 0) / downMarketPeriods) - : 0; - - return { upCaptureRatio, downCaptureRatio }; -} - -/** - * Calculate Sortino Ratio - */ -export function sortinoRatio(returns: number[], riskFreeRate: number = 0): number { - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const downsideReturns = returns.filter(ret => ret < riskFreeRate); - const downsideDeviation = Math.sqrt( - downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length - ); - - return downsideDeviation === 0 ? 0 : (avgReturn - riskFreeRate) / downsideDeviation; -} - -/** - * Calculate Tail Ratio - */ -export function tailRatio(returns: number[], tailPercent: number = 0.1): number { - const numReturns = returns.length; - const tailSize = Math.floor(numReturns * tailPercent); - - if (tailSize === 0) { - return 0; - } - - const sortedReturns = [...returns].sort((a, b) => a - b); - const worstTail = sortedReturns.slice(0, tailSize); - const bestTail = sortedReturns.slice(numReturns - tailSize); - - const avgWorst = worstTail.reduce((sum, ret) => sum + ret, 0) / tailSize; - const avgBest = bestTail.reduce((sum, ret) => sum + ret, 0) / tailSize; - - return avgWorst === 0 ? 0 : avgBest / Math.abs(avgWorst); -} - -/** - * Calculate Rolling Beta - */ -export function calculateRollingBeta( - portfolioReturns: number[], - marketReturns: number[], - windowSize: number -): number[] { - if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) { - return []; - } - - const rollingBetas: number[] = []; - - for (let i = windowSize; i <= portfolioReturns.length; i++) { - const portfolioWindow = portfolioReturns.slice(i - windowSize, i); - const marketWindow = marketReturns.slice(i - windowSize, i); - rollingBetas.push(calculateBeta(portfolioWindow, marketWindow)); - } - - return rollingBetas; -} - -/** - * Calculate Ulcer Performance Index (UPI) - */ -export function ulcerPerformanceIndex( - returns: number[], - equityCurve: Array<{ value: number; date: Date }>, - riskFreeRate: number = 0 -): number { - const ui = ulcerIndex(equityCurve); - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - - return ui === 0 ? 0 : (avgReturn - riskFreeRate) / ui; -} - -/** - * Calculate Rolling Alpha - */ -export function calculateRollingAlpha( - portfolioReturns: number[], - marketReturns: number[], - riskFreeRate: number, - windowSize: number -): number[] { - if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) { - return []; - } - - const rollingAlphas: number[] = []; - - for (let i = windowSize; i <= portfolioReturns.length; i++) { - const portfolioWindow = portfolioReturns.slice(i - windowSize, i); - const marketWindow = marketReturns.slice(i - windowSize, i); - rollingAlphas.push(calculateAlpha(portfolioWindow, marketWindow, riskFreeRate)); - } - - return rollingAlphas; -} - -/** - * Calculate Time Weighted Rate of Return (TWRR) - */ -export function timeWeightedRateOfReturn( - cashFlows: Array<{ amount: number; date: Date; value: number }> -): number { - if (cashFlows.length < 2) { - return 0; - } - - const first = cashFlows[0]; - if (!first) { - return 0; - } - - let totalReturn = 1; - let previousValue = first.value; - - for (let i = 1; i < cashFlows.length; i++) { - const current = cashFlows[i]; - if (!current) { - continue; - } - - const periodReturn = - (current.value - previousValue - current.amount) / (previousValue + current.amount); - totalReturn *= 1 + periodReturn; - previousValue = current.value; - } - - return totalReturn - 1; -} - -/** - * Calculate Money Weighted Rate of Return (MWRR) - Approximation using IRR - */ -export function moneyWeightedRateOfReturn( - cashFlows: Array<{ amount: number; date: Date; value: number }> -): number { - if (cashFlows.length === 0) { - return 0; - } - - const first = cashFlows[0]; - if (!first) { - return 0; - } - - // Approximate MWRR using Internal Rate of Return (IRR) - // This requires a numerical method or library for accurate IRR calculation - // This is a simplified example and may not be accurate for all cases - - let totalCashFlow = 0; - let totalWeightedCashFlow = 0; - const startDate = first.date.getTime(); - - for (const cf of cashFlows) { - const timeDiff = (cf.date.getTime() - startDate) / (1000 * 60 * 60 * 24 * 365); // Years - totalCashFlow += cf.amount; - totalWeightedCashFlow += cf.amount * timeDiff; - } - - // Simplified approximation: MWRR โ‰ˆ totalCashFlow / totalWeightedCashFlow - 1 - return totalWeightedCashFlow === 0 ? 0 : totalCashFlow / totalWeightedCashFlow - 1; -} - -// Helper functions - -function calculateSharpeRatio(returns: number[], riskFreeRate: number = 0): number { - if (returns.length < 2) { - return 0; - } - - const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / (returns.length - 1); - const stdDev = Math.sqrt(variance); - - return stdDev === 0 ? 0 : (avgReturn - riskFreeRate) / stdDev; -} - -function calculateVolatility(returns: number[]): number { - if (returns.length < 2) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1); - - return Math.sqrt(variance); -} - -function calculateBeta(portfolioReturns: number[], marketReturns: number[]): number { - if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) { - return 0; - } - - const portfolioMean = - portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length; - const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length; - - let covariance = 0; - let marketVariance = 0; - - for (let i = 0; i < portfolioReturns.length; i++) { - const portfolioReturn = portfolioReturns[i]; - const marketReturn = marketReturns[i]; - if (portfolioReturn === undefined || marketReturn === undefined) { - continue; - } - - const portfolioDiff = portfolioReturn - portfolioMean; - const marketDiff = marketReturn - marketMean; - - covariance += portfolioDiff * marketDiff; - marketVariance += marketDiff * marketDiff; - } - - covariance /= portfolioReturns.length - 1; - marketVariance /= marketReturns.length - 1; - - return marketVariance === 0 ? 0 : covariance / marketVariance; -} - -function calculateAlpha( - portfolioReturns: number[], - marketReturns: number[], - riskFreeRate: number -): number { - const portfolioMean = - portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length; - const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length; - const beta = calculateBeta(portfolioReturns, marketReturns); - - return portfolioMean - (riskFreeRate + beta * (marketMean - riskFreeRate)); -} - -function calculateSkewness(returns: number[]): number { - if (returns.length < 3) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - if (stdDev === 0) { - return 0; - } - - const skew = - returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length; - - return skew; -} - -function calculateKurtosis(returns: number[]): number { - if (returns.length < 4) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - if (stdDev === 0) { - return 0; - } - - const kurt = - returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length; - - return kurt - 3; // Excess kurtosis -} - -function aggregateMonthlyReturns(returns: Array<{ return: number; date: Date }>): number[] { - const monthlyReturns: { [key: string]: number } = {}; - - for (const ret of returns) { - const monthKey = `${ret.date.getFullYear()}-${ret.date.getMonth()}`; - if (!monthlyReturns[monthKey]) { - monthlyReturns[monthKey] = 1; - } - monthlyReturns[monthKey] *= 1 + ret.return; - } - - return Object.values(monthlyReturns).map(cumReturn => cumReturn - 1); -} diff --git a/libs/calculations/src/legacy/risk-metrics.ts b/libs/calculations/src/legacy/risk-metrics.ts deleted file mode 100644 index 9987d984..00000000 --- a/libs/calculations/src/legacy/risk-metrics.ts +++ /dev/null @@ -1,482 +0,0 @@ -/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ -/** - * Risk Metrics and Analysis - * Comprehensive risk measurement tools for portfolio and trading analysis - */ - -import type { RiskMetrics } from '@stock-bot/types'; - -/** - * Calculate Value at Risk (VaR) using historical simulation - */ -export function valueAtRisk(returns: number[], confidenceLevel: number = 0.95): number { - if (returns.length === 0) { - return 0; - } - - const sortedReturns = [...returns].sort((a, b) => a - b); - const index = Math.floor((1 - confidenceLevel) * sortedReturns.length); - - return sortedReturns[index] || 0; -} - -/** - * Calculate Conditional Value at Risk (CVaR/Expected Shortfall) - */ -export function conditionalValueAtRisk(returns: number[], confidenceLevel: number = 0.95): number { - if (returns.length === 0) { - return 0; - } - - const sortedReturns = [...returns].sort((a, b) => a - b); - const cutoffIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length); - - if (cutoffIndex === 0) { - return sortedReturns[0] || 0; - } - - const tailReturns = sortedReturns.slice(0, cutoffIndex); - return tailReturns.reduce((sum, ret) => sum + ret, 0) / tailReturns.length; -} - -/** - * Calculate parametric VaR using normal distribution - */ -export function parametricVaR( - returns: number[], - confidenceLevel: number = 0.95, - portfolioValue: number = 1 -): number { - if (returns.length === 0) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1); - const stdDev = Math.sqrt(variance); - - // Z-score for confidence level (normal distribution) - const zScore = getZScore(confidenceLevel); - - return portfolioValue * (mean - zScore * stdDev); -} - -/** - * Calculate maximum drawdown - */ -export function maxDrawdown(equityCurve: number[]): number { - if (equityCurve.length < 2) { - return 0; - } - - let maxDD = 0; - const first = equityCurve[0]; - if (first === undefined) { - return 0; - } - - let peak = first; - - for (let i = 1; i < equityCurve.length; i++) { - const current = equityCurve[i]; - if (current === undefined) { - continue; - } - - if (current > peak) { - peak = current; - } else { - const drawdown = (peak - current) / peak; - maxDD = Math.max(maxDD, drawdown); - } - } - - return maxDD; -} - -/** - * Calculate downside deviation - */ -export function downsideDeviation(returns: number[], targetReturn: number = 0): number { - if (returns.length === 0) { - return 0; - } - - const downsideReturns = returns.filter(ret => ret < targetReturn); - - if (downsideReturns.length === 0) { - return 0; - } - - const sumSquaredDownside = downsideReturns.reduce( - (sum, ret) => sum + Math.pow(ret - targetReturn, 2), - 0 - ); - - return Math.sqrt(sumSquaredDownside / returns.length); -} - -/** - * Calculate Sharpe ratio - */ -export function sharpeRatio(returns: number[], riskFreeRate: number = 0): number { - if (returns.length < 2) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1); - const stdDev = Math.sqrt(variance); - - if (stdDev === 0) { - return 0; - } - - return (mean - riskFreeRate) / stdDev; -} - -/** - * Calculate beta coefficient - */ -export function beta(portfolioReturns: number[], marketReturns: number[]): number { - if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) { - return 0; - } - - const n = portfolioReturns.length; - const portfolioMean = portfolioReturns.reduce((sum, ret) => sum + ret, 0) / n; - const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / n; - - let covariance = 0; - let marketVariance = 0; - - for (let i = 0; i < n; i++) { - const portfolioReturn = portfolioReturns[i]; - const marketReturn = marketReturns[i]; - if (portfolioReturn === undefined || marketReturn === undefined) { - continue; - } - - const portfolioDiff = portfolioReturn - portfolioMean; - const marketDiff = marketReturn - marketMean; - - covariance += portfolioDiff * marketDiff; - marketVariance += marketDiff * marketDiff; - } - - return marketVariance === 0 ? 0 : covariance / marketVariance; -} - -/** - * Calculate alpha - */ -export function alpha( - portfolioReturns: number[], - marketReturns: number[], - riskFreeRate: number = 0 -): number { - const portfolioMean = - portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length; - const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length; - const portfolioBeta = beta(portfolioReturns, marketReturns); - - return portfolioMean - (riskFreeRate + portfolioBeta * (marketMean - riskFreeRate)); -} - -/** - * Calculate Treynor ratio - */ -export function treynorRatio( - portfolioReturns: number[], - marketReturns: number[], - riskFreeRate: number = 0 -): number { - const portfolioBeta = beta(portfolioReturns, marketReturns); - - if (portfolioBeta === 0) { - return 0; - } - - const portfolioMean = - portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length; - return (portfolioMean - riskFreeRate) / portfolioBeta; -} - -/** - * Calculate tracking error - */ -export function trackingError(portfolioReturns: number[], benchmarkReturns: number[]): number { - if (portfolioReturns.length !== benchmarkReturns.length || portfolioReturns.length === 0) { - return 0; - } - - const activeReturns = portfolioReturns.map((ret, i) => { - const benchmark = benchmarkReturns[i]; - return benchmark !== undefined ? ret - benchmark : 0; - }); - const mean = activeReturns.reduce((sum, ret) => sum + ret, 0) / activeReturns.length; - - const variance = - activeReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / - (activeReturns.length - 1); - - return Math.sqrt(variance); -} - -/** - * Calculate volatility (standard deviation of returns) - */ -export function volatility(returns: number[]): number { - if (returns.length < 2) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = - returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1); - - return Math.sqrt(variance); -} - -/** - * Calculate annualized volatility - */ -export function annualizedVolatility(returns: number[], periodsPerYear: number = 252): number { - return volatility(returns) * Math.sqrt(periodsPerYear); -} - -/** - * Calculate skewness (measure of asymmetry) - */ -export function skewness(returns: number[]): number { - if (returns.length < 3) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - if (stdDev === 0) { - return 0; - } - - const skew = - returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length; - - return skew; -} - -/** - * Calculate kurtosis (measure of tail heaviness) - */ -export function kurtosis(returns: number[]): number { - if (returns.length < 4) { - return 0; - } - - const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - if (stdDev === 0) { - return 0; - } - - const kurt = - returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length; - - return kurt - 3; // Excess kurtosis (subtract 3 for normal distribution baseline) -} - -/** - * Calculate comprehensive risk metrics - */ -export function calculateRiskMetrics( - returns: number[], - equityCurve: number[], - marketReturns?: number[], - riskFreeRate: number = 0 -): RiskMetrics { - if (returns.length === 0) { - return { - var95: 0, - var99: 0, - cvar95: 0, - maxDrawdown: 0, - volatility: 0, - downside_deviation: 0, - calmar_ratio: 0, - sortino_ratio: 0, - beta: 0, - alpha: 0, - sharpeRatio: 0, - treynorRatio: 0, - trackingError: 0, - informationRatio: 0, - }; - } - - const portfolioVolatility = volatility(returns); - const portfolioMean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length; - // Calculate VaR - const var95Value = valueAtRisk(returns, 0.95); - const var99Value = valueAtRisk(returns, 0.99); - const cvar95Value = conditionalValueAtRisk(returns, 0.95); - - // Calculate max drawdown - const maxDD = maxDrawdown(equityCurve); - - // Calculate downside deviation - const downsideDeviationValue = downsideDeviation(returns); - // Calculate ratios - const calmarRatio = maxDD > 0 ? portfolioMean / maxDD : 0; - const sortinoRatio = - downsideDeviationValue > 0 ? (portfolioMean - riskFreeRate) / downsideDeviationValue : 0; - const sharpeRatio = - portfolioVolatility > 0 ? (portfolioMean - riskFreeRate) / portfolioVolatility : 0; - - let portfolioBeta = 0; - let portfolioAlpha = 0; - let portfolioTreynorRatio = 0; - let portfolioTrackingError = 0; - let informationRatio = 0; - - if (marketReturns && marketReturns.length === returns.length) { - portfolioBeta = beta(returns, marketReturns); - portfolioAlpha = alpha(returns, marketReturns, riskFreeRate); - portfolioTreynorRatio = treynorRatio(returns, marketReturns, riskFreeRate); - portfolioTrackingError = trackingError(returns, marketReturns); - informationRatio = portfolioTrackingError > 0 ? portfolioAlpha / portfolioTrackingError : 0; - } - return { - var95: var95Value, - var99: var99Value, - cvar95: cvar95Value, - maxDrawdown: maxDD, - volatility: portfolioVolatility, - downside_deviation: downsideDeviationValue, - calmar_ratio: calmarRatio, - sortino_ratio: sortinoRatio, - beta: portfolioBeta, - alpha: portfolioAlpha, - sharpeRatio, - treynorRatio: portfolioTreynorRatio, - trackingError: portfolioTrackingError, - informationRatio, - }; -} - -/** - * Helper function to get Z-score for confidence level - * This implementation handles arbitrary confidence levels - */ -function getZScore(confidenceLevel: number): number { - // First check our lookup table for common values (more precise) - const zScores: { [key: string]: number } = { - '0.90': 1.282, - '0.95': 1.645, - '0.975': 1.96, - '0.99': 2.326, - '0.995': 2.576, - }; - - const key = confidenceLevel.toString(); - if (zScores[key]) { - return zScores[key]; - } - - // For arbitrary confidence levels, use approximation - if (confidenceLevel < 0.5) { - return -getZScore(1 - confidenceLevel); - } - - if (confidenceLevel >= 0.999) { - return 3.09; - } // Cap at 99.9% for numerical stability - - // Approximation of inverse normal CDF - const y = Math.sqrt(-2.0 * Math.log(1.0 - confidenceLevel)); - return ( - y - - (2.515517 + 0.802853 * y + 0.010328 * y * y) / - (1.0 + 1.432788 * y + 0.189269 * y * y + 0.001308 * y * y * y) - ); -} - -/** - * Calculate portfolio risk contribution - */ -export function riskContribution( - weights: number[], - covarianceMatrix: number[][], - portfolioVolatility: number -): number[] { - const n = weights.length; - const contributions: number[] = []; - - for (let i = 0; i < n; i++) { - let marginalContribution = 0; - const row = covarianceMatrix[i]; - if (!row) { - continue; - } - - for (let j = 0; j < n; j++) { - const weight = weights[j]; - const covariance = row[j]; - if (weight !== undefined && covariance !== undefined) { - marginalContribution += weight * covariance; - } - } - - const weight = weights[i]; - if (weight !== undefined && portfolioVolatility !== 0) { - const contribution = (weight * marginalContribution) / Math.pow(portfolioVolatility, 2); - contributions.push(contribution); - } - } - - return contributions; -} - -/** - * Calculate Ulcer Index - */ -export function ulcerIndex(equityCurve: Array<{ value: number; date: Date }>): number { - if (equityCurve.length === 0) { - return 0; - } - - let sumSquaredDrawdown = 0; - const first = equityCurve[0]; - if (!first) { - return 0; - } - - let peak = first.value; - - for (const point of equityCurve) { - peak = Math.max(peak, point.value); - const drawdownPercent = ((peak - point.value) / peak) * 100; - sumSquaredDrawdown += drawdownPercent * drawdownPercent; - } - - return Math.sqrt(sumSquaredDrawdown / equityCurve.length); -} - -/** - * Calculate risk-adjusted return (RAR) - */ -export function riskAdjustedReturn( - portfolioReturn: number, - portfolioRisk: number, - riskFreeRate: number = 0 -): number { - if (portfolioRisk === 0) { - return 0; - } - return (portfolioReturn - riskFreeRate) / portfolioRisk; -} diff --git a/libs/calculations/src/legacy/technical-indicators.ts b/libs/calculations/src/legacy/technical-indicators.ts deleted file mode 100644 index 1fb716dc..00000000 --- a/libs/calculations/src/legacy/technical-indicators.ts +++ /dev/null @@ -1,1340 +0,0 @@ -/** Legacy calculation API retained for migration/research; see ../../README.md before use. */ -import { defined } from '@stock-bot/invariants'; -/** - * Technical Indicators - * Comprehensive set of technical analysis indicators - */ - -import type { OHLCV } from '@stock-bot/types'; - -/** - * Simple Moving Average - */ -export function sma(values: number[], period: number): number[] { - if (period > values.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < values.length; i++) { - const sum = values.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - result.push(sum / period); - } - - return result; -} - -/** - * Exponential Moving Average - */ -export function ema(values: number[], period: number): number[] { - if (period > values.length) { - return []; - } - - const result: number[] = []; - const multiplier = 2 / (period + 1); - - // Start with SMA for first value - let ema = values.slice(0, period).reduce((a, b) => a + b, 0) / period; - result.push(ema); - - for (let i = period; i < values.length; i++) { - const value = values[i]; - if (value !== undefined) { - ema = value * multiplier + ema * (1 - multiplier); - result.push(ema); - } - } - - return result; -} - -/** - * Relative Strength Index (RSI) - */ -export function rsi(prices: number[], period: number = 14): number[] { - if (period >= prices.length) { - return []; - } - - const gains: number[] = []; - const losses: number[] = []; - - // Calculate gains and losses - for (let i = 1; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - 1]; - if (current !== undefined && previous !== undefined) { - const change = current - previous; - gains.push(change > 0 ? change : 0); - losses.push(change < 0 ? Math.abs(change) : 0); - } - } - - const result: number[] = []; - - // Calculate RSI - for (let i = period - 1; i < gains.length; i++) { - const avgGain = gains.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0) / period; - const avgLoss = losses.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0) / period; - - if (avgLoss === 0) { - result.push(100); - } else { - const rs = avgGain / avgLoss; - const rsiValue = 100 - 100 / (1 + rs); - result.push(rsiValue); - } - } - - return result; -} - -/** - * Moving Average Convergence Divergence (MACD) - */ -export function macd( - prices: number[], - fastPeriod: number = 12, - slowPeriod: number = 26, - signalPeriod: number = 9 -): { macd: number[]; signal: number[]; histogram: number[] } { - const fastEMA = ema(prices, fastPeriod); - const slowEMA = ema(prices, slowPeriod); - - const macdLine: number[] = []; - const startIndex = slowPeriod - fastPeriod; - - for (let i = 0; i < fastEMA.length - startIndex; i++) { - const fastValue = fastEMA[i + startIndex]; - const slowValue = slowEMA[i]; - if (fastValue !== undefined && slowValue !== undefined) { - macdLine.push(fastValue - slowValue); - } - } - - const signalLine = ema(macdLine, signalPeriod); - const histogram: number[] = []; - - const signalStartIndex = signalPeriod - 1; - for (let i = 0; i < signalLine.length; i++) { - const macdValue = macdLine[i + signalStartIndex]; - const signalValue = signalLine[i]; - if (macdValue !== undefined && signalValue !== undefined) { - histogram.push(macdValue - signalValue); - } - } - - return { - macd: macdLine, - signal: signalLine, - histogram: histogram, - }; -} - -/** - * Bollinger Bands - */ -export function bollingerBands( - prices: number[], - period: number = 20, - standardDeviations: number = 2 -): { upper: number[]; middle: number[]; lower: number[] } { - const middle = sma(prices, period); - const upper: number[] = []; - const lower: number[] = []; - - for (let i = period - 1; i < prices.length; i++) { - const slice = prices.slice(i - period + 1, i + 1); - const mean = slice.reduce((a, b) => a + b, 0) / period; - const variance = slice.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / period; - const stdDev = Math.sqrt(variance); - - const middleValue = middle[i - period + 1]; - if (middleValue !== undefined) { - upper.push(middleValue + standardDeviations * stdDev); - lower.push(middleValue - standardDeviations * stdDev); - } - } - - return { upper, middle, lower }; -} - -/** - * Average True Range (ATR) - */ -export function atr(ohlcv: OHLCV[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const trueRanges: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]; - const previous = ohlcv[i - 1]; - if (current && previous) { - const high = current.high; - const low = current.low; - const prevClose = previous.close; - - const tr = Math.max(high - low, Math.abs(high - prevClose), Math.abs(low - prevClose)); - trueRanges.push(tr); - } - } - - return sma(trueRanges, period); -} - -/** - * On-Balance Volume (OBV) - */ -export function obv(ohlcv: OHLCV[]): number[] { - if (ohlcv.length === 0) { - return []; - } - - const first = ohlcv[0]; - if (!first) { - return []; - } - const result: number[] = [first.volume]; - - for (let i = 1; i < ohlcv.length; i++) { - const prev = ohlcv[i - 1]; - const curr = ohlcv[i]; - if (!prev || !curr) { - continue; - } - - const lastValue = result[result.length - 1]; - if (lastValue === undefined) { - continue; - } - - if (curr.close > prev.close) { - result.push(lastValue + curr.volume); - } else if (curr.close < prev.close) { - result.push(lastValue - curr.volume); - } else { - result.push(lastValue); - } - } - - return result; -} - -/** - * Stochastic Oscillator - */ -export function stochastic( - ohlcv: OHLCV[], - kPeriod: number = 14, - dPeriod: number = 3 -): { k: number[]; d: number[] } { - if (kPeriod >= ohlcv.length) { - return { k: [], d: [] }; - } - - const kValues: number[] = []; - - for (let i = kPeriod - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - kPeriod + 1, i + 1); - const highest = Math.max(...slice.map(d => d.high)); - const lowest = Math.min(...slice.map(d => d.low)); - const current = ohlcv[i]; - if (!current) { - continue; - } - const currentClose = current.close; - - if (highest === lowest) { - kValues.push(50); // Avoid division by zero - } else { - const kValue = ((currentClose - lowest) / (highest - lowest)) * 100; - kValues.push(kValue); - } - } - - const dValues = sma(kValues, dPeriod); - - return { k: kValues, d: dValues }; -} - -/** - * Williams %R - */ -export function williamsR(ohlcv: OHLCV[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highest = Math.max(...slice.map(d => d.high)); - const lowest = Math.min(...slice.map(d => d.low)); - const current = ohlcv[i]; - if (!current) { - continue; - } - const currentClose = current.close; - - if (highest === lowest) { - result.push(-50); // Avoid division by zero - } else { - const wrValue = ((highest - currentClose) / (highest - lowest)) * -100; - result.push(wrValue); - } - } - - return result; -} - -/** - * Commodity Channel Index (CCI) - */ -export function cci(ohlcv: OHLCV[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const typicalPrices = ohlcv.map(d => (d.high + d.low + d.close) / 3); - const smaTP = sma(typicalPrices, period); - const result: number[] = []; - - for (let i = 0; i < smaTP.length; i++) { - const slice = typicalPrices.slice(i, i + period); - const mean = smaTP[i]; - if (mean === undefined) { - continue; - } - const meanDeviation = slice.reduce((sum, value) => sum + Math.abs(value - mean), 0) / period; - const typicalPrice = typicalPrices[i + period - 1]; - if (typicalPrice === undefined) { - continue; - } - - if (meanDeviation === 0) { - result.push(0); - } else { - const cciValue = (typicalPrice - mean) / (0.015 * meanDeviation); - result.push(cciValue); - } - } - - return result; -} - -/** - * Money Flow Index (MFI) - */ -export function mfi(ohlcv: OHLCV[], period: number = 14): number[] { - if (period >= ohlcv.length) { - return []; - } - - const typicalPrices = ohlcv.map(d => (d.high + d.low + d.close) / 3); - const moneyFlows = ohlcv.map((d, i) => { - const tp = typicalPrices[i]; - return tp !== undefined ? tp * d.volume : 0; - }); - - const result: number[] = []; - - for (let i = period; i < ohlcv.length; i++) { - let positiveFlow = 0; - let negativeFlow = 0; - - for (let j = i - period + 1; j <= i; j++) { - if (j > 0) { - const currentTP = typicalPrices[j]; - const prevTP = typicalPrices[j - 1]; - const currentMF = moneyFlows[j]; - if (currentTP !== undefined && prevTP !== undefined && currentMF !== undefined) { - if (currentTP > prevTP) { - positiveFlow += currentMF; - } else if (currentTP < prevTP) { - negativeFlow += currentMF; - } - } - } - } - - if (negativeFlow === 0) { - result.push(100); - } else { - const mfiRatio = positiveFlow / negativeFlow; - const mfiValue = 100 - 100 / (1 + mfiRatio); - result.push(mfiValue); - } - } - - return result; -} - -/** - * Volume Weighted Moving Average (VWMA) - */ -export function vwma(ohlcv: OHLCV[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - - let totalVolumePrice = 0; - let totalVolume = 0; - - for (const candle of slice) { - const typicalPrice = (candle.high + candle.low + candle.close) / 3; - totalVolumePrice += typicalPrice * candle.volume; - totalVolume += candle.volume; - } - - const vwmaValue = totalVolume > 0 ? totalVolumePrice / totalVolume : 0; - result.push(vwmaValue); - } - - return result; -} - -/** - * Momentum - */ -export function momentum(prices: number[], period: number = 10): number[] { - if (period >= prices.length) { - return []; - } - - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - period]; - if (current !== undefined && previous !== undefined) { - const momentum = current - previous; - result.push(momentum); - } - } - - return result; -} - -/** - * Rate of Change (ROC) - */ -export function roc(prices: number[], period: number = 10): number[] { - if (period >= prices.length) { - return []; - } - - const result: number[] = []; - - for (let i = period; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - period]; - if (current !== undefined && previous !== undefined) { - if (previous === 0) { - result.push(0); - } else { - const rocValue = ((current - previous) / previous) * 100; - result.push(rocValue); - } - } - } - - return result; -} - -/** - * Accumulation/Distribution Line - */ -export function accumulationDistribution(ohlcv: OHLCV[]): number[] { - if (ohlcv.length === 0) { - return []; - } - - const result: number[] = []; - let adLine = 0; - - for (const candle of ohlcv) { - if (candle.high === candle.low) { - // Avoid division by zero - result.push(adLine); - continue; - } - - const moneyFlowMultiplier = - (candle.close - candle.low - (candle.high - candle.close)) / (candle.high - candle.low); - const moneyFlowVolume = moneyFlowMultiplier * candle.volume; - adLine += moneyFlowVolume; - result.push(adLine); - } - - return result; -} - -/** - * Aroon Indicator - */ -export function aroon(ohlcv: OHLCV[], period: number = 14): { up: number[]; down: number[] } { - if (period >= ohlcv.length) { - return { up: [], down: [] }; - } - - const up: number[] = []; - const down: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - - // Find highest high and lowest low positions - let highestIndex = 0; - let lowestIndex = 0; - - for (let j = 1; j < slice.length; j++) { - const current = slice[j]; - const highest = slice[highestIndex]; - const lowest = slice[lowestIndex]; - if (current && highest && lowest) { - if (current.high > highest.high) { - highestIndex = j; - } - if (current.low < lowest.low) { - lowestIndex = j; - } - } - } - - const aroonUp = ((period - 1 - highestIndex) / (period - 1)) * 100; - const aroonDown = ((period - 1 - lowestIndex) / (period - 1)) * 100; - - up.push(aroonUp); - down.push(aroonDown); - } - - return { up, down }; -} - -/** - * Average Directional Movement Index (ADX) and Directional Movement Indicators (DMI) - */ -export function adx( - ohlcv: OHLCV[], - period: number = 14 -): { adx: number[]; plusDI: number[]; minusDI: number[] } { - if (period >= ohlcv.length) { - return { adx: [], plusDI: [], minusDI: [] }; - } - - const trueRanges: number[] = []; - const plusDM: number[] = []; - const minusDM: number[] = []; - - // Calculate True Range and Directional Movements - for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]; - const previous = ohlcv[i - 1]; - if (!current || !previous) { - continue; - } - - // True Range - const tr = Math.max( - current.high - current.low, - Math.abs(current.high - previous.close), - Math.abs(current.low - previous.close) - ); - trueRanges.push(tr); - - // Directional Movements - const highDiff = current.high - previous.high; - const lowDiff = previous.low - current.low; - - const plusDMValue = highDiff > lowDiff && highDiff > 0 ? highDiff : 0; - const minusDMValue = lowDiff > highDiff && lowDiff > 0 ? lowDiff : 0; - - plusDM.push(plusDMValue); - minusDM.push(minusDMValue); - } - - // Calculate smoothed averages - const atrValues = sma(trueRanges, period); - const smoothedPlusDM = sma(plusDM, period); - const smoothedMinusDM = sma(minusDM, period); - - const plusDI: number[] = []; - const minusDI: number[] = []; - const dx: number[] = []; - - // Calculate DI+ and DI- - for (let i = 0; i < atrValues.length; i++) { - const atr = atrValues[i]; - const plusDMSmoothed = smoothedPlusDM[i]; - const minusDMSmoothed = smoothedMinusDM[i]; - if (atr === undefined || plusDMSmoothed === undefined || minusDMSmoothed === undefined) { - continue; - } - - const diPlus = atr > 0 ? (plusDMSmoothed / atr) * 100 : 0; - const diMinus = atr > 0 ? (minusDMSmoothed / atr) * 100 : 0; - - plusDI.push(diPlus); - minusDI.push(diMinus); - - // Calculate DX - const diSum = diPlus + diMinus; - const dxValue = diSum > 0 ? (Math.abs(diPlus - diMinus) / diSum) * 100 : 0; - dx.push(dxValue); - } - - // Calculate ADX (smoothed DX) - const adxValues = sma(dx, period); - - return { - adx: adxValues, - plusDI: plusDI.slice(period - 1), - minusDI: minusDI.slice(period - 1), - }; -} - -/** - * Parabolic SAR - */ -export function parabolicSAR(ohlcv: OHLCV[], step: number = 0.02, maxStep: number = 0.2): number[] { - if (ohlcv.length < 2) { - return []; - } - - const first = ohlcv[0]; - if (!first) { - return []; - } - - const result: number[] = []; - let trend = 1; // 1 for uptrend, -1 for downtrend - let acceleration = step; - let extremePoint = first.high; - let sar = first.low; - - result.push(sar); - - for (let i = 1; i < ohlcv.length; i++) { - const curr = ohlcv[i]; - const prev = ohlcv[i - 1]; - if (!curr || !prev) { - continue; - } - - // Calculate new SAR - sar = sar + acceleration * (extremePoint - sar); - - if (trend === 1) { - // Uptrend - if (curr.low <= sar) { - // Trend reversal - trend = -1; - sar = extremePoint; - extremePoint = curr.low; - acceleration = step; - } else { - if (curr.high > extremePoint) { - extremePoint = curr.high; - acceleration = Math.min(acceleration + step, maxStep); - } - // Ensure SAR doesn't exceed previous lows - const prevPrev = i > 1 ? ohlcv[i - 2] : null; - sar = Math.min(sar, prev.low, prevPrev ? prevPrev.low : prev.low); - } - } else { - // Downtrend - if (curr.high >= sar) { - // Trend reversal - trend = 1; - sar = extremePoint; - extremePoint = curr.high; - acceleration = step; - } else { - if (curr.low < extremePoint) { - extremePoint = curr.low; - acceleration = Math.min(acceleration + step, maxStep); - } - // Ensure SAR doesn't exceed previous highs - const prevPrev = i > 1 ? ohlcv[i - 2] : null; - sar = Math.max(sar, prev.high, prevPrev ? prevPrev.high : prev.high); - } - } - - result.push(sar); - } - - return result; -} - -/** - * Chaikin Money Flow (CMF) - */ -export function chaikinMoneyFlow(ohlcv: OHLCV[], period: number = 20): number[] { - if (period >= ohlcv.length) { - return []; - } - - const adValues: number[] = []; - - for (const candle of ohlcv) { - if (candle.high === candle.low) { - adValues.push(0); - } else { - const moneyFlowMultiplier = - (candle.close - candle.low - (candle.high - candle.close)) / (candle.high - candle.low); - const moneyFlowVolume = moneyFlowMultiplier * candle.volume; - adValues.push(moneyFlowVolume); - } - } - - const result: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const sumAD = adValues.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - const sumVolume = ohlcv.slice(i - period + 1, i + 1).reduce((a, b) => a + b.volume, 0); - - if (sumVolume === 0) { - result.push(0); - } else { - result.push(sumAD / sumVolume); - } - } - - return result; -} - -/** - * Pivot Points (Standard) - */ -export function pivotPoints(ohlcv: OHLCV[]): Array<{ - pivot: number; - r1: number; - r2: number; - r3: number; - s1: number; - s2: number; - s3: number; -}> { - const result: Array<{ - pivot: number; - r1: number; - r2: number; - r3: number; - s1: number; - s2: number; - s3: number; - }> = []; - - for (const candle of ohlcv) { - const pivot = (candle.high + candle.low + candle.close) / 3; - const r1 = 2 * pivot - candle.low; - const s1 = 2 * pivot - candle.high; - const r2 = pivot + (candle.high - candle.low); - const s2 = pivot - (candle.high - candle.low); - const r3 = candle.high + 2 * (pivot - candle.low); - const s3 = candle.low - 2 * (candle.high - pivot); - - result.push({ pivot, r1, r2, r3, s1, s2, s3 }); - } - - return result; -} - -/** - * Ichimoku Cloud components - */ -export function ichimoku( - ohlcv: OHLCV[], - tenkanPeriod: number = 9, - kijunPeriod: number = 26, - senkouBPeriod: number = 52, - _displacement: number = 26 -): { - tenkanSen: number[]; - kijunSen: number[]; - senkouSpanA: number[]; - senkouSpanB: number[]; - chikouSpan: number[]; -} { - const tenkanSen: number[] = []; - const kijunSen: number[] = []; - const senkouSpanA: number[] = []; - const senkouSpanB: number[] = []; - const chikouSpan: number[] = []; - - for (let i = 0; i < ohlcv.length; i++) { - // Tenkan-sen (Conversion Line) - if (i >= tenkanPeriod - 1) { - const slice = ohlcv.slice(i - tenkanPeriod + 1, i + 1); - const high = Math.max(...slice.map(d => d.high)); - const low = Math.min(...slice.map(d => d.low)); - tenkanSen.push((high + low) / 2); - } - - // Kijun-sen (Base Line) - if (i >= kijunPeriod - 1) { - const slice = ohlcv.slice(i - kijunPeriod + 1, i + 1); - const high = Math.max(...slice.map(d => d.high)); - const low = Math.min(...slice.map(d => d.low)); - kijunSen.push((high + low) / 2); - } - - // Senkou Span A (Leading Span A) - if (tenkanSen.length > 0 && kijunSen.length > 0) { - const tenkanValue = tenkanSen[tenkanSen.length - 1]; - const kijunValue = kijunSen[kijunSen.length - 1]; - if (tenkanValue !== undefined && kijunValue !== undefined) { - senkouSpanA.push((tenkanValue + kijunValue) / 2); - } - } - - // Senkou Span B (Leading Span B) - if (i >= senkouBPeriod - 1) { - const slice = ohlcv.slice(i - senkouBPeriod + 1, i + 1); - const high = Math.max(...slice.map(d => d.high)); - const low = Math.min(...slice.map(d => d.low)); - senkouSpanB.push((high + low) / 2); - } - - // Chikou Span (Lagging Span) - chikouSpan.push(defined(ohlcv[i]).close); - } - - return { - tenkanSen, - kijunSen, - senkouSpanA, - senkouSpanB, - chikouSpan, - }; -} - -/** - * Ultimate Oscillator - */ -export function ultimateOscillator( - ohlcv: OHLCV[], - period1: number = 7, - period2: number = 14, - period3: number = 28 -): number[] { - if (ohlcv.length < Math.max(period1, period2, period3)) { - return []; - } - - const bp: number[] = []; // Buying Pressure - const tr: number[] = []; // True Range - - // Calculate BP and TR - for (let i = 0; i < ohlcv.length; i++) { - const current = defined(ohlcv[i]); - - if (i === 0) { - bp.push(current.close - current.low); - tr.push(current.high - current.low); - } else { - const previous = defined(ohlcv[i - 1]); - bp.push(current.close - Math.min(current.low, previous.close)); - tr.push( - Math.max( - current.high - current.low, - Math.abs(current.high - previous.close), - Math.abs(current.low - previous.close) - ) - ); - } - } - - const result: number[] = []; - - for (let i = Math.max(period1, period2, period3) - 1; i < ohlcv.length; i++) { - const avg1 = - bp.slice(i - period1 + 1, i + 1).reduce((a, b) => a + b, 0) / - tr.slice(i - period1 + 1, i + 1).reduce((a, b) => a + b, 0); - const avg2 = - bp.slice(i - period2 + 1, i + 1).reduce((a, b) => a + b, 0) / - tr.slice(i - period2 + 1, i + 1).reduce((a, b) => a + b, 0); - const avg3 = - bp.slice(i - period3 + 1, i + 1).reduce((a, b) => a + b, 0) / - tr.slice(i - period3 + 1, i + 1).reduce((a, b) => a + b, 0); - - const uo = (100 * (4 * avg1 + 2 * avg2 + avg3)) / (4 + 2 + 1); - result.push(uo); - } - - return result; -} - -/** - * Ease of Movement (EOM) - */ -export function easeOfMovement(ohlcv: OHLCV[], period: number = 14): number[] { - if (ohlcv.length < 2) { - return []; - } - - const emv: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = defined(ohlcv[i]); - const previous = defined(ohlcv[i - 1]); - - const distance = (current.high + current.low) / 2 - (previous.high + previous.low) / 2; - const boxHeight = current.high - current.low; - const volume = current.volume; - - if (boxHeight > 0 && volume > 0) { - const emvValue = (distance * 1000000) / (volume / boxHeight); - emv.push(emvValue); - } else { - emv.push(0); - } - } - - return sma(emv, period); -} - -/** - * Triple Exponential Moving Average (TEMA) - */ -export function tema(values: number[], period: number): number[] { - const ema1 = ema(values, period); - const ema2 = ema(ema1, period); - const ema3 = ema(ema2, period); - - const result: number[] = []; - const minLength = Math.min(ema1.length, ema2.length, ema3.length); - - for (let i = 0; i < minLength; i++) { - const e1 = ema1[i]; - const e2 = ema2[i]; - const e3 = ema3[i]; - if (e1 !== undefined && e2 !== undefined && e3 !== undefined) { - const temaValue = 3 * e1 - 3 * e2 + e3; - result.push(temaValue); - } - } - - return result; -} - -/** - * Weighted Moving Average (WMA) - */ -export function wma(values: number[], period: number): number[] { - if (period > values.length) { - return []; - } - - const result: number[] = []; - const denominator = (period * (period + 1)) / 2; - - for (let i = period - 1; i < values.length; i++) { - let weightedSum = 0; - let weight = 1; - - for (let j = i - period + 1; j <= i; j++) { - const value = values[j]; - if (value !== undefined) { - weightedSum += value * weight; - weight++; - } - } - - result.push(weightedSum / denominator); - } - - return result; -} - -/** - * Keltner Channels - */ -export function keltnerChannels( - ohlcv: OHLCV[], - period: number = 20, - multiplier: number = 2 -): { upper: number[]; middle: number[]; lower: number[] } { - const typicalPrices = ohlcv.map(d => (d.high + d.low + d.close) / 3); - const middle = ema(typicalPrices, period); - const atrValues = atr(ohlcv, period); - - const upper: number[] = []; - const lower: number[] = []; - - const minLength = Math.min(middle.length, atrValues.length); - for (let i = 0; i < minLength; i++) { - const middleValue = middle[i]; - const atrValue = atrValues[i]; - if (middleValue !== undefined && atrValue !== undefined) { - upper.push(middleValue + multiplier * atrValue); - lower.push(middleValue - multiplier * atrValue); - } - } - - return { upper, middle, lower }; -} - -/** - * Donchian Channels - */ -export function donchianChannels( - ohlcv: OHLCV[], - period: number = 20 -): { upper: number[]; middle: number[]; lower: number[] } { - if (period >= ohlcv.length) { - return { upper: [], middle: [], lower: [] }; - } - - const upper: number[] = []; - const lower: number[] = []; - const middle: number[] = []; - - for (let i = period - 1; i < ohlcv.length; i++) { - const slice = ohlcv.slice(i - period + 1, i + 1); - const highest = Math.max(...slice.map(d => d.high)); - const lowest = Math.min(...slice.map(d => d.low)); - const middleValue = (highest + lowest) / 2; - - upper.push(highest); - lower.push(lowest); - middle.push(middleValue); - } - - return { upper, middle, lower }; -} - -/** - * Klinger Volume Oscillator - */ -export function klingerVolumeOscillator( - ohlcv: OHLCV[], - fastPeriod: number = 34, - slowPeriod: number = 55, - signalPeriod: number = 13 -): { kvo: number[]; signal: number[] } { - if (ohlcv.length < 2) { - return { kvo: [], signal: [] }; - } - - const volumeForce: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = defined(ohlcv[i]); - const previous = defined(ohlcv[i - 1]); - - const typicalPrice = (current.high + current.low + current.close) / 3; - const prevTypicalPrice = (previous.high + previous.low + previous.close) / 3; - - const trend = typicalPrice > prevTypicalPrice ? 1 : -1; - const vf = - current.volume * - trend * - Math.abs( - (2 * (current.close - current.low - (current.high - current.close))) / - (current.high - current.low) - ) * - 100; - - volumeForce.push(vf); - } - - const fastEMA = ema(volumeForce, fastPeriod); - const slowEMA = ema(volumeForce, slowPeriod); - - const kvo: number[] = []; - const minLength = Math.min(fastEMA.length, slowEMA.length); - - for (let i = 0; i < minLength; i++) { - const fast = fastEMA[i]; - const slow = slowEMA[i]; - if (fast !== undefined && slow !== undefined) { - kvo.push(fast - slow); - } - } - - const signal = ema(kvo, signalPeriod); - - return { kvo, signal }; -} - -/** - * Price Oscillator (PPO) - */ -export function priceOscillator( - prices: number[], - fastPeriod: number = 12, - slowPeriod: number = 26, - signalPeriod: number = 9 -): { ppo: number[]; signal: number[]; histogram: number[] } { - const fastEMA = ema(prices, fastPeriod); - const slowEMA = ema(prices, slowPeriod); - - const ppo: number[] = []; - const minLength = Math.min(fastEMA.length, slowEMA.length); - - for (let i = 0; i < minLength; i++) { - const fast = fastEMA[i]; - const slow = slowEMA[i]; - if (fast !== undefined && slow !== undefined && slow !== 0) { - const ppoValue = ((fast - slow) / slow) * 100; - ppo.push(ppoValue); - } - } - - const signal = ema(ppo, signalPeriod); - const histogram: number[] = []; - - const histMinLength = Math.min(ppo.length, signal.length); - for (let i = 0; i < histMinLength; i++) { - const ppoValue = ppo[i]; - const signalValue = signal[i]; - if (ppoValue !== undefined && signalValue !== undefined) { - histogram.push(ppoValue - signalValue); - } - } - - return { ppo, signal, histogram }; -} - -/** - * Chande Momentum Oscillator (CMO) - */ -export function chandeMomentumOscillator(prices: number[], period: number = 14): number[] { - if (period >= prices.length) { - return []; - } - - const gains: number[] = []; - const losses: number[] = []; - - // Calculate gains and losses - for (let i = 1; i < prices.length; i++) { - const current = prices[i]; - const previous = prices[i - 1]; - if (current !== undefined && previous !== undefined) { - const change = current - previous; - gains.push(change > 0 ? change : 0); - losses.push(change < 0 ? Math.abs(change) : 0); - } - } - - const result: number[] = []; - - for (let i = period - 1; i < gains.length; i++) { - const sumGains = gains.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - const sumLosses = losses.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - - const cmo = ((sumGains - sumLosses) / (sumGains + sumLosses)) * 100; - result.push(isNaN(cmo) ? 0 : cmo); - } - - return result; -} - -/** - * Stochastic RSI - */ -export function stochasticRSI( - prices: number[], - rsiPeriod: number = 14, - stochPeriod: number = 14, - smoothK: number = 3, - smoothD: number = 3 -): { k: number[]; d: number[] } { - const rsiValues = rsi(prices, rsiPeriod); - - if (rsiValues.length < stochPeriod) { - return { k: [], d: [] }; - } - - const stochRSI: number[] = []; - - for (let i = stochPeriod - 1; i < rsiValues.length; i++) { - const slice = rsiValues.slice(i - stochPeriod + 1, i + 1); - const highest = Math.max(...slice); - const lowest = Math.min(...slice); - const currentRSI = defined(rsiValues[i]); - - if (highest === lowest) { - stochRSI.push(0); - } else { - const stochValue = ((currentRSI - lowest) / (highest - lowest)) * 100; - stochRSI.push(stochValue); - } - } - - const k = sma(stochRSI, smoothK); - const d = sma(k, smoothD); - - return { k, d }; -} - -/** - * Vortex Indicator - */ -export function vortexIndicator( - ohlcv: OHLCV[], - period: number = 14 -): { vi_plus: number[]; vi_minus: number[] } { - if (ohlcv.length < period + 1) { - return { vi_plus: [], vi_minus: [] }; - } - - const vm_plus: number[] = []; - const vm_minus: number[] = []; - const tr: number[] = []; - - for (let i = 1; i < ohlcv.length; i++) { - const current = defined(ohlcv[i]); - const previous = defined(ohlcv[i - 1]); - - // Vortex Movement - vm_plus.push(Math.abs(current.high - previous.low)); - vm_minus.push(Math.abs(current.low - previous.high)); - - // True Range - const trValue = Math.max( - current.high - current.low, - Math.abs(current.high - previous.close), - Math.abs(current.low - previous.close) - ); - tr.push(trValue); - } - - const vi_plus: number[] = []; - const vi_minus: number[] = []; - - for (let i = period - 1; i < vm_plus.length; i++) { - const sumVMPlus = vm_plus.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - const sumVMMinus = vm_minus.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - const sumTR = tr.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - - if (sumTR > 0) { - vi_plus.push(sumVMPlus / sumTR); - vi_minus.push(sumVMMinus / sumTR); - } else { - vi_plus.push(0); - vi_minus.push(0); - } - } - - return { vi_plus, vi_minus }; -} - -/** - * Balance of Power (BOP) - */ -export function balanceOfPower(ohlcv: OHLCV[]): number[] { - const result: number[] = []; - - for (const candle of ohlcv) { - if (candle.high === candle.low) { - result.push(0); - } else { - const bop = (candle.close - candle.open) / (candle.high - candle.low); - result.push(bop); - } - } - - return result; -} - -/** - * Trix (Triple Exponential Moving Average Oscillator) - */ -export function trix(prices: number[], period: number = 14): number[] { - const ema1 = ema(prices, period); - const ema2 = ema(ema1, period); - const ema3 = ema(ema2, period); - - const result: number[] = []; - - for (let i = 1; i < ema3.length; i++) { - const current = ema3[i]; - const previous = ema3[i - 1]; - if (current !== undefined && previous !== undefined && previous !== 0) { - const trixValue = ((current - previous) / previous) * 10000; - result.push(trixValue); - } - } - - return result; -} - -/** - * Mass Index - */ -export function massIndex(ohlcv: OHLCV[], period: number = 25): number[] { - if (ohlcv.length < period) { - return []; - } - - // Calculate high-low ranges - const ranges = ohlcv.map(candle => candle.high - candle.low); - - // Calculate 9-period EMA of ranges - const ema9 = ema(ranges, 9); - - // Calculate 9-period EMA of the EMA (double smoothing) - const emaEma9 = ema(ema9, 9); - - // Calculate ratio - const ratios: number[] = []; - const minLength = Math.min(ema9.length, emaEma9.length); - - for (let i = 0; i < minLength; i++) { - const singleEMA = ema9[i]; - const doubleEMA = emaEma9[i]; - if (singleEMA !== undefined && doubleEMA !== undefined && doubleEMA !== 0) { - ratios.push(singleEMA / doubleEMA); - } - } - - // Calculate 25-period sum of ratios - const result: number[] = []; - for (let i = period - 1; i < ratios.length; i++) { - const sum = ratios.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); - result.push(sum); - } - - return result; -} - -/** - * Coppock Curve - */ -export function coppockCurve( - prices: number[], - shortROC: number = 11, - longROC: number = 14, - wma: number = 10 -): number[] { - const roc1 = roc(prices, shortROC); - const roc2 = roc(prices, longROC); - - const combined: number[] = []; - const minLength = Math.min(roc1.length, roc2.length); - - for (let i = 0; i < minLength; i++) { - const r1 = roc1[i]; - const r2 = roc2[i]; - if (r1 !== undefined && r2 !== undefined) { - combined.push(r1 + r2); - } - } - - return sma(combined, wma); // Using SMA instead of WMA for simplicity -} diff --git a/libs/calculations/test/preservation.test.ts b/libs/calculations/test/preservation.test.ts deleted file mode 100644 index 08f10042..00000000 --- a/libs/calculations/test/preservation.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { createHash } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { describe, expect, test } from 'bun:test'; -import ts from 'typescript'; -import * as legacy from '@stock-bot/calculations/legacy'; -import audit from '../migration-audit.json'; - -const root = join(import.meta.dir, '..'); -const namespaces: Record = { - 'basic-calculations.ts': legacy.basic, - 'technical-indicators.ts': legacy.indicators, - 'risk-metrics.ts': legacy.risk, - 'performance-metrics.ts': legacy.performance, -}; -const hash = (value: string) => createHash('sha256').update(value).digest('hex'); - -describe('calculation capability preservation', () => { - test('all 105 previously active functions remain available with unchanged legacy bodies', () => { - let count = 0; - for (const module of audit.modules.filter(module => module.status === 'legacy-api')) { - const name = module.original.split('/').at(-1)!; - expect(Object.keys(namespaces[name]!).sort()).toEqual(module.functions); - const source = readFileSync(join(root, module.destination), 'utf8'); - const ast = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true); - expect(hash(ts.createPrinter({ removeComments: true }).printFile(ast))).toBe( - module.astSha256! - ); - count += module.functions.length; - } - expect(count).toBe(105); - // Legacy behavior is preserved, not silently relabeled as validated core behavior. - expect(legacy.basic.simpleReturn(0, 100)).toBe(0); - expect(legacy.indicators.sma([1, 2, 3], 2)).toEqual([1.5, 2.5]); - expect(legacy.risk.maxDrawdown([100, 80, 100])).toBeCloseTo(0.2); - expect( - legacy.performance.analyzeTradePerformance([{ pnl: 1, date: new Date(0) }]).profitFactor - ).toBe(Infinity); - }); - - test('all seven disabled prototypes survive as non-executable, source-verified references', () => { - const modules = audit.modules.filter(module => module.status === 'research-reference'); - expect(modules).toHaveLength(7); - for (const module of modules) { - const reference = readFileSync(join(root, module.destination), 'utf8'); - const start = reference.indexOf('```ts\n') + 6; - const end = reference.lastIndexOf('```'); - expect(start).toBeGreaterThan(5); - expect(end).toBeGreaterThan(start); - expect(hash(reference.slice(start, end).replaceAll('\r\n', '\n').trimEnd())).toBe( - module.sourceSha256 - ); - } - }); -}); diff --git a/libs/core/cache/src/key-generator.ts b/libs/core/cache/src/key-generator.ts deleted file mode 100644 index 54f25b91..00000000 --- a/libs/core/cache/src/key-generator.ts +++ /dev/null @@ -1,83 +0,0 @@ -export class CacheKeyGenerator { - /** - * Generate cache key for market data - */ - static marketData(symbol: string, timeframe: string, date?: Date): string { - const dateStr = date ? date.toISOString().split('T')[0] : 'latest'; - return `market:${symbol.toLowerCase()}:${timeframe}:${dateStr}`; - } - - /** - * Generate cache key for technical indicators - */ - static indicator(symbol: string, indicator: string, period: number, dataHash: string): string { - return `indicator:${symbol.toLowerCase()}:${indicator}:${period}:${dataHash}`; - } - - /** - * Generate cache key for backtest results - */ - static backtest(strategyName: string, params: Record): string { - const paramHash = this.hashObject(params); - return `backtest:${strategyName}:${paramHash}`; - } - - /** - * Generate cache key for strategy results - */ - static strategy(strategyName: string, symbol: string, timeframe: string): string { - return `strategy:${strategyName}:${symbol.toLowerCase()}:${timeframe}`; - } - - /** - * Generate cache key for user sessions - */ - static userSession(userId: string): string { - return `session:${userId}`; - } - - /** - * Generate cache key for portfolio data - */ - static portfolio(userId: string, portfolioId: string): string { - return `portfolio:${userId}:${portfolioId}`; - } - - /** - * Generate cache key for real-time prices - */ - static realtimePrice(symbol: string): string { - return `price:realtime:${symbol.toLowerCase()}`; - } - - /** - * Generate cache key for order book data - */ - static orderBook(symbol: string, depth: number = 10): string { - return `orderbook:${symbol.toLowerCase()}:${depth}`; - } - - /** - * Create a simple hash from object for cache keys - */ - private static hashObject(obj: Record): string { - const str = JSON.stringify(obj, Object.keys(obj).sort()); - let hash = 0; - for (let i = 0; i < str.length; i++) { - const char = str.charCodeAt(i); - hash = (hash << 5) - hash + char; - hash = hash & hash; // Convert to 32-bit integer - } - return Math.abs(hash).toString(36); - } -} - -/** - * Simple key generator function - */ -export function generateKey(...parts: (string | number | boolean | undefined)[]): string { - return parts - .filter(part => part !== undefined) - .map(part => String(part)) - .join(':'); -} diff --git a/libs/core/cache/src/namespaced-cache.ts b/libs/core/cache/src/namespaced-cache.ts index f7b9b778..fadcac7c 100644 --- a/libs/core/cache/src/namespaced-cache.ts +++ b/libs/core/cache/src/namespaced-cache.ts @@ -41,7 +41,7 @@ export class NamespacedCache implements CacheProvider { // Clear only keys with this namespace prefix const keys = await this.cache.keys(`${this.prefix}*`); if (keys.length > 0) { - await Promise.all(keys.map(key => this.cache.del(key.substring(this.prefix.length)))); + await Promise.all(keys.map(key => this.cache.del(key))); } } diff --git a/libs/core/cache/test/cache.test.ts b/libs/core/cache/test/cache.test.ts index b672fc13..e32969a7 100644 --- a/libs/core/cache/test/cache.test.ts +++ b/libs/core/cache/test/cache.test.ts @@ -1,6 +1,5 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { CacheFactory, createNamespacedCache } from '../src/cache-factory'; -import { generateKey } from '../src/key-generator'; import type { ICache } from '../src/types'; describe('CacheFactory', () => { @@ -89,25 +88,3 @@ describe('NamespacedCache', () => { expect(keys).toEqual(['key1', 'key2']); }); }); - -describe('KeyGenerator', () => { - it('should generate key from parts', () => { - const key = generateKey('part1', 'part2', 'part3'); - expect(key).toBe('part1:part2:part3'); - }); - - it('should handle empty parts', () => { - const key = generateKey(); - expect(key).toBe(''); - }); - - it('should skip undefined parts', () => { - const key = generateKey('part1', undefined, 'part3'); - expect(key).toBe('part1:part3'); - }); - - it('should convert non-string parts', () => { - const key = generateKey('prefix', 123, true); - expect(key).toBe('prefix:123:true'); - }); -}); diff --git a/libs/core/cache/test/key-generator.test.ts b/libs/core/cache/test/key-generator.test.ts deleted file mode 100644 index b7c172e8..00000000 --- a/libs/core/cache/test/key-generator.test.ts +++ /dev/null @@ -1,220 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { CacheKeyGenerator, generateKey } from '../src/key-generator'; - -describe('CacheKeyGenerator', () => { - describe('marketData', () => { - it('should generate key with symbol, timeframe and date', () => { - const date = new Date('2024-01-15T10:30:00Z'); - const key = CacheKeyGenerator.marketData('AAPL', '1h', date); - expect(key).toBe('market:aapl:1h:2024-01-15'); - }); - - it('should generate key with "latest" when no date provided', () => { - const key = CacheKeyGenerator.marketData('MSFT', '1d'); - expect(key).toBe('market:msft:1d:latest'); - }); - - it('should lowercase the symbol', () => { - const key = CacheKeyGenerator.marketData('GOOGL', '5m'); - expect(key).toBe('market:googl:5m:latest'); - }); - - it('should handle different timeframes', () => { - expect(CacheKeyGenerator.marketData('TSLA', '1m')).toBe('market:tsla:1m:latest'); - expect(CacheKeyGenerator.marketData('TSLA', '15m')).toBe('market:tsla:15m:latest'); - expect(CacheKeyGenerator.marketData('TSLA', '1w')).toBe('market:tsla:1w:latest'); - }); - }); - - describe('indicator', () => { - it('should generate key with all parameters', () => { - const key = CacheKeyGenerator.indicator('AAPL', 'RSI', 14, 'abc123'); - expect(key).toBe('indicator:aapl:RSI:14:abc123'); - }); - - it('should lowercase the symbol but not indicator name', () => { - const key = CacheKeyGenerator.indicator('META', 'MACD', 20, 'hash456'); - expect(key).toBe('indicator:meta:MACD:20:hash456'); - }); - - it('should handle different period values', () => { - expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 50, 'hash1')).toBe( - 'indicator:amzn:SMA:50:hash1' - ); - expect(CacheKeyGenerator.indicator('AMZN', 'SMA', 200, 'hash2')).toBe( - 'indicator:amzn:SMA:200:hash2' - ); - }); - }); - - describe('backtest', () => { - it('should generate key with strategy name and hashed params', () => { - const params = { stopLoss: 0.02, takeProfit: 0.05 }; - const key = CacheKeyGenerator.backtest('MomentumStrategy', params); - expect(key).toMatch(/^backtest:MomentumStrategy:[a-z0-9]+$/); - }); - - it('should generate same hash for same params regardless of order', () => { - const params1 = { a: 1, b: 2, c: 3 }; - const params2 = { c: 3, a: 1, b: 2 }; - const key1 = CacheKeyGenerator.backtest('Strategy', params1); - const key2 = CacheKeyGenerator.backtest('Strategy', params2); - expect(key1).toBe(key2); - }); - - it('should generate different hashes for different params', () => { - const params1 = { threshold: 0.01 }; - const params2 = { threshold: 0.02 }; - const key1 = CacheKeyGenerator.backtest('Strategy', params1); - const key2 = CacheKeyGenerator.backtest('Strategy', params2); - expect(key1).not.toBe(key2); - }); - - it('should handle complex nested params', () => { - const params = { - indicators: { rsi: { period: 14 }, macd: { fast: 12, slow: 26 } }, - risk: { maxDrawdown: 0.1 }, - }; - const key = CacheKeyGenerator.backtest('ComplexStrategy', params); - expect(key).toMatch(/^backtest:ComplexStrategy:[a-z0-9]+$/); - }); - }); - - describe('strategy', () => { - it('should generate key with strategy name, symbol and timeframe', () => { - const key = CacheKeyGenerator.strategy('TrendFollowing', 'NVDA', '4h'); - expect(key).toBe('strategy:TrendFollowing:nvda:4h'); - }); - - it('should lowercase the symbol but not strategy name', () => { - const key = CacheKeyGenerator.strategy('MeanReversion', 'AMD', '1d'); - expect(key).toBe('strategy:MeanReversion:amd:1d'); - }); - }); - - describe('userSession', () => { - it('should generate key with userId', () => { - const key = CacheKeyGenerator.userSession('user123'); - expect(key).toBe('session:user123'); - }); - - it('should handle different userId formats', () => { - expect(CacheKeyGenerator.userSession('uuid-123-456')).toBe('session:uuid-123-456'); - expect(CacheKeyGenerator.userSession('email@example.com')).toBe('session:email@example.com'); - }); - }); - - describe('portfolio', () => { - it('should generate key with userId and portfolioId', () => { - const key = CacheKeyGenerator.portfolio('user123', 'portfolio456'); - expect(key).toBe('portfolio:user123:portfolio456'); - }); - - it('should handle UUID format IDs', () => { - const key = CacheKeyGenerator.portfolio( - '550e8400-e29b-41d4-a716-446655440000', - '6ba7b810-9dad-11d1-80b4-00c04fd430c8' - ); - expect(key).toBe( - 'portfolio:550e8400-e29b-41d4-a716-446655440000:6ba7b810-9dad-11d1-80b4-00c04fd430c8' - ); - }); - }); - - describe('realtimePrice', () => { - it('should generate key with symbol', () => { - const key = CacheKeyGenerator.realtimePrice('BTC'); - expect(key).toBe('price:realtime:btc'); - }); - - it('should lowercase the symbol', () => { - const key = CacheKeyGenerator.realtimePrice('ETH-USD'); - expect(key).toBe('price:realtime:eth-usd'); - }); - }); - - describe('orderBook', () => { - it('should generate key with symbol and default depth', () => { - const key = CacheKeyGenerator.orderBook('BTC'); - expect(key).toBe('orderbook:btc:10'); - }); - - it('should generate key with custom depth', () => { - const key = CacheKeyGenerator.orderBook('ETH', 20); - expect(key).toBe('orderbook:eth:20'); - }); - - it('should lowercase the symbol', () => { - const key = CacheKeyGenerator.orderBook('USDT', 5); - expect(key).toBe('orderbook:usdt:5'); - }); - }); - - describe('hashObject', () => { - it('should generate consistent hashes', () => { - const params = { x: 1, y: 2 }; - const key1 = CacheKeyGenerator.backtest('Test', params); - const key2 = CacheKeyGenerator.backtest('Test', params); - expect(key1).toBe(key2); - }); - - it('should handle empty objects', () => { - const key = CacheKeyGenerator.backtest('Empty', {}); - expect(key).toMatch(/^backtest:Empty:[a-z0-9]+$/); - }); - - it('should handle arrays in objects', () => { - const params = { symbols: ['AAPL', 'MSFT'], periods: [10, 20, 30] }; - const key = CacheKeyGenerator.backtest('ArrayTest', params); - expect(key).toMatch(/^backtest:ArrayTest:[a-z0-9]+$/); - }); - - it('should handle null and undefined values', () => { - const params = { a: null, b: undefined, c: 'value' }; - const key = CacheKeyGenerator.backtest('NullTest', params); - expect(key).toMatch(/^backtest:NullTest:[a-z0-9]+$/); - }); - }); -}); - -describe('generateKey', () => { - it('should join parts with colons', () => { - const key = generateKey('user', 123, 'data'); - expect(key).toBe('user:123:data'); - }); - - it('should filter undefined values', () => { - const key = generateKey('prefix', undefined, 'suffix'); - expect(key).toBe('prefix:suffix'); - }); - - it('should convert all types to strings', () => { - const key = generateKey('bool', true, 'num', 42, 'str', 'text'); - expect(key).toBe('bool:true:num:42:str:text'); - }); - - it('should handle empty input', () => { - const key = generateKey(); - expect(key).toBe(''); - }); - - it('should handle single part', () => { - const key = generateKey('single'); - expect(key).toBe('single'); - }); - - it('should handle all undefined values', () => { - const key = generateKey(undefined, undefined, undefined); - expect(key).toBe(''); - }); - - it('should handle boolean false', () => { - const key = generateKey('flag', false, 'end'); - expect(key).toBe('flag:false:end'); - }); - - it('should handle zero', () => { - const key = generateKey('count', 0, 'items'); - expect(key).toBe('count:0:items'); - }); -}); diff --git a/libs/core/cache/test/namespaced-cache.test.ts b/libs/core/cache/test/namespaced-cache.test.ts index 177c1058..35b525d3 100644 --- a/libs/core/cache/test/namespaced-cache.test.ts +++ b/libs/core/cache/test/namespaced-cache.test.ts @@ -189,9 +189,9 @@ describe('NamespacedCache', () => { expect(mockCache.keys).toHaveBeenCalledWith('test-namespace:*'); expect(mockCache.del).toHaveBeenCalledTimes(3); - expect(mockCache.del).toHaveBeenCalledWith('key1'); - expect(mockCache.del).toHaveBeenCalledWith('key2'); - expect(mockCache.del).toHaveBeenCalledWith('key3'); + expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key1'); + expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key2'); + expect(mockCache.del).toHaveBeenCalledWith('test-namespace:key3'); }); it('should handle empty namespace', async () => { diff --git a/libs/core/config/.env.example b/libs/core/config/.env.example deleted file mode 100644 index 135c4e4c..00000000 --- a/libs/core/config/.env.example +++ /dev/null @@ -1,50 +0,0 @@ -# Environment -NODE_ENV=development - -# Service Configuration -STOCKBOT_SERVICE_NAME=stock-bot-service -STOCKBOT_SERVICE_PORT=3000 - -# Database Configuration -STOCKBOT_DATABASE_POSTGRES_HOST=localhost -STOCKBOT_DATABASE_POSTGRES_PORT=5432 -STOCKBOT_DATABASE_POSTGRES_DATABASE=stockbot -STOCKBOT_DATABASE_POSTGRES_USER=postgres -STOCKBOT_DATABASE_POSTGRES_PASSWORD=postgres - -STOCKBOT_DATABASE_QUESTDB_HOST=localhost -STOCKBOT_DATABASE_QUESTDB_ILP_PORT=9009 -STOCKBOT_DATABASE_QUESTDB_HTTP_PORT=9000 - -STOCKBOT_DATABASE_MONGODB_HOST=localhost -STOCKBOT_DATABASE_MONGODB_PORT=27017 -STOCKBOT_DATABASE_MONGODB_DATABASE=stockbot - -STOCKBOT_DATABASE_DRAGONFLY_HOST=localhost -STOCKBOT_DATABASE_DRAGONFLY_PORT=6379 - -# Provider Configuration -STOCKBOT_PROVIDERS_EOD_API_KEY=your_eod_api_key -STOCKBOT_PROVIDERS_EOD_ENABLED=true - -STOCKBOT_PROVIDERS_IB_ENABLED=false -STOCKBOT_PROVIDERS_IB_GATEWAY_HOST=localhost -STOCKBOT_PROVIDERS_IB_GATEWAY_PORT=5000 -STOCKBOT_PROVIDERS_IB_ACCOUNT=your_account_id - -STOCKBOT_PROVIDERS_QM_ENABLED=false -STOCKBOT_PROVIDERS_QM_USERNAME=your_username -STOCKBOT_PROVIDERS_QM_PASSWORD=your_password -STOCKBOT_PROVIDERS_QM_WEBMASTER_ID=your_webmaster_id - -# Logging -STOCKBOT_LOGGING_LEVEL=info -STOCKBOT_LOGGING_LOKI_ENABLED=false -STOCKBOT_LOGGING_LOKI_HOST=localhost -STOCKBOT_LOGGING_LOKI_PORT=3100 - -# HTTP Proxy (optional) -STOCKBOT_HTTP_PROXY_ENABLED=false -STOCKBOT_HTTP_PROXY_URL=http://proxy.example.com:8080 -STOCKBOT_HTTP_PROXY_AUTH_USERNAME=username -STOCKBOT_HTTP_PROXY_AUTH_PASSWORD=password \ No newline at end of file diff --git a/libs/core/config/config/default.json b/libs/core/config/config/default.json deleted file mode 100644 index 166b02cb..00000000 --- a/libs/core/config/config/default.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "name": "stock-bot", - "version": "1.0.0", - "debug": false, - "service": { - "name": "stock-bot-service", - "port": 3000, - "host": "0.0.0.0", - "healthCheckPath": "/health", - "metricsPath": "/metrics", - "shutdownTimeout": 30000, - "cors": { - "enabled": true, - "origin": "*", - "credentials": true - } - }, - "logging": { - "level": "info", - "format": "json", - "loki": { - "enabled": false, - "host": "localhost", - "port": 3100, - "labels": {} - } - }, - "database": { - "postgres": { - "host": "localhost", - "port": 5432, - "database": "stockbot", - "user": "postgres", - "password": "postgres", - "ssl": false, - "poolSize": 10, - "connectionTimeout": 30000, - "idleTimeout": 10000 - }, - "questdb": { - "host": "localhost", - "ilpPort": 9009, - "httpPort": 9000, - "pgPort": 8812, - "database": "questdb", - "user": "admin", - "password": "quest", - "bufferSize": 65536, - "flushInterval": 1000 - }, - "mongodb": { - "host": "localhost", - "port": 27017, - "database": "stockbot", - "authSource": "admin", - "poolSize": 10 - }, - "dragonfly": { - "host": "localhost", - "port": 6379, - "db": 0, - "maxRetries": 3, - "retryDelay": 100 - } - }, - "queue": { - "redis": { - "host": "localhost", - "port": 6379, - "db": 0 - }, - "defaultJobOptions": { - "attempts": 3, - "backoff": { - "type": "exponential", - "delay": 1000 - }, - "removeOnComplete": 100, - "removeOnFail": 100 - } - }, - "http": { - "timeout": 30000, - "retries": 3, - "retryDelay": 1000, - "proxy": { - "enabled": false - } - }, - "webshare": { - "apiKey": "", - "apiUrl": "https://proxy.webshare.io/api/v2/" - } -} diff --git a/libs/core/config/config/development.json b/libs/core/config/config/development.json deleted file mode 100644 index 991c30c3..00000000 --- a/libs/core/config/config/development.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "debug": true, - "logging": { - "level": "debug", - "format": "pretty" - }, - "providers": { - "eod": { - "name": "eod-historical-data", - "enabled": true, - "priority": 1, - "apiKey": "demo", - "tier": "free", - "rateLimit": { - "maxRequests": 20, - "windowMs": 60000 - } - }, - "yahoo": { - "name": "yahoo-finance", - "enabled": true, - "priority": 2, - "rateLimit": { - "maxRequests": 100, - "windowMs": 60000 - } - }, - "ib": { - "name": "interactive-brokers", - "enabled": false, - "priority": 0, - "gateway": { - "host": "localhost", - "port": 5000, - "clientId": 1 - }, - "marketDataType": "delayed" - }, - "qm": { - "name": "quotemedia", - "enabled": false, - "priority": 3, - "username": "", - "password": "", - "webmasterId": "" - } - } -} diff --git a/libs/core/config/config/production.json b/libs/core/config/config/production.json deleted file mode 100644 index 390d5ff6..00000000 --- a/libs/core/config/config/production.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "debug": false, - "logging": { - "level": "warn", - "format": "json", - "loki": { - "enabled": true, - "labels": { - "app": "stock-bot", - "env": "production" - } - } - }, - "database": { - "postgres": { - "ssl": true, - "poolSize": 20 - }, - "questdb": { - "bufferSize": 131072, - "flushInterval": 500 - }, - "mongodb": { - "poolSize": 20 - } - }, - "http": { - "timeout": 60000, - "retries": 5, - "retryDelay": 2000 - } -} diff --git a/libs/core/config/config/test.json b/libs/core/config/config/test.json deleted file mode 100644 index 2080deb8..00000000 --- a/libs/core/config/config/test.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "debug": true, - "logging": { - "level": "error", - "format": "json" - }, - "service": { - "port": 0, - "shutdownTimeout": 5000 - }, - "database": { - "postgres": { - "database": "stockbot_test", - "poolSize": 5 - }, - "questdb": { - "database": "questdb_test" - }, - "mongodb": { - "database": "stockbot_test", - "poolSize": 5 - }, - "dragonfly": { - "db": 15, - "keyPrefix": "test:" - } - }, - "queue": { - "redis": { - "db": 15 - }, - "defaultJobOptions": { - "attempts": 1, - "removeOnComplete": 100, - "removeOnFail": 100 - } - }, - "http": { - "timeout": 5000, - "retries": 1 - } -} diff --git a/libs/core/config/package.json b/libs/core/config/package.json index 9d90e534..c1c49a21 100644 --- a/libs/core/config/package.json +++ b/libs/core/config/package.json @@ -14,13 +14,7 @@ "build": "tsc", "dev": "tsc --watch", "test": "bun test", - "clean": "rm -rf dist", - "cli": "bun run src/cli.ts", - "validate": "bun run src/cli.ts --validate", - "check": "bun run src/cli.ts --check" - }, - "bin": { - "config-cli": "./dist/cli.js" + "clean": "rm -rf dist" }, "dependencies": { "@stock-bot/logger": "workspace:*", diff --git a/libs/core/config/src/cli.ts b/libs/core/config/src/cli.ts deleted file mode 100644 index ed12f00e..00000000 --- a/libs/core/config/src/cli.ts +++ /dev/null @@ -1,175 +0,0 @@ -#!/usr/bin/env bun -/* eslint-disable no-console */ -import { join } from 'path'; -import { parseArgs } from 'util'; -import { redactSecrets } from './utils/secrets'; -import { - checkRequiredEnvVars, - formatValidationResult, - validateCompleteness, - validateConfig, -} from './utils/validation'; -import { ConfigManager } from './config-manager'; -import { baseAppSchema } from './schemas'; -import type { Environment } from './types'; - -interface CliOptions { - config?: string; - env?: string; - validate?: boolean; - show?: boolean; - check?: boolean; - json?: boolean; - help?: boolean; -} - -const REQUIRED_PATHS = [ - 'service.name', - 'service.port', - 'database.postgres.host', - 'database.postgres.database', -]; - -const REQUIRED_ENV_VARS = ['NODE_ENV']; - -const SECRET_PATHS = [ - 'database.postgres.password', - 'database.mongodb.uri', - 'providers.quoteMedia.apiKey', - 'providers.interactiveBrokers.clientId', -]; - -function printUsage() { - console.log(` -Stock Bot Configuration CLI - -Usage: bun run config-cli [options] - -Options: - --config Path to config directory (default: ./config) - --env Environment to use (development, test, production) - --validate Validate configuration against schema - --show Show current configuration (secrets redacted) - --check Run all configuration checks - --json Output in JSON format - --help Show this help message - -Examples: - # Validate configuration - bun run config-cli --validate - - # Show configuration for production - bun run config-cli --env production --show - - # Run all checks - bun run config-cli --check - - # Output configuration as JSON - bun run config-cli --show --json -`); -} - -async function main() { - const { values } = parseArgs({ - args: process.argv.slice(2), - options: { - config: { type: 'string' }, - env: { type: 'string' }, - validate: { type: 'boolean' }, - show: { type: 'boolean' }, - check: { type: 'boolean' }, - json: { type: 'boolean' }, - help: { type: 'boolean' }, - }, - }) as { values: CliOptions }; - - if (values.help) { - printUsage(); - process.exit(0); - } - - const configPath = values.config || join(process.cwd(), 'config'); - const environment = values.env as Environment; - - try { - const manager = new ConfigManager({ - configPath, - environment, - }); - - const config = await manager.initialize(baseAppSchema); - - if (values.validate) { - const result = validateConfig(config, baseAppSchema); - - if (values.json) { - console.log(JSON.stringify(result, null, 2)); - } else { - console.log(formatValidationResult(result)); - } - - process.exit(result.valid ? 0 : 1); - } - - if (values.show) { - const redacted = redactSecrets(config, SECRET_PATHS); - - if (values.json) { - console.log(JSON.stringify(redacted, null, 2)); - } else { - console.log('Current Configuration:'); - console.log(JSON.stringify(redacted, null, 2)); - } - } - - if (values.check) { - console.log('Running configuration checks...\n'); - - // Schema validation - console.log('1. Schema Validation:'); - const schemaResult = validateConfig(config, baseAppSchema); - console.log(formatValidationResult(schemaResult)); - console.log(); - - // Environment variables - console.log('2. Required Environment Variables:'); - const envResult = checkRequiredEnvVars(REQUIRED_ENV_VARS); - console.log(formatValidationResult(envResult)); - console.log(); - - // Required paths - console.log('3. Required Configuration Paths:'); - const pathResult = validateCompleteness(config, REQUIRED_PATHS); - console.log(formatValidationResult(pathResult)); - console.log(); - - // Overall result - const allValid = schemaResult.valid && envResult.valid && pathResult.valid; - - if (allValid) { - console.log('โœ… All configuration checks passed!'); - process.exit(0); - } else { - console.log('โŒ Some configuration checks failed'); - process.exit(1); - } - } - - if (!values.validate && !values.show && !values.check) { - console.log('No action specified. Use --help for usage information.'); - process.exit(1); - } - } catch (error) { - if (values.json) { - console.error(JSON.stringify({ error: String(error) })); - } else { - console.error('Error:', error); - } - process.exit(1); - } -} - -// Run CLI -if (import.meta.main) { - main(); -} diff --git a/libs/core/config/src/config-manager.ts b/libs/core/config/src/config-manager.ts index 759f67f2..afad344a 100644 --- a/libs/core/config/src/config-manager.ts +++ b/libs/core/config/src/config-manager.ts @@ -1,9 +1,9 @@ import { join } from 'path'; import { z } from 'zod'; import { getLogger } from '@stock-bot/logger'; +import { ConfigError, ConfigValidationError } from './errors'; import { EnvLoader } from './loaders/env.loader'; import { FileLoader } from './loaders/file.loader'; -import { ConfigError, ConfigValidationError } from './errors'; import type { ConfigLoader, ConfigManagerOptions, @@ -21,8 +21,9 @@ export class ConfigManager> { private environment: Environment; private schema?: ConfigSchema; - constructor(options: ConfigManagerOptions = {}) { + constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) { this.environment = options.environment || this.detectEnvironment(); + this.schema = defaultSchema; if (options.loaders) { this.loaders = options.loaders; @@ -32,20 +33,17 @@ export class ConfigManager> { } } - /** - * Initialize the configuration by loading from all sources - */ initialize(schema?: ConfigSchema): T { if (this.config) { return this.config; } - this.schema = schema; + if (schema) { + this.schema = schema; + } - // Sort loaders by priority (higher priority last) const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority); - // Load configurations from all sources const configs: Record[] = []; for (const loader of sortedLoaders) { const config = loader.load(); @@ -54,10 +52,8 @@ export class ConfigManager> { } } - // Merge all configurations const mergedConfig = this.merge(...configs) as T; - // Add environment if not present if ( typeof mergedConfig === 'object' && mergedConfig !== null && @@ -66,7 +62,6 @@ export class ConfigManager> { (mergedConfig as Record)['environment'] = this.environment; } - // Validate if schema provided if (this.schema) { try { this.config = this.schema.parse(mergedConfig) as T; @@ -90,9 +85,6 @@ export class ConfigManager> { return this.config; } - /** - * Get the current configuration - */ get(): T { if (!this.config) { throw new ConfigError('Configuration not initialized. Call initialize() first.'); @@ -100,9 +92,6 @@ export class ConfigManager> { return this.config; } - /** - * Get a specific configuration value by path - */ getValue(path: string): R { const config = this.get(); const keys = path.split('.'); @@ -119,9 +108,6 @@ export class ConfigManager> { return value as R; } - /** - * Check if a configuration path exists - */ has(path: string): boolean { try { this.getValue(path); @@ -131,9 +117,6 @@ export class ConfigManager> { } } - /** - * Update configuration at runtime - */ set(updates: DeepPartial): void { if (!this.config) { throw new ConfigError('Configuration not initialized. Call initialize() first.'); @@ -161,23 +144,14 @@ export class ConfigManager> { } } - /** - * Get the current environment - */ getEnvironment(): Environment { return this.environment; } - /** - * Reset configuration - */ reset(): void { this.config = null; } - /** - * Validate configuration against a schema - */ validate(schema: S): z.infer { const config = this.get(); return schema.parse(config); @@ -201,11 +175,12 @@ export class ConfigManager> { } /** - * Deep merge with circular reference handling + * Deep merge tracking only active ancestor objects so valid shared DAG references + * (e.g. redis = database.dragonfly) are preserved rather than replaced with '[Circular]'. */ private merge(...objects: Record[]): Record { - const seen = new WeakSet(); - + const ancestors = new WeakSet(); + const mergeRecursive = (...objs: Record[]): Record => { const result: Record = {}; @@ -219,17 +194,21 @@ export class ConfigManager> { !(value instanceof Date) && !(value instanceof RegExp) ) { - // Check for circular reference - if (seen.has(value)) { + if (ancestors.has(value)) { result[key] = '[Circular]'; continue; } - seen.add(value); - - result[key] = mergeRecursive( - (result[key] as Record) || {}, - value as Record - ); + ancestors.add(value); + try { + result[key] = mergeRecursive( + (result[key] && typeof result[key] === 'object' && !Array.isArray(result[key]) + ? (result[key] as Record) + : {}), + value as Record + ); + } finally { + ancestors.delete(value); + } } else { result[key] = value; } @@ -238,7 +217,7 @@ export class ConfigManager> { return result; }; - + return mergeRecursive(...objects); } } diff --git a/libs/core/config/src/index.ts b/libs/core/config/src/index.ts index 8acb702f..4fd61f45 100644 --- a/libs/core/config/src/index.ts +++ b/libs/core/config/src/index.ts @@ -1,14 +1,10 @@ import { ConfigManager, type ConfigManagerOptions } from './config-manager'; +import type { ConfigSchema } from './types'; -// Export only what's actually used export { ConfigManager } from './config-manager'; export type { ConfigManagerOptions } from './config-manager'; export { toUnifiedConfig } from './schemas/unified-app.schema'; - -// Export used types export type { BaseAppConfig, UnifiedAppConfig } from './schemas'; - -// Export schemas that are used by apps export { baseAppSchema, dragonflyConfigSchema, @@ -24,33 +20,13 @@ export { type ProviderName, } from './schemas'; -// createAppConfig function for apps/stock export function createAppConfig( schema: unknown, options?: ConfigManagerOptions ): ConfigManager { - return new ConfigManager(options); + const zodSchema = + schema && typeof schema === 'object' && 'parse' in schema + ? (schema as ConfigSchema) + : undefined; + return new ConfigManager(options, zodSchema); } - -// Export utilities -export { - SecretValue, - secret, - isSecret, - isSecretEnvVar, - COMMON_SECRET_PATTERNS, - redactSecrets, - wrapSecretEnvVars, - secretSchema, - secretStringSchema -} from './utils/secrets'; - -export { - checkRequiredEnvVars, - createStrictSchema, - formatValidationResult, - mergeSchemas, - validateConfig, - validateCompleteness, - type ValidationResult -} from './utils/validation'; diff --git a/libs/core/config/src/loaders/env.loader.ts b/libs/core/config/src/loaders/env.loader.ts index 3c073c91..08d82f62 100644 --- a/libs/core/config/src/loaders/env.loader.ts +++ b/libs/core/config/src/loaders/env.loader.ts @@ -10,7 +10,7 @@ interface EnvLoaderOptions { } export class EnvLoader implements ConfigLoader { - readonly priority = 100; // Highest priority + readonly priority = 100; constructor( private prefix = '', @@ -27,10 +27,12 @@ export class EnvLoader implements ConfigLoader { load(): Record { try { - // Load root .env file - try multiple possible locations + // Stop on the first .env file found so repo-root runs never traverse into parent directories const possiblePaths = ['./.env', '../.env', '../../.env', '../../../.env']; for (const path of possiblePaths) { - this.loadEnvFile(path); + if (this.loadEnvFile(path)) { + break; + } } const config: Record = {}; @@ -44,10 +46,8 @@ export class EnvLoader implements ConfigLoader { const configKey = this.prefix ? key.slice(this.prefix.length) : key; if (!this.options.convertCase && !this.options.nestedDelimiter) { - // Simple case - just keep the key as is config[configKey] = this.parseValue(value || ''); } else { - // Handle nested structure or case conversion this.setConfigValue(config, configKey, value || ''); } } @@ -60,22 +60,19 @@ export class EnvLoader implements ConfigLoader { private setConfigValue(config: Record, key: string, value: string): void { try { - // Handle provider-specific environment variables (only for application usage, not tests) if (!this.prefix && !this.options.convertCase) { const providerMapping = this.getProviderMapping(key); if (providerMapping) { - // For certain fields, we need to preserve the string value const shouldPreserveString = this.shouldPreserveStringForKey(key); const parsedValue = shouldPreserveString ? value : this.parseValue(value); - this.setNestedValue(config, providerMapping.path, parsedValue); + this.setNestedValue(config, [...providerMapping.path], parsedValue); return; } } - const parsedValue = this.parseValue(value); + const parsedValue = this.shouldPreserveStringForKey(key) ? value : this.parseValue(value); if (this.options.convertCase) { - // Convert to camelCase const camelKey = this.toCamelCase(key); config[camelKey] = parsedValue; } else if ( @@ -83,32 +80,26 @@ export class EnvLoader implements ConfigLoader { this.options.nestedDelimiter !== '_' && key.includes(this.options.nestedDelimiter) ) { - // Handle nested delimiter (e.g., APP__NAME -> { APP: { NAME: value } }) const parts = key.split(this.options.nestedDelimiter); this.setNestedValue(config, parts, parsedValue); + } else if (key.includes('_')) { + const path = key.toLowerCase().split('_'); + this.setNestedValue(config, path, parsedValue); } else { - // Convert to nested structure based on underscores, or keep as-is if no underscores - if (key.includes('_')) { - const path = key.toLowerCase().split('_'); - this.setNestedValue(config, path, parsedValue); - } else { - // Single key without underscores - keep original case - config[key] = parsedValue; - } + config[key] = parsedValue; } } catch { - // Skip environment variables that can't be set (readonly properties) - // This is expected behavior for system environment variables + // Skip environment variables that cannot be set on readonly target keys } } private setNestedValue(obj: Record, path: string[], value: unknown): boolean { if (path.length === 0) { - return false; // Cannot set value on empty path + return false; } const lastKey = path.pop(); if (!lastKey) { - return false; // This should never happen due to length check above + return false; } try { @@ -122,7 +113,6 @@ export class EnvLoader implements ConfigLoader { (target as Record)[lastKey] = value; return true; } catch { - // If we can't assign to any property (readonly), skip this env var silently return false; } } @@ -132,22 +122,19 @@ export class EnvLoader implements ConfigLoader { } private shouldPreserveStringForKey(key: string): boolean { - // Keys that should preserve string values even if they look like numbers const preserveStringKeys = [ 'QM_WEBMASTER_ID', 'IB_MARKET_DATA_TYPE', 'MONGODB_URI', 'MONGODB_READ_URI', - 'MONGODB_PASSWORD', - 'POSTGRES_PASSWORD', - 'DRAGONFLY_PASSWORD', - 'QUESTDB_PASSWORD', ]; - return preserveStringKeys.includes(key); + if (preserveStringKeys.includes(key)) { + return true; + } + return /(?:^|_)(?:PASSWORD|SECRET|TOKEN|API_KEY|URI)$/i.test(key); } private getProviderMapping(envKey: string): { path: string[] } | null { - // Provider-specific and special environment variable mappings const providerMappings: Record = { // Database mappings MONGODB_URI: ['database', 'mongodb', 'uri'], @@ -167,8 +154,25 @@ export class EnvLoader implements ConfigLoader { DRAGONFLY_HOST: ['database', 'dragonfly', 'host'], DRAGONFLY_PORT: ['database', 'dragonfly', 'port'], DRAGONFLY_PASSWORD: ['database', 'dragonfly', 'password'], + QUESTDB_ENABLED: ['database', 'questdb', 'enabled'], QUESTDB_HOST: ['database', 'questdb', 'host'], QUESTDB_PORT: ['database', 'questdb', 'httpPort'], + QUESTDB_HTTP_PORT: ['database', 'questdb', 'httpPort'], + QUESTDB_PG_PORT: ['database', 'questdb', 'pgPort'], + QUESTDB_ILP_PORT: ['database', 'questdb', 'ilpPort'], + QUESTDB_INFLUX_PORT: ['database', 'questdb', 'influxPort'], + QUESTDB_USER: ['database', 'questdb', 'user'], + QUESTDB_PASSWORD: ['database', 'questdb', 'password'], + + // Queue mappings + QUEUE_ENABLED: ['queue', 'enabled'], + QUEUE_ENABLE_SCHEDULED_JOBS: ['queue', 'enableScheduledJobs'], + QUEUE_WORKERS: ['queue', 'workers'], + QUEUE_CONCURRENCY: ['queue', 'concurrency'], + QUEUE_REDIS_HOST: ['queue', 'redis', 'host'], + QUEUE_REDIS_PORT: ['queue', 'redis', 'port'], + QUEUE_REDIS_PASSWORD: ['queue', 'redis', 'password'], + QUEUE_REDIS_DB: ['queue', 'redis', 'db'], // WebShare provider mappings WEBSHARE_API_KEY: ['webshare', 'apiKey'], @@ -210,7 +214,7 @@ export class EnvLoader implements ConfigLoader { NAME: ['name'], VERSION: ['version'], - // Log mappings (using LOG_ prefix for all) + // Log mappings LOG_LEVEL: ['log', 'level'], LOG_FORMAT: ['log', 'format'], LOG_HIDE_OBJECT: ['log', 'hideObject'], @@ -218,7 +222,6 @@ export class EnvLoader implements ConfigLoader { LOG_LOKI_HOST: ['log', 'loki', 'host'], LOG_LOKI_PORT: ['log', 'loki', 'port'], - // Special mappings to avoid conflicts DEBUG_MODE: ['debug'], }; @@ -231,12 +234,11 @@ export class EnvLoader implements ConfigLoader { return value; } - // Try to parse as JSON first if enabled if (this.options.parseJson) { try { return JSON.parse(value); } catch { - // Not JSON, continue with other parsing + // Not JSON, continue } } @@ -244,7 +246,6 @@ export class EnvLoader implements ConfigLoader { return value; } - // Handle booleans if (value.toLowerCase() === 'true') { return true; } @@ -252,7 +253,6 @@ export class EnvLoader implements ConfigLoader { return false; } - // Handle numbers (but preserve strings with leading zeros or plus signs) if (!/^[+-]/.test(value) && !/^0\d/.test(value)) { const num = Number(value); if (!isNaN(num) && value !== '') { @@ -260,7 +260,6 @@ export class EnvLoader implements ConfigLoader { } } - // Handle null/undefined if (value.toLowerCase() === 'null') { return null; } @@ -268,11 +267,10 @@ export class EnvLoader implements ConfigLoader { return undefined; } - // Return as string return value; } - private loadEnvFile(filePath: string): void { + private loadEnvFile(filePath: string): boolean { try { const envContent = readFileSync(filePath, 'utf-8'); const lines = envContent.split('\n'); @@ -280,18 +278,20 @@ export class EnvLoader implements ConfigLoader { for (const line of lines) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) { - continue; // Skip empty lines and comments + continue; } const equalIndex = trimmed.indexOf('='); if (equalIndex === -1) { - continue; // Skip lines without = + continue; } const key = trimmed.substring(0, equalIndex).trim(); + if (!key) { + continue; + } let value = trimmed.substring(equalIndex + 1).trim(); - // Remove surrounding quotes if present if ( (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")) @@ -299,13 +299,12 @@ export class EnvLoader implements ConfigLoader { value = value.slice(1, -1); } - // Only set if not already set (allows override precedence) if (!(key in process.env)) { process.env[key] = value; } } + return true; } catch (error: unknown) { - // File not found is not an error (env files are optional) if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT') { // eslint-disable-next-line no-console console.warn( @@ -313,6 +312,7 @@ export class EnvLoader implements ConfigLoader { error instanceof Error ? error.message : String(error) ); } + return false; } } } diff --git a/libs/core/config/src/utils/secrets.ts b/libs/core/config/src/utils/secrets.ts deleted file mode 100644 index 29febf93..00000000 --- a/libs/core/config/src/utils/secrets.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { z } from 'zod'; - -/** - * Secret value wrapper to prevent accidental logging - */ -export class SecretValue { - private readonly value: T; - private readonly masked: string; - - constructor(value: T, mask: string = '***') { - this.value = value; - this.masked = mask; - } - - /** - * Get the actual secret value - * @param reason - Required reason for accessing the secret - */ - reveal(reason: string): T { - if (!reason) { - throw new Error('Reason required for revealing secret value'); - } - return this.value; - } - - /** - * Get masked representation - */ - toString(): string { - return this.masked; - } - - /** - * Prevent JSON serialization of actual value - */ - toJSON(): string { - return this.masked; - } - - /** - * Check if value matches without revealing it - */ - equals(other: T): boolean { - return this.value === other; - } - - /** - * Transform the secret value - */ - map(fn: (value: T) => R, reason: string): SecretValue { - return new SecretValue(fn(this.reveal(reason))); - } -} - -/** - * Zod schema for secret values - */ -export const secretSchema = (_schema: T) => { - return z.custom>>(val => val instanceof SecretValue, { - message: 'Expected SecretValue instance', - }); -}; - -/** - * Transform string to SecretValue in Zod schema - */ -export const secretStringSchema = z.string().transform(val => new SecretValue(val)); - -/** - * Create a secret value - */ -export function secret(value: T, mask?: string): SecretValue { - return new SecretValue(value, mask); -} - -/** - * Check if a value is a secret - */ -export function isSecret(value: unknown): value is SecretValue { - return value instanceof SecretValue; -} - -/** - * Redact secrets from an object - */ -export function redactSecrets>( - obj: T, - secretPaths: string[] = [] -): T { - const result = redactSecretValues(obj) as T; - - // Redact known secret paths - for (const path of secretPaths) { - const keys = path.split('.'); - let current: Record = result; - - for (let i = 0; i < keys.length - 1; i++) { - const key = keys[i]; - if (key && current[key] && typeof current[key] === 'object') { - current = current[key] as Record; - } else { - break; - } - } - - const lastKey = keys[keys.length - 1]; - if (current && lastKey && lastKey in current) { - current[lastKey] = '***REDACTED***'; - } - } - - // Recursively redact SecretValue instances - function redactSecretValues(obj: unknown): unknown { - if (obj === null || obj === undefined) { - return obj; - } - - if (isSecret(obj)) { - return obj.toString(); - } - - if (Array.isArray(obj)) { - return obj.map(redactSecretValues); - } - - if (typeof obj === 'object') { - const result: Record = {}; - for (const [key, value] of Object.entries(obj)) { - result[key] = redactSecretValues(value); - } - return result; - } - - return obj; - } - - return result; -} - -/** - * Environment variable names that should be treated as secrets - */ -export const COMMON_SECRET_PATTERNS = [ - /password/i, - /secret/i, - /key/i, - /token/i, - /credential/i, - /private/i, - /auth/i, - /api[-_]?key/i, -]; - -/** - * Check if an environment variable name indicates a secret - */ -export function isSecretEnvVar(name: string): boolean { - return COMMON_SECRET_PATTERNS.some(pattern => pattern.test(name)); -} - -/** - * Wrap environment variables that look like secrets - */ -export function wrapSecretEnvVars( - env: Record -): Record { - const result: Record = {}; - - for (const [key, value] of Object.entries(env)) { - if (value !== undefined && isSecretEnvVar(key)) { - result[key] = new SecretValue(value, `***${key}***`); - } else { - result[key] = value; - } - } - - return result; -} diff --git a/libs/core/config/src/utils/validation.ts b/libs/core/config/src/utils/validation.ts deleted file mode 100644 index 169cc149..00000000 --- a/libs/core/config/src/utils/validation.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { z } from 'zod'; -import { defined } from '@stock-bot/invariants'; - -export interface ValidationResult { - valid: boolean; - errors?: Array<{ - path: string; - message: string; - expected?: string; - received?: string; - }>; - warnings?: Array<{ - path: string; - message: string; - }>; -} - -/** - * Validate configuration against a schema - */ -export function validateConfig(config: unknown, schema: z.ZodSchema): ValidationResult { - try { - schema.parse(config); - return { valid: true }; - } catch (error) { - if (error instanceof z.ZodError) { - const errors = error.errors.map(err => ({ - path: err.path.join('.'), - message: err.message, - expected: 'expected' in err ? String(err.expected) : undefined, - received: 'received' in err ? String(err.received) : undefined, - })); - - return { valid: false, errors }; - } - - throw error; - } -} - -/** - * Check for required environment variables - */ -export function checkRequiredEnvVars(required: string[]): ValidationResult { - const errors: ValidationResult['errors'] = []; - - for (const envVar of required) { - if (!process.env[envVar]) { - errors.push({ - path: `env.${envVar}`, - message: `Required environment variable ${envVar} is not set`, - }); - } - } - - return { - valid: errors.length === 0, - errors: errors.length > 0 ? errors : undefined, - }; -} - -/** - * Validate configuration completeness - */ -export function validateCompleteness( - config: Record, - required: string[] -): ValidationResult { - const errors: ValidationResult['errors'] = []; - - for (const path of required) { - const keys = path.split('.'); - let current: unknown = config; - let found = true; - - for (const key of keys) { - if (current && typeof current === 'object' && key in current) { - current = (current as Record)[key]; - } else { - found = false; - break; - } - } - - if (!found || current === undefined || current === null) { - errors.push({ - path, - message: `Required configuration value is missing`, - }); - } - } - - return { - valid: errors.length === 0, - errors: errors.length > 0 ? errors : undefined, - }; -} - -/** - * Format validation result for display - */ -export function formatValidationResult(result: ValidationResult): string { - const lines: string[] = []; - - if (result.valid) { - lines.push('โœ… Configuration is valid'); - } else { - lines.push('โŒ Configuration validation failed'); - } - - if (result.errors && result.errors.length > 0) { - lines.push('\nErrors:'); - for (const error of result.errors) { - lines.push(` - ${error.path}: ${error.message}`); - if (error.expected && error.received) { - lines.push(` Expected: ${error.expected}, Received: ${error.received}`); - } - } - } - - if (result.warnings && result.warnings.length > 0) { - lines.push('\nWarnings:'); - for (const warning of result.warnings) { - lines.push(` - ${warning.path}: ${warning.message}`); - } - } - - return lines.join('\n'); -} - -/** - * Create a strict schema that doesn't allow extra properties - */ -export function createStrictSchema(shape: T): z.ZodObject { - return z.object(shape).strict(); -} - -/** - * Merge multiple schemas - */ -export function mergeSchemas( - ...schemas: T -): z.ZodIntersection { - if (schemas.length < 2) { - throw new Error('At least two schemas required for merge'); - } - - let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1])); - - for (let i = 2; i < schemas.length; i++) { - result = result.and(defined(schemas[i])); - } - - return result as z.ZodIntersection; -} diff --git a/libs/core/config/test/utils.test.ts b/libs/core/config/test/utils.test.ts deleted file mode 100644 index 65d1b013..00000000 --- a/libs/core/config/test/utils.test.ts +++ /dev/null @@ -1,518 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; -import { z } from 'zod'; -import { - checkRequiredEnvVars, - COMMON_SECRET_PATTERNS, - createStrictSchema, - formatValidationResult, - isSecret, - isSecretEnvVar, - mergeSchemas, - redactSecrets, - secret, - secretSchema, - secretStringSchema, - SecretValue, - validateCompleteness, - validateConfig, - wrapSecretEnvVars, - type ValidationResult, -} from '../src'; - -describe('Config Utils', () => { - describe('SecretValue', () => { - it('should create a secret value', () => { - const secret = new SecretValue('my-secret'); - expect(secret).toBeInstanceOf(SecretValue); - expect(secret.toString()).toBe('***'); - }); - - it('should use custom mask', () => { - const secret = new SecretValue('my-secret', 'HIDDEN'); - expect(secret.toString()).toBe('HIDDEN'); - }); - - it('should reveal value with reason', () => { - const secret = new SecretValue('my-secret'); - expect(secret.reveal('testing')).toBe('my-secret'); - }); - - it('should throw when revealing without reason', () => { - const secret = new SecretValue('my-secret'); - expect(() => secret.reveal('')).toThrow('Reason required for revealing secret value'); - }); - - it('should mask value in JSON', () => { - const secret = new SecretValue('my-secret'); - expect(JSON.stringify(secret)).toBe('"***"'); - expect(secret.toJSON()).toBe('***'); - }); - - it('should compare values without revealing', () => { - const secret = new SecretValue('my-secret'); - expect(secret.equals('my-secret')).toBe(true); - expect(secret.equals('other-secret')).toBe(false); - }); - - it('should map secret values', () => { - const secret = new SecretValue('hello'); - const mapped = secret.map(val => val.toUpperCase(), 'testing transformation'); - expect(mapped.reveal('checking result')).toBe('HELLO'); - expect(mapped.toString()).toBe('***'); - }); - - it('should work with non-string types', () => { - const numberSecret = new SecretValue(12345, 'XXX'); - expect(numberSecret.reveal('test')).toBe(12345); - expect(numberSecret.toString()).toBe('XXX'); - - const objectSecret = new SecretValue({ key: 'value' }, '[OBJECT]'); - expect(objectSecret.reveal('test')).toEqual({ key: 'value' }); - expect(objectSecret.toString()).toBe('[OBJECT]'); - }); - }); - - describe('secret helper function', () => { - it('should create secret values', () => { - const s = secret('my-secret'); - expect(s).toBeInstanceOf(SecretValue); - expect(s.reveal('test')).toBe('my-secret'); - }); - - it('should accept custom mask', () => { - const s = secret('my-secret', 'REDACTED'); - expect(s.toString()).toBe('REDACTED'); - }); - }); - - describe('isSecret', () => { - it('should identify secret values', () => { - expect(isSecret(new SecretValue('test'))).toBe(true); - expect(isSecret(secret('test'))).toBe(true); - expect(isSecret('test')).toBe(false); - expect(isSecret(null)).toBe(false); - expect(isSecret(undefined)).toBe(false); - expect(isSecret({})).toBe(false); - }); - }); - - describe('secretSchema', () => { - it('should validate SecretValue instances', () => { - const schema = secretSchema(z.string()); - const secretVal = new SecretValue('test'); - - expect(() => schema.parse(secretVal)).not.toThrow(); - expect(() => schema.parse('test')).toThrow(); - expect(() => schema.parse(null)).toThrow(); - }); - }); - - describe('secretStringSchema', () => { - it('should transform string to SecretValue', () => { - const result = secretStringSchema.parse('my-secret'); - expect(result).toBeInstanceOf(SecretValue); - expect(result.reveal('test')).toBe('my-secret'); - }); - - it('should reject non-strings', () => { - expect(() => secretStringSchema.parse(123)).toThrow(); - expect(() => secretStringSchema.parse(null)).toThrow(); - }); - }); - - describe('redactSecrets', () => { - it('should redact specified paths', () => { - const obj = { - username: 'admin', - password: 'secret123', - nested: { - apiKey: 'key123', - public: 'visible', - }, - }; - - const redacted = redactSecrets(obj, ['password', 'nested.apiKey']); - - expect(redacted).toEqual({ - username: 'admin', - password: '***REDACTED***', - nested: { - apiKey: '***REDACTED***', - public: 'visible', - }, - }); - }); - - it('should redact SecretValue instances', () => { - const obj = { - normal: 'value', - secret: new SecretValue('hidden', 'MASKED'), - nested: { - anotherSecret: secret('also-hidden'), - }, - }; - - const redacted = redactSecrets(obj); - - expect(redacted).toEqual({ - normal: 'value', - secret: 'MASKED', - nested: { - anotherSecret: '***', - }, - }); - }); - - it('should handle arrays', () => { - const obj = { - items: [ - { name: 'item1', secret: new SecretValue('s1') }, - { name: 'item2', secret: new SecretValue('s2') }, - ], - }; - - const redacted = redactSecrets(obj); - - expect(redacted.items).toEqual([ - { name: 'item1', secret: '***' }, - { name: 'item2', secret: '***' }, - ]); - }); - - it('should handle null and undefined', () => { - const obj = { - nullValue: null, - undefinedValue: undefined, - secret: new SecretValue('test'), - }; - - const redacted = redactSecrets(obj); - - expect(redacted).toEqual({ - nullValue: null, - undefinedValue: undefined, - secret: '***', - }); - }); - - it('should handle non-existent paths gracefully', () => { - const obj = { a: 'value' }; - const redacted = redactSecrets(obj, ['b.c.d']); - expect(redacted).toEqual({ a: 'value' }); - }); - - it('should not modify original object', () => { - const obj = { password: 'secret', nested: { token: 'nested-secret' } }; - const original = { password: 'secret', nested: { token: 'nested-secret' } }; - const redacted = redactSecrets(obj, ['password', 'nested.token']); - expect(redacted.nested.token).toBe('***REDACTED***'); - expect(obj).toEqual(original); - }); - }); - - describe('isSecretEnvVar', () => { - it('should identify common secret patterns', () => { - // Positive cases - expect(isSecretEnvVar('PASSWORD')).toBe(true); - expect(isSecretEnvVar('DB_PASSWORD')).toBe(true); - expect(isSecretEnvVar('API_KEY')).toBe(true); - expect(isSecretEnvVar('API-KEY')).toBe(true); - expect(isSecretEnvVar('SECRET_TOKEN')).toBe(true); - expect(isSecretEnvVar('AUTH_TOKEN')).toBe(true); - expect(isSecretEnvVar('PRIVATE_KEY')).toBe(true); - expect(isSecretEnvVar('CREDENTIAL')).toBe(true); - expect(isSecretEnvVar('password')).toBe(true); // Case insensitive - - // Negative cases - expect(isSecretEnvVar('USERNAME')).toBe(false); - expect(isSecretEnvVar('PORT')).toBe(false); - expect(isSecretEnvVar('DEBUG')).toBe(false); - expect(isSecretEnvVar('NODE_ENV')).toBe(false); - }); - }); - - describe('wrapSecretEnvVars', () => { - it('should wrap secret environment variables', () => { - const env = { - USERNAME: 'admin', - PASSWORD: 'secret123', - API_KEY: 'key123', - PORT: '3000', - }; - - const wrapped = wrapSecretEnvVars(env); - - expect(wrapped.USERNAME).toBe('admin'); - expect(wrapped.PORT).toBe('3000'); - - expect(isSecret(wrapped.PASSWORD)).toBe(true); - expect(isSecret(wrapped.API_KEY)).toBe(true); - - const passwordSecret = wrapped.PASSWORD as SecretValue; - expect(passwordSecret.reveal('test')).toBe('secret123'); - expect(passwordSecret.toString()).toBe('***PASSWORD***'); - }); - - it('should handle undefined values', () => { - const env = { - PASSWORD: undefined, - USERNAME: 'admin', - }; - - const wrapped = wrapSecretEnvVars(env); - - expect(wrapped.PASSWORD).toBeUndefined(); - expect(wrapped.USERNAME).toBe('admin'); - }); - }); - - describe('validateConfig', () => { - const schema = z.object({ - name: z.string(), - port: z.number(), - optional: z.string().optional(), - }); - - it('should validate valid config', () => { - const result = validateConfig({ name: 'app', port: 3000 }, schema); - expect(result.valid).toBe(true); - expect(result.errors).toBeUndefined(); - }); - - it('should return errors for invalid config', () => { - const result = validateConfig({ name: 'app', port: 'invalid' }, schema); - expect(result.valid).toBe(false); - expect(result.errors).toBeDefined(); - expect(result.errors![0].path).toBe('port'); - expect(result.errors![0].message).toContain('Expected number'); - }); - - it('should handle missing required fields', () => { - const result = validateConfig({ port: 3000 }, schema); - expect(result.valid).toBe(false); - expect(result.errors).toBeDefined(); - expect(result.errors![0].path).toBe('name'); - }); - - it('should rethrow non-Zod errors', () => { - const badSchema = { - parse: () => { - throw new Error('Not a Zod error'); - }, - } as any; - - expect(() => validateConfig({}, badSchema)).toThrow('Not a Zod error'); - }); - }); - - describe('checkRequiredEnvVars', () => { - const originalEnv = { ...process.env }; - - beforeEach(() => { - // Clear environment - for (const key in process.env) { - delete process.env[key]; - } - }); - - afterEach(() => { - // Restore environment - for (const key in process.env) { - delete process.env[key]; - } - Object.assign(process.env, originalEnv); - }); - - it('should pass when all required vars are set', () => { - process.env.API_KEY = 'key123'; - process.env.DATABASE_URL = 'postgres://...'; - - const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL']); - expect(result.valid).toBe(true); - expect(result.errors).toBeUndefined(); - }); - - it('should fail when required vars are missing', () => { - process.env.API_KEY = 'key123'; - - const result = checkRequiredEnvVars(['API_KEY', 'DATABASE_URL', 'MISSING_VAR']); - expect(result.valid).toBe(false); - expect(result.errors).toHaveLength(2); - expect(result.errors![0].path).toBe('env.DATABASE_URL'); - expect(result.errors![1].path).toBe('env.MISSING_VAR'); - }); - - it('should handle empty required list', () => { - const result = checkRequiredEnvVars([]); - expect(result.valid).toBe(true); - expect(result.errors).toBeUndefined(); - }); - }); - - describe('validateCompleteness', () => { - it('should validate complete config', () => { - const config = { - database: { - host: 'localhost', - port: 5432, - credentials: { - username: 'admin', - password: 'secret', - }, - }, - }; - - const result = validateCompleteness(config, [ - 'database.host', - 'database.port', - 'database.credentials.username', - ]); - - expect(result.valid).toBe(true); - expect(result.errors).toBeUndefined(); - }); - - it('should detect missing values', () => { - const config = { - database: { - host: 'localhost', - credentials: {}, - }, - }; - - const result = validateCompleteness(config, [ - 'database.host', - 'database.port', - 'database.credentials.username', - ]); - - expect(result.valid).toBe(false); - expect(result.errors).toHaveLength(2); - expect(result.errors![0].path).toBe('database.port'); - expect(result.errors![1].path).toBe('database.credentials.username'); - }); - - it('should handle null and undefined as missing', () => { - const config = { - a: null, - b: undefined, - c: 'value', - }; - - const result = validateCompleteness(config, ['a', 'b', 'c']); - expect(result.valid).toBe(false); - expect(result.errors).toHaveLength(2); - }); - - it('should handle non-existent paths', () => { - const config = { a: 'value' }; - const result = validateCompleteness(config, ['b.c.d']); - expect(result.valid).toBe(false); - expect(result.errors![0].path).toBe('b.c.d'); - }); - }); - - describe('formatValidationResult', () => { - it('should format valid result', () => { - const result: ValidationResult = { valid: true }; - const formatted = formatValidationResult(result); - expect(formatted).toBe('โœ… Configuration is valid'); - }); - - it('should format errors', () => { - const result: ValidationResult = { - valid: false, - errors: [ - { path: 'port', message: 'Expected number' }, - { - path: 'database.host', - message: 'Invalid value', - expected: 'string', - received: 'number', - }, - ], - }; - - const formatted = formatValidationResult(result); - expect(formatted).toContain('โŒ Configuration validation failed'); - expect(formatted).toContain('Errors:'); - expect(formatted).toContain('- port: Expected number'); - expect(formatted).toContain('- database.host: Invalid value'); - expect(formatted).toContain('Expected: string, Received: number'); - }); - - it('should format warnings', () => { - const result: ValidationResult = { - valid: true, - warnings: [{ path: 'deprecated.feature', message: 'This feature is deprecated' }], - }; - - const formatted = formatValidationResult(result); - expect(formatted).toContain('โœ… Configuration is valid'); - expect(formatted).toContain('Warnings:'); - expect(formatted).toContain('- deprecated.feature: This feature is deprecated'); - }); - }); - - describe('createStrictSchema', () => { - it('should create strict schema', () => { - const schema = createStrictSchema({ - name: z.string(), - age: z.number(), - }); - - expect(() => schema.parse({ name: 'John', age: 30 })).not.toThrow(); - expect(() => schema.parse({ name: 'John', age: 30, extra: 'field' })).toThrow(); - }); - }); - - describe('mergeSchemas', () => { - it('should merge two schemas', () => { - const schema1 = z.object({ a: z.string() }); - const schema2 = z.object({ b: z.number() }); - - const merged = mergeSchemas(schema1, schema2); - const result = merged.parse({ a: 'test', b: 123 }); - - expect(result).toEqual({ a: 'test', b: 123 }); - }); - - it('should merge multiple schemas', () => { - const schema1 = z.object({ a: z.string() }); - const schema2 = z.object({ b: z.number() }); - const schema3 = z.object({ c: z.boolean() }); - - const merged = mergeSchemas(schema1, schema2, schema3); - const result = merged.parse({ a: 'test', b: 123, c: true }); - - expect(result).toEqual({ a: 'test', b: 123, c: true }); - }); - - it('should throw with less than two schemas', () => { - expect(() => mergeSchemas(z.object({}))).toThrow('At least two schemas required'); - expect(() => mergeSchemas()).toThrow('At least two schemas required'); - }); - - it('should handle overlapping fields', () => { - const schema1 = z.object({ a: z.string(), shared: z.string() }); - const schema2 = z.object({ b: z.number(), shared: z.string() }); - - const merged = mergeSchemas(schema1, schema2); - - // Both schemas require 'shared' to be a string - expect(() => merged.parse({ a: 'test', b: 123, shared: 'value' })).not.toThrow(); - expect(() => merged.parse({ a: 'test', b: 123, shared: 123 })).toThrow(); - }); - }); - - describe('COMMON_SECRET_PATTERNS', () => { - it('should be an array of RegExp', () => { - expect(Array.isArray(COMMON_SECRET_PATTERNS)).toBe(true); - expect(COMMON_SECRET_PATTERNS.length).toBeGreaterThan(0); - - for (const pattern of COMMON_SECRET_PATTERNS) { - expect(pattern).toBeInstanceOf(RegExp); - } - }); - }); -}); diff --git a/libs/core/di/package.json b/libs/core/di/package.json index 3f8d63bc..fecf9059 100644 --- a/libs/core/di/package.json +++ b/libs/core/di/package.json @@ -1,8 +1,21 @@ { "name": "@stock-bot/di", "version": "1.0.0", + "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "default": "./dist/index.js" + }, + "./http-security": { + "types": "./dist/http/security.d.ts", + "import": "./dist/http/security.js", + "default": "./dist/http/security.js" + } + }, "scripts": { "build": "tsc", "clean": "rm -rf dist", @@ -13,11 +26,10 @@ "@stock-bot/config": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/types": "workspace:*", - "@stock-bot/browser": "workspace:*", "@stock-bot/cache": "workspace:*", + "@stock-bot/proxy": "workspace:*", "@stock-bot/mongodb": "workspace:*", "@stock-bot/postgres": "workspace:*", - "@stock-bot/proxy": "workspace:*", "@stock-bot/questdb": "workspace:*", "@stock-bot/queue": "workspace:*", "@stock-bot/shutdown": "workspace:*", diff --git a/libs/core/di/src/awilix-container.ts b/libs/core/di/src/awilix-container.ts deleted file mode 100644 index 7e3a0c8b..00000000 --- a/libs/core/di/src/awilix-container.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { AwilixContainer } from 'awilix'; -import type { ServiceDefinitions } from './container/types'; - -// Compatibility exports use the same composition contract as the active builder. -export type { AppConfig } from './config/schemas'; -export type { ServiceCradle, ServiceDefinitions, ServiceContainerOptions } from './container/types'; -export type ServiceContainer = AwilixContainer; diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 772ccc89..6ea7bd49 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -1,4 +1,11 @@ -import { asClass, asFunction, createContainer, InjectionMode, type AwilixContainer } from 'awilix'; +import { + asClass, + asFunction, + asValue, + createContainer, + InjectionMode, + type AwilixContainer, +} from 'awilix'; import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config'; import { toUnifiedConfig } from '@stock-bot/config'; import { HandlerRegistry } from '@stock-bot/handler-registry'; @@ -14,8 +21,22 @@ import { HandlerScanner } from '../scanner'; import { ServiceLifecycleManager } from '../utils/lifecycle'; import type { ContainerBuildOptions, ServiceDefinitions } from './types'; +export interface ContainerRegistrationHelpers { + asClass: typeof asClass; + asFunction: typeof asFunction; + asValue: typeof asValue; +} + +export type ContainerRegistrar = ( + container: AwilixContainer, + config: AppConfig, + helpers: ContainerRegistrationHelpers +) => void; + function extractMongoDatabaseFromUri(uri?: string): string | undefined { - if (!uri) return undefined; + if (!uri) { + return undefined; + } try { const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0]; return db || undefined; @@ -31,6 +52,7 @@ function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): numbe export class ServiceContainerBuilder { private config: Partial = {}; private unifiedConfig: UnifiedAppConfig | null = null; + private customRegistrations: ContainerRegistrar[] = []; private options: ContainerBuildOptions = { enableCache: true, enableQueue: true, @@ -55,6 +77,11 @@ export class ServiceContainerBuilder { return this; } + withRegistrations(registrar: ContainerRegistrar): this { + this.customRegistrations.push(registrar); + return this; + } + enableService( service: keyof Omit, enabled = true @@ -85,6 +112,10 @@ export class ServiceContainerBuilder { // Register services this.registerServices(container, validatedConfig); + const helpers: ContainerRegistrationHelpers = { asClass, asFunction, asValue }; + for (const registrar of this.customRegistrations) { + registrar(container, validatedConfig, helpers); + } const lifecycleManager = new ServiceLifecycleManager(); // Initialize services if not skipped diff --git a/libs/core/di/src/container/types.ts b/libs/core/di/src/container/types.ts index a881c2f2..15d4ecb8 100644 --- a/libs/core/di/src/container/types.ts +++ b/libs/core/di/src/container/types.ts @@ -1,26 +1,21 @@ -import type { Browser } from '@stock-bot/browser'; import type { CacheProvider } from '@stock-bot/cache'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import type { Logger } from '@stock-bot/logger'; import type { MongoDBClient } from '@stock-bot/mongodb'; import type { PostgreSQLClient } from '@stock-bot/postgres'; -import type { ProxyManager } from '@stock-bot/proxy'; import type { QuestDBClient } from '@stock-bot/questdb'; import type { QueueManager } from '@stock-bot/queue'; -import type { IServiceContainer } from '@stock-bot/services'; +import type { Browser, IServiceContainer, ProxyManager } from '@stock-bot/services'; import type { AppConfig } from '../config/schemas'; import type { HandlerScanner } from '../scanner'; export interface ServiceDefinitions { - // Configuration config: AppConfig; logger: Logger; - // Handler infrastructure handlerRegistry: HandlerRegistry; handlerScanner: HandlerScanner; - // Core services cache: CacheProvider | null; globalCache: CacheProvider | null; proxyCache: CacheProvider | null; @@ -28,12 +23,10 @@ export interface ServiceDefinitions { browser: Browser | null; queueManager: QueueManager | null; - // Database clients mongoClient: MongoDBClient | null; postgresClient: PostgreSQLClient | null; questdbClient: QuestDBClient | null; - // Aggregate service container serviceContainer: IServiceContainer; } diff --git a/libs/core/di/src/factories/index.ts b/libs/core/di/src/factories/index.ts deleted file mode 100644 index 48cef01f..00000000 --- a/libs/core/di/src/factories/index.ts +++ /dev/null @@ -1 +0,0 @@ -// This directory is reserved for future factory implementations \ No newline at end of file diff --git a/libs/core/di/src/index.ts b/libs/core/di/src/index.ts index 0912aece..fa08b817 100644 --- a/libs/core/di/src/index.ts +++ b/libs/core/di/src/index.ts @@ -1,7 +1,6 @@ -// Export only what's actually used export { ServiceApplication } from './service-application'; export { ServiceContainerBuilder } from './container/builder'; -export { OperationContext } from './operation-context'; +export type { ContainerRegistrar, ContainerRegistrationHelpers } from './container/builder'; export { createHttpSecurity, httpSecurityOptions, @@ -11,12 +10,10 @@ export { getResearchHttpPrincipal, } from './http/security'; export type { HttpSecurity, HttpSecurityOptions } from './http/security'; -export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator'; export { ServiceLifecycleManager } from './utils/lifecycle'; export { HandlerScanner } from './scanner/handler-scanner'; export type { IServiceContainer } from '@stock-bot/services'; -// Export schemas export { appConfigSchema, redisConfigSchema, @@ -29,5 +26,4 @@ export { } from './config/schemas'; export type { ServiceDefinitions, ServiceCradle } from './container/types'; - export type { HandlerInitializationContext } from './service-application'; diff --git a/libs/core/di/src/operation-context.ts b/libs/core/di/src/operation-context.ts deleted file mode 100644 index b2013417..00000000 --- a/libs/core/di/src/operation-context.ts +++ /dev/null @@ -1,144 +0,0 @@ -/** - * OperationContext - Unified context for handler operations - */ - -import { getLogger, type Logger } from '@stock-bot/logger'; - -interface ServiceResolver { - resolve(serviceName: string): T; - resolveAsync(serviceName: string): Promise; -} - -export interface OperationContextOptions { - handlerName: string; - operationName: string; - parentLogger?: Logger; - container?: ServiceResolver; - metadata?: Record; - traceId?: string; -} - -export class OperationContext { - public readonly logger: Logger; - public readonly traceId: string; - public readonly metadata: Record; - private readonly container?: ServiceResolver; - private readonly startTime: Date; - - constructor(options: OperationContextOptions) { - this.container = options.container; - this.metadata = options.metadata || {}; - this.traceId = options.traceId || this.generateTraceId(); - this.startTime = new Date(); - - this.logger = - options.parentLogger || - getLogger(`${options.handlerName}:${options.operationName}`, { - traceId: this.traceId, - metadata: this.metadata, - }); - } - - /** - * Creates a new OperationContext with automatic resource management - */ - static create( - handlerName: string, - operationName: string, - options: { - container?: ServiceResolver; - parentLogger?: Logger; - metadata?: Record; - traceId?: string; - } = {} - ): OperationContext { - return new OperationContext({ - handlerName, - operationName, - ...options, - }); - } - - /** - * Resolve a service from the container - */ - resolve(serviceName: string): T { - if (!this.container) { - throw new Error('No service container available'); - } - return this.container.resolve(serviceName); - } - - /** - * Resolve a service asynchronously from the container - */ - async resolveAsync(serviceName: string): Promise { - if (!this.container) { - throw new Error('No service container available'); - } - return this.container.resolveAsync(serviceName); - } - - /** - * Add metadata to the context - */ - addMetadata(key: string, value: unknown): void { - this.metadata[key] = value; - } - - /** - * Get execution time in milliseconds - */ - getExecutionTime(): number { - return Date.now() - this.startTime.getTime(); - } - - /** - * Log operation completion with metrics - */ - logCompletion(success: boolean, error?: Error): void { - const executionTime = this.getExecutionTime(); - - if (success) { - this.logger.info('Operation completed successfully', { - executionTime, - metadata: this.metadata, - }); - } else { - this.logger.error('Operation failed', { - executionTime, - error: error?.message, - stack: error?.stack, - metadata: this.metadata, - }); - } - } - - /** - * Cleanup method - */ - async dispose(): Promise { - this.logCompletion(true); - } - - /** - * Create child context - */ - createChild(operationName: string, metadata?: Record): OperationContext { - return new OperationContext({ - handlerName: 'child', - operationName, - parentLogger: this.logger, - container: this.container, - traceId: this.traceId, - metadata: { ...this.metadata, ...metadata }, - }); - } - - /** - * Generate a unique trace ID - */ - private generateTraceId(): string { - return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } -} diff --git a/libs/core/di/src/pool-size-calculator.ts b/libs/core/di/src/pool-size-calculator.ts deleted file mode 100644 index 177f85d7..00000000 --- a/libs/core/di/src/pool-size-calculator.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type { ConnectionPoolConfig } from './types'; - -export interface PoolSizeRecommendation { - min: number; - max: number; - idle: number; -} - -export class PoolSizeCalculator { - private static readonly DEFAULT_SIZES: Record = { - // Service-level defaults - 'data-ingestion': { min: 5, max: 50, idle: 10 }, - 'data-pipeline': { min: 3, max: 30, idle: 5 }, - 'processing-service': { min: 2, max: 20, idle: 3 }, - 'web-api': { min: 2, max: 10, idle: 2 }, - 'portfolio-service': { min: 2, max: 15, idle: 3 }, - 'strategy-service': { min: 3, max: 25, idle: 5 }, - 'execution-service': { min: 2, max: 10, idle: 2 }, - - // Handler-level defaults - 'batch-import': { min: 10, max: 100, idle: 20 }, - 'real-time': { min: 2, max: 10, idle: 3 }, - analytics: { min: 5, max: 30, idle: 10 }, - reporting: { min: 3, max: 20, idle: 5 }, - }; - - static calculate( - serviceName: string, - handlerName?: string, - customConfig?: Partial - ): PoolSizeRecommendation { - // Check for custom configuration first - if (customConfig?.minConnections && customConfig?.maxConnections) { - return { - min: customConfig.minConnections, - max: customConfig.maxConnections, - idle: Math.floor((customConfig.minConnections + customConfig.maxConnections) / 4), - }; - } - - // Try handler-specific sizes first, then service-level - const key = handlerName || serviceName; - const recommendation = this.DEFAULT_SIZES[key] || this.DEFAULT_SIZES[serviceName]; - - if (recommendation) { - return { ...recommendation }; - } - - // Fall back to generic defaults - return { - min: 2, - max: 10, - idle: 3, - }; - } - - static getOptimalPoolSize( - expectedConcurrency: number, - averageQueryTimeMs: number, - targetLatencyMs: number - ): number { - // Little's Law: L = ฮป * W - // L = number of connections needed - // ฮป = arrival rate (requests per second) - // W = average time in system (seconds) - - const requestsPerSecond = expectedConcurrency; - const averageTimeInSystem = averageQueryTimeMs / 1000; - - const minConnections = Math.ceil(requestsPerSecond * averageTimeInSystem); - - // Add buffer for burst traffic (20% overhead) - const recommendedSize = Math.ceil(minConnections * 1.2); - - // Ensure we meet target latency - const latencyBasedSize = Math.ceil( - expectedConcurrency * (averageQueryTimeMs / targetLatencyMs) - ); - - return Math.max(recommendedSize, latencyBasedSize, 2); // Minimum 2 connections - } -} - -// Export convenience functions -export function calculatePoolSize( - serviceName: string, - handlerName?: string, - customConfig?: Partial -): PoolSizeRecommendation { - return PoolSizeCalculator.calculate(serviceName, handlerName, customConfig); -} - -export function getServicePoolSize(serviceName: string): PoolSizeRecommendation { - return PoolSizeCalculator.calculate(serviceName); -} - -export function getHandlerPoolSize( - serviceName: string, - handlerName: string -): PoolSizeRecommendation { - return PoolSizeCalculator.calculate(serviceName, handlerName); -} diff --git a/libs/core/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index 06be66e7..7a5b1f26 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -1,7 +1,8 @@ -import { asClass, asFunction, asValue, type AwilixContainer } from 'awilix'; -import { Browser } from '@stock-bot/browser'; +import { asFunction, asValue, type AwilixContainer } from 'awilix'; +import { createCache } from '@stock-bot/cache'; import { defined } from '@stock-bot/invariants'; import { ProxyManager } from '@stock-bot/proxy'; +import { QueueManager } from '@stock-bot/queue'; import type { AppConfig } from '../config/schemas'; import type { ServiceDefinitions } from '../container/types'; @@ -9,52 +10,40 @@ export function registerApplicationServices( container: AwilixContainer, config: AppConfig ): void { - // Browser - if (config.browser) { - container.register({ - browser: asClass(Browser) - .singleton() - .inject(() => ({ - options: { - headless: defined(config.browser).headless, - timeout: defined(config.browser).timeout, - }, - })), - }); - } else { - container.register({ - browser: asValue(null), // Required field - }); - } + // Browser is an ingestion-only capability registered by apps/stock/data-ingestion + // via ServiceContainerBuilder.withRegistrations() so non-ingestion apps never pull Playwright. + container.register({ + browser: asValue(null), + }); - // Proxy Manager + // Proxy Manager (pure TypeScript + Redis cache; zero browser dependencies) if (config.proxy && config.redis?.enabled) { + const redisConfig = config.redis; + const proxyConfig = config.proxy; container.register({ proxyCache: asFunction(({ logger }) => { - // Create a separate cache instance for proxy with global prefix - const { createCache } = require('@stock-bot/cache'); return createCache({ redisConfig: { - host: config.redis.host, - port: config.redis.port, - password: config.redis.password, - username: config.redis.username, - maxRetriesPerRequest: config.redis.maxRetries, - retryDelay: config.redis.retryDelay, - db: 1, // Use cache DB (usually DB 1) + host: redisConfig.host, + port: redisConfig.port, + password: redisConfig.password, + username: redisConfig.username, + maxRetriesPerRequest: redisConfig.maxRetries, + retryDelay: redisConfig.retryDelay, + db: 1, }, shared: false, keyPrefix: 'cache:proxy:', - ttl: 86400, // 24 hours default + ttl: 86400, enableMetrics: true, logger, }); }) .singleton() .disposer(cache => cache.disconnect?.()), - proxyManager: asFunction( - ({ logger, proxyCache }) => new ProxyManager(defined(proxyCache), config.proxy, logger) - ).singleton(), + proxyManager: asFunction(({ logger, proxyCache }) => { + return new ProxyManager(defined(proxyCache), proxyConfig, logger); + }).singleton(), }); } else { container.register({ @@ -67,8 +56,6 @@ export function registerApplicationServices( if (config.queue?.enabled && config.redis?.enabled) { container.register({ queueManager: asFunction(({ logger, handlerRegistry }) => { - const { QueueManager } = require('@stock-bot/queue'); - const queueConfig = { serviceName: config.service?.serviceName || config.service?.name || 'unknown', redis: { diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index fdeeb10f..d2a82f38 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -168,6 +168,25 @@ export class ServiceApplication { return app; } + private resolveOptional( + name: K + ): ServiceDefinitions[K] | null { + if (!this.container) { + return null; + } + if ( + typeof this.container.hasRegistration === 'function' && + !this.container.hasRegistration(name) + ) { + return null; + } + try { + return this.container.resolve(name); + } catch { + return null; + } + } + /** * Register graceful shutdown handlers */ @@ -178,30 +197,26 @@ export class ServiceApplication { timeout: this.serviceConfig.shutdownTimeout, }); - // Priority 1: Queue system (highest priority) - if (this.serviceConfig.enableScheduledJobs) { - this.shutdown.onShutdown( - async () => { - this.logger.info('Shutting down queue system...'); - const startTime = Date.now(); - try { - const queueManager = this.container?.resolve('queueManager'); - if (queueManager) { - await queueManager.shutdown(); - const duration = Date.now() - startTime; - this.logger.info('Queue system shut down successfully', { duration }); - } else { - this.logger.warn('No queue manager found to shut down'); - } - } catch (error) { + // Priority 1: Queue system (always register so active workers drain even when scheduled cron jobs are disabled) + this.shutdown.onShutdown( + async () => { + const startTime = Date.now(); + try { + const queueManager = this.resolveOptional('queueManager'); + if (queueManager) { + this.logger.info('Shutting down queue system...'); + await queueManager.shutdown(); const duration = Date.now() - startTime; - this.logger.error('Error shutting down queue system', { error, duration }); + this.logger.info('Queue system shut down successfully', { duration }); } - }, - SHUTDOWN_DEFAULTS.HIGH_PRIORITY, - 'Queue System' - ); - } + } catch (error) { + const duration = Date.now() - startTime; + this.logger.error('Error shutting down queue system', { error, duration }); + } + }, + SHUTDOWN_DEFAULTS.HIGH_PRIORITY, + 'Queue System' + ); // Priority 1: HTTP Server (high priority) this.shutdown.onShutdown( @@ -251,7 +266,7 @@ export class ServiceApplication { try { if (this.container) { // Disconnect database clients - const mongoClient = this.container.resolve('mongoClient'); + const mongoClient = this.resolveOptional('mongoClient'); if (mongoClient?.disconnect) { try { const mongoStart = Date.now(); @@ -263,7 +278,7 @@ export class ServiceApplication { } } - const postgresClient = this.container.resolve('postgresClient'); + const postgresClient = this.resolveOptional('postgresClient'); if (postgresClient?.disconnect) { try { const pgStart = Date.now(); @@ -275,7 +290,7 @@ export class ServiceApplication { } } - const questdbClient = this.container.resolve('questdbClient'); + const questdbClient = this.resolveOptional('questdbClient'); if (questdbClient?.disconnect) { try { const questStart = Date.now(); @@ -287,6 +302,13 @@ export class ServiceApplication { } } + if (typeof this.container.dispose === 'function') { + await this.container.dispose().catch(error => { + this.logger.error('Failed to dispose DI container resources', { error }); + failed.push('Container'); + }); + } + const duration = Date.now() - startTime; this.logger.info('Service disposal completed', { duration, @@ -326,10 +348,7 @@ export class ServiceApplication { this.logger.info('All shutdown handlers registered', { service: this.serviceConfig.serviceName, - handlerCount: - 3 + - (this.serviceConfig.enableScheduledJobs ? 1 : 0) + - (this.hooks.onBeforeShutdown ? 1 : 0), + handlerCount: 4 + (this.hooks.onBeforeShutdown ? 1 : 0), }); } @@ -377,10 +396,10 @@ export class ServiceApplication { this.logger.info('Handlers initialized'); // After handlers are initialized, add rate limit rules to queue manager - const queueManager = this.container.resolve('queueManager'); - const handlerRegistry = this.container.resolve('handlerRegistry'); + const queueManager = this.resolveOptional('queueManager'); + const handlerRegistry = this.resolveOptional('handlerRegistry'); - if (queueManager && handlerRegistry) { + if (queueManager && typeof handlerRegistry?.getAllMetadata === 'function') { const rateLimitRules = []; const allMetadata = handlerRegistry.getAllMetadata(); @@ -420,9 +439,17 @@ export class ServiceApplication { const routes = routeFactory(this.serviceContainer); this.app.route('/', routes); - // Initialize scheduled jobs if enabled - if (this.serviceConfig.enableScheduledJobs) { + // Initialize scheduled jobs if enabled in both serviceConfig and runtime queue config + const scheduledJobsEnabled = + this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? true); + if (scheduledJobsEnabled) { await this.initializeScheduledJobs(); + } else { + const queueManager = this.resolveOptional('queueManager'); + if (queueManager?.startAllWorkers) { + queueManager.startAllWorkers(); + this.logger.info('Queue workers started (scheduled cron jobs disabled)'); + } } // Call before start hook diff --git a/libs/core/di/src/types.ts b/libs/core/di/src/types.ts deleted file mode 100644 index f51eebc5..00000000 --- a/libs/core/di/src/types.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Generic types to avoid circular dependencies -export interface GenericClientConfig { - [key: string]: unknown; -} - -export interface ConnectionPoolConfig { - name: string; - poolSize?: number; - minConnections?: number; - maxConnections?: number; - idleTimeoutMillis?: number; - connectionTimeoutMillis?: number; - enableMetrics?: boolean; -} - -export interface MongoDBPoolConfig extends ConnectionPoolConfig { - config: GenericClientConfig; -} - -export interface PostgreSQLPoolConfig extends ConnectionPoolConfig { - config: GenericClientConfig; -} - -export interface CachePoolConfig extends ConnectionPoolConfig { - config: GenericClientConfig; -} - -export interface QueuePoolConfig extends ConnectionPoolConfig { - config: GenericClientConfig; -} - -export interface ConnectionFactoryConfig { - service: string; - environment: 'development' | 'qa' | 'production' | 'test'; - pools?: { - mongodb?: Partial; - postgres?: Partial; - cache?: Partial; - queue?: Partial; - }; -} - -export interface ConnectionPool { - name: string; - client: T; - metrics: PoolMetrics; - health(): Promise; - dispose(): Promise; -} - -export interface PoolMetrics { - created: Date; - totalConnections: number; - activeConnections: number; - idleConnections: number; - waitingRequests: number; - errors: number; -} - -export interface ConnectionFactory { - createMongoDB(config: MongoDBPoolConfig): Promise>; - createPostgreSQL(config: PostgreSQLPoolConfig): Promise>; - createCache(config: CachePoolConfig): Promise>; - createQueue(config: QueuePoolConfig): Promise>; - getPool( - type: 'mongodb' | 'postgres' | 'cache' | 'queue', - name: string - ): ConnectionPool | undefined; - listPools(): Array<{ type: string; name: string; metrics: PoolMetrics }>; - disposeAll(): Promise; -} diff --git a/libs/core/di/src/utils/lifecycle.ts b/libs/core/di/src/utils/lifecycle.ts index 32aadf73..89f35f17 100644 --- a/libs/core/di/src/utils/lifecycle.ts +++ b/libs/core/di/src/utils/lifecycle.ts @@ -20,6 +20,7 @@ export class ServiceLifecycleManager { { name: 'postgresClient', key: 'postgresClient' as const }, { name: 'questdbClient', key: 'questdbClient' as const }, { name: 'proxyManager', key: 'proxyManager' as const }, + { name: 'browser', key: 'browser' as const }, { name: 'queueManager', key: 'queueManager' as const }, ]; diff --git a/libs/core/di/test/awilix-container.test.ts b/libs/core/di/test/awilix-container.test.ts deleted file mode 100644 index 1ab8232e..00000000 --- a/libs/core/di/test/awilix-container.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import type { - ServiceContainer, - ServiceContainerOptions, - ServiceCradle, - ServiceDefinitions, -} from '../src/awilix-container'; - -describe('Awilix Container Types', () => { - it('should export ServiceDefinitions interface', () => { - // Type test - if this compiles, the type exists - const testDefinitions: Partial = { - config: {} as any, - logger: {} as any, - cache: null, - proxyManager: null, - browser: {} as any, - queueManager: null, - mongoClient: null, - postgresClient: null, - questdbClient: null, - serviceContainer: {} as any, - }; - - expect(testDefinitions).toBeDefined(); - }); - - it('should export ServiceContainer type', () => { - // Type test - if this compiles, the type exists - const testContainer: ServiceContainer | null = null; - expect(testContainer).toBeNull(); - }); - - it('should export ServiceCradle type', () => { - // Type test - if this compiles, the type exists - const testCradle: Partial = { - config: {} as any, - logger: {} as any, - }; - - expect(testCradle).toBeDefined(); - }); - - it('should export ServiceContainerOptions interface', () => { - // Type test - if this compiles, the type exists - const testOptions: ServiceContainerOptions = { - enableQuestDB: true, - enableMongoDB: true, - enablePostgres: true, - enableCache: true, - enableQueue: true, - enableBrowser: true, - enableProxy: true, - }; - - expect(testOptions).toBeDefined(); - expect(testOptions.enableQuestDB).toBe(true); - expect(testOptions.enableMongoDB).toBe(true); - expect(testOptions.enablePostgres).toBe(true); - expect(testOptions.enableCache).toBe(true); - expect(testOptions.enableQueue).toBe(true); - expect(testOptions.enableBrowser).toBe(true); - expect(testOptions.enableProxy).toBe(true); - }); - - it('should allow partial ServiceContainerOptions', () => { - const partialOptions: ServiceContainerOptions = { - enableCache: true, - enableQueue: false, - }; - - expect(partialOptions.enableCache).toBe(true); - expect(partialOptions.enableQueue).toBe(false); - expect(partialOptions.enableQuestDB).toBeUndefined(); - }); -}); diff --git a/libs/core/di/test/container-builder.test.ts b/libs/core/di/test/container-builder.test.ts index 6c01f031..03c5d4db 100644 --- a/libs/core/di/test/container-builder.test.ts +++ b/libs/core/di/test/container-builder.test.ts @@ -102,6 +102,23 @@ describe('ServiceContainerBuilder production configuration', () => { } }); + it('allows service-specific capability overrides via withRegistrations', async () => { + const fakeBrowser = { close: async () => {} } as never; + const container = await new ServiceContainerBuilder() + .withConfig(configuration()) + .withRegistrations((diContainer, _cfg, { asValue }) => { + diContainer.register({ browser: asValue(fakeBrowser) }); + }) + .skipInitialization() + .build(); + try { + expect(container.resolve('browser')).toBe(fakeBrowser); + expect(container.resolve('serviceContainer').browser).toBe(fakeBrowser); + } finally { + await container.dispose(); + } + }); + it('rejects invalid settings and missing required app fields with schema errors', () => { expect(() => new ServiceContainerBuilder().withConfig({ diff --git a/libs/core/di/test/di.test.ts b/libs/core/di/test/di.test.ts index 3d9be3b8..518535ad 100644 --- a/libs/core/di/test/di.test.ts +++ b/libs/core/di/test/di.test.ts @@ -1,8 +1,6 @@ import { asClass, asFunction, asValue, createContainer, InjectionMode } from 'awilix'; import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { ServiceContainerBuilder } from '../src/container/builder'; -import { OperationContext } from '../src/operation-context'; -import { PoolSizeCalculator } from '../src/pool-size-calculator'; import { HandlerScanner } from '../src/scanner/handler-scanner'; import { ServiceApplication } from '../src/service-application'; @@ -124,55 +122,6 @@ describe('Dependency Injection', () => { }); }); - describe('OperationContext', () => { - it('should create operation context', () => { - const context = new OperationContext({ - handlerName: 'test-handler', - operationName: 'test-op', - }); - - expect(context.traceId).toBeDefined(); - expect(context.logger).toBeDefined(); - expect(context.metadata).toEqual({}); - }); - - it('should include metadata', () => { - const metadata = { userId: '123', source: 'api' }; - const context = new OperationContext({ - handlerName: 'test-handler', - operationName: 'test-op', - metadata, - }); - - expect(context.metadata).toEqual(metadata); - }); - - it('should track execution time', async () => { - const context = new OperationContext({ - handlerName: 'test-handler', - operationName: 'test-op', - }); - - await new Promise(resolve => setTimeout(resolve, 10)); - - const executionTime = context.getExecutionTime(); - expect(executionTime).toBeGreaterThanOrEqual(10); - }); - - it('should create child context', () => { - const parentContext = new OperationContext({ - handlerName: 'parent-handler', - operationName: 'parent-op', - metadata: { parentId: '123' }, - }); - - const childContext = parentContext.createChild('child-op', { childId: '456' }); - - expect(childContext.traceId).toBe(parentContext.traceId); - expect(childContext.metadata).toEqual({ parentId: '123', childId: '456' }); - }); - }); - describe('HandlerScanner', () => { it('should create scanner instance', () => { const mockRegistry = { @@ -219,52 +168,4 @@ describe('Dependency Injection', () => { expect(app.stop).toBeDefined(); }); }); - - describe('Pool Size Calculator', () => { - it('should calculate pool size for services', () => { - const recommendation = PoolSizeCalculator.calculate('web-api'); - - expect(recommendation.min).toBe(2); - expect(recommendation.max).toBe(10); - expect(recommendation.idle).toBe(2); - }); - - it('should calculate pool size for handlers', () => { - const recommendation = PoolSizeCalculator.calculate('data-ingestion', 'batch-import'); - - expect(recommendation.min).toBe(10); - expect(recommendation.max).toBe(100); - expect(recommendation.idle).toBe(20); - }); - - it('should use custom configuration', () => { - const recommendation = PoolSizeCalculator.calculate('custom', undefined, { - minConnections: 5, - maxConnections: 50, - }); - - expect(recommendation.min).toBe(5); - expect(recommendation.max).toBe(50); - expect(recommendation.idle).toBe(13); // (5+50)/4 = 13.75 -> 13 - }); - - it('should fall back to defaults', () => { - const recommendation = PoolSizeCalculator.calculate('unknown-service'); - - expect(recommendation.min).toBe(2); - expect(recommendation.max).toBe(10); - expect(recommendation.idle).toBe(3); - }); - - it('should calculate optimal pool size', () => { - const size = PoolSizeCalculator.getOptimalPoolSize( - 100, // 100 requests per second - 50, // 50ms average query time - 100 // 100ms target latency - ); - - expect(size).toBeGreaterThan(0); - expect(size).toBe(50); // max(100*0.05*1.2, 100*50/100, 2) = max(6, 50, 2) = 50 - }); - }); }); diff --git a/libs/core/di/test/index.test.ts b/libs/core/di/test/index.test.ts index b00695fa..41c514f4 100644 --- a/libs/core/di/test/index.test.ts +++ b/libs/core/di/test/index.test.ts @@ -2,16 +2,6 @@ import { describe, expect, it } from 'bun:test'; import * as diExports from '../src/index'; describe('DI Package Exports', () => { - it('should export OperationContext', () => { - expect(diExports.OperationContext).toBeDefined(); - }); - - it('should export pool size calculator', () => { - expect(diExports.calculatePoolSize).toBeDefined(); - expect(diExports.getServicePoolSize).toBeDefined(); - expect(diExports.getHandlerPoolSize).toBeDefined(); - }); - it('should export ServiceContainerBuilder', () => { expect(diExports.ServiceContainerBuilder).toBeDefined(); }); diff --git a/libs/core/di/test/operation-context.test.ts b/libs/core/di/test/operation-context.test.ts deleted file mode 100644 index ffe73ce4..00000000 --- a/libs/core/di/test/operation-context.test.ts +++ /dev/null @@ -1,273 +0,0 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import { OperationContext } from '../src/operation-context'; -import type { OperationContextOptions } from '../src/operation-context'; - -describe('OperationContext', () => { - const mockLogger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - trace: mock(() => {}), - child: mock(() => mockLogger), - }; - - const mockContainer = { - resolve: mock((name: string) => ({ name })), - resolveAsync: mock(async (name: string) => ({ name })), - }; - - beforeEach(() => { - // Reset mocks - Object.keys(mockLogger).forEach(key => { - if (typeof mockLogger[key as keyof typeof mockLogger] === 'function') { - (mockLogger as any)[key] = mock(() => (key === 'child' ? mockLogger : undefined)); - } - }); - mockContainer.resolve = mock((name: string) => ({ name })); - mockContainer.resolveAsync = mock(async (name: string) => ({ name })); - }); - - describe('constructor', () => { - it('should create context with required options', () => { - const options: OperationContextOptions = { - handlerName: 'test-handler', - operationName: 'test-op', - }; - - const context = new OperationContext(options); - - expect(context).toBeDefined(); - expect(context.traceId).toBeDefined(); - expect(context.metadata).toEqual({}); - expect(context.logger).toBeDefined(); - }); - - it('should create context with all options', () => { - const options: OperationContextOptions = { - handlerName: 'test-handler', - operationName: 'test-op', - parentLogger: mockLogger, - container: mockContainer, - metadata: { key: 'value' }, - traceId: 'custom-trace-id', - }; - - const context = new OperationContext(options); - - expect(context.traceId).toBe('custom-trace-id'); - expect(context.metadata).toEqual({ key: 'value' }); - expect(context.logger).toBe(mockLogger); - }); - }); - - describe('static create', () => { - it('should create context using static method', () => { - const context = OperationContext.create('handler', 'operation', { - metadata: { foo: 'bar' }, - }); - - expect(context).toBeDefined(); - expect(context.metadata).toEqual({ foo: 'bar' }); - }); - }); - - describe('service resolution', () => { - it('should resolve services from container', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - container: mockContainer, - }); - - const service = context.resolve('myService'); - expect(service).toEqual({ name: 'myService' }); - expect(mockContainer.resolve).toHaveBeenCalledWith('myService'); - }); - - it('should resolve services asynchronously', async () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - container: mockContainer, - }); - - const service = await context.resolveAsync('myService'); - expect(service).toEqual({ name: 'myService' }); - expect(mockContainer.resolveAsync).toHaveBeenCalledWith('myService'); - }); - - it('should throw error when no container available', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - expect(() => context.resolve('service')).toThrow('No service container available'); - }); - - it('should throw error when no container available for async', async () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - await expect(context.resolveAsync('service')).rejects.toThrow( - 'No service container available' - ); - }); - }); - - describe('metadata', () => { - it('should add metadata', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - context.addMetadata('userId', '12345'); - context.addMetadata('correlationId', 'corr-456'); - - expect(context.metadata.userId).toBe('12345'); - expect(context.metadata.correlationId).toBe('corr-456'); - }); - - it('should preserve initial metadata', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - metadata: { initial: 'value' }, - }); - - context.addMetadata('added', 'new-value'); - - expect(context.metadata.initial).toBe('value'); - expect(context.metadata.added).toBe('new-value'); - }); - }); - - describe('execution time', () => { - it('should track execution time', async () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - // Wait a bit - await new Promise(resolve => setTimeout(resolve, 50)); - - const executionTime = context.getExecutionTime(); - expect(executionTime).toBeGreaterThan(40); - expect(executionTime).toBeLessThan(100); - }); - }); - - describe('logging', () => { - it('should log successful completion', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - parentLogger: mockLogger, - }); - - context.logCompletion(true); - - expect(mockLogger.info).toHaveBeenCalledWith( - 'Operation completed successfully', - expect.objectContaining({ - executionTime: expect.any(Number), - metadata: {}, - }) - ); - }); - - it('should log failed completion with error', () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - parentLogger: mockLogger, - }); - - const error = new Error('Test error'); - context.logCompletion(false, error); - - expect(mockLogger.error).toHaveBeenCalledWith( - 'Operation failed', - expect.objectContaining({ - executionTime: expect.any(Number), - error: 'Test error', - stack: expect.any(String), - metadata: {}, - }) - ); - }); - }); - - describe('child context', () => { - it('should create child context', () => { - const parent = new OperationContext({ - handlerName: 'parent', - operationName: 'parent-op', - parentLogger: mockLogger, - container: mockContainer, - traceId: 'parent-trace', - metadata: { parentKey: 'parentValue' }, - }); - - const child = parent.createChild('child-op', { childKey: 'childValue' }); - - expect(child.traceId).toBe('parent-trace'); // Inherits trace ID - expect(child.metadata).toEqual({ - parentKey: 'parentValue', - childKey: 'childValue', - }); - expect(child.logger).toBe(mockLogger); // Inherits logger - }); - - it('should create child without additional metadata', () => { - const parent = new OperationContext({ - handlerName: 'parent', - operationName: 'parent-op', - metadata: { key: 'value' }, - }); - - const child = parent.createChild('child-op'); - - expect(child.metadata).toEqual({ key: 'value' }); - }); - }); - - describe('dispose', () => { - it('should log completion on dispose', async () => { - const context = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - parentLogger: mockLogger, - }); - - await context.dispose(); - - expect(mockLogger.info).toHaveBeenCalledWith( - 'Operation completed successfully', - expect.any(Object) - ); - }); - }); - - describe('trace ID generation', () => { - it('should generate unique trace IDs', () => { - const context1 = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - const context2 = new OperationContext({ - handlerName: 'test', - operationName: 'test-op', - }); - - expect(context1.traceId).not.toBe(context2.traceId); - expect(context1.traceId).toMatch(/^\d+-[a-z0-9]+$/); - }); - }); -}); diff --git a/libs/core/di/test/pool-size-calculator.test.ts b/libs/core/di/test/pool-size-calculator.test.ts deleted file mode 100644 index b50af589..00000000 --- a/libs/core/di/test/pool-size-calculator.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { PoolSizeCalculator } from '../src/pool-size-calculator'; -import type { ConnectionPoolConfig } from '../src/types'; - -describe('PoolSizeCalculator', () => { - describe('calculate', () => { - it('should return service-level defaults for known services', () => { - const result = PoolSizeCalculator.calculate('data-ingestion'); - expect(result).toEqual({ min: 5, max: 50, idle: 10 }); - }); - - it('should return handler-level defaults when handler name is provided', () => { - const result = PoolSizeCalculator.calculate('any-service', 'batch-import'); - expect(result).toEqual({ min: 10, max: 100, idle: 20 }); - }); - - it('should prefer handler-level over service-level defaults', () => { - const result = PoolSizeCalculator.calculate('data-ingestion', 'real-time'); - expect(result).toEqual({ min: 2, max: 10, idle: 3 }); - }); - - it('should return generic defaults for unknown services', () => { - const result = PoolSizeCalculator.calculate('unknown-service'); - expect(result).toEqual({ min: 2, max: 10, idle: 3 }); - }); - - it('should use custom configuration when provided', () => { - const customConfig: Partial = { - minConnections: 15, - maxConnections: 75, - }; - const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig); - expect(result).toEqual({ - min: 15, - max: 75, - idle: Math.floor((15 + 75) / 4), // 22 - }); - }); - - it('should ignore partial custom configuration', () => { - const customConfig: Partial = { - minConnections: 15, - // maxConnections not provided - }; - const result = PoolSizeCalculator.calculate('data-ingestion', undefined, customConfig); - // Should fall back to defaults - expect(result).toEqual({ min: 5, max: 50, idle: 10 }); - }); - - it('should handle all predefined service types', () => { - const services = [ - { name: 'data-pipeline', expected: { min: 3, max: 30, idle: 5 } }, - { name: 'processing-service', expected: { min: 2, max: 20, idle: 3 } }, - { name: 'web-api', expected: { min: 2, max: 10, idle: 2 } }, - { name: 'portfolio-service', expected: { min: 2, max: 15, idle: 3 } }, - { name: 'strategy-service', expected: { min: 3, max: 25, idle: 5 } }, - { name: 'execution-service', expected: { min: 2, max: 10, idle: 2 } }, - ]; - - services.forEach(({ name, expected }) => { - const result = PoolSizeCalculator.calculate(name); - expect(result).toEqual(expected); - }); - }); - - it('should handle all predefined handler types', () => { - const handlers = [ - { name: 'analytics', expected: { min: 5, max: 30, idle: 10 } }, - { name: 'reporting', expected: { min: 3, max: 20, idle: 5 } }, - ]; - - handlers.forEach(({ name, expected }) => { - const result = PoolSizeCalculator.calculate('any-service', name); - expect(result).toEqual(expected); - }); - }); - - it('should return a new object each time', () => { - const result1 = PoolSizeCalculator.calculate('data-ingestion'); - const result2 = PoolSizeCalculator.calculate('data-ingestion'); - - expect(result1).not.toBe(result2); - expect(result1).toEqual(result2); - }); - }); - - describe('getOptimalPoolSize', () => { - it("should calculate pool size based on Little's Law", () => { - // 10 requests/second, 100ms average query time, 50ms target latency - const result = PoolSizeCalculator.getOptimalPoolSize(10, 100, 50); - - // Little's Law: L = ฮป * W = 10 * 0.1 = 1 - // With 20% buffer: 1 * 1.2 = 1.2, ceil = 2 - // Latency based: 10 * (100/50) = 20 - // Max of (2, 20, 2) = 20 - expect(result).toBe(20); - }); - - it('should return minimum 2 connections', () => { - // Very low concurrency - const result = PoolSizeCalculator.getOptimalPoolSize(0.1, 10, 1000); - expect(result).toBe(2); - }); - - it('should handle high concurrency scenarios', () => { - // 100 requests/second, 500ms average query time, 100ms target latency - const result = PoolSizeCalculator.getOptimalPoolSize(100, 500, 100); - - // Little's Law: L = 100 * 0.5 = 50 - // With 20% buffer: 50 * 1.2 = 60 - // Latency based: 100 * (500/100) = 500 - // Max of (60, 500, 2) = 500 - expect(result).toBe(500); - }); - - it('should handle scenarios where latency target is already met', () => { - // 10 requests/second, 50ms average query time, 200ms target latency - const result = PoolSizeCalculator.getOptimalPoolSize(10, 50, 200); - - // Little's Law: L = 10 * 0.05 = 0.5 - // With 20% buffer: 0.5 * 1.2 = 0.6, ceil = 1 - // Latency based: 10 * (50/200) = 2.5, ceil = 3 - // Max of (1, 3, 2) = 3 - expect(result).toBe(3); - }); - - it('should handle edge cases with zero values', () => { - expect(PoolSizeCalculator.getOptimalPoolSize(0, 100, 100)).toBe(2); - expect(PoolSizeCalculator.getOptimalPoolSize(10, 0, 100)).toBe(2); - }); - - it('should handle fractional calculations correctly', () => { - // 15 requests/second, 75ms average query time, 150ms target latency - const result = PoolSizeCalculator.getOptimalPoolSize(15, 75, 150); - - // Little's Law: L = 15 * 0.075 = 1.125 - // With 20% buffer: 1.125 * 1.2 = 1.35, ceil = 2 - // Latency based: 15 * (75/150) = 7.5, ceil = 8 - // Max of (2, 8, 2) = 8 - expect(result).toBe(8); - }); - - it('should prioritize latency-based sizing when it requires more connections', () => { - // Scenario where latency requirements demand more connections than throughput - const result = PoolSizeCalculator.getOptimalPoolSize(5, 200, 50); - - // Little's Law: L = 5 * 0.2 = 1 - // With 20% buffer: 1 * 1.2 = 1.2, ceil = 2 - // Latency based: 5 * (200/50) = 20 - // Max of (2, 20, 2) = 20 - expect(result).toBe(20); - }); - - it('should handle very high query times', () => { - // 50 requests/second, 2000ms average query time, 500ms target latency - const result = PoolSizeCalculator.getOptimalPoolSize(50, 2000, 500); - - // Little's Law: L = 50 * 2 = 100 - // With 20% buffer: 100 * 1.2 = 120 - // Latency based: 50 * (2000/500) = 200 - // Max of (120, 200, 2) = 200 - expect(result).toBe(200); - }); - }); -}); diff --git a/libs/core/di/test/registration.test.ts b/libs/core/di/test/registration.test.ts index 719b6046..d61e404f 100644 --- a/libs/core/di/test/registration.test.ts +++ b/libs/core/di/test/registration.test.ts @@ -231,44 +231,20 @@ describe('DI Registrations', () => { }); describe('registerApplicationServices', () => { - it('should register browser when config exists', () => { + it('should register default null browser outside ingestion and register proxy when redis enabled', () => { const container = createContainer(); - // Mock browser factory - const mockBrowser = { - launch: mock(() => Promise.resolve()), - close: mock(() => Promise.resolve()), - }; - - mock.module('@stock-bot/browser', () => ({ - createBrowser: () => mockBrowser, - })); - const config = { browser: { headless: true, timeout: 30000, }, - } as any; - - registerApplicationServices(container, config); - - expect(container.hasRegistration('browser')).toBe(true); - }); - - it('should register proxy when config exists', () => { - const container = createContainer(); - - // Mock proxy factory - const mockProxy = { - getProxy: mock(() => 'http://proxy:8080'), - }; - - mock.module('@stock-bot/proxy', () => ({ - createProxyManager: () => mockProxy, - })); - - const config = { + redis: { + enabled: true, + host: 'localhost', + port: 6379, + db: 0, + }, proxy: { enabled: true, url: 'http://proxy:8080', @@ -277,10 +253,14 @@ describe('DI Registrations', () => { registerApplicationServices(container, config); + expect(container.hasRegistration('browser')).toBe(true); + expect(container.hasRegistration('proxyCache')).toBe(true); expect(container.hasRegistration('proxyManager')).toBe(true); + expect(container.resolve('browser')).toBeNull(); + expect(container.getRegistration('proxyManager')?.lifetime).toBe('SINGLETON'); }); - it('should register queue manager when queue config exists', () => { + it('should register queue manager when queue and redis configs exist', () => { const container = createContainer(); // Mock dependencies @@ -321,6 +301,12 @@ describe('DI Registrations', () => { name: 'test-service', serviceName: 'test-service', }, + redis: { + enabled: true, + host: 'localhost', + port: 6379, + db: 0, + }, queue: { enabled: true, workers: 2, @@ -394,20 +380,26 @@ describe('DI Registrations', () => { }); describe('registration options', () => { - it('should register services as singletons', () => { + it('should register queueManager as singleton when enabled', () => { const container = createContainer(); const config = { - browser: { - headless: true, - timeout: 30000, + redis: { + enabled: true, + host: 'localhost', + port: 6379, + db: 0, + }, + queue: { + enabled: true, + workers: 1, + concurrency: 1, }, } as any; registerApplicationServices(container, config); - // Check that browser was registered as singleton - const registration = container.getRegistration('browser'); + const registration = container.getRegistration('queueManager'); expect(registration).toBeDefined(); expect(registration?.lifetime).toBe('SINGLETON'); }); diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 5d99a761..2d07aea8 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -263,9 +263,9 @@ describe('ServiceApplication', () => { await app.start(mockContainerFactory, mockRouteFactory, mockHandlerInitializer); expect(mockHandlerInitializer).toHaveBeenCalledWith( + { test: 'container' }, expect.objectContaining({ - test: 'container', - _diContainer: mockContainer, + handlerRegistry: expect.anything(), }) ); expect(mockLogger.info).toHaveBeenCalledWith('Handlers initialized'); diff --git a/libs/core/di/test/types.test.ts b/libs/core/di/test/types.test.ts deleted file mode 100644 index b1818702..00000000 --- a/libs/core/di/test/types.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import type { - CachePoolConfig, - ConnectionFactory, - ConnectionFactoryConfig, - ConnectionPool, - ConnectionPoolConfig, - GenericClientConfig, - MongoDBPoolConfig, - PoolMetrics, - PostgreSQLPoolConfig, - QueuePoolConfig, -} from '../src/types'; - -describe('DI Types', () => { - describe('GenericClientConfig', () => { - it('should allow any key-value pairs', () => { - const config: GenericClientConfig = { - host: 'localhost', - port: 5432, - username: 'test', - password: 'test', - customOption: true, - }; - - expect(config.host).toBe('localhost'); - expect(config.port).toBe(5432); - expect(config.customOption).toBe(true); - }); - }); - - describe('ConnectionPoolConfig', () => { - it('should have required and optional fields', () => { - const config: ConnectionPoolConfig = { - name: 'test-pool', - poolSize: 10, - minConnections: 2, - maxConnections: 20, - idleTimeoutMillis: 30000, - connectionTimeoutMillis: 5000, - enableMetrics: true, - }; - - expect(config.name).toBe('test-pool'); - expect(config.poolSize).toBe(10); - expect(config.enableMetrics).toBe(true); - }); - - it('should allow minimal configuration', () => { - const config: ConnectionPoolConfig = { - name: 'minimal-pool', - }; - - expect(config.name).toBe('minimal-pool'); - expect(config.poolSize).toBeUndefined(); - }); - }); - - describe('Specific Pool Configs', () => { - it('should extend ConnectionPoolConfig for MongoDB', () => { - const config: MongoDBPoolConfig = { - name: 'mongo-pool', - poolSize: 5, - config: { - uri: 'mongodb://localhost:27017', - database: 'test', - }, - }; - - expect(config.name).toBe('mongo-pool'); - expect(config.config.uri).toBe('mongodb://localhost:27017'); - }); - - it('should extend ConnectionPoolConfig for PostgreSQL', () => { - const config: PostgreSQLPoolConfig = { - name: 'postgres-pool', - config: { - host: 'localhost', - port: 5432, - database: 'test', - }, - }; - - expect(config.name).toBe('postgres-pool'); - expect(config.config.host).toBe('localhost'); - }); - - it('should extend ConnectionPoolConfig for Cache', () => { - const config: CachePoolConfig = { - name: 'cache-pool', - config: { - host: 'localhost', - port: 6379, - }, - }; - - expect(config.name).toBe('cache-pool'); - expect(config.config.port).toBe(6379); - }); - - it('should extend ConnectionPoolConfig for Queue', () => { - const config: QueuePoolConfig = { - name: 'queue-pool', - config: { - redis: { - host: 'localhost', - port: 6379, - }, - }, - }; - - expect(config.name).toBe('queue-pool'); - expect(config.config.redis.host).toBe('localhost'); - }); - }); - - describe('ConnectionFactoryConfig', () => { - it('should define factory configuration', () => { - const config: ConnectionFactoryConfig = { - service: 'test-service', - environment: 'development', - pools: { - mongodb: { - poolSize: 10, - }, - postgres: { - maxConnections: 20, - }, - cache: { - idleTimeoutMillis: 60000, - }, - queue: { - enableMetrics: true, - }, - }, - }; - - expect(config.service).toBe('test-service'); - expect(config.environment).toBe('development'); - expect(config.pools?.mongodb?.poolSize).toBe(10); - expect(config.pools?.postgres?.maxConnections).toBe(20); - }); - - it('should allow minimal factory config', () => { - const config: ConnectionFactoryConfig = { - service: 'minimal-service', - environment: 'test', - }; - - expect(config.service).toBe('minimal-service'); - expect(config.pools).toBeUndefined(); - }); - }); - - describe('ConnectionPool', () => { - it('should define connection pool interface', () => { - const mockPool: ConnectionPool = { - name: 'test-pool', - client: { connected: true }, - metrics: { - created: new Date(), - totalConnections: 10, - activeConnections: 5, - idleConnections: 5, - waitingRequests: 0, - errors: 0, - }, - health: async () => true, - dispose: async () => {}, - }; - - expect(mockPool.name).toBe('test-pool'); - expect(mockPool.client.connected).toBe(true); - expect(mockPool.metrics.totalConnections).toBe(10); - }); - }); - - describe('PoolMetrics', () => { - it('should define pool metrics structure', () => { - const metrics: PoolMetrics = { - created: new Date('2024-01-01'), - totalConnections: 100, - activeConnections: 25, - idleConnections: 75, - waitingRequests: 2, - errors: 3, - }; - - expect(metrics.totalConnections).toBe(100); - expect(metrics.activeConnections).toBe(25); - expect(metrics.idleConnections).toBe(75); - expect(metrics.waitingRequests).toBe(2); - expect(metrics.errors).toBe(3); - }); - }); - - describe('ConnectionFactory', () => { - it('should define connection factory interface', () => { - const mockFactory: ConnectionFactory = { - createMongoDB: async config => ({ - name: config.name, - client: {}, - metrics: { - created: new Date(), - totalConnections: 0, - activeConnections: 0, - idleConnections: 0, - waitingRequests: 0, - errors: 0, - }, - health: async () => true, - dispose: async () => {}, - }), - createPostgreSQL: async config => ({ - name: config.name, - client: {}, - metrics: { - created: new Date(), - totalConnections: 0, - activeConnections: 0, - idleConnections: 0, - waitingRequests: 0, - errors: 0, - }, - health: async () => true, - dispose: async () => {}, - }), - createCache: async config => ({ - name: config.name, - client: {}, - metrics: { - created: new Date(), - totalConnections: 0, - activeConnections: 0, - idleConnections: 0, - waitingRequests: 0, - errors: 0, - }, - health: async () => true, - dispose: async () => {}, - }), - createQueue: async config => ({ - name: config.name, - client: {}, - metrics: { - created: new Date(), - totalConnections: 0, - activeConnections: 0, - idleConnections: 0, - waitingRequests: 0, - errors: 0, - }, - health: async () => true, - dispose: async () => {}, - }), - getPool: (_type, _name) => undefined, - listPools: () => [], - disposeAll: async () => {}, - }; - - expect(mockFactory.createMongoDB).toBeDefined(); - expect(mockFactory.createPostgreSQL).toBeDefined(); - expect(mockFactory.createCache).toBeDefined(); - expect(mockFactory.createQueue).toBeDefined(); - expect(mockFactory.getPool).toBeDefined(); - expect(mockFactory.listPools).toBeDefined(); - expect(mockFactory.disposeAll).toBeDefined(); - }); - }); -}); diff --git a/libs/core/event-bus/README.md b/libs/core/event-bus/README.md deleted file mode 100644 index 48460881..00000000 --- a/libs/core/event-bus/README.md +++ /dev/null @@ -1,191 +0,0 @@ -# @stock-bot/event-bus - -Lightweight event bus for inter-service communication in the Stock Bot platform. - -## Overview - -This library provides a simple pub/sub event system using Redis, designed for real-time event distribution between microservices. It focuses on simplicity and reliability for event-driven communication. - -## Features - -- Simple pub/sub pattern using Redis -- Automatic reconnection and resubscription -- Local event emission (works even without Redis) -- TypeScript support with predefined trading event types -- Lightweight with minimal dependencies - -## Installation - -```bash -bun add @stock-bot/event-bus -``` - -## Usage - -### Basic Setup - -```typescript -import { createEventBus, TradingEventType } from '@stock-bot/event-bus'; - -const eventBus = createEventBus({ - serviceName: 'data-ingestion', - redisConfig: { - host: 'localhost', - port: 6379, - }, - enableLogging: true, -}); - -// Wait for connection -await eventBus.waitForConnection(); -``` - -### Publishing Events - -```typescript -// Publish a price update -await eventBus.publish(TradingEventType.PRICE_UPDATE, { - symbol: 'AAPL', - price: 150.25, - volume: 1000000, - timestamp: Date.now(), -}); - -// Publish with metadata -await eventBus.publish(TradingEventType.ORDER_FILLED, - { - orderId: '12345', - symbol: 'TSLA', - side: 'buy', - quantity: 100, - price: 250.50, - }, - { source: 'ib-gateway', region: 'us' } -); -``` - -### Subscribing to Events - -```typescript -// Subscribe to price updates -await eventBus.subscribe(TradingEventType.PRICE_UPDATE, async (message) => { - console.log(`Price update for ${message.data.symbol}: $${message.data.price}`); -}); - -// Subscribe to order events -await eventBus.subscribe(TradingEventType.ORDER_FILLED, async (message) => { - const { orderId, symbol, quantity, price } = message.data; - console.log(`Order ${orderId} filled: ${quantity} ${symbol} @ $${price}`); -}); -``` - -### Event Types - -The library includes predefined event types for common trading operations: - -```typescript -enum TradingEventType { - // Market data events - PRICE_UPDATE = 'market.price.update', - ORDERBOOK_UPDATE = 'market.orderbook.update', - TRADE_EXECUTED = 'market.trade.executed', - - // Order events - ORDER_CREATED = 'order.created', - ORDER_FILLED = 'order.filled', - ORDER_CANCELLED = 'order.cancelled', - ORDER_REJECTED = 'order.rejected', - - // Position events - POSITION_OPENED = 'position.opened', - POSITION_CLOSED = 'position.closed', - POSITION_UPDATED = 'position.updated', - - // Strategy events - STRATEGY_SIGNAL = 'strategy.signal', - STRATEGY_STARTED = 'strategy.started', - STRATEGY_STOPPED = 'strategy.stopped', - - // Risk events - RISK_LIMIT_BREACH = 'risk.limit.breach', - RISK_WARNING = 'risk.warning', - - // System events - SERVICE_STARTED = 'system.service.started', - SERVICE_STOPPED = 'system.service.stopped', - SERVICE_ERROR = 'system.service.error', -} -``` - -### Typed Events - -Use TypeScript generics for type-safe event handling: - -```typescript -import type { PriceUpdateEvent, OrderEvent } from '@stock-bot/event-bus'; - -// Type-safe subscription -await eventBus.subscribe( - TradingEventType.PRICE_UPDATE, - async (message) => { - // message.data is typed as PriceUpdateEvent - const { symbol, price, volume } = message.data; - } -); -``` - -### Cleanup - -```typescript -// Unsubscribe from specific event -await eventBus.unsubscribe(TradingEventType.PRICE_UPDATE); - -// Close all connections -await eventBus.close(); -``` - -## Architecture Notes - -This library is designed for lightweight, real-time event distribution. For reliable job processing, retries, and persistence, use the `@stock-bot/queue` library with BullMQ instead. - -### When to Use Event Bus - -- Real-time notifications (price updates, trade executions) -- Service coordination (strategy signals, risk alerts) -- System monitoring (service status, errors) - -### When to Use Queue - -- Data processing jobs -- Batch operations -- Tasks requiring persistence and retries -- Scheduled operations - -## Error Handling - -The event bus handles connection failures gracefully: - -```typescript -try { - await eventBus.publish(TradingEventType.PRICE_UPDATE, data); -} catch (error) { - // Event will still be emitted locally - console.error('Failed to publish to Redis:', error); -} -``` - -## Development - -```bash -# Install dependencies -bun install - -# Build -bun run build - -# Run tests -bun test - -# Clean build artifacts -bun run clean -``` \ No newline at end of file diff --git a/libs/core/event-bus/package.json b/libs/core/event-bus/package.json deleted file mode 100644 index 2a5243c6..00000000 --- a/libs/core/event-bus/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@stock-bot/event-bus", - "version": "1.0.0", - "description": "Event bus library for inter-service communication", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "type": "module", - "scripts": { - "build": "tsc", - "test": "bun test", - "clean": "rimraf dist" - }, - "dependencies": { - "@stock-bot/logger": "*", - "ioredis": "^5.3.2", - "eventemitter3": "^5.0.1", - "@stock-bot/invariants": "workspace:*" - }, - "devDependencies": { - "@types/node": "^20.11.0", - "typescript": "^5.3.0", - "bun-types": "^1.2.15" - }, - "exports": { - ".": { - "import": "./dist/index.js", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" - }, - "./types": { - "import": "./dist/types.js", - "require": "./dist/types.js", - "types": "./dist/types.d.ts" - } - }, - "files": [ - "dist", - "README.md" - ] -} diff --git a/libs/core/event-bus/src/event-bus.ts b/libs/core/event-bus/src/event-bus.ts deleted file mode 100644 index 06951e5f..00000000 --- a/libs/core/event-bus/src/event-bus.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { EventEmitter } from 'eventemitter3'; -import Redis from 'ioredis'; -import { getLogger } from '@stock-bot/logger'; -import type { EventBusConfig, EventBusMessage, EventHandler, EventSubscription } from './types'; - -/** - * Lightweight Event Bus for inter-service communication - * Uses Redis pub/sub for simple, real-time event distribution - */ -export class EventBus extends EventEmitter { - private publisher: Redis; - private subscriber: Redis; - private readonly serviceName: string; - private readonly logger: ReturnType; - private subscriptions: Map = new Map(); - private isConnected: boolean = false; - - constructor(config: EventBusConfig) { - super(); - this.serviceName = config.serviceName; - this.logger = getLogger(`event-bus:${this.serviceName}`); - - // Create Redis connections - const redisOptions = { - host: config.redisConfig.host, - port: config.redisConfig.port, - password: config.redisConfig.password, - db: config.redisConfig.db || 0, - lazyConnect: false, - enableOfflineQueue: true, - reconnectOnError: (err: Error) => { - this.logger.error('Redis connection error:', err); - return true; - }, - }; - - this.publisher = new Redis(redisOptions); - this.subscriber = new Redis(redisOptions); - - this.setupRedisHandlers(); - } - - private setupRedisHandlers(): void { - // Publisher handlers - this.publisher.on('connect', () => { - this.logger.info('Publisher connected to Redis'); - this.isConnected = true; - }); - - this.publisher.on('error', error => { - this.logger.error('Publisher Redis error:', error); - }); - - // Subscriber handlers - this.subscriber.on('connect', () => { - this.logger.info('Subscriber connected to Redis'); - // Resubscribe to all channels on reconnect - this.resubscribeAll(); - }); - - this.subscriber.on('error', error => { - this.logger.error('Subscriber Redis error:', error); - }); - - // Handle incoming messages - this.subscriber.on('message', this.handleMessage.bind(this)); - } - - private handleMessage(channel: string, message: string): void { - try { - const eventMessage: EventBusMessage = JSON.parse(message); - - // Skip messages from self - if (eventMessage.source === this.serviceName) { - return; - } - - // Extract event type from channel (remove 'events:' prefix) - const eventType = channel.replace('events:', ''); - - // Emit locally - this.emit(eventType, eventMessage); - - // Call registered handler if exists - const subscription = this.subscriptions.get(eventType); - if (subscription?.handler) { - Promise.resolve(subscription.handler(eventMessage)).catch(error => { - this.logger.error(`Handler error for event ${eventType}:`, error); - }); - } - - this.logger.debug(`Received event: ${eventType} from ${eventMessage.source}`); - } catch (error) { - this.logger.error('Failed to handle message:', { error, channel, message }); - } - } - - /** - * Publish an event - */ - async publish( - type: string, - data: T, - metadata?: Record - ): Promise { - const message: EventBusMessage = { - id: this.generateId(), - type, - source: this.serviceName, - timestamp: Date.now(), - data, - metadata, - }; - - // Emit locally first - this.emit(type, message); - - // Publish to Redis - if (this.isConnected) { - try { - const channel = `events:${type}`; - await this.publisher.publish(channel, JSON.stringify(message)); - this.logger.debug(`Published event: ${type}`, { messageId: message.id }); - } catch (error) { - this.logger.error(`Failed to publish event: ${type}`, { error, messageId: message.id }); - throw error; - } - } else { - this.logger.warn(`Not connected to Redis, event ${type} only emitted locally`); - } - } - - /** - * Subscribe to an event - */ - async subscribe(eventType: string, handler: EventHandler): Promise { - // Register handler - this.subscriptions.set(eventType, { - channel: `events:${eventType}`, - handler: message => handler(message as EventBusMessage), - }); - - // Add local listener - this.on(eventType, handler); - - // Subscribe to Redis channel - try { - const channel = `events:${eventType}`; - await this.subscriber.subscribe(channel); - this.logger.debug(`Subscribed to event: ${eventType}`); - } catch (error) { - this.logger.error(`Failed to subscribe to event: ${eventType}`, error); - throw error; - } - } - - /** - * Unsubscribe from an event - */ - async unsubscribe(eventType: string, handler?: EventHandler): Promise { - // Remove specific handler or all handlers - if (handler) { - this.off(eventType, handler); - } else { - this.removeAllListeners(eventType); - } - - // Remove from subscriptions - this.subscriptions.delete(eventType); - - // Unsubscribe from Redis - try { - const channel = `events:${eventType}`; - await this.subscriber.unsubscribe(channel); - this.logger.debug(`Unsubscribed from event: ${eventType}`); - } catch (error) { - this.logger.error(`Failed to unsubscribe from event: ${eventType}`, error); - } - } - - /** - * Resubscribe to all channels (used on reconnect) - */ - private async resubscribeAll(): Promise { - for (const [eventType, subscription] of this.subscriptions.entries()) { - try { - await this.subscriber.subscribe(subscription.channel); - this.logger.debug(`Resubscribed to event: ${eventType}`); - } catch (error) { - this.logger.error(`Failed to resubscribe to event: ${eventType}`, error); - } - } - } - - /** - * Wait for connection to be established - */ - async waitForConnection(timeout: number = 5000): Promise { - const startTime = Date.now(); - - while (!this.isConnected && Date.now() - startTime < timeout) { - await new Promise(resolve => setTimeout(resolve, 100)); - } - - if (!this.isConnected) { - throw new Error(`Failed to connect to Redis within ${timeout}ms`); - } - } - - /** - * Close all connections - */ - async close(): Promise { - this.isConnected = false; - - // Clear all subscriptions - this.subscriptions.clear(); - this.removeAllListeners(); - - // Close Redis connections - await Promise.all([this.publisher.quit(), this.subscriber.quit()]); - - this.logger.info('Event bus closed'); - } - - /** - * Generate unique message ID - */ - private generateId(): string { - return `${this.serviceName}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - /** - * Check if connected to Redis - */ - get connected(): boolean { - return this.isConnected; - } - - /** - * Get service name - */ - get service(): string { - return this.serviceName; - } -} diff --git a/libs/core/event-bus/src/index.ts b/libs/core/event-bus/src/index.ts deleted file mode 100644 index 87dfbd2e..00000000 --- a/libs/core/event-bus/src/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { EventBus } from './event-bus'; -import type { EventBusConfig } from './types'; - -/** - * Create a new event bus instance - */ -export function createEventBus(config: EventBusConfig): EventBus { - return new EventBus(config); -} - -// Re-export everything -export { EventBus } from './event-bus'; -export * from './types'; diff --git a/libs/core/event-bus/src/simple-event-bus.ts b/libs/core/event-bus/src/simple-event-bus.ts deleted file mode 100644 index b4d453d7..00000000 --- a/libs/core/event-bus/src/simple-event-bus.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import type { EventBusMessage, EventHandler, EventSubscription } from './types'; - -/** - * Simple in-memory event bus for testing - */ -export class SimpleEventBus { - private subscriptions = new Map>(); - private subscriptionById = new Map< - string, - { id: string; channel: string; handler: EventHandler } - >(); - private nextId = 1; - - subscribe(channel: string, handler: EventHandler): EventSubscription { - const id = `sub-${this.nextId++}`; - const subscription = { id, handler }; - - if (!this.subscriptions.has(channel)) { - this.subscriptions.set(channel, new Set()); - } - defined(this.subscriptions.get(channel)).add(subscription); - this.subscriptionById.set(id, { id, channel, handler }); - - return { channel, handler }; - } - - unsubscribe(idOrSubscription: string | EventSubscription): boolean { - if (typeof idOrSubscription === 'string') { - const subscription = this.subscriptionById.get(idOrSubscription); - if (!subscription) { - return false; - } - - const channelSubs = this.subscriptions.get(subscription.channel); - if (channelSubs) { - channelSubs.forEach(sub => { - if (sub.id === idOrSubscription) { - channelSubs.delete(sub); - } - }); - if (channelSubs.size === 0) { - this.subscriptions.delete(subscription.channel); - } - } - - this.subscriptionById.delete(idOrSubscription); - return true; - } else { - // Unsubscribe by matching handler and channel - const channelSubs = this.subscriptions.get(idOrSubscription.channel); - if (channelSubs) { - let removed = false; - channelSubs.forEach(sub => { - if (sub.handler === idOrSubscription.handler) { - channelSubs.delete(sub); - this.subscriptionById.delete(sub.id); - removed = true; - } - }); - if (channelSubs.size === 0) { - this.subscriptions.delete(idOrSubscription.channel); - } - return removed; - } - return false; - } - } - - async publish(event: string, data: unknown): Promise { - const message: EventBusMessage = { - id: `msg-${this.nextId++}`, - type: event, - source: 'simple-event-bus', - timestamp: Date.now(), - data, - }; - - const handlers: EventHandler[] = []; - - // Direct matches - const directSubs = this.subscriptions.get(event); - if (directSubs) { - handlers.push(...Array.from(directSubs).map(s => s.handler)); - } - - // Pattern matches - for (const [pattern, subs] of this.subscriptions) { - if (pattern.includes('*') && this.matchPattern(pattern, event)) { - handlers.push(...Array.from(subs).map(s => s.handler)); - } - } - - // Execute all handlers - await Promise.all( - handlers.map(handler => - Promise.resolve(handler(message)).catch(_err => { - // Silently catch errors - }) - ) - ); - } - - publishSync(event: string, data: unknown): void { - const message: EventBusMessage = { - id: `msg-${this.nextId++}`, - type: event, - source: 'simple-event-bus', - timestamp: Date.now(), - data, - }; - - const handlers: EventHandler[] = []; - - // Direct matches - const directSubs = this.subscriptions.get(event); - if (directSubs) { - handlers.push(...Array.from(directSubs).map(s => s.handler)); - } - - // Pattern matches - for (const [pattern, subs] of this.subscriptions) { - if (pattern.includes('*') && this.matchPattern(pattern, event)) { - handlers.push(...Array.from(subs).map(s => s.handler)); - } - } - - // Execute all handlers synchronously - handlers.forEach(handler => { - try { - handler(message); - } catch { - // Silently catch errors - } - }); - } - - once(event: string, handler: EventHandler): EventSubscription { - let subId: string; - const wrappedHandler: EventHandler = async message => { - await handler(message); - this.unsubscribe(subId); - }; - - const subscription = this.subscribe(event, wrappedHandler); - // Find the subscription ID - this.subscriptionById.forEach((value, key) => { - if (value.handler === wrappedHandler) { - subId = key; - } - }); - - return subscription; - } - - off(event: string, handler?: EventHandler): void { - if (!handler) { - // Remove all handlers for this event - const subs = this.subscriptions.get(event); - if (subs) { - for (const sub of subs) { - this.subscriptionById.delete(sub.id); - } - this.subscriptions.delete(event); - } - } else { - // Remove specific handler - const subs = this.subscriptions.get(event); - if (subs) { - const toRemove: string[] = []; - subs.forEach(sub => { - if (sub.handler === handler) { - toRemove.push(sub.id); - } - }); - toRemove.forEach(id => { - subs.forEach(sub => { - if (sub.id === id) { - subs.delete(sub); - } - }); - this.subscriptionById.delete(id); - }); - if (subs.size === 0) { - this.subscriptions.delete(event); - } - } - } - } - - hasSubscribers(event: string): boolean { - return this.subscriptions.has(event) && defined(this.subscriptions.get(event)).size > 0; - } - - clear(): void { - this.subscriptions.clear(); - this.subscriptionById.clear(); - } - - private matchPattern(pattern: string, event: string): boolean { - // Simple pattern matching: user.* matches user.created, user.updated, etc. - const regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$'); - return regex.test(event); - } -} diff --git a/libs/core/event-bus/src/types.ts b/libs/core/event-bus/src/types.ts deleted file mode 100644 index bb2032dd..00000000 --- a/libs/core/event-bus/src/types.ts +++ /dev/null @@ -1,111 +0,0 @@ -export interface EventBusMessage { - id: string; - type: string; - source: string; - timestamp: number; - data: T; - metadata?: Record; -} - -export interface EventHandler { - (message: EventBusMessage): Promise | void; -} - -export interface EventBusConfig { - serviceName: string; - redisConfig: { - host: string; - port: number; - password?: string; - db?: number; - }; - enableLogging?: boolean; -} - -export interface EventSubscription { - channel: string; - handler: EventHandler; -} - -// Trading-specific event types -export enum TradingEventType { - // Market data events - PRICE_UPDATE = 'market.price.update', - ORDERBOOK_UPDATE = 'market.orderbook.update', - TRADE_EXECUTED = 'market.trade.executed', - - // Order events - ORDER_CREATED = 'order.created', - ORDER_FILLED = 'order.filled', - ORDER_CANCELLED = 'order.cancelled', - ORDER_REJECTED = 'order.rejected', - - // Position events - POSITION_OPENED = 'position.opened', - POSITION_CLOSED = 'position.closed', - POSITION_UPDATED = 'position.updated', - - // Strategy events - STRATEGY_SIGNAL = 'strategy.signal', - STRATEGY_STARTED = 'strategy.started', - STRATEGY_STOPPED = 'strategy.stopped', - - // Risk events - RISK_LIMIT_BREACH = 'risk.limit.breach', - RISK_WARNING = 'risk.warning', - - // System events - SERVICE_STARTED = 'system.service.started', - SERVICE_STOPPED = 'system.service.stopped', - SERVICE_ERROR = 'system.service.error', -} - -// Event data types -export interface PriceUpdateEvent { - symbol: string; - price: number; - volume: number; - timestamp: number; -} - -export interface OrderEvent { - orderId: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price?: number; - type: 'market' | 'limit' | 'stop' | 'stop_limit'; - status: string; - portfolioId: string; - strategyId?: string; -} - -export interface PositionEvent { - positionId: string; - symbol: string; - quantity: number; - averageCost: number; - currentPrice: number; - unrealizedPnl: number; - realizedPnl: number; - portfolioId: string; -} - -export interface StrategySignalEvent { - strategyId: string; - signal: 'buy' | 'sell' | 'hold'; - symbol: string; - confidence: number; - indicators: Record; - timestamp: number; -} - -export interface RiskEvent { - type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration'; - severity: 'warning' | 'critical'; - currentValue: number; - limit: number; - portfolioId?: string; - strategyId?: string; - message: string; -} diff --git a/libs/core/event-bus/tsconfig.json b/libs/core/event-bus/tsconfig.json deleted file mode 100644 index 0b1bc98a..00000000 --- a/libs/core/event-bus/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "outDir": "./dist", - "rootDir": "./src", - "composite": true - }, - "include": ["src/**/*"], - "references": [ - { - "path": "../../core/logger" - }, - { - "path": "../../../libs/core/invariants" - } - ] -} diff --git a/libs/core/handlers/package.json b/libs/core/handlers/package.json index 894ffa24..587eda77 100644 --- a/libs/core/handlers/package.json +++ b/libs/core/handlers/package.json @@ -12,7 +12,6 @@ "dependencies": { "@stock-bot/services": "workspace:*", "@stock-bot/cache": "workspace:*", - "@stock-bot/config": "workspace:*", "@stock-bot/handler-registry": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/types": "workspace:*", diff --git a/libs/core/logger/package.json b/libs/core/logger/package.json index fabcc7ed..3f4e8736 100644 --- a/libs/core/logger/package.json +++ b/libs/core/logger/package.json @@ -11,7 +11,6 @@ "test": "bun test" }, "dependencies": { - "got": "^14.4.7", "pino": "^9.7.0", "pino-loki": "^2.6.0", "pino-pretty": "^13.0.0" diff --git a/libs/core/queue/src/batch-processor.ts b/libs/core/queue/src/batch-processor.ts index 0016ca1d..b6d7e1f1 100644 --- a/libs/core/queue/src/batch-processor.ts +++ b/libs/core/queue/src/batch-processor.ts @@ -346,6 +346,7 @@ async function addJobsInChunks( chunkSize: chunk.length, error, }); + throw error; } } diff --git a/libs/core/queue/src/dlq-handler.ts b/libs/core/queue/src/dlq-handler.ts deleted file mode 100644 index ec1fd4bb..00000000 --- a/libs/core/queue/src/dlq-handler.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { Queue, type Job } from 'bullmq'; -import type { DLQConfig, RedisConfig } from './types'; -import { getRedisConnection } from './utils'; - -// Logger interface for type safety -interface Logger { - info(message: string, meta?: Record): void; - error(message: string, meta?: Record): void; - warn(message: string, meta?: Record): void; - debug(message: string, meta?: Record): void; -} - -export class DeadLetterQueueHandler { - private dlq: Queue; - private config: Required; - private failureCount = new Map(); - private readonly logger: Logger; - - constructor( - private mainQueue: Queue, - connection: RedisConfig, - config: DLQConfig = {}, - logger?: Logger - ) { - this.logger = logger || console; - this.config = { - maxRetries: config.maxRetries ?? 3, - retryDelay: config.retryDelay ?? 60000, // 1 minute - alertThreshold: config.alertThreshold ?? 100, - cleanupAge: config.cleanupAge ?? 168, // 7 days - }; - - // Create DLQ with same name but -dlq suffix - const dlqName = `${mainQueue.name}-dlq`; - this.dlq = new Queue(dlqName, { connection: getRedisConnection(connection) }); - } - - /** - * Process a failed job - either retry or move to DLQ - */ - async handleFailedJob(job: Job, error: Error): Promise { - const jobKey = `${job.name}:${job.id}`; - const currentFailures = (this.failureCount.get(jobKey) || 0) + 1; - this.failureCount.set(jobKey, currentFailures); - - this.logger.warn('Job failed', { - jobId: job.id, - jobName: job.name, - attempt: job.attemptsMade, - maxAttempts: job.opts.attempts, - error: error.message, - failureCount: currentFailures, - }); - - // Check if job should be moved to DLQ - if (job.attemptsMade >= (job.opts.attempts || this.config.maxRetries)) { - await this.moveToDeadLetterQueue(job, error); - this.failureCount.delete(jobKey); - } - } - - /** - * Move job to dead letter queue - */ - private async moveToDeadLetterQueue(job: Job, error: Error): Promise { - try { - const dlqData = { - originalJob: { - id: job.id, - name: job.name, - data: job.data, - opts: job.opts, - attemptsMade: job.attemptsMade, - failedReason: job.failedReason, - processedOn: job.processedOn, - timestamp: job.timestamp, - }, - error: { - message: error.message, - stack: error.stack, - name: error.name, - }, - movedToDLQAt: new Date().toISOString(), - }; - - await this.dlq.add('failed-job', dlqData, { - removeOnComplete: 100, - removeOnFail: 100, - }); - - this.logger.error('Job moved to DLQ', { - jobId: job.id, - jobName: job.name, - error: error.message, - }); - - // Check if we need to alert - await this.checkAlertThreshold(); - } catch (dlqError) { - this.logger.error('Failed to move job to DLQ', { - jobId: job.id, - error: dlqError, - }); - } - } - - /** - * Retry jobs from DLQ - */ - async retryDLQJobs(limit = 10): Promise { - const jobs = await this.dlq.getCompleted(0, limit); - let retriedCount = 0; - - for (const dlqJob of jobs) { - try { - const { originalJob } = dlqJob.data; - - // Re-add to main queue with delay - await this.mainQueue.add(originalJob.name, originalJob.data, { - ...originalJob.opts, - delay: this.config.retryDelay, - attempts: this.config.maxRetries, - }); - - // Remove from DLQ - await dlqJob.remove(); - retriedCount++; - - this.logger.info('Job retried from DLQ', { - originalJobId: originalJob.id, - jobName: originalJob.name, - }); - } catch (error) { - this.logger.error('Failed to retry DLQ job', { - dlqJobId: dlqJob.id, - error, - }); - } - } - - return retriedCount; - } - - /** - * Get DLQ statistics - */ - async getStats(): Promise<{ - total: number; - recent: number; - byJobName: Record; - oldestJob: Date | null; - }> { - const [completed, failed, waiting] = await Promise.all([ - this.dlq.getCompleted(), - this.dlq.getFailed(), - this.dlq.getWaiting(), - ]); - - const allJobs = [...completed, ...failed, ...waiting]; - const byJobName: Record = {}; - let oldestTimestamp: number | null = null; - - for (const job of allJobs) { - const jobName = job.data.originalJob?.name || 'unknown'; - byJobName[jobName] = (byJobName[jobName] || 0) + 1; - - if (!oldestTimestamp || job.timestamp < oldestTimestamp) { - oldestTimestamp = job.timestamp; - } - } - - // Count recent jobs (last 24 hours) - const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000; - const recent = allJobs.filter(job => job.timestamp > oneDayAgo).length; - - return { - total: allJobs.length, - recent, - byJobName, - oldestJob: oldestTimestamp ? new Date(oldestTimestamp) : null, - }; - } - - /** - * Clean up old DLQ entries - */ - async cleanup(): Promise { - const ageInMs = this.config.cleanupAge * 60 * 60 * 1000; - const cutoffTime = Date.now() - ageInMs; - - const jobs = await this.dlq.getCompleted(); - let removedCount = 0; - - for (const job of jobs) { - if (job.timestamp < cutoffTime) { - await job.remove(); - removedCount++; - } - } - - this.logger.info('DLQ cleanup completed', { - removedCount, - cleanupAge: `${this.config.cleanupAge} hours`, - }); - - return removedCount; - } - - /** - * Check if alert threshold is exceeded - */ - private async checkAlertThreshold(): Promise { - const stats = await this.getStats(); - - if (stats.total >= this.config.alertThreshold) { - this.logger.error('DLQ alert threshold exceeded', { - threshold: this.config.alertThreshold, - currentCount: stats.total, - byJobName: stats.byJobName, - }); - // In a real implementation, this would trigger alerts - } - } - - /** - * Get failed jobs for inspection - */ - async inspectFailedJobs(limit = 10): Promise< - Array<{ - id: string; - name: string; - data: unknown; - error: unknown; - failedAt: string; - attempts: number; - }> - > { - const jobs = await this.dlq.getCompleted(0, limit); - - return jobs.map(job => ({ - id: job.data.originalJob.id, - name: job.data.originalJob.name, - data: job.data.originalJob.data, - error: job.data.error, - failedAt: job.data.movedToDLQAt, - attempts: job.data.originalJob.attemptsMade, - })); - } - - /** - * Shutdown DLQ handler - */ - async shutdown(): Promise { - await this.dlq.close(); - this.failureCount.clear(); - } -} diff --git a/libs/core/queue/src/index.ts b/libs/core/queue/src/index.ts index 67f6d19b..9ab2edaa 100644 --- a/libs/core/queue/src/index.ts +++ b/libs/core/queue/src/index.ts @@ -1,67 +1,32 @@ -// Core exports export { Queue } from './queue'; export { QueueManager } from './queue-manager'; export { ServiceCache, createServiceCache } from './service-cache'; -// Service utilities export { normalizeServiceName, generateCachePrefix, getFullQueueName, parseQueueName, } from './service-utils'; - -// Batch processing export { processBatchJob, processItems } from './batch-processor'; - -// DLQ handling -export { DeadLetterQueueHandler } from './dlq-handler'; - -// Metrics -export { QueueMetricsCollector } from './queue-metrics'; - -// Rate limiting export { QueueRateLimiter } from './rate-limiter'; - -// Types export type { - // Core types JobData, JobOptions, QueueOptions, GlobalStats, - - // Batch processing types BatchResult, ProcessOptions, BatchJobData, - - // Handler types JobHandler, TypedJobHandler, HandlerConfig, HandlerConfigWithSchedule, - HandlerInitializer, QueueStats, QueueWorkerConfig, - - // Configuration types RedisConfig, - QueueConfig, QueueManagerConfig, - - // Rate limiting types RateLimitConfig, RateLimitRule, - - // DLQ types - DLQConfig, - DLQJobInfo, - - // Scheduled job types ScheduledJob, - ScheduleConfig, - - // Smart Queue types - SmartQueueConfig, QueueRoute, } from './types'; diff --git a/libs/core/queue/src/queue-metrics.ts b/libs/core/queue/src/queue-metrics.ts deleted file mode 100644 index 6ea65372..00000000 --- a/libs/core/queue/src/queue-metrics.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { Queue, QueueEvents } from 'bullmq'; - -// import { getLogger } from '@stock-bot/logger'; - -// const logger = getLogger('queue-metrics'); - -interface QueueMetrics { - // Job counts - waiting: number; - active: number; - completed: number; - failed: number; - delayed: number; - paused?: number; - - // Performance metrics - processingTime: { - avg: number; - min: number; - max: number; - p95: number; - p99: number; - }; - - // Throughput - throughput: { - completedPerMinute: number; - failedPerMinute: number; - totalPerMinute: number; - }; - - // Job age - oldestWaitingJob: Date | null; - - // Health - isHealthy: boolean; - healthIssues: string[]; -} - -export class QueueMetricsCollector { - private processingTimes: number[] = []; - private completedTimestamps: number[] = []; - private failedTimestamps: number[] = []; - private jobStartTimes = new Map(); - private readonly maxSamples = 1000; - private readonly metricsInterval = 60000; // 1 minute - - constructor( - private queue: Queue, - private queueEvents: QueueEvents - ) { - this.setupEventListeners(); - } - - /** - * Setup event listeners for metrics collection - */ - private setupEventListeners(): void { - this.queueEvents.on('completed', () => { - // Record completion - this.completedTimestamps.push(Date.now()); - this.cleanupOldTimestamps(); - }); - - this.queueEvents.on('failed', () => { - // Record failure - this.failedTimestamps.push(Date.now()); - this.cleanupOldTimestamps(); - }); - - // Track processing times - this.queueEvents.on('active', ({ jobId }) => { - this.jobStartTimes.set(jobId, Date.now()); - }); - - this.queueEvents.on('completed', ({ jobId }) => { - const startTime = this.jobStartTimes.get(jobId); - if (startTime) { - const processingTime = Date.now() - startTime; - this.recordProcessingTime(processingTime); - this.jobStartTimes.delete(jobId); - } - }); - } - - /** - * Record processing time - */ - private recordProcessingTime(time: number): void { - this.processingTimes.push(time); - - // Keep only recent samples - if (this.processingTimes.length > this.maxSamples) { - this.processingTimes = this.processingTimes.slice(-this.maxSamples); - } - } - - /** - * Clean up old timestamps - */ - private cleanupOldTimestamps(): void { - const cutoff = Date.now() - this.metricsInterval; - - this.completedTimestamps = this.completedTimestamps.filter(ts => ts > cutoff); - this.failedTimestamps = this.failedTimestamps.filter(ts => ts > cutoff); - } - - /** - * Collect current metrics - */ - async collect(): Promise { - // Get job counts - const [waiting, active, completed, failed, delayed] = await Promise.all([ - this.queue.getWaitingCount(), - this.queue.getActiveCount(), - this.queue.getCompletedCount(), - this.queue.getFailedCount(), - this.queue.getDelayedCount(), - ]); - - // BullMQ doesn't have getPausedCount, check if queue is paused - const paused = (await this.queue.isPaused()) ? waiting : 0; - - // Calculate processing time metrics - const processingTime = this.calculateProcessingTimeMetrics(); - - // Calculate throughput - const throughput = this.calculateThroughput(); - - // Get oldest waiting job - const oldestWaitingJob = await this.getOldestWaitingJob(); - - // Check health - const { isHealthy, healthIssues } = this.checkHealth({ - waiting, - active, - failed, - processingTime, - }); - - return { - waiting, - active, - completed, - failed, - delayed, - paused, - processingTime, - throughput, - oldestWaitingJob, - isHealthy, - healthIssues, - }; - } - - /** - * Calculate processing time metrics - */ - private calculateProcessingTimeMetrics(): QueueMetrics['processingTime'] { - if (this.processingTimes.length === 0) { - return { avg: 0, min: 0, max: 0, p95: 0, p99: 0 }; - } - - const sorted = [...this.processingTimes].sort((a, b) => a - b); - const sum = sorted.reduce((acc, val) => acc + val, 0); - - return { - avg: sorted.length > 0 ? Math.round(sum / sorted.length) : 0, - min: sorted[0] || 0, - max: sorted[sorted.length - 1] || 0, - p95: sorted[Math.floor(sorted.length * 0.95)] || 0, - p99: sorted[Math.floor(sorted.length * 0.99)] || 0, - }; - } - - /** - * Calculate throughput metrics - */ - private calculateThroughput(): QueueMetrics['throughput'] { - const now = Date.now(); - const oneMinuteAgo = now - 60000; - - const completedPerMinute = this.completedTimestamps.filter(ts => ts > oneMinuteAgo).length; - const failedPerMinute = this.failedTimestamps.filter(ts => ts > oneMinuteAgo).length; - - return { - completedPerMinute, - failedPerMinute, - totalPerMinute: completedPerMinute + failedPerMinute, - }; - } - - /** - * Get oldest waiting job - */ - private async getOldestWaitingJob(): Promise { - const waitingJobs = await this.queue.getWaiting(0, 1); - - if (waitingJobs.length > 0) { - return new Date(waitingJobs[0].timestamp); - } - - return null; - } - - /** - * Check queue health - */ - private checkHealth(metrics: { - waiting: number; - active: number; - failed: number; - processingTime: QueueMetrics['processingTime']; - }): { isHealthy: boolean; healthIssues: string[] } { - const issues: string[] = []; - - // Check for high failure rate - const failureRate = metrics.failed / (metrics.failed + this.completedTimestamps.length); - if (failureRate > 0.1) { - issues.push(`High failure rate: ${(failureRate * 100).toFixed(1)}%`); - } - - // Check for queue backlog - if (metrics.waiting > 1000) { - issues.push(`Large queue backlog: ${metrics.waiting} jobs waiting`); - } - - // Check for slow processing - if (metrics.processingTime.avg > 30000) { - // 30 seconds - issues.push( - `Slow average processing time: ${(metrics.processingTime.avg / 1000).toFixed(1)}s` - ); - } - - // Check for stalled active jobs - if (metrics.active > 100) { - issues.push(`High number of active jobs: ${metrics.active}`); - } - - return { - isHealthy: issues.length === 0, - healthIssues: issues, - }; - } - - /** - * Get formatted metrics report - */ - async getReport(): Promise { - const metrics = await this.collect(); - - return ` -Queue Metrics Report -=================== -Status: ${metrics.isHealthy ? 'โœ… Healthy' : 'โš ๏ธ Issues Detected'} - -Job Counts: -- Waiting: ${metrics.waiting} -- Active: ${metrics.active} -- Completed: ${metrics.completed} -- Failed: ${metrics.failed} -- Delayed: ${metrics.delayed} -- Paused: ${metrics.paused} - -Performance: -- Avg Processing Time: ${(metrics.processingTime.avg / 1000).toFixed(2)}s -- Min/Max: ${(metrics.processingTime.min / 1000).toFixed(2)}s / ${(metrics.processingTime.max / 1000).toFixed(2)}s -- P95/P99: ${(metrics.processingTime.p95 / 1000).toFixed(2)}s / ${(metrics.processingTime.p99 / 1000).toFixed(2)}s - -Throughput: -- Completed/min: ${metrics.throughput.completedPerMinute} -- Failed/min: ${metrics.throughput.failedPerMinute} -- Total/min: ${metrics.throughput.totalPerMinute} - -${metrics.oldestWaitingJob ? `Oldest Waiting Job: ${metrics.oldestWaitingJob.toISOString()}` : 'No waiting jobs'} - -${metrics.healthIssues.length > 0 ? `\nHealth Issues:\n${metrics.healthIssues.map(issue => `- ${issue}`).join('\n')}` : ''} - `.trim(); - } - - /** - * Export metrics in Prometheus format - */ - async getPrometheusMetrics(): Promise { - const metrics = await this.collect(); - const queueName = this.queue.name; - - return ` -# HELP queue_jobs_total Total number of jobs by status -# TYPE queue_jobs_total gauge -queue_jobs_total{queue="${queueName}",status="waiting"} ${metrics.waiting} -queue_jobs_total{queue="${queueName}",status="active"} ${metrics.active} -queue_jobs_total{queue="${queueName}",status="completed"} ${metrics.completed} -queue_jobs_total{queue="${queueName}",status="failed"} ${metrics.failed} -queue_jobs_total{queue="${queueName}",status="delayed"} ${metrics.delayed} -queue_jobs_total{queue="${queueName}",status="paused"} ${metrics.paused} - -# HELP queue_processing_time_seconds Job processing time in seconds -# TYPE queue_processing_time_seconds summary -queue_processing_time_seconds{queue="${queueName}",quantile="0.5"} ${(metrics.processingTime.avg / 1000).toFixed(3)} -queue_processing_time_seconds{queue="${queueName}",quantile="0.95"} ${(metrics.processingTime.p95 / 1000).toFixed(3)} -queue_processing_time_seconds{queue="${queueName}",quantile="0.99"} ${(metrics.processingTime.p99 / 1000).toFixed(3)} -queue_processing_time_seconds_sum{queue="${queueName}"} ${((metrics.processingTime.avg * this.processingTimes.length) / 1000).toFixed(3)} -queue_processing_time_seconds_count{queue="${queueName}"} ${this.processingTimes.length} - -# HELP queue_throughput_per_minute Jobs processed per minute -# TYPE queue_throughput_per_minute gauge -queue_throughput_per_minute{queue="${queueName}",status="completed"} ${metrics.throughput.completedPerMinute} -queue_throughput_per_minute{queue="${queueName}",status="failed"} ${metrics.throughput.failedPerMinute} -queue_throughput_per_minute{queue="${queueName}",status="total"} ${metrics.throughput.totalPerMinute} - -# HELP queue_health Queue health status -# TYPE queue_health gauge -queue_health{queue="${queueName}"} ${metrics.isHealthy ? 1 : 0} - `.trim(); - } -} diff --git a/libs/core/queue/src/types.ts b/libs/core/queue/src/types.ts index 5f4cfde5..3e215ab4 100644 --- a/libs/core/queue/src/types.ts +++ b/libs/core/queue/src/types.ts @@ -84,16 +84,6 @@ export interface GlobalStats { uptime: number; } -// Legacy type for backward compatibility -export interface QueueConfig extends QueueManagerConfig { - queueName?: string; - workers?: number; - concurrency?: number; - handlers?: HandlerInitializer[]; - dlqConfig?: DLQConfig; - enableMetrics?: boolean; -} - // Extended batch job data for queue implementation export interface BatchJobData { payloadKey: string; @@ -103,10 +93,6 @@ export interface BatchJobData { totalDelayHours: number; // Total time to distribute all batches } -export interface HandlerInitializer { - (): void | Promise; -} - // Rate limiting types export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow; @@ -120,40 +106,6 @@ export interface RateLimitRule { config: RateLimitConfig; } -// DLQ types -export interface DLQConfig { - maxRetries?: number; - retryDelay?: number; - alertThreshold?: number; - cleanupAge?: number; -} - -export interface DLQJobInfo { - id: string; - name: string; - failedReason: string; - attemptsMade: number; - timestamp: number; - data: unknown; -} - -export interface ScheduleConfig { - pattern: string; - jobName: string; - data?: unknown; - options?: ExtendedJobOptions; -} - -// Smart Queue Types -export interface SmartQueueConfig extends QueueManagerConfig { - /** Name of the current service */ - serviceName: string; - /** Whether to auto-discover handlers from registry */ - autoDiscoverHandlers?: boolean; - /** Custom service registry (defaults to built-in) */ - serviceRegistry?: Record; -} - export interface QueueRoute { /** Full queue name (now just the handler name, e.g., 'ceo') */ fullName: string; diff --git a/libs/core/queue/test/batch-processor.test.ts b/libs/core/queue/test/batch-processor.test.ts index bd69086b..60d1ed42 100644 --- a/libs/core/queue/test/batch-processor.test.ts +++ b/libs/core/queue/test/batch-processor.test.ts @@ -120,15 +120,17 @@ describe('Batch Processor', () => { throw new Error('Failed to add jobs'); }); - // processBatchJob should still complete even if addBulk fails - const _result = await processBatchJob( - batchData, - 'test-queue', - mockQueueManager as unknown as QueueManager - ); + // processBatchJob rethrows chunk errors and retains the cached payload for retry + await expect( + processBatchJob( + batchData, + 'test-queue', + mockQueueManager as unknown as QueueManager + ) + ).rejects.toThrow('Failed to add jobs'); expect(mockQueue.addBulk).toHaveBeenCalled(); - // The error is logged in addJobsInChunks, not in processBatchJob + expect(mockCache.del).not.toHaveBeenCalled(); expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object)); }); @@ -273,15 +275,15 @@ describe('Batch Processor', () => { throw new Error('Process error'); }); - // processItems catches errors and continues, so it won't reject - const result = await processItems( - items, - 'test-queue', - options, - mockQueueManager as unknown as QueueManager - ); + await expect( + processItems( + items, + 'test-queue', + options, + mockQueueManager as unknown as QueueManager + ) + ).rejects.toThrow('Process error'); - expect(result.jobsCreated).toBe(0); expect(mockQueue.addBulk).toHaveBeenCalled(); expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object)); }); diff --git a/libs/core/queue/test/dlq-handler.test.ts b/libs/core/queue/test/dlq-handler.test.ts deleted file mode 100644 index e681ce61..00000000 --- a/libs/core/queue/test/dlq-handler.test.ts +++ /dev/null @@ -1,278 +0,0 @@ -import type { Job, Queue } from 'bullmq'; -import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import { DeadLetterQueueHandler } from '../src/dlq-handler'; -import type { RedisConfig } from '../src/types'; - -describe('DeadLetterQueueHandler', () => { - // Mock the DLQ Queue that will be created - const mockDLQQueue = { - name: 'test-queue-dlq', - add: mock(() => Promise.resolve({})), - getCompleted: mock(() => Promise.resolve([])), - getFailed: mock(() => Promise.resolve([])), - getWaiting: mock(() => Promise.resolve([])), - close: mock(() => Promise.resolve()), - } as unknown as Queue; - const mockLogger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - trace: mock(() => {}), - }; - - const mockQueue = { - name: 'test-queue', - add: mock(() => Promise.resolve({})), - getCompleted: mock(() => Promise.resolve([])), - getFailed: mock(() => Promise.resolve([])), - getWaiting: mock(() => Promise.resolve([])), - } as unknown as Queue; - - const mockRedisConfig: RedisConfig = { - host: 'localhost', - port: 6379, - }; - - let dlqHandler: DeadLetterQueueHandler; - - beforeEach(() => { - // Reset DLQ queue mocks - mockDLQQueue.add = mock(() => Promise.resolve({})); - mockDLQQueue.getCompleted = mock(() => Promise.resolve([])); - mockDLQQueue.getFailed = mock(() => Promise.resolve([])); - mockDLQQueue.getWaiting = mock(() => Promise.resolve([])); - mockDLQQueue.close = mock(() => Promise.resolve()); - - // Create handler with mocked DLQ queue - dlqHandler = new DeadLetterQueueHandler(mockQueue, mockRedisConfig, {}, mockLogger); - // Override the dlq property to use our mock - (dlqHandler as any).dlq = mockDLQQueue; - - // Reset mocks - mockLogger.info = mock(() => {}); - mockLogger.error = mock(() => {}); - mockLogger.warn = mock(() => {}); - }); - - describe('handleFailedJob', () => { - it('should log failed job details', async () => { - const mockJob = { - id: 'job-123', - name: 'test-job', - queueName: 'test-queue', - data: { - handler: 'testHandler', - operation: 'testOp', - payload: { test: true }, - }, - attemptsMade: 3, - opts: { attempts: 3 }, - failedReason: 'Test error', - finishedOn: Date.now(), - processedOn: Date.now() - 5000, - timestamp: Date.now() - 10000, - } as Job; - - const error = new Error('Job processing failed'); - - await dlqHandler.handleFailedJob(mockJob, error); - - expect(mockLogger.error).toHaveBeenCalledWith( - 'Job moved to DLQ', - expect.objectContaining({ - jobId: 'job-123', - jobName: 'test-job', - error: 'Job processing failed', - }) - ); - }); - - it('should handle jobs without data gracefully', async () => { - const mockJob = { - id: 'job-123', - name: 'test-job', - queueName: 'test-queue', - data: null, - attemptsMade: 3, - opts: { attempts: 3 }, - timestamp: Date.now() - 10000, - processedOn: Date.now() - 5000, - } as any; - - const error = new Error('No data'); - - await dlqHandler.handleFailedJob(mockJob, error); - - expect(mockLogger.error).toHaveBeenCalled(); - }); - - it('should check alert threshold', async () => { - const mockJob = { - id: 'job-123', - name: 'critical-job', - queueName: 'critical-queue', - data: { handler: 'critical', operation: 'process' }, - attemptsMade: 3, - opts: { attempts: 3 }, - } as Job; - - const error = new Error('Critical failure'); - - await dlqHandler.handleFailedJob(mockJob, error); - - expect(mockLogger.warn).toHaveBeenCalled(); - }); - }); - - describe('getStats', () => { - it('should return DLQ statistics', async () => { - const mockJobs = [ - { - id: 'job-1', - data: { originalJob: { name: 'process' } }, - timestamp: Date.now(), - }, - { - id: 'job-2', - data: { originalJob: { name: 'process' } }, - timestamp: Date.now() - 100000, - }, - { - id: 'job-3', - data: { originalJob: { name: 'validate' } }, - timestamp: Date.now() - 200000, - }, - ]; - - mockDLQQueue.getCompleted = mock(() => Promise.resolve(mockJobs)); - mockDLQQueue.getFailed = mock(() => Promise.resolve([])); - mockDLQQueue.getWaiting = mock(() => Promise.resolve([])); - - const stats = await dlqHandler.getStats(); - - expect(stats.total).toBe(3); - expect(stats.byJobName['process']).toBe(2); - expect(stats.byJobName['validate']).toBe(1); - expect(stats.oldestJob).toBeDefined(); - }); - - it('should handle empty DLQ', async () => { - const stats = await dlqHandler.getStats(); - - expect(stats.total).toBe(0); - expect(stats.byJobName).toEqual({}); - expect(stats.oldestJob).toBeNull(); - }); - }); - - describe('retryDLQJobs', () => { - it('should retry jobs from DLQ', async () => { - const mockDLQJobs = [ - { - id: 'dlq-1', - data: { - originalJob: { - id: 'orig-1', - name: 'retry-job', - data: { test: true }, - opts: {}, - }, - }, - remove: mock(() => Promise.resolve()), - }, - ]; - - (dlqHandler as any).dlq = { - getCompleted: mock(() => Promise.resolve(mockDLQJobs)), - }; - - const retriedCount = await dlqHandler.retryDLQJobs(1); - - expect(retriedCount).toBe(1); - expect(mockQueue.add).toHaveBeenCalledWith( - 'retry-job', - { test: true }, - expect.objectContaining({ delay: expect.any(Number) }) - ); - expect(mockDLQJobs[0].remove).toHaveBeenCalled(); - }); - }); - - describe('cleanup', () => { - it('should clean up old DLQ entries', async () => { - const oldJob = { - id: 'old-1', - timestamp: Date.now() - 8 * 24 * 60 * 60 * 1000, // 8 days old - remove: mock(() => Promise.resolve()), - }; - - const newJob = { - id: 'new-1', - timestamp: Date.now() - 1 * 24 * 60 * 60 * 1000, // 1 day old - remove: mock(() => Promise.resolve()), - }; - - (dlqHandler as any).dlq = { - getCompleted: mock(() => Promise.resolve([oldJob, newJob])), - }; - - const removedCount = await dlqHandler.cleanup(); - - expect(removedCount).toBe(1); - expect(oldJob.remove).toHaveBeenCalled(); - expect(newJob.remove).not.toHaveBeenCalled(); - }); - }); - - describe('inspectFailedJobs', () => { - it('should return formatted failed jobs', async () => { - const mockDLQJobs = [ - { - data: { - originalJob: { - id: 'orig-1', - name: 'test-job', - data: { test: true }, - attemptsMade: 3, - }, - error: { - message: 'Test error', - stack: 'Error stack', - }, - movedToDLQAt: '2024-01-01T00:00:00Z', - }, - }, - ]; - - (dlqHandler as any).dlq = { - getCompleted: mock(() => Promise.resolve(mockDLQJobs)), - }; - - const inspected = await dlqHandler.inspectFailedJobs(10); - - expect(inspected).toHaveLength(1); - expect(inspected[0]).toEqual({ - id: 'orig-1', - name: 'test-job', - data: { test: true }, - error: { message: 'Test error', stack: 'Error stack' }, - failedAt: '2024-01-01T00:00:00Z', - attempts: 3, - }); - }); - }); - - describe('shutdown', () => { - it('should close DLQ and clear state', async () => { - const mockClose = mock(() => Promise.resolve()); - (dlqHandler as any).dlq = { - close: mockClose, - }; - - await dlqHandler.shutdown(); - - expect(mockClose).toHaveBeenCalled(); - }); - }); -}); diff --git a/libs/core/queue/test/queue-metrics.test.ts b/libs/core/queue/test/queue-metrics.test.ts deleted file mode 100644 index 5f2b0100..00000000 --- a/libs/core/queue/test/queue-metrics.test.ts +++ /dev/null @@ -1,233 +0,0 @@ -import type { Job, Queue, QueueEvents } from 'bullmq'; -import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test'; -import { QueueMetricsCollector } from '../src/queue-metrics'; - -describe('QueueMetricsCollector', () => { - let metrics: QueueMetricsCollector; - let mockQueue: { - name: string; - getWaitingCount: Mock<() => Promise>; - getActiveCount: Mock<() => Promise>; - getCompletedCount: Mock<() => Promise>; - getFailedCount: Mock<() => Promise>; - getDelayedCount: Mock<() => Promise>; - isPaused: Mock<() => Promise>; - getWaiting: Mock<() => Promise>; - }; - let mockQueueEvents: { - on: Mock<(event: string, handler: Function) => void>; - }; - - beforeEach(() => { - mockQueue = { - name: 'test-queue', - getWaitingCount: mock(() => Promise.resolve(0)), - getActiveCount: mock(() => Promise.resolve(0)), - getCompletedCount: mock(() => Promise.resolve(0)), - getFailedCount: mock(() => Promise.resolve(0)), - getDelayedCount: mock(() => Promise.resolve(0)), - isPaused: mock(() => Promise.resolve(false)), - getWaiting: mock(() => Promise.resolve([])), - }; - - mockQueueEvents = { - on: mock(() => {}), - }; - - metrics = new QueueMetricsCollector( - mockQueue as unknown as Queue, - mockQueueEvents as unknown as QueueEvents - ); - }); - - describe('collect metrics', () => { - it('should collect current metrics', async () => { - mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5)); - mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2)); - mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100)); - mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3)); - mockQueue.getDelayedCount.mockImplementation(() => Promise.resolve(1)); - - // Add some completed timestamps to avoid 100% failure rate - const completedHandler = mockQueueEvents.on.mock.calls.find( - call => call[0] === 'completed' - )?.[1]; - if (completedHandler) { - for (let i = 0; i < 50; i++) { - completedHandler(); - } - } - - const result = await metrics.collect(); - - expect(result.waiting).toBe(5); - expect(result.active).toBe(2); - expect(result.completed).toBe(100); - expect(result.failed).toBe(3); - expect(result.delayed).toBe(1); - expect(result.isHealthy).toBe(true); - }); - - it('should detect health issues', async () => { - mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(2000)); // High backlog - mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(150)); // High active - mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(50)); - - const result = await metrics.collect(); - - expect(result.isHealthy).toBe(false); - expect(result.healthIssues.length).toBeGreaterThan(0); - expect(result.healthIssues.some(issue => issue.includes('queue backlog'))).toBe(true); - expect(result.healthIssues.some(issue => issue.includes('active jobs'))).toBe(true); - }); - - it('should handle paused queue', async () => { - mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(10)); - mockQueue.isPaused.mockImplementation(() => Promise.resolve(true)); - - const result = await metrics.collect(); - - expect(result.paused).toBe(10); - }); - }); - - describe('processing time metrics', () => { - it('should calculate processing time metrics', async () => { - // Access private property for testing - const metricsWithPrivate = metrics as QueueMetricsCollector & { - processingTimes: number[]; - }; - metricsWithPrivate.processingTimes = [1000, 2000, 3000, 4000, 5000]; - - const result = await metrics.collect(); - - expect(result.processingTime.avg).toBe(3000); - expect(result.processingTime.min).toBe(1000); - expect(result.processingTime.max).toBe(5000); - expect(result.processingTime.p95).toBe(5000); - }); - - it('should handle no processing times', async () => { - const result = await metrics.collect(); - - expect(result.processingTime.avg).toBe(0); - expect(result.processingTime.min).toBe(0); - expect(result.processingTime.max).toBe(0); - }); - }); - - describe('throughput metrics', () => { - it('should calculate throughput', async () => { - // Access private properties for testing - const metricsWithPrivate = metrics as QueueMetricsCollector & { - completedTimestamps: number[]; - failedTimestamps: number[]; - }; - - const now = Date.now(); - metricsWithPrivate.completedTimestamps = [ - now - 30000, // 30 seconds ago - now - 20000, - now - 10000, - ]; - metricsWithPrivate.failedTimestamps = [now - 25000, now - 5000]; - - const result = await metrics.collect(); - - expect(result.throughput.completedPerMinute).toBe(3); - expect(result.throughput.failedPerMinute).toBe(2); - expect(result.throughput.totalPerMinute).toBe(5); - }); - }); - - describe('getReport', () => { - it('should generate formatted report', async () => { - mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5)); - mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2)); - mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100)); - mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3)); - - // Add some completed timestamps to make it healthy - const completedHandler = mockQueueEvents.on.mock.calls.find( - call => call[0] === 'completed' - )?.[1]; - if (completedHandler) { - for (let i = 0; i < 50; i++) { - completedHandler(); - } - } - - const report = await metrics.getReport(); - - expect(report).toContain('Queue Metrics Report'); - expect(report).toContain('โœ… Healthy'); - expect(report).toContain('Waiting: 5'); - expect(report).toContain('Active: 2'); - expect(report).toContain('Completed: 100'); - expect(report).toContain('Failed: 3'); - }); - }); - - describe('getPrometheusMetrics', () => { - it('should generate Prometheus formatted metrics', async () => { - mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5)); - mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2)); - mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100)); - mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3)); - - const prometheusMetrics = await metrics.getPrometheusMetrics(); - - expect(prometheusMetrics).toContain('# HELP queue_jobs_total'); - expect(prometheusMetrics).toContain( - 'queue_jobs_total{queue="test-queue",status="waiting"} 5' - ); - expect(prometheusMetrics).toContain('queue_jobs_total{queue="test-queue",status="active"} 2'); - expect(prometheusMetrics).toContain( - 'queue_jobs_total{queue="test-queue",status="completed"} 100' - ); - expect(prometheusMetrics).toContain('# HELP queue_processing_time_seconds'); - expect(prometheusMetrics).toContain('# HELP queue_throughput_per_minute'); - expect(prometheusMetrics).toContain('# HELP queue_health'); - }); - }); - - describe('event listeners', () => { - it('should setup event listeners on construction', () => { - const newMockQueueEvents = { - on: mock<(event: string, handler: Function) => void>(() => {}), - }; - - new QueueMetricsCollector( - mockQueue as unknown as Queue, - newMockQueueEvents as unknown as QueueEvents - ); - - expect(newMockQueueEvents.on).toHaveBeenCalledWith('completed', expect.any(Function)); - expect(newMockQueueEvents.on).toHaveBeenCalledWith('failed', expect.any(Function)); - expect(newMockQueueEvents.on).toHaveBeenCalledWith('active', expect.any(Function)); - }); - }); - - describe('oldest waiting job', () => { - it('should get oldest waiting job date', async () => { - const oldJob = { - timestamp: Date.now() - 60000, // 1 minute ago - } as Job; - - mockQueue.getWaiting.mockImplementation(() => Promise.resolve([oldJob])); - - const result = await metrics.collect(); - - expect(result.oldestWaitingJob).toBeDefined(); - expect(result.oldestWaitingJob).toBeInstanceOf(Date); - }); - - it('should return null when no waiting jobs', async () => { - mockQueue.getWaiting.mockImplementation(() => Promise.resolve([])); - - const result = await metrics.collect(); - - expect(result.oldestWaitingJob).toBeNull(); - }); - }); -}); diff --git a/libs/core/services/package.json b/libs/core/services/package.json index e6ba70a8..05f3d88d 100644 --- a/libs/core/services/package.json +++ b/libs/core/services/package.json @@ -23,7 +23,6 @@ "@stock-bot/postgres": "workspace:*", "@stock-bot/proxy": "workspace:*", "@stock-bot/questdb": "workspace:*", - "@stock-bot/queue": "workspace:*", - "playwright": "^1.40.0" + "@stock-bot/queue": "workspace:*" } } diff --git a/libs/core/services/src/index.ts b/libs/core/services/src/index.ts index 81650072..5539aac1 100644 --- a/libs/core/services/src/index.ts +++ b/libs/core/services/src/index.ts @@ -22,7 +22,6 @@ export type QuestDBClient = Public; export type Browser = Public; export type ProxyManager = Public; export type { CacheProvider, CacheStats } from '@stock-bot/cache'; -export type { BrowserContext, Page } from 'playwright'; export type { ProxyInfo, ProxyStats } from '@stock-bot/proxy'; /** Disabled adapters are null; omitted capabilities are undefined. */ diff --git a/libs/core/types/src/backtesting.ts b/libs/core/types/src/backtesting.ts deleted file mode 100644 index 0aa505dd..00000000 --- a/libs/core/types/src/backtesting.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Backtesting & Strategy Types - * Types for strategy backtesting and analysis - */ - -import type { PortfolioAnalysis } from './portfolio'; -import type { DrawdownAnalysis, RiskMetrics } from './risk-metrics'; -import type { TradeExecution, TradePerformance } from './trading'; - -/** - * Backtesting results - */ -export interface BacktestResults { - /** All trades executed */ - trades: TradeExecution[]; - /** Equity curve over time */ - equityCurve: Array<{ value: number; date: Date }>; - /** Performance metrics */ - performance: PortfolioAnalysis; - /** Risk metrics */ - riskMetrics: RiskMetrics; - /** Drawdown analysis */ - drawdownAnalysis: DrawdownAnalysis; - /** Trade performance */ - tradePerformance: TradePerformance; - /** Start date */ - startDate: Date; - /** End date */ - endDate: Date; - /** Initial capital */ - initialCapital: number; - /** Final value */ - finalValue: number; -} diff --git a/libs/core/types/src/decorators.ts b/libs/core/types/src/decorators.ts index 76bac395..eeb9f42c 100644 --- a/libs/core/types/src/decorators.ts +++ b/libs/core/types/src/decorators.ts @@ -1,45 +1,3 @@ -/** - * Decorator Type Definitions - * Type definitions for handler decorators - */ - -/** - * Schedule configuration for operations - */ -export interface ScheduleConfig { - cronPattern: string; - priority?: number; - immediately?: boolean; - description?: string; -} - -/** - * Decorator metadata stored on classes - */ -export interface DecoratorMetadata { - handlerName?: string; - operations?: Array<{ - name: string; - methodName: string; - schedules?: ScheduleConfig[]; - }>; - disabled?: boolean; -} - -/** - * Type for decorator factories - */ -export type DecoratorFactory = (target: T, context?: unknown) => T | void; - -/** - * Type for method decorators - */ -export type MethodDecoratorFactory = ( - target: object, - propertyKey: string, - descriptor?: PropertyDescriptor -) => void | PropertyDescriptor; - /** Metadata shared by decorators, discovery, and handler dispatch. */ export interface RateLimitWindow { points: number; diff --git a/libs/core/types/src/financial-statements.ts b/libs/core/types/src/financial-statements.ts deleted file mode 100644 index dd4bda6b..00000000 --- a/libs/core/types/src/financial-statements.ts +++ /dev/null @@ -1,197 +0,0 @@ -/** - * Financial Statements Types - * Types for fundamental financial statement data - */ - -/** - * Balance Sheet data structure - */ -export interface BalanceSheet { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - // Assets - /** Total current assets */ - totalCurrentAssets: number; - /** Cash and cash equivalents */ - cashAndEquivalents: number; - /** Short-term investments */ - shortTermInvestments?: number; - /** Accounts receivable */ - accountsReceivable: number; - /** Inventory */ - inventory: number; - /** Prepaid expenses */ - prepaidExpenses?: number; - /** Other current assets */ - otherCurrentAssets?: number; - - /** Total non-current assets */ - totalNonCurrentAssets: number; - /** Property, plant & equipment (net) */ - propertyPlantEquipmentNet: number; - /** Intangible assets */ - intangibleAssets?: number; - /** Goodwill */ - goodwill?: number; - /** Long-term investments */ - longTermInvestments?: number; - /** Other non-current assets */ - otherNonCurrentAssets?: number; - - /** Total assets */ - totalAssets: number; - - // Liabilities - /** Total current liabilities */ - totalCurrentLiabilities: number; - /** Accounts payable */ - accountsPayable: number; - /** Short-term debt */ - shortTermDebt: number; - /** Accrued liabilities */ - accruedLiabilities?: number; - /** Other current liabilities */ - otherCurrentLiabilities?: number; - - /** Total non-current liabilities */ - totalNonCurrentLiabilities: number; - /** Long-term debt */ - longTermDebt: number; - /** Deferred tax liabilities */ - deferredTaxLiabilities?: number; - /** Other non-current liabilities */ - otherNonCurrentLiabilities?: number; - - /** Total liabilities */ - totalLiabilities: number; - - // Equity - /** Total stockholders' equity */ - totalStockholdersEquity: number; - /** Common stock */ - commonStock: number; - /** Retained earnings */ - retainedEarnings: number; - /** Additional paid-in capital */ - additionalPaidInCapital?: number; - /** Treasury stock */ - treasuryStock?: number; - /** Accumulated other comprehensive income */ - accumulatedOtherComprehensiveIncome?: number; -} - -/** - * Income Statement data structure - */ -export interface IncomeStatement { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - /** Total revenue/net sales */ - totalRevenue: number; - /** Cost of goods sold */ - costOfGoodsSold: number; - /** Gross profit */ - grossProfit: number; - - /** Operating expenses */ - operatingExpenses: number; - /** Research and development */ - researchAndDevelopment?: number; - /** Selling, general & administrative */ - sellingGeneralAdministrative?: number; - /** Depreciation and amortization */ - depreciationAmortization?: number; - /** Other operating expenses */ - otherOperatingExpenses?: number; - - /** Operating income */ - operatingIncome: number; - - /** Interest income */ - interestIncome?: number; - /** Interest expense */ - interestExpense?: number; - /** Other income/expense */ - otherIncomeExpense?: number; - - /** Income before taxes */ - incomeBeforeTaxes: number; - /** Income tax expense */ - incomeTaxExpense: number; - /** Net income */ - netIncome: number; - - /** Earnings per share (basic) */ - earningsPerShareBasic: number; - /** Earnings per share (diluted) */ - earningsPerShareDiluted: number; - /** Weighted average shares outstanding (basic) */ - sharesOutstandingBasic: number; - /** Weighted average shares outstanding (diluted) */ - sharesOutstandingDiluted: number; -} - -/** - * Cash Flow Statement data structure - */ -export interface CashFlowStatement { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - // Operating Activities - /** Net income */ - netIncome: number; - /** Depreciation and amortization */ - depreciationAmortization: number; - /** Changes in working capital */ - changesInWorkingCapital: number; - /** Other operating activities */ - otherOperatingActivities?: number; - /** Net cash from operating activities */ - netCashFromOperatingActivities: number; - - // Investing Activities - /** Capital expenditures */ - capitalExpenditures: number; - /** Acquisitions */ - acquisitions?: number; - /** Investments */ - investments?: number; - /** Other investing activities */ - otherInvestingActivities?: number; - /** Net cash from investing activities */ - netCashFromInvestingActivities: number; - - // Financing Activities - /** Debt issuance/repayment */ - debtIssuanceRepayment?: number; - /** Equity issuance/repurchase */ - equityIssuanceRepurchase?: number; - /** Dividends paid */ - dividendsPaid?: number; - /** Other financing activities */ - otherFinancingActivities?: number; - /** Net cash from financing activities */ - netCashFromFinancingActivities: number; - - /** Net change in cash */ - netChangeInCash: number; - /** Cash at beginning of period */ - cashAtBeginningOfPeriod: number; - /** Cash at end of period */ - cashAtEndOfPeriod: number; -} diff --git a/libs/core/types/src/helpers.ts b/libs/core/types/src/helpers.ts index 835d73b9..62ef0ea4 100644 --- a/libs/core/types/src/helpers.ts +++ b/libs/core/types/src/helpers.ts @@ -1,19 +1,7 @@ -/** - * Helper Types - * Generic utility types for making functions work across different data types - */ - -/** - * Interface for data that has a close price - * Used to make functions generic across different data types - */ export interface HasClose { close: number; } -/** - * Interface for data that has OHLC prices - */ export interface HasOHLC { open: number; high: number; @@ -21,16 +9,6 @@ export interface HasOHLC { close: number; } -/** - * Interface for data that has volume - */ export interface HasVolume { volume: number; } - -/** - * Interface for data that has timestamp - */ -export interface HasTimestamp { - timestamp: number; -} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 0bc3ea60..ff1c14e2 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -1,49 +1,9 @@ /** * Stock Bot Types Library - * Standardized type definitions for the entire trading platform + * Standardized type definitions for the trading and research platform */ -// Export all market data types -export type { - LiquidityMetrics, - MarketData, - MarketRegime, - OHLCV, - OHLCVWithMetadata, -} from './market-data'; - -// Export all portfolio & position types -export type { - AssetAllocation, - KellyParams, - PortfolioAnalysis, - PortfolioPosition, - PositionSizeParams, -} from './portfolio'; - -// Export all trading & execution types -export type { TradeExecution, TradePerformance } from './trading'; - -// Export all risk & performance metrics -export type { DrawdownAnalysis, ReturnAnalysis, RiskMetrics } from './risk-metrics'; - -// Export all options pricing types -export type { GreeksCalculation, OptionParameters, OptionPricing } from './options'; - -// Export all financial statement types -export type { BalanceSheet, CashFlowStatement, IncomeStatement } from './financial-statements'; - -// Export all technical analysis types -export type { - CorrelationMatrix, - CorrelationResult, - GARCHParameters, - TechnicalIndicators, - VolatilityEstimates, -} from './technical-analysis'; - -// Export backtesting types -export type { BacktestResults } from './backtesting'; +export type { OHLCV } from './market-data'; export type { BacktestRunConfiguration, BacktestRunMetrics, @@ -59,11 +19,7 @@ export type { CanonicalMetrics, CanonicalBacktestAnalytics, } from './canonical-analytics'; - -// Export helper types -export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers'; - -// Export handler types +export type { HasClose, HasOHLC, HasVolume } from './helpers'; export type { ExecutionContext, HandlerConfig, @@ -75,18 +31,7 @@ export type { ScheduledJob, TypedJobHandler, } from './handlers'; - -// Export decorator types -export type { - ScheduleConfig, - DecoratorMetadata, - DecoratorFactory, - MethodDecoratorFactory, -} from './decorators'; - -// Export queue types export type { JobData, JobOptions, QueueStats, BatchJobData, QueueWorkerConfig } from './queue'; - export type { DecoratedHandlerClass, DecoratedHandlerMetadata, diff --git a/libs/core/types/src/market-data.ts b/libs/core/types/src/market-data.ts index 4d51fd74..a96e71c5 100644 --- a/libs/core/types/src/market-data.ts +++ b/libs/core/types/src/market-data.ts @@ -1,11 +1,6 @@ -/** - * Market Data Types - * Standard types for market data and pricing information - */ - /** * Standard OHLCV (Open, High, Low, Close, Volume) data structure - * Used for candlestick/bar chart data across all market data providers + * Used for candlestick/bar chart data across market data adapters */ export interface OHLCV { /** Opening price for the time period */ @@ -25,83 +20,3 @@ export interface OHLCV { /** Time interval (e.g., '1m', '5m', '1h', '1d') */ interval?: string; } - -/** - * OHLCV data with additional metadata - */ -export interface OHLCVWithMetadata extends OHLCV { - /** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */ - source: string; - /** Whether this is adjusted data */ - adjusted?: boolean; - /** Number of trades during the period */ - trades?: number; - /** Volume weighted average price */ - vwap?: number; -} - -/** - * Market data structure - */ -export interface MarketData { - /** Security symbol */ - symbol: string; - /** Current price */ - price: number; - /** Trading volume */ - volume: number; - /** Timestamp */ - timestamp: number; - /** Bid price */ - bid?: number; - /** Ask price */ - ask?: number; - /** Bid size */ - bidSize?: number; - /** Ask size */ - askSize?: number; - /** Previous close */ - previousClose?: number; - /** Day's high */ - high?: number; - /** Day's low */ - low?: number; - /** Day's open */ - open?: number; -} - -/** - * Market liquidity metrics - */ -export interface LiquidityMetrics { - /** Bid-ask spread */ - bidAskSpread: number; - /** Bid-ask spread percentage */ - bidAskSpreadPercent: number; - /** Market depth */ - marketDepth: number; - /** Average daily volume */ - averageDailyVolume: number; - /** Volume rate */ - volumeRate: number; - /** Price impact */ - priceImpact: number; - /** Liquidity score */ - liquidityScore: number; -} - -/** - * Market regime classification - */ -export interface MarketRegime { - /** Current regime */ - regime: 'trending' | 'ranging' | 'volatile' | 'quiet'; - /** Regime strength (0-1) */ - strength: number; - /** Regime duration (periods) */ - duration: number; - /** Trend direction (if trending) */ - trendDirection?: 'up' | 'down'; - /** Volatility level */ - volatilityLevel: 'low' | 'medium' | 'high'; -} diff --git a/libs/core/types/src/options.ts b/libs/core/types/src/options.ts deleted file mode 100644 index b56fb5d0..00000000 --- a/libs/core/types/src/options.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Options Pricing Types - * Types for options pricing and derivatives - */ - -/** - * Options pricing parameters - */ -export interface OptionParameters { - /** Underlying asset price */ - spotPrice: number; - /** Strike price */ - strikePrice: number; - /** Time to expiration (in years) */ - timeToExpiry: number; - /** Risk-free interest rate */ - riskFreeRate: number; - /** Volatility */ - volatility: number; - /** Dividend yield */ - dividendYield?: number; - /** Option type */ - optionType: 'call' | 'put'; -} - -/** - * Option pricing results - */ -export interface OptionPricing { - /** Call option price */ - callPrice: number; - /** Put option price */ - putPrice: number; - /** Call intrinsic value */ - callIntrinsic: number; - /** Put intrinsic value */ - putIntrinsic: number; - /** Call time value */ - callTimeValue: number; - /** Put time value */ - putTimeValue: number; -} - -/** - * Option Greeks calculation - */ -export interface GreeksCalculation { - /** Delta - price sensitivity */ - delta: number; - /** Gamma - delta sensitivity */ - gamma: number; - /** Theta - time decay */ - theta: number; - /** Vega - volatility sensitivity */ - vega: number; - /** Rho - interest rate sensitivity */ - rho: number; -} diff --git a/libs/core/types/src/portfolio.ts b/libs/core/types/src/portfolio.ts deleted file mode 100644 index bbf137b3..00000000 --- a/libs/core/types/src/portfolio.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Portfolio & Position Types - * Types for portfolio management and position tracking - */ - -/** - * Individual portfolio position - */ -export interface PortfolioPosition { - /** Security symbol/ticker */ - symbol: string; - /** Number of shares/units */ - shares: number; - /** Average entry price */ - averagePrice: number; - /** Current market price */ - currentPrice: number; - /** Current market value */ - marketValue: number; - /** Unrealized P&L */ - unrealizedPnL: number; - /** Unrealized P&L percentage */ - unrealizedPnLPercent: number; - /** Weight in portfolio */ - weight: number; - /** Security type (stock, bond, option, etc.) */ - securityType?: string; - /** Currency */ - currency?: string; -} - -/** - * Portfolio analysis metrics - */ -export interface PortfolioAnalysis { - /** Total portfolio value */ - totalValue: number; - /** Total cash balance */ - cash: number; - /** Total invested amount */ - invested: number; - /** Total unrealized P&L */ - unrealizedPnL: number; - /** Total unrealized P&L percentage */ - unrealizedPnLPercent: number; - /** Total return */ - totalReturn: number; - /** Total return percentage */ - totalReturnPercent: number; - /** Annualized return */ - annualizedReturn: number; - /** Portfolio volatility (annualized) */ - volatility: number; - /** Sharpe ratio */ - sharpeRatio: number; - /** Maximum drawdown */ - maxDrawdown: number; - /** Number of positions */ - positionCount: number; - /** Portfolio concentration (largest position weight) */ - concentration: number; -} - -/** - * Asset allocation breakdown - */ -export interface AssetAllocation { - /** Asset class or category */ - category: string; - /** Allocation value */ - value: number; - /** Allocation percentage */ - percentage: number; - /** Target allocation percentage */ - target?: number; - /** Deviation from target */ - deviation?: number; -} - -/** - * Position sizing parameters - */ -export interface PositionSizeParams { - /** Account size */ - accountSize: number; - /** Risk percentage per trade */ - riskPercent: number; - /** Entry price */ - entryPrice: number; - /** Stop loss price */ - stopPrice: number; - /** Commission per share */ - commission?: number; -} - -/** - * Kelly Criterion parameters - */ -export interface KellyParams { - /** Win rate (0-1) */ - winRate: number; - /** Average winning trade */ - averageWin: number; - /** Average losing trade */ - averageLoss: number; - /** Risk-free rate */ - riskFreeRate?: number; -} diff --git a/libs/core/types/src/risk-metrics.ts b/libs/core/types/src/risk-metrics.ts deleted file mode 100644 index 7d8ac7b4..00000000 --- a/libs/core/types/src/risk-metrics.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Risk & Performance Metrics Types - * Types for risk measurement and performance analysis - */ - -/** - * Comprehensive risk metrics - */ -export interface RiskMetrics { - /** Value at Risk 95% */ - var95: number; - /** Value at Risk 99% */ - var99: number; - /** Conditional VaR 95% */ - cvar95: number; - /** Maximum drawdown */ - maxDrawdown: number; - /** Volatility (annualized) */ - volatility: number; - /** Downside deviation */ - downside_deviation: number; - /** Calmar ratio */ - calmar_ratio: number; - /** Sortino ratio */ - sortino_ratio: number; - /** Beta (vs benchmark) */ - beta: number; - /** Alpha (vs benchmark) */ - alpha: number; - /** Sharpe ratio */ - sharpeRatio: number; - /** Treynor ratio */ - treynorRatio: number; - /** Tracking error */ - trackingError: number; - /** Information ratio */ - informationRatio: number; -} - -/** - * Drawdown analysis - */ -export interface DrawdownAnalysis { - /** Maximum drawdown percentage */ - maxDrawdown: number; - /** Maximum drawdown duration (days) */ - maxDrawdownDuration: number; - /** Current drawdown percentage */ - currentDrawdown: number; - /** Current drawdown duration (days) */ - currentDrawdownDuration: number; - /** Average drawdown percentage */ - averageDrawdown: number; - /** Average drawdown duration (days) */ - averageDrawdownDuration: number; - /** Number of drawdown periods */ - drawdownPeriods: number; - /** Recovery factor */ - recoveryFactor: number; -} - -/** - * Return analysis statistics - */ -export interface ReturnAnalysis { - /** Total return */ - totalReturn: number; - /** Annualized return */ - annualizedReturn: number; - /** Volatility (annualized) */ - volatility: number; - /** Skewness */ - skewness: number; - /** Kurtosis */ - kurtosis: number; - /** Best period return */ - bestPeriod: number; - /** Worst period return */ - worstPeriod: number; - /** Positive periods percentage */ - positivePeriods: number; - /** Average positive return */ - averagePositiveReturn: number; - /** Average negative return */ - averageNegativeReturn: number; -} diff --git a/libs/core/types/src/technical-analysis.ts b/libs/core/types/src/technical-analysis.ts deleted file mode 100644 index cd866387..00000000 --- a/libs/core/types/src/technical-analysis.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Technical Analysis Types - * Types for technical indicators and market analysis - */ - -/** - * Technical indicators collection - */ -export interface TechnicalIndicators { - /** Simple Moving Average */ - sma: number[]; - /** Exponential Moving Average */ - ema: number[]; - /** Relative Strength Index */ - rsi: number[]; - /** MACD indicator */ - macd: { - macd: number[]; - signal: number[]; - histogram: number[]; - }; - /** Bollinger Bands */ - bollinger: { - upper: number[]; - middle: number[]; - lower: number[]; - }; - /** Average True Range */ - atr: number[]; - /** Stochastic Oscillator */ - stochastic: { - k: number[]; - d: number[]; - }; - /** Williams %R */ - williams_r: number[]; - /** Commodity Channel Index */ - cci: number[]; - /** Momentum */ - momentum: number[]; - /** Rate of Change */ - roc: number[]; -} - -/** - * Correlation analysis result - */ -export interface CorrelationResult { - /** Correlation coefficient */ - correlation: number; - /** P-value for statistical significance */ - pValue: number; - /** Is statistically significant */ - isSignificant: boolean; - /** Confidence interval */ - confidenceInterval: [number, number]; - /** Sample size */ - sampleSize: number; -} - -/** - * Correlation matrix - */ -export interface CorrelationMatrix { - /** Asset symbols */ - symbols: string[]; - /** Correlation matrix values */ - matrix: number[][]; - /** Eigenvalues */ - eigenvalues: number[]; - /** Condition number */ - conditionNumber: number; - /** Is positive definite */ - isPositiveDefinite: boolean; -} - -/** - * Volatility estimates using different models - */ -export interface VolatilityEstimates { - /** Close-to-close volatility */ - closeToClose: number; - /** Parkinson volatility */ - parkinson: number; - /** Garman-Klass volatility */ - garmanKlass: number; - /** Rogers-Satchell volatility */ - rogersSatchell: number; - /** Yang-Zhang volatility */ - yangZhang: number; -} - -/** - * GARCH model parameters - */ -export interface GARCHParameters { - /** Alpha parameter */ - alpha: number; - /** Beta parameter */ - beta: number; - /** Omega parameter */ - omega: number; - /** Log likelihood */ - logLikelihood: number; - /** AIC (Akaike Information Criterion) */ - aic: number; - /** BIC (Bayesian Information Criterion) */ - bic: number; -} diff --git a/libs/core/types/src/trading.ts b/libs/core/types/src/trading.ts deleted file mode 100644 index 4c8cf6f9..00000000 --- a/libs/core/types/src/trading.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Trading & Execution Types - * Types for trade execution and performance analysis - */ - -/** - * Trade execution record - */ -export interface TradeExecution { - /** Trade ID */ - id?: string; - /** Security symbol */ - symbol: string; - /** Trade type */ - type: 'buy' | 'sell' | 'short' | 'cover'; - /** Number of shares/units */ - quantity: number; - /** Execution price */ - price: number; - /** Total trade value */ - value: number; - /** Commission/fees */ - commission?: number; - /** Execution timestamp */ - timestamp: number; - /** Order ID reference */ - orderId?: string; - /** Execution venue */ - venue?: string; -} - -/** - * Trade performance analysis - */ -export interface TradePerformance { - /** Total number of trades */ - totalTrades: number; - /** Number of winning trades */ - winningTrades: number; - /** Number of losing trades */ - losingTrades: number; - /** Win rate percentage */ - winRate: number; - /** Average winning trade */ - averageWin: number; - /** Average losing trade */ - averageLoss: number; - /** Largest winning trade */ - largestWin: number; - /** Largest losing trade */ - largestLoss: number; - /** Profit factor (gross profit / gross loss) */ - profitFactor: number; - /** Mathematical expectancy */ - expectancy: number; - /** Total gross profit */ - grossProfit: number; - /** Total gross loss */ - grossLoss: number; - /** Net profit */ - netProfit: number; -} diff --git a/libs/data/mongodb/package.json b/libs/data/mongodb/package.json index c39d9f4a..7b966739 100644 --- a/libs/data/mongodb/package.json +++ b/libs/data/mongodb/package.json @@ -14,8 +14,6 @@ }, "dependencies": { "@stock-bot/logger": "*", - "@stock-bot/types": "*", - "@types/mongodb": "^4.0.7", "mongodb": "^6.17.0" }, "devDependencies": { diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index b624ce3b..2df9c41d 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -18,17 +18,37 @@ import type { Logger } from '@stock-bot/logger'; import type { ConnectionEvents, DocumentBase, - DynamicPoolConfig, MongoDBClientConfig, PoolMetrics, } from './types'; -/** - * MongoDB Client for Stock Bot Data Service - * - * MongoDB client focused on batch upsert operations - * with minimal configuration and no health monitoring complexity. - */ +const READ_ONLY_COLLECTION_METHODS = new Set([ + 'find', + 'findOne', + 'countDocuments', + 'estimatedDocumentCount', + 'distinct', + 'listIndexes', + 'indexExists', + 'indexes', + 'options', +]); + +const READ_ONLY_COLLECTION_PROPS = new Set([ + 'collectionName', + 'dbName', + 'namespace', + 'then', +]); + +const READ_ONLY_DB_METHODS = new Set(['listCollections', 'stats']); +const READ_ONLY_DB_PROPS = new Set([ + 'databaseName', + 'namespace', + 'options', + 'then', +]); + export class MongoDBClient { private client: MongoClient | null = null; private db: Db | null = null; @@ -38,8 +58,6 @@ export class MongoDBClient { private isConnected = false; private readonly metrics: PoolMetrics; private readonly events?: ConnectionEvents; - private dynamicPoolConfig?: DynamicPoolConfig; - private poolMonitorInterval?: Timer; constructor(mongoConfig: MongoDBClientConfig, logger: Logger, events?: ConnectionEvents) { this.config = mongoConfig; @@ -56,9 +74,6 @@ export class MongoDBClient { }; } - /** - * Connect to MongoDB with simple configuration - */ async connect(retryAttempts: number = 3, retryDelay: number = 1000): Promise { if (this.isConnected && this.client) { return; @@ -74,6 +89,7 @@ export class MongoDBClient { this.client = new MongoClient(uri, { maxPoolSize: this.config.poolSettings?.maxPoolSize || 10, minPoolSize: this.config.poolSettings?.minPoolSize || 1, + maxIdleTimeMS: this.config.poolSettings?.maxIdleTime, connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000, socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000, serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000, @@ -82,20 +98,15 @@ export class MongoDBClient { await this.client.connect(); await this.client.db(this.defaultDatabase).command({ ping: 1 }); - // Set default database from config this.db = this.client.db(this.defaultDatabase); this.isConnected = true; - // Update metrics this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10; this.metrics.idleConnections = this.metrics.totalConnections; - // Fire connection event if (this.events?.onConnect) { await Promise.resolve(this.events.onConnect()); } - - // Fire pool created event if (this.events?.onPoolCreated) { await Promise.resolve(this.events.onPoolCreated()); } @@ -103,20 +114,14 @@ export class MongoDBClient { this.logger.info('Successfully connected to MongoDB', { database: this.defaultDatabase, poolSize: this.metrics.totalConnections, + readOnly: Boolean(this.config.readOnly), }); - - // Start pool monitoring if dynamic sizing is enabled - if (this.dynamicPoolConfig?.enabled) { - this.startPoolMonitoring(); - } - return; } catch (error) { lastError = error as Error; this.metrics.errors++; this.metrics.lastError = lastError.message; - // Fire error event if (this.events?.onError) { await Promise.resolve(this.events.onError(lastError)); } @@ -124,7 +129,7 @@ export class MongoDBClient { this.logger.error(`MongoDB connection attempt ${attempt} failed:`, error); if (this.client) { - await this.client.close(); + await this.client.close().catch(() => {}); this.client = null; } @@ -139,27 +144,17 @@ export class MongoDBClient { ); } - /** - * Disconnect from MongoDB - */ async disconnect(): Promise { if (!this.client) { return; } try { - // Stop pool monitoring - if (this.poolMonitorInterval) { - clearInterval(this.poolMonitorInterval); - this.poolMonitorInterval = undefined; - } - await this.client.close(); this.isConnected = false; this.client = null; this.db = null; - // Fire disconnect event if (this.events?.onDisconnect) { await Promise.resolve(this.events.onDisconnect()); } @@ -171,9 +166,6 @@ export class MongoDBClient { } } - /** - * Set the default database for operations - */ setDefaultDatabase(databaseName: string): void { this.defaultDatabase = databaseName; if (this.client) { @@ -182,28 +174,90 @@ export class MongoDBClient { } } - /** - * Get the current default database name - */ getDefaultDatabase(): string { return this.defaultDatabase; } - /** - * Get a database instance by name - */ - getDatabase(databaseName?: string): Db { + private getRawDatabase(databaseName?: string): Db { if (!this.client) { throw new Error('MongoDB client not connected'); } - - const dbName = databaseName || this.defaultDatabase; - return this.client.db(dbName); + return this.client.db(databaseName || this.defaultDatabase); + } + + private wrapReadOnlyCollection(collection: Collection): Collection { + return new Proxy(collection, { + get: (target, prop, receiver) => { + if (typeof prop === 'symbol' || READ_ONLY_COLLECTION_PROPS.has(prop)) { + return Reflect.get(target, prop, receiver); + } + if (prop === 'aggregate') { + return (pipeline: Document[] = [], options?: AggregateOptions) => { + this.assertReadOnlyPipeline(pipeline); + return target.aggregate(pipeline, options); + }; + } + if (READ_ONLY_COLLECTION_METHODS.has(prop)) { + const fn = Reflect.get(target, prop, target); + return typeof fn === 'function' ? fn.bind(target) : fn; + } + return () => { + throw new Error( + `MongoDB client is configured in read-only mode; collection operation "${String(prop)}" is forbidden` + ); + }; + }, + }); + } + + private wrapReadOnlyDatabase(db: Db): Db { + return new Proxy(db, { + get: (target, prop, receiver) => { + if (typeof prop === 'symbol' || READ_ONLY_DB_PROPS.has(prop)) { + return Reflect.get(target, prop, receiver); + } + if (prop === 'collection') { + return (name: string) => + this.wrapReadOnlyCollection(target.collection(name)); + } + if (READ_ONLY_DB_METHODS.has(prop)) { + const fn = Reflect.get(target, prop, target); + return typeof fn === 'function' ? fn.bind(target) : fn; + } + return () => { + throw new Error( + `MongoDB client is configured in read-only mode; database operation "${String(prop)}" is forbidden` + ); + }; + }, + }); + } + + getDatabase(databaseName?: string): Db { + const raw = this.getRawDatabase(databaseName); + return this.config.readOnly ? this.wrapReadOnlyDatabase(raw) : raw; + } + + getDb(dbName?: string): Db { + return this.getDatabase(dbName); + } + + get database(): Db | null { + if (!this.db) { + return null; + } + return this.config.readOnly ? this.wrapReadOnlyDatabase(this.db) : this.db; + } + + getCollection(name: string, database?: string): Collection { + const raw = this.getRawDatabase(database).collection(name); + return this.config.readOnly ? this.wrapReadOnlyCollection(raw) : raw; + } + + collection(name: string, database?: string): Collection { + return this.getCollection(name, database); } - /** - * Check whether this client is locked to read-only mode - */ isReadOnly(): boolean { return this.config.readOnly === true; } @@ -221,7 +275,9 @@ export class MongoDBClient { return; } const checkStage = (value: unknown): void => { - if (!value || typeof value !== 'object') return; + if (!value || typeof value !== 'object') { + return; + } for (const [key, child] of Object.entries(value)) { if (key === '$out' || key === '$merge') { throw new Error( @@ -236,10 +292,6 @@ export class MongoDBClient { } } - /** - * Batch upsert documents for high-performance operations - * Supports single or multiple unique keys for matching - */ async batchUpsert( collectionName: string, documents: Array< @@ -248,7 +300,7 @@ export class MongoDBClient { uniqueKeys: string | string[], options: { chunkSize?: number; - database?: string; // Optional database override + database?: string; } = {} ): Promise<{ insertedCount: number; updatedCount: number; errors: unknown[] }> { this.assertWritable(`batchUpsert(${collectionName})`); @@ -260,42 +312,24 @@ export class MongoDBClient { return { insertedCount: 0, updatedCount: 0, errors: [] }; } - // Normalize uniqueKeys to array const keyFields = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys]; - if (keyFields.length === 0) { throw new Error('At least one unique key must be provided'); } const { chunkSize = 10000, database } = options; - const db = this.getDatabase(database); - const collection = db.collection(collectionName); + const collection = this.getRawDatabase(database).collection(collectionName); const operationId = Math.random().toString(36).substring(7); const dbName = database || this.defaultDatabase; let totalInserted = 0; let totalUpdated = 0; - const errors: unknown[] = []; - this.logger.debug( - `Starting batch upsert operation [${collectionName}-${documents.length}][${operationId}]`, - { - database: dbName, - collection: collectionName, - totalDocuments: documents.length, - uniqueKeys: keyFields, - chunkSize, - } - ); - - // Process documents in chunks to avoid memory issues for (let i = 0; i < documents.length; i += chunkSize) { const chunk = documents.slice(i, i + chunkSize); try { const startTime = Date.now(); - - // Prepare bulk operations const bulkOps = chunk.map(doc => { const now = new Date(); const docWithTimestamps = { @@ -304,17 +338,15 @@ export class MongoDBClient { updated_at: now, }; - // Create filter using multiple unique keys const filter: Record = {}; - keyFields.forEach(key => { + for (const key of keyFields) { const value = (doc as Record)[key]; if (value === undefined || value === null) { throw new Error(`Document missing required unique key: ${key}`); } filter[key] = value; - }); + } - // Remove created_at from $set to avoid conflict with $setOnInsert const { created_at, ...updateFields } = docWithTimestamps; return { @@ -329,22 +361,16 @@ export class MongoDBClient { }; }); - // Execute bulk operation with type assertion to handle complex MongoDB types const result = await collection.bulkWrite(bulkOps as never, { ordered: false }); - - const executionTime = Date.now() - startTime; - const inserted = result.upsertedCount; - const updated = result.modifiedCount; - - totalInserted += inserted; - totalUpdated += updated; + totalInserted += result.upsertedCount; + totalUpdated += result.modifiedCount; this.logger.debug(`Batch upsert chunk processed [${operationId}]`, { chunkNumber: Math.floor(i / chunkSize) + 1, chunkSize: chunk.length, - inserted, - updated, - executionTime, + inserted: result.upsertedCount, + updated: result.modifiedCount, + executionTime: Date.now() - startTime, database: dbName, collection: collectionName, }); @@ -358,45 +384,13 @@ export class MongoDBClient { chunkSize: chunk.length, uniqueKeys: keyFields, }); - errors.push(error); + throw error; } } - this.logger.debug( - `Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`, - { - database: dbName, - collection: collectionName, - totalRecords: documents.length, - inserted: totalInserted, - updated: totalUpdated, - errors: errors.length, - uniqueKeys: keyFields, - } - ); - - return { insertedCount: totalInserted, updatedCount: totalUpdated, errors }; + return { insertedCount: totalInserted, updatedCount: totalUpdated, errors: [] }; } - /** - * Get a typed collection - */ - getCollection(name: string, database?: string): Collection { - const db = this.getDatabase(database); - return db.collection(name); - } - - /** - * Get a collection (interface compatibility method) - * This method provides compatibility with the IMongoDBClient interface - */ - collection(name: string, database?: string): Collection { - return this.getCollection(name, database); - } - - /** - * Simple insert operation - */ async insertOne( collectionName: string, document: Omit & @@ -404,7 +398,7 @@ export class MongoDBClient { database?: string ): Promise { this.assertWritable(`insertOne(${collectionName})`); - const collection = this.getCollection(collectionName, database); + const collection = this.getRawDatabase(database).collection(collectionName); const now = new Date(); const docWithTimestamps = { @@ -417,9 +411,6 @@ export class MongoDBClient { return { ...docWithTimestamps, _id: result.insertedId } as T; } - /** - * Insert multiple documents - */ async insertMany( collectionName: string, documents: T[], @@ -427,7 +418,7 @@ export class MongoDBClient { dbName?: string ) { this.assertWritable(`insertMany(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); const now = new Date(); const docsWithTimestamps = documents.map(doc => ({ @@ -446,9 +437,6 @@ export class MongoDBClient { }; } - /** - * Find multiple documents - */ async find( collectionName: string, filter: Filter = {}, @@ -460,9 +448,6 @@ export class MongoDBClient { return (await cursor.toArray()) as T[]; } - /** - * Find a single document - */ async findOne( collectionName: string, filter: Filter, @@ -474,9 +459,21 @@ export class MongoDBClient { return result as T | null; } - /** - * Update a single document - */ + private withUpdatedTimestamp(update: Document): Document { + const now = new Date(); + const hasOperator = Object.keys(update).some(key => key.startsWith('$')); + if (!hasOperator) { + return { $set: { ...update, updated_at: now } }; + } + return { + ...update, + $set: { + ...(update.$set && typeof update.$set === 'object' ? update.$set : {}), + updated_at: now, + }, + }; + } + async updateOne( collectionName: string, filter: Filter, @@ -485,16 +482,8 @@ export class MongoDBClient { dbName?: string ) { this.assertWritable(`updateOne(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); - - // Add updated_at timestamp - if (update.$set) { - update.$set.updated_at = new Date(); - } else if (!update.$setOnInsert && !update.$unset && !update.$inc) { - update = { $set: { ...update, updated_at: new Date() } }; - } - - const result = await collection.updateOne(filter, update, options); + const collection = this.getRawDatabase(dbName).collection(collectionName); + const result = await collection.updateOne(filter, this.withUpdatedTimestamp(update), options); return { matchedCount: result.matchedCount, modifiedCount: result.modifiedCount, @@ -503,9 +492,6 @@ export class MongoDBClient { }; } - /** - * Update multiple documents - */ async updateMany( collectionName: string, filter: Filter, @@ -514,16 +500,8 @@ export class MongoDBClient { dbName?: string ) { this.assertWritable(`updateMany(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); - - // Add updated_at timestamp - if (update.$set) { - update.$set.updated_at = new Date(); - } else if (!update.$setOnInsert && !update.$unset && !update.$inc) { - update = { $set: { ...update, updated_at: new Date() } }; - } - - const result = await collection.updateMany(filter, update, options); + const collection = this.getRawDatabase(dbName).collection(collectionName); + const result = await collection.updateMany(filter, this.withUpdatedTimestamp(update), options); return { matchedCount: result.matchedCount, modifiedCount: result.modifiedCount, @@ -532,9 +510,6 @@ export class MongoDBClient { }; } - /** - * Delete a single document - */ async deleteOne( collectionName: string, filter: Filter, @@ -542,16 +517,11 @@ export class MongoDBClient { dbName?: string ) { this.assertWritable(`deleteOne(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); const result = await collection.deleteOne(filter, options); - return { - deletedCount: result.deletedCount, - }; + return { deletedCount: result.deletedCount }; } - /** - * Delete multiple documents - */ async deleteMany( collectionName: string, filter: Filter, @@ -559,16 +529,11 @@ export class MongoDBClient { dbName?: string ) { this.assertWritable(`deleteMany(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); const result = await collection.deleteMany(filter, options); - return { - deletedCount: result.deletedCount, - }; + return { deletedCount: result.deletedCount }; } - /** - * Count documents matching a filter - */ async countDocuments( collectionName: string, filter: Filter = {}, @@ -579,9 +544,6 @@ export class MongoDBClient { return await collection.countDocuments(filter, options); } - /** - * Perform aggregation operations - */ async aggregate( collectionName: string, pipeline: Document[], @@ -589,14 +551,11 @@ export class MongoDBClient { dbName?: string ): Promise { this.assertReadOnlyPipeline(pipeline); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); const cursor = collection.aggregate(pipeline, options); return (await cursor.toArray()) as T[]; } - /** - * Create an index - */ async createIndex( collectionName: string, indexSpec: IndexSpecification, @@ -604,13 +563,10 @@ export class MongoDBClient { dbName?: string ): Promise { this.assertWritable(`createIndex(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); return await collection.createIndex(indexSpec, options); } - /** - * Drop an index - */ async dropIndex( collectionName: string, indexName: string, @@ -618,118 +574,44 @@ export class MongoDBClient { dbName?: string ): Promise { this.assertWritable(`dropIndex(${collectionName})`); - const collection = this.getCollection(collectionName, dbName); + const collection = this.getRawDatabase(dbName).collection(collectionName); await collection.dropIndex(indexName, options); } - /** - * List all indexes on a collection - */ async listIndexes(collectionName: string, dbName?: string): Promise { const collection = this.getCollection(collectionName, dbName); const cursor = collection.listIndexes(); return await cursor.toArray(); } - /** - * Get a database instance (interface compatibility) - */ - getDb(dbName?: string): Db { - return this.getDatabase(dbName); - } - - /** - * Create a new collection - */ async createCollection( collectionName: string, options?: CreateCollectionOptions, dbName?: string ): Promise { this.assertWritable(`createCollection(${collectionName})`); - const db = this.getDatabase(dbName); + const db = this.getRawDatabase(dbName); await db.createCollection(collectionName, options); } - /** - * Drop a collection - */ async dropCollection(collectionName: string, dbName?: string): Promise { this.assertWritable(`dropCollection(${collectionName})`); - const db = this.getDatabase(dbName); + const db = this.getRawDatabase(dbName); await db.dropCollection(collectionName); } - /** - * List all collections in a database - */ async listCollections(filter: Filter = {}, dbName?: string): Promise { const db = this.getDatabase(dbName); - const collections = await db.listCollections(filter).toArray(); - return collections; + return await db.listCollections(filter).toArray(); } - /** - * Check if client is connected - */ get connected(): boolean { return this.isConnected && !!this.client; } - /** - * Get the default database instance - */ - get database(): Db | null { - return this.db; - } - - /** - * Convenience methods for common databases - */ - - // Stock database operations - async batchUpsertStock( - collectionName: string, - documents: Array< - Omit & Partial> - >, - uniqueKeys: string | string[], - options: { chunkSize?: number } = {} - ) { - return this.batchUpsert(collectionName, documents, uniqueKeys, { - ...options, - database: 'stock', - }); - } - - // Trading documents database operations - async batchUpsertTrading( - collectionName: string, - documents: Array< - Omit & Partial> - >, - uniqueKeys: string | string[], - options: { chunkSize?: number } = {} - ) { - return this.batchUpsert(collectionName, documents, uniqueKeys, { - ...options, - database: 'trading_documents', - }); - } - - // Analytics database operations - async batchUpsertAnalytics( - collectionName: string, - documents: Array< - Omit & Partial> - >, - uniqueKeys: string | string[], - options: { chunkSize?: number } = {} - ) { - return this.batchUpsert(collectionName, documents, uniqueKeys, { - ...options, - database: 'analytics', - }); + getPoolMetrics(): PoolMetrics { + this.metrics.lastUsed = new Date(); + return { ...this.metrics }; } private buildConnectionUri(): string { @@ -738,136 +620,12 @@ export class MongoDBClient { } const { host, port, username, password, database, authSource } = this.config; - - // Build URI components - const auth = username && password ? `${username}:${password}@` : ''; - const authParam = authSource && username ? `?authSource=${authSource}` : ''; + const auth = + username && password !== undefined + ? `${encodeURIComponent(username)}:${encodeURIComponent(password)}@` + : ''; + const authParam = authSource && username ? `?authSource=${encodeURIComponent(authSource)}` : ''; return `mongodb://${auth}${host}:${port}/${database}${authParam}`; } - - /** - * Get current pool metrics - */ - getPoolMetrics(): PoolMetrics { - // Update last used timestamp - this.metrics.lastUsed = new Date(); - - // Note: MongoDB driver doesn't expose detailed pool metrics - // These are estimates based on configuration - return { ...this.metrics }; - } - - /** - * Set dynamic pool configuration - */ - setDynamicPoolConfig(config: DynamicPoolConfig): void { - this.dynamicPoolConfig = config; - - if (config.enabled && this.isConnected && !this.poolMonitorInterval) { - this.startPoolMonitoring(); - } else if (!config.enabled && this.poolMonitorInterval) { - clearInterval(this.poolMonitorInterval); - this.poolMonitorInterval = undefined; - } - } - - /** - * Start monitoring pool and adjust size dynamically - */ - private startPoolMonitoring(): void { - if (!this.dynamicPoolConfig || this.poolMonitorInterval) { - return; - } - - this.poolMonitorInterval = setInterval(() => { - this.evaluatePoolSize(); - }, this.dynamicPoolConfig.evaluationInterval); - } - - /** - * Evaluate and adjust pool size based on usage - */ - private async evaluatePoolSize(): Promise { - if (!this.dynamicPoolConfig || !this.client) { - return; - } - - const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig; - const currentSize = this.metrics.totalConnections; - const utilization = (this.metrics.activeConnections / currentSize) * 100; - - this.logger.debug('Pool utilization', { - utilization: `${utilization.toFixed(1)}%`, - active: this.metrics.activeConnections, - total: currentSize, - }); - - // Scale up if utilization is high - if (utilization > scaleUpThreshold && currentSize < maxSize) { - const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize); - await this.resizePool(newSize); - this.logger.info('Scaling up connection pool', { - from: currentSize, - to: newSize, - utilization, - }); - } - // Scale down if utilization is low - else if (utilization < scaleDownThreshold && currentSize > minSize) { - const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize); - await this.resizePool(newSize); - this.logger.info('Scaling down connection pool', { - from: currentSize, - to: newSize, - utilization, - }); - } - } - - /** - * Resize the connection pool - * Note: MongoDB driver doesn't support dynamic resizing, this would require reconnection - */ - private async resizePool(newSize: number): Promise { - // MongoDB doesn't support dynamic pool resizing - // This is a placeholder for future implementation - this.logger.warn('Dynamic pool resizing not yet implemented for MongoDB', { - requestedSize: newSize, - }); - - // Update metrics to reflect desired state - this.metrics.totalConnections = newSize; - } - - /** - * Enable pool warmup on connect - */ - async warmupPool(): Promise { - if (!this.client || !this.isConnected) { - throw new Error('Client not connected'); - } - - const minSize = this.config.poolSettings?.minPoolSize || 1; - const promises: Promise[] = []; - - // Create minimum connections by running parallel pings - for (let i = 0; i < minSize; i++) { - promises.push( - this.client - .db(this.defaultDatabase) - .admin() - .ping() - .then(() => { - this.logger.debug(`Warmed up connection ${i + 1}/${minSize}`); - }) - .catch(error => { - this.logger.warn(`Failed to warm up connection ${i + 1}`, { error }); - }) - ); - } - - await Promise.allSettled(promises); - this.logger.info('Connection pool warmup complete', { connections: minSize }); - } } diff --git a/libs/data/mongodb/src/index.ts b/libs/data/mongodb/src/index.ts index 5e93d612..7a12daa0 100644 --- a/libs/data/mongodb/src/index.ts +++ b/libs/data/mongodb/src/index.ts @@ -1,29 +1,10 @@ -/** - * MongoDB Client Library for Stock Bot Data Service - * - * Provides a MongoDB client focused on batch upsert operations - * for high-performance data ingestion. - */ - export { MongoDBClient } from './client'; - -// Types export type { - AnalystReport, ConnectionEvents, DocumentBase, - DynamicPoolConfig, - EarningsTranscript, ExchangeSourceMapping, MasterExchange, MongoDBClientConfig, MongoDBConnectionOptions, - NewsArticle, PoolMetrics, - RawDocument, - SecFiling, - SentimentData, } from './types'; - -// Note: Factory functions removed - use Awilix DI container instead -// See: libs/core/di/src/awilix-container.ts diff --git a/libs/data/mongodb/src/types.ts b/libs/data/mongodb/src/types.ts index 58e089e8..60dfe8c4 100644 --- a/libs/data/mongodb/src/types.ts +++ b/libs/data/mongodb/src/types.ts @@ -1,8 +1,5 @@ import type { ObjectId } from 'mongodb'; -/** - * MongoDB Client Configuration - */ export interface MongoDBClientConfig { host: string; port: number; @@ -35,9 +32,6 @@ export interface MongoDBClientConfig { }; } -/** - * MongoDB Connection Options - */ export interface MongoDBConnectionOptions { retryAttempts?: number; retryDelay?: number; @@ -63,20 +57,6 @@ export interface ConnectionEvents { onPoolCreated?: () => void | Promise; } -export interface DynamicPoolConfig { - enabled: boolean; - minSize: number; - maxSize: number; - scaleUpThreshold: number; // % of pool in use (0-100) - scaleDownThreshold: number; // % of pool idle (0-100) - scaleUpIncrement: number; // connections to add - scaleDownIncrement: number; // connections to remove - evaluationInterval: number; // ms between checks -} - -/** - * Base Document Interface - */ export interface DocumentBase { _id?: ObjectId; created_at: Date; @@ -85,129 +65,6 @@ export interface DocumentBase { metadata?: Record; } -/** - * Sentiment Data Document - */ -export interface SentimentData extends DocumentBase { - symbol: string; - sentiment_score: number; - sentiment_label: 'positive' | 'negative' | 'neutral'; - confidence: number; - text: string; - source_type: 'reddit' | 'twitter' | 'news' | 'forums'; - source_id: string; - timestamp: Date; - processed_at: Date; - language: string; - keywords: string[]; - entities: Array<{ - name: string; - type: string; - confidence: number; - }>; -} - -/** - * Raw Document - */ -export interface RawDocument extends DocumentBase { - document_type: 'html' | 'pdf' | 'text' | 'json' | 'xml'; - content: string; - content_hash: string; - url?: string; - title?: string; - author?: string; - published_date?: Date; - extracted_text?: string; - processing_status: 'pending' | 'processed' | 'failed'; - size_bytes: number; - language?: string; -} - -/** - * News Article - */ -export interface NewsArticle extends DocumentBase { - headline: string; - content: string; - summary?: string; - author: string; - publication: string; - published_date: Date; - url: string; - symbols: string[]; - categories: string[]; - sentiment_score?: number; - relevance_score?: number; - image_url?: string; - tags: string[]; -} - -/** - * SEC Filing - */ -export interface SecFiling extends DocumentBase { - cik: string; - accession_number: string; - filing_type: string; - company_name: string; - symbols: string[]; - filing_date: Date; - period_end_date: Date; - url: string; - content: string; - extracted_data?: Record; - financial_statements?: Array<{ - statement_type: string; - data: Record; - }>; - processing_status: 'pending' | 'processed' | 'failed'; -} - -/** - * Earnings Transcript - */ -export interface EarningsTranscript extends DocumentBase { - symbol: string; - company_name: string; - quarter: string; - year: number; - call_date: Date; - transcript: string; - participants: Array<{ - name: string; - title: string; - type: 'executive' | 'analyst'; - }>; - key_topics: string[]; - sentiment_analysis?: { - overall_sentiment: number; - topic_sentiments: Record; - }; - financial_highlights?: Record; -} - -/** - * Analyst Report - */ -export interface AnalystReport extends DocumentBase { - symbol: string; - analyst_firm: string; - analyst_name: string; - report_title: string; - report_date: Date; - rating: 'buy' | 'hold' | 'sell' | 'strong_buy' | 'strong_sell'; - price_target?: number; - previous_rating?: string; - content: string; - summary: string; - key_points: string[]; - financial_projections?: Record; -} - -/** - * Exchange-related types - */ export interface ExchangeSourceMapping { id: string; name: string; @@ -224,13 +81,11 @@ export interface MasterExchange extends DocumentBase { currency: string; timezone: string; active?: boolean; - tradingHours?: { open: string; close: string; timezone: string; }; - sourceMappings: Record; confidence: number; verified: boolean; diff --git a/libs/data/mongodb/test/mongodb.test.ts b/libs/data/mongodb/test/mongodb.test.ts deleted file mode 100644 index 341da5b2..00000000 --- a/libs/data/mongodb/test/mongodb.test.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { beforeEach, describe, expect, it } from 'bun:test'; -import { SimpleMongoDBClient } from './support/simple-mongodb'; - -describe('MongoDBClient', () => { - let client: SimpleMongoDBClient; - const config = { - uri: 'mongodb://localhost:27017', - database: 'test-db', - }; - - beforeEach(() => { - client = new SimpleMongoDBClient(config); - }); - - describe('connection', () => { - it('should connect on first operation', async () => { - const results = await client.find('test-collection', {}); - - expect(results).toBeDefined(); - expect(results).toEqual([]); - }); - - it('should handle health check', async () => { - // Connect first by doing an operation - await client.find('test', {}); - - const health = await client.healthCheck(); - - expect(health.status).toBe('healthy'); - expect(health.isConnected).toBe(true); - }); - - it('should disconnect properly', async () => { - await client.find('test', {}); - await client.disconnect(); - - const health = await client.healthCheck(); - expect(health.isConnected).toBe(false); - }); - }); - - describe('CRUD operations', () => { - it('should find documents', async () => { - await client.insert('users', { id: 1, active: true }); - await client.insert('users', { id: 2, active: true }); - await client.insert('users', { id: 3, active: false }); - - const results = await client.find('users', { active: true }); - - expect(results).toHaveLength(2); - expect(results[0].active).toBe(true); - expect(results[1].active).toBe(true); - }); - - it('should find one document', async () => { - await client.insert('users', { id: 1, name: 'Test' }); - await client.insert('users', { id: 2, name: 'Other' }); - - const result = await client.findOne('users', { id: 1 }); - - expect(result).toBeDefined(); - expect(result.id).toBe(1); - expect(result.name).toBe('Test'); - }); - - it('should insert documents', async () => { - const doc = { name: 'Test User', email: 'test@example.com' }; - - await client.insert('users', doc); - - const result = await client.findOne('users', { email: 'test@example.com' }); - expect(result).toBeDefined(); - expect(result.name).toBe('Test User'); - }); - - it('should insert many documents', async () => { - const docs = [{ name: 'User 1' }, { name: 'User 2' }]; - - await client.insertMany('users', docs); - - const all = await client.find('users', {}); - expect(all).toHaveLength(2); - }); - - it('should update documents', async () => { - await client.insert('users', { id: 1, active: true }); - - const updated = await client.update('users', { id: 1 }, { $set: { active: false } }); - - expect(updated).toBe(1); - const result = await client.findOne('users', { id: 1 }); - expect(result.active).toBe(false); - }); - - it('should update many documents', async () => { - await client.insert('users', { id: 1, active: true }); - await client.insert('users', { id: 2, active: true }); - await client.insert('users', { id: 3, active: false }); - - const updated = await client.updateMany( - 'users', - { active: true }, - { $set: { status: 'active' } } - ); - - expect(updated).toBe(2); - const activeUsers = await client.find('users', { status: 'active' }); - expect(activeUsers).toHaveLength(2); - }); - - it('should delete documents', async () => { - await client.insert('users', { id: 1 }); - await client.insert('users', { id: 2 }); - - const deleted = await client.delete('users', { id: 1 }); - - expect(deleted).toBe(1); - const remaining = await client.find('users', {}); - expect(remaining).toHaveLength(1); - expect(remaining[0].id).toBe(2); - }); - - it('should delete many documents', async () => { - await client.insert('users', { id: 1, active: true }); - await client.insert('users', { id: 2, active: false }); - await client.insert('users', { id: 3, active: false }); - - const deleted = await client.deleteMany('users', { active: false }); - - expect(deleted).toBe(2); - const remaining = await client.find('users', {}); - expect(remaining).toHaveLength(1); - expect(remaining[0].active).toBe(true); - }); - }); - - describe('batch operations', () => { - it('should perform batch upsert', async () => { - const docs = [ - { id: 1, name: 'User 1' }, - { id: 2, name: 'User 2' }, - ]; - - await client.batchUpsert('users', docs, ['id']); - - const all = await client.find('users', {}); - expect(all).toHaveLength(2); - - // Update existing - await client.batchUpsert('users', [{ id: 1, name: 'Updated User 1' }], ['id']); - - const updated = await client.findOne('users', { id: 1 }); - expect(updated.name).toBe('Updated User 1'); - }); - - it('should handle empty batch', async () => { - await client.batchUpsert('users', [], ['id']); - - const all = await client.find('users', {}); - expect(all).toHaveLength(0); - }); - }); - - describe('utility methods', () => { - it('should count documents', async () => { - await client.insert('users', { active: true }); - await client.insert('users', { active: true }); - await client.insert('users', { active: false }); - - const count = await client.count('users', { active: true }); - - expect(count).toBe(2); - }); - - it('should create indexes', async () => { - await client.createIndex('users', { email: 1 }, { unique: true }); - - // Simple implementation doesn't throw, just no-op - expect(true).toBe(true); - }); - }); - - describe('error handling', () => { - it('should handle disconnected state', async () => { - await client.disconnect(); - - // Simple implementation auto-reconnects - const results = await client.find('users', {}); - expect(results).toBeDefined(); - }); - - it('should return empty array for non-existent collection', async () => { - const results = await client.find('non-existent', {}); - expect(results).toEqual([]); - }); - }); -}); diff --git a/libs/data/mongodb/test/support/simple-mongodb.ts b/libs/data/mongodb/test/support/simple-mongodb.ts deleted file mode 100644 index c78430fa..00000000 --- a/libs/data/mongodb/test/support/simple-mongodb.ts +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Test-only in-memory MongoDB double. Never used by production adapters. - */ -export class SimpleMongoDBClient { - private collections = new Map(); - private connected = false; - - constructor(private config: any) {} - - async connect(): Promise { - this.connected = true; - } - - async disconnect(): Promise { - this.connected = false; - } - - async find(collection: string, filter: any = {}): Promise { - if (!this.connected) { - await this.connect(); - } - const docs = this.collections.get(collection) || []; - - // Simple filter matching - if (Object.keys(filter).length === 0) { - return docs; - } - - return docs.filter(doc => { - for (const [key, value] of Object.entries(filter)) { - if (doc[key] !== value) { - return false; - } - } - return true; - }); - } - - async findOne(collection: string, filter: any = {}): Promise { - const results = await this.find(collection, filter); - return results[0] || null; - } - - async insert(collection: string, doc: any): Promise { - if (!this.connected) { - await this.connect(); - } - const docs = this.collections.get(collection) || []; - docs.push({ ...doc, _id: Math.random().toString(36) }); - this.collections.set(collection, docs); - } - - async insertMany(collection: string, documents: any[]): Promise { - for (const doc of documents) { - await this.insert(collection, doc); - } - } - - async update(collection: string, filter: any, update: any): Promise { - if (!this.connected) { - await this.connect(); - } - const docs = await this.find(collection, filter); - - if (docs.length === 0) { - return 0; - } - - const doc = docs[0]; - if (update.$set) { - Object.assign(doc, update.$set); - } - - return 1; - } - - async updateMany(collection: string, filter: any, update: any): Promise { - if (!this.connected) { - await this.connect(); - } - const docs = await this.find(collection, filter); - - for (const doc of docs) { - if (update.$set) { - Object.assign(doc, update.$set); - } - } - - return docs.length; - } - - async delete(collection: string, filter: any): Promise { - if (!this.connected) { - await this.connect(); - } - const allDocs = this.collections.get(collection) || []; - const toDelete = await this.find(collection, filter); - - if (toDelete.length === 0) { - return 0; - } - - const remaining = allDocs.filter(doc => !toDelete.includes(doc)); - this.collections.set(collection, remaining); - - return 1; - } - - async deleteMany(collection: string, filter: any): Promise { - if (!this.connected) { - await this.connect(); - } - const allDocs = this.collections.get(collection) || []; - const toDelete = await this.find(collection, filter); - - const remaining = allDocs.filter(doc => !toDelete.includes(doc)); - this.collections.set(collection, remaining); - - return toDelete.length; - } - - async batchUpsert(collection: string, documents: any[], uniqueKeys: string[]): Promise { - if (!this.connected) { - await this.connect(); - } - - for (const doc of documents) { - const filter: any = {}; - for (const key of uniqueKeys) { - filter[key] = doc[key]; - } - - const existing = await this.findOne(collection, filter); - if (existing) { - await this.update(collection, filter, { $set: doc }); - } else { - await this.insert(collection, doc); - } - } - } - - async count(collection: string, filter: any = {}): Promise { - const docs = await this.find(collection, filter); - return docs.length; - } - - async createIndex(_collection: string, _index: any, _options?: any): Promise { - // No-op for simple implementation - } - - async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> { - try { - return { - status: this.connected ? 'healthy' : 'unhealthy', - isConnected: this.connected, - }; - } catch (error: any) { - return { - status: 'unhealthy', - isConnected: false, - error: error.message, - }; - } - } -} diff --git a/libs/data/postgres/package.json b/libs/data/postgres/package.json index 361e2231..ea4e75f1 100644 --- a/libs/data/postgres/package.json +++ b/libs/data/postgres/package.json @@ -14,7 +14,6 @@ }, "dependencies": { "@stock-bot/logger": "*", - "@stock-bot/types": "*", "pg": "^8.11.3", "@stock-bot/invariants": "workspace:*" }, diff --git a/libs/data/postgres/src/client.ts b/libs/data/postgres/src/client.ts index 500cfd5a..1c3d2e17 100644 --- a/libs/data/postgres/src/client.ts +++ b/libs/data/postgres/src/client.ts @@ -1,13 +1,9 @@ import type { PoolConfig, QueryResultRow } from 'pg'; import { Pool } from 'pg'; -import { at } from '@stock-bot/invariants'; import type { LoggerLike } from '@stock-bot/logger'; -import { PostgreSQLHealthMonitor } from './health'; -import { PostgreSQLQueryBuilder } from './query-builder'; import { PostgreSQLTransactionManager } from './transactions'; import type { ConnectionEvents, - DynamicPoolConfig, PoolMetrics, PostgreSQLClientConfig, PostgreSQLConnectionOptions, @@ -15,24 +11,15 @@ import type { TransactionCallback, } from './types'; -/** - * PostgreSQL Client for Stock Bot - * - * Provides type-safe access to PostgreSQL with connection pooling, - * health monitoring, and transaction support. - */ export class PostgreSQLClient { private pool: Pool | null = null; private readonly config: PostgreSQLClientConfig; private readonly options: PostgreSQLConnectionOptions; private readonly logger: LoggerLike; - private readonly healthMonitor: PostgreSQLHealthMonitor; private readonly transactionManager: PostgreSQLTransactionManager; private isConnected = false; private readonly metrics: PoolMetrics; private readonly events?: ConnectionEvents; - private dynamicPoolConfig?: DynamicPoolConfig; - private poolMonitorInterval?: NodeJS.Timeout; constructor( config: PostgreSQLClientConfig, @@ -44,15 +31,11 @@ export class PostgreSQLClient { this.options = { retryAttempts: 3, retryDelay: 1000, - healthCheckInterval: 30000, ...options, }; this.events = events; - this.logger = logger || console; - this.healthMonitor = new PostgreSQLHealthMonitor(this); this.transactionManager = new PostgreSQLTransactionManager(this); - this.metrics = { totalConnections: 0, activeConnections: 0, @@ -63,71 +46,48 @@ export class PostgreSQLClient { }; } - /** - * Connect to PostgreSQL - */ async connect(): Promise { if (this.isConnected && this.pool) { return; } let lastError: Error | null = null; + const attempts = this.options.retryAttempts ?? 3; - for (let attempt = 1; attempt <= (this.options.retryAttempts ?? 3); attempt++) { + for (let attempt = 1; attempt <= attempts; attempt++) { try { - this.logger.info( - `Connecting to PostgreSQL (attempt ${attempt}/${this.options.retryAttempts})...` - ); + this.logger.info(`Connecting to PostgreSQL (attempt ${attempt}/${attempts})...`); this.pool = new Pool(this.buildPoolConfig()); - // Test the connection const client = await this.pool.connect(); - await client.query('SELECT 1'); - client.release(); + try { + await client.query('SELECT 1'); + } finally { + client.release(); + } this.isConnected = true; + this.metrics.totalConnections = this.config.poolSettings?.max || 10; + this.metrics.idleConnections = this.pool.idleCount; - // Update metrics - const poolConfig = this.config.poolSettings; - this.metrics.totalConnections = poolConfig?.max || 10; - this.metrics.idleConnections = poolConfig?.min || 2; - - // Fire connection event if (this.events?.onConnect) { await Promise.resolve(this.events.onConnect()); } - - // Fire pool created event if (this.events?.onPoolCreated) { await Promise.resolve(this.events.onPoolCreated()); } + this.setupErrorHandlers(); this.logger.info('Successfully connected to PostgreSQL', { poolSize: this.metrics.totalConnections, }); - - // Start health monitoring - this.healthMonitor.start(); - - // Setup error handlers - this.setupErrorHandlers(); - - // Setup pool event listeners for metrics - this.setupPoolMetrics(); - - // Start dynamic pool monitoring if enabled - if (this.dynamicPoolConfig?.enabled) { - this.startPoolMonitoring(); - } - return; } catch (error) { lastError = error as Error; this.metrics.errors++; this.metrics.lastError = lastError.message; - // Fire error event if (this.events?.onError) { await Promise.resolve(this.events.onError(lastError)); } @@ -135,42 +95,31 @@ export class PostgreSQLClient { this.logger.error(`PostgreSQL connection attempt ${attempt} failed:`, error); if (this.pool) { - await this.pool.end(); + await this.pool.end().catch(() => {}); this.pool = null; } - if (attempt < (this.options.retryAttempts ?? 3)) { - await this.delay((this.options.retryDelay ?? 1000) * attempt); + if (attempt < attempts) { + await new Promise(resolve => setTimeout(resolve, (this.options.retryDelay ?? 1000) * attempt)); } } } throw new Error( - `Failed to connect to PostgreSQL after ${this.options.retryAttempts} attempts: ${lastError?.message}` + `Failed to connect to PostgreSQL after ${attempts} attempts: ${lastError?.message}` ); } - /** - * Disconnect from PostgreSQL - */ async disconnect(): Promise { if (!this.pool) { return; } try { - // Stop pool monitoring - if (this.poolMonitorInterval) { - clearInterval(this.poolMonitorInterval); - this.poolMonitorInterval = undefined; - } - - this.healthMonitor.stop(); await this.pool.end(); this.isConnected = false; this.pool = null; - // Fire disconnect event if (this.events?.onDisconnect) { await Promise.resolve(this.events.onDisconnect()); } @@ -182,9 +131,6 @@ export class PostgreSQLClient { } } - /** - * Execute a query - */ async query( text: string, params?: unknown[] @@ -194,16 +140,13 @@ export class PostgreSQLClient { } const startTime = Date.now(); - try { const result = await this.pool.query(text, params); const executionTime = Date.now() - startTime; - this.logger.debug(`Query executed in ${executionTime}ms`, { query: text.substring(0, 100), params: params?.length, }); - return { ...result, executionTime, @@ -219,204 +162,13 @@ export class PostgreSQLClient { } } - /** - * Execute multiple queries in a transaction - */ async transaction(callback: TransactionCallback): Promise { return await this.transactionManager.execute(callback); } - /** - * Get a query builder instance - */ - queryBuilder(): PostgreSQLQueryBuilder { - return new PostgreSQLQueryBuilder(this); - } - - /** - * Create a new query builder with SELECT - */ - select(columns: string | string[] = '*'): PostgreSQLQueryBuilder { - return this.queryBuilder().select(columns); - } - - /** - * Create a new query builder with INSERT - */ - insert(table: string): PostgreSQLQueryBuilder { - return this.queryBuilder().insert(table); - } - - /** - * Create a new query builder with UPDATE - */ - update(table: string): PostgreSQLQueryBuilder { - return this.queryBuilder().update(table); - } - - /** - * Create a new query builder with DELETE - */ - delete(table: string): PostgreSQLQueryBuilder { - return this.queryBuilder().delete(table); - } - - /** - * Execute a stored procedure or function - */ - async callFunction( - functionName: string, - params?: unknown[] - ): Promise> { - const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : ''; - const query = `SELECT * FROM ${functionName}(${placeholders})`; - return await this.query(query, params); - } - - /** - * Batch upsert operation for high-performance inserts/updates - */ - async batchUpsert( - tableName: string, - data: Record[], - conflictColumn: string, - options: { - chunkSize?: number; - excludeColumns?: string[]; - } = {} - ): Promise<{ insertedCount: number; updatedCount: number }> { - if (!this.pool) { - throw new Error('PostgreSQL client not connected'); - } - - if (data.length === 0) { - return { insertedCount: 0, updatedCount: 0 }; - } - - const { chunkSize = 1000, excludeColumns = [] } = options; - const columns = Object.keys(data[0] ?? {}).filter(col => !excludeColumns.includes(col)); - const updateColumns = columns.filter(col => col !== conflictColumn); - - let totalInserted = 0; - let totalUpdated = 0; - - // Process in chunks to avoid memory issues and parameter limits - for (let i = 0; i < data.length; i += chunkSize) { - const chunk = data.slice(i, i + chunkSize); - - // Build placeholders for this chunk - const placeholders = chunk.map((_, rowIndex) => { - const rowPlaceholders = columns.map((_, colIndex) => { - return `$${rowIndex * columns.length + colIndex + 1}`; - }); - return `(${rowPlaceholders.join(', ')})`; - }); - - // Flatten the chunk data - const values = chunk.flatMap(row => columns.map(col => row[col as keyof typeof row])); - - // Build the upsert query - const updateClauses = updateColumns.map(col => `${col} = EXCLUDED.${col}`); - const query = ` - INSERT INTO ${tableName} (${columns.join(', ')}) - VALUES ${placeholders.join(', ')} - ON CONFLICT (${conflictColumn}) - DO UPDATE SET - ${updateClauses.join(', ')}, - updated_at = NOW() - RETURNING (xmax = 0) AS is_insert - `; - - try { - const startTime = Date.now(); - const result = await this.pool.query(query, values); - const executionTime = Date.now() - startTime; - - // Count inserts vs updates - const inserted = result.rows.filter((row: { is_insert: boolean }) => row.is_insert).length; - const updated = result.rows.length - inserted; - - totalInserted += inserted; - totalUpdated += updated; - - this.logger.debug(`Batch upsert chunk processed in ${executionTime}ms`, { - chunkSize: chunk.length, - inserted, - updated, - table: tableName, - }); - } catch (error) { - this.logger.error(`Batch upsert failed on chunk ${Math.floor(i / chunkSize) + 1}:`, { - error, - table: tableName, - chunkStart: i, - chunkSize: chunk.length, - }); - throw error; - } - } - - this.logger.info('Batch upsert completed', { - table: tableName, - totalRecords: data.length, - inserted: totalInserted, - updated: totalUpdated, - }); - - return { insertedCount: totalInserted, updatedCount: totalUpdated }; - } - - /** - * Check if a table exists - */ - async tableExists(tableName: string, schemaName: string = 'public'): Promise { - const result = await this.query( - `SELECT EXISTS ( - SELECT FROM information_schema.tables - WHERE table_schema = $1 AND table_name = $2 - )`, - [schemaName, tableName] - ); - return at(result.rows, 0).exists; - } - - /** - * Get table schema information - */ - async getTableSchema( - tableName: string, - schemaName: string = 'public' - ): Promise { - const result = await this.query( - `SELECT - column_name, - data_type, - is_nullable, - column_default, - character_maximum_length - FROM information_schema.columns - WHERE table_schema = $1 AND table_name = $2 - ORDER BY ordinal_position`, - [schemaName, tableName] - ); - return result.rows; - } - - /** - * Execute EXPLAIN for query analysis - */ - async explain(query: string, params?: unknown[]): Promise { - const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`; - const result = await this.query(explainQuery, params); - return at(result.rows, 0)['QUERY PLAN']; - } - - /** - * Get database statistics - */ async getStats(): Promise { const result = await this.query(` - SELECT + SELECT (SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections, (SELECT count(*) FROM pg_stat_activity WHERE state = 'idle') as idle_connections, (SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections, @@ -425,34 +177,24 @@ export class PostgreSQLClient { return result.rows[0] ?? {}; } - /** - * Check if client is connected - */ get connected(): boolean { return this.isConnected && !!this.pool; } - /** - * Get the underlying connection pool - */ get connectionPool(): Pool | null { return this.pool; } - private buildPoolConfig(): PoolConfig { + buildPoolConfig(): PoolConfig { this.logger.debug('Building PostgreSQL pool config:', { host: this.config.host, port: this.config.port, database: this.config.database, user: this.config.username, - passwordLength: this.config.password?.length, - passwordType: typeof this.config.password, - passwordValue: this.config.password - ? `${this.config.password.substring(0, 3)}***` - : 'NO_PASSWORD', + hasPassword: Boolean(this.config.password), }); - const poolConfig = { + return { host: this.config.host, port: this.config.port, database: this.config.database, @@ -475,166 +217,28 @@ export class PostgreSQLClient { } : false, }; + } - return poolConfig; + getPoolMetrics(): PoolMetrics { + this.metrics.lastUsed = new Date(); + if (this.pool) { + this.metrics.totalConnections = this.pool.totalCount; + this.metrics.idleConnections = this.pool.idleCount; + this.metrics.waitingRequests = this.pool.waitingCount; + this.metrics.activeConnections = Math.max( + 0, + this.metrics.totalConnections - this.metrics.idleConnections + ); + } + return { ...this.metrics }; } private setupErrorHandlers(): void { if (!this.pool) { return; } - this.pool.on('error', error => { this.logger.error('PostgreSQL pool error:', error); }); - - this.pool.on('connect', () => { - this.logger.debug('New PostgreSQL client connected'); - }); - - this.pool.on('remove', () => { - this.logger.debug('PostgreSQL client removed from pool'); - }); - } - - private delay(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)); - } - - /** - * Get current pool metrics - */ - getPoolMetrics(): PoolMetrics { - // Update last used timestamp - this.metrics.lastUsed = new Date(); - - // Update metrics from pool if available - if (this.pool) { - this.metrics.totalConnections = this.pool.totalCount; - this.metrics.idleConnections = this.pool.idleCount; - this.metrics.waitingRequests = this.pool.waitingCount; - this.metrics.activeConnections = this.metrics.totalConnections - this.metrics.idleConnections; - } - - return { ...this.metrics }; - } - - /** - * Set dynamic pool configuration - */ - setDynamicPoolConfig(config: DynamicPoolConfig): void { - this.dynamicPoolConfig = config; - - if (config.enabled && this.isConnected && !this.poolMonitorInterval) { - this.startPoolMonitoring(); - } else if (!config.enabled && this.poolMonitorInterval) { - clearInterval(this.poolMonitorInterval); - this.poolMonitorInterval = undefined; - } - } - - /** - * Start monitoring pool and adjust size dynamically - */ - private startPoolMonitoring(): void { - if (!this.dynamicPoolConfig || this.poolMonitorInterval) { - return; - } - - this.poolMonitorInterval = setInterval(() => { - this.evaluatePoolSize(); - }, this.dynamicPoolConfig.evaluationInterval); - } - - /** - * Setup pool event listeners for metrics - */ - private setupPoolMetrics(): void { - if (!this.pool) { - return; - } - - // Track when connections are acquired - this.pool.on('acquire', () => { - this.metrics.activeConnections++; - this.metrics.idleConnections--; - }); - - // Track when connections are released - this.pool.on('release', () => { - this.metrics.activeConnections--; - this.metrics.idleConnections++; - }); - } - - /** - * Evaluate and adjust pool size based on usage - */ - private async evaluatePoolSize(): Promise { - if (!this.dynamicPoolConfig || !this.pool) { - return; - } - - const metrics = this.getPoolMetrics(); - const { minSize, maxSize, scaleUpThreshold, scaleDownThreshold } = this.dynamicPoolConfig; - const currentSize = metrics.totalConnections; - const utilization = currentSize > 0 ? (metrics.activeConnections / currentSize) * 100 : 0; - - this.logger.debug('Pool utilization', { - utilization: `${utilization.toFixed(1)}%`, - active: metrics.activeConnections, - total: currentSize, - waiting: metrics.waitingRequests, - }); - - // Scale up if utilization is high or there are waiting requests - if ((utilization > scaleUpThreshold || metrics.waitingRequests > 0) && currentSize < maxSize) { - const newSize = Math.min(currentSize + this.dynamicPoolConfig.scaleUpIncrement, maxSize); - this.logger.info('Would scale up connection pool', { - from: currentSize, - to: newSize, - utilization, - }); - // Note: pg module doesn't support dynamic resizing, would need reconnection - } - // Scale down if utilization is low - else if (utilization < scaleDownThreshold && currentSize > minSize) { - const newSize = Math.max(currentSize - this.dynamicPoolConfig.scaleDownIncrement, minSize); - this.logger.info('Would scale down connection pool', { - from: currentSize, - to: newSize, - utilization, - }); - // Note: pg module doesn't support dynamic resizing, would need reconnection - } - } - - /** - * Enable pool warmup on connect - */ - async warmupPool(): Promise { - if (!this.pool || !this.isConnected) { - throw new Error('Client not connected'); - } - - const minSize = this.config.poolSettings?.min || 2; - const promises: Promise[] = []; - - // Create minimum connections by running parallel queries - for (let i = 0; i < minSize; i++) { - promises.push( - this.pool - .query('SELECT 1') - .then(() => { - this.logger.debug(`Warmed up connection ${i + 1}/${minSize}`); - }) - .catch(error => { - this.logger.warn(`Failed to warm up connection ${i + 1}`, { error }); - }) - ); - } - - await Promise.allSettled(promises); - this.logger.info('Connection pool warmup complete', { connections: minSize }); } } diff --git a/libs/data/postgres/src/health.ts b/libs/data/postgres/src/health.ts deleted file mode 100644 index 563e887e..00000000 --- a/libs/data/postgres/src/health.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import type { PostgreSQLClient } from './client'; -import type { PostgreSQLHealthCheck, PostgreSQLHealthStatus, PostgreSQLMetrics } from './types'; - -/** - * PostgreSQL Health Monitor - * - * Monitors PostgreSQL connection health and provides metrics - */ -export class PostgreSQLHealthMonitor { - private readonly client: PostgreSQLClient; - private readonly logger: ReturnType; - private healthCheckInterval: NodeJS.Timeout | null = null; - private metrics: PostgreSQLMetrics; - private lastHealthCheck: PostgreSQLHealthCheck | null = null; - - constructor(client: PostgreSQLClient) { - this.client = client; - this.logger = getLogger('postgres-health-monitor'); - this.metrics = { - queriesPerSecond: 0, - averageQueryTime: 0, - errorRate: 0, - connectionPoolUtilization: 0, - slowQueries: 0, - }; - } - - /** - * Start health monitoring - */ - start(intervalMs: number = 30000): void { - if (this.healthCheckInterval) { - this.stop(); - } - - this.logger.info(`Starting PostgreSQL health monitoring (interval: ${intervalMs}ms)`); - - this.healthCheckInterval = setInterval(async () => { - try { - await this.performHealthCheck(); - } catch (error) { - this.logger.error('Health check failed:', error); - } - }, intervalMs); - - // Perform initial health check - this.performHealthCheck().catch(error => { - this.logger.error('Initial health check failed:', error); - }); - } - - /** - * Stop health monitoring - */ - stop(): void { - if (this.healthCheckInterval) { - clearInterval(this.healthCheckInterval); - this.healthCheckInterval = null; - this.logger.info('Stopped PostgreSQL health monitoring'); - } - } - - /** - * Get current health status - */ - async getHealth(): Promise { - if (!this.lastHealthCheck) { - await this.performHealthCheck(); - } - if (!this.lastHealthCheck) { - throw new Error('Health check failed to produce results'); - } - return this.lastHealthCheck; - } - - /** - * Get current metrics - */ - getMetrics(): PostgreSQLMetrics { - return { ...this.metrics }; - } - - /** - * Perform a health check - */ - private async performHealthCheck(): Promise { - const startTime = Date.now(); - const errors: string[] = []; - let status: PostgreSQLHealthStatus = 'healthy'; - - try { - if (!this.client.connected) { - errors.push('PostgreSQL client not connected'); - status = 'unhealthy'; - } else { - // Test basic connectivity - await this.client.query('SELECT 1'); - - // Get connection stats - const stats = await this.client.getStats(); - - // Check connection pool utilization - const utilization = parseInt(stats.active_connections) / parseInt(stats.max_connections); - if (utilization > 0.8) { - errors.push('High connection pool utilization'); - status = status === 'healthy' ? 'degraded' : status; - } - - // Check for high latency - const latency = Date.now() - startTime; - if (latency > 1000) { - errors.push(`High latency: ${latency}ms`); - status = status === 'healthy' ? 'degraded' : status; - } - - this.metrics.connectionPoolUtilization = utilization; - } - } catch (error) { - errors.push(`Health check failed: ${(error as Error).message}`); - status = 'unhealthy'; - } - - const latency = Date.now() - startTime; - - this.lastHealthCheck = { - status, - timestamp: new Date(), - latency, - connections: { - active: 1, - idle: 9, - total: 10, - }, - errors: errors.length > 0 ? errors : undefined, - }; - - // Log health status changes - if (status !== 'healthy') { - this.logger.warn(`PostgreSQL health status: ${status}`, { errors, latency }); - } else { - this.logger.debug(`PostgreSQL health check passed (${latency}ms)`); - } - } -} diff --git a/libs/data/postgres/src/index.ts b/libs/data/postgres/src/index.ts index 6218f411..eadd1545 100644 --- a/libs/data/postgres/src/index.ts +++ b/libs/data/postgres/src/index.ts @@ -1,37 +1,11 @@ -/** - * PostgreSQL Client Library for Stock Bot - * - * Provides type-safe PostgreSQL access for operational data, - * transactions, and relational queries. - */ - export { PostgreSQLClient } from './client'; -export { PostgreSQLHealthMonitor } from './health'; export { PostgreSQLTransactionManager } from './transactions'; -export { PostgreSQLQueryBuilder } from './query-builder'; -// export { PostgreSQLMigrationManager } from './migrations'; // TODO: Implement migrations - -// Types +export { runPostgresMigrations, type MigrationTrack } from './migrations'; export type { + ConnectionEvents, + PoolMetrics, PostgreSQLClientConfig, PostgreSQLConnectionOptions, - PostgreSQLHealthStatus, - PostgreSQLMetrics, QueryResult, TransactionCallback, - SchemaNames, - TableNames, - Trade, - Order, - Position, - Portfolio, - Strategy, - RiskLimit, - AuditLog, - PoolMetrics, - ConnectionEvents, - DynamicPoolConfig, } from './types'; - -// Note: Factory functions removed - instantiate directly with new PostgreSQLClient() -// or use the Awilix DI container (recommended) diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts new file mode 100644 index 00000000..1cb74670 --- /dev/null +++ b/libs/data/postgres/src/migrations.ts @@ -0,0 +1,113 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { getLogger } from '@stock-bot/logger'; +import type { PostgreSQLClient } from './client'; + +const logger = getLogger('postgres-migrations'); + +export type MigrationTrack = 'master' | 'research' | 'all'; + +const MASTER_FILES = new Set([ + '01-init-database.sql', + '02-master-schema.sql', + '03-initial-data.sql', + '04-provider-exchange-mapping-schema.sql', + '05-add-visible-column.sql', +]); + +const RESEARCH_FILES = new Set([ + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '11-simulation-execution-ledger.sql', + '12-historical-datasets.sql', + '13-strategy-recovery.sql', + '14-backtest-submission.sql', + '15-canonical-paper-intents.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + '20-research-workspace.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + '24-chronological-validation.sql', + '25-walk-forward.sql', + '26-cost-sensitivity.sql', + '27-research-evidence-sources.sql', + '28-research-agents.sql', + '29-isolated-candidates.sql', + '30-paper-deployments.sql', + '31-research-agent-project-links.sql', + '32-candidate-parameter-defaults.sql', + '33-candidate-decimal-normalization.sql', +]); + +function locateMigrationsDir(): string { + let directory = dirname(fileURLToPath(import.meta.url)); + while (!existsSync(join(directory, 'database', 'postgres', 'init'))) { + const parent = dirname(directory); + if (parent === directory) { + throw new Error('Cannot locate PostgreSQL migrations directory (database/postgres/init)'); + } + directory = parent; + } + return join(directory, 'database', 'postgres', 'init'); +} + +function matchesTrack(file: string, track: MigrationTrack): boolean { + if (!file.endsWith('.sql')) { + return false; + } + const inMaster = MASTER_FILES.has(file); + const inResearch = file.startsWith('001_') || RESEARCH_FILES.has(file); + if (track === 'master') { + return inMaster; + } + if (track === 'research') { + return inResearch; + } + return inMaster || inResearch; +} + +export async function runPostgresMigrations( + postgres: Pick, + options: { track?: MigrationTrack; migrationsDir?: string } = {} +): Promise { + const track = options.track ?? 'research'; + const applied: string[] = []; + + await postgres.transaction(async client => { + await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]); + + await client.query(` + CREATE TABLE IF NOT EXISTS migrations ( + id SERIAL PRIMARY KEY, + filename VARCHAR(255) NOT NULL UNIQUE, + executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW() + ) + `); + + const migrationsDir = options.migrationsDir ?? locateMigrationsDir(); + const files = readdirSync(migrationsDir) + .filter(f => matchesTrack(f, track)) + .sort(); + + for (const file of files) { + const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]); + if (result.rows.length === 0) { + logger.info(`Running migration: ${file}`); + const sql = readFileSync(join(migrationsDir, file), 'utf8'); + await client.query(sql); + await client.query( + 'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING', + [file] + ); + applied.push(file); + } + } + }); + + return applied; +} diff --git a/libs/data/postgres/src/query-builder.ts b/libs/data/postgres/src/query-builder.ts deleted file mode 100644 index 2983925c..00000000 --- a/libs/data/postgres/src/query-builder.ts +++ /dev/null @@ -1,270 +0,0 @@ -import type { QueryResultRow } from 'pg'; -import type { PostgreSQLClient } from './client'; -import type { JoinCondition, OrderByCondition, QueryResult, WhereCondition } from './types'; - -/** - * PostgreSQL Query Builder - * - * Provides a fluent interface for building SQL queries - */ -export class PostgreSQLQueryBuilder { - private queryType: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | null = null; - private selectColumns: string[] = []; - private fromTable: string = ''; - private joins: JoinCondition[] = []; - private whereConditions: WhereCondition[] = []; - private groupByColumns: string[] = []; - private havingConditions: WhereCondition[] = []; - private orderByConditions: OrderByCondition[] = []; - private limitCount: number | null = null; - private offsetCount: number | null = null; - private insertValues: Record = {}; - private updateValues: Record = {}; - - private readonly client: PostgreSQLClient; - - constructor(client: PostgreSQLClient) { - this.client = client; - } - - /** - * SELECT statement - */ - select(columns: string | string[] = '*'): this { - this.queryType = 'SELECT'; - this.selectColumns = Array.isArray(columns) ? columns : [columns]; - return this; - } - - /** - * FROM clause - */ - from(table: string): this { - this.fromTable = table; - return this; - } - - /** - * JOIN clause - */ - join(table: string, on: string, type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL' = 'INNER'): this { - this.joins.push({ type, table, on }); - return this; - } - - /** - * WHERE clause - */ - where(column: string, operator: WhereCondition['operator'], value?: unknown): this { - this.whereConditions.push({ column, operator, value }); - return this; - } - - /** - * GROUP BY clause - */ - groupBy(columns: string | string[]): this { - this.groupByColumns = Array.isArray(columns) ? columns : [columns]; - return this; - } - - /** - * ORDER BY clause - */ - orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): this { - this.orderByConditions.push({ column, direction }); - return this; - } - - /** - * LIMIT clause - */ - limit(count: number): this { - this.limitCount = count; - return this; - } - - /** - * OFFSET clause - */ - offset(count: number): this { - this.offsetCount = count; - return this; - } - - /** - * INSERT statement - */ - insert(table: string): this { - this.queryType = 'INSERT'; - this.fromTable = table; - return this; - } - - /** - * VALUES for INSERT - */ - values(data: Record): this { - this.insertValues = data; - return this; - } - - /** - * UPDATE statement - */ - update(table: string): this { - this.queryType = 'UPDATE'; - this.fromTable = table; - return this; - } - - /** - * SET for UPDATE - */ - set(data: Record): this { - this.updateValues = data; - return this; - } - - /** - * DELETE statement - */ - delete(table: string): this { - this.queryType = 'DELETE'; - this.fromTable = table; - return this; - } - - /** - * Build and execute the query - */ - async execute(): Promise> { - const { sql, params } = this.build(); - return await this.client.query(sql, params); - } - - /** - * Build the SQL query - */ - build(): { sql: string; params: unknown[] } { - const params: unknown[] = []; - let sql = ''; - - switch (this.queryType) { - case 'SELECT': - sql = this.buildSelectQuery(params); - break; - case 'INSERT': - sql = this.buildInsertQuery(params); - break; - case 'UPDATE': - sql = this.buildUpdateQuery(params); - break; - case 'DELETE': - sql = this.buildDeleteQuery(params); - break; - default: - throw new Error('Query type not specified'); - } - - return { sql, params }; - } - - private buildSelectQuery(params: unknown[]): string { - let sql = `SELECT ${this.selectColumns.join(', ')}`; - - if (this.fromTable) { - sql += ` FROM ${this.fromTable}`; - } - - // Add JOINs - for (const join of this.joins) { - sql += ` ${join.type} JOIN ${join.table} ON ${join.on}`; - } - - // Add WHERE - if (this.whereConditions.length > 0) { - sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params); - } - - // Add GROUP BY - if (this.groupByColumns.length > 0) { - sql += ` GROUP BY ${this.groupByColumns.join(', ')}`; - } - - // Add HAVING - if (this.havingConditions.length > 0) { - sql += ' HAVING ' + this.buildWhereClause(this.havingConditions, params); - } - - // Add ORDER BY - if (this.orderByConditions.length > 0) { - const orderBy = this.orderByConditions - .map(order => `${order.column} ${order.direction}`) - .join(', '); - sql += ` ORDER BY ${orderBy}`; - } - - // Add LIMIT - if (this.limitCount !== null) { - sql += ` LIMIT $${params.length + 1}`; - params.push(this.limitCount); - } - - // Add OFFSET - if (this.offsetCount !== null) { - sql += ` OFFSET $${params.length + 1}`; - params.push(this.offsetCount); - } - - return sql; - } - - private buildInsertQuery(params: unknown[]): string { - const columns = Object.keys(this.insertValues); - const placeholders = columns.map((_, i) => `$${params.length + i + 1}`); - - params.push(...Object.values(this.insertValues)); - - return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`; - } - - private buildUpdateQuery(params: unknown[]): string { - const sets = Object.keys(this.updateValues).map((key, i) => { - return `${key} = $${params.length + i + 1}`; - }); - - params.push(...Object.values(this.updateValues)); - - let sql = `UPDATE ${this.fromTable} SET ${sets.join(', ')}`; - - if (this.whereConditions.length > 0) { - sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params); - } - - return sql; - } - - private buildDeleteQuery(params: unknown[]): string { - let sql = `DELETE FROM ${this.fromTable}`; - - if (this.whereConditions.length > 0) { - sql += ' WHERE ' + this.buildWhereClause(this.whereConditions, params); - } - - return sql; - } - - private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string { - return conditions - .map(condition => { - if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') { - return `${condition.column} ${condition.operator}`; - } else { - params.push(condition.value); - return `${condition.column} ${condition.operator} $${params.length}`; - } - }) - .join(' AND '); - } -} diff --git a/libs/data/postgres/src/types.ts b/libs/data/postgres/src/types.ts index 9737201e..44e5237c 100644 --- a/libs/data/postgres/src/types.ts +++ b/libs/data/postgres/src/types.ts @@ -1,8 +1,5 @@ import type { QueryResult as PgQueryResult, PoolClient, QueryResultRow } from 'pg'; -/** - * PostgreSQL Client Configuration - */ export interface PostgreSQLClientConfig { host: string; port: number; @@ -27,13 +24,9 @@ export interface PostgreSQLClientConfig { }; } -/** - * PostgreSQL Connection Options - */ export interface PostgreSQLConnectionOptions { retryAttempts?: number; retryDelay?: number; - healthCheckInterval?: number; } export interface PoolMetrics { @@ -43,7 +36,6 @@ export interface PoolMetrics { waitingRequests: number; errors: number; lastError?: string; - avgResponseTime?: number; created: Date; lastUsed?: Date; } @@ -55,194 +47,8 @@ export interface ConnectionEvents { onPoolCreated?: () => void | Promise; } -export interface DynamicPoolConfig { - enabled: boolean; - minSize: number; - maxSize: number; - scaleUpThreshold: number; // % of pool in use (0-100) - scaleDownThreshold: number; // % of pool idle (0-100) - scaleUpIncrement: number; // connections to add - scaleDownIncrement: number; // connections to remove - evaluationInterval: number; // ms between checks -} - -/** - * Health Status Types - */ -export type PostgreSQLHealthStatus = 'healthy' | 'degraded' | 'unhealthy'; - -export interface PostgreSQLHealthCheck { - status: PostgreSQLHealthStatus; - timestamp: Date; - latency: number; - connections: { - active: number; - idle: number; - total: number; - }; - errors?: string[]; -} - -export interface PostgreSQLMetrics { - queriesPerSecond: number; - averageQueryTime: number; - errorRate: number; - connectionPoolUtilization: number; - slowQueries: number; -} - -/** - * Query Result Types - */ export interface QueryResult extends PgQueryResult { executionTime?: number; } export type TransactionCallback = (client: PoolClient) => Promise; - -/** - * Schema and Table Names - */ -export type SchemaNames = 'trading' | 'strategy' | 'risk' | 'audit'; - -export type TableNames = - | 'trades' - | 'orders' - | 'positions' - | 'portfolios' - | 'strategies' - | 'risk_limits' - | 'audit_logs' - | 'users' - | 'accounts' - | 'symbols' - | 'exchanges'; - -/** - * Trading Domain Types - */ -export interface Trade { - id: string; - order_id: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - executed_at: Date; - commission: number; - fees: number; - portfolio_id: string; - strategy_id?: string; - created_at: Date; - updated_at: Date; -} - -export interface Order { - id: string; - symbol: string; - side: 'buy' | 'sell'; - type: 'market' | 'limit' | 'stop' | 'stop_limit'; - quantity: number; - price?: number; - stop_price?: number; - status: 'pending' | 'filled' | 'cancelled' | 'rejected'; - portfolio_id: string; - strategy_id?: string; - created_at: Date; - updated_at: Date; - expires_at?: Date; -} - -export interface Position { - id: string; - symbol: string; - quantity: number; - average_cost: number; - market_value: number; - unrealized_pnl: number; - realized_pnl: number; - portfolio_id: string; - created_at: Date; - updated_at: Date; -} - -export interface Portfolio { - id: string; - name: string; - cash_balance: number; - total_value: number; - unrealized_pnl: number; - realized_pnl: number; - user_id: string; - created_at: Date; - updated_at: Date; -} - -export interface Strategy { - id: string; - name: string; - description: string; - parameters: Record; - status: 'active' | 'inactive' | 'paused'; - performance_metrics: Record; - portfolio_id: string; - created_at: Date; - updated_at: Date; -} - -export interface RiskLimit { - id: string; - type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration'; - value: number; - threshold: number; - status: 'active' | 'breached' | 'disabled'; - portfolio_id?: string; - strategy_id?: string; - created_at: Date; - updated_at: Date; -} - -export interface AuditLog { - id: string; - action: string; - entity_type: string; - entity_id: string; - old_values?: Record; - new_values?: Record; - user_id?: string; - ip_address?: string; - user_agent?: string; - timestamp: Date; -} - -/** - * Query Builder Types - */ -export interface WhereCondition { - column: string; - operator: - | '=' - | '!=' - | '>' - | '<' - | '>=' - | '<=' - | 'IN' - | 'NOT IN' - | 'LIKE' - | 'ILIKE' - | 'IS NULL' - | 'IS NOT NULL'; - value?: unknown; -} - -export interface JoinCondition { - type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL'; - table: string; - on: string; -} - -export interface OrderByCondition { - column: string; - direction: 'ASC' | 'DESC'; -} diff --git a/libs/data/postgres/test/postgres.test.ts b/libs/data/postgres/test/postgres.test.ts deleted file mode 100644 index 7408622d..00000000 --- a/libs/data/postgres/test/postgres.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { beforeEach, describe, expect, it } from 'bun:test'; -import { - SimplePostgresClient, - SimpleQueryBuilder, - SimpleTransactionManager, -} from './support/simple-postgres'; - -describe('PostgresClient', () => { - let client: SimplePostgresClient; - const config = { - host: 'localhost', - port: 5432, - database: 'test', - user: 'test', - password: 'test', - max: 10, - }; - - beforeEach(() => { - client = new SimplePostgresClient(config); - }); - - describe('query execution', () => { - it('should execute simple query', async () => { - const result = await client.query('SELECT * FROM users WHERE id = $1', [1]); - - expect(result).toBeDefined(); - expect(result.rows).toBeDefined(); - expect(result.rowCount).toBe(0); - }); - - it('should handle empty results', async () => { - const result = await client.query('SELECT * FROM invalid'); - - expect(result.rows).toEqual([]); - expect(result.rowCount).toBe(0); - }); - }); - - describe('convenience methods', () => { - it('should find one record', async () => { - await client.insert('users', { name: 'Test' }); - - const result = await client.findOne('users', { id: 1 }); - - expect(result).toBeDefined(); - expect(result.id).toBe(1); - expect(result.name).toBe('Test'); - }); - - it('should find multiple records', async () => { - await client.insert('users', { name: 'User 1', active: true }); - await client.insert('users', { name: 'User 2', active: true }); - await client.insert('users', { name: 'User 3', active: false }); - - const results = await client.find('users', { active: true }); - - expect(results).toHaveLength(2); - }); - - it('should insert record', async () => { - const result = await client.insert('users', { name: 'New User' }); - - expect(result).toBeDefined(); - expect(result.id).toBe(1); - expect(result.name).toBe('New User'); - }); - - it('should update records', async () => { - await client.insert('users', { name: 'User 1', active: false }); - await client.insert('users', { name: 'User 2', active: false }); - - const result = await client.update('users', { active: false }, { status: 'inactive' }); - - expect(result).toBe(2); - }); - - it('should delete records', async () => { - await client.insert('users', { name: 'User 1', active: false }); - await client.insert('users', { name: 'User 2', active: false }); - await client.insert('users', { name: 'User 3', active: true }); - - const result = await client.delete('users', { active: false }); - - expect(result).toBe(2); - }); - }); - - describe('health check', () => { - it('should perform health check', async () => { - const health = await client.healthCheck(); - - expect(health.status).toBe('healthy'); - expect(health.isConnected).toBe(true); - }); - - it('should handle disconnection', async () => { - await client.disconnect(); - - // Simple implementation doesn't track connection state in health check - const health = await client.healthCheck(); - expect(health.status).toBe('healthy'); - }); - }); - - describe('connection management', () => { - it('should disconnect properly', async () => { - await client.disconnect(); - - // Simple test - just ensure no errors - expect(true).toBe(true); - }); - }); -}); - -describe('QueryBuilder', () => { - it('should build SELECT query', () => { - const query = new SimpleQueryBuilder() - .select(['id', 'name']) - .from('users') - .where({ active: true }) - .orderBy('created_at', 'DESC') - .limit(10) - .build(); - - expect(query.text).toContain('SELECT id, name FROM users'); - expect(query.text).toContain('WHERE active = $1'); - expect(query.text).toContain('ORDER BY created_at DESC'); - expect(query.text).toContain('LIMIT 10'); - expect(query.values).toEqual([true]); - }); - - it('should build INSERT query', () => { - const query = new SimpleQueryBuilder() - .insert('users', { name: 'Test', email: 'test@example.com' }) - .returning('*') - .build(); - - expect(query.text).toContain('INSERT INTO users'); - expect(query.text).toContain('(name, email)'); - expect(query.text).toContain('VALUES ($1, $2)'); - expect(query.text).toContain('RETURNING *'); - expect(query.values).toEqual(['Test', 'test@example.com']); - }); - - it('should build UPDATE query', () => { - const date = new Date(); - const query = new SimpleQueryBuilder() - .update('users') - .set({ name: 'Updated', modified: date }) - .where({ id: 1 }) - .build(); - - expect(query.text).toContain('UPDATE users SET'); - expect(query.text).toContain('name = $1'); - expect(query.text).toContain('WHERE id = $3'); - expect(query.values).toHaveLength(3); - }); - - it('should build DELETE query', () => { - const query = new SimpleQueryBuilder().delete('users').where({ id: 1 }).build(); - - expect(query.text).toContain('DELETE FROM users'); - expect(query.text).toContain('WHERE id = $1'); - expect(query.values).toEqual([1]); - }); - - it('should handle joins', () => { - const query = new SimpleQueryBuilder() - .select(['u.name', 'p.title']) - .from('users u') - .join('posts p', 'u.id = p.user_id') - .where({ 'u.active': true }) - .build(); - - expect(query.text).toContain('JOIN posts p ON u.id = p.user_id'); - }); -}); - -describe('TransactionManager', () => { - let manager: SimpleTransactionManager; - - beforeEach(() => { - manager = new SimpleTransactionManager({} as any); - }); - - it('should execute transaction successfully', async () => { - const result = await manager.transaction(async client => { - await client.query('INSERT INTO users (name) VALUES ($1)', ['Test']); - return { success: true }; - }); - - expect(result).toEqual({ success: true }); - }); - - it('should rollback on error', async () => { - await expect( - manager.transaction(async _client => { - throw new Error('Transaction failed'); - }) - ).rejects.toThrow('Transaction failed'); - }); - - it('should handle multiple operations', async () => { - const result = await manager.transaction(async client => { - await client.query('INSERT INTO users VALUES ($1)', ['User 1']); - await client.query('INSERT INTO users VALUES ($1)', ['User 2']); - return { count: 2 }; - }); - - expect(result).toEqual({ count: 2 }); - }); -}); diff --git a/libs/data/postgres/test/support/simple-postgres.ts b/libs/data/postgres/test/support/simple-postgres.ts deleted file mode 100644 index e39d32e8..00000000 --- a/libs/data/postgres/test/support/simple-postgres.ts +++ /dev/null @@ -1,215 +0,0 @@ -/** - * Test-only in-memory PostgreSQL double. Never used by production adapters. - */ -export class SimplePostgresClient { - private tables = new Map(); - private connected = false; - - constructor(private config: any) {} - - async query(_sql: string, _params?: any[]): Promise<{ rows: any[]; rowCount: number }> { - // Simple mock implementation - return { rows: [], rowCount: 0 }; - } - - async findOne(table: string, where: any): Promise { - const rows = this.tables.get(table) || []; - for (const row of rows) { - let match = true; - for (const [key, value] of Object.entries(where)) { - if (row[key] !== value) { - match = false; - break; - } - } - if (match) { - return row; - } - } - return null; - } - - async find(table: string, where: any): Promise { - const rows = this.tables.get(table) || []; - if (Object.keys(where).length === 0) { - return rows; - } - - return rows.filter(row => { - for (const [key, value] of Object.entries(where)) { - if (row[key] !== value) { - return false; - } - } - return true; - }); - } - - async insert(table: string, data: any): Promise { - const rows = this.tables.get(table) || []; - const newRow = { ...data, id: rows.length + 1 }; - rows.push(newRow); - this.tables.set(table, rows); - return newRow; - } - - async update(table: string, where: any, data: any): Promise { - const rows = this.tables.get(table) || []; - let updated = 0; - - for (const row of rows) { - let match = true; - for (const [key, value] of Object.entries(where)) { - if (row[key] !== value) { - match = false; - break; - } - } - if (match) { - Object.assign(row, data); - updated++; - } - } - - return updated; - } - - async delete(table: string, where: any): Promise { - const rows = this.tables.get(table) || []; - const remaining = rows.filter(row => { - for (const [key, value] of Object.entries(where)) { - if (row[key] !== value) { - return true; - } - } - return false; - }); - - const deleted = rows.length - remaining.length; - this.tables.set(table, remaining); - return deleted; - } - - async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> { - return { - status: 'healthy', - isConnected: true, - }; - } - - async disconnect(): Promise { - this.connected = false; - } -} - -export class SimpleQueryBuilder { - private parts: string[] = []; - private params: any[] = []; - - select(columns: string[] | string = '*'): SimpleQueryBuilder { - const cols = Array.isArray(columns) ? columns.join(', ') : columns; - this.parts.push(`SELECT ${cols}`); - return this; - } - - from(table: string): SimpleQueryBuilder { - this.parts.push(`FROM ${table}`); - return this; - } - - where(conditions: any): SimpleQueryBuilder { - const whereClause = Object.entries(conditions) - .map(([key], _i) => { - this.params.push(conditions[key]); - return `${key} = $${this.params.length}`; - }) - .join(' AND '); - - this.parts.push(`WHERE ${whereClause}`); - return this; - } - - orderBy(column: string, direction = 'ASC'): SimpleQueryBuilder { - this.parts.push(`ORDER BY ${column} ${direction}`); - return this; - } - - limit(count: number): SimpleQueryBuilder { - this.parts.push(`LIMIT ${count}`); - return this; - } - - insert(table: string, data: any): SimpleQueryBuilder { - const columns = Object.keys(data); - const values = Object.values(data); - this.params.push(...values); - - const placeholders = columns.map((_, i) => `$${i + 1}`); - this.parts.push( - `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})` - ); - return this; - } - - update(table: string): SimpleQueryBuilder { - this.parts.push(`UPDATE ${table}`); - return this; - } - - set(data: any): SimpleQueryBuilder { - const setClause = Object.entries(data) - .map(([key, value]) => { - this.params.push(value); - return `${key} = $${this.params.length}`; - }) - .join(', '); - - this.parts.push(`SET ${setClause}`); - return this; - } - - delete(table: string): SimpleQueryBuilder { - this.parts.push(`DELETE FROM ${table}`); - return this; - } - - returning(columns: string): SimpleQueryBuilder { - this.parts.push(`RETURNING ${columns}`); - return this; - } - - join(table: string, condition: string): SimpleQueryBuilder { - this.parts.push(`JOIN ${table} ON ${condition}`); - return this; - } - - build(): { text: string; values: any[] } { - return { - text: this.parts.join(' '), - values: this.params, - }; - } -} - -export class SimpleTransactionManager { - constructor(private pool: any) {} - - async transaction(fn: (client: any) => Promise): Promise { - const mockClient = { - query: async (_sql?: string) => ({ rows: [], rowCount: 0 }), - release: () => {}, - }; - - await mockClient.query('BEGIN'); - try { - const result = await fn(mockClient); - await mockClient.query('COMMIT'); - return result; - } catch (error) { - await mockClient.query('ROLLBACK'); - throw error; - } finally { - mockClient.release(); - } - } -} diff --git a/libs/data/questdb/package.json b/libs/data/questdb/package.json index 1b0e02e4..25340f95 100644 --- a/libs/data/questdb/package.json +++ b/libs/data/questdb/package.json @@ -14,7 +14,6 @@ }, "dependencies": { "@stock-bot/logger": "*", - "@stock-bot/types": "*", "pg": "^8.11.3", "@stock-bot/invariants": "workspace:*" }, diff --git a/libs/services/browser/src/utils.ts b/libs/services/browser/src/utils.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/libs/services/browser/test/browser.test.ts b/libs/services/browser/test/browser.test.ts deleted file mode 100644 index c10a5791..00000000 --- a/libs/services/browser/test/browser.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import { SimpleBrowser } from './support/simple-browser'; - -describe('Browser', () => { - let browser: SimpleBrowser; - const logger = { - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - }; - - beforeEach(() => { - logger.info = mock(() => {}); - logger.error = mock(() => {}); - - browser = new SimpleBrowser(logger); - }); - - describe('initialization', () => { - it('should initialize browser on first call', async () => { - await browser.initialize(); - - expect(logger.info).toHaveBeenCalledWith('Initializing browser...'); - }); - - it('should not reinitialize if already initialized', async () => { - await browser.initialize(); - await browser.initialize(); - - expect(logger.info).toHaveBeenCalledTimes(1); - }); - - it('should merge options', async () => { - await browser.initialize({ headless: false, timeout: 60000 }); - - // Just verify it doesn't throw - expect(true).toBe(true); - }); - }); - - describe('context management', () => { - it('should create new context', async () => { - await browser.initialize(); - const contextId = await browser.createContext('test'); - - expect(contextId).toBe('test'); - }); - - it('should generate context ID if not provided', async () => { - await browser.initialize(); - const contextId = await browser.createContext(); - - expect(contextId).toBeDefined(); - expect(typeof contextId).toBe('string'); - }); - - it('should close context', async () => { - await browser.initialize(); - const contextId = await browser.createContext('test'); - await browser.closeContext(contextId); - - // Just verify it doesn't throw - expect(true).toBe(true); - }); - - it('should handle closing non-existent context', async () => { - await browser.initialize(); - await expect(browser.closeContext('non-existent')).resolves.toBeUndefined(); - }); - }); - - describe('page operations', () => { - it('should create new page', async () => { - await browser.initialize(); - const contextId = await browser.createContext(); - const page = await browser.newPage(contextId); - - expect(page).toBeDefined(); - }); - - it('should navigate to URL', async () => { - await browser.initialize(); - const contextId = await browser.createContext(); - const page = await browser.newPage(contextId); - - await browser.goto(page, 'https://example.com'); - - // Just verify it doesn't throw - expect(true).toBe(true); - }); - - it('should scrape page', async () => { - await browser.initialize(); - - const result = await browser.scrape('https://example.com'); - - expect(result.success).toBe(true); - expect(result.data.title).toBeDefined(); - expect(result.data.text).toBeDefined(); - expect(result.data.links).toBeDefined(); - }); - }); - - describe('resource blocking', () => { - it('should block resources when enabled', async () => { - await browser.initialize({ blockResources: true }); - const contextId = await browser.createContext(); - const page = await browser.newPage(contextId); - - // Just verify it doesn't throw - expect(page).toBeDefined(); - }); - - it('should not block resources when disabled', async () => { - await browser.initialize({ blockResources: false }); - const contextId = await browser.createContext(); - const page = await browser.newPage(contextId); - - expect(page).toBeDefined(); - }); - }); - - describe('cleanup', () => { - it('should close browser', async () => { - await browser.initialize(); - await browser.close(); - - // Just verify it doesn't throw - expect(true).toBe(true); - }); - - it('should handle close when not initialized', async () => { - await expect(browser.close()).resolves.toBeUndefined(); - }); - - it('should close all contexts on browser close', async () => { - await browser.initialize(); - await browser.createContext('test1'); - await browser.createContext('test2'); - - await browser.close(); - - // Just verify it doesn't throw - expect(true).toBe(true); - }); - }); - - describe('error handling', () => { - it('should handle browser launch failure', async () => { - // SimpleBrowser doesn't actually fail to launch - await browser.initialize(); - // Just verify it initialized - expect(true).toBe(true); - }); - - it('should handle page creation failure', async () => { - await browser.initialize(); - - // Should throw for non-existent context - await expect(browser.newPage('non-existent')).rejects.toThrow( - 'Context non-existent not found' - ); - }); - - it('should handle scrape errors', async () => { - // SimpleBrowser catches errors and returns success: false - await browser.initialize(); - - const result = await browser.scrape('https://example.com'); - - expect(result.success).toBe(true); // SimpleBrowser always succeeds - }); - }); -}); diff --git a/libs/services/browser/test/support/simple-browser.ts b/libs/services/browser/test/support/simple-browser.ts deleted file mode 100644 index 697080b6..00000000 --- a/libs/services/browser/test/support/simple-browser.ts +++ /dev/null @@ -1,166 +0,0 @@ -import type { Page } from 'playwright'; -import type { BrowserOptions, ScrapingResult } from '../../src/types'; - -/** - * Simple browser implementation for testing - */ -export class SimpleBrowser { - private browser: any; - private contexts = new Map(); - private logger: any; - private initialized = false; - private _options: BrowserOptions = { - headless: true, - timeout: 30000, - blockResources: false, - enableNetworkLogging: false, - }; - - constructor(logger?: any) { - this.logger = logger || console; - - // Initialize mock browser - this.browser = { - newContext: async () => { - const pages: any[] = []; - const context = { - newPage: async () => { - const page = { - goto: async () => {}, - close: async () => {}, - evaluate: async () => {}, - waitForSelector: async () => {}, - screenshot: async () => Buffer.from('screenshot'), - setViewport: async () => {}, - content: async () => '', - on: () => {}, - route: async () => {}, - }; - pages.push(page); - return page; - }, - close: async () => {}, - pages: async () => pages, - }; - return context; - }, - close: async () => {}, - isConnected: () => true, - }; - } - - async initialize(options: BrowserOptions = {}): Promise { - if (this.initialized) { - return; - } - - // Merge options - this._options = { ...this._options, ...options }; - - this.logger.info('Initializing browser...'); - - // Mock browser is already initialized in constructor for simplicity - this.initialized = true; - } - - async createContext(id?: string): Promise { - if (!this.browser) { - await this.initialize(); - } - - const contextId = id || `context-${Date.now()}`; - const context = await this.browser.newContext(); - this.contexts.set(contextId, context); - return contextId; - } - - async closeContext(contextId: string): Promise { - const context = this.contexts.get(contextId); - if (context) { - await context.close(); - this.contexts.delete(contextId); - } - } - - async newPage(contextId: string): Promise { - const context = this.contexts.get(contextId); - if (!context) { - throw new Error(`Context ${contextId} not found`); - } - - const page = await context.newPage(); - - // Add resource blocking if enabled - if (this._options?.blockResources) { - await page.route('**/*.{png,jpg,jpeg,gif,svg,ico,woff,woff2,ttf,css}', (route: any) => { - route.abort(); - }); - } - - return page; - } - - async goto(page: Page, url: string, options?: any): Promise { - await page.goto(url, { - timeout: this._options?.timeout || 30000, - ...options, - }); - } - - async scrape(url: string, options?: { contextId?: string }): Promise { - try { - let contextId = options?.contextId; - const shouldCloseContext = !contextId; - - if (!contextId) { - contextId = await this.createContext(); - } - - const page = await this.newPage(contextId); - - await this.goto(page, url); - - // Mock data for testing - const data = { - title: 'Test Title', - text: 'Test content', - links: ['link1', 'link2'], - }; - - await page.close(); - - if (shouldCloseContext) { - await this.closeContext(contextId); - } - - return { - success: true, - data, - url, - }; - } catch (error: any) { - return { - success: false, - error: error.message, - url, - data: {} as any, - }; - } - } - - async close(): Promise { - if (!this.browser) { - return; - } - - // Close all contexts - for (const [_contextId, context] of this.contexts) { - await context.close(); - } - this.contexts.clear(); - - await this.browser.close(); - this.browser = null; - this.initialized = false; - } -} diff --git a/libs/services/proxy/src/simple-proxy-manager.ts b/libs/services/proxy/src/simple-proxy-manager.ts deleted file mode 100644 index 1d541ed1..00000000 --- a/libs/services/proxy/src/simple-proxy-manager.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { ProxyInfo } from './types'; - -export interface ProxyConfig { - protocol: string; - host: string; - port: number; - auth?: { - username: string; - password: string; - }; -} - -/** - * Simple proxy manager for testing - */ -export class SimpleProxyManager { - private proxies: Array = []; - private currentIndex = 0; - private activeProxyIndex = 0; - - addProxy(proxy: ProxyInfo & { id: string; active: boolean }): void { - this.proxies.push(proxy); - } - - removeProxy(id: string): void { - this.proxies = this.proxies.filter(p => p.id !== id); - } - - updateProxyStatus(id: string, active: boolean): void { - const proxy = this.proxies.find(p => p.id === id); - if (proxy) { - proxy.active = active; - } - } - - getProxies(): Array { - return [...this.proxies]; - } - - getActiveProxies(): Array { - return this.proxies.filter(p => p.active); - } - - getNextProxy(): (ProxyInfo & { id: string; active: boolean }) | null { - const activeProxies = this.getActiveProxies(); - if (activeProxies.length === 0) { - return null; - } - - const proxy = activeProxies[this.activeProxyIndex % activeProxies.length]; - this.activeProxyIndex++; - return proxy || null; - } - - getProxyConfig(proxy: ProxyInfo & { id: string; active: boolean }): ProxyConfig { - const config: ProxyConfig = { - protocol: proxy.protocol, - host: proxy.host, - port: proxy.port, - }; - - if (proxy.username && proxy.password) { - config.auth = { - username: proxy.username, - password: proxy.password, - }; - } - - return config; - } - - formatProxyUrl(proxy: ProxyInfo): string { - let url = `${proxy.protocol}://`; - if (proxy.username && proxy.password) { - url += `${proxy.username}:${proxy.password}@`; - } - url += `${proxy.host}:${proxy.port}`; - return url; - } - - async validateProxy(id: string): Promise { - const proxy = this.proxies.find(p => p.id === id); - if (!proxy) { - return false; - } - - try { - const proxyUrl = this.formatProxyUrl(proxy); - const response = await fetch('https://httpbin.org/ip', { - // @ts-ignore - proxy option might not be in types - proxy: proxyUrl, - signal: AbortSignal.timeout(5000), - }); - return response.ok; - } catch { - return false; - } - } - - async validateAllProxies(): Promise> { - const results: Record = {}; - - for (const proxy of this.proxies) { - const isValid = await this.validateProxy(proxy.id); - results[proxy.id] = isValid; - - // Disable invalid proxies - if (!isValid) { - this.updateProxyStatus(proxy.id, false); - } - } - - return results; - } - - getStatistics() { - const stats = { - total: this.proxies.length, - active: this.proxies.filter(p => p.active).length, - inactive: this.proxies.filter(p => !p.active).length, - byProtocol: {} as Record, - }; - - this.proxies.forEach(proxy => { - stats.byProtocol[proxy.protocol] = (stats.byProtocol[proxy.protocol] || 0) + 1; - }); - - return stats; - } - - clear(): void { - this.proxies = []; - this.currentIndex = 0; - } -} diff --git a/libs/services/proxy/test/proxy.test.ts b/libs/services/proxy/test/proxy.test.ts deleted file mode 100644 index 9963be77..00000000 --- a/libs/services/proxy/test/proxy.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import { SimpleProxyManager } from '../src/simple-proxy-manager'; -import type { ProxyInfo } from '../src/types'; - -describe('ProxyManager', () => { - let manager: SimpleProxyManager; - - const getMockProxies = (): ProxyInfo[] => [ - { - id: 'proxy1', - host: '1.2.3.4', - port: 8080, - protocol: 'http', - username: 'user1', - password: 'pass1', - active: true, - }, - { - id: 'proxy2', - host: '5.6.7.8', - port: 8080, - protocol: 'http', - username: 'user2', - password: 'pass2', - active: true, - }, - { - id: 'proxy3', - host: '9.10.11.12', - port: 8080, - protocol: 'socks5', - active: false, - }, - ]; - - beforeEach(() => { - manager = new SimpleProxyManager(); - }); - - describe('proxy management', () => { - it('should add proxies', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - manager.addProxy(mockProxies[1]); - - const proxies = manager.getProxies(); - expect(proxies).toHaveLength(2); - expect(proxies[0].id).toBe('proxy1'); - expect(proxies[1].id).toBe('proxy2'); - }); - - it('should remove proxy by id', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - manager.addProxy(mockProxies[1]); - - manager.removeProxy('proxy1'); - - const proxies = manager.getProxies(); - expect(proxies).toHaveLength(1); - expect(proxies[0].id).toBe('proxy2'); - }); - - it('should update proxy status', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - - manager.updateProxyStatus('proxy1', false); - - const proxies = manager.getProxies(); - expect(proxies[0].active).toBe(false); - }); - - it('should get only active proxies', () => { - const mockProxies = getMockProxies(); - mockProxies.forEach(proxy => manager.addProxy(proxy)); - - const activeProxies = manager.getActiveProxies(); - - expect(activeProxies).toHaveLength(2); - expect(activeProxies.every(p => p.active)).toBe(true); - }); - }); - - describe('proxy rotation', () => { - it('should rotate through proxies', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - manager.addProxy(mockProxies[1]); - - const proxy1 = manager.getNextProxy(); - const proxy2 = manager.getNextProxy(); - const proxy3 = manager.getNextProxy(); - - expect(proxy1?.id).toBe('proxy1'); - expect(proxy2?.id).toBe('proxy2'); - expect(proxy3?.id).toBe('proxy1'); // Back to first - }); - - it('should skip inactive proxies', () => { - const mockProxies = getMockProxies(); - mockProxies.forEach(proxy => manager.addProxy(proxy)); - - const proxy1 = manager.getNextProxy(); - const proxy2 = manager.getNextProxy(); - const proxy3 = manager.getNextProxy(); - - expect(proxy1?.id).toBe('proxy1'); - expect(proxy2?.id).toBe('proxy2'); - expect(proxy3?.id).toBe('proxy1'); // Skips proxy3 (inactive) - }); - - it('should return null when no active proxies', () => { - const mockProxies = getMockProxies(); - manager.addProxy({ ...mockProxies[0], active: false }); - - const proxy = manager.getNextProxy(); - - expect(proxy).toBeNull(); - }); - }); - - describe('proxy configuration', () => { - it('should get proxy config for HTTP proxy', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - const proxy = manager.getNextProxy(); - - const config = manager.getProxyConfig(proxy!); - - expect(config).toEqual({ - protocol: 'http', - host: '1.2.3.4', - port: 8080, - auth: { - username: 'user1', - password: 'pass1', - }, - }); - }); - - it('should get proxy config without auth', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[2]); - manager.updateProxyStatus('proxy3', true); // Make it active - const proxy = manager.getNextProxy(); - - const config = manager.getProxyConfig(proxy!); - - expect(config).toEqual({ - protocol: 'socks5', - host: '9.10.11.12', - port: 8080, - }); - }); - - it('should format proxy URL', () => { - const mockProxies = getMockProxies(); - const url1 = manager.formatProxyUrl(mockProxies[0]); - expect(url1).toBe('http://user1:pass1@1.2.3.4:8080'); - - const url2 = manager.formatProxyUrl(mockProxies[2]); - expect(url2).toBe('socks5://9.10.11.12:8080'); - }); - }); - - describe('proxy validation', () => { - it('should validate proxy connectivity', async () => { - const mockProxies = getMockProxies(); - // Mock fetch for validation - const mockFetch = mock(() => Promise.resolve({ ok: true })); - global.fetch = mockFetch as any; - - manager.addProxy(mockProxies[0]); - - const isValid = await manager.validateProxy('proxy1'); - - expect(mockFetch).toHaveBeenCalled(); - expect(isValid).toBe(true); - }); - - it('should handle validation failure', async () => { - const mockProxies = getMockProxies(); - const mockFetch = mock(() => Promise.reject(new Error('Connection failed'))); - global.fetch = mockFetch as any; - - manager.addProxy(mockProxies[0]); - - const isValid = await manager.validateProxy('proxy1'); - - expect(isValid).toBe(false); - }); - - it('should validate all proxies', async () => { - const mockProxies = getMockProxies(); - - // Mock fetch to return different results for each proxy - let callCount = 0; - const mockFetch = mock(() => { - callCount++; - // First call succeeds, second fails - if (callCount === 1) { - return Promise.resolve({ ok: true }); - } else { - return Promise.reject(new Error('Failed')); - } - }); - global.fetch = mockFetch as any; - - manager.addProxy(mockProxies[0]); - manager.addProxy(mockProxies[1]); - - const results = await manager.validateAllProxies(); - - expect(results['proxy1']).toBe(true); - expect(results['proxy2']).toBe(false); - - // Should disable failed proxy - const activeProxies = manager.getActiveProxies(); - expect(activeProxies).toHaveLength(1); - expect(activeProxies[0].id).toBe('proxy1'); - }); - }); - - describe('statistics', () => { - it('should track proxy statistics', () => { - const mockProxies = getMockProxies(); - mockProxies.forEach(proxy => manager.addProxy(proxy)); - - const stats = manager.getStatistics(); - - expect(stats).toEqual({ - total: 3, - active: 2, - inactive: 1, - byProtocol: { - http: 2, - socks5: 1, - }, - }); - }); - - it('should clear all proxies', () => { - const mockProxies = getMockProxies(); - manager.addProxy(mockProxies[0]); - manager.addProxy(mockProxies[1]); - - manager.clear(); - - const proxies = manager.getProxies(); - expect(proxies).toHaveLength(0); - }); - }); -}); diff --git a/libs/trading-runtime/src/paper-operator.ts b/libs/trading-runtime/src/paper-operator.ts index 4ea511d1..d9cb35f7 100644 --- a/libs/trading-runtime/src/paper-operator.ts +++ b/libs/trading-runtime/src/paper-operator.ts @@ -1,4 +1,4 @@ -import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import { getCredentialHttpPrincipal } from '@stock-bot/di/http-security'; import { PaperDeploymentError } from './paper-deployment-custody'; /** Defense in depth for both public services, including bearer requests carrying browser Origin. */ diff --git a/libs/utils/README.md b/libs/utils/README.md index d685e90b..75c6ebd8 100644 --- a/libs/utils/README.md +++ b/libs/utils/README.md @@ -1,23 +1,15 @@ # General utilities -`@stock-bot/utils` is a private workspace package for infrastructure-neutral general -helpers. Financial/feature calculations belong to `@stock-bot/calculations`, not here. +`@stock-bot/utils` is a private workspace package for infrastructure-neutral HTTP and +user-agent helpers. Financial/feature calculations belong to +[`@stock-bot/calculations`](../calculations/README.md), not here. ## Supported capabilities - `@stock-bot/utils/fetch`: `fetch` and the type-only `FetchOptions`. - `@stock-bot/utils/user-agent`: `getRandomUserAgent` selects from a fixed local list. -- `@stock-bot/utils/common`: `createProxyUrl` encodes proxy credentials; `sleep` - returns a timer-backed promise. -- `@stock-bot/utils/dates`: `utcDates` supplies `isWeekday`, `nextWeekday`, - `previousWeekday`, strict `parseDate` (`YYYY-MM-DD`) and `formatDate`. - -The root explicitly exports these six runtime values (`fetch`, `getRandomUserAgent`, -`createProxyUrl`, `sleep`, `utcDates`, `dateUtils`) plus the `FetchOptions` type. -Capability subpaths avoid loading unrelated helpers. There are no wildcard/deep exports. ```ts -import { utcDates } from '@stock-bot/utils/dates'; import { fetch, type FetchOptions } from '@stock-bot/utils/fetch'; import { getRandomUserAgent } from '@stock-bot/utils/user-agent'; @@ -26,54 +18,16 @@ const options: FetchOptions = { timeout: 5_000, }; const response = await fetch('https://example.com/data', options); -const next = utcDates.nextWeekday(utcDates.parseDate('2024-03-08')); ``` -Fetch keeps its existing logging, Bun proxy, timeout and original-`Response` behavior. -Non-OK statuses are returned, not thrown. Timeout cancellation and caller cancellation -are not composed: a configured timeout currently replaces the supplied signal. The -user-agent list is not fingerprinting or a guarantee of provider access. - -Date arithmetic is explicitly UTC, validates inputs and does not mutate the supplied -date. Weekdays are **not** exchange sessions: holidays, exchange time zones and trading -hours are not modeled. The deprecated `dateUtils` names (`isTradingDay`, -`getNextTradingDay`, `getPreviousTradingDay`, `formatDate`, `parseDate`) remain -as aliases for migration, not as verified trading-calendar APIs. This replaces the old -environment-dependent local weekday arithmetic; use `utcDates` in new code. - -`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike` -from `@stock-bot/logger` is type-only. No databases, configuration initialization, -application service containers or mandatory native bindings may be added here. - -## Calculation migration and removals - -The financial modules and OHLCV helpers were **relocated/preserved**, not discarded: - -- Reviewed returns/analytics/window math and OHLCV processing: - `@stock-bot/calculations` and its explicit capability subpaths. -- All 105 formerly active calculation functions with their original bodies: - `@stock-bot/calculations/legacy`, an opt-in historical API, not reviewed core. -- All seven disabled numerical/indicator prototypes: - non-executable source-verified snapshots in `libs/calculations/research/`. - -See [the calculation contract](../calculations/README.md) and -[the complete cleanup audit](../../docs/cleanup-audit.md) for readiness, preserved test -scenarios and deliberate removals. The empty `analyzePortfolio` placeholder remains -removed because it calculated nothing. - -Import assertions directly from `@stock-bot/invariants`; the redundant utility assertion -facade was removed, not its functionality. Import domain types from `@stock-bot/types`. -No finance compatibility re-export is added to the general utility package. +`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike` from +`@stock-bot/logger` is type-only. Import assertions directly from `@stock-bot/invariants` +and domain types from `@stock-bot/types`. ## Verify -From the repository root: - ```sh bun run test:utils bun run test:calculations bun run check ``` - -The root gate includes general-utility and handler HTTP-consumer tests, calculation -regressions and architecture checks for the explicit APIs and dependency boundaries. diff --git a/libs/utils/package.json b/libs/utils/package.json index d8d3dfd9..5e5a7f40 100644 --- a/libs/utils/package.json +++ b/libs/utils/package.json @@ -22,8 +22,6 @@ "exports": { ".": "./src/index.ts", "./fetch": "./src/fetch.ts", - "./user-agent": "./src/user-agent.ts", - "./common": "./src/common.ts", - "./dates": "./src/dateUtils.ts" + "./user-agent": "./src/user-agent.ts" } } diff --git a/libs/utils/src/common.ts b/libs/utils/src/common.ts deleted file mode 100644 index 48d7601b..00000000 --- a/libs/utils/src/common.ts +++ /dev/null @@ -1,17 +0,0 @@ -export function createProxyUrl(proxy: { - protocol: string; - host: string; - port: number; - username?: string; - password?: string; -}): string { - const { protocol, host, port, username, password } = proxy; - if (username && password) { - return `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`; - } - return `${protocol}://${host}:${port}`; -} - -export function sleep(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)); -} diff --git a/libs/utils/src/dateUtils.ts b/libs/utils/src/dateUtils.ts deleted file mode 100644 index d7e5e008..00000000 --- a/libs/utils/src/dateUtils.ts +++ /dev/null @@ -1,48 +0,0 @@ -function valid(date: Date): Date { - if (!Number.isFinite(date.getTime())) { - throw new RangeError('Invalid UTC date'); - } - return date; -} - -/** Weekdays in UTC, NOT an exchange calendar: holidays and venue sessions are not modeled. */ -function isWeekday(date: Date): boolean { - const day = valid(date).getUTCDay(); - return day > 0 && day < 6; -} - -function shiftWeekday(date: Date, direction: 1 | -1): Date { - const result = new Date(valid(date).getTime()); - do { - result.setUTCDate(result.getUTCDate() + direction); - } while (!isWeekday(result)); - return result; -} - -function parseDate(value: string): Date { - if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) { - throw new RangeError('Expected YYYY-MM-DD'); - } - const date = valid(new Date(`${value}T00:00:00.000Z`)); - if (date.toISOString().slice(0, 10) !== value) { - throw new RangeError('Invalid calendar date'); - } - return date; -} - -export const utcDates = { - isWeekday, - nextWeekday: (date: Date): Date => shiftWeekday(date, 1), - previousWeekday: (date: Date): Date => shiftWeekday(date, -1), - formatDate: (date: Date): string => valid(date).toISOString().slice(0, 10), - parseDate, -}; - -/** @deprecated Compatibility names only. These are UTC weekdays, never verified trading sessions. */ -export const dateUtils = { - isTradingDay: utcDates.isWeekday, - getNextTradingDay: utcDates.nextWeekday, - getPreviousTradingDay: utcDates.previousWeekday, - formatDate: utcDates.formatDate, - parseDate: utcDates.parseDate, -}; diff --git a/libs/utils/src/index.ts b/libs/utils/src/index.ts index 08241eed..090cc3ae 100644 --- a/libs/utils/src/index.ts +++ b/libs/utils/src/index.ts @@ -1,5 +1,3 @@ export { fetch } from './fetch'; export type { FetchOptions } from './fetch'; export { getRandomUserAgent } from './user-agent'; -export { createProxyUrl, sleep } from './common'; -export { dateUtils, utcDates } from './dateUtils'; diff --git a/libs/utils/test/common-dates.test.ts b/libs/utils/test/common-dates.test.ts deleted file mode 100644 index e1accce7..00000000 --- a/libs/utils/test/common-dates.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { createProxyUrl, sleep } from '@stock-bot/utils/common'; -import { dateUtils, utcDates } from '@stock-bot/utils/dates'; - -describe('restored general utilities', () => { - describe('common utilities', () => { - it('should create proxy URL with auth', () => { - const proxy = { - protocol: 'http', - host: '192.168.1.1', - port: 8080, - username: 'user', - password: 'pass', - }; - - const url = createProxyUrl(proxy); - expect(url).toBe('http://user:pass@192.168.1.1:8080'); - }); - - it('should create proxy URL without auth', () => { - const proxy = { - protocol: 'socks5', - host: '192.168.1.1', - port: 1080, - }; - - const url = createProxyUrl(proxy); - expect(url).toBe('socks5://192.168.1.1:1080'); - }); - - it('should sleep for specified milliseconds', async () => { - const start = Date.now(); - await sleep(100); - const elapsed = Date.now() - start; - - expect(elapsed).toBeGreaterThanOrEqual(90); - }); - - it('UTC weekday helpers preserve the supplied instant time and never mutate inputs', () => { - const friday = new Date('2024-03-08T23:30:00.000Z'); - expect(utcDates.nextWeekday(friday).toISOString()).toBe('2024-03-11T23:30:00.000Z'); - expect(friday.toISOString()).toBe('2024-03-08T23:30:00.000Z'); - expect(utcDates.previousWeekday(new Date('2024-03-11T23:30:00Z')).toISOString()).toBe( - '2024-03-08T23:30:00.000Z' - ); - // Christmas is a weekday, not a promise that any particular exchange is open. - expect(utcDates.isWeekday(new Date('2023-12-25T00:00:00Z'))).toBe(true); - const detached = utcDates.nextWeekday; - expect(detached(friday).getUTCDay()).toBe(1); - }); - - it('strict UTC dates reject invalid inputs and impossible calendar dates', () => { - expect(utcDates.parseDate('2024-02-29').toISOString()).toBe('2024-02-29T00:00:00.000Z'); - for (const value of ['2023-02-29', '2024-02-30', '2024-13-01', '2024-01-01T00:00:00Z', '']) { - expect(() => utcDates.parseDate(value)).toThrow(); - } - expect(() => utcDates.nextWeekday(new Date(NaN))).toThrow(); - expect(() => utcDates.formatDate(new Date(NaN))).toThrow(); - }); - - it('proxy credentials remain encoded and sleep remains asynchronous', async () => { - expect( - createProxyUrl({ - protocol: 'http', - host: 'localhost', - port: 8080, - username: 'a@b', - password: 'p:/?', - }) - ).toBe('http://a%40b:p%3A%2F%3F@localhost:8080'); - const wait = sleep(0); - expect(wait).toBeInstanceOf(Promise); - await wait; - }); - }); - - describe('date utilities', () => { - it('should check if date is trading day', () => { - const monday = new Date('2023-12-25'); // Monday - const saturday = new Date('2023-12-23'); // Saturday - const sunday = new Date('2023-12-24'); // Sunday - - expect(dateUtils.isTradingDay(monday)).toBe(true); - expect(dateUtils.isTradingDay(saturday)).toBe(false); - expect(dateUtils.isTradingDay(sunday)).toBe(false); - }); - - it('should get next trading day', () => { - const friday = new Date('2023-12-22'); // Friday - const nextDay = dateUtils.getNextTradingDay(friday); - - expect(nextDay.getUTCDay()).toBe(1); // Monday - }); - - it('should get previous trading day', () => { - const monday = new Date('2023-12-25'); // Monday - const prevDay = dateUtils.getPreviousTradingDay(monday); - - expect(prevDay.getUTCDay()).toBe(5); // Friday - }); - - it('should format date as YYYY-MM-DD', () => { - const date = new Date('2023-12-25T10:30:00Z'); - const formatted = dateUtils.formatDate(date); - - expect(formatted).toBe('2023-12-25'); - }); - - it('should parse date from string', () => { - const date = dateUtils.parseDate('2023-12-25'); - - expect(date.getUTCFullYear()).toBe(2023); - expect(date.getUTCMonth()).toBe(11); // 0-based - expect(date.getUTCDate()).toBe(25); - }); - }); -}); diff --git a/monitoring/prometheus.yml b/monitoring/prometheus.yml deleted file mode 100644 index 4bb976a0..00000000 --- a/monitoring/prometheus.yml +++ /dev/null @@ -1,45 +0,0 @@ -global: - scrape_interval: 15s - evaluation_interval: 15s - -rule_files: - # - "first_rules.yml" - # - "second_rules.yml" - -scrape_configs: - # Prometheus itself - - job_name: 'prometheus' - static_configs: - - targets: ['localhost:9090'] - - # Trading Bot Services - - job_name: 'market-data-gateway' - static_configs: - - targets: ['host.docker.internal:3001'] - metrics_path: '/metrics' - scrape_interval: 5s - - - job_name: 'strategy-orchestrator' - static_configs: - - targets: ['host.docker.internal:4001'] - metrics_path: '/metrics' - scrape_interval: 10s - - - job_name: 'risk-guardian' - static_configs: - - targets: ['host.docker.internal:3002'] - metrics_path: '/metrics' - scrape_interval: 10s - - # Infrastructure - - job_name: 'dragonfly' - static_configs: - - targets: ['dragonfly:6379'] - - - job_name: 'postgres' - static_configs: - - targets: ['postgres:5432'] - - - job_name: 'questdb' - static_configs: - - targets: ['questdb:9000'] diff --git a/package.json b/package.json index 083b52e4..432c33c1 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "test:utils": "bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts", "test:calculations": "bun test libs/calculations/test/", "test:contracts": "tsc --project tsconfig.contracts.json --noEmit", - "test": "turbo run test --filter=!@stock-bot/stock-app", + "test": "turbo run test", "test:watch": "bun test --watch", "test:coverage": "bun test --coverage", "coverage": "bun run tools/coverage-cli/src/index.ts --reporters html markdown", @@ -27,7 +27,6 @@ "test:integration": "bun test test/integration/", "test:native": "cargo test -p engine --lib --offline", "test:postgres": "bun run scripts/test-postgres.ts", - "test:analytics-api": "uv run --no-project --with fastapi==0.104.1 --with httpx==0.25.2 --with pydantic==2.5.0 python -m unittest discover -s apps/stock/analytics/test", "audit:secrets": "bun run scripts/audit-secrets.ts", "test:e2e": "bun run scripts/test-e2e.ts", "test:e2e:install": "playwright install chromium", @@ -70,15 +69,14 @@ "infra:reset": "./scripts/docker.sh reset --dev", "infra:qa:up": "./scripts/docker.sh start --qa", "infra:qa:status": "./scripts/docker.sh status --qa", - "dev:full": "npm run infra:up && npm run docker:admin && turbo run dev", - "dev:clean": "npm run infra:reset && npm run dev:full" + "dev:full": "bun run infra:up && turbo run dev", + "dev:clean": "bun run infra:reset && bun run dev:full" }, "workspaces": [ "libs/*", "libs/core/*", "libs/data/*", "libs/services/*", - "apps/stock", "apps/stock/config", "apps/stock/data-ingestion", "apps/stock/data-pipeline", @@ -91,33 +89,18 @@ "devDependencies": { "@eslint/js": "^9.28.0", "@ianvs/prettier-plugin-sort-imports": "^4.4.2", - "@modelcontextprotocol/server-postgres": "^0.6.2", - "@testcontainers/mongodb": "^10.7.2", - "@testcontainers/postgresql": "^10.7.2", "@types/bun": "^1.2.17", "@types/pako": "^2.0.4", - "@types/supertest": "^6.0.2", - "@types/yup": "^0.32.0", "@typescript-eslint/eslint-plugin": "^8.34.0", "@typescript-eslint/parser": "^8.34.0", "bun-types": "^1.2.15", "eslint": "^9.28.0", - "eslint-plugin-import": "^2.31.0", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-promise": "^7.2.1", - "knip": "^5.61.2", "mongodb": "^6.17.0", - "mongodb-mcp-server": "^0.1.1", - "mongodb-memory-server": "^9.1.6", "pg-mem": "^2.8.1", "playwright": "1.53.2", "prettier": "^3.5.3", - "supertest": "^6.3.4", - "ts-unused-exports": "^11.0.1", - "tsx": "^4.20.3", "turbo": "^2.5.4", - "typescript": "^5.8.3", - "yup": "^1.6.1" + "typescript": "^5.8.3" }, "packageManager": "bun@1.2.17", "engines": { @@ -132,7 +115,6 @@ "trustedDependencies": [ "@tailwindcss/oxide", "esbuild", - "mongodb", - "mongodb-memory-server" + "mongodb" ] } diff --git a/proxy-playwrite.ts b/proxy-playwrite.ts deleted file mode 100644 index 73be73bd..00000000 --- a/proxy-playwrite.ts +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/bin/env bun -/** - * Quick test tool to open Playwright in non-headless mode with proxy - * For debugging and manual testing of the IB website - */ -import { Browser } from '@stock-bot/browser'; - -async function testProxyBrowser() { - try { - console.log('๐Ÿš€ Starting proxy browser test...'); - - // Initialize browser in non-headless mode - await Browser.initialize({ - headless: false, // Non-headless for debugging - timeout: 30000, // 30 second timeout - blockResources: false, // Allow all resources - }); - console.log('โœ… Browser initialized in non-headless mode'); - - // Create page with your proxy - const { page } = await Browser.createPageWithProxy( - 'https://www.interactivebrokers.com/en/trading/products-exchanges.php#/', - 'http://doimvbnb-US-rotate:w5fpiwrb9895@p.webshare.io:80' - ); - console.log('โœ… Page created with proxy'); - - // Set up network event logging to see what's happening - page.onNetworkEvent(event => { - if (event.type === 'request') { - console.log('๐Ÿ“ค Request:', { - url: event.url, - method: event.method, - data: event.requestData, - headers: Object.keys(event.headers || {}).length, - }); - } - - if (event.type === 'response') { - console.log('๐Ÿ“ฅ Response:', { - url: event.url, - status: event.status, - }); - } - }); - - console.log('โณ Waiting for page load...'); - await page.waitForLoadState('domcontentloaded', { timeout: 30000 }); - console.log('โœ… Page loaded - you can now interact with it manually'); - - // Log current URL - const currentUrl = page.url(); - console.log('๐ŸŒ Current URL:', currentUrl); - - // Keep the browser open for manual testing - console.log('๐Ÿ” Browser is open for manual testing...'); - console.log('๐Ÿ’ก You can now:'); - console.log(' - Click around the page manually'); - console.log(' - Check if the proxy is working'); - console.log(' - Test the Products tab and radio buttons'); - console.log(' - Press Ctrl+C to close when done'); - - // Wait indefinitely until user closes - await new Promise(resolve => { - process.on('SIGINT', () => { - console.log('๐Ÿ‘‹ Closing browser...'); - resolve(void 0); - }); - }); - } catch (error) { - console.error('โŒ Proxy browser test failed:', { error }); - } finally { - try { - await Browser.close(); - console.log('๐Ÿงน Browser cleanup completed'); - } catch (cleanupError) { - console.error('Failed to cleanup browser:', { error: cleanupError }); - } - } -} - -// Run the test -if (import.meta.main) { - testProxyBrowser().catch(console.error); -} - -export { testProxyBrowser }; diff --git a/scripts/benchmark-candidate-isolation.ts b/scripts/benchmark-candidate-isolation.ts index 49fcfec7..ca0c6dd1 100644 --- a/scripts/benchmark-candidate-isolation.ts +++ b/scripts/benchmark-candidate-isolation.ts @@ -7,7 +7,7 @@ import { IsolatedCandidateController, readCandidateExecution, } from '../apps/stock/orchestrator/src/backtest/candidate-sandbox'; -import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { NativeReplaySession, prepareReplayLoad, diff --git a/scripts/benchmark-execution.ts b/scripts/benchmark-execution.ts deleted file mode 100644 index 53fc5e0f..00000000 --- a/scripts/benchmark-execution.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** Local, deterministic workload; no native engine, database, network or trading credentials. */ -import { defaultRiskLimits, type Account } from '../apps/stock/orchestrator/src/execution/model'; -import { BacktestExecutionRepository } from '../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; - -const account: Account = { - initialCapital: 10000, - cash: 10000, - realizedPnl: 0, - dailyPnl: 0, - day: '2024-01-01', - commission: 0.001, - slippage: 0, - limits: { ...defaultRiskLimits }, - maxQuoteAgeMs: 60000, - positions: {}, - quotes: {}, - strategyPositions: {}, -}; - -for (const history of [0, 1000, 10000]) { - const repository = new BacktestExecutionRepository(); - await repository.initialize('benchmark', account); - await repository.transact('benchmark', async tx => { - for (let i = 0; i < history; i++) { - await tx.appendJournal({ - kind: 'market', - market: { - type: 'trade', - eventId: String(i), - data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: i }, - }, - recipients: [], - account, - }); - } - }); - const start = performance.now(); - for (let i = 0; i < 200; i++) { - await repository.transact('benchmark', async tx => ({ - cash: tx.account.cash, - next: await tx.nextJournal(history), - })); - } - process.stdout.write( - `${history} journal events: ${((performance.now() - start) / 200).toFixed(3)} ms/transaction\n` - ); -} diff --git a/scripts/benchmark-replay.ts b/scripts/benchmark-replay.ts index 04a579cf..8b2bd296 100644 --- a/scripts/benchmark-replay.ts +++ b/scripts/benchmark-replay.ts @@ -6,7 +6,7 @@ import type { ReplayOutput, ReplayProjectionResult, ReplayResultFormat, -} from '../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; export const replayProfiles = ['none', 'sparse', 'turnover'] as const; export type ReplayProfile = (typeof replayProfiles)[number]; diff --git a/scripts/benchmark-research-pool.ts b/scripts/benchmark-research-pool.ts index e8579af3..30519dcd 100644 --- a/scripts/benchmark-research-pool.ts +++ b/scripts/benchmark-research-pool.ts @@ -6,7 +6,7 @@ import { cpus, freemem, platform, release, totalmem } from 'node:os'; import { resolve } from 'node:path'; import { defined } from '@stock-bot/invariants'; import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; -import { readCanonicalBuildIdentity } from '../apps/stock/orchestrator/src/backtest/canonical-build'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import type { ResearchConcurrency } from '../apps/stock/orchestrator/src/backtest/ResearchBacktestPool'; import { canonicalReproductionHash } from '../apps/stock/web-api/src/services/reproduction-comparison'; import { nativeReplayFixture } from '../test/fixtures/native-replay'; diff --git a/scripts/benchmark-sma.ts b/scripts/benchmark-sma.ts index c55439e7..68dcbcd4 100644 --- a/scripts/benchmark-sma.ts +++ b/scripts/benchmark-sma.ts @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'; import { loadavg } from 'node:os'; import { join } from 'node:path'; -import type { ReplayOutput, ReplayProjectionResult } from '../apps/stock/orchestrator/src/contracts/native-replay'; +import type { ReplayOutput, ReplayProjectionResult } from '@stock-bot/stock-config/canonical-replay'; import type { FinancialStrategyDecision } from '@stock-bot/types'; type Mode = 'sma' | 'recorded'; @@ -29,7 +29,7 @@ export async function smaChild(root: string, workload: SmaWorkload, mode: Mode) const importsStart = performance.now(); const { nativeReplayFixture } = await import('../test/fixtures/native-replay'); const { validateDatasetV2 } = await import('../apps/stock/orchestrator/src/data/historical-dataset-v2'); - const { builtinStrategySelectionSchema } = await import('../apps/stock/orchestrator/src/contracts/builtin-strategy'); + const { builtinStrategySelectionSchema } = await import('@stock-bot/stock-config/strategy'); const { createBuiltinStrategy, validateBuiltinStrategyBindings } = await import('../apps/stock/orchestrator/src/strategies/canonical-builtins'); const { prepareReplayLoad, NativeReplaySession, runReplaySession } = await import('../apps/stock/orchestrator/src/backtest/native-replay'); const { runStrategyReplay } = await import('../apps/stock/orchestrator/src/backtest/strategy-runtime'); diff --git a/scripts/build-all.sh b/scripts/build-all.sh index 374c3a28..f487084e 100755 --- a/scripts/build-all.sh +++ b/scripts/build-all.sh @@ -19,6 +19,4 @@ for option in "$@"; do esac done -# The stock-app package contains convenience commands, not buildable source. -# Select all leaf workspaces so nested stock services are actually built. -exec bun run turbo run build --filter='!@stock-bot/stock-app' "${args[@]}" +exec bun run turbo run build "${args[@]}" diff --git a/scripts/build-clean.sh b/scripts/build-clean.sh deleted file mode 100755 index 617e27a1..00000000 --- a/scripts/build-clean.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/bash - -# Build Clean Script for Stock Bot -# Clean previous builds then build everything fresh - -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -CYAN='\033[0;36m' -NC='\033[0m' # No Color - -echo -e "${CYAN}๐Ÿงน Clean Build Process Starting...${NC}" - -# Store original location -ORIGINAL_DIR=$(pwd) - -# Find git root directory -GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) -if [ $? -ne 0 ]; then - echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}" - exit 1 -fi - -cd "$GIT_ROOT" - -cleanup() { - cd "$ORIGINAL_DIR" -} - -# Set up cleanup on exit -trap cleanup EXIT - -# Step 1: Clean everything -echo -e "${YELLOW}๐Ÿ—‘๏ธ Cleaning previous builds...${NC}" -./scripts/clean.sh --dist --cache --tsbuildinfo -if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Clean failed${NC}" - exit 1 -fi - -# Step 2: Build everything fresh -echo -e "${GREEN}๐Ÿ—๏ธ Building everything fresh...${NC}" -./scripts/build-all.sh -if [ $? -ne 0 ]; then - echo -e "${RED}โŒ Build failed${NC}" - exit 1 -fi - -echo -e "${GREEN}โœ… Clean build completed successfully!${NC}" -echo -e "${CYAN}๐Ÿš€ Project is ready for deployment.${NC}" diff --git a/scripts/build-libs-turbo.sh b/scripts/build-libs-turbo.sh deleted file mode 100644 index 41afef13..00000000 --- a/scripts/build-libs-turbo.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - -# Build libraries using Turbo instead of direct commands -# This leverages Turbo's caching and dependency management - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -CYAN='\033[0;36m' -NC='\033[0m' # No Color - -echo -e "${CYAN}Building libraries using Turborepo...${NC}" - -# Store original location -ORIGINAL_DIR=$(pwd) - -# Find git root directory -GIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null) -if [ $? -ne 0 ]; then - echo -e "${RED}Error: Not in a git repository. Please run this script from within the stock-bot git repository.${NC}" - exit 1 -fi - -cd "$GIT_ROOT" - -cleanup() { - cd "$ORIGINAL_DIR" -} - -# Set up cleanup on exit -trap cleanup EXIT - -# Build all libraries using turbo -echo -e "${GREEN}Building all libraries at once with Turborepo...${NC}" -npx turbo build --filter="./libs/*" - -if [ $? -ne 0 ]; then - echo -e "${RED}Failed to build libraries with Turborepo. Exiting.${NC}" - exit 1 -else - echo -e "${GREEN}All libraries built successfully!${NC}" -fi - -cd "$GIT_ROOT" diff --git a/scripts/docker.sh b/scripts/docker.sh index 4b166c39..07d331cd 100755 --- a/scripts/docker.sh +++ b/scripts/docker.sh @@ -3,6 +3,10 @@ # Trading Bot Docker Management Script (dev / qa / prod) set -euo pipefail +# Ensure top-level `name:` in each docker-compose*.yml (stock-bot-dev vs stock-bot vs stock-bot-prod) +# is never overridden by COMPOSE_PROJECT_NAME in .env or caller shell environment. +unset COMPOSE_PROJECT_NAME + RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' diff --git a/scripts/get-redis-connections.ts b/scripts/get-redis-connections.ts deleted file mode 100644 index 35f98711..00000000 --- a/scripts/get-redis-connections.ts +++ /dev/null @@ -1,368 +0,0 @@ -#!/usr/bin/env bun -/** - * Redis/Dragonfly Connection Monitor - Simplified Version - * - * Shows active connections grouped by client name with basic stats - * - * Usage: - * bun run scripts/get-redis-connections.ts # Show connections once - * bun run scripts/get-redis-connections.ts --monitor # Monitor in real-time - */ - -import Redis from 'ioredis'; - -interface ClientInfo { - id: string; - name?: string; - addr: string; - age: string; - idle: string; - cmd: string; - tot?: string; - fd?: string; - flags?: string; - db?: string; - sub?: string; - psub?: string; - multi?: string; - qbuf?: string; - qbufFree?: string; - obl?: string; - oll?: string; - omem?: string; - events?: string; - [key: string]: string | undefined; // Index signature for dynamic properties -} - -interface GroupedConnections { - [clientName: string]: { - count: number; - connections: ClientInfo[]; - totalCommands: number; - avgIdleTime: number; - }; -} - -class RedisConnectionMonitor { - private redis: Redis; - - constructor() { - this.redis = new Redis({ - host: process.env.DRAGONFLY_HOST || 'localhost', - port: parseInt(process.env.DRAGONFLY_PORT || '6379'), - password: process.env.DRAGONFLY_PASSWORD || undefined, - db: parseInt(process.env.DRAGONFLY_DATABASE || '0'), - maxRetriesPerRequest: 3, - connectTimeout: 10000, - lazyConnect: true, - }); - } - - /** - * Parse CLIENT LIST output into structured data - */ - private parseClientList(clientListOutput: string): ClientInfo[] { - const lines = clientListOutput.trim().split('\n'); - const clients: ClientInfo[] = []; - - for (const line of lines) { - if (!line.trim()) continue; - - const client: ClientInfo = { - id: '', - addr: '', - age: '', - idle: '', - cmd: '', - }; - - // Parse key=value pairs - const pairs = line.split(' '); - for (const pair of pairs) { - const [key, value] = pair.split('='); - if (key && value !== undefined) { - client[key] = value; - } - } - - clients.push(client); - } - - return clients; - } - - /** - * Clean up client names by removing timestamp/number suffixes - */ - private cleanClientName(rawName: string): string { - if (!rawName || rawName === 'unnamed') { - return rawName; - } - - // Remove timestamp/number suffixes (like BATCH-PROCESSOR-1749573709724) - // Pattern: Remove dash followed by numbers at the end - let cleanName = rawName.replace(/-\d+$/, ''); - - // Also handle patterns like NAME---1-1- (RedisInsight style) - cleanName = cleanName.replace(/---\d+-\d+-?$/, ''); - - // Convert to a more readable format - cleanName = cleanName - .replace(/-/g, ' ') - .toLowerCase() - .replace(/\b\w/g, l => l.toUpperCase()); - - return cleanName; - } - - /** - * Group connections by client name/type - */ - private groupConnectionsByName(clients: ClientInfo[]): GroupedConnections { - const grouped: GroupedConnections = {}; - - for (const client of clients) { - // Determine client name - use 'name' field if set, otherwise infer from other properties - let clientName = client.name || 'unnamed'; - - // Clean up the client name by removing timestamps/numbers - if (clientName && clientName !== 'unnamed') { - clientName = this.cleanClientName(clientName); - } - - // If no name is set, try to infer from the connection characteristics - if (clientName === 'unnamed' || !clientName) { - if (client.flags?.includes('M')) { - clientName = 'Master Connection'; - } else if (client.flags?.includes('S')) { - clientName = 'Slave Connection'; - } else if (client.flags?.includes('P')) { - clientName = 'PubSub Connection'; - } else if (client.cmd === 'monitor') { - clientName = 'Monitor Connection'; - } else if (client.addr.includes('127.0.0.1') || client.addr.includes('localhost')) { - clientName = 'Local Client'; - } else if (client.addr.includes('172.') || client.addr.includes('192.168.')) { - clientName = 'Docker Network Client'; - } else { - clientName = `Client ${client.addr.split(':')[0]}`; - } - } - - if (!grouped[clientName]) { - grouped[clientName] = { - count: 0, - connections: [], - totalCommands: 0, - avgIdleTime: 0, - }; - } - - grouped[clientName].count++; - grouped[clientName].connections.push(client); - - // Parse command count if available - const cmdCount = client.tot ? parseInt(client.tot) : 0; - grouped[clientName].totalCommands += cmdCount; - } - - // Calculate average idle times - for (const groupName in grouped) { - const group = grouped[groupName]; - const totalIdle = group.connections.reduce((sum, client) => { - return sum + parseInt(client.idle || '0'); - }, 0); - group.avgIdleTime = group.count > 0 ? Math.round(totalIdle / group.count) : 0; - } - - return grouped; - } - - /** - * Format connection details for display - */ - private formatConnectionDetails(client: ClientInfo): string { - const details = [ - `ID: ${client.id}`, - `Address: ${client.addr}`, - `Age: ${client.age}s`, - `Idle: ${client.idle}s`, - ]; - - if (client.tot) { - details.push(`Total Commands: ${client.tot}`); - } - - return details.join(', '); - } - - /** - * Get and display all connections grouped by name - */ - async getConnectionsGroupedByName(): Promise { - try { - console.log('๐Ÿ” Connecting to Dragonfly...'); - - // Check if already connected, if not connect - if (this.redis.status !== 'ready') { - await this.redis.connect(); - } - - console.log('๐Ÿ“ก Fetching client connections...'); - const clientListOutput = await this.redis.client('LIST') as string; - - if (!clientListOutput) { - console.log('โŒ No client information available'); - return; - } - - const clients = this.parseClientList(clientListOutput); - const grouped = this.groupConnectionsByName(clients); - - // Get server and memory info first - const info = await this.redis.info('server'); - const memoryInfo = await this.redis.info('memory'); - - // Parse server info - const infoLines = info.split('\n'); - let version = '', uptime = '', connectedClients = ''; - for (const line of infoLines) { - if (line.includes('dragonfly_version')) version = line.split(':')[1]?.trim() || ''; - if (line.includes('uptime_in_seconds')) { - const seconds = parseInt(line.split(':')[1]?.trim() || '0'); - const days = Math.floor(seconds / 86400); - const hours = Math.floor((seconds % 86400) / 3600); - uptime = `${days}d ${hours}h`; - } - if (line.includes('connected_clients')) connectedClients = line.split(':')[1]?.trim() || ''; - } - - // Parse memory info - const memoryLines = memoryInfo.split('\n'); - let usedMemory = '', maxMemory = '', memoryPercent = ''; - for (const line of memoryLines) { - if (line.includes('used_memory_human')) usedMemory = line.split(':')[1]?.trim() || ''; - if (line.includes('maxmemory_human')) maxMemory = line.split(':')[1]?.trim() || ''; - if (line.includes('used_memory_percentage')) memoryPercent = line.split(':')[1]?.trim() || ''; - } - - console.log('\n๐ŸŽฏ DRAGONFLY CONNECTION SUMMARY'); - console.log('โ•'.repeat(60)); - console.log(`๐Ÿ”— Connections: ${clients.length} active (${Object.keys(grouped).length} groups) | ๐Ÿ–ฅ๏ธ Version: ${version} | โฑ๏ธ Uptime: ${uptime}`); - console.log(`๐Ÿ’พ Memory: ${usedMemory}${maxMemory ? ` / ${maxMemory}` : ''}${memoryPercent ? ` (${memoryPercent}%)` : ''}`); - console.log(''); - - // Sort groups by count (most connections first) - const sortedGroups = Object.entries(grouped).sort((a, b) => b[1].count - a[1].count); - - // Display grouped connections - for (const [groupName, group] of sortedGroups) { - console.log(`๐Ÿ“‚ ${groupName.toUpperCase()} (${group.count} connections, ${group.totalCommands} commands, ${group.avgIdleTime}s avg idle)`); - - for (const client of group.connections) { - console.log(` โ”œโ”€ ${this.formatConnectionDetails(client)}`); - } - } - - } catch (error) { - console.error('โŒ Error connecting to Dragonfly:', error); - console.log('\n๐Ÿ’ก Troubleshooting:'); - console.log(' - Make sure Dragonfly Docker container is running'); - console.log(' - Check if port 6379 is accessible'); - console.log(' - Verify environment variables if using custom connection settings'); - console.log(' - Run: docker ps | grep dragonfly'); - } finally { - // Only disconnect if we're not in monitoring mode - if (this.redis.status === 'ready') { - await this.redis.disconnect(); - } - } - } - - /** - * Monitor connections in real-time - */ - async monitorConnections(intervalSeconds: number = 5): Promise { - console.log(`๐Ÿ”„ Starting real-time monitoring (refresh every ${intervalSeconds}s)`); - console.log('Press Ctrl+C to stop...\n'); - - const monitor = async () => { - try { - console.clear(); - console.log(`๐Ÿ• Last updated: ${new Date().toLocaleTimeString()}\n`); - await this.getConnectionsGroupedByName(); - } catch (error) { - console.error('โŒ Monitoring error:', error); - console.log('Retrying in next interval...'); - } - }; - - // Initial run - await monitor(); - - // Set up interval - const interval = setInterval(monitor, intervalSeconds * 1000); - - // Handle graceful shutdown - process.on('SIGINT', async () => { - clearInterval(interval); - console.log('\n๐Ÿ‘‹ Monitoring stopped'); - await this.redis.disconnect(); - process.exit(0); - }); - } -} - -// Main execution -async function main() { - const args = process.argv.slice(2); - const monitor = new RedisConnectionMonitor(); - - if (args.includes('--monitor') || args.includes('-m')) { - const intervalArg = args.find(arg => arg.startsWith('--interval=')); - const interval = intervalArg ? parseInt(intervalArg.split('=')[1]) : 5; - await monitor.monitorConnections(interval); - } else { - await monitor.getConnectionsGroupedByName(); - } -} - -// Help text -if (process.argv.includes('--help') || process.argv.includes('-h')) { - console.log(` -๐Ÿ‰ Redis/Dragonfly Connection Monitor - -Usage: - bun run scripts/get-redis-connections.ts [options] - -Options: - --help, -h Show this help message - --monitor, -m Monitor connections in real-time - --interval=N Set monitoring refresh interval in seconds (default: 5) - -Examples: - bun run scripts/get-redis-connections.ts # One-time connection list - bun run scripts/get-redis-connections.ts --monitor # Real-time monitoring - bun run scripts/get-redis-connections.ts -m --interval=10 # Monitor every 10 seconds - -Environment Variables: - DRAGONFLY_HOST Dragonfly host (default: localhost) - DRAGONFLY_PORT Dragonfly port (default: 6379) - DRAGONFLY_PASSWORD Dragonfly password (if auth enabled) - DRAGONFLY_DATABASE Database number (default: 0) - -Features: - โœจ Groups connections by clean names (removes timestamp suffixes) - ๐Ÿ“Š Shows connection statistics and command counts - ๐Ÿ”„ Real-time monitoring mode available - ๐ŸŽจ Color-coded output with connection details -`); - process.exit(0); -} - -// Run the script -console.log('๐Ÿš€ Starting Redis connection monitor...'); -main().catch((error) => { - console.error('โŒ Script error:', error); - process.exit(1); -}); diff --git a/scripts/import-research-dataset.ts b/scripts/import-research-dataset.ts index 7889c4ec..df5a4557 100644 --- a/scripts/import-research-dataset.ts +++ b/scripts/import-research-dataset.ts @@ -2,9 +2,9 @@ import { readFile } from 'node:fs/promises'; import { Pool } from 'pg'; import { validateDatasetV2 } from '../apps/stock/orchestrator/src/data/historical-dataset-v2'; -import { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset'; +import { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset'; -export { retainResearchDataset } from '../apps/stock/orchestrator/src/data/retained-research-dataset'; +export { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset'; if (import.meta.main) { let database: Pool | undefined; diff --git a/scripts/populate-ib-exchanges.ts b/scripts/populate-ib-exchanges.ts deleted file mode 100644 index e69de29b..00000000 diff --git a/scripts/setup-playwright.sh b/scripts/setup-playwright.sh deleted file mode 100755 index 8a8bdc1d..00000000 --- a/scripts/setup-playwright.sh +++ /dev/null @@ -1,134 +0,0 @@ -#!/bin/bash - -# Playwright Setup Script for Stock Bot -# This script specifically handles Playwright installation and browser setup - -set -e - -# Colors -GREEN='\033[0;32m' -BLUE='\033[0;34m' -RED='\033[0;31m' -NC='\033[0m' - -log_info() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -log_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -log_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -# Check if we're in the project directory -check_project_directory() { - if [[ ! -f "package.json" ]]; then - log_error "Please run this script from the project root directory" - exit 1 - fi -} - -# Install Playwright dependencies -install_playwright_deps() { - log_info "Installing Playwright system dependencies..." - bunx playwright install-deps chromium - log_success "Playwright system dependencies installed" -} - -# Install Playwright browsers -install_browsers() { - log_info "Installing Playwright browsers..." - - # Install all browsers - bunx playwright install chromium - bunx playwright install firefox - bunx playwright install webkit - - log_success "All Playwright browsers installed" -} - -# Test Playwright installation -test_playwright() { - log_info "Testing Playwright installation..." - - # Create a simple test script - cat > /tmp/test-playwright.js << 'EOF' -const { chromium } = require('playwright'); - -(async () => { - try { - const browser = await chromium.launch({ headless: true }); - const page = await browser.newPage(); - await page.goto('https://example.com'); - const title = await page.title(); - console.log('โœ… Playwright test successful! Page title:', title); - await browser.close(); - } catch (error) { - console.error('โŒ Playwright test failed:', error.message); - process.exit(1); - } -})(); -EOF - - # Run the test - node /tmp/test-playwright.js - - # Clean up - rm /tmp/test-playwright.js - - log_success "Playwright test completed successfully" -} - -# Main function -main() { - log_info "Setting up Playwright for Stock Bot..." - - check_project_directory - install_playwright_deps - install_browsers - test_playwright - - log_success "Playwright setup completed!" - log_info "You can now run your browser automation scripts" -} - -# Show help -show_help() { - echo "Playwright Setup Script for Stock Bot" - echo "" - echo "Usage: $0 [OPTIONS]" - echo "" - echo "Options:" - echo " -h, --help Show this help message" - echo " --test-only Only run the Playwright test" - echo " --deps-only Only install system dependencies" - echo "" -} - -# Parse arguments -case "${1:-}" in - -h|--help) - show_help - exit 0 - ;; - --test-only) - check_project_directory - test_playwright - exit 0 - ;; - --deps-only) - install_playwright_deps - exit 0 - ;; - "") - main - ;; - *) - log_error "Unknown option: $1" - show_help - exit 1 - ;; -esac diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 6616468a..3e93e80f 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -76,8 +76,7 @@ describe('orchestrator architecture boundaries', () => { expect( path === 'types.ts' || path.startsWith('contracts/') || - path === 'backtest/native-worker-protocol.ts' || - path === 'backtest/canonical-result.ts' + path === 'backtest/native-worker-protocol.ts' ).toBe(true); for (const specifier of imports.get(file) ?? []) { expect( @@ -96,6 +95,7 @@ describe('orchestrator architecture boundaries', () => { '@stock-bot/calculations/analytics', '@stock-bot/calculations/returns', '@stock-bot/research/results', + '@stock-bot/research/strategy-api', ].includes(specifier) ).toBe(true); } @@ -173,52 +173,8 @@ describe('orchestrator architecture boundaries', () => { } }); - it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => { - for (const entry of [ - 'execution/SimulationExecution.ts', - 'execution/StrategyRecovery.ts', - 'execution/repository.ts', - 'execution/strategy-recovery.ts', - 'execution/model.ts', - ]) { - for (const file of reachable(join(root, entry))) { - expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data)\//); - expect(relative(root, file)).not.toMatch(/(Postgres|Backtest)ExecutionRepository/); - for (const specifier of imports.get(file) ?? []) { - expect( - ['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes( - specifier - ) - ).toBe(false); - } - } - } - expect(imports.get(join(root, 'execution/repository.ts'))).toEqual([]); - }); - - it('the strategy manager cannot select or directly import concrete strategies', () => { - const file = join(root, 'strategies/StrategyManager.ts'); - expect( - graph - .get(file) - ?.some(target => /^strategies\/(builtin|experimental)\//.test(relative(root, target))) - ).toBe(false); - expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/); - expect( - [...reachable(join(root, 'strategies/StrategyRegistry.ts'))] - .map(file => relative(root, file)) - .sort() - ).toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']); - }); - - it('backtest and strategy lifecycle collaborators are injected, not located or constructed internally', () => { - for (const file of [ - 'backtest/BacktestEngine.ts', - 'backtest/RustBacktestAdapter.ts', - 'strategies/StrategyManager.ts', - 'core/ModeManager.ts', - 'services/MarketDataService.ts', - ]) { + it('backtest adapter collaborators are injected, not located or constructed internally', () => { + for (const file of ['backtest/RustBacktestAdapter.ts']) { const source = readFileSync(join(root, file), 'utf8'); expect(source).not.toMatch(/\b(OrchestratorServices|IServiceContainer)\b/); const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true); @@ -238,39 +194,47 @@ describe('orchestrator architecture boundaries', () => { } }); - it('concrete strategies can only be loaded by the registry or other strategy implementations', () => { - for (const [file, dependencies] of graph) { - const owner = relative(root, file); - for (const dependency of dependencies) { - const target = relative(root, dependency); - if (!/^strategies\/(builtin|experimental)\//.test(target)) { - continue; - } - expect( - owner === 'strategies/builtin-strategies.ts' || - /^strategies\/(builtin|experimental)\//.test(owner) - ).toBe(true); - if (owner.startsWith('strategies/builtin/')) { - expect(target.startsWith('strategies/experimental/')).toBe(false); - } - } - } - }); - it('retired execution paths and strategy-local financial frameworks cannot return', () => { const retired = [ 'backtest/RustBacktestEngine.ts', + 'backtest/BacktestEngine.ts', + 'backtest/BacktestMarket.ts', + 'backtest/MarketSimulator.ts', + 'backtest/BacktestPlayback.ts', + 'backtest/BacktestReport.ts', + 'core/ModeManager.ts', + 'execution/SimulationExecution.ts', + 'execution/StrategyRecovery.ts', + 'execution/PostgresExecutionRepository.ts', + 'execution/BacktestExecutionRepository.ts', + 'execution/model.ts', + 'execution/repository.ts', + 'paper/PaperTradingManager.ts', + 'services/ExecutionService.ts', + 'services/MarketDataService.ts', + 'strategies/BaseStrategy.ts', + 'strategies/StrategyManager.ts', + 'strategies/StrategyRegistry.ts', 'strategies/RustStrategy.ts', 'strategies/StrategyExecutor.ts', + 'api/rest/orders.ts', + 'api/rest/positions.ts', + 'api/websocket/index.ts', ]; for (const file of retired) { expect(existsSync(join(root, file))).toBe(false); } for (const file of files) { expect(relative(root, file)).not.toMatch( - /^strategies\/(examples|rust|position|risk|signals|indicators)\// + /^strategies\/(builtin|experimental|examples|rust|position|risk|signals|indicators)\// ); } + expect(readFileSync(join(root, 'backtest/native-worker-protocol.ts'), 'utf8')).not.toContain( + "z.literal('run')" + ); + expect(readFileSync(join(root, 'backtest/BacktestRunner.ts'), 'utf8')).not.toContain( + 'engine.runBacktest(' + ); }); it('native backtest execution stays in the worker and strategies cannot submit orders directly', () => { @@ -298,7 +262,6 @@ describe('orchestrator architecture boundaries', () => { true ); function visit(node: ts.Node) { - // Check named imports anywhere, including aliases; a new wrapper outside backtest/ is still forbidden. if ( ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && @@ -349,75 +312,11 @@ describe('orchestrator architecture boundaries', () => { } }); - it('production research and paper entrypoints cannot reach prototype financial execution', () => { - const forbidden = [ - 'backtest/BacktestEngine.ts', - 'backtest/BacktestMarket.ts', - 'core/ModeManager.ts', - 'execution/SimulationExecution.ts', - 'execution/model.ts', - 'services/ExecutionService.ts', - 'paper/PaperTradingManager.ts', - 'api/rest/orders.ts', - 'api/rest/positions.ts', - 'api/websocket/index.ts', - ]; - for (const entry of [ - 'index.ts', - 'container.ts', - 'simple-container.ts', - 'backtest/native-worker.ts', - ]) { - const production = [...reachable(join(root, entry))].map(file => relative(root, file)); - for (const prototype of forbidden) { - expect(production).not.toContain(prototype); - } - } - expect(readFileSync(join(root, 'backtest/native-worker-protocol.ts'), 'utf8')).not.toContain( - "z.literal('run')" - ); - expect(readFileSync(join(root, 'backtest/BacktestRunner.ts'), 'utf8')).not.toContain( - 'engine.runBacktest(' - ); - }); - - it('backtest playback cannot depend on trading, data, reporting or service adapters', () => { - const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))] - .map(file => relative(root, file)) - .sort(); - expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']); - }); - it('reviewed analytics and window math live in the shared calculations library', () => { for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) { expect(existsSync(join(root, 'analytics/' + entry + '.ts'))).toBe(false); } expect(existsSync(join(root, 'indicators/window-statistics.ts'))).toBe(false); - expect(imports.get(join(root, 'analytics/PerformanceAnalyzer.ts'))).toEqual([ - '@stock-bot/calculations/analytics', - ]); - }); - - it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => { - for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) { - for (const file of reachable(join(root, entry))) { - expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data|execution)\//); - expect(relative(root, file)).not.toMatch( - /backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/ - ); - for (const specifier of imports.get(file) ?? []) { - expect( - specifier.startsWith('.') || - [ - 'zod', - '@stock-bot/invariants', - '@stock-bot/logger', - '@stock-bot/calculations/analytics', - ].includes(specifier) - ).toBe(true); - } - } - } }); }); @@ -429,15 +328,25 @@ describe('shared research boundary', () => { const source = readFileSync(join(research, name), 'utf8'); const sourceFile = ts.createSourceFile(name, source, ts.ScriptTarget.Latest, true); for (const statement of sourceFile.statements) { - if ((ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) { + if ( + (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement)) && + statement.moduleSpecifier && + ts.isStringLiteral(statement.moduleSpecifier) + ) { const dependency = statement.moduleSpecifier.text; - expect(dependency).not.toMatch(/apps\/|orchestrator|@stock-bot\/(?:di|postgres|mongodb|questdb|engine|queue)(?:\/|$)/); + expect(dependency).not.toMatch( + /apps\/|orchestrator|@stock-bot\/(?:di|postgres|mongodb|questdb|engine|queue)(?:\/|$)/ + ); } } } }); it('the shared response contract bundles for browsers without server dependencies', async () => { - const result = await Bun.build({ entrypoints: [join(research, 'dataset-contracts.ts')], target: 'browser', write: false }); + const result = await Bun.build({ + entrypoints: [join(research, 'dataset-contracts.ts')], + target: 'browser', + write: false, + }); expect(result.success).toBe(true); expect(await result.outputs[0]!.text()).not.toMatch(/node:crypto|node:fs|engine\.node/); }); @@ -445,9 +354,13 @@ describe('shared research boundary', () => { describe('canonical admission boundary', () => { it('new run operations cannot construct legacy snapshots or invoke legacy execution', () => { - const path = fileURLToPath(new URL('../../apps/stock/web-api/src/services/backtests/runs.ts', import.meta.url)); + const path = fileURLToPath( + new URL('../../apps/stock/web-api/src/services/backtests/runs.ts', import.meta.url) + ); const dependencies = runtimeImports(path); - expect(dependencies.some(value => /execution-engine|BacktestRunner|strategy-manager/.test(value))).toBe(false); + expect( + dependencies.some(value => /execution-engine|BacktestRunner|strategy-manager/.test(value)) + ).toBe(false); const source = readFileSync(path, 'utf8'); expect(source).not.toContain('backtestRequestFromDefinition'); expect(source).not.toContain('legacyDefinition'); diff --git a/scripts/test/library-boundaries.test.ts b/scripts/test/library-boundaries.test.ts index 61f1e8da..1d072b99 100644 --- a/scripts/test/library-boundaries.test.ts +++ b/scripts/test/library-boundaries.test.ts @@ -18,12 +18,8 @@ const sourceFiles = [...new Bun.Glob('src/**/*.ts').scanSync({ cwd: utilsRoot }) describe('shared library boundaries', () => { it('utils exposes general helpers without a financial framework', () => { expect(Object.keys(utils).sort()).toEqual([ - 'createProxyUrl', - 'dateUtils', 'fetch', 'getRandomUserAgent', - 'sleep', - 'utcDates', ]); expect(utils.fetch).toBe(fetch); expect(utils.getRandomUserAgent).toBe(getRandomUserAgent); @@ -32,10 +28,8 @@ describe('shared library boundaries', () => { '.': './src/index.ts', './fetch': './src/fetch.ts', './user-agent': './src/user-agent.ts', - './common': './src/common.ts', - './dates': './src/dateUtils.ts', }); - for (const retired of ['assertions', 'calculations', 'src/fetch', 'dateUtils']) { + for (const retired of ['assertions', 'calculations', 'common', 'dates', 'src/fetch', 'dateUtils']) { expect(() => Bun.resolveSync(`@stock-bot/utils/${retired}`, root)).toThrow(); } }); @@ -97,11 +91,11 @@ describe('shared library boundaries', () => { '.', './analytics', './indicators', - './legacy', './market-data', './returns', ]); for (const path of [ + 'legacy', 'research', 'src/legacy/basic-calculations', 'legacy/technical-indicators', diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index 2cb64810..42dd15a7 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -12,7 +12,7 @@ import { parseFinancialDecimal } from '@stock-bot/types'; import { financialTransactionRequestSchema, parseFinancialTransactionResult, -} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +} from '@stock-bot/stock-config/canonical-execution'; import nativeReplayLoad from '../../test/fixtures/native-replay-load.json'; describe('generated native bindings', () => { diff --git a/scripts/test/orchestrator-container.test.ts b/scripts/test/orchestrator-container.test.ts deleted file mode 100644 index 939aa19c..00000000 --- a/scripts/test/orchestrator-container.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { expect, test } from 'bun:test'; -import { createExampleRuntime } from '../../apps/stock/orchestrator/examples/example-runtime'; - -test('offline examples use the shared DI graph without starting a real-time feed', async () => { - const runtime = await createExampleRuntime(); - expect(runtime.container.custom?.StorageService).toBe(runtime.storageService); - expect(runtime.container.custom?.StrategyManager).toBe(runtime.strategyManager); - expect(runtime.container.mongodb).toBeNull(); - expect(runtime.container.queueManager).toBeNull(); - expect(runtime.modeManager.getConfig()).toBeNull(); - expect(() => runtime.modeManager.getTradingEngine()).toThrow('Trading engine not initialized'); -}); diff --git a/scripts/test/strategy-packaging.test.ts b/scripts/test/strategy-packaging.test.ts index aaad9b3e..635ab562 100644 --- a/scripts/test/strategy-packaging.test.ts +++ b/scripts/test/strategy-packaging.test.ts @@ -14,7 +14,7 @@ import { import type { StrategyContext, StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; import { packageBuiltinStrategies } from '../package-builtin-strategies'; import { runtimeImports } from '../runtime-imports'; diff --git a/scripts/test/strategy-runtime.test.ts b/scripts/test/strategy-runtime.test.ts index ebb1fd2b..6c164838 100644 --- a/scripts/test/strategy-runtime.test.ts +++ b/scripts/test/strategy-runtime.test.ts @@ -9,7 +9,7 @@ import { StrategyReplayError, type StrategyProgram, } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { nativeAdmissionOrders } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { nativeAdmissionOrders } from '@stock-bot/stock-config/canonical-replay'; import { nativeReplayFixture } from '../../test/fixtures/native-replay'; const hold = () => ({ mode: 'target' as const, targets: [] }); diff --git a/scripts/test/workspace.test.ts b/scripts/test/workspace.test.ts index c296d8f0..098748e6 100644 --- a/scripts/test/workspace.test.ts +++ b/scripts/test/workspace.test.ts @@ -32,7 +32,7 @@ function config(path: string) { } describe('workspace verification', () => { - it('the real root build selects every buildable workspace and excludes the command aggregate', () => { + it('the real root build selects every buildable workspace', () => { const result = Bun.spawnSync([process.execPath, 'run', 'build', '--dry=json'], { cwd: root, env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' }, @@ -42,11 +42,10 @@ describe('workspace verification', () => { const planned = new Set(plan.tasks.map((task: { taskId: string }) => task.taskId)); for (const file of packageFiles) { const pkg = JSON.parse(readFileSync(join(root, file), 'utf8')); - if (pkg.scripts?.build && pkg.name !== '@stock-bot/stock-app') { + if (pkg.scripts?.build) { expect(planned.has(`${pkg.name}#build`)).toBe(true); } } - expect(planned.has('@stock-bot/stock-app#build')).toBe(false); }); it('research development selects only the API, worker and web application', () => { @@ -82,7 +81,7 @@ describe('workspace verification', () => { const success = invoke('0'); expect(success.exitCode).toBe(0); const output = new TextDecoder().decode(success.stdout); - expect(output).toContain('compose\n-f\ndocker-compose.yml\nup\n-d\ndragonfly\npostgres\nquestdb\nmongodb'); + expect(output).toContain('compose\n-f\ndocker-compose.dev.yml\nup\n-d\ndragonfly\npostgres\nquestdb\nmongodb'); expect(output).not.toContain('down'); const failed = invoke('23'); expect(failed.exitCode).toBe(23); diff --git a/scripts/verify-build.sh b/scripts/verify-build.sh deleted file mode 100755 index 1cca1942..00000000 --- a/scripts/verify-build.sh +++ /dev/null @@ -1,169 +0,0 @@ -#!/bin/bash - -# Build verification script for Stock Bot Trading Platform - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -CYAN='\033[0;36m' -GRAY='\033[0;37m' -NC='\033[0m' # No Color - -# Default options -VERBOSE=false - -# Parse command line arguments -while [[ $# -gt 0 ]]; do - case $1 in - --verbose|-v) - VERBOSE=true - shift - ;; - --help|-h) - echo "Usage: $0 [--verbose]" - echo " --verbose, -v Show verbose output" - echo " --help, -h Show this help message" - exit 0 - ;; - *) - echo "Unknown option: $1" - echo "Use --help for usage information" - exit 1 - ;; - esac -done - -echo -e "${GREEN}=== Verifying Build Health ===${NC}" - -errors=() -warnings=() - -# Check for common build issues -echo -e "${YELLOW}Checking for common build issues...${NC}" - -# Check for mismatched .d.ts files in source directories -echo -e "${BLUE}Checking for .d.ts files in source directories...${NC}" -source_dts_files=$(find ./libs/*/src -name "*.d.ts" -type f 2>/dev/null) -if [ -n "$source_dts_files" ]; then - warnings+=("Found .d.ts files in source directories:") - while IFS= read -r file; do - warnings+=(" - $file") - done <<< "$source_dts_files" -fi - -# Check for missing dist directories after build -echo -e "${BLUE}Checking for missing dist directories...${NC}" -libraries=("types" "config" "logger" "utils" "cache" "http") -for lib in "${libraries[@]}"; do - dist_path="libs/$lib/dist" - if [ ! -d "$dist_path" ]; then - errors+=("Missing dist directory for $lib") - else - index_file="$dist_path/index.js" - if [ ! -f "$index_file" ]; then - errors+=("Missing index.js in dist for $lib") - fi - fi -done - -# Check for TypeScript compilation errors -echo -e "${BLUE}Checking for TypeScript compilation errors...${NC}" -tsc_errors=$(find . -name "*.tsbuildinfo" -exec grep -l "error" {} \; 2>/dev/null) -if [ -n "$tsc_errors" ]; then - errors+=("TypeScript compilation errors found in build info files") - if [ "$VERBOSE" = true ]; then - while IFS= read -r file; do - errors+=(" - $file") - done <<< "$tsc_errors" - fi -fi - -# Check for large build files (potential issues) -echo -e "${BLUE}Checking for unusually large build files...${NC}" -large_files=$(find ./libs/*/dist -name "*.js" -size +1M 2>/dev/null) -if [ -n "$large_files" ]; then - warnings+=("Found unusually large build files (>1MB):") - while IFS= read -r file; do - size=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file" 2>/dev/null) - size_mb=$(echo "scale=2; $size / 1024 / 1024" | bc 2>/dev/null || echo "unknown") - warnings+=(" - $file (${size_mb}MB)") - done <<< "$large_files" -fi - -# Check for circular dependencies (basic check) -echo -e "${BLUE}Checking for potential circular dependencies...${NC}" -package_json_files=$(find ./libs -name "package.json" -type f) -while IFS= read -r pkg_file; do - lib_name=$(basename "$(dirname "$pkg_file")") - if [ -f "$pkg_file" ]; then - # Check if library depends on itself (basic check) - self_dep=$(grep -o "@stock-bot/$lib_name" "$pkg_file" 2>/dev/null) - if [ -n "$self_dep" ]; then - warnings+=("Potential circular dependency in $lib_name") - fi - fi -done <<< "$package_json_files" - -# Check for missing package.json files -echo -e "${BLUE}Checking for missing package.json files...${NC}" -lib_dirs=$(find ./libs -maxdepth 1 -type d -name "*" ! -name "libs") -while IFS= read -r lib_dir; do - if [ -d "$lib_dir" ] && [ ! -f "$lib_dir/package.json" ]; then - lib_name=$(basename "$lib_dir") - errors+=("Missing package.json in $lib_name") - fi -done <<< "$lib_dirs" - -# Check for environment variable dependencies -echo -e "${BLUE}Checking for hardcoded paths...${NC}" -hardcoded_paths_win=$(grep -r "g:\\repos\\stock-bot" ./libs 2>/dev/null || true) -hardcoded_paths_unix=$(grep -r "/home/.*/stock-bot" ./libs 2>/dev/null || true) - -if [ -n "$hardcoded_paths_win" ]; then - warnings+=("Found hardcoded Windows paths:") - while IFS= read -r line; do - warnings+=(" - $line") - done <<< "$hardcoded_paths_win" -fi - -if [ -n "$hardcoded_paths_unix" ]; then - warnings+=("Found hardcoded Unix paths:") - while IFS= read -r line; do - warnings+=(" - $line") - done <<< "$hardcoded_paths_unix" -fi - -# Summary -echo "" -echo -e "${CYAN}=== Build Verification Summary ===${NC}" - -if [ ${#errors[@]} -eq 0 ] && [ ${#warnings[@]} -eq 0 ]; then - echo -e "${GREEN}โœ… Build verification passed - no issues found!${NC}" - exit 0 -fi - -if [ ${#errors[@]} -gt 0 ]; then - echo -e "${RED}โŒ Errors found (${#errors[@]}):${NC}" - for error in "${errors[@]}"; do - echo -e "${RED} $error${NC}" - done -fi - -if [ ${#warnings[@]} -gt 0 ]; then - echo -e "${YELLOW}โš ๏ธ Warnings found (${#warnings[@]}):${NC}" - for warning in "${warnings[@]}"; do - echo -e "${YELLOW} $warning${NC}" - done -fi - -if [ ${#errors[@]} -gt 0 ]; then - echo "" - echo -e "${RED}Build verification failed due to errors.${NC}" - exit 1 -else - echo "" - echo -e "${YELLOW}Build verification completed with warnings.${NC}" - exit 0 -fi diff --git a/test-e2e-backtest.sh b/test-e2e-backtest.sh deleted file mode 100755 index e3641f74..00000000 --- a/test-e2e-backtest.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/bin/bash - -echo "Testing End-to-End Backtest Flow" -echo "================================" - -# Wait for services to be ready -echo "Waiting for services to be ready..." -sleep 5 - -# Test 1: Check web-api health -echo -e "\n1. Checking web-api health..." -curl -s http://localhost:2003/health | jq . - -# Test 2: Check orchestrator health -echo -e "\n2. Checking orchestrator health..." -curl -s http://localhost:2004/health | jq . - -# Test 3: Create a backtest -echo -e "\n3. Creating a backtest..." -BACKTEST_RESPONSE=$(curl -s -X POST http://localhost:2003/api/backtests \ - -H "Content-Type: application/json" \ - -d '{ - "strategy": "SimpleMovingAverageCrossover", - "symbols": ["AAPL"], - "startDate": "2024-01-01", - "endDate": "2024-01-31", - "initialCapital": 100000, - "config": { - "commission": 0.001, - "slippage": 0.0001 - } - }') - -echo "$BACKTEST_RESPONSE" | jq . - -# Extract backtest ID -BACKTEST_ID=$(echo "$BACKTEST_RESPONSE" | jq -r .id) -echo "Backtest ID: $BACKTEST_ID" - -# Test 4: Check backtest status -echo -e "\n4. Checking backtest status..." -sleep 2 -curl -s http://localhost:2003/api/backtests/$BACKTEST_ID | jq . - -# Test 5: Get backtest results (wait a bit for completion) -echo -e "\n5. Waiting for backtest to complete..." -for i in {1..10}; do - sleep 2 - STATUS=$(curl -s http://localhost:2003/api/backtests/$BACKTEST_ID | jq -r .status) - echo "Status: $STATUS" - - if [ "$STATUS" = "completed" ]; then - echo -e "\n6. Getting backtest results..." - curl -s http://localhost:2003/api/backtests/$BACKTEST_ID/results | jq . - break - fi -done - -echo -e "\nEnd-to-End test complete!" \ No newline at end of file diff --git a/test-queue.ts b/test-queue.ts deleted file mode 100644 index 3a8fb1a5..00000000 --- a/test-queue.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Queue } from 'bullmq'; - -const queue = new Queue('{data-ingestion_ceo}', { - connection: { - host: 'localhost', - port: 6379, - db: 0, - }, -}); - -async function testJob() { - const job = await queue.add('fetchCompany', { - handler: 'ceo', - operation: 'fetchCompany', - payload: { symbol: 'AAPL' }, - }); - - console.log('Job added:', job.id); - process.exit(0); -} - -testJob().catch(console.error); \ No newline at end of file diff --git a/test-rust-strategies.js b/test-rust-strategies.js deleted file mode 100644 index 4e03b48b..00000000 --- a/test-rust-strategies.js +++ /dev/null @@ -1,274 +0,0 @@ -#!/usr/bin/env bun - -import { BacktestEngine } from './apps/stock/core/index.js'; - -// Test configuration -const config = { - name: 'Native Rust Strategies Test', - symbols: ['AA', 'AAS'], - startDate: '2024-01-01T00:00:00Z', - endDate: '2024-01-31T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d', -}; - -// Create the Rust engine -const engine = new BacktestEngine(config); - -// Test different native Rust strategies -console.log('Testing native Rust strategies...\n'); - -// 1. Test Mean Reversion Strategy -console.log('1. Mean Reversion Strategy'); -engine.addNativeStrategy( - 'mean_reversion', - 'Mean Reversion AA/AAS', - 'mean-rev-1', - { - lookbackPeriod: 20, - entryThreshold: 2.0, - positionSize: 1000, - } -); - -// Generate synthetic market data with mean-reverting characteristics -const testData = []; -const startDate = new Date('2024-01-01'); - -for (let i = 0; i < 30; i++) { - const date = new Date(startDate); - date.setDate(date.getDate() + i); - - // AA: Mean-reverting around 100 - const aaMean = 100; - const aaPrice = aaMean + Math.sin(i / 5) * 10 + (Math.random() - 0.5) * 5; - - // AAS: Mean-reverting around 50 - const aasMean = 50; - const aasPrice = aasMean + Math.sin(i / 5) * 5 + (Math.random() - 0.5) * 2.5; - - testData.push({ - symbol: 'AA', - timestamp: date.getTime(), - type: 'bar', - open: aaPrice - 0.5, - high: aaPrice + 0.5, - low: aaPrice - 1, - close: aaPrice, - volume: 1000000, - vwap: aaPrice, - }); - - testData.push({ - symbol: 'AAS', - timestamp: date.getTime(), - type: 'bar', - open: aasPrice - 0.25, - high: aasPrice + 0.25, - low: aasPrice - 0.5, - close: aasPrice, - volume: 500000, - vwap: aasPrice, - }); -} - -console.log(`Loading ${testData.length} market data points...`); -engine.loadMarketData(testData); - -// Run the backtest -console.log('Running mean reversion backtest...'); -try { - const resultJson = engine.run(); - const result = JSON.parse(resultJson); - - console.log('\nResults:'); - console.log('Total trades:', result.trades?.length || 0); - console.log('Win rate:', result.metrics.win_rate?.toFixed(2) + '%'); - console.log('Profit factor:', result.metrics.profit_factor?.toFixed(2)); - console.log('Total PnL:', '$' + result.metrics.total_pnl?.toFixed(2)); - console.log('Final equity:', '$' + result.equity_curve[result.equity_curve.length - 1]?.[1].toFixed(2)); - - // Show some trades - if (result.trades && result.trades.length > 0) { - console.log('\nFirst few trades:'); - result.trades.slice(0, 5).forEach((trade, i) => { - console.log(` ${i + 1}. ${trade.symbol} ${trade.side} @ $${trade.price.toFixed(2)}`); - }); - } - -} catch (error) { - console.error('Backtest failed:', error); -} - -console.log('\n' + '='.repeat(50) + '\n'); - -// 2. Test Momentum Strategy -console.log('2. Momentum Strategy'); - -// Create a new engine for momentum strategy -const engine2 = new BacktestEngine(config); - -engine2.addNativeStrategy( - 'momentum', - 'Momentum Trading', - 'momentum-1', - { - lookbackPeriod: 10, - momentumThreshold: 5.0, - positionSize: 1000, - } -); - -// Generate trending market data -const trendData = []; -for (let i = 0; i < 30; i++) { - const date = new Date(startDate); - date.setDate(date.getDate() + i); - - // AA: Uptrend - const aaPrice = 100 + i * 2 + (Math.random() - 0.5) * 2; - - // AAS: Downtrend then uptrend - const aasPrice = i < 15 - ? 50 - i * 1 + (Math.random() - 0.5) * 1 - : 35 + (i - 15) * 1.5 + (Math.random() - 0.5) * 1; - - trendData.push({ - symbol: 'AA', - timestamp: date.getTime(), - type: 'bar', - open: aaPrice - 0.5, - high: aaPrice + 0.5, - low: aaPrice - 1, - close: aaPrice, - volume: 1000000, - vwap: aaPrice, - }); - - trendData.push({ - symbol: 'AAS', - timestamp: date.getTime(), - type: 'bar', - open: aasPrice - 0.25, - high: aasPrice + 0.25, - low: aasPrice - 0.5, - close: aasPrice, - volume: 500000, - vwap: aasPrice, - }); -} - -engine2.loadMarketData(trendData); - -console.log('Running momentum backtest...'); -try { - const resultJson = engine2.run(); - const result = JSON.parse(resultJson); - - console.log('\nResults:'); - console.log('Total trades:', result.trades?.length || 0); - console.log('Win rate:', result.metrics.win_rate?.toFixed(2) + '%'); - console.log('Profit factor:', result.metrics.profit_factor?.toFixed(2)); - console.log('Total PnL:', '$' + result.metrics.total_pnl?.toFixed(2)); - console.log('Final equity:', '$' + result.equity_curve[result.equity_curve.length - 1]?.[1].toFixed(2)); - -} catch (error) { - console.error('Backtest failed:', error); -} - -console.log('\n' + '='.repeat(50) + '\n'); - -// 3. Test Pairs Trading Strategy -console.log('3. Pairs Trading Strategy'); - -const engine3 = new BacktestEngine(config); - -engine3.addNativeStrategy( - 'pairs_trading', - 'Pairs Trading AA/AAS', - 'pairs-1', - { - pairA: 'AA', - pairB: 'AAS', - lookbackPeriod: 20, - entryThreshold: 2.0, - positionSize: 1000, - } -); - -// Generate correlated market data with spread deviations -const pairsData = []; -for (let i = 0; i < 30; i++) { - const date = new Date(startDate); - date.setDate(date.getDate() + i); - - // Base prices - const basePrice = 100 + Math.sin(i / 10) * 5; - - // Spread oscillates around 50 - const spread = 50 + Math.sin(i / 3) * 10 + (Math.random() - 0.5) * 2; - - const aaPrice = basePrice; - const aasPrice = basePrice - spread; - - pairsData.push({ - symbol: 'AA', - timestamp: date.getTime(), - type: 'bar', - open: aaPrice - 0.5, - high: aaPrice + 0.5, - low: aaPrice - 1, - close: aaPrice, - volume: 1000000, - vwap: aaPrice, - }); - - pairsData.push({ - symbol: 'AAS', - timestamp: date.getTime(), - type: 'bar', - open: aasPrice - 0.25, - high: aasPrice + 0.25, - low: aasPrice - 0.5, - close: aasPrice, - volume: 500000, - vwap: aasPrice, - }); -} - -engine3.loadMarketData(pairsData); - -console.log('Running pairs trading backtest...'); -try { - const resultJson = engine3.run(); - const result = JSON.parse(resultJson); - - console.log('\nResults:'); - console.log('Total trades:', result.trades?.length || 0); - console.log('Win rate:', result.metrics.win_rate?.toFixed(2) + '%'); - console.log('Profit factor:', result.metrics.profit_factor?.toFixed(2)); - console.log('Total PnL:', '$' + result.metrics.total_pnl?.toFixed(2)); - console.log('Final equity:', '$' + result.equity_curve[result.equity_curve.length - 1]?.[1].toFixed(2)); - - // Show paired trades - if (result.trades && result.trades.length > 0) { - console.log('\nPairs trades (showing pairs):'); - for (let i = 0; i < result.trades.length && i < 6; i += 2) { - const trade1 = result.trades[i]; - const trade2 = result.trades[i + 1]; - if (trade2) { - console.log(` Pair ${Math.floor(i/2) + 1}: ${trade1.symbol} ${trade1.side} @ $${trade1.price.toFixed(2)}, ${trade2.symbol} ${trade2.side} @ $${trade2.price.toFixed(2)}`); - } - } - } - -} catch (error) { - console.error('Backtest failed:', error); -} - -console.log('\n' + '='.repeat(50)); -console.log('\nNative Rust strategies test complete!'); -console.log('\nThese strategies run at microsecond speeds in Rust,'); -console.log('perfect for high-frequency trading and production use.'); \ No newline at end of file diff --git a/test-typescript-strategy.js b/test-typescript-strategy.js deleted file mode 100644 index cd8efc59..00000000 --- a/test-typescript-strategy.js +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bun - -import { BacktestEngine } from './apps/stock/core/index.js'; - -// Create a simple test configuration -const config = { - name: 'TypeScript Strategy Test', - symbols: ['AA', 'AAS'], - startDate: '2024-01-01T00:00:00Z', - endDate: '2024-01-15T00:00:00Z', - initialCapital: 100000, - commission: 0.001, - slippage: 0.0001, - dataFrequency: '1d', -}; - -// Create the Rust engine -const engine = new BacktestEngine(config); - -// Add TypeScript strategy with callback -console.log('Adding TypeScript strategy with callback...'); -engine.addTypescriptStrategy( - 'SMA Crossover', - 'strategy-test-1', - { fastPeriod: 5, slowPeriod: 15 }, - (callJson) => { - const call = JSON.parse(callJson); - console.log('TypeScript callback called:', call.method); - - if (call.method === 'on_market_data') { - const data = call.data; - console.log(`Market data for ${data.symbol}: close=${data.data?.close}`); - return JSON.stringify({ signals: [] }); - } else if (call.method === 'on_fill') { - console.log('Fill received:', call.data); - return JSON.stringify({ signals: [] }); - } - - return JSON.stringify({ signals: [] }); - } -); - -// Load some test market data -const testData = []; -const startDate = new Date('2024-01-01'); -for (let i = 0; i < 20; i++) { - const date = new Date(startDate); - date.setDate(date.getDate() + i); - - // Add data for both symbols - for (const symbol of ['AA', 'AAS']) { - const basePrice = symbol === 'AA' ? 100 : 50; - const price = basePrice + Math.sin(i / 3) * 5 + Math.random() * 2; - - testData.push({ - symbol, - timestamp: date.getTime(), - type: 'bar', - open: price - 0.5, - high: price + 0.5, - low: price - 1, - close: price, - volume: 1000000, - vwap: price, - }); - } -} - -console.log(`Loading ${testData.length} market data points...`); -engine.loadMarketData(testData); - -// Run the backtest -console.log('Running backtest...'); -try { - const resultJson = engine.run(); - const result = JSON.parse(resultJson); - - console.log('\nBacktest Results:'); - console.log('Total trades:', result.trades?.length || 0); - console.log('Final equity:', result.equity_curve[result.equity_curve.length - 1]?.[1]); - console.log('Metrics:', result.metrics); - -} catch (error) { - console.error('Backtest failed:', error); -} \ No newline at end of file diff --git a/test/contracts/canonical-runner.type-test.ts b/test/contracts/canonical-runner.type-test.ts index 14054a7a..82750590 100644 --- a/test/contracts/canonical-runner.type-test.ts +++ b/test/contracts/canonical-runner.type-test.ts @@ -1,8 +1,5 @@ import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; -import type { - BacktestExecutionEngine, - LegacyBacktestExecutionEngine, -} from '../../apps/stock/orchestrator/src/backtest/execution-engine'; +import type { BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import type { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import type { BacktestRunRepository, @@ -12,7 +9,7 @@ import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/ function canonicalDependencies( engine: BacktestExecutionEngine, - legacy: LegacyBacktestExecutionEngine, + legacy: Pick, repository: BacktestRunRepository, withoutReplay: Omit, withoutClaim: Omit, diff --git a/test/contracts/strategy-runtime.type-test.ts b/test/contracts/strategy-runtime.type-test.ts index 36cf6b76..2bfd432e 100644 --- a/test/contracts/strategy-runtime.type-test.ts +++ b/test/contracts/strategy-runtime.type-test.ts @@ -1,8 +1,6 @@ import type { StrategyContext, StrategyProgram } from '@stock-bot/research/strategy-api'; import type * as AuthorAPI from '@stock-bot/research/strategy-api'; import type { FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types'; -// Existing hosts keep the same contract while external authors use the public subpath. -import type { StrategyProgram as LegacyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; type State = { count: number; indicator: { values: number[] } }; @@ -62,8 +60,7 @@ const asynchronous: StrategyProgram = { }; void asynchronous; -const legacyProgram: LegacyProgram = valid; -const publicProgram: StrategyProgram = legacyProgram; +const publicProgram: StrategyProgram = valid; void publicProgram; // @ts-expect-error The author package exposes no strategy execution controller. diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index e1736519..2d0c7247 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -17,7 +17,7 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; -import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import type { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types'; import { createRoutes, diff --git a/test/fixtures/canonical-paper.ts b/test/fixtures/canonical-paper.ts index 84d4bbd5..cb8fee20 100644 --- a/test/fixtures/canonical-paper.ts +++ b/test/fixtures/canonical-paper.ts @@ -1,6 +1,6 @@ import { parseFinancialDecimal } from '@stock-bot/types'; -import type { CanonicalMatchingConfig } from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; -import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { CanonicalMatchingConfig } from '@stock-bot/stock-config/canonical-execution'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import type { CanonicalPaperInput } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; export function canonicalConfig(owners = ['A']): CanonicalMatchingConfig { diff --git a/test/fixtures/canonical-regime-research.ts b/test/fixtures/canonical-regime-research.ts index 0c081001..0affc767 100644 --- a/test/fixtures/canonical-regime-research.ts +++ b/test/fixtures/canonical-regime-research.ts @@ -3,7 +3,7 @@ import { type BuiltinStrategySelection, type MeanReversionSignalParameters, type MeanReversionStrategySelection, -} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +} from '@stock-bot/stock-config/strategy'; import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import { nativeReplayFixture } from './native-replay'; diff --git a/test/fixtures/canonical-result.ts b/test/fixtures/canonical-result.ts index 6c59319e..619d0130 100644 --- a/test/fixtures/canonical-result.ts +++ b/test/fixtures/canonical-result.ts @@ -2,7 +2,7 @@ import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research'; import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; import { createSmaStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-sma'; import { canonicalRunnerFixture } from './canonical-runner'; diff --git a/test/fixtures/canonical-sma.ts b/test/fixtures/canonical-sma.ts index 01a54559..88e70eb9 100644 --- a/test/fixtures/canonical-sma.ts +++ b/test/fixtures/canonical-sma.ts @@ -1,4 +1,4 @@ -import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import { nativeReplayFixture } from './native-replay'; diff --git a/test/fixtures/execution.ts b/test/fixtures/execution.ts index da448b68..74e31124 100644 --- a/test/fixtures/execution.ts +++ b/test/fixtures/execution.ts @@ -1,55 +1,4 @@ -import { TradingEngine } from '@stock-bot/engine'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository'; -import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; -import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { - BacktestConfigSchema, - type MarketData, - type OrderRequest, -} from '../../apps/stock/orchestrator/src/types'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); export const logger = getLogger('execution-test'); -export const start = Date.parse('2024-01-01T00:00:00Z'); -export const config = BacktestConfigSchema.parse({ - mode: 'backtest', - strategy: 'sma-crossover', - symbols: ['A.US', 'B.US'], - startDate: new Date(start).toISOString(), - endDate: '2025-01-01T00:00:00Z', - initialCapital: 10000, - dataFrequency: '1d', - commission: 0.001, - slippage: 0, -}); -export function quote( - id: string, - price = 100, - size = 100, - timestamp = start, - symbol = 'A' -): MarketData { - return { - type: 'quote', - eventId: id, - data: { symbol, bid: price, ask: price, bidSize: size, askSize: size, timestamp }, - }; -} -export function order( - clientOrderId: string, - side: 'buy' | 'sell' = 'buy', - quantity = 10 -): OrderRequest { - return { symbol: 'A', side, quantity, orderType: 'market', timeInForce: 'DAY', clientOrderId }; -} -export function makeExecution(repository?: ExecutionRepository, clock = () => start) { - const engine = new TradingEngine('backtest', { - startTime: start, - endTime: Date.parse(config.endDate), - speedMultiplier: 0, - initialCapital: 10000, - }); - const execution = new ExecutionService({ logger }, {} as StorageService, { repository, clock }); - return { execution, engine }; -} diff --git a/test/fixtures/native-replay-worker.ts b/test/fixtures/native-replay-worker.ts index 3c83b068..26842e2f 100644 --- a/test/fixtures/native-replay-worker.ts +++ b/test/fixtures/native-replay-worker.ts @@ -1,5 +1,5 @@ import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; -import { replayTraceSchema } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay'; function send(message: unknown): Promise { return new Promise((resolve, reject) => diff --git a/test/fixtures/native-replay.ts b/test/fixtures/native-replay.ts index 60cc45f6..d5f3f13d 100644 --- a/test/fixtures/native-replay.ts +++ b/test/fixtures/native-replay.ts @@ -1,4 +1,4 @@ -import type { ReplayConfig } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import type { ReplayConfig } from '@stock-bot/stock-config/canonical-replay'; import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; /** Retained synthetic sessions, raw executable bars, explicit availability. */ diff --git a/test/fixtures/paper-feed.ts b/test/fixtures/paper-feed.ts index c76348d8..177e4b17 100644 --- a/test/fixtures/paper-feed.ts +++ b/test/fixtures/paper-feed.ts @@ -2,7 +2,7 @@ import { parseFinancialDecimal } from '@stock-bot/types'; import type { PaperConfigurationInput, PaperFrameInput, -} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +} from '@stock-bot/stock-config/paper-runtime'; import { canonicalConfig } from './canonical-paper'; export function paperFeedConfiguration(instruments = ['X']): PaperConfigurationInput { diff --git a/test/fixtures/paper-runtime.ts b/test/fixtures/paper-runtime.ts index c84e76f7..145ced68 100644 --- a/test/fixtures/paper-runtime.ts +++ b/test/fixtures/paper-runtime.ts @@ -3,11 +3,11 @@ import { readFileSync } from 'node:fs'; import { Pool } from 'pg'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { parseFinancialDecimal } from '@stock-bot/types'; -import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import type { PaperConfigurationInput, PaperFrameInput, -} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +} from '@stock-bot/stock-config/paper-runtime'; import type { CanonicalExecutionRepository, CanonicalTransaction, diff --git a/test/fixtures/strategy-crash-owner.ts b/test/fixtures/strategy-crash-owner.ts deleted file mode 100644 index fc338938..00000000 --- a/test/fixtures/strategy-crash-owner.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** Disposable process used only against an isolated stock_bot_safety schema. */ -import { Pool } from 'pg'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; -import { logger, makeExecution, start } from './execution'; -import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL, - schema = process.env.STRATEGY_FIXTURE_SCHEMA, - phase = process.env.STRATEGY_FIXTURE_PHASE; -if ( - !url || - !new URL(url).pathname.startsWith('/stock_bot_safety') || - !schema || - !/^stock_bot_safety_[a-f0-9]+$/.test(schema) || - !['decision', 'checkpoint', 'dispatch'].includes(phase ?? '') -) { - throw new Error('Unsafe strategy crash fixture'); -} -const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); -const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' }, - logger -); -Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); -const repository = new FaultRepository(new PostgresExecutionRepository(postgres)); -const { execution, engine } = makeExecution(repository, () => start + 100); -await execution.initialize( - { - mode: 'paper', - accountId: 'fixture', - startingCapital: 10000, - commission: 0.001, - slippage: 0, - maxQuoteAgeMs: 1000, - }, - engine -); -const blocked = async () => { - process.send?.({ phase }); - await new Promise(() => {}); -}; -const strategy = new CounterStrategy(execution); -if (phase === 'decision') { - strategy.onDecision = blocked; -} else { - repository.fault = { - method: 'putIntent', - stage: 'commit', - matches: value => - (value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'), - hook: blocked, - }; -} -await attachCounter(execution, strategy); -throw new Error('Crash fixture did not reach its requested boundary'); diff --git a/test/fixtures/strategy-recovery.ts b/test/fixtures/strategy-recovery.ts deleted file mode 100644 index 678227c4..00000000 --- a/test/fixtures/strategy-recovery.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { EventEmitter } from 'node:events'; -import { z } from 'zod'; -import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import type { - ExecutionRepository, - ExecutionTransaction, -} from '../../apps/stock/orchestrator/src/execution/repository'; -import type { - ExecutionService, - StrategyFill, -} from '../../apps/stock/orchestrator/src/services/ExecutionService'; -import { - BaseStrategy, - type Signal, -} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; -import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; -import type { - StrategyDependencies, - StrategyRegistry, -} from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; -import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types'; -import { logger } from './execution'; - -export const recoveryConfig: StrategyConfig = { - id: 'counter', - name: 'fixture', - symbols: ['A'], - parameters: {}, - allocation: 1, - enabled: true, -}; -export function makeStrategyManager({ - execution, - modeManager, - registry = createBuiltinStrategyRegistry(), - marketData = new EventEmitter(), -}: StrategyDependencies & { registry?: StrategyRegistry; marketData?: EventEmitter }) { - return new StrategyManager({ - logger, - execution, - marketData, - createStrategy: config => registry.create(config, { execution, modeManager }), - }); -} - -export class CounterStrategy extends BaseStrategy { - count = 0; - equities: number[] = []; - failDecision = false; - failFill = false; - onDecision?: () => Promise; - version = 'counter/v1'; - constructor(execution: ExecutionService, config = recoveryConfig) { - super(config, {} as ModeManager, execution); - } - override getCheckpointVersion() { - return this.version; - } - protected override captureIndicators() { - return { count: this.count, equities: this.equities }; - } - protected override restoreIndicators(input: unknown) { - const state = z - .object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) }) - .parse(input); - this.count = state.count; - this.equities = state.equities; - } - protected updateIndicators() { - this.count++; - } - protected async generateSignal(data: MarketData): Promise { - this.equities.push((await this.executionService.getAccount()).equity); - await this.onDecision?.(); - if (this.failDecision) { - throw new Error('injected decision failure'); - } - return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } }; - } - override async onFill(fill: StrategyFill) { - await super.onFill(fill); - if (this.failFill) { - throw new Error('injected fill callback failure'); - } - } -} -export async function attachCounter( - execution: ExecutionService, - strategy = new CounterStrategy(execution) -) { - const manager = new StrategyManager({ - logger, - execution, - marketData: new EventEmitter(), - createStrategy: () => { - throw new Error('Counter fixtures attach their strategies directly'); - }, - }); - try { - await manager.attachStrategy(strategy); - } catch (error) { - await manager.shutdown(); - throw error; - } - return { manager, strategy }; -} - -export class FaultRepository implements ExecutionRepository { - fault?: { - method: keyof ExecutionTransaction; - matches: (argument: unknown) => boolean; - stage: 'before' | 'after' | 'commit'; - hook?: () => Promise; - }; - constructor(private readonly delegate: ExecutionRepository) {} - initialize(...args: Parameters) { - return this.delegate.initialize(...args); - } - async transact(account: string, work: (tx: ExecutionTransaction) => Promise): Promise { - let matched: typeof this.fault; - const result = await this.delegate.transact(account, tx => - work( - new Proxy(tx, { - get: (target, key: keyof ExecutionTransaction) => { - const value = target[key]; - if (typeof value !== 'function') { - return value; - } - return async (...args: unknown[]) => { - const fault = this.fault; - const hit = fault && key === fault.method && fault.matches(args[0]); - if (hit) { - this.fault = undefined; - matched = fault; - } - if (hit && fault.stage === 'before') { - throw new Error('injected transaction failure'); - } - const answer = await Reflect.apply(value, target, args); - if (hit && fault.stage === 'after') { - throw new Error('injected transaction failure'); - } - return answer; - }; - }, - }) - ) - ); - if (matched?.stage === 'commit') { - if (matched.hook) { - await matched.hook(); - } - throw new Error('injected lost commit acknowledgement'); - } - return result; - } -} diff --git a/test/integration/analytics-math.test.ts b/test/integration/analytics-math.test.ts deleted file mode 100644 index 5bf861f2..00000000 --- a/test/integration/analytics-math.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - dayMs, - equityAnalysis, - factorStatistics, - performanceAnalysis, - returnStatistics, - tradeStatistics, -} from '@stock-bot/calculations/analytics'; -import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer'; -import golden from '../fixtures/analytics-golden.json'; - -const start = Date.parse('2024-01-01T00:00:00Z'); -const points = (values: number[]) => - values.map((value, i) => ({ timestamp: start + i * dayMs, value })); - -describe('pure, fraction-based analytics golden fixtures', () => { - test('drawdown depths belong to each period, equal peaks recover, and ongoing periods use observed time', () => { - const result = equityAnalysis(points(golden.drawdowns.equity), 100); - result.periods.forEach((period, i) => { - expect(period.depth).toBeCloseTo(golden.drawdowns.depths[i]!); - expect(period.duration).toBe(golden.drawdowns.durations[i]!); - }); - expect(result.maxDrawdown).toBeCloseTo(0.2); - expect(result.currentDrawdown).toBe(0); - const recovered = equityAnalysis(points([100, 90, 100, 80]), 100); - expect(recovered.periods[0]?.recovery).toBe(2); - expect(recovered.periods[1]?.recovery).toBeNull(); - expect(recovered.periods[1]?.depth).toBeCloseTo(0.2); - expect(recovered.maxDrawdownDuration).toBe(1); - const facade = new PerformanceAnalyzer(100); - points(golden.drawdowns.equity).forEach(point => - facade.addEquityPoint(new Date(point.timestamp), point.value) - ); - expect(facade.analyzeDrawdowns().drawdownPeriods.map(period => period.depth)).toEqual( - result.periods.map(period => period.depth) - ); - }); - test('CAGR requires positive capital, positive ending equity and positive elapsed time', () => { - expect(equityAnalysis([], 100).annualizedReturn).toBeNull(); - const growth = equityAnalysis( - [ - { timestamp: start, value: 100 }, - { timestamp: start + 730 * dayMs, value: 121 }, - ], - 100 - ); - expect(growth.totalReturn).toBeCloseTo(0.21); - expect(growth.annualizedReturn).toBeCloseTo(0.1); - for (const end of [0, -10]) - expect(equityAnalysis(points([100, end]), 100).annualizedReturn).toBeNull(); - expect(() => equityAnalysis(points([100]), 0)).toThrow(); - expect(() => equityAnalysis(points([100, NaN]), 100)).toThrow('finite'); - expect(() => equityAnalysis(points([100, 110]).reverse(), 100)).toThrow('ordered'); - const sameTime = new PerformanceAnalyzer(100); - sameTime.addEquityPoint(new Date(start), 100); - sameTime.addEquityPoint(new Date(start), 101); - expect(sameTime.analyze().cagr).toBeNull(); - expect(sameTime.analyze().annualizedReturn).toBeNull(); - expect(sameTime.exportReport()).toContain('CAGR: N/A'); - expect(sameTime.exportReport()).not.toMatch(/Infinity|NaN/); - }); - test('UTC grouping keeps first-period returns and never associates a skipped denominator with another month', () => { - const result = equityAnalysis( - [ - { timestamp: Date.parse('2024-01-31T23:30:00Z'), value: 110 }, - { timestamp: Date.parse('2024-02-01T00:30:00Z'), value: 0 }, - { timestamp: Date.parse('2024-03-01T00:30:00Z'), value: 50 }, - { timestamp: Date.parse('2024-04-01T00:30:00Z'), value: 75 }, - ], - 100 - ); - expect(result.dailyReturns[0]).toBeCloseTo(0.1); - expect(result.monthlyReturns['2024-01']).toBeCloseTo(0.1); - expect(result.monthlyReturns['2024-02']).toBe(-1); - expect(result.monthlyReturns['2024-03']).toBeUndefined(); - expect(result.monthlyReturns['2024-04']).toBe(0.5); - }); - test('sample volatility and full-series downside RMS use daily fractions, not percentage points', () => { - const result = returnStatistics(golden.daily.returns, 0); - expect(result.volatility! ** 2).toBeCloseTo(golden.daily.annualVariance, 10); - expect(result.downsideDeviation! ** 2).toBeCloseTo(golden.daily.annualDownsideVariance, 10); - expect(result.sharpeRatio).toBeCloseTo( - golden.daily.annualExcess / Math.sqrt(golden.daily.annualVariance) - ); - expect(result.sortinoRatio).toBeCloseTo( - golden.daily.annualExcess / Math.sqrt(golden.daily.annualDownsideVariance) - ); - expect(returnStatistics([], 0).volatility).toBeNull(); - expect(returnStatistics([0.1], 0).sharpeRatio).toBeNull(); - expect(returnStatistics([0, 0, 0], 0).sharpeRatio).toBeNull(); - expect(returnStatistics([0, 0, 0], 0).volatility).toBe(0); - expect(returnStatistics([0.1, 0.2], 0).sortinoRatio).toBeNull(); - expect(() => returnStatistics([Infinity])).toThrow('finite'); - expect(() => returnStatistics(Array(3))).toThrow('finite'); - }); - test('historical loss tails require enough samples and have one shared positive-loss sign convention', () => { - expect(returnStatistics(Array(19).fill(-0.01)).var95).toBeNull(); - const risk = returnStatistics(Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05)); - expect(risk.var95).toBeCloseTo(0.046); - expect(risk.cvar95).toBeCloseTo(0.048); - expect(risk.var99).toBeCloseTo(0.05); - expect(returnStatistics(Array(100).fill(0.01)).var95).toBe(0); - }); - test('trade statistics count completed trades, break streaks on breakeven and preserve undefined ratios', () => { - const result = tradeStatistics( - golden.trades.pnl.map(pnl => ({ pnl, holdingPeriod: 60 })), - 365 - ); - const { pnl: _pnl, ...expected } = golden.trades; - expect(result).toMatchObject(expected); - expect(result.avgWin).toBe(15); - expect(result.avgLoss).toBe(2.5); - expect(result.avgHoldingPeriod).toBe(60); - expect(result.avgTradesPerDay).toBeCloseTo(8 / 252); - expect(tradeStatistics([], 0).profitFactor).toBeNull(); - expect(tradeStatistics([{ pnl: 10, holdingPeriod: 0 }], 1).profitFactor).toBeNull(); - expect(tradeStatistics([{ pnl: -10, holdingPeriod: 0 }], 1).profitFactor).toBe(0); - expect(() => tradeStatistics([{ pnl: NaN, holdingPeriod: 0 }], 1)).toThrow(); - }); - test('benchmark math validates alignment and uses the same fraction-based excess-return convention', () => { - const benchmark = [-0.01, 0.02, -0.02, 0.03]; - const result = factorStatistics( - benchmark.map(value => 2 * value), - benchmark, - 0 - ); - expect(result.beta).toBeCloseTo(2); - expect(result.alpha).toBeCloseTo(0); - expect(result.correlation).toBeCloseTo(1); - expect(factorStatistics([0, 0], [0, 0]).beta).toBeNull(); - expect(() => factorStatistics([0], [0, 0])).toThrow('same length'); - expect(() => factorStatistics([0, NaN], [0, 0])).toThrow('finite'); - }); - test('facade input/output detachment, cache invalidation and legacy report percentages are explicit', () => { - const analyzer = new PerformanceAnalyzer(100); - const date = new Date(start); - analyzer.addEquityPoint(date, 100); - date.setUTCFullYear(2030); - analyzer.addEquityPoint(new Date(start + 365 * dayMs), 110); - expect(analyzer.analyze().totalReturn).toBeCloseTo(10); - expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1); - const view = analyzer.getAnalysis(); - view.metrics.totalReturn = 999; - expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1); - analyzer.addEquityPoint(new Date(start + 366 * dayMs), 120); - expect(analyzer.analyze().totalReturn).toBeCloseTo(20); - const bankrupt = performanceAnalysis(points([100, 0, -10]), [], 100); - expect(bankrupt.metrics.totalReturn).toBeCloseTo(-1.1); - expect(bankrupt.metrics.cagr).toBeNull(); - expect( - Object.values(bankrupt.metrics).every(value => value === null || Number.isFinite(value)) - ).toBe(true); - }); -}); diff --git a/test/integration/analytics-service.test.ts b/test/integration/analytics-service.test.ts deleted file mode 100644 index 4a460791..00000000 --- a/test/integration/analytics-service.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -import type { AxiosRequestConfig } from 'axios'; -import { describe, expect, test } from 'bun:test'; -import { createAnalyticsRoutes } from '../../apps/stock/orchestrator/src/api/rest/analytics'; -import { AnalyticsServiceError } from '../../apps/stock/orchestrator/src/services/analytics-error'; -import { AnalyticsService } from '../../apps/stock/orchestrator/src/services/AnalyticsService'; -import { logger } from '../fixtures/execution'; - -const performance = { - totalReturn: 0, - sharpeRatio: null, - sortinoRatio: null, - maxDrawdown: 0, - winRate: 0, - profitFactor: null, - avgWin: 0, - avgLoss: 0, - totalTrades: 0, -}; -const risk = { currentExposure: 0, dailyPnl: 0, positionCount: 0, grossExposure: 0, var95: null }; -const optimize = { - symbols: ['A.US', 'B.US'], - returns: [ - [0.01, -0.01], - [-0.01, 0.02], - ], - constraints: { minWeight: 0.1, maxWeight: 0.9 }, -}; -function fixture(initial: unknown = performance) { - let data = initial; - let failure = false; - let now = 0; - const requests: AxiosRequestConfig[] = []; - const service = new AnalyticsService( - { logger }, - { - baseUrl: 'http://analytics.fixture', - now: () => now, - client: { - async request(request) { - requests.push(structuredClone(request)); - if (failure) throw new Error('Private upstream diagnostic must never reach the client'); - return { data }; - }, - }, - } - ); - return { - service, - requests, - routes: createAnalyticsRoutes({ logger, custom: { AnalyticsService: service } }), - setData(value: unknown) { - data = value; - }, - fail(value = true) { - failure = value; - }, - advance(ms: number) { - now += ms; - }, - }; -} -const post = (body: unknown) => ({ - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify(body), -}); -const from = new Date('2024-01-01T00:00:00Z'); -const to = new Date('2024-02-01T00:00:00Z'); - -describe('analytics upstream contract and HTTP failure semantics', () => { - test('outages never become zero metrics, equal weights, normal regimes, identity matrices or false model misses', async () => { - const f = fixture(); - f.fail(); - for (const [path, options] of [ - [ - '/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString(), - undefined, - ], - ['/risk/P', undefined], - ['/regime', undefined], - ['/optimize', post(optimize)], - ['/correlation', post({ symbols: ['A.US', 'B.US'] })], - ['/predict', post({ modelId: 'model', features: { x: 1 } })], - ] as const) { - const response = await f.routes.request(path, options); - expect(response.status).toBe(503); - expect(await response.json()).toEqual({ - error: 'Analytics service is unavailable', - code: 'analytics_unavailable', - }); - } - await expect(f.service.runBacktestAnalysis('run')).rejects.toBeInstanceOf( - AnalyticsServiceError - ); - expect( - f.requests.every(request => request.timeout === 5000 && request.maxContentLength === 1048576) - ).toBe(true); - const missing = await createAnalyticsRoutes({ logger }).request('/risk/P'); - expect(missing.status).toBe(503); - }); - test('invalid upstream values are 502, not client 400, and never enter the success cache', async () => { - const f = fixture({ ...performance, totalReturn: '0' }); - const path = - '/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString(); - const response = await f.routes.request(path); - expect(response.status).toBe(502); - expect((await response.json()).code).toBe('analytics_invalid_response'); - f.setData(performance); - expect(await f.service.getPerformanceMetrics('P', from, to)).toEqual(performance); - expect(f.requests).toHaveLength(2); - const view = await f.service.getPerformanceMetrics('P', from, to); - view.totalReturn = 100; - expect((await f.service.getPerformanceMetrics('P', from, to)).totalReturn).toBe(0); - f.setData({ ...performance, totalReturn: Infinity }); - f.advance(60000); - await expect(f.service.getPerformanceMetrics('P', from, to)).rejects.toMatchObject({ - status: 502, - }); - }); - test('cache expiration honors each entry TTL and expired failures never masquerade as fresh observations', async () => { - const f = fixture({ regime: 'observed-bull' }); - expect(await f.service.detectMarketRegime()).toBe('observed-bull'); - f.setData({ regime: 'observed-bear' }); - f.advance(60001); - expect(await f.service.detectMarketRegime()).toBe('observed-bull'); - expect(f.requests).toHaveLength(1); - f.advance(240000); - expect(await f.service.detectMarketRegime()).toBe('observed-bear'); - f.setData(risk); - expect(await f.service.getRiskMetrics('P')).toEqual(risk); - f.advance(60000); - f.fail(); - await expect(f.service.getRiskMetrics('P')).rejects.toMatchObject({ status: 503 }); - f.fail(false); - f.setData({ ...risk, dailyPnl: -10 }); - expect((await f.service.getRiskMetrics('P')).dailyPnl).toBe(-10); - }); - test('success cache is bounded and identifiers are encoded rather than interpreted as paths', async () => { - const f = fixture(risk); - for (let i = 0; i < 129; i++) await f.service.getRiskMetrics(String(i)); - await f.service.getRiskMetrics('0'); - expect(f.requests).toHaveLength(130); - await f.service.getRiskMetrics('A/B?secret'); - expect(f.requests.at(-1)?.url).toBe('http://analytics.fixture/analytics/risk/A%2FB%3Fsecret'); - }); - test('optimization forwards real symbol identities and maps the Python wire contract without fabricating weights', async () => { - const f = fixture({ - symbols: optimize.symbols, - weights: [0.4, 0.6], - expected_return: 0.1, - expected_risk: 0.2, - sharpe_ratio: null, - }); - const result = await f.service.optimizePortfolio(optimize); - expect(result).toEqual({ - symbols: optimize.symbols, - weights: [0.4, 0.6], - expectedReturn: 0.1, - expectedRisk: 0.2, - sharpeRatio: null, - }); - expect(f.requests[0]?.data).toMatchObject({ - symbols: optimize.symbols, - returns: optimize.returns, - constraints: { min_weight: 0.1, max_weight: 0.9 }, - }); - for (const data of [ - { - symbols: ['B.US', 'A.US'], - weights: [0.4, 0.6], - expected_return: 0.1, - expected_risk: 0.2, - sharpe_ratio: 1, - }, - { - symbols: optimize.symbols, - weights: [0.4, 0.4], - expected_return: 0.1, - expected_risk: 0.2, - sharpe_ratio: 1, - }, - { - symbols: optimize.symbols, - weights: [0.4, 0.6], - expected_return: NaN, - expected_risk: 0.2, - sharpe_ratio: 1, - }, - ]) { - f.setData(data); - await expect(f.service.optimizePortfolio(optimize)).rejects.toMatchObject({ status: 502 }); - } - }); - test('correlations validate dimensions, ordered identities, symmetry, range and positive semidefiniteness', async () => { - const f = fixture({ - symbols: ['A.US', 'B.US'], - matrix: [ - [1, 0.5], - [0.5, 1], - ], - }); - expect(await f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).toEqual([ - [1, 0.5], - [0.5, 1], - ]); - expect(f.requests[0]?.data).toEqual(['A.US', 'B.US']); - for (const matrix of [ - [[1]], - [ - [1, 2], - [2, 1], - ], - [ - [1, 0.5], - [0.2, 1], - ], - [ - [0.9, 0], - [0, 1], - ], - [ - [1, NaN], - [NaN, 1], - ], - ]) { - f.setData({ symbols: ['A.US', 'B.US'], matrix }); - await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({ - status: 502, - }); - } - f.setData({ - symbols: ['A.US', 'B.US', 'C.US'], - matrix: [ - [1, 0.9, 0.9], - [0.9, 1, -0.9], - [0.9, -0.9, 1], - ], - }); - await expect( - f.service.calculateCorrelationMatrix(['A.US', 'B.US', 'C.US']) - ).rejects.toMatchObject({ status: 502 }); - f.setData({ - symbols: ['B.US', 'A.US'], - matrix: [ - [1, 0], - [0, 1], - ], - }); - await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({ - status: 502, - }); - }); - test('model and backtest responses validate identity, finite JSON and wire field names', async () => { - const f = fixture({ - model_id: 'model', - prediction: 0, - probability: null, - metadata: { version: 'v1' }, - }); - expect((await f.service.predictWithModel('model', { x: 1 })).prediction).toBe(0); - expect(f.requests[0]?.data).toEqual({ model_id: 'model', features: { x: 1 } }); - f.setData({ model_id: 'wrong-model', prediction: 1 }); - await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({ - status: 502, - }); - f.setData({ model_id: 'model', prediction: 1, metadata: { nested: { value: Infinity } } }); - await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({ - status: 502, - }); - f.setData({ - backtest_id: 'other', - metrics: {}, - statistics: {}, - risk_analysis: {}, - trade_analysis: {}, - }); - await expect(f.service.runBacktestAnalysis('run')).rejects.toMatchObject({ status: 502 }); - }); - test('invalid client requests return 400 before upstream access', async () => { - const f = fixture(); - for (const [path, options] of [ - [ - '/performance/P?start_date=' + to.toISOString() + '&end_date=' + from.toISOString(), - undefined, - ], - ['/optimize', post({ ...optimize, returns: [[1], [2]] })], - ['/optimize', post({ ...optimize, constraints: { minWeight: 0.8 } })], - ['/correlation', post({ symbols: ['A.US', 'A.US'] })], - ['/predict', post({ modelId: '', features: { x: 1 } })], - ['/predict', { method: 'POST', body: '{broken' }], - ] as const) - expect((await f.routes.request(path, options)).status).toBe(400); - expect(f.requests).toHaveLength(0); - }); -}); diff --git a/test/integration/analytics-ui.test.tsx b/test/integration/analytics-ui.test.tsx index 1f795443..3a5b1d83 100644 --- a/test/integration/analytics-ui.test.tsx +++ b/test/integration/analytics-ui.test.tsx @@ -2,7 +2,6 @@ import { expect, test } from 'bun:test'; import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import type { BacktestRunResult } from '@stock-bot/types'; -import { BacktestMetrics } from '../../apps/stock/web-app/src/features/backtest/components/BacktestMetrics'; import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics'; const metrics = { @@ -19,40 +18,7 @@ const metrics = { avgLoss: 0, }; const text = (html: string) => html.replace(/<[^>]*>/g, ''); -test('detailed metrics distinguish undefined ratios from legitimate zero return and exposure', () => { - const html = renderToStaticMarkup( - createElement(BacktestMetrics, { - isLoading: false, - result: { - id: 'fixture', - config: { - name: 'fixture', - startDate: new Date('2024-01-01'), - endDate: new Date('2024-02-01'), - initialCapital: 1000, - symbols: ['A.US'], - strategy: 'sma', - speedMultiplier: 0, - commission: 0, - slippage: 0, - }, - metrics, - positions: [], - trades: [], - performanceData: [], - analytics: { exposureTime: 0 }, - }, - }) - ); - const rendered = text(html); - expect(rendered).toContain('Sharpe RatioN/A'); - expect(rendered).toContain('Profit FactorN/A'); - expect(rendered).toContain('Calmar RatioN/A'); - expect(rendered).toContain('Sortino RatioN/A'); - expect(rendered).toContain('Total Return0.00%'); - expect(rendered).toContain('Exposure Time0.0%'); - expect(rendered).not.toMatch(/Infinity|NaN/); -}); + test('compact metrics preserve null ratios and render a genuine zero profit', () => { const result: BacktestRunResult = { runId: 'fixture', @@ -88,34 +54,3 @@ test('compact metrics preserve null ratios and render a genuine zero profit', () expect(rendered).toContain('$0.00'); expect(rendered).not.toMatch(/Infinity|NaN/); }); - -test('null_metrics: detailed exposure is unavailable rather than a measured zero', () => { - const rendered = text( - renderToStaticMarkup( - createElement(BacktestMetrics, { - isLoading: false, - result: { - id: 'fixture', - config: { - name: 'fixture', - startDate: new Date('2024-01-01'), - endDate: new Date('2024-02-01'), - initialCapital: 1000, - symbols: ['A.US'], - strategy: 'sma', - speedMultiplier: 0, - commission: 0, - slippage: 0, - }, - metrics, - positions: [], - trades: [], - performanceData: [], - analytics: { exposureTime: null }, - }, - }) - ) - ); - expect(rendered).toContain('Exposure TimeN/A'); - expect(rendered).not.toContain('Exposure Time0.0%'); -}); diff --git a/test/integration/async-strategy-replay.test.ts b/test/integration/async-strategy-replay.test.ts index ad59a154..f4131f5a 100644 --- a/test/integration/async-strategy-replay.test.ts +++ b/test/integration/async-strategy-replay.test.ts @@ -6,8 +6,8 @@ import { runReplaySessionAsync, } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import type { ReplayResultFormat } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; +import type { ReplayResultFormat } from '@stock-bot/stock-config/canonical-replay'; import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller'; import { nativeReplayFixture } from '../fixtures/native-replay'; diff --git a/test/integration/backtest-components.test.ts b/test/integration/backtest-components.test.ts deleted file mode 100644 index 5689e71c..00000000 --- a/test/integration/backtest-components.test.ts +++ /dev/null @@ -1,436 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import type { HistoricalDataset } from '@stock-bot/types'; -import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer'; -import { - BacktestPlayback, - type PlaybackProgress, -} from '../../apps/stock/orchestrator/src/backtest/BacktestPlayback'; -import { BacktestReport } from '../../apps/stock/orchestrator/src/backtest/BacktestReport'; -import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import type { ClosedTrade } from '../../apps/stock/orchestrator/src/backtest/native-result'; -import { formatReport } from '../../apps/stock/orchestrator/src/backtest/report-format'; -import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager'; -import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; - -const day = 86400000; -const start = Date.parse('2024-01-01T00:00:00Z'); -const config = BacktestConfigSchema.parse({ - mode: 'backtest', - strategy: 'sma-crossover', - symbols: ['A.US', 'B.US'], - startDate: new Date(start).toISOString(), - endDate: '2024-03-01T00:00:00Z', - initialCapital: 1000, - dataFrequency: '1d', -}); -const bars = [0, 1, 2].flatMap(index => - config.symbols.map(symbol => ({ - symbol, - timestamp: start + index * day, - open: 100, - high: 101, - low: 99, - close: 100, - volume: 1000, - vwap: 100, - })) -); -const dataset: HistoricalDataset = { - manifest: { - version: 1, - hash: '0'.repeat(64), - instruments: config.symbols.map(id => ({ id, symbol: id.split('.')[0]!, exchange: 'US' })), - startDate: config.startDate, - endDate: config.endDate, - interval: '1d', - policy: { adjustment: 'raw', timestamp: 'utc-session-date' }, - volumePolicy: 'reported', - qualityPolicy: 'reject-invalid-no-interpolation', - sources: config.symbols.map(instrumentId => ({ - instrumentId, - provider: 'synthetic', - revision: 'fixture', - })), - barCount: bars.length, - }, - bars, -}; -const trade: ClosedTrade = { - id: 'closed-1', - symbol: 'A.US', - side: 'Buy', - quantity: 1, - entry_price: 100, - exit_price: 90, - entry_time: new Date(start).toISOString(), - exit_time: new Date(start + day).toISOString(), - pnl: -10, - pnl_percent: -10, - commission: 0, - duration_ms: day, -}; - -function deferred() { - let resolve!: (value: T) => void; - let reject!: (reason: unknown) => void; - const promise = new Promise((done, fail) => { - resolve = done; - reject = fail; - }); - return { promise, resolve, reject }; -} -async function deadline(work: Promise): Promise { - let timer: ReturnType | undefined; - try { - return await Promise.race([ - work, - new Promise((_resolve, reject) => { - timer = setTimeout(() => reject(new Error('Control did not settle promptly')), 500); - }), - ]); - } finally { - clearTimeout(timer); - } -} -const turn = () => new Promise(resolve => setTimeout(resolve, 0)); - -describe('backtest playback isolation and controls', () => { - test('a cursor consumes frozen inputs in order, preserves timestamp ties and yields to timers', async () => { - const playback = new BacktestPlayback(start, null); - const events = Object.freeze( - Array.from({ length: 1001 }, (_, id) => ({ id, timestamp: start + Math.floor(id / 2) })) - ); - const seen: number[] = []; - const updates: PlaybackProgress[] = []; - let timerRan = false; - setTimeout(() => { - timerRan = true; - }, 0); - await playback.process( - events, - event => event.timestamp, - async event => { - seen.push(event.id); - }, - update => updates.push(update) - ); - playback.finish(); - expect(seen).toEqual(events.map(event => event.id)); - expect(timerRan).toBe(true); - expect(events).toHaveLength(1001); - expect(updates.filter(update => update.progress === 100)).toHaveLength(1); - expect(updates.at(-1)).toMatchObject({ - processed: 1001, - total: 1001, - remaining: 0, - progress: 100, - }); - expect(playback.getStatus()).toMatchObject({ - isRunning: false, - isPaused: false, - progress: 100, - }); - }); - - test('pause blocks delivery and resume wakes it without a polling interval', async () => { - const playback = new BacktestPlayback(start, null); - playback.pause(); - let processed = 0; - const work = playback.process( - [start], - time => time, - async () => { - processed++; - }, - () => {} - ); - await turn(); - expect(processed).toBe(0); - playback.resume(); - await deadline(work); - expect(processed).toBe(1); - playback.finish(); - playback.pause(); - expect(playback.getStatus().isPaused).toBe(false); - }); - - test('stop wakes a paused run and never emits completed progress', async () => { - const playback = new BacktestPlayback(start, null); - playback.pause(); - const updates: number[] = []; - const work = playback.process( - [start], - time => time, - async () => { - throw new Error('Must not execute'); - }, - update => updates.push(update.progress) - ); - const outcome = work.catch(error => error); - await turn(); - playback.stop(); - expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError); - expect(updates).toEqual([]); - playback.finish(); - }); - - test.each(['stop', 'setSpeed'] as const)('%s interrupts a long pacing timer', async control => { - const playback = new BacktestPlayback(start, 0.001); - let processed = 0; - const work = playback.process( - [start], - time => time, - async () => { - processed++; - }, - () => {} - ); - const outcome = work.catch(error => error); - await turn(); - if (control === 'stop') playback.stop(); - else playback.setSpeed(null); - const settled = await deadline(outcome); - if (control === 'stop') expect(settled).toBeInstanceOf(BacktestCancelledError); - expect(processed).toBe(control === 'stop' ? 0 : 1); - playback.finish(); - }); - - test('cancellation detaches a slow read and a late rejection cannot resume execution', async () => { - const playback = new BacktestPlayback(start, null); - const load = deferred(); - const entered = deferred(); - const work = playback.read(() => { - entered.resolve(); - return load.promise; - }); - const outcome = work.catch(error => error); - await entered.promise; - playback.stop(); - expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError); - load.reject(new Error('Late read failure')); - await turn(); - let calls = 0; - await expect( - playback.read(async () => { - calls++; - return 1; - }) - ).rejects.toBeInstanceOf(BacktestCancelledError); - expect(calls).toBe(0); - playback.finish(); - }); - - test('failed delivery cannot advance its cursor or claim completion', async () => { - const playback = new BacktestPlayback(start, null); - const updates: number[] = []; - await expect( - playback.process( - [1, 2], - time => time, - async time => { - if (time === 2) throw new Error('delivery failure'); - }, - update => updates.push(update.progress) - ) - ).rejects.toThrow('delivery failure'); - expect(playback.getStatus().progress).toBe(50); - expect(updates).not.toContain(100); - playback.finish(); - }); - - test('speed validation rejects non-finite, zero and negative values', () => { - for (const speed of [NaN, Infinity, 0, -1]) { - expect(() => new BacktestPlayback(start, speed)).toThrow('positive or null'); - expect(() => new BacktestPlayback(start, null).setSpeed(speed)).toThrow('positive or null'); - } - }); - - test('one playback cannot run two cursors or continue after finalization', async () => { - const playback = new BacktestPlayback(start, null); - await playback.process( - [start], - time => time, - async () => {}, - () => {} - ); - await expect( - playback.process( - [start], - time => time, - async () => {}, - () => {} - ) - ).rejects.toThrow('already started'); - playback.finish(); - await expect(playback.read(async () => 1)).rejects.toBeInstanceOf(BacktestCancelledError); - }); -}); - -describe('detached, repeatable backtest reporting', () => { - test('analysis runs once per completion and formatting never re-analyzes retained inputs', () => { - const analyze = spyOn(PerformanceAnalyzer.prototype, 'analyze'); - try { - const report = new BacktestReport(config, 'cached'); - report.record(start + day, 990); - report.complete(dataset, [trade], [], {}); - report.export('html'); - report.export('csv'); - report.export('json'); - expect(analyze).toHaveBeenCalledTimes(1); - } finally { - analyze.mockRestore(); - } - }); - test('exports retain completed equity and do not append the same trades repeatedly', () => { - const report = new BacktestReport(config, 'report'); - report.record(start, 1000); - report.record(start + day, 990); - const trades = structuredClone([trade]); - const result = report.complete(dataset, trades, [], { totalIssues: 0 }); - expect(result.metrics.totalTrades).toBe(1); - expect(result.config).toMatchObject({ commission: 0.001, slippage: 0.0001 }); - const first = report.export(); - const parsed = JSON.parse(first); - expect(parsed.summary.totalTrades).toBe(1); - expect(parsed.equityCurve.at(-1).value).toBe(990); - trades[0]!.pnl = 10000; - result.equity[0]!.value = 1; - report.export('csv'); - report.export('html'); - expect(report.export()).toBe(first); - expect(() => report.complete(dataset, [], [], {})).toThrow('already finalized'); - expect(() => report.record(start + day * 2, 0)).toThrow('already finalized'); - }); - - test('zero and negative equity remain losses, never a fabricated starting balance', () => { - const report = new BacktestReport(config, 'loss'); - report.record(start + day, 0); - report.record(start + day * 2, -100); - const result = report.complete(dataset, [], [], {}); - expect(result.equity.map(point => point.value)).toEqual([1000, 0, -100]); - expect(result.metrics.totalReturn).toBeCloseTo(-110); - expect(result.metrics.maxDrawdown).toBe(1.1); - expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110); - expect( - Object.values(result.analytics.riskMetrics).every( - value => value === null || Number.isFinite(value) - ) - ).toBe(true); - expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true); - }); - - test('a one-timestamp run has finite analytics, stable timestamp ties and grouped OHLC', () => { - const report = new BacktestReport(config, 'single'); - report.record(start, 999); - report.record(start, 998); - const result = report.complete(dataset, [], [], {}); - expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]); - expect(result.metrics.totalReturn).toBeCloseTo(-0.2); - expect(result.metrics.maxDrawdown).toBeCloseTo(0.002); - expect(result.analytics.dailyReturns).toHaveLength(1); - expect(result.analytics.dailyReturns[0]).toBeCloseTo(-0.2); - expect(result.metrics.sharpeRatio).toBeNull(); - expect(result.metrics.annualizedReturn).toBeNull(); - expect( - Object.values(result.analytics.riskMetrics).every( - value => value === null || Number.isFinite(value) - ) - ).toBe(true); - expect(Object.keys(result.ohlcData)).toEqual(config.symbols); - expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([ - start, - start + day, - start + day * 2, - ]); - expect(result.ohlcData['B.US']).toHaveLength(3); - }); - - test('ongoing drawdown duration uses the simulated horizon, not the wall clock', () => { - const report = new BacktestReport(config, 'drawdown'); - report.record(start + day, 900); - report.record(start + day * 4, 800); - report.complete(dataset, [], [], {}); - expect(JSON.parse(report.export()).summary.maxDrawdownDuration).toBe(3); - expect(report.export('html')).toContain('20.00%'); - expect(JSON.parse(report.export()).performanceReport).toContain('Max Drawdown: 20.00%'); - }); - - test('monthly grouping uses UTC, and invalid or unordered observations fail explicitly', () => { - const report = new BacktestReport(config, 'utc'); - report.record(Date.parse('2024-01-31T23:30:00Z'), 1100); - report.record(Date.parse('2024-02-01T00:30:00Z'), 1200); - const result = report.complete(dataset, [], [], {}); - expect(Object.keys(result.analytics.monthlyReturns)).toEqual(['2024-01', '2024-02']); - expect(result.analytics.monthlyReturns['2024-01']).toBeCloseTo(10); - expect(result.analytics.monthlyReturns['2024-02']).toBeCloseTo((100 / 1100) * 100); - const invalid = new BacktestReport(config, 'invalid'); - expect(() => invalid.export()).toThrow('No completed'); - expect(() => invalid.record(start - 1, 1000)).toThrow('Out-of-order'); - expect(() => invalid.record(start, NaN)).toThrow('Invalid'); - expect(() => invalid.record(Infinity, 1000)).toThrow('Invalid'); - const insolvent = new BacktestReport(config, 'insolvent'); - insolvent.record(start + day, 0); - insolvent.record(Date.parse('2024-02-01T00:30:00Z'), -10); - const losses = insolvent.complete(dataset, [], [], {}); - expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 }); - }); - - test('risk analytics and summary share fraction-based math without 100x percentage scaling', () => { - const report = new BacktestReport(config, 'risk'); - let value = config.initialCapital; - for (let i = 1; i <= 30; i++) { - value *= 1 + (i % 2 ? -0.01 : 0.02); - report.record(start + i * day, value); - } - const result = report.complete(dataset, [], [], {}); - const returns = result.analytics.dailyReturns.map(value => value / 100); - const average = returns.reduce((sum, value) => sum + value, 0) / returns.length; - const expected = - Math.sqrt( - returns.reduce((sum, value) => sum + (value - average) ** 2, 0) / (returns.length - 1) - ) * Math.sqrt(252); - expect(result.analytics.riskMetrics.volatility).toBeCloseTo(expected, 10); - const summary = JSON.parse(report.export()).summary; - expect(summary.volatility / 100).toBeCloseTo(expected, 10); - expect(summary.var95 / 100).toBeCloseTo(result.analytics.riskMetrics.var95!, 10); - expect(summary.cvar95 / 100).toBeCloseTo(result.analytics.riskMetrics.cvar95!, 10); - }); - - test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => { - const input = structuredClone(dataset); - for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) { - bar.close = bar.symbol === 'A.US' ? 150 : 50; - bar.open = bar.close; - bar.high = bar.close + 1; - bar.low = bar.close - 1; - bar.vwap = bar.close; - } - const before = structuredClone(input); - const inspector = new DataManager({ - async getHistoricalBars() { - return []; - }, - }); - inspector.inspectDataset(input); - const quality = inspector.getDataQualityReport(); - expect(quality.totalIssues).toBe(4); - expect(quality.bySymbol).toEqual({ 'A.US': 2, 'B.US': 2 }); - expect(quality.issues.map(issue => issue.symbol)).toEqual(['A.US', 'A.US', 'B.US', 'B.US']); - expect(input).toEqual(before); - inspector.inspectDataset(dataset); - expect(inspector.getDataQualityReport().totalIssues).toBe(0); - }); - - test('HTML escapes text and CSV quotes cells while preserving numeric losses', () => { - const report = new BacktestReport(config, 'escaping'); - report.record(start + day, 990); - report.complete(dataset, [{ ...trade, symbol: '' }], [], {}); - expect(report.export('html')).not.toContain('"'); - expect(report.export('csv')).toContain(',-10,-10'); - const snapshot = JSON.parse(report.export()); - snapshot.trades[0].symbol = '=HYPERLINK("hostile")'; - expect(formatReport(snapshot, 'csv')).toContain('"\'=HYPERLINK(""hostile"")"'); - }); -}); diff --git a/test/integration/backtest-ledger.test.ts b/test/integration/backtest-ledger.test.ts deleted file mode 100644 index 9ed567ff..00000000 --- a/test/integration/backtest-ledger.test.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; -import { - defaultRiskLimits, - type Account, - type StoredOrder, -} from '../../apps/stock/orchestrator/src/execution/model'; -import type { ExecutionTransaction } from '../../apps/stock/orchestrator/src/execution/repository'; -import type { - MarketInput, - StrategyCheckpoint, - StrategyOrderIntent, -} from '../../apps/stock/orchestrator/src/execution/strategy-recovery'; - -const initial: Account = { - initialCapital: 10000, - cash: 10000, - realizedPnl: 0, - dailyPnl: 0, - day: '2024-01-01', - commission: 0.001, - slippage: 0, - limits: { ...defaultRiskLimits }, - maxQuoteAgeMs: 60000, - positions: {}, - quotes: {}, - strategyPositions: {}, -}; -const input: MarketInput = { - id: '10', - sequence: 1, - status: 'pending', - market: { - type: 'trade', - data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: 1 }, - }, -}; -const request = { - symbol: 'A.US', - side: 'buy', - quantity: 1, - orderType: 'market', - timeInForce: 'DAY', - clientOrderId: '__proto__', -} as const; -const order: StoredOrder = { - request, - fingerprint: 'fingerprint', - policy: { commission: 0.001, slippage: 0 }, - report: { - orderId: 'order', - clientOrderId: request.clientOrderId, - symbol: request.symbol, - side: request.side, - quantity: 1, - status: 'accepted', - fills: [], - timestamp: 1, - }, -}; -const checkpoint: StrategyCheckpoint = { - strategyId: 'strategy', - config: { - id: 'strategy', - name: 'test', - enabled: true, - symbols: ['A.US'], - parameters: {}, - allocation: 1, - }, - configHash: 'hash', - version: 'v1', - enabled: true, - cursor: 0, - state: { count: 0 }, -}; -const intent: StrategyOrderIntent = { - clientOrderId: request.clientOrderId, - strategyId: checkpoint.strategyId, - sequence: 1, - request, - status: 'pending', -}; -const fill = { id: '__proto__', price: 100, quantity: 1, commission: 0.1, timestamp: 1, pnl: 0 }; -const journal = { - kind: 'market' as const, - market: input.market, - recipients: ['strategy'], - account: initial, -}; - -async function fixture(account = initial) { - const repository = new BacktestExecutionRepository(); - await repository.initialize('run', account); - return { - repository, - transact: (work: (tx: ExecutionTransaction) => Promise) => - repository.transact('run', work), - }; -} - -describe('run-local execution transaction isolation', () => { - test('uninitialized stores fail explicitly', async () => { - await expect(new BacktestExecutionRepository().transact('run', async () => 1)).rejects.toThrow( - 'not initialized' - ); - }); - - test('a failed transaction rolls back every table, index, sequence and account mutation', async () => { - const f = await fixture(); - await expect( - f.transact(async tx => { - tx.account.cash = 1; - await tx.putOrder(order); - await tx.insertFill(order.report.orderId, fill); - await tx.recordEvent('__proto__', 'hash'); - await tx.putStrategy(checkpoint); - await tx.putIntent(intent); - await tx.putInput(input); - await tx.appendJournal(journal); - expect(await tx.findOrder('__proto__')).toEqual(order); - expect(await tx.nextJournal(0)).toMatchObject({ sequence: 1 }); - throw new Error('rollback'); - }) - ).rejects.toThrow('rollback'); - await f.transact(async tx => { - expect(tx.account.cash).toBe(10000); - expect(tx.account.strategySequence).toBeUndefined(); - expect(await tx.findOrder('__proto__')).toBeUndefined(); - expect(await tx.getOrder('order')).toBeUndefined(); - expect(await tx.openOrders()).toEqual([]); - expect(await tx.strategies()).toEqual([]); - expect(await tx.nextIntent()).toBeUndefined(); - expect(await tx.nextInput()).toBeUndefined(); - expect(await tx.nextJournal(0)).toBeUndefined(); - expect(await tx.recordEvent('__proto__', 'hash')).toBe(true); - expect(await tx.insertFill('order', fill)).toBe(true); - }); - }); - - test('caller-owned objects, returned reads and retained transaction references cannot mutate commits', async () => { - const seed = structuredClone(initial); - const f = await fixture(seed); - seed.cash = 0; - const writes = structuredClone({ order, checkpoint, intent, input, journal }); - let escaped!: ExecutionTransaction; - const result = await f.transact(async tx => { - escaped = tx; - await tx.putOrder(writes.order); - await tx.putStrategy(writes.checkpoint); - await tx.putIntent(writes.intent); - await tx.putInput(writes.input); - await tx.appendJournal(writes.journal); - return tx.account; - }); - result.cash = 2; - escaped.account.cash = 3; - writes.order.report.status = 'rejected'; - writes.checkpoint.enabled = false; - writes.intent.status = 'dispatched'; - writes.input.status = 'applied'; - writes.journal.account.cash = 4; - await expect(escaped.putInput(input)).rejects.toThrow('finished'); - await f.transact(async tx => { - expect(tx.account.cash).toBe(10000); - (await tx.getOrder('order'))!.report.status = 'rejected'; - (await tx.strategies())[0]!.enabled = false; - (await tx.nextInput())!.status = 'applied'; - (await tx.nextIntent())!.status = 'dispatched'; - (await tx.nextJournal(0))!.payload.account.cash = 5; - }); - await f.transact(async tx => { - expect(await tx.openOrders()).toEqual([order]); - expect(await tx.strategies()).toEqual([checkpoint]); - expect(await tx.nextInput()).toEqual(input); - expect(await tx.nextIntent()).toEqual(intent); - expect((await tx.nextJournal(0))?.payload.account.cash).toBe(10000); - }); - }); - - test('uncloneable callback results roll back before publishing any staged writes', async () => { - const f = await fixture(); - await expect( - f.transact(async tx => { - tx.account.cash = 0; - await tx.putOrder(order); - return () => {}; - }) - ).rejects.toThrow(); - await f.transact(async tx => { - expect(tx.account.cash).toBe(10000); - expect(await tx.openOrders()).toEqual([]); - }); - }); - - test('transactions serialize and a failed predecessor does not poison the queue', async () => { - const f = await fixture(); - const results = await Promise.allSettled([ - f.transact(async tx => { - tx.account.cash -= 1; - await Promise.resolve(); - }), - f.transact(async tx => { - tx.account.cash = -1; - throw new Error('rollback'); - }), - f.transact(async tx => { - tx.account.cash -= 2; - }), - ]); - expect(results.map(result => result.status)).toEqual(['fulfilled', 'rejected', 'fulfilled']); - expect(await f.transact(async tx => tx.account.cash)).toBe(9997); - }); - - test('pending indexes reflect staged updates, and rollback preserves their previous heads', async () => { - const f = await fixture(); - await f.transact(async tx => { - await tx.putOrder(order); - await tx.putInput(input); - await tx.putInput({ ...input, id: '2', sequence: 2 }); - await tx.putIntent(intent); - await tx.putIntent({ - ...intent, - clientOrderId: 'next', - sequence: 2, - request: { ...request, clientOrderId: 'next' }, - }); - }); - const drain = async (tx: ExecutionTransaction) => { - await tx.putOrder({ ...order, report: { ...order.report, status: 'filled' } }); - await tx.putInput({ ...input, status: 'applied' }); - await tx.putIntent({ ...intent, status: 'dispatched' }); - expect(await tx.openOrders()).toEqual([]); - expect((await tx.nextInput())?.id).toBe('2'); - expect((await tx.nextIntent())?.clientOrderId).toBe('next'); - }; - await expect( - f.transact(async tx => { - await drain(tx); - throw new Error('rollback'); - }) - ).rejects.toThrow('rollback'); - await f.transact(async tx => { - expect(await tx.openOrders()).toEqual([order]); - expect(await tx.nextInput()).toEqual(input); - expect(await tx.nextIntent()).toEqual(intent); - await drain(tx); - }); - await f.transact(async tx => { - expect(await tx.openOrders()).toEqual([]); - expect((await tx.nextInput())?.id).toBe('2'); - expect((await tx.nextIntent())?.clientOrderId).toBe('next'); - }); - }); - - test('journal lookup supports nonzero sequences, gaps at the cursor and staged appends', async () => { - const f = await fixture({ ...initial, strategySequence: 20 }); - await f.transact(async tx => { - await tx.appendJournal(journal); - await tx.appendJournal(journal); - }); - await f.transact(async tx => { - await tx.appendJournal(journal); - for (const [cursor, expected] of [ - [-1, 21], - [20, 21], - [21, 22], - [22, 23], - [23, undefined], - [100, undefined], - ]) { - expect((await tx.nextJournal(cursor!))?.sequence).toBe(expected); - } - }); - }); - - test('sequence exhaustion cannot commit a partial journal or account change', async () => { - const f = await fixture({ ...initial, strategySequence: Number.MAX_SAFE_INTEGER }); - await expect( - f.transact(async tx => { - tx.account.cash = 1; - await tx.appendJournal(journal); - }) - ).rejects.toThrow('exhausted'); - expect(await f.transact(async tx => tx.account.cash)).toBe(10000); - }); - - test('pending-intent ties use deterministic sequence, strategy and client ID order', async () => { - const f = await fixture(); - await f.transact(async tx => { - for (const [strategyId, clientOrderId, sequence] of [ - ['b', '1', 1], - ['a', '2', 1], - ['a', '10', 1], - ['0', '0', 2], - ] as const) { - await tx.putIntent({ - ...intent, - strategyId, - clientOrderId, - sequence, - request: { ...request, clientOrderId }, - }); - } - }); - for (const expected of ['10', '2', '1', '0']) { - await f.transact(async tx => { - const next = (await tx.nextIntent())!; - expect(next.clientOrderId).toBe(expected); - await tx.putIntent({ ...next, status: 'dispatched' }); - }); - } - expect(await f.transact(tx => tx.nextIntent())).toBeUndefined(); - }); - - test('duplicate financial identities are indexed safely, including special JavaScript keys', async () => { - const f = await fixture(); - await f.transact(async tx => { - await tx.putOrder(order); - expect(await tx.findOrder('__proto__')).toEqual(order); - expect(await tx.insertFill('order', fill)).toBe(true); - expect(await tx.insertFill('order', fill)).toBe(false); - expect(await tx.recordEvent('constructor', 'hash')).toBe(true); - expect(await tx.recordEvent('constructor', 'hash')).toBe(false); - }); - await expect( - f.transact(tx => tx.putOrder({ ...order, report: { ...order.report, orderId: 'duplicate' } })) - ).rejects.toThrow('already exists'); - await expect(f.transact(tx => tx.recordEvent('constructor', 'different'))).rejects.toThrow( - 'Conflicting' - ); - expect(await f.transact(tx => tx.insertFill('order', fill))).toBe(false); - }); -}); diff --git a/test/integration/candidate-sandbox.test.ts b/test/integration/candidate-sandbox.test.ts index fd855b76..730cb5ef 100644 --- a/test/integration/candidate-sandbox.test.ts +++ b/test/integration/candidate-sandbox.test.ts @@ -17,7 +17,7 @@ import { import { canonicalWorkerUrl, readCanonicalBuildIdentity, -} from '../../apps/stock/orchestrator/src/backtest/canonical-build'; +} from '@stock-bot/trading-runtime/canonical-build'; import { NativeReplaySession, prepareReplayLoad, diff --git a/test/integration/canonical-builtins.test.ts b/test/integration/canonical-builtins.test.ts index 5ba6ed81..6ba20a68 100644 --- a/test/integration/canonical-builtins.test.ts +++ b/test/integration/canonical-builtins.test.ts @@ -1,5 +1,5 @@ import { expect, test } from 'bun:test'; -import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; import { canonicalRegimeSelection } from '../fixtures/canonical-regime-research'; test('canonical mean-reversion selection requires its exact version and explicit compatible parameters', () => { diff --git a/test/integration/canonical-mean-reversion.test.ts b/test/integration/canonical-mean-reversion.test.ts index cf1150a2..daa49745 100644 --- a/test/integration/canonical-mean-reversion.test.ts +++ b/test/integration/canonical-mean-reversion.test.ts @@ -4,12 +4,12 @@ import { meanReversionStrategySelectionSchema, type MeanReversionSignalParameters, type MeanReversionStrategySelection, -} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +} from '@stock-bot/stock-config/strategy'; import type { StrategyContext, StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/research/strategy-api'; +import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay'; import { calculateMeanReversionSignals, createMeanReversionStrategy, diff --git a/test/integration/canonical-native-report.test.ts b/test/integration/canonical-native-report.test.ts index d71b6afc..9df23fff 100644 --- a/test/integration/canonical-native-report.test.ts +++ b/test/integration/canonical-native-report.test.ts @@ -1,12 +1,12 @@ import { expect, test } from 'bun:test'; import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import { executeReplayTrace } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; import { parseReplayReportResult, replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { nativeReplayFixture } from '../fixtures/native-replay'; const policy: CanonicalMetricsInput = { diff --git a/test/integration/canonical-regime-research.test.ts b/test/integration/canonical-regime-research.test.ts index 9a0dd22c..fbf2fe0c 100644 --- a/test/integration/canonical-regime-research.test.ts +++ b/test/integration/canonical-regime-research.test.ts @@ -4,15 +4,15 @@ import { parseFinancialDecimal, type FinancialStrategyIntent } from '@stock-bot/ import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker'; import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; -import { smaStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { smaStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; import type { StrategyContext, StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import type { ReplayProjectionResult, ReplayReportResult, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { parseStrategyReplayResult, strategyReplayRequestSchema, diff --git a/test/integration/canonical-result.test.ts b/test/integration/canonical-result.test.ts index 54ca6560..28b32a56 100644 --- a/test/integration/canonical-result.test.ts +++ b/test/integration/canonical-result.test.ts @@ -1,11 +1,11 @@ import { describe, expect, test } from 'bun:test'; import { parseFinancialDecimal, type CanonicalMetricsInput } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import { parseReplayReportValue, type ReplayConfig, type ReplayReportResult, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; const policy: CanonicalMetricsInput = { version: 1, diff --git a/test/integration/canonical-sma.test.ts b/test/integration/canonical-sma.test.ts index f57c4127..bda4ff25 100644 --- a/test/integration/canonical-sma.test.ts +++ b/test/integration/canonical-sma.test.ts @@ -9,14 +9,13 @@ import { builtinStrategySelectionSchema, smaStrategySelectionSchema, type SmaStrategySelection, -} from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +} from '@stock-bot/stock-config/strategy'; import type { StrategyContext, StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; -import type { PublishedObservation } from '../../apps/stock/orchestrator/src/contracts/native-replay'; -import { strategyAliases } from '../../apps/stock/orchestrator/src/contracts/strategy-names'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; +} from '@stock-bot/research/strategy-api'; +import type { PublishedObservation } from '@stock-bot/stock-config/canonical-replay'; +import { strategyAliases } from '@stock-bot/stock-config/strategy-names'; import { validateBuiltinStrategyBindings } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; import { createSmaStrategy as createBuiltinStrategy, @@ -146,7 +145,6 @@ test('sma_registry_alias selects only the explicit canonical version and leaves ]) { expect(() => builtinStrategySelectionSchema.parse({ ...selection(), ...patch })).toThrow(); } - expect(typeof createBuiltinStrategyRegistry().create).toBe('function'); }); test('binding validation rejects wrong owners, mode, cadence, instrument and unknown series before replay', () => { diff --git a/test/integration/canonical-strategy-worker.test.ts b/test/integration/canonical-strategy-worker.test.ts index 1feeef33..445f3f4f 100644 --- a/test/integration/canonical-strategy-worker.test.ts +++ b/test/integration/canonical-strategy-worker.test.ts @@ -7,7 +7,7 @@ import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/st import { replayIdentitySchema, type ReplayResultFormat, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { parseStrategyReplayResult, strategyReplayRequestSchema, diff --git a/test/integration/canonical-workbench.test.tsx b/test/integration/canonical-workbench.test.tsx index f2d6bcaa..84d6a7c2 100644 --- a/test/integration/canonical-workbench.test.tsx +++ b/test/integration/canonical-workbench.test.tsx @@ -26,7 +26,7 @@ import type { StrategyVersionSummary, } from '@stock-bot/types'; import { parseFinancialDecimal as decimal } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import type { CreateBacktestRequest, Run, diff --git a/test/integration/dataset-preparation.test.ts b/test/integration/dataset-preparation.test.ts index 2bac9cbe..de15715b 100644 --- a/test/integration/dataset-preparation.test.ts +++ b/test/integration/dataset-preparation.test.ts @@ -14,7 +14,7 @@ import { import { StorageService, type HistoricalBar, -} from '../../apps/stock/orchestrator/src/services/StorageService'; +} from '@stock-bot/trading-runtime/historical-storage'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; import { logger } from '../fixtures/execution'; diff --git a/test/integration/dataset-source-preparation.test.ts b/test/integration/dataset-source-preparation.test.ts index 286ff5e5..d4c4749a 100644 --- a/test/integration/dataset-source-preparation.test.ts +++ b/test/integration/dataset-source-preparation.test.ts @@ -13,7 +13,7 @@ import { createDatasetV2, validateDatasetV2, } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; -import { retainResearchDataset } from '../../apps/stock/orchestrator/src/data/retained-research-dataset'; +import { retainResearchDataset } from '@stock-bot/trading-runtime/retained-dataset'; import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; import { readCanonicalDataset } from '../../apps/stock/web-api/src/services/canonical-research.service'; import { diff --git a/test/integration/fee-funding.test.ts b/test/integration/fee-funding.test.ts deleted file mode 100644 index 1374ac57..00000000 --- a/test/integration/fee-funding.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; -import { config, makeExecution, order, quote, start } from '../fixtures/execution'; - -const cleanup: (() => Promise)[] = []; -const runId = '00000000-0000-4000-8000-000000000003'; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function fixture() { - const repository = new BacktestExecutionRepository(); - const runtime = makeExecution(repository); - await runtime.execution.initialize( - { - ...config, - runId, - commission: 0.01, - riskLimits: { - maxOrderSize: 10000, - maxPositionSize: 10000, - maxDailyLoss: 1000000, - maxSymbolExposure: 1000000, - maxGrossExposure: 1000000, - }, - }, - runtime.engine - ); - cleanup.push(() => runtime.execution.shutdown()); - return { ...runtime, repository }; -} - -describe('fee-inclusive legacy capital commitments', () => { - test('fee_budget_10000: an otherwise fully funded buy rejects without financial mutation', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q')); - const before = await execution.getAccount(); - - const report = await execution.submitOrder(order('unfunded', 'buy', 100)); - - expect(report.status).toBe('rejected'); - expect(report.rejectionReason).toBe('Unlevered capital exposure limit'); - expect(report.fills).toEqual([]); - expect(await execution.getAccount()).toEqual(before); - expect(await execution.getPositions()).toEqual([]); - }); - - test('fee_budget_99: entry fees leave exactly one unit of cash', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q')); - - const report = await execution.submitOrder(order('funded', 'buy', 99)); - - expect(report.status).toBe('filled'); - expect(report.fills.map(fill => fill.commission)).toEqual([99]); - expect((await execution.getAccount()).cash).toBe(1); - expect((await execution.getAccount()).equity).toBe(9901); - expect((await execution.getPositions())[0]?.quantity).toBe(99); - }); - - test('pending_fee_commitments and cancelled_commitment_released: two commitments of 5050 cannot fit 10000', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('a', 100, 0)); - await execution.onMarketData(quote('b', 100, 0, start, 'B')); - const first = await execution.submitOrder(order('first', 'buy', 50)); - expect(first.status).toBe('accepted'); - expect(first.fills).toEqual([]); - - const second = await execution.submitOrder({ ...order('second', 'buy', 50), symbol: 'B' }); - expect(second.status).toBe('rejected'); - expect(second.rejectionReason).toBe('Unlevered capital exposure limit'); - expect((await execution.getAccount()).cash).toBe(10000); - - expect(await execution.cancelOrder(first.orderId)).toBe(true); - const replacement = await execution.submitOrder({ - ...order('replacement', 'buy', 99), - symbol: 'B', - }); - expect(replacement.status).toBe('accepted'); - await execution.onMarketData(quote('b-fill', 100, 99, start + 1, 'B')); - expect((await execution.getOrderStatus(replacement.orderId))?.status).toBe('filled'); - expect((await execution.getAccount()).cash).toBe(1); - expect((await execution.getOrderStatus(first.orderId))?.fills).toEqual([]); - }); - - test('partial_fee_not_double_counted: fills 10 then 89 charge 99 once, including duplicate events', async () => { - const { execution } = await fixture(); - const firstQuote = quote('q1', 100, 10); - await execution.onMarketData(firstQuote); - const first = await execution.submitOrder(order('partial', 'buy', 99)); - expect(first.status).toBe('partiallyFilled'); - expect(first.fills.map(fill => [fill.quantity, fill.commission])).toEqual([[10, 10]]); - expect((await execution.getAccount()).cash).toBe(8990); - - expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(first); - expect(await execution.onMarketData(firstQuote)).toBe(false); - const nextQuote = quote('q2', 100, 89, start + 1); - await execution.onMarketData(nextQuote); - const complete = await execution.getOrderStatus(first.orderId); - expect(complete?.status).toBe('filled'); - expect(complete?.fills.map(fill => [fill.quantity, fill.commission])).toEqual([ - [10, 10], - [89, 89], - ]); - expect((await execution.getAccount()).cash).toBe(1); - const beforeRetry = await execution.getAccount(); - expect(await execution.onMarketData(nextQuote)).toBe(false); - expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(complete); - expect(await execution.getAccount()).toEqual(beforeRetry); - }); - - test('frozen_order_fee_policy: pending commitments retain their original commission', async () => { - const { execution, repository } = await fixture(); - await execution.onMarketData(quote('q', 100, 0)); - const first = await execution.submitOrder(order('first', 'buy', 50)); - expect(first.status).toBe('accepted'); - await repository.transact(runId, async tx => { - tx.account.commission = 0; - }); - - const second = await execution.submitOrder(order('second', 'buy', 50)); - expect(second.status).toBe('rejected'); - expect(second.rejectionReason).toBe('Unlevered capital exposure limit'); - await execution.onMarketData(quote('fill', 100, 50, start + 1)); - expect((await execution.getOrderStatus(first.orderId))?.fills[0]?.commission).toBe(50); - expect((await execution.getAccount()).cash).toBe(4950); - }); - - test('a partially filled pending order reserves only its unpaid remaining fees for another order', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q1', 100, 10)); - const partial = await execution.submitOrder(order('partial', 'buy', 50)); - expect(partial.status).toBe('partiallyFilled'); - expect(partial.fills[0]?.commission).toBe(10); - - const pending = await execution.submitOrder(order('other', 'buy', 49)); - expect(pending.status).toBe('accepted'); - await execution.onMarketData(quote('q2', 100, 89, start + 1)); - const first = await execution.getOrderStatus(partial.orderId); - const second = await execution.getOrderStatus(pending.orderId); - expect(first?.status).toBe('filled'); - expect(first?.fills.map(fill => fill.commission)).toEqual([10, 40]); - expect(second?.status).toBe('filled'); - expect(second?.fills.map(fill => fill.commission)).toEqual([49]); - expect((await execution.getAccount()).cash).toBe(1); - }); - - test('frozen_order_fee_policy: fill-time admission uses stored rather than current commission', async () => { - const { execution, repository } = await fixture(); - await execution.onMarketData(quote('q', 100, 0)); - const pending = await execution.submitOrder(order('pending', 'buy', 99)); - expect(pending.status).toBe('accepted'); - await repository.transact(runId, async tx => { - tx.account.commission = 0.5; - }); - - await execution.onMarketData(quote('fill', 100, 99, start + 1)); - const report = await execution.getOrderStatus(pending.orderId); - expect(report?.status).toBe('filled'); - expect(report?.fills[0]?.commission).toBe(99); - expect((await execution.getAccount()).cash).toBe(1); - }); - - test('fill-time repricing cannot consume capital reserved for unpaid fees', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q', 99, 0)); - const pending = await execution.submitOrder(order('pending', 'buy', 100)); - expect(pending.status).toBe('accepted'); - - await execution.onMarketData(quote('gap', 100, 100, start + 1)); - const report = await execution.getOrderStatus(pending.orderId); - expect(report?.status).toBe('cancelled'); - expect(report?.rejectionReason).toBe('Unlevered capital exposure limit'); - expect(report?.fills).toEqual([]); - expect((await execution.getAccount()).cash).toBe(10000); - }); - - test('existing long/short reversal behavior is unchanged', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q')); - for (const [id, side, quantity] of [ - ['long', 'buy', 10], - ['reverse', 'sell', 20], - ['close', 'buy', 10], - ] as const) { - expect((await execution.submitOrder(order(id, side, quantity))).status).toBe('filled'); - } - expect((await execution.getAccount()).cash).toBe(9960); - expect((await execution.getPositions())[0]?.quantity).toBe(0); - }); - - test('reducing-order exemption still permits an insolvent short cover under legacy policy', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('short', 100, 99)); - expect((await execution.submitOrder(order('short', 'sell', 99))).status).toBe('filled'); - await execution.onMarketData(quote('gap', 200, 99, start + 1)); - - const report = await execution.submitOrder(order('cover', 'buy', 99)); - expect(report.status).toBe('filled'); - expect(report.fills[0]?.commission).toBe(198); - expect((await execution.getAccount()).cash).toBe(-197); - expect((await execution.getPositions())[0]?.quantity).toBe(0); - }); -}); diff --git a/test/integration/indicator-contracts.test.ts b/test/integration/indicator-contracts.test.ts index 83c15726..115624b9 100644 --- a/test/integration/indicator-contracts.test.ts +++ b/test/integration/indicator-contracts.test.ts @@ -1,7 +1,6 @@ import { expect, test } from 'bun:test'; import { atr, ema, macd, rsi, trailingSimpleRsi } from '@stock-bot/calculations/indicators'; import { IncrementalEMA, IncrementalRSI, TechnicalIndicators } from '@stock-bot/engine'; -import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; import { calculateATR, calculateBollingerBands, @@ -112,7 +111,6 @@ test('mean-reversion/v2 keeps exact rolling-RSI arithmetic and checkpoint identi } } expect(trailingSimpleRsi([1, 1, 1, 1], 3, 100)).toBe(100); - expect(MeanReversionStrategy.prototype.getCheckpointVersion()).toBe('mean-reversion/v2'); }); test('chart adapters map real source timestamps, warm-up and final rounding only', () => { diff --git a/test/integration/ingestion-backtest.test.ts b/test/integration/ingestion-backtest.test.ts index 82261955..362f1aaa 100644 --- a/test/integration/ingestion-backtest.test.ts +++ b/test/integration/ingestion-backtest.test.ts @@ -10,7 +10,7 @@ import { loadDataset, validateDataset, } from '../../apps/stock/orchestrator/src/data/historical-dataset'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); diff --git a/test/integration/intraday-storage.test.ts b/test/integration/intraday-storage.test.ts index 598b1e48..880a8dd9 100644 --- a/test/integration/intraday-storage.test.ts +++ b/test/integration/intraday-storage.test.ts @@ -16,7 +16,7 @@ import { HistoricalStorageError, StorageService, type HistoricalStorageProvider, -} from '../../apps/stock/orchestrator/src/services/StorageService'; +} from '@stock-bot/trading-runtime/historical-storage'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; import { end, identity, intradayResponse, metadata, start } from '../fixtures/intraday/eod'; diff --git a/test/integration/mode-lifecycle.test.ts b/test/integration/mode-lifecycle.test.ts deleted file mode 100644 index b92c90f0..00000000 --- a/test/integration/mode-lifecycle.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { config, logger } from '../fixtures/execution'; - -function fixture(failAt?: string) { - const calls: string[] = []; - const failure = new Error('injected lifecycle failure'); - const failures = new Map(); - const resources = new Set(); - if (failAt) { - failures.set(failAt, failure); - } - const record = async (step: string) => { - calls.push(step); - const [service, operation] = step.split('.'); - if (!service || !operation) { - throw new Error('Invalid lifecycle fixture step'); - } - if (operation === 'shutdown') { - resources.delete(service); - } else { - resources.add(service); - } - if (failures.has(step)) { - throw failures.get(step); - } - }; - const mode = new ModeManager({ - logger, - execution: { - initialize: () => record('execution.initialize'), - shutdown: () => record('execution.shutdown'), - }, - strategies: { - restoreStrategies: () => record('strategies.restore'), - shutdown: () => record('strategies.shutdown'), - }, - marketData: { - initialize: () => record('market.initialize'), - shutdown: () => record('market.shutdown'), - }, - }); - return { mode, calls, failure, failures, resources }; -} - -describe('explicit mode lifecycle dependencies', () => { - test('paper recovery completes before the feed starts; shutdown drains the feed before strategies and execution', async () => { - const f = fixture(); - await f.mode.initializeMode({ mode: 'paper', startingCapital: 10000 }); - expect(f.calls).toEqual(['execution.initialize', 'strategies.restore', 'market.initialize']); - await f.mode.shutdown(); - expect(f.calls.slice(3)).toEqual([ - 'market.shutdown', - 'strategies.shutdown', - 'execution.shutdown', - ]); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - expect(f.mode.getConfig()).toBeNull(); - await f.mode.shutdown(); - expect(f.calls).toHaveLength(6); - }); - - test('backtest mode replaces the current engine without restoring paper strategies', async () => { - const f = fixture(); - await f.mode.initializeMode(config); - const prior = f.mode.getTradingEngine(); - await f.mode.initializeMode(config); - expect(f.mode.getTradingEngine()).not.toBe(prior); - expect(f.calls).toEqual([ - 'execution.initialize', - 'market.initialize', - 'market.shutdown', - 'strategies.shutdown', - 'execution.shutdown', - 'execution.initialize', - 'market.initialize', - ]); - await f.mode.shutdown(); - }); - - test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown'])( - '%s failure still closes every other dependency and clears the mode engine', - async failAt => { - const f = fixture(failAt); - await f.mode.initializeMode(config); - await expect(f.mode.shutdown()).rejects.toBe(f.failure); - expect(f.calls.slice(2)).toEqual([ - 'market.shutdown', - 'strategies.shutdown', - 'execution.shutdown', - ]); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - expect(f.mode.getConfig()).toBeNull(); - await f.mode.shutdown(); - expect(f.calls).toHaveLength(5); - } - ); - - const paper = { mode: 'paper' as const, startingCapital: 10000 }; - const initialization = ['execution.initialize', 'strategies.restore', 'market.initialize']; - const cleanup = ['market.shutdown', 'strategies.shutdown', 'execution.shutdown']; - - test.each(initialization)( - 'partial acquisition in %s cleans up attempted stages and allows retry without a success event', - async failAt => { - const f = fixture(failAt); - const events: unknown[] = []; - f.mode.on('modeChanged', changed => events.push(changed)); - await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure); - - const attempted = initialization.slice(0, initialization.indexOf(failAt) + 1); - const acquired = new Set(attempted.map(step => step.split('.')[0])); - const applicableCleanup = cleanup.filter(step => acquired.has(step.split('.')[0])); - expect(f.calls).toEqual([...attempted, ...applicableCleanup]); - expect(f.resources.size).toBe(0); - expect(events).toEqual([]); - expect(f.mode.getConfig()).toBeNull(); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - - const cleanupCount = f.calls.length; - await f.mode.shutdown(); - expect(f.calls).toHaveLength(cleanupCount); - f.failures.clear(); - await f.mode.initializeMode(paper); - expect(f.calls.slice(cleanupCount)).toEqual(initialization); - expect(events).toEqual([paper]); - expect(f.mode.getConfig()).toEqual(paper); - expect(f.mode.getTradingEngine()).toBeDefined(); - await f.mode.shutdown(); - expect(f.calls.slice(cleanupCount + initialization.length)).toEqual(cleanup); - expect(f.resources.size).toBe(0); - } - ); - - test.each(cleanup)( - '%s cleanup failure does not mask initialization error or skip remaining cleanup', - async cleanupFailure => { - const f = fixture('market.initialize'); - f.failures.set(cleanupFailure, new Error('injected cleanup failure')); - await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure); - expect(f.calls).toEqual([...initialization, ...cleanup]); - expect(f.resources.size).toBe(0); - expect(f.mode.getConfig()).toBeNull(); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - - f.failures.clear(); - await f.mode.initializeMode(paper); - await f.mode.shutdown(); - expect(f.calls).toEqual([...initialization, ...cleanup, ...initialization, ...cleanup]); - } - ); - - test('failed mode replacement does not expose the prior or partially created engine', async () => { - const f = fixture(); - await f.mode.initializeMode(config); - const prior = f.mode.getTradingEngine(); - f.failures.set('strategies.restore', f.failure); - await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure); - expect(f.mode.getConfig()).toBeNull(); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - - f.failures.clear(); - await f.mode.initializeMode(paper); - expect(f.mode.getTradingEngine()).not.toBe(prior); - await f.mode.shutdown(); - }); - - test('invalid configuration and disabled live trading reject before lifecycle side effects', async () => { - const f = fixture(); - await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow(); - expect(f.calls).toEqual([]); - expect(f.mode.getConfig()).toBeNull(); - expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); - - const live = { - mode: 'live' as const, - broker: 'disabled', - accountId: 'disabled', - accountType: 'cash' as const, - riskLimits: { - maxPositionSize: 1, - maxDailyLoss: 1, - maxOrderSize: 1, - maxGrossExposure: 1, - maxSymbolExposure: 1, - }, - }; - await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled'); - expect(f.calls).toEqual([]); - await f.mode.initializeMode(paper); - const engine = f.mode.getTradingEngine(); - await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled'); - await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow(); - expect(f.calls).toEqual(initialization); - expect(f.mode.getConfig()).toEqual(paper); - expect(f.mode.getTradingEngine()).toBe(engine); - await f.mode.shutdown(); - }); -}); diff --git a/test/integration/native-replay-projection.test.ts b/test/integration/native-replay-projection.test.ts index 5a5b48e6..447d37f9 100644 --- a/test/integration/native-replay-projection.test.ts +++ b/test/integration/native-replay-projection.test.ts @@ -14,7 +14,7 @@ import { parseReplayProjectionResult, parseReplayResult, replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { nativeReplayFixture } from '../fixtures/native-replay'; const intent = (quantity = '2') => ({ diff --git a/test/integration/native-replay-report.test.ts b/test/integration/native-replay-report.test.ts index 60174d5e..91dac102 100644 --- a/test/integration/native-replay-report.test.ts +++ b/test/integration/native-replay-report.test.ts @@ -14,7 +14,7 @@ import { parseReplayReportResult, parseReplayResult, replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { nativeReplayFixture } from '../fixtures/native-replay'; const hold = () => ({ mode: 'target' as const, targets: [] }); diff --git a/test/integration/native-replay.test.ts b/test/integration/native-replay.test.ts index 2bd9f991..0b847997 100644 --- a/test/integration/native-replay.test.ts +++ b/test/integration/native-replay.test.ts @@ -14,7 +14,7 @@ import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest import { parseReplayResult, replayConfigSchema, -} from '../../apps/stock/orchestrator/src/contracts/native-replay'; +} from '@stock-bot/stock-config/canonical-replay'; import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2'; import { datasetInput } from '../fixtures/historical-v2/dataset'; import { nativeReplayFixture } from '../fixtures/native-replay'; diff --git a/test/integration/order-execution.test.ts b/test/integration/order-execution.test.ts deleted file mode 100644 index 11bbd1bf..00000000 --- a/test/integration/order-execution.test.ts +++ /dev/null @@ -1,250 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { TradingEngine } from '@stock-bot/engine'; -import { createOrderRoutes } from '../../apps/stock/orchestrator/src/api/rest/orders'; -import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; -import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; -import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { - BaseStrategy, - type Signal, -} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; -import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; -import type { MarketData } from '../../apps/stock/orchestrator/src/types'; -import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close(); -}); -async function fixture() { - const runtime = makeExecution(); - await runtime.execution.initialize(config, runtime.engine); - cleanup.push(() => runtime.execution.shutdown()); - return runtime; -} -describe('one simulation execution gateway', () => { - test('identical client IDs return one order/fill; conflicting retries cannot mutate accounting', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q1')); - const reports = await Promise.all([ - execution.submitOrder(order('id')), - execution.submitOrder(order('id')), - ]); - expect(reports[0]).toEqual(reports[1]); - expect(reports[0]!.status).toBe('filled'); - expect((await execution.getPositions())[0]?.quantity).toBe(10); - await expect(execution.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf( - ExecutionConflictError - ); - expect((await execution.getAccount()).cash).toBe(8999); - }); - test('quote liquidity is consumed once; partial fills complete across distinct events only', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q1', 100, 3)); - const first = await execution.submitOrder(order('partial', 'buy', 10)); - expect(first.status).toBe('partiallyFilled'); - expect(first.fills[0]?.quantity).toBe(3); - expect(await execution.onMarketData(quote('q1', 100, 3))).toBe(false); - await execution.onMarketData(quote('q2', 100, 4, start + 1)); - expect((await execution.getOrderStatus(first.orderId))?.fills.map(f => f.quantity)).toEqual([ - 3, 4, - ]); - await execution.onMarketData(quote('q3', 100, 50, start + 2)); - const report = await execution.getOrderStatus(first.orderId); - expect(report?.status).toBe('filled'); - expect(report?.fills.map(f => f.quantity)).toEqual([3, 4, 3]); - expect((await execution.getAccount()).cash).toBe(8999); - expect((await execution.getPositions())[0]?.quantity).toBe(10); - }); - test('long/short partial closes and reversals conserve equity and charge commission exactly once', async () => { - const { execution, engine } = await fixture(); - for (const [i, side, price, quantity] of [ - [0, 'buy', 100, 10], - [1, 'sell', 110, 4], - [2, 'sell', 90, 10], - [3, 'buy', 80, 4], - ] as const) { - await execution.onMarketData(quote('q' + i, price, 100, start + i)); - await execution.submitOrder(order('o' + i, side, quantity)); - } - const account = await execution.getAccount(); - expect(account.cash).toBeCloseTo(10017.34, 8); - expect(account.equity).toBe(account.cash); - expect(account.realizedPnl).toBeCloseTo(17.34, 8); - expect(account.dailyPnl).toBe(account.realizedPnl); - expect(account.positions.A?.quantity).toBe(0); - expect(account.positions.A?.averagePrice).toBe(0); - const [native] = engine.getTotalPnl(); - expect(native).toBeCloseTo(account.realizedPnl, 8); - }); - test('pending reservations and projected notional enforce limits across symbols', async () => { - const { execution, engine } = await fixture(); - await execution.initialize( - { - ...config, - riskLimits: { - maxOrderSize: 100, - maxPositionSize: 100, - maxDailyLoss: 100, - maxSymbolExposure: 800, - maxGrossExposure: 1000, - }, - }, - engine - ); - await execution.onMarketData(quote('a', 100, 0)); - await execution.onMarketData(quote('b', 100, 0, start, 'B')); - expect((await execution.submitOrder(order('pending', 'buy', 6))).status).toBe('accepted'); - expect((await execution.submitOrder(order('over', 'buy', 3))).status).toBe('rejected'); - const other = { ...order('b', 'buy', 5), symbol: 'B' }; - expect((await execution.submitOrder(other)).status).toBe('rejected'); - expect(await execution.getPositions()).toHaveLength(0); - }); - test('IOC/FOK and limits have truthful states; cancellations cannot cancel an already filled order', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q', 100, 3)); - const fok = await execution.submitOrder({ ...order('fok'), timeInForce: 'FOK' }); - expect(fok.status).toBe('cancelled'); - expect(fok.fills).toHaveLength(0); - const ioc = await execution.submitOrder({ ...order('ioc'), timeInForce: 'IOC' }); - expect(ioc.status).toBe('cancelled'); - expect(ioc.fills[0]?.quantity).toBe(3); - const limit = await execution.submitOrder({ - ...order('limit', 'buy', 1), - orderType: 'limit', - limitPrice: 90, - }); - expect(limit.status).toBe('accepted'); - expect(await execution.cancelOrder(limit.orderId)).toBe(true); - await execution.onMarketData(quote('q2', 80, 100, start + 1)); - expect((await execution.getOrderStatus(limit.orderId))?.fills).toHaveLength(0); - const filled = await execution.submitOrder(order('filled', 'buy', 1)); - expect(await execution.cancelOrder(filled.orderId)).toBe(false); - }); - test('invalid/stale state cannot masquerade as acceptance and event conflicts roll back', async () => { - const { execution } = await fixture(); - expect((await execution.submitOrder(order('missing'))).status).toBe('rejected'); - await execution.onMarketData(quote('q')); - await expect(execution.onMarketData(quote('q', 101))).rejects.toBeInstanceOf( - ExecutionConflictError - ); - await expect( - execution.onMarketData(quote('older', 100, 100, start - 1)) - ).rejects.toBeInstanceOf(ExecutionConflictError); - const stop = await execution.submitOrder({ - ...order('stop'), - orderType: 'stop', - stopPrice: 100, - }); - expect(stop.status).toBe('rejected'); - expect(stop.rejectionReason).toContain('Unsupported'); - expect((await execution.getAccount()).cash).toBe(10000); - }); - test('HTTP requires an idempotency ID and returns conflict for mismatched reuse', async () => { - const { execution } = await fixture(); - await execution.onMarketData(quote('q')); - const routes = createOrderRoutes({ logger, custom: { ExecutionService: execution } }); - const send = (body: object) => - routes.request('/', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body), - }); - const { clientOrderId: _, ...missing } = order('id'); - expect((await send(missing)).status).toBe(400); - expect((await send(order('id'))).status).toBe(201); - expect((await send(order('id', 'buy', 20))).status).toBe(409); - }); - test('unsupported live initialization cannot alter an existing simulation account', async () => { - const { execution, engine } = await fixture(); - const live = { - mode: 'live' as const, - broker: 'none', - accountId: 'none', - accountType: 'cash' as const, - riskLimits: { - maxOrderSize: 10, - maxPositionSize: 10, - maxDailyLoss: 10, - maxSymbolExposure: 100, - maxGrossExposure: 100, - }, - }; - await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled'); - expect((await execution.getAccount()).cash).toBe(10000); - const lifecycle = { initialize: async () => {}, shutdown: async () => {} }; - const mode = new ModeManager({ - logger, - marketData: lifecycle, - execution, - strategies: { restoreStrategies: async () => {}, shutdown: async () => {} }, - }); - await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled'); - expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow( - 'Live trading is disabled' - ); - expect(() => engine.submitOrder({ ...order('direct'), id: 'direct' })).toThrow( - 'execution gateway' - ); - }); - test('batch delivery is ordered, subscribed once, deduplicated, and routes every strategy order through risk', async () => { - const { execution } = await fixture(); - class Strategy extends BaseStrategy { - calls: number[] = []; - protected updateIndicators(data: MarketData) { - this.calls.push(data.data.timestamp); - } - protected async generateSignal(data: MarketData): Promise { - await new Promise(resolve => setTimeout(resolve, 5)); - return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } }; - } - protected async onStart() {} - protected async onStop() {} - protected onConfigUpdate() {} - } - const market: MarketDataService = new MarketDataService({ - logger, - storage: new StorageService(logger, null, null), - drainStrategies: () => manager.drain(), - }); - const manager: StrategyManager = new StrategyManager({ - logger, - execution, - marketData: market, - createStrategy: config => new Strategy(config, {} as ModeManager, execution), - }); - manager.setupEventListeners(); - manager.setupEventListeners(); - const strategy = new Strategy( - { - id: 'strategy', - name: 'fixture', - enabled: true, - parameters: {}, - symbols: ['A'], - allocation: 1, - }, - {} as ModeManager, - execution - ); - // Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real. - await manager.attachStrategy(strategy); - cleanup.push(() => manager.shutdown()); - const first = quote('1'); - const second = quote('2', 100, 100, start + 1); - market.emit('marketDataBatch', [first]); - market.emit('marketData', first); - market.emit('marketDataBatch', [first, second]); - await manager.drain(); - expect(strategy.calls).toEqual([start, start + 1]); - expect(strategy.getPosition('A')).toBe(2); - expect((await execution.getAccount()).strategyPositions.strategy?.A).toBe(2); - expect(market.listenerCount('marketDataBatch')).toBe(1); - market.ingest(quote('3', 100, 100, start + 2)); - await market.flush(); - expect(strategy.calls).toEqual([start, start + 1, start + 2]); - expect(strategy.getPosition('A')).toBe(3); - }); -}); diff --git a/test/integration/paper-composition.test.ts b/test/integration/paper-composition.test.ts index 23682524..7df1b938 100644 --- a/test/integration/paper-composition.test.ts +++ b/test/integration/paper-composition.test.ts @@ -3,7 +3,7 @@ import { expect, test } from 'bun:test'; import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di'; import type { StockAppConfig } from '@stock-bot/stock-config'; import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; -import type { PaperConfigurationInput } from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import type { PaperConfigurationInput } from '@stock-bot/stock-config/paper-runtime'; import { createContainer } from '../../apps/stock/orchestrator/src/simple-container'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import { logger } from '../fixtures/execution'; diff --git a/test/integration/paper-feed.test.ts b/test/integration/paper-feed.test.ts index ba17a895..f2017306 100644 --- a/test/integration/paper-feed.test.ts +++ b/test/integration/paper-feed.test.ts @@ -5,12 +5,12 @@ import { compareEventKeys, parseFinancialTransactionResult, type CanonicalMatchingCommand, -} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; +} from '@stock-bot/stock-config/canonical-execution'; import { PaperRuntimeError, type PaperConfigurationInput, type PaperFrameInput, -} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +} from '@stock-bot/stock-config/paper-runtime'; import type { CanonicalAccount } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { planPaperFrame, diff --git a/test/integration/paper-native-identity.test.ts b/test/integration/paper-native-identity.test.ts index 61955fe6..dc7e7e45 100644 --- a/test/integration/paper-native-identity.test.ts +++ b/test/integration/paper-native-identity.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { expect, test } from 'bun:test'; import { loadedNativeIdentity } from '@stock-bot/engine'; -import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity'; +import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity'; test('paper identity names the actual bundle and loaded immutable native bytes, not the research worker', async () => { const identity = await readPaperHostIdentity(); diff --git a/test/integration/paper-routes.test.ts b/test/integration/paper-routes.test.ts index 7013e4ca..741cf61b 100644 --- a/test/integration/paper-routes.test.ts +++ b/test/integration/paper-routes.test.ts @@ -1,8 +1,6 @@ import { describe, expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; -import type { Server as SocketIOServer } from 'socket.io'; -import { createHttpSecurity } from '@stock-bot/di'; -import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; +import { createHttpSecurity } from '@stock-bot/di/http-security'; import { PaperRuntimeError, type PaperConfigurationInput, @@ -10,8 +8,9 @@ import { type PaperFrameInput, type PaperReadiness, type PaperRuntime, -} from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; -import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; +} from '@stock-bot/stock-config/paper-runtime'; +import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; +import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import { paperFeedFrame } from '../fixtures/paper-feed'; diff --git a/test/integration/product-response-contracts.test.ts b/test/integration/product-response-contracts.test.ts index 17eeec70..b7f16faa 100644 --- a/test/integration/product-response-contracts.test.ts +++ b/test/integration/product-response-contracts.test.ts @@ -22,7 +22,7 @@ import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { createStrategyRoutes } from '../../apps/stock/web-api/src/routes/strategies.routes'; import { mapBacktest, mapRun } from '../../apps/stock/web-api/src/services/backtests/mapping'; -import { RunControls } from '../../apps/stock/web-app/src/features/backtest/components/RunControls'; +import { RunControlsCompact } from '../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const original = Object.getOwnPropertyDescriptor(globalThis, 'window'); @@ -109,20 +109,20 @@ test('real server backtest/run mappings survive JSON serialization and display t respond(run()); const savedRun = await backtest.backtestApiV2.getRun(runId); expect(savedRun.currentDate).toBe(now.toISOString()); + expect(savedRun.progress).toBe(12.5); expect(savedRun.completedAt).toBeNull(); expect(savedRun.dataset?.state).toBe('unknown'); const noop = () => {}; const html = renderToStaticMarkup( - createElement(RunControls, { + createElement(RunControlsCompact, { run: savedRun, - onPause: noop, - onResume: noop, + cancelRequested: false, onCancel: noop, - onSpeedChange: noop, + onRerun: noop, }) ); - expect(html).toContain(now.toLocaleString()); - expect(html).toContain('12.5%'); + expect(html).toContain('Running'); + expect(html).toContain('13%'); }); test('existing optional fields remain optional without accepting malformed rendered fields', async () => { diff --git a/test/integration/reproduction-comparison.test.ts b/test/integration/reproduction-comparison.test.ts index 25788927..07d9e913 100644 --- a/test/integration/reproduction-comparison.test.ts +++ b/test/integration/reproduction-comparison.test.ts @@ -5,7 +5,7 @@ import { type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { parseFinancialDecimal } from '@stock-bot/types'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; diff --git a/test/integration/retained-strategy-worker.test.ts b/test/integration/retained-strategy-worker.test.ts index b0e4d4c5..720056ad 100644 --- a/test/integration/retained-strategy-worker.test.ts +++ b/test/integration/retained-strategy-worker.test.ts @@ -10,8 +10,8 @@ import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/t import { canonicalWorkerUrl, readCanonicalBuildIdentity, -} from '../../apps/stock/orchestrator/src/backtest/canonical-build'; -import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result'; +} from '@stock-bot/trading-runtime/canonical-build'; +import { buildCanonicalBacktestReport } from '@stock-bot/research/results'; import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; import { nativeWorkerRequestSchema, diff --git a/test/integration/setup.js b/test/integration/setup.js deleted file mode 100644 index a565d5f8..00000000 --- a/test/integration/setup.js +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Integration Test Setup - * - * Sets up test containers and real database instances for integration testing. - * This file is executed before integration tests run. - */ -import { GenericContainer } from 'testcontainers'; -import { MongoMemoryServer } from 'mongodb-memory-server'; -let questdbContainer; -let postgresContainer; -let mongoContainer; -let mongoMemoryServer; -/** - * Global setup for integration tests - * Starts real database containers for testing - */ -beforeAll(async () => { - console.log('๐Ÿš€ Starting integration test containers...'); - try { - // Start QuestDB container - console.log('๐Ÿ“Š Starting QuestDB container...'); - questdbContainer = await new GenericContainer('questdb/questdb:7.3.10') - .withExposedPorts(9000, 8812, 9009) - .withEnvironment({ - 'QDB_TELEMETRY_ENABLED': 'false', - 'QDB_LOG_LEVEL': 'ERROR' - }) - .withStartupTimeout(60000) - .start(); - // Start PostgreSQL container - console.log('๐Ÿ˜ Starting PostgreSQL container...'); - postgresContainer = await new GenericContainer('postgres:15-alpine') - .withExposedPorts(5432) - .withEnvironment({ - 'POSTGRES_DB': 'trading_bot_test', - 'POSTGRES_USER': 'trading_admin', - 'POSTGRES_PASSWORD': 'trading_pass_test' - }) - .withStartupTimeout(60000) - .start(); - // Start MongoDB container - console.log('๐Ÿƒ Starting MongoDB container...'); - mongoContainer = await new GenericContainer('mongo:7-jammy') - .withExposedPorts(27017) - .withEnvironment({ - 'MONGO_INITDB_ROOT_USERNAME': 'trading_admin', - 'MONGO_INITDB_ROOT_PASSWORD': 'trading_mongo_test', - 'MONGO_INITDB_DATABASE': 'trading_bot_test' - }) - .withStartupTimeout(60000) - .start(); - // Update environment variables for tests - process.env.QUESTDB_HOST = questdbContainer.getHost(); - process.env.QUESTDB_HTTP_PORT = questdbContainer.getMappedPort(9000).toString(); - process.env.QUESTDB_PG_PORT = questdbContainer.getMappedPort(8812).toString(); - process.env.QUESTDB_INFLUX_PORT = questdbContainer.getMappedPort(9009).toString(); - process.env.POSTGRES_HOST = postgresContainer.getHost(); - process.env.POSTGRES_PORT = postgresContainer.getMappedPort(5432).toString(); - process.env.MONGODB_HOST = mongoContainer.getHost(); - process.env.MONGODB_PORT = mongoContainer.getMappedPort(27017).toString(); - console.log('โœ… All containers started successfully!'); - console.log(`๐Ÿ“Š QuestDB: http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`); - console.log(`๐Ÿ˜ PostgreSQL: ${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}`); - console.log(`๐Ÿƒ MongoDB: ${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}`); - } - catch (error) { - console.error('โŒ Failed to start test containers:', error); - // Try to use MongoDB Memory Server as fallback - console.log('๐Ÿ”„ Falling back to MongoDB Memory Server...'); - try { - mongoMemoryServer = await MongoMemoryServer.create({ - instance: { - dbName: 'trading_bot_test' - } - }); - const mongoUri = mongoMemoryServer.getUri(); - const mongoUrl = new URL(mongoUri); - process.env.MONGODB_HOST = mongoUrl.hostname; - process.env.MONGODB_PORT = mongoUrl.port; - process.env.MONGODB_URI = mongoUri; - console.log('โœ… MongoDB Memory Server started as fallback'); - } - catch (fallbackError) { - console.error('โŒ Failed to start MongoDB Memory Server:', fallbackError); - throw fallbackError; - } - // For other databases, use localhost defaults if containers fail - if (!questdbContainer) { - console.log('โš ๏ธ Using localhost QuestDB (ensure it\'s running)'); - process.env.QUESTDB_HOST = 'localhost'; - process.env.QUESTDB_HTTP_PORT = '9000'; - process.env.QUESTDB_PG_PORT = '8812'; - process.env.QUESTDB_INFLUX_PORT = '9009'; - } - if (!postgresContainer) { - console.log('โš ๏ธ Using localhost PostgreSQL (ensure it\'s running)'); - process.env.POSTGRES_HOST = 'localhost'; - process.env.POSTGRES_PORT = '5432'; - } - } -}, 120000); // 2 minutes timeout for container startup -/** - * Global cleanup for integration tests - * Stops all test containers - */ -afterAll(async () => { - console.log('๐Ÿงน Cleaning up integration test containers...'); - const cleanup = async (container, name) => { - if (container) { - try { - await container.stop(); - console.log(`โœ… ${name} container stopped`); - } - catch (error) { - console.warn(`โš ๏ธ Failed to stop ${name} container:`, error); - } - } - }; - await Promise.all([ - cleanup(questdbContainer, 'QuestDB'), - cleanup(postgresContainer, 'PostgreSQL'), - cleanup(mongoContainer, 'MongoDB') - ]); - if (mongoMemoryServer) { - try { - await mongoMemoryServer.stop(); - console.log('โœ… MongoDB Memory Server stopped'); - } - catch (error) { - console.warn('โš ๏ธ Failed to stop MongoDB Memory Server:', error); - } - } - console.log('๐ŸŽ‰ Integration test cleanup complete!'); -}, 30000); -/** - * Wait for database services to be ready - */ -export const waitForServices = async (timeout = 30000) => { - const start = Date.now(); - while (Date.now() - start < timeout) { - try { - // Check if QuestDB HTTP interface is ready - const questdbUrl = `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}/status`; - const response = await fetch(questdbUrl); - if (response.ok) { - console.log('โœ… QuestDB is ready'); - return; - } - } - catch (error) { - // Service not ready yet, continue waiting - } - await new Promise(resolve => setTimeout(resolve, 1000)); - } - throw new Error('Services did not become ready within timeout'); -}; -/** - * Test utilities for integration tests - */ -export const integrationTestHelpers = { - /** - * Get QuestDB HTTP URL - */ - getQuestDBUrl: () => `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`, - /** - * Get PostgreSQL connection string - */ - getPostgresUrl: () => `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`, - /** - * Get MongoDB connection string - */ - getMongoUrl: () => { - if (process.env.MONGODB_URI) { - return process.env.MONGODB_URI; - } - return `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DATABASE}`; - }, - /** - * Wait for services to be ready - */ - waitForServices -}; -//# sourceMappingURL=setup.js.map \ No newline at end of file diff --git a/test/integration/setup.ts b/test/integration/setup.ts deleted file mode 100644 index e448556d..00000000 --- a/test/integration/setup.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Integration Test Setup - * - * Sets up test containers and real database instances for integration testing. - * This file is executed before integration tests run. - */ - -import { GenericContainer, StartedTestContainer } from 'testcontainers'; -import { MongoMemoryServer } from 'mongodb-memory-server'; - -let questdbContainer: StartedTestContainer; -let postgresContainer: StartedTestContainer; -let mongoContainer: StartedTestContainer; -let mongoMemoryServer: MongoMemoryServer; - -/** - * Global setup for integration tests - * Starts real database containers for testing - */ -beforeAll(async () => { - console.log('๐Ÿš€ Starting integration test containers...'); - - try { - // Start QuestDB container - console.log('๐Ÿ“Š Starting QuestDB container...'); - questdbContainer = await new GenericContainer('questdb/questdb:7.3.10') - .withExposedPorts(9000, 8812, 9009) - .withEnvironment({ - 'QDB_TELEMETRY_ENABLED': 'false', - 'QDB_LOG_LEVEL': 'ERROR' - }) - .withStartupTimeout(60000) - .start(); - - // Start PostgreSQL container - console.log('๐Ÿ˜ Starting PostgreSQL container...'); - postgresContainer = await new GenericContainer('postgres:15-alpine') - .withExposedPorts(5432) - .withEnvironment({ - 'POSTGRES_DB': 'trading_bot_test', - 'POSTGRES_USER': 'trading_admin', - 'POSTGRES_PASSWORD': 'trading_pass_test' - }) - .withStartupTimeout(60000) - .start(); - - // Start MongoDB container - console.log('๐Ÿƒ Starting MongoDB container...'); - mongoContainer = await new GenericContainer('mongo:7-jammy') - .withExposedPorts(27017) - .withEnvironment({ - 'MONGO_INITDB_ROOT_USERNAME': 'trading_admin', - 'MONGO_INITDB_ROOT_PASSWORD': 'trading_mongo_test', - 'MONGO_INITDB_DATABASE': 'trading_bot_test' - }) - .withStartupTimeout(60000) - .start(); - - // Update environment variables for tests - process.env.QUESTDB_HOST = questdbContainer.getHost(); - process.env.QUESTDB_HTTP_PORT = questdbContainer.getMappedPort(9000).toString(); - process.env.QUESTDB_PG_PORT = questdbContainer.getMappedPort(8812).toString(); - process.env.QUESTDB_INFLUX_PORT = questdbContainer.getMappedPort(9009).toString(); - - process.env.POSTGRES_HOST = postgresContainer.getHost(); - process.env.POSTGRES_PORT = postgresContainer.getMappedPort(5432).toString(); - - process.env.MONGODB_HOST = mongoContainer.getHost(); - process.env.MONGODB_PORT = mongoContainer.getMappedPort(27017).toString(); - - console.log('โœ… All containers started successfully!'); - console.log(`๐Ÿ“Š QuestDB: http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`); - console.log(`๐Ÿ˜ PostgreSQL: ${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}`); - console.log(`๐Ÿƒ MongoDB: ${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}`); - - } catch (error) { - console.error('โŒ Failed to start test containers:', error); - - // Try to use MongoDB Memory Server as fallback - console.log('๐Ÿ”„ Falling back to MongoDB Memory Server...'); - try { - mongoMemoryServer = await MongoMemoryServer.create({ - instance: { - dbName: 'trading_bot_test' - } - }); - - const mongoUri = mongoMemoryServer.getUri(); - const mongoUrl = new URL(mongoUri); - process.env.MONGODB_HOST = mongoUrl.hostname; - process.env.MONGODB_PORT = mongoUrl.port; - process.env.MONGODB_URI = mongoUri; - - console.log('โœ… MongoDB Memory Server started as fallback'); - } catch (fallbackError) { - console.error('โŒ Failed to start MongoDB Memory Server:', fallbackError); - throw fallbackError; - } - - // For other databases, use localhost defaults if containers fail - if (!questdbContainer) { - console.log('โš ๏ธ Using localhost QuestDB (ensure it\'s running)'); - process.env.QUESTDB_HOST = 'localhost'; - process.env.QUESTDB_HTTP_PORT = '9000'; - process.env.QUESTDB_PG_PORT = '8812'; - process.env.QUESTDB_INFLUX_PORT = '9009'; - } - - if (!postgresContainer) { - console.log('โš ๏ธ Using localhost PostgreSQL (ensure it\'s running)'); - process.env.POSTGRES_HOST = 'localhost'; - process.env.POSTGRES_PORT = '5432'; - } - } -}, 120000); // 2 minutes timeout for container startup - -/** - * Global cleanup for integration tests - * Stops all test containers - */ -afterAll(async () => { - console.log('๐Ÿงน Cleaning up integration test containers...'); - - const cleanup = async (container: StartedTestContainer | undefined, name: string) => { - if (container) { - try { - await container.stop(); - console.log(`โœ… ${name} container stopped`); - } catch (error) { - console.warn(`โš ๏ธ Failed to stop ${name} container:`, error); - } - } - }; - - await Promise.all([ - cleanup(questdbContainer, 'QuestDB'), - cleanup(postgresContainer, 'PostgreSQL'), - cleanup(mongoContainer, 'MongoDB') - ]); - - if (mongoMemoryServer) { - try { - await mongoMemoryServer.stop(); - console.log('โœ… MongoDB Memory Server stopped'); - } catch (error) { - console.warn('โš ๏ธ Failed to stop MongoDB Memory Server:', error); - } - } - - console.log('๐ŸŽ‰ Integration test cleanup complete!'); -}, 30000); - -/** - * Wait for database services to be ready - */ -export const waitForServices = async (timeout: number = 30000): Promise => { - const start = Date.now(); - - while (Date.now() - start < timeout) { - try { - // Check if QuestDB HTTP interface is ready - const questdbUrl = `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}/status`; - const response = await fetch(questdbUrl); - - if (response.ok) { - console.log('โœ… QuestDB is ready'); - return; - } - } catch (error) { - // Service not ready yet, continue waiting - } - - await new Promise(resolve => setTimeout(resolve, 1000)); - } - - throw new Error('Services did not become ready within timeout'); -}; - -/** - * Test utilities for integration tests - */ -export const integrationTestHelpers = { - /** - * Get QuestDB HTTP URL - */ - getQuestDBUrl: () => `http://${process.env.QUESTDB_HOST}:${process.env.QUESTDB_HTTP_PORT}`, - - /** - * Get PostgreSQL connection string - */ - getPostgresUrl: () => - `postgresql://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DB}`, - - /** - * Get MongoDB connection string - */ - getMongoUrl: () => { - if (process.env.MONGODB_URI) { - return process.env.MONGODB_URI; - } - return `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGODB_HOST}:${process.env.MONGODB_PORT}/${process.env.MONGODB_DATABASE}`; - }, - - /** - * Wait for services to be ready - */ - waitForServices -}; diff --git a/test/integration/stored-dataset-preparation.test.ts b/test/integration/stored-dataset-preparation.test.ts index 29657f5b..f196b99e 100644 --- a/test/integration/stored-dataset-preparation.test.ts +++ b/test/integration/stored-dataset-preparation.test.ts @@ -13,7 +13,7 @@ import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historic import { StorageService, type HistoricalBar, -} from '../../apps/stock/orchestrator/src/services/StorageService'; +} from '@stock-bot/trading-runtime/historical-storage'; import { createDatasetRoutes } from '../../apps/stock/web-api/src/routes/datasets.routes'; import { previewDatasetPreparation } from '../../apps/stock/web-api/src/services/dataset-preparation.service'; import { prepareStoredDataset } from '../../apps/stock/web-api/src/services/stored-dataset-preparation'; diff --git a/test/integration/strategy-contracts.test.ts b/test/integration/strategy-contracts.test.ts deleted file mode 100644 index ae14b7be..00000000 --- a/test/integration/strategy-contracts.test.ts +++ /dev/null @@ -1,468 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { - movingAverageCrossover, - trailingMean, - trailingPopulationDeviation, -} from '@stock-bot/calculations/indicators'; -import { - IncrementalSMA, - BacktestEngine as NativeEngine, - TechnicalIndicators, -} from '@stock-bot/engine'; -import { BacktestExecutionSettingsSchema } from '@stock-bot/stock-config/backtest'; -import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine'; -import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies'; -import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan'; -import { - nativeMeanReversionParameters, - nativeMomentumParameters, - nativePairsParameters, - nativeSmaParameters, - typescriptMeanReversionParameters, - typescriptSmaParameters, -} from '../../apps/stock/orchestrator/src/contracts/strategies'; -import { - builtinStrategy, - normalizeStrategyName, -} from '../../apps/stock/orchestrator/src/contracts/strategy-names'; -import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; -import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; -import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types'; -import { config, logger, makeExecution, start } from '../fixtures/execution'; -import { makeStrategyManager } from '../fixtures/strategy-recovery'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close(); -}); -const definition: StrategyConfig = { - id: 'sma', - name: 'sma-crossover', - enabled: true, - parameters: {}, - symbols: ['A.US'], - allocation: 1, -}; -function nativeEngine() { - return new NativeEngine({ - name: 'contracts', - symbols: ['A.US'], - startDate: config.startDate, - endDate: config.endDate, - initialCapital: 10000, - commission: 0, - slippage: 0, - dataFrequency: '1d', - }); -} -const bar = (close: number, index: number, symbol = 'A.US') => ({ - type: 'bar' as const, - eventId: symbol + ':' + index, - data: { - symbol, - close, - open: close, - high: close + 0.1, - low: close - 0.1, - volume: 1000, - timestamp: start + index * 86400000, - }, -}); -async function runtime(parameters: Record = {}, name = definition.name) { - const f = makeExecution(); - await f.execution.initialize({ ...config, commission: 0 }, f.engine); - cleanup.push(() => f.execution.shutdown()); - const mode = { getTradingEngine: () => f.engine } as ModeManager; - const manager = makeStrategyManager({ execution: f.execution, modeManager: mode }); - cleanup.push(() => manager.shutdown()); - await manager.initializeStrategies([{ ...definition, name, parameters }]); - return { ...f, manager, mode, strategy: manager.getStrategy('sma')! }; -} - -describe('explicit strategy contracts and shared planning', () => { - test('aliases have one canonical identity across registries and native planning', () => { - for (const name of [ - 'SMA', - ' sma-crossover ', - 'sma_crossover', - 'Simple Moving Average Crossover', - 'moving-average', - ]) { - expect(builtinStrategy(name)).toBe('sma_crossover'); - expect(resolveNativeStrategies({ ...config, strategy: name })[0]?.strategy).toBe( - 'sma_crossover' - ); - } - expect(normalizeStrategyName(' Mean-Reversion ')).toBe('meanreversion'); - expect(builtinStrategy('unknown')).toBeUndefined(); - }); - - test('both backends use the same shared-default then per-strategy override rule', () => { - const request = { - ...config, - config: { fastPeriod: 2, slowPeriod: 9, commission: 0, slippage: 0 }, - strategies: [ - { name: 'sma', enabled: true, config: { slowPeriod: 5 } }, - { name: 'not-installed', enabled: false, config: {} }, - { name: 'sma_crossover', enabled: true, config: { fastPeriod: 3 } }, - ], - }; - const before = structuredClone(request); - for (const backend of ['typescript', 'native'] as const) { - const plan = backtestStrategies(request, backend); - expect(plan.map(entry => [entry.parameters.fastPeriod, entry.parameters.slowPeriod])).toEqual( - [ - [2, 5], - [3, 9], - ] - ); - expect(plan.every(entry => !('commission' in entry.parameters))).toBe(true); - } - expect(request).toEqual(before); - const custom = backtestStrategies( - { ...config, strategy: 'custom-extension', config: { vendorOption: 42 } }, - 'typescript' - ); - expect(custom[0]?.parameters).toMatchObject({ - vendorOption: 42, - initialCapital: config.initialCapital, - }); - }); - - test('periods and units have explicit defaults and fail rather than coerce or truncate', () => { - expect(typescriptSmaParameters.parse({})).toMatchObject({ - fastPeriod: 5, - slowPeriod: 15, - positionFraction: 0.1, - minHoldingBars: 3, - }); - expect(nativeSmaParameters.parse({})).toEqual({ fastPeriod: 5, slowPeriod: 15, quantity: 100 }); - for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) { - expect(nativeSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false); - expect(typescriptSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false); - } - expect(typescriptSmaParameters.safeParse({ fastPeriod: 20, slowPeriod: 5 }).success).toBe( - false - ); - for (const bad of [0, -1, Infinity, 1e10]) { - expect(nativeSmaParameters.safeParse({ quantity: bad }).success).toBe(false); - expect(typescriptSmaParameters.safeParse({ quantity: bad }).success).toBe(false); - } - expect(typescriptSmaParameters.safeParse({ positionFraction: 2 }).success).toBe(false); - expect(typescriptSmaParameters.safeParse({ positionSize: 100 }).success).toBe(false); - expect(typescriptSmaParameters.safeParse({ fastPreriod: 3 }).success).toBe(false); - expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false); - }); - - test('mixed execution settings never reach built-in parameters or alter run-wide precedence', () => { - const mixed = { - ...config, - config: { - ...BacktestExecutionSettingsSchema.parse(config), - fastPeriod: 3, - slowPeriod: 7, - useTypeScriptImplementation: false, - }, - strategies: [ - { name: 'disabled', enabled: false, config: {} }, - { - name: 'sma', - enabled: true, - config: { slowPeriod: 9, dataFrequency: '1m', commission: 0.1 }, - }, - { name: 'sma_crossover', enabled: true, config: { fastPeriod: 2 } }, - ], - }; - const before = structuredClone(mixed); - for (const backend of ['native', 'typescript'] as const) { - const plan = backtestStrategies(mixed, backend); - expect( - plan.map(entry => [entry.index, entry.parameters.fastPeriod, entry.parameters.slowPeriod]) - ).toEqual([ - [0, 3, 9], - [1, 2, 7], - ]); - for (const entry of plan) { - expect(entry.parameters).not.toHaveProperty('dataFrequency'); - expect(entry.parameters).not.toHaveProperty('commission'); - expect(entry.parameters).not.toHaveProperty('useTypeScriptImplementation'); - if (backend === 'typescript') { - expect(entry.parameters.initialCapital).toBe(config.initialCapital); - } - } - for (const parameters of [{ fastPreriod: 3 }, { dataFrequncy: '1d' }]) { - expect(() => backtestStrategies({ ...config, config: parameters }, backend)).toThrow( - 'Unrecognized' - ); - } - } - expect(resolveNativeStrategies(mixed).map(entry => entry.id)).toEqual([ - 'backtest-strategy-0', - 'backtest-strategy-1', - ]); - expect(mixed).toEqual(before); - expect(mixed.dataFrequency).toBe('1d'); - }); - - test('custom factories retain their existing extension bag, including names also used by execution', () => { - const parameters = { - vendorOption: { window: 9 }, - dataFrequency: 'feature cadence', - commission: 12, - }; - const custom = backtestStrategies( - { ...config, strategy: 'custom', config: parameters }, - 'typescript' - ); - expect(custom[0]?.parameters).toMatchObject({ - ...parameters, - initialCapital: config.initialCapital, - }); - (custom[0]!.parameters.vendorOption as { window: number }).window = 100; - expect(parameters.vendorOption.window).toBe(9); - }); - - test('mean reversion and native-only strategies validate their actual, different contracts', () => { - const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 }); - expect(mean.trendPeriod).toBe(80); - expect(mean.entryThreshold).toBe(2); - expect(typescriptMeanReversionParameters.safeParse({ exitZScore: 3 }).success).toBe(false); - expect( - typescriptMeanReversionParameters.safeParse({ rsiOversold: 80, rsiOverbought: 20 }).success - ).toBe(false); - expect( - typescriptMeanReversionParameters.safeParse({ lookbackPeriod: 30, trendPeriod: 20 }).success - ).toBe(false); - expect(nativeMeanReversionParameters.safeParse({ exitZScore: 0.5 }).success).toBe(false); - expect(nativeMeanReversionParameters.safeParse({ lookbackPeriod: 0 }).success).toBe(false); - expect(nativeMomentumParameters.safeParse({ momentumThreshold: NaN }).success).toBe(false); - expect(nativePairsParameters.safeParse({ pairA: 'A.US', pairB: 'A.US' }).success).toBe(false); - expect(() => - backtestStrategies( - { ...config, strategy: 'pairs', config: { pairA: 'A.US', pairB: 'C.US' } }, - 'native' - ) - ).toThrow('included in backtest symbols'); - }); - - test('invalid native plans fail before loading input and unsupported execution flags are explicit', () => { - expect(() => backtestStrategies({ ...config, strategies: [] }, 'native')).toThrow('No enabled'); - expect(() => backtestStrategies({ ...config, strategies: [] }, 'typescript')).toThrow( - 'No enabled' - ); - expect(() => - resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: true } }) - ).toThrow('does not execute TypeScript'); - expect(() => - resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: 'false' } }) - ).toThrow(); - expect( - backtestStrategies({ ...config, config: { useTypeScriptImplementation: true } }, 'typescript') - ).toHaveLength(1); - }); - - test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => { - const f = await runtime(); - const storage = new StorageService(logger, null, null); - const backend = new BacktestEngine({ - logger, - execution: f.execution, - storage, - strategies: f.manager, - getTradingEngine: () => f.engine, - }); - cleanup.push(() => backend.shutdown()); - let reads = 0; - await expect( - backend.runBacktest({ ...config, config: { fastPeriod: 5, slowPeriod: 2 } }, async () => { - reads++; - throw new Error('Must not load data'); - }) - ).rejects.toThrow('SMA periods must satisfy'); - expect(reads).toBe(0); - }); - - test('definitions are detached and rejected inactive edits leave effective settings intact', async () => { - const f = await runtime(); - const input = { ...definition, parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 7 } }; - const strategy = new SmaCrossoverStrategy(input, f.mode, f.execution); - input.parameters.fastPeriod = 0; - const view = strategy.getConfig(); - view.parameters.slowPeriod = 0; - expect(strategy.getConfig().parameters).toMatchObject({ - fastPeriod: 2, - slowPeriod: 3, - quantity: 7, - }); - await expect( - strategy.updateConfig({ parameters: { fastPeriod: 9, slowPeriod: 3 } }) - ).rejects.toThrow('SMA periods'); - expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 2, slowPeriod: 3 }); - await strategy.updateConfig({ parameters: { fastPeriod: 3, slowPeriod: 8 } }); - expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 8 }); - }); -}); - -describe('shared trailing-window math and native parity', () => { - test('warm-up never manufactures zero averages or first-window crossovers', () => { - expect(trailingMean([3, 2], 3)).toBeUndefined(); - expect(movingAverageCrossover([3, 2, 1], 2, 3)).toBeUndefined(); - expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)).toMatchObject({ - goldenCross: true, - deathCross: false, - }); - expect(movingAverageCrossover([1, 2, 3, 1], 2, 3)).toMatchObject({ - goldenCross: false, - deathCross: false, - }); - expect(movingAverageCrossover([1, 2, 3, 0.5], 2, 3)).toMatchObject({ - goldenCross: false, - deathCross: true, - }); - expect(trailingPopulationDeviation([10, 10, 10], 3)).toBe(0); - for (const period of [0, -1, 1.5, Infinity]) - expect(() => trailingMean([1, 2, 3], period)).toThrow(); - expect(() => trailingMean([1, NaN, 3], 3)).toThrow('finite'); - expect(() => trailingMean([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('overflow'); - }); - - test('scalar SMA and population deviation match native batch and incremental indicators', () => { - const native = new TechnicalIndicators(); - const prices = Array.from( - { length: 130 }, - (_, index) => 100 + Math.sin(index / 3) * 8 + index / 100 - ); - for (const period of [2, 5, 15, 80]) { - const rolling = new IncrementalSMA(period); - const series = native.calculateSma(prices, period); - const bands = JSON.parse(native.calculateBollingerBands(prices, period, 2)); - for (let index = 0; index < prices.length; index++) { - const value = rolling.update(prices[index]!); - const scalar = trailingMean(prices.slice(0, index + 1), period); - if (scalar === undefined) { - expect(value == null).toBe(true); - continue; - } - expect(value!).toBeCloseTo(scalar, 9); - expect(series[index + 1 - period]!).toBeCloseTo(scalar, 9); - const deviation = trailingPopulationDeviation(prices.slice(0, index + 1), period)!; - expect( - (bands.upper[index + 1 - period] - bands.middle[index + 1 - period]) / 2 - ).toBeCloseTo(deviation, 8); - } - } - }); - - test('configured SMA periods and explicit shares reach real fills in both backends', async () => { - const f = await runtime({ fastPeriod: 2, slowPeriod: 3, quantity: 7, minHoldingBars: 0 }); - const prices = [3, 2, 1, 4]; - for (let i = 0; i < 3; i++) await f.manager.onMarketData(bar(prices[i]!, i)); - expect((await f.execution.getAccount()).positions['A.US']).toBeUndefined(); - await f.manager.onMarketData(bar(prices[3]!, 3)); - expect((await f.execution.getAccount()).positions['A.US']?.quantity).toBe(7); - const native = nativeEngine(); - native.addNativeStrategy('sma_crossover', 'sma', 'id', { - fastPeriod: 2, - slowPeriod: 3, - quantity: 7, - }); - native.loadMarketData( - prices.map((price, i) => ({ ...bar(price, i).data, type: 'bar', vwap: price })) - ); - const result = JSON.parse(native.run()); - // Native backtests liquidate at the end; that exit is not a second strategy entry. - expect(result.trades).toHaveLength(2); - expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 7, symbol: 'A.US' }); - expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 7, symbol: 'A.US' }); - expect(() => native.addNativeStrategy('sma_crossover', 'late', 'late', {})).toThrow('consumed'); - }); - - test('configured long windows remain checkpointable and preserve state through replacement', async () => { - const settings = { fastPeriod: 5, slowPeriod: 80, quantity: 1 }; - const f = await runtime(settings); - for (let i = 0; i < 90; i++) await f.manager.onMarketData(bar(100 + Math.sin(i / 3), i)); - const state = f.strategy.captureCheckpoint(); - const replacement = new SmaCrossoverStrategy(f.strategy.getConfig(), f.mode, f.execution); - replacement.restoreCheckpoint(state); - expect(replacement.captureCheckpoint()).toEqual(state); - expect(replacement.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); - const mean = await runtime({ lookbackPeriod: 80 }, 'mean-reversion'); - const prices = Array.from({ length: 90 }, (_, i) => 100 + Math.sin(i / 3)); - for (let i = 0; i < prices.length; i++) { - await mean.manager.onMarketData(bar(prices[i]!, i)); - } - const meanState = mean.strategy.captureCheckpoint(); - expect(meanState).toMatchObject({ - indicators: { - priceHistory: [['A.US', prices]], - indicators: [ - [ - 'A.US', - { - mean: trailingMean(prices, 80), - trendMean: trailingMean(prices, 80), - stdDev: trailingPopulationDeviation(prices, 80), - }, - ], - ], - }, - }); - const restoredMean = new MeanReversionStrategy( - mean.strategy.getConfig(), - mean.mode, - mean.execution - ); - restoredMean.restoreCheckpoint(meanState); - expect(restoredMean.captureCheckpoint()).toEqual(meanState); - expect(restoredMean.getConfig().parameters.trendPeriod).toBe(80); - }); - - test('v2 cannot silently reset a legacy paper definition; explicit new IDs preserve old registration', async () => { - const f = makeExecution(); - await f.execution.initialize(config, f.engine); - cleanup.push(() => f.execution.shutdown()); - const mode = { getTradingEngine: () => f.engine } as ModeManager; - const legacy = new SmaCrossoverStrategy(definition, mode, f.execution); - legacy.getCheckpointVersion = () => 'sma-crossover-fixed/v1'; - await f.execution.registerStrategy(legacy); - const before = await f.execution.getRecoveryStatus(); - const upgraded = new SmaCrossoverStrategy(definition, mode, f.execution); - await expect(f.execution.registerStrategy(upgraded)).rejects.toThrow('version changed'); - expect(await f.execution.getRecoveryStatus()).toEqual(before); - await f.execution.pauseStrategy('sma'); - const fresh = new SmaCrossoverStrategy({ ...definition, id: 'sma-v2' }, mode, f.execution); - await f.execution.registerStrategy(fresh); - expect((await f.execution.getRecoveryStatus()).strategies).toMatchObject([ - { strategyId: 'sma', enabled: false, version: 'sma-crossover-fixed/v1' }, - { strategyId: 'sma-v2', enabled: true, version: 'sma-crossover-fixed/v2' }, - ]); - }); -}); - -describe('native parameter trust boundary', () => { - test('native bindings reject invalid numeric types, fractions, infinities and unknown keys independently', () => { - const engine = nativeEngine(); - for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) { - expect(() => - engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: bad }) - ).toThrow('SMA periods'); - } - for (const [name, parameters] of [ - ['sma_crossover', { fastPreriod: 3 }], - ['sma_crossover', { quantity: -1 }], - ['mean_reversion', { lookbackPeriod: 0 }], - ['mean_reversion', { lookbackPeriod: 1.5 }], - ['mean_reversion', { entryThreshold: NaN }], - ['momentum', { positionSize: Infinity }], - ['momentum', { momentumThreshold: '5' }], - ['pairs_trading', { pairA: 'A.US', pairB: 'A.US' }], - ] as const) { - expect(() => engine.addNativeStrategy(name, 'invalid', 'invalid', parameters)).toThrow(); - } - expect(() => - engine.addNativeStrategy('sma_crossover', 'defaults', 'defaults', {}) - ).not.toThrow(); - }); -}); diff --git a/test/integration/strategy-recovery.test.ts b/test/integration/strategy-recovery.test.ts deleted file mode 100644 index 987db1e5..00000000 --- a/test/integration/strategy-recovery.test.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { canonicalJson as neutralCanonicalJson } from '../../apps/stock/orchestrator/src/canonical-json'; -import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; -import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery'; -import { config, makeExecution, order, quote, start } from '../fixtures/execution'; -import { - attachCounter, - CounterStrategy, - FaultRepository, - recoveryConfig, -} from '../fixtures/strategy-recovery'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - const repository = new FaultRepository(new BacktestExecutionRepository()); - const { execution, engine } = makeExecution(repository); - await execution.initialize(config, engine); - cleanup.push(() => execution.shutdown()); - const { manager, strategy } = await attachCounter(execution); - cleanup.push(() => manager.shutdown()); - return { repository, execution, manager, strategy }; -} -const isPending = (value: unknown) => (value as { status?: string }).status === 'pending'; -const isDispatched = (value: unknown) => (value as { status?: string }).status === 'dispatched'; - -describe('transactional strategy recovery', () => { - test('input order is its admission sequence, not JavaScript numeric object-key enumeration', async () => { - const f = await fixture(); - await f.execution.enqueueMarketData(quote('10')); - await f.execution.enqueueMarketData(quote('2', 110, 100, start + 1)); - await f.manager.recover(); - expect(f.strategy.equities).toEqual([10000, 10009.9]); - }); - test('a failed decision restores indicators and leaves later admitted inputs recoverable', async () => { - const f = await fixture(); - f.strategy.failDecision = true; - await f.execution.enqueueMarketData(quote('one')); - await f.execution.enqueueMarketData(quote('two', 110, 100, start + 1)); - await expect(f.manager.recover()).rejects.toThrow('decision failure'); - expect(f.strategy.count).toBe(0); - expect(f.strategy.getPosition('A')).toBe(0); - expect((await f.execution.getRecoveryStatus()).pendingInputs).toBe(true); - await expect(f.execution.submitOrder(order('manual'))).rejects.toThrow('backlog'); - f.strategy.failDecision = false; - await f.manager.recover(); - expect(f.strategy.count).toBe(2); - expect(f.strategy.getPosition('A')).toBe(2); - expect(f.strategy.equities).toEqual([10000, 10009.9]); - expect((await f.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); - await f.manager.onMarketData(quote('one')); - expect(f.strategy.count).toBe(2); - }); - test.each(['before', 'after'] as const)( - 'checkpoint + intent roll back together on a %s intent-write failure', - async stage => { - const f = await fixture(); - f.repository.fault = { method: 'putIntent', matches: isPending, stage }; - await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('transaction failure'); - expect(f.strategy.count).toBe(0); - expect((await f.execution.getAccount()).cash).toBe(10000); - expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false); - await f.manager.recover(); - expect(f.strategy.count).toBe(1); - expect(f.strategy.getPosition('A')).toBe(1); - } - ); - test('a lost checkpoint commit acknowledgement resumes from durable state, not a second decision', async () => { - const f = await fixture(); - f.repository.fault = { method: 'putIntent', matches: isPending, stage: 'commit' }; - await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('commit acknowledgement'); - expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(true); - await f.manager.shutdown(); - const restarted = await attachCounter(f.execution); - cleanup.push(() => restarted.manager.shutdown()); - expect(restarted.strategy.count).toBe(1); - expect(restarted.strategy.getPosition('A')).toBe(1); - expect(restarted.strategy.getPerformance().trades).toBe(1); - await restarted.manager.onMarketData(quote('one')); - expect(restarted.strategy.count).toBe(1); - }); - test.each(['after', 'commit'] as const)( - 'outbox dispatch is idempotent after a %s dispatch-status failure', - async stage => { - const f = await fixture(); - f.repository.fault = { method: 'putIntent', matches: isDispatched, stage }; - await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('injected'); - await f.manager.recover(); - expect(f.strategy.count).toBe(1); - expect(f.strategy.getPosition('A')).toBe(1); - expect(f.strategy.getPerformance().trades).toBe(1); - expect((await f.execution.getAccount()).cash).toBe(9899.9); - expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false); - } - ); - test('fill callback failure cannot lose a committed fill or advance its checkpoint', async () => { - const f = await fixture(); - f.strategy.failFill = true; - await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('fill callback'); - expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1); - expect(f.strategy.getPosition('A')).toBe(0); - expect(f.strategy.getPerformance().trades).toBe(0); - f.strategy.failFill = false; - await f.manager.recover(); - await f.manager.recover(); - expect(f.strategy.getPosition('A')).toBe(1); - expect(f.strategy.getPerformance().trades).toBe(1); - }); - test('shutdown preserves unfilled orders, indicator history, and committed cursor', async () => { - const f = await fixture(); - await f.manager.onMarketData(quote('one', 100, 0)); - const before = f.strategy.captureCheckpoint(); - await f.manager.shutdown(); - const restarted = await attachCounter(f.execution); - cleanup.push(() => restarted.manager.shutdown()); - expect(restarted.strategy.captureCheckpoint()).toEqual(before); - expect((await f.execution.getStrategySnapshot('counter')).orders).toHaveLength(1); - await restarted.manager.onMarketData(quote('two', 100, 100, start + 1)); - expect(restarted.strategy.getPerformance().trades).toBe(2); - }); - test('configuration and implementation versions cannot silently reset an existing strategy', async () => { - const f = await fixture(); - await f.manager.onMarketData(quote('one')); - await f.manager.shutdown(); - const changed = new CounterStrategy(f.execution, { - ...recoveryConfig, - parameters: { changed: true }, - }); - await expect(attachCounter(f.execution, changed)).rejects.toThrow('version changed'); - const version = new CounterStrategy(f.execution); - version.version = 'counter/v2'; - await expect(attachCounter(f.execution, version)).rejects.toThrow('version changed'); - expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1); - }); - test('disabled-period inputs do not become retroactive trades when re-enabled', async () => { - const f = await fixture(); - await f.manager.onMarketData(quote('one')); - await f.manager.disableStrategy('counter'); - await f.manager.onMarketData(quote('two', 100, 100, start + 1)); - await f.manager.enableStrategy('counter'); - await f.manager.recover(); - expect(f.strategy.count).toBe(1); - await f.manager.onMarketData(quote('three', 100, 100, start + 2)); - expect(f.strategy.count).toBe(2); - }); - test('observers run only after checkpoint commit and cannot roll back financial intent', async () => { - const f = await fixture(); - let signals = 0; - f.strategy.on('signal', () => { - signals++; - throw new Error('observer'); - }); - f.execution.setObserver(async () => { - throw new Error('observer'); - }); - await f.manager.onMarketData(quote('one')); - expect(signals).toBe(1); - expect(f.strategy.count).toBe(1); - expect(f.strategy.getPosition('A')).toBe(1); - }); - test('checkpoint serialization rejects lossy or non-finite state', () => { - for (const value of [NaN, Infinity, undefined, new Map(), new Date(), { hidden: undefined }]) { - expect(() => canonicalJson(value)).toThrow('plain JSON'); - } - expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 })); - }); - test('canonical serialization retains historical bytes and the compatibility export', () => { - expect(canonicalJson).toBe(neutralCanonicalJson); - const value = JSON.parse( - '{"z":-0,"๐€€":3,"a":[{"z":2,"a":1},null,true],"\\ue000":4,"__proto__":{"b":2,"a":1},"10":10,"2":2}' - ); - const expected = - '{"2":2,"10":10,"__proto__":{"a":1,"b":2},"a":[{"a":1,"z":2},null,true],"z":0,"๐€€":3,"\ue000":4}'; - expect(canonicalJson(value)).toBe(expected); - expect(neutralCanonicalJson(value)).toBe(expected); - }); - test('a callback cannot open a nested repository transaction and deadlock its account', async () => { - const f = await fixture(); - f.strategy.onDecision = async () => { - await f.execution.getOrderStatus('anything'); - }; - await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow( - 'cannot perform repository I/O' - ); - expect(f.strategy.count).toBe(0); - }); - test('a reused intent ID cannot replace a dispatched request or advance its next decision', async () => { - const f = await fixture(); - f.strategy.onDecision = async () => { - f.execution.captureStrategyOrder(order('fixed-id', 'buy', 1), 'counter'); - }; - await f.manager.onMarketData(quote('one')); - await expect(f.manager.onMarketData(quote('two', 100, 100, start + 1))).rejects.toThrow( - 'Conflicting strategy order intent' - ); - expect(f.strategy.count).toBe(1); - expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2); - }); -}); diff --git a/test/integration/strategy-registry.test.ts b/test/integration/strategy-registry.test.ts deleted file mode 100644 index db8849bb..00000000 --- a/test/integration/strategy-registry.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { EventEmitter } from 'node:events'; -import { afterEach, describe, expect, test } from 'bun:test'; -import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; -import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; -import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; -import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; -import { config, makeExecution, quote } from '../fixtures/execution'; -import { - CounterStrategy, - makeStrategyManager, - recoveryConfig, -} from '../fixtures/strategy-recovery'; - -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function fixture() { - const { execution, engine } = makeExecution(); - await execution.initialize(config, engine); - cleanup.push(() => execution.shutdown()); - const modeManager = { getTradingEngine: () => engine } as ModeManager; - return { - execution, - dependencies: { modeManager, execution }, - }; -} - -describe('strategy registration and expansion', () => { - test('custom lazy factories integrate with ordinary initialization, recovery and restart', async () => { - const f = await fixture(); - let created = 0; - const registry = new StrategyRegistry().register( - ['fixture', 'custom-alias'], - (config, dependencies) => { - created++; - expect(dependencies.execution).toBe(f.execution); - return new CounterStrategy(dependencies.execution, config); - } - ); - expect(created).toBe(0); - const marketData = new EventEmitter(); - const manager = makeStrategyManager({ ...f.dependencies, registry, marketData }); - cleanup.push(() => manager.shutdown()); - await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]); - expect(marketData.listenerCount('marketDataBatch')).toBe(1); - marketData.emit('marketDataBatch', [quote('first')]); - await manager.drain(); - expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1); - await manager.shutdown(); - expect(marketData.listenerCount('marketDataBatch')).toBe(0); - const restarted = makeStrategyManager({ ...f.dependencies, registry, marketData }); - cleanup.push(() => restarted.shutdown()); - await restarted.restoreStrategies(); - restarted.setupEventListeners(); - expect(marketData.listenerCount('marketDataBatch')).toBe(1); - expect(created).toBe(2); - expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1); - marketData.emit('marketDataBatch', [quote('second')]); - await restarted.drain(); - expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2); - }); - - test('aliases are normalized and registration conflicts fail atomically', async () => { - const f = await fixture(); - const registry = new StrategyRegistry().register( - ['fixture'], - config => new CounterStrategy(f.execution, config) - ); - const factory = () => new CounterStrategy(f.execution); - expect(() => registry.register(['new', 'FIXTURE'], factory)).toThrow('already registered'); - await expect( - registry.create({ ...recoveryConfig, name: 'new' }, f.dependencies) - ).rejects.toThrow('Unknown strategy'); - for (const aliases of [[], [''], [' '], ['duplicate', 'DUPLICATE']]) { - expect(() => registry.register(aliases, factory)).toThrow('nonempty and distinct'); - } - expect( - (await registry.create({ ...recoveryConfig, name: ' FIXTURE ' }, f.dependencies)).getConfig() - .id - ).toBe('counter'); - }); - - test('built-in aliases keep their implementations and unknown names fail closed', async () => { - const f = await fixture(); - const registry = createBuiltinStrategyRegistry(); - for (const name of ['meanreversion', 'mean-reversion']) { - const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); - expect(strategy).toBeInstanceOf(MeanReversionStrategy); - expect(strategy.getCheckpointVersion()).toBe('mean-reversion/v2'); - } - for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) { - const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); - expect(strategy).toBeInstanceOf(SmaCrossoverStrategy); - expect(strategy.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); - } - for (const name of ['mlenhanced', 'ml-enhanced']) { - expect( - (await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion() - ).toBeUndefined(); - } - await expect( - registry.create({ ...recoveryConfig, name: 'missing' }, f.dependencies) - ).rejects.toThrow('Unknown strategy: missing'); - }); - - test('factory failures propagate before an invalid strategy can be activated', async () => { - const f = await fixture(); - const registry = new StrategyRegistry().register(['fixture'], async () => { - throw new Error('factory failed'); - }); - const manager = makeStrategyManager({ ...f.dependencies, registry }); - cleanup.push(() => manager.shutdown()); - await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed'); - expect(manager.getActiveStrategies()).toEqual([]); - expect(await f.execution.registeredStrategies()).toEqual([]); - }); -}); diff --git a/test/integration/strategy-runtime.test.ts b/test/integration/strategy-runtime.test.ts index 84df6d83..376ef37f 100644 --- a/test/integration/strategy-runtime.test.ts +++ b/test/integration/strategy-runtime.test.ts @@ -13,7 +13,7 @@ import type { StrategyContext, StrategyDiagnosticSnapshot, StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +} from '@stock-bot/research/strategy-api'; import { nativeReplayFixture } from '../fixtures/native-replay'; const hold = () => ({ mode: 'target' as const, targets: [] }); diff --git a/test/integration/typescript-backtest.test.ts b/test/integration/typescript-backtest.test.ts deleted file mode 100644 index 29f03cc5..00000000 --- a/test/integration/typescript-backtest.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine'; -import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; -import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; -import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; -import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; -import { - BacktestConfigSchema, - type OrchestratorServices, -} from '../../apps/stock/orchestrator/src/types'; -import { logger } from '../fixtures/execution'; - -const config = BacktestConfigSchema.parse({ - mode: 'backtest', - strategy: 'sma-crossover', - symbols: ['A.US', 'B.US'], - startDate: '2024-01-01T00:00:00Z', - endDate: '2024-03-15T00:00:00Z', - initialCapital: 10000, - dataFrequency: '1d', - speed: 'max', - commission: 0.001, - slippage: 0, -}); -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close(); -}); -async function fixture() { - const services: OrchestratorServices = { logger }; - const storage = new StorageService(services.logger, null, null, { - allowSyntheticData: true, - syntheticSeed: 42, - }); - const market: MarketDataService = new MarketDataService({ - logger, - storage, - drainStrategies: () => manager.drain(), - }); - const execution = new ExecutionService(services, storage); - const registry = createBuiltinStrategyRegistry(); - const manager: StrategyManager = new StrategyManager({ - logger, - marketData: market, - execution, - createStrategy: config => registry.create(config, { execution, modeManager: mode }), - }); - const mode: ModeManager = new ModeManager({ - logger, - marketData: market, - execution, - strategies: manager, - }); - const backend = new BacktestEngine({ - logger, - storage, - strategies: manager, - execution, - getTradingEngine: () => mode.getTradingEngine(), - }); - await mode.initializeMode(config); - cleanup.push(async () => { - await backend.shutdown(); - await mode.shutdown(); - }); - return { services, storage, execution, manager, mode, backend }; -} -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise(done => { - resolve = done; - }); - return { promise, resolve }; -} - -describe('composed TypeScript backtests', () => { - test('completed results and repeatable exports agree with the authoritative ledger', async () => { - const f = await fixture(); - const result = await f.backend.runBacktest(config); - const account = await f.execution.getAccount(); - expect(result.status).toBe('completed'); - expect(result.trades.length).toBeGreaterThan(0); - expect(result.equity.at(-1)?.value).toBe(account.equity); - expect(result.metrics.totalReturn).toBeCloseTo( - ((account.equity - config.initialCapital) / config.initialCapital) * 100 - ); - expect(result.positions.every(position => position.quantity !== 0)).toBe(true); - for (const position of result.positions) { - const quote = account.quotes[position.symbol]!; - expect(position.currentPrice).toBe((quote.bid + quote.ask) / 2); - } - const first = await f.backend.exportResults(); - expect(JSON.parse(first).summary.totalTrades).toBe(result.trades.length); - expect(JSON.parse(first).equityCurve.map((point: { value: number }) => point.value)).toEqual( - result.equity.map(point => point.value) - ); - result.equity[0]!.value = -1; - await f.backend.exportResults('csv'); - await f.backend.exportResults('html'); - expect(await f.backend.exportResults()).toBe(first); - expect(f.backend.getStatus()).toMatchObject({ - isRunning: false, - isPaused: false, - progress: 100, - }); - }); - - test('service reuse does not leak symbols, indicators, equity or exports across runs', async () => { - const f = await fixture(); - const first = await f.backend.runBacktest(config); - const secondConfig = { ...config, symbols: ['C.US'] }; - await f.mode.initializeMode(secondConfig); - const second = await f.backend.runBacktest(secondConfig); - expect(Object.keys(second.ohlcData)).toEqual(['C.US']); - expect(second.trades.every(trade => trade.symbol === 'C.US')).toBe(true); - await f.mode.initializeMode(config); - const repeated = await f.backend.runBacktest(config); - expect(repeated.trades).toEqual(first.trades); - expect(repeated.metrics).toEqual(first.metrics); - expect(repeated.equity).toEqual(first.equity); - }); - - test('overlapping runs fail before they can reset the active read or its controls', async () => { - const f = await fixture(); - const gate = deferred(); - let loads = 0; - const run = f.backend.runBacktest(config, async load => { - loads++; - await gate.promise; - return load(); - }); - const settled = run.catch(error => error); - await expect(f.backend.runBacktest(config)).rejects.toThrow('already running'); - await expect(f.backend.exportResults()).rejects.toThrow('unfinished'); - expect(loads).toBe(1); - await f.backend.stopBacktest(); - expect(await settled).toBeInstanceOf(BacktestCancelledError); - gate.resolve(); - await new Promise(resolve => setTimeout(resolve, 0)); - expect(f.manager.getAllStrategies()).toEqual([]); - await expect(f.backend.exportResults()).rejects.toThrow('No completed'); - expect(f.backend.getStatus()).toMatchObject({ isRunning: false, progress: 0 }); - }); - - test('cancellation at progress never returns a partial completed result or a reusable export', async () => { - const f = await fixture(); - const updates: number[] = []; - f.backend.on('progress', update => { - updates.push(update.progress); - void f.backend.stopBacktest(); - }); - const outcome = await f.backend.runBacktest(config).catch(error => error); - expect(outcome).toBeInstanceOf(BacktestCancelledError); - expect(updates).not.toContain(100); - expect(f.backend.getStatus()).toMatchObject({ isRunning: false, isPaused: false }); - await expect(f.backend.exportResults()).rejects.toThrow('No completed'); - }); - - test('pause gates the next input, and resume produces the same ledger result', async () => { - const f = await fixture(); - const paused = deferred(); - const original = f.manager.onMarketData.bind(f.manager); - let received = 0; - f.manager.onMarketData = async data => { - await original(data); - if (++received === 1) { - await f.backend.pauseBacktest(); - paused.resolve(); - } - }; - const run = f.backend.runBacktest(config); - await paused.promise; - await new Promise(resolve => setTimeout(resolve, 0)); - expect(received).toBe(1); - expect(f.backend.getStatus().isPaused).toBe(true); - await f.backend.resumeBacktest(); - const result = await run; - expect(result.status).toBe('completed'); - expect(result.equity.at(-1)?.value).toBe((await f.execution.getAccount()).equity); - }); - - test('unavailable financial state fails instead of fabricating initial-capital performance', async () => { - const f = await fixture(); - f.execution.getAccount = async () => { - throw new Error('Ledger unavailable'); - }; - await expect(f.backend.runBacktest(config)).rejects.toThrow('Ledger unavailable'); - expect(f.backend.getStatus().isRunning).toBe(false); - await expect(f.backend.exportResults()).rejects.toThrow('No completed'); - }); - - test('observer failures cannot change the result, and shutdown closes future admission', async () => { - const f = await fixture(); - f.backend.on('progress', () => { - throw new Error('observer failed'); - }); - expect((await f.backend.runBacktest(config)).status).toBe('completed'); - await f.backend.shutdown(); - await expect(f.backend.runBacktest(config)).rejects.toThrow('shutting down'); - }); -}); diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts index e883ca74..f1f0db0e 100644 --- a/test/postgres/canonical-durable-backtest.test.ts +++ b/test/postgres/canonical-durable-backtest.test.ts @@ -11,7 +11,7 @@ import { type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; -import { readCanonicalBuildIdentity } from '../../apps/stock/orchestrator/src/backtest/canonical-build'; +import { readCanonicalBuildIdentity } from '@stock-bot/trading-runtime/canonical-build'; import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; diff --git a/test/postgres/canonical-paper.test.ts b/test/postgres/canonical-paper.test.ts index 8fa8a88b..4670f965 100644 --- a/test/postgres/canonical-paper.test.ts +++ b/test/postgres/canonical-paper.test.ts @@ -5,12 +5,12 @@ import { Pool } from 'pg'; import { stageFinancialTransaction } from '@stock-bot/engine'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { parseFinancialDecimal } from '@stock-bot/types'; -import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; +import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; import { parseFinancialTransactionResult, type CanonicalMatchingConfig, -} from '../../apps/stock/orchestrator/src/contracts/canonical-execution'; -import type { StrategyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +} from '@stock-bot/stock-config/canonical-execution'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; import { canonicalPaperInputSchema, type CanonicalExecutionRepository, @@ -20,7 +20,6 @@ import { } from '../../apps/stock/orchestrator/src/execution/canonical-paper'; import { CanonicalPaperExecution } from '../../apps/stock/orchestrator/src/execution/CanonicalPaperExecution'; import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresCanonicalExecutionRepository'; -import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; import { StrategyController } from '../../apps/stock/orchestrator/src/strategies/strategy-controller'; import { @@ -535,20 +534,10 @@ describe.skipIf(!url)('canonical paper custody on real PostgreSQL', () => { ]) { await expect(f.make({ programs: [program] })).rejects.toThrow('definition'); } - const legacy = new PostgresExecutionRepository(f.postgres); - await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow( - 'canonical adapter' - ); - await expect(legacy.initialize(f.config.risk.ledger.accountId, {} as never)).rejects.toThrow( - 'canonical adapter' - ); await f.pool.query( 'UPDATE simulation_accounts SET state = \'{"kind":"canonical-paper","version":99}\'' ); await expect(f.make()).rejects.toThrow('explicit migration'); - await expect(legacy.transact(f.config.risk.ledger.accountId, async () => null)).rejects.toThrow( - 'canonical adapter' - ); await f.pool.query('UPDATE simulation_accounts SET state = \'{"cash":100}\''); await expect(f.make()).rejects.toThrow('explicit migration'); }); diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 8f49ce90..61cba00b 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -23,7 +23,7 @@ import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import { StorageService } from '@stock-bot/trading-runtime/historical-storage'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; import { diff --git a/test/postgres/order-execution.test.ts b/test/postgres/order-execution.test.ts deleted file mode 100644 index 6a15b7ea..00000000 --- a/test/postgres/order-execution.test.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; -import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; -import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close(); -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) - throw new Error('Dedicated safety database required'); - const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - const sql = readFileSync( - new URL('../../database/postgres/init/11-simulation-execution-ledger.sql', import.meta.url), - 'utf8' - ); - await pool.query(sql); - await pool.query(sql); - await pool.query( - readFileSync( - new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url), - 'utf8' - ) - ); - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - let now = start; - const make = async ( - limits = { - maxOrderSize: 100, - maxPositionSize: 100, - maxDailyLoss: 100, - maxGrossExposure: 10000, - maxSymbolExposure: 10000, - } - ) => { - const runtime = makeExecution(new PostgresExecutionRepository(postgres), () => now); - await runtime.execution.initialize( - { - mode: 'paper', - accountId: 'fixture', - startingCapital: config.initialCapital, - commission: 0.001, - slippage: 0, - maxQuoteAgeMs: 1000, - riskLimits: limits, - }, - runtime.engine - ); - cleanup.push(() => runtime.execution.shutdown()); - return runtime.execution; - }; - const execution = await make(); - return { - pool, - postgres, - execution, - make, - setTime(time: number) { - now = time; - }, - }; -} -describe.skipIf(!url)('paper execution ledger on real PostgreSQL', () => { - test('competing service instances deduplicate the same client ID, fill and account transaction', async () => { - const f = await fixture(); - const second = await f.make(); - await f.execution.onMarketData(quote('q')); - const reports = await Promise.all([ - f.execution.submitOrder(order('id')), - second.submitOrder(order('id')), - ]); - expect(reports[0]).toEqual(reports[1]); - expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1); - const fills = (await f.pool.query('SELECT payload FROM simulation_fills')).rows; - expect(fills).toHaveLength(1); - expect(fills[0].payload.pnl).toBe(-1); - expect((await second.getAccount()).cash).toBe(8999); - expect((await second.getPositions())[0]?.quantity).toBe(10); - await expect(second.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf( - ExecutionConflictError - ); - }); - test('a fill-write failure rolls back acceptance and cash/positions together; retry has no phantom fill', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q')); - let events = 0; - f.execution.on('fill', () => events++); - await f.pool.query(`CREATE FUNCTION reject_fill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - RAISE EXCEPTION 'injected fill failure'; END $$; - CREATE TRIGGER reject_fill BEFORE INSERT ON simulation_fills FOR EACH ROW EXECUTE FUNCTION reject_fill();`); - await expect(f.execution.submitOrder(order('id'))).rejects.toThrow('injected fill failure'); - expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0); - expect((await f.execution.getAccount()).cash).toBe(10000); - expect(events).toBe(0); - await f.pool.query('DROP TRIGGER reject_fill ON simulation_fills'); - expect((await f.execution.submitOrder(order('id'))).status).toBe('filled'); - expect(events).toBe(1); - }); - test('restart restores partial orders, consumed liquidity, cash and strategy positions without refilling duplicates', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q1', 100, 3)); - const first = await f.execution.submitOrder(order('id'), { strategyId: 'strategy' }); - expect(first.status).toBe('partiallyFilled'); - await f.execution.shutdown(); - const second = await f.make(); - expect((await second.getStrategySnapshot('strategy')).positions.A).toBe(3); - expect((await second.getStrategySnapshot('strategy')).orders).toHaveLength(1); - expect(await second.onMarketData(quote('q1', 100, 3))).toBe(false); - f.setTime(start + 1); - await second.onMarketData(quote('q2', 100, 7, start + 1)); - expect((await second.getOrderStatus(first.orderId))?.status).toBe('filled'); - expect((await second.getAccount()).cash).toBe(8999); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(2); - }); - test('account locking serializes projected-risk reservations across producers', async () => { - const f = await fixture(); - const limits = { - maxOrderSize: 100, - maxPositionSize: 100, - maxDailyLoss: 100, - maxGrossExposure: 1000, - maxSymbolExposure: 1000, - }; - const first = await f.make(limits), - second = await f.make(limits); - await first.onMarketData(quote('q', 100, 0)); - const reports = await Promise.all([ - first.submitOrder(order('a', 'buy', 7)), - second.submitOrder(order('b', 'buy', 7)), - ]); - expect(reports.map(r => r.status).sort()).toEqual(['accepted', 'rejected']); - expect((await f.execution.getAccount()).cash).toBe(10000); - }); - test('duplicate and conflicting market IDs cannot reapply fills, even after a restart', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q', 100, 3)); - const report = await f.execution.submitOrder(order('id')); - const second = await f.make(); - await expect(second.onMarketData(quote('q', 200, 3))).rejects.toBeInstanceOf( - ExecutionConflictError - ); - expect(await second.onMarketData(quote('q', 100, 3))).toBe(false); - expect((await second.getOrderStatus(report.orderId))?.fills).toHaveLength(1); - expect((await second.getAccount()).cash).toBe(9699.7); - }); - test('daily P&L uses deltas; loss limit blocks new risk but permits reduction and resets at UTC midnight', async () => { - const f = await fixture(); - const e = await f.make({ - maxOrderSize: 100, - maxPositionSize: 100, - maxDailyLoss: 1, - maxGrossExposure: 10000, - maxSymbolExposure: 10000, - }); - await e.onMarketData(quote('q')); - await e.submitOrder(order('open')); - expect((await e.submitOrder(order('blocked', 'buy', 1))).status).toBe('rejected'); - expect((await e.submitOrder(order('close', 'sell', 10))).status).toBe('filled'); - expect((await e.getAccount()).dailyPnl).toBe(-2); - f.setTime(start + 86400000); - await e.onMarketData(quote('new-day', 100, 100, start + 86400000)); - expect((await e.getAccount()).dailyPnl).toBe(0); - expect((await e.submitOrder(order('new-day-order', 'buy', 1))).status).toBe('filled'); - }); - test('stale quotes reject submission; day orders expire and unfilled cancellation survives restart', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q', 100, 0)); - const day = await f.execution.submitOrder(order('day')); - const gtc = await f.execution.submitOrder({ ...order('gtc'), timeInForce: 'GTC' }); - f.setTime(start + 2000); - expect((await f.execution.submitOrder(order('stale'))).rejectionReason).toContain('stale'); - await expect(f.execution.onMarketData(quote('old', 100, 100, start + 1))).rejects.toThrow( - 'Stale' - ); - f.setTime(start + 86400000); - await f.execution.onMarketData(quote('next', 100, 0, start + 86400000)); - expect((await f.execution.getOrderStatus(day.orderId))?.status).toBe('cancelled'); - expect(await f.execution.cancelOrder(gtc.orderId)).toBe(true); - const second = await f.make(); - expect((await second.getOrderStatus(gtc.orderId))?.status).toBe('cancelled'); - }); - test('observer exceptions cannot change committed fills into reported failure or trigger another fill', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q')); - f.execution.setObserver(async () => { - throw new Error('observer disconnected'); - }); - const report = await f.execution.submitOrder(order('id')); - expect(report.status).toBe('filled'); - expect((await f.execution.submitOrder(order('id'))).orderId).toBe(report.orderId); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1); - }); - - test('pending orders retain their accepted commission policy after account configuration changes', async () => { - const f = await fixture(); - await f.execution.onMarketData(quote('q1', 100, 3)); - const original = await f.execution.submitOrder(order('pending')); - const changed = makeExecution(new PostgresExecutionRepository(f.postgres), () => start + 1); - await changed.execution.initialize( - { - mode: 'paper', - accountId: 'fixture', - startingCapital: 10000, - commission: 0.01, - slippage: 0, - }, - changed.engine - ); - cleanup.push(() => changed.execution.shutdown()); - await changed.execution.onMarketData(quote('q2', 100, 10, start + 1)); - const report = await changed.execution.getOrderStatus(original.orderId); - expect(report?.fills.reduce((n, fill) => n + fill.commission, 0)).toBe(1); - const next = await changed.execution.submitOrder(order('new', 'buy', 1)); - expect(next.fills[0]?.commission).toBe(1); - }); -}); diff --git a/test/postgres/paper-deployments.test.ts b/test/postgres/paper-deployments.test.ts index dac9f5b0..9c5b4cf1 100644 --- a/test/postgres/paper-deployments.test.ts +++ b/test/postgres/paper-deployments.test.ts @@ -13,8 +13,8 @@ import { PostgresCanonicalExecutionRepository } from '../../apps/stock/orchestra import { readPaperDeployment, verifyPaperEvidenceCustody, -} from '../../apps/stock/orchestrator/src/paper/paper-deployment-custody'; -import { readPaperHostIdentity } from '../../apps/stock/orchestrator/src/paper/paper-host-identity'; +} from '@stock-bot/trading-runtime/paper-deployment-custody'; +import { readPaperHostIdentity } from '@stock-bot/trading-runtime/paper-host-identity'; import { PaperDeploymentHost } from '../../apps/stock/orchestrator/src/paper/PaperDeploymentHost'; import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; diff --git a/test/postgres/paper-http.test.ts b/test/postgres/paper-http.test.ts index f78bda02..3c1d288f 100644 --- a/test/postgres/paper-http.test.ts +++ b/test/postgres/paper-http.test.ts @@ -5,8 +5,8 @@ import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di'; import { parseFinancialDecimal } from '@stock-bot/types'; import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper'; import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; -import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy'; -import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime'; +import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy'; +import type { PaperRuntime } from '@stock-bot/stock-config/paper-runtime'; import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; diff --git a/test/postgres/strategy-recovery.test.ts b/test/postgres/strategy-recovery.test.ts deleted file mode 100644 index aeead35e..00000000 --- a/test/postgres/strategy-recovery.test.ts +++ /dev/null @@ -1,373 +0,0 @@ -import { fork } from 'node:child_process'; -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; -import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; -import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository'; -import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; -import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; -import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; -import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; -import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; -import { logger, makeExecution, quote, start } from '../fixtures/execution'; -import { - attachCounter, - CounterStrategy, - makeStrategyManager, - recoveryConfig, -} from '../fixtures/strategy-recovery'; - -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); -async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated safety database required'); - } - const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); - const admin = new Pool({ connectionString: url }); - await admin.query('CREATE SCHEMA ' + schema); - const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); - cleanup.push(async () => { - await pool.end(); - await admin.query('DROP SCHEMA ' + schema + ' CASCADE'); - await admin.end(); - }); - for (const migration of ['11-simulation-execution-ledger.sql', '13-strategy-recovery.sql']) { - await pool.query( - readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8') - ); - } - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); - Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); - let now = start + 100; - const make = async ( - accountId = 'fixture', - repository: ExecutionRepository = new PostgresExecutionRepository(postgres) - ) => { - const runtime = makeExecution(repository, () => now); - await runtime.execution.initialize( - { - mode: 'paper', - accountId, - startingCapital: 10000, - commission: 0.001, - slippage: 0, - maxQuoteAgeMs: 1000, - }, - runtime.engine - ); - cleanup.push(() => runtime.execution.shutdown()); - return runtime; - }; - return { - pool, - postgres, - schema, - make, - setTime: (time: number) => { - now = time; - }, - getTime: () => now, - }; -} - -describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => { - test('paper mode restores registered strategies and drains their inbox before starting the feed', async () => { - const f = await fixture(); - const original = await f.make(); - const config = { - ...recoveryConfig, - id: 'sma', - name: 'sma-crossover', - parameters: { initialCapital: 10000 }, - }; - const prior = makeStrategyManager({ - execution: original.execution, - modeManager: { getTradingEngine: () => original.engine } as ModeManager, - }); - await prior.initializeStrategies([config]); - await prior.onMarketData(quote('one')); - await prior.shutdown(); - await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1)); - const services: OrchestratorServices = { logger, postgres: f.postgres }; - const storage = new StorageService(services.logger, null, null); - const execution = new ExecutionService(services, storage, { clock: f.getTime }); - let feedStarted = false; - class OfflineMarket extends MarketDataService { - override async initialize() { - feedStarted = true; - expect((await execution.getRecoveryStatus()).pendingInputs).toBe(false); - expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); - } - } - const market: MarketDataService = new OfflineMarket({ - logger, - storage, - drainStrategies: () => manager.drain(), - }); - const registry = createBuiltinStrategyRegistry(); - const manager: StrategyManager = new StrategyManager({ - logger, - execution, - marketData: market, - createStrategy: config => registry.create(config, { execution, modeManager: mode }), - }); - const mode: ModeManager = new ModeManager({ - logger, - marketData: market, - execution, - strategies: manager, - }); - cleanup.push(() => mode.shutdown()); - await mode.initializeMode({ - mode: 'paper', - accountId: 'fixture', - startingCapital: 10000, - commission: 0.001, - slippage: 0, - maxQuoteAgeMs: 1000, - }); - expect(feedStarted).toBe(true); - expect(manager.getActiveStrategies()).toEqual(['sma']); - }); - test.each(['decision', 'checkpoint', 'dispatch'] as const)( - 'hard kill at %s resumes without skipped decisions or duplicate fills', - async phase => { - const f = await fixture(); - const { execution } = await f.make(); - const initial = await attachCounter(execution); - await initial.manager.shutdown(); - await execution.enqueueMarketData(quote('one')); - const child = fork( - fileURLToPath(new URL('../fixtures/strategy-crash-owner.ts', import.meta.url)), - [], - { - execPath: process.execPath, - execArgv: [], - stdio: ['ignore', 'ignore', 'ignore', 'ipc'], - env: { ...process.env, STRATEGY_FIXTURE_SCHEMA: f.schema, STRATEGY_FIXTURE_PHASE: phase }, - } - ); - const exited = new Promise(resolve => child.once('exit', () => resolve())); - cleanup.push(async () => { - child.kill('SIGKILL'); - await exited; - }); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(new Error('Crash fixture boundary timeout')), 5000); - child.once('message', message => { - clearTimeout(timeout); - if ((message as { phase: string }).phase === phase) { - resolve(); - } else { - reject(new Error('Wrong crash boundary')); - } - }); - child.once('exit', () => { - clearTimeout(timeout); - reject(new Error('Crash fixture exited before its boundary')); - }); - }); - child.kill('SIGKILL'); - await exited; - const restarted = await f.make(); - const resumed = await attachCounter(restarted.execution); - cleanup.push(() => resumed.manager.shutdown()); - expect(resumed.strategy.count).toBe(1); - expect(resumed.strategy.getPosition('A')).toBe(1); - expect(resumed.strategy.getPerformance().trades).toBe(1); - expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1); - await resumed.manager.onMarketData(quote('one')); - expect(resumed.strategy.count).toBe(1); - expect((await restarted.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); - } - ); - - test('checkpoint and order-intent SQL writes roll back together on an injected trigger failure', async () => { - const f = await fixture(); - const { execution } = await f.make(); - const { manager, strategy } = await attachCounter(execution); - cleanup.push(() => manager.shutdown()); - await f.pool - .query(`CREATE FUNCTION reject_intent() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent failure'; END $$; - CREATE TRIGGER reject_intent BEFORE INSERT ON simulation_strategy_intents FOR EACH ROW EXECUTE FUNCTION reject_intent()`); - await expect(manager.onMarketData(quote('one'))).rejects.toThrow('intent failure'); - expect(strategy.count).toBe(0); - expect( - (await f.pool.query('SELECT payload FROM simulation_strategy_checkpoints')).rows[0].payload - .cursor - ).toBe(0); - expect((await f.pool.query('SELECT * FROM simulation_strategy_intents')).rows).toHaveLength(0); - await f.pool.query('DROP TRIGGER reject_intent ON simulation_strategy_intents'); - await manager.recover(); - expect(strategy.count).toBe(1); - expect(strategy.getPosition('A')).toBe(1); - }); - - test('input admission survives a rollback before quote application and journal creation', async () => { - const f = await fixture(); - const { execution } = await f.make(); - const { manager } = await attachCounter(execution); - cleanup.push(() => manager.shutdown()); - await f.pool - .query(`CREATE FUNCTION reject_input_apply() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected application failure'; END $$; - CREATE TRIGGER reject_input_apply BEFORE UPDATE ON simulation_market_inputs FOR EACH ROW EXECUTE FUNCTION reject_input_apply()`); - await expect(manager.onMarketData(quote('one'))).rejects.toThrow('application failure'); - expect((await execution.getAccount()).quotes.A).toBeUndefined(); - expect((await f.pool.query('SELECT * FROM simulation_strategy_journal')).rows).toHaveLength(0); - expect((await execution.getRecoveryStatus()).pendingInputs).toBe(true); - await manager.shutdown(); - await f.pool.query('DROP TRIGGER reject_input_apply ON simulation_market_inputs'); - const restarted = await f.make(); - const resumed = await attachCounter(restarted.execution); - cleanup.push(() => resumed.manager.shutdown()); - expect(resumed.strategy.count).toBe(1); - expect(resumed.strategy.getPosition('A')).toBe(1); - }); - - test('competing owners restore the locked checkpoint before every decision and consume one intent', async () => { - const f = await fixture(); - const one = await f.make(), - two = await f.make(); - const first = await attachCounter(one.execution), - second = await attachCounter(two.execution); - cleanup.push( - () => first.manager.shutdown(), - () => second.manager.shutdown() - ); - await one.execution.enqueueMarketData(quote('one')); - await Promise.all([first.manager.recover(), second.manager.recover()]); - await Promise.all([first.manager.recover(), second.manager.recover()]); - expect(first.strategy.count).toBe(1); - expect(second.strategy.count).toBe(1); - expect(first.strategy.getPosition('A')).toBe(1); - expect(second.strategy.getPosition('A')).toBe(1); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1); - }); - - test('stale admitted inputs restore indicators but never fabricate stale paper fills', async () => { - const f = await fixture(); - const { execution } = await f.make(); - const { manager, strategy } = await attachCounter(execution); - cleanup.push(() => manager.shutdown()); - await execution.enqueueMarketData(quote('one')); - f.setTime(start + 5000); - await manager.recover(); - expect(strategy.count).toBe(1); - expect(strategy.getPosition('A')).toBe(0); - const orders = (await f.pool.query('SELECT payload FROM simulation_orders')).rows; - expect(orders[0].payload.report.status).toBe('rejected'); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0); - }); - - test('real SMA indicator checkpoints reproduce an uninterrupted run across process replacement', async () => { - const f = await fixture(); - const smaConfig = { - ...recoveryConfig, - id: 'sma', - name: 'sma-crossover', - parameters: { initialCapital: 10000 }, - }; - const makeManager = async (account: string) => { - const runtime = await f.make(account); - const manager = makeStrategyManager({ - execution: runtime.execution, - modeManager: { getTradingEngine: () => runtime.engine } as ModeManager, - }); - await manager.initializeStrategies([smaConfig]); - cleanup.push(() => manager.shutdown()); - return { ...runtime, manager }; - }; - const bars = Array.from({ length: 45 }, (_, index) => { - const price = 100 + Math.sin(index / 3) * 8; - return { - type: 'bar' as const, - eventId: 'bar-' + index, - data: { - symbol: 'A', - timestamp: start + index * 86400000, - open: price, - high: price + 1, - low: price - 1, - close: price, - volume: 100000, - }, - }; - }); - const baseline = await makeManager('baseline'); - for (const bar of bars) { - f.setTime(bar.data.timestamp); - await baseline.manager.onMarketData(bar); - } - f.setTime(start); - const interrupted = await makeManager('interrupted'); - for (const bar of bars.slice(0, 22)) { - f.setTime(bar.data.timestamp); - await interrupted.manager.onMarketData(bar); - } - await interrupted.manager.shutdown(); - const restarted = await makeManager('interrupted'); - for (const bar of bars.slice(22)) { - f.setTime(bar.data.timestamp); - await restarted.manager.onMarketData(bar); - } - const meaningfulState = (manager: StrategyManager) => { - const { - seenFills: _seenFills, - pendingOrders: _pendingOrders, - ...state - } = manager.getStrategy('sma')!.captureCheckpoint() as Record; - return state; - }; - expect(meaningfulState(restarted.manager)).toEqual(meaningfulState(baseline.manager)); - expect((await restarted.execution.getAccount()).cash).toBe( - (await baseline.execution.getAccount()).cash - ); - expect( - (await f.pool.query("SELECT * FROM simulation_fills WHERE account_id = 'baseline'")).rows - .length - ).toBeGreaterThan(0); - }); - - test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => { - const f = await fixture(); - const { execution, engine } = await f.make(); - const manager = makeStrategyManager({ - execution, - modeManager: { getTradingEngine: () => engine } as ModeManager, - }); - cleanup.push(() => manager.shutdown()); - await expect( - manager.initializeStrategies([{ ...recoveryConfig, name: 'ml-enhanced' }]) - ).rejects.toThrow('versioned checkpoint'); - expect((await f.pool.query('SELECT * FROM simulation_strategy_checkpoints')).rows).toHaveLength( - 0 - ); - const active = await attachCounter(execution); - cleanup.push(() => active.manager.shutdown()); - await active.manager.onMarketData(quote('one')); - await f.pool.query( - readFileSync( - new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url), - 'utf8' - ) - ); - expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1); - expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); - }); -}); diff --git a/test/setup.js b/test/setup.js deleted file mode 100644 index 5f67360e..00000000 --- a/test/setup.js +++ /dev/null @@ -1,112 +0,0 @@ -"use strict"; -/** - * Bun Test Setup File for Stock Bot Trading Platform - * - * Global test configuration and utilities available across all tests. - * This file is executed before each test via bunfig.toml preload. - */ -// Increase test timeout if needed (already configured in bunfig.toml) -// Bun.timeout = 30000; -// Store original console methods to allow restoration -const originalConsole = global.console; -// Mock console methods to reduce noise during tests -// These can be restored with testHelpers.restoreConsole() -console.log = () => { }; -console.debug = () => { }; -console.info = () => { }; -console.warn = () => { }; -console.error = () => { }; -global.testHelpers = { - /** - * Sleep utility for async tests - */ - sleep: (ms) => new Promise(resolve => setTimeout(resolve, ms)), - /** - * Consistent mock timestamp for tests - */ - mockTimestamp: () => new Date('2024-01-01T12:00:00Z'), - /** - * Generate test OHLCV data - */ - generateTestOHLCV: (symbol = 'AAPL', overrides = {}) => ({ - symbol, - open: 150.0, - high: 153.0, - low: 149.0, - close: 152.5, - volume: 10000, - timestamp: global.testHelpers.mockTimestamp(), - ...overrides - }), - /** - * Generate test trade data - */ - generateTestTrade: (symbol = 'AAPL', overrides = {}) => ({ - symbol, - price: 152.5, - size: 100, - timestamp: global.testHelpers.mockTimestamp(), - exchange: 'NASDAQ', - conditions: ['@', 'T'], - ...overrides - }), - /** - * Generate test quote data - */ - generateTestQuote: (symbol = 'AAPL', overrides = {}) => ({ - symbol, - bidPrice: 152.45, - bidSize: 200, - askPrice: 152.55, - askSize: 150, - timestamp: global.testHelpers.mockTimestamp(), - ...overrides - }), - /** - * Create a mock logger - */ - mockLogger: () => ({ - debug: () => { }, - info: () => { }, - warn: () => { }, - error: () => { }, - critical: () => { }, - }), - /** - * Restore console methods - */ - restoreConsole: () => { - global.console = originalConsole; - } -}; -// Set up spyOn utilities -// Similar to jest.spyOn but using Bun's built-in spy functionality -// This makes it easier to migrate from Jest -global.spyOn = function (object, method) { - const original = object[method]; - const mock = function (...args) { - mock.mock.calls.push(args); - return mock.mockImplementation ? mock.mockImplementation(...args) : original.apply(object, args); - }; - mock.mock = { calls: [] }; - mock.mockClear = () => { mock.mock.calls = []; return mock; }; - mock.mockReset = () => { - mock.mock.calls = []; - mock.mockImplementation = null; - return mock; - }; - mock.mockImplementation = null; - mock.mockReturnValue = (value) => { - mock.mockImplementation = () => value; - return mock; - }; - mock.mockResolvedValue = (value) => { - return mock.mockReturnValue(Promise.resolve(value)); - }; - mock.mockRejectedValue = (value) => { - return mock.mockReturnValue(Promise.reject(value)); - }; - object[method] = mock; - return mock; -}; -//# sourceMappingURL=setup.js.map \ No newline at end of file diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index f288789a..f49c5650 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -197,6 +197,54 @@ describe('MongoDBClient read-only enforcement', () => { ).rejects.toThrow(/aggregation stage "\$merge" is forbidden/); }); + test('wraps getDatabase/getCollection/collection in fail-closed read-only proxies', () => { + const fakeCollection = { + collectionName: 'qmSymbols', + find: () => ({ toArray: async () => [{ symbol: 'AAPL' }] }), + aggregate: () => ({ toArray: async () => [] }), + insertOne: async () => ({}), + updateOne: async () => ({}), + deleteOne: async () => ({}), + bulkWrite: async () => ({}), + drop: async () => true, + }; + const fakeDb = { + databaseName: 'stock', + collection: () => fakeCollection, + listCollections: () => ({ toArray: async () => [] }), + createCollection: async () => ({}), + dropCollection: async () => true, + dropDatabase: async () => true, + command: async () => ({}), + }; + const attached = new MongoDBClient( + { host: 'localhost', port: 27017, database: 'stock', readOnly: true }, + logger + ); + Object.assign(attached, { + client: { db: () => fakeDb }, + db: fakeDb, + isConnected: true, + }); + + // Safe read accessors succeed + expect(attached.getDatabase().databaseName).toBe('stock'); + expect(typeof attached.getDatabase().collection('qmSymbols').find).toBe('function'); + + // Escape-hatch mutations on getDatabase(), getDb(), database, getCollection(), collection() fail closed + expect(() => attached.getDatabase().createCollection('evil')).toThrow(/read-only mode/); + expect(() => attached.getDb().dropDatabase()).toThrow(/read-only mode/); + expect(() => attached.database!.command({ dropDatabase: 1 })).toThrow(/read-only mode/); + expect(() => attached.getCollection('qmSymbols').insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => attached.collection('qmSymbols').bulkWrite([])).toThrow(/read-only mode/); + expect(() => attached.getDatabase().collection('qmSymbols').deleteOne({})).toThrow( + /read-only mode/ + ); + expect(() => + attached.getCollection('qmSymbols').aggregate([{ $out: 'hijack' }]) + ).toThrow(/aggregation stage "\$out" is forbidden/); + }); + test('ServiceContainerBuilder resolves readUri and read-only mode when mongoReadOnly=true', async () => { const cfg = makeConfig({ environment: 'development' }); const { container, shutdown } = await new ServiceContainerBuilder() diff --git a/tetest.ts b/tetest.ts deleted file mode 100644 index 48d71832..00000000 --- a/tetest.ts +++ /dev/null @@ -1,35 +0,0 @@ -const pako = require('pako'); - - -const value = "a/lpZGluZ2VjbAM1pgcHtCCefSKpgAeH6QtP0aHicG8/E3R+LXZixUTbVGiIXr8M4eCCDCL834tYqtuIDcXYS1QZCKHHNMoXO8X+qlYyeas0uDlKeJPzqaonV4UIeZ6Xl0yU84SAbzuXJYyTBAebk1o1gV6dmouchDgdjAcMt75NiQFeGhMPW/D8zjdw1FvG6eUWq6YxKZIBlK7Z+v6MrfS+FltPy43ImpPt0t6CXdZW3ki9z+7+S475zI4ckhSan5yCtAo6jrrNkphC3JBpGtcZovpSkJkPA4yHn6LTm6bEyIm4shCc1JqYk/qFmwzerHDMhuKPPsYKtYcmzedlx5/6adh/bnyQn6Gc1BJddpUBmCPJkKPM9OJelArjhpVYaXXe+7Xkjc3V5XbKLlMVn9HQ5ggh3VWeyqoeTy2e1Ayw7WC00qoPjeHNjS69w5bYMYQvUIHD+t/WsdlavkBvPtjyEytQa/8vzVOblwjy2626ldpGWBzQotgGSx8pKwN3YlmDMcam2kJQ6wZoXwy/XsQE9SqmZQ1CJROVwYE2L/BvL06jWxT1w6LRKNwbH6IP0JMGqyqTXQjZ1TOZRrQOifUkTm5/9d++VCAzM2KsqH3b/os/yPk6Ubt5x6AJW7Ng4mQB3m+R+sc1fwfZfkLwHQEld1HLrmMiNoFgvBeL/y2AOAn7lLZ3zCBvL4MHChEcDZx7LppmG4wVu9inrH+dJqLgREyZF8ONRW89+Q4wf/qszwqMi5yDWyCZF/MT7LHRrLvSokxddwH+XrnuMXygH/5gH0WrJNQCYuSTSzAyRUbI+rwyETTkOXbGtE2r7AnHd/XfKyCTtSf9rJL9u9obwLVWW65+ocVG0z/K4jZUdWNRVAb3iqDy2pj5TwqHJxIyBVPfcX0L5fJqzj9nlyrNIr5zXr5gPhtHz//vsu/nCwqbHarK950T4hflFmFrJUPyaXwB/1eT7vlYB6YrUHV/wkvVzIQ2WSTqYy5OeEffhKyHTJWkaOuNCKKPovqrtjYCwIiElaGG99HeQP/tZ4yWfeIIuN8deiBlEa1OMRcgqhRxEXtY1mR3MDBAs8M1M7WRT0dGcnvJPlL5ihxZal2nY7qN4yb6/MNdFJ3xwk/5IEG8W4J4DqioZ7IJxFkOKLixxAQiyS3hOqD9NZh0KPg0OkUkPiMUul0mTRYnNgPf79grkM0w+BvUfaP1274L4e01tA+CmrfYSvkfHk8wNTvI+0XI+O8XFYMYX9ewa1L4yWHpVZj8HlD0/oNLp/JBHr7n+AMXAGZfvtPy6YXT4NrYBO1IAsRr0MJZThDd14VTzbkMh4pVwn467fGKLYLXOVgj8pia9YY54AE28YZ7ox5/G2Cy6vbnZYnJdUF0mBBvijkhzNchHVtzyw7BMehKMF5TAEN6ndcH5fW7KtV4IKyv/ZRvxOZcgKDBRx/LYbFri8uGs03sXvBC4CmOpGsHmtaBCvZ1G8fwxK/jHt+ZoxlNfsbaS9mxiRdVDdlFRmobRTzA5+W4c+1HLvlTNMRIW0auXQWGjSfYeFQfpICzWAiTKw1w0gcC7YLAvot+ivrinZFORkSyCvFtETc/gok/ajprIF97eoeEY+2yEqaeTOdo3G04wyOz27EOjvy8XUst4Na3d8j+e0LPTh93ZaCxjAYUdv5DwjkktyM8nQyyTmfiXTJlUUKWuvbedG9lNnn/9Oq5T+4cGSm9tfsMz8tK8VD/68FIiu2pq/o2h6yzV8RX0PgJu6q3Oub2143YgzQy7Xp+fCslI3BJ+kbEEWGgtxgV6WIAbeMHgJvyizjfZsk/CHzModCYWF3KnXzWDbwe8FL+rhC0GGuvZbleThSx9IYw0/MI5YQs3+1fAcUkkgN01F1/qxCkAF3q2fXq2Ctbm8Uim1OBOsMg3zi1sDXbdUMeTQs7MislQdMiX3VLVHqHGm61jynPf5X8OTLkFl6LGy2HHj8LYGg74bLcPIoyxONilLHWe48FtJMaJdqmCKK+v2WrhQ/uhvyIEf2Lrij/jd8JXjhg1Q4vugu/DXLCzETrFxJU+XbFyifAa0kQ/p1X0jfH/8f6vkO7zyfUE1d1N46iudYeSRpZNCLZlIZZY/EfVj4XAEM46M5E1xlyDLrWXvxf6ewF8oLMBarSDqzg2MbgH2q0SPIN1jfE2RYpJDzGlp1hZ8YTEESlpu+1ofbJqSnRfu6A3YtqXJ9aImkqpAo4WzVZoN/Ppn+DpsvMRO37kNmqPapC1+MBRP+cR0nYKPuNx92NrrgY4WBTGR0F4tnCC4bxEFimd0kJgTeksjRC0htizYQYNGLKrSYG3Nt9NFkrSBn6c+HYgAH3u86l2U1H+W7JmDW3h5kkt9L2n5Ml+OtSwit0uP95BGtgD/ZVWx13K9WkqF7l7SckA3kTtGN/n3AlPnzklR0JZpItGuB2S6Joe8oBWltEMRQjDS7Li688Lv0Q8fVHKvRt9ct2ZgibPmu4vbAWqhbv9tvVP2A5GZk9MIJEOG10owdhPcayBiK08DhLyLxY2/C7xKEj2XlHB/I13beb8u+oGT9umT1H29jN1qyKEAxRPapPT5TzEAATVi5kPPvWvxw5/x6Xg6koQ4WkN1gIWByOuX/hS+Y+jrfLE8Y5FOOeDguqigQXfgULWi44VcpF9DLFVMbT9uQlRr4Kal2GvDtFxb1PsdYQRN9KrRmCMQU+ZFFyP0CF1EEZ73hQ2KOXdT7rpLW8Q+z26dVbmyipAwXcxDxOFwSLEGJlCYgaB0/TQtj3b/aa9qjFM8iZH++pch7Jb8RY4TOfyviaOWsUJXAvwowQqB6lS5UQXj6wqKY9sq/D4iQdgqzXLjyaD7S3ZSMPWxE28qyP4o6Blrnhnv6UyvbFasIy/6/Dej3FNS6fFaU+6Lo3nuCjXczeASIDa5JqPQXqJcaW5ZcOrBIFizTkgHCQV+eBNllfufva7Gzaei51Hy98mCWwVxuNXuGql3EyTKF8f6vloesS6rjMGdsbUiZVWSWgwTCUTbzT9i+i+PK70gm+9nSJhRcyqOYC3nC9xuF6UImmGyUf4ocCSowW+s3GKzoV+HQ67mAf9iM5qq8NaH12SznH3CnZThUyOqBQ/wpRMF8sBK7gvAh3NVQ/UvXfOyPEh1QogRRARzT2C1X2wKc7yqVMKNOuJjy+wGi/1+1otom3BVCeqZwCmHSpXlTbrXEQzt0FSObtyDr2yGDADOrvyDL59/81hatpfxDcZlABQtXJc7NhtdiCXwRH4f3zJpGhkaTY1Dw6RrUY4TeePOCvBYa9aQegzaLZBYFUfFV8el+CpksZYtnwKSrYCgeBErXb/ILnmwj+gTmYaqWzeCSDy4gvjVan+K7Ndp06ziZFMuZ9uad9p0G1hk5p5WjQnCU2qV6V7HZooODkxwNRV+75SxOrhGK6hmz7fO9AXSh0DnudJLEI3Opcb3ABB1Uelbd5zwjt7qbS0Ko9wuYJbnLd4E8RJnbjcYddPgtLa6HSVnizFXGIbE8z+PKHNs6iq/XK1UBPhFswZ60bbPl56ucquQfmzqKxy0gepgNVPyypmsRS1mLed+K2g7NGUCRbMwilWmAwLF644S9hEcHQ1Y8MdSPcj+umluyEWGfeXrRVrRpkmzfAjckbzLc/EHJuBBMEsFmX2KZ7Q4o63Tk4vGrh1Jm7PIorHoW2LXKX24ahvI773rGwgC80WURYumc4voF1iYfKOamEwUgJQyHPvTvKUsAO37mF/Mi509CNlEU7FLtbTu8YTqzT2z6XWZcvVmFXVI2FO7dGxPKES3Rhe7C3n5m03JxuHaWyEN53326liRK8UZ0bX9Y8tQc8PDQBAGiSM9qmECOMzHaYSqEE3xfntRtMADQOxLfj6eDfcTABPTPkfPseQ1v/zBDZxvCmd91BOx+Asda6HHCGxkCC+j+7bzVk9yDkR89Zk8Z7D9yg4jJ54e3DSvZeTa5ta/gbpzaPGnkM158IqSBLKGB2HzWjUhe1VfSh0ruuFkbUulO0apI00iia2s8yCyVdf5tb8DHieW3HcXkWeWkEHq4TNdzb12cDRpou3UcUlPNU1aC+xf2F8pcID7WxyZADLOuqWD1/+9TFtvvOG8h5HyXOPDcEeUlp7jUNazvel6pAYbqbpzah24GftKNZ4cdy3TrWt31efsJtzARHKTDqFue1nT8f3gnU0aje3jTW9z++HH/pt3m4mMfDVnlt0lbtocIPQTOfuVG6nEQk7ltTtnOCwyeSMesX2Mjw2ilZoqW6ULWvyFfGpqOjAVD2Nqp9Cnb/W6hOQJ6su6+5uOUDi7+s1oEVtLVHfASfjVDawwzhcSbNkbXmRhSmkr7m0JiBFfqfo/d8GtLDILpWgAcJ0ivqPyL4Tf2ruPHRmE2PgeKf585jY24iXlrD/cIwrH6A/j4EKg5HtfqaGsXMpgVaPuv3mfiS1qGW0z2gtsF/0FHxGMSb6YwF6bGLyN60mR9qgGGgAbwH3NgtMA90D3sI0pb0JUAMjmff/uVpPPi7BqWaaBvLwceSstkZpc3ZKYzIWLPLlpGs77kX1X8kz9xPMhsh7ftlfses0Pygpw3AObDJRHqCQFO4tJxxor6IndwRhZ9VEtjDyoimu5aSoFqeR7H211K8LTMtn04lowOVmYaF2o2UipyeF8CTgpuAhYCAld8edIITGhoYCZHY/04draSRPbFMGlMbDowi9apWO4UOy/7JIJsz0A4amBMaS9KUgZBuCwwX3rOu+AOWzLJiF+eKKAcf+6VCnrLUgrEB8nfc71jstbqF0+T62ryfqsqGiILDlxeCCItNAzDZmYAfkZeRhmRcs+Cgu4KZ05YxkZ6RtuB2DmvUWbyLmo6f/9YXHtkYFBcSk3NITHF9d//MsCwChLSlwsBB7/YC3Bnvp0/OrVND6+6cGleczlReL0M8Br/swxT6DKGvPSWF7bYTlZNG0DIiUb1JZ2U=" -const URL = 'https://d3ii0wo49og5mi.cloudfront.net/economics/szlttr?span=max&v=20250619074600&key=20240229:nazare' - -const key = 'tradingeconomics-charts-core-api-key' - -const testFunc = function(e, k) { - console.log('testFunc called with:', e, k); - const a = atob(e) - , n = new Uint8Array(a.length); - console.log('Decoded base64 string:', a); - for (let e = 0; e < a.length; e++) - {n[e] = a.charCodeAt(e);} - const i = (new TextEncoder).encode(k); - console.log('Encoded key:', i); - for (let e = 0; e < n.length; e++) - {n[e] ^= i[e % i.length];} - console.log('XORed data:', n); - return pako.inflate(n, {to :'string'}); -} - -fetch(URL, { - proxy: 'http://5.79.66.2:13010', - headers: { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome' - } -}).then(async response => { - const resp = await response.text(); - const result = testFunc(resp.replaceAll('"', ""), key); - // console.log(result.toString()); - console.log(JSON.stringify(JSON.parse(result.toString()))); -}) - diff --git a/tools/coverage-cli/package.json b/tools/coverage-cli/package.json index 1bba9908..52e12aab 100644 --- a/tools/coverage-cli/package.json +++ b/tools/coverage-cli/package.json @@ -16,13 +16,11 @@ "commander": "^11.1.0", "glob": "^10.3.10", "handlebars": "^4.7.8", - "lcov-parse": "^1.0.0", "table": "^6.8.1", "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/glob": "^8.1.0", - "@types/lcov-parse": "^1.0.0", "@types/node": "^20.10.5", "bun-types": "^1.0.18" }, diff --git a/tsconfig.check.json b/tsconfig.check.json index 71225eda..d67c308a 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -8,11 +8,13 @@ "declarationMap": false, "allowImportingTsExtensions": true, "paths": { + "@stock-bot/di/http-security": ["libs/core/di/src/http/security.ts"], "@stock-bot/research/*": ["libs/research/src/*"], "@/*": ["apps/stock/web-app/src/*"], "@stock-bot/stock-config": ["apps/stock/config/src/index.ts"], "@stock-bot/stock-config/backtest": ["apps/stock/config/src/contracts/backtest.ts"], "@stock-bot/stock-config/strategy": ["apps/stock/config/src/contracts/strategy.ts"], + "@stock-bot/stock-config/strategy-names": ["apps/stock/config/src/contracts/strategy-names.ts"], "@stock-bot/engine": ["apps/stock/engine/index.d.ts"], "@stock-bot/*": [ "libs/core/*/src/index.ts", @@ -29,7 +31,6 @@ "apps/stock/**/src/**/*.ts", "apps/stock/**/src/**/*.tsx", "tools/**/src/**/*.ts", - "apps/stock/orchestrator/examples/multi-strategy-backtest.ts", "apps/stock/orchestrator/examples/canonical-regime-research.ts", "libs/core/services/test/contracts.type-test.ts" ], diff --git a/tsconfig.unused.json b/tsconfig.unused.json deleted file mode 100644 index db98298a..00000000 --- a/tsconfig.unused.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "./tsconfig.json", - "include": ["apps/**/*.ts", "apps/**/*.tsx", "libs/**/*.ts", "libs/**/*.tsx"], - "exclude": [ - "node_modules", - "dist", - "**/dist/**", - "**/node_modules/**", - "**/*.test.ts", - "**/*.spec.ts", - "**/test/**", - "**/tests/**" - ] -}