From 32e43c9243821b0d4be2487e84ddcb855ac5f913 Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 20 Oct 2026 14:35:45 -0400 Subject: [PATCH] commit 2 refactor --- .eslintignore | 81 - .prettierrc | 21 +- README.md | 39 +- .../config/src/schemas/stock-app.schema.ts | 3 + apps/stock/data-ingestion/package.json | 3 +- .../ceo/actions/get-channels.action.ts | 64 +- .../handlers/ceo/actions/get-posts.action.ts | 25 +- .../handlers/ceo/actions/get-shorts.action.ts | 6 +- .../actions/update-unique-symbols.action.ts | 2 +- .../src/handlers/ceo/ceo.handler.ts | 16 +- .../handlers/eod/actions/corporate-actions.ts | 482 +-- .../src/handlers/eod/actions/fundamentals.ts | 779 ++--- .../src/handlers/eod/actions/intraday.ts | 1172 +++---- .../src/handlers/eod/actions/prices.ts | 384 ++- .../src/handlers/eod/actions/symbols.ts | 315 +- .../src/handlers/eod/eod.handler.ts | 375 +-- .../handlers/eod/shared/operation-provider.ts | 245 +- .../src/handlers/eod/shared/price-storage.ts | 47 + .../fetch-exchanges-and-symbols.action.ts | 1 + .../ib/actions/fetch-session.action.ts | 7 +- .../ib/actions/fetch-symbols.action.ts | 6 +- .../src/handlers/ib/ib.handler.ts | 14 +- .../data-ingestion/src/handlers/index.ts | 68 +- .../src/handlers/qm/actions/events.action.ts | 104 +- .../src/handlers/qm/actions/filings.action.ts | 128 +- .../handlers/qm/actions/financials.action.ts | 180 +- .../handlers/qm/actions/insiders.action.ts | 563 ++-- .../qm/actions/intraday-crawl.action.ts | 848 ++--- .../src/handlers/qm/actions/news.action.ts | 879 +++--- .../src/handlers/qm/actions/prices.action.ts | 113 +- .../qm/actions/symbol-dedup.action.ts | 122 +- .../handlers/qm/actions/symbol-info.action.ts | 72 +- .../src/handlers/qm/actions/symbol.action.ts | 131 +- .../src/handlers/qm/qm.handler.ts | 56 +- .../handlers/qm/shared/operation-provider.ts | 51 +- .../qm/shared/session-manager-redis.ts | 35 +- .../qm/shared/session-manager-wrapper.ts | 10 +- .../src/handlers/qm/shared/types.ts | 33 +- .../te/actions/crawl-scheduler.action.ts | 38 +- .../handlers/te/actions/data-fetch.action.ts | 150 +- .../te/actions/fetch-countries.action.ts | 5 +- .../te/actions/fetch-indicators.action.ts | 41 +- .../te/actions/market-data-fetch.action.ts | 126 +- .../src/handlers/te/actions/spider.action.ts | 224 +- .../src/handlers/te/shared/types.ts | 158 +- .../src/handlers/te/te.handler.ts | 91 +- .../actions/fetch-exchanges.action.ts | 326 +- .../src/handlers/tradingview/shared/types.ts | 72 +- .../tradingview/tradingview.handler.ts | 58 +- .../src/handlers/tt/actions/import.action.ts | 54 +- .../src/handlers/tt/tt.handler.ts | 23 +- .../src/handlers/webshare/webshare.handler.ts | 6 +- apps/stock/data-ingestion/src/index.ts | 6 +- .../src/routes/create-routes.ts | 11 +- .../BaseOperationProvider.ts | 37 +- .../operation-manager/OperationRegistry.ts | 89 +- .../operation-manager/OperationTracker.ts | 331 +- .../src/shared/operation-manager/types.ts | 14 +- apps/stock/data-ingestion/src/types.ts | 22 +- .../test/test-advanced-rate-limit.ts | 199 +- .../data-ingestion/test/test-intraday-flow.ts | 319 +- .../test/test-modified-functions.ts | 278 +- .../data-ingestion/test/test-symbol-x.ts | 240 +- apps/stock/data-pipeline/package.json | 3 +- .../data-pipeline/src/container-setup.ts | 4 +- .../handlers/exchanges/exchanges.handler.ts | 16 +- .../clear-postgresql-data.operations.ts | 13 +- .../enhanced-sync-status.operations.ts | 6 +- .../operations/exchange-stats.operations.ts | 9 +- .../provider-mapping-stats.operations.ts | 6 +- .../operations/qm-exchanges.operations.ts | 16 +- .../sync-all-exchanges.operations.ts | 33 +- .../sync-ib-exchanges.operations.ts | 8 +- .../sync-qm-provider-mappings.operations.ts | 26 +- .../stock/data-pipeline/src/handlers/index.ts | 8 +- .../operations/qm-symbols.operations.ts | 34 +- .../operations/sync-status.operations.ts | 4 +- .../sync-symbols-from-provider.operations.ts | 44 +- .../src/handlers/symbols/symbols.handler.ts | 6 +- apps/stock/data-pipeline/src/index.ts | 5 +- .../data-pipeline/src/routes/create-routes.ts | 6 - .../data-pipeline/src/types/job-payloads.ts | 2 + apps/stock/engine/src/api/backtest.rs | 888 +++--- apps/stock/engine/src/indicators/macd.rs | 460 +-- .../examples/advanced-risk-management.ts | 550 ++-- .../examples/debug-position-tracking.ts | 206 +- .../examples/debug-rust-short-trades.ts | 259 +- .../orchestrator/examples/example-runtime.ts | 33 + .../examples/force-both-trade-types.ts | 299 +- .../orchestrator/examples/indicator-usage.ts | 455 +-- .../orchestrator/examples/show-order-flow.ts | 174 +- .../examples/simple-backtest-test.ts | 207 +- .../examples/sophisticated-backtest.ts | 585 ++-- .../examples/test-short-trades.ts | 187 +- .../examples/trace-short-positions.ts | 327 +- .../examples/verify-both-trade-types.ts | 248 +- apps/stock/orchestrator/package.json | 11 +- .../src/analytics/PerformanceAnalyzer.ts | 1356 ++++---- .../orchestrator/src/api/rest/analytics.ts | 394 +-- .../orchestrator/src/api/rest/backtest.ts | 523 ++-- .../stock/orchestrator/src/api/rest/orders.ts | 240 +- .../orchestrator/src/api/rest/positions.ts | 260 +- .../orchestrator/src/api/websocket/index.ts | 389 +-- .../src/backtest/BacktestEngine.ts | 2783 +++++++++-------- .../src/backtest/MarketSimulator.ts | 796 ++--- .../src/backtest/RustBacktestAdapter.ts | 392 +-- .../src/backtest/RustBacktestEngine.ts | 375 +-- .../src/backtest/native-result.ts | 89 + apps/stock/orchestrator/src/container.ts | 223 +- .../orchestrator/src/core/ModeManager.ts | 351 ++- .../orchestrator/src/data/DataManager.ts | 1005 +++--- .../src/handlers/backtest/backtest.handler.ts | 241 +- apps/stock/orchestrator/src/index.ts | 311 +- .../src/indicators/TechnicalAnalysis.ts | 647 ++-- .../src/paper/PaperTradingManager.ts | 758 ++--- .../orchestrator/src/routes/create-routes.ts | 101 +- .../src/services/AnalyticsService.ts | 442 +-- .../src/services/ExecutionService.ts | 645 ++-- .../src/services/MarketDataService.ts | 586 ++-- .../src/services/StorageService.ts | 875 +++--- .../orchestrator/src/simple-container.ts | 172 +- .../src/strategies/BaseStrategy.ts | 562 ++-- .../src/strategies/RustStrategy.ts | 269 +- .../src/strategies/StrategyExecutor.ts | 286 +- .../src/strategies/StrategyManager.ts | 593 ++-- .../AdvancedMultiIndicatorStrategy.ts | 1141 +++---- .../examples/IndicatorBasedStrategy.ts | 278 +- .../strategies/examples/MLEnhancedStrategy.ts | 888 +++--- .../examples/MeanReversionStrategy.ts | 401 +-- .../examples/SimpleMovingAverageCrossover.ts | 707 +++-- .../SimpleMovingAverageCrossoverFixed.ts | 626 ++-- .../SimpleMovingAverageCrossoverV2.ts | 641 ++-- .../strategies/indicators/IndicatorManager.ts | 652 ++-- .../strategies/position/PositionManager.ts | 594 ++-- .../src/strategies/risk/RiskManager.ts | 537 ++-- .../rust/SimpleMovingAverageCrossoverRust.ts | 275 +- .../src/strategies/signals/SignalManager.ts | 966 +++--- apps/stock/orchestrator/src/types.ts | 379 ++- .../orchestrator/tests/indicators.test.ts | 394 +-- apps/stock/orchestrator/tsconfig.json | 7 +- apps/stock/web-api/package.json | 3 +- apps/stock/web-api/src/container-setup.ts | 4 +- .../src/migrations/migration-runner.ts | 137 +- .../web-api/src/routes/backtests-v2.router.ts | 178 -- .../web-api/src/routes/backtests-v2.routes.ts | 393 +-- .../web-api/src/routes/monitoring.routes.ts | 7 +- .../web-api/src/routes/pipeline.routes.ts | 4 +- .../web-api/src/routes/websocket.routes.ts | 100 +- .../web-api/src/server-with-websocket.ts | 262 +- .../src/services/backtest-v2.service.ts | 1140 +++---- .../web-api/src/services/backtest.service.ts | 595 ++-- .../web-api/src/services/exchange.service.ts | 61 +- .../src/services/monitoring.service.ts | 341 +- .../web-api/src/services/pipeline.service.ts | 8 +- .../web-api/src/types/monitoring.types.ts | 5 +- apps/stock/web-api/src/utils/error-handler.ts | 4 +- apps/stock/web-api/src/utils/validation.ts | 9 +- .../web-api/src/websocket/run-updates.ts | 278 +- apps/stock/web-app/package.json | 3 +- .../web-app/src/components/ErrorBoundary.tsx | 105 +- .../web-app/src/components/charts/Chart.tsx | 849 ++--- .../backtest/BacktestDetailPageV2.tsx | 762 ++--- .../features/backtest/BacktestListPageV2.tsx | 294 +- .../backtest/components/BacktestChart.tsx | 408 +-- .../backtest/components/BacktestPlayback.tsx | 486 +-- .../backtest/components/BacktestTrades.tsx | 497 +-- .../backtest/components/ChartContainer.tsx | 86 +- .../components/CompactPerformanceMetrics.tsx | 647 ++-- .../components/CreateBacktestDialog.tsx | 456 +-- .../backtest/components/PositionsSummary.tsx | 291 +- .../backtest/components/RunControls.tsx | 397 ++- .../components/RunControlsCompact.tsx | 202 +- .../components/RunsListWithMetrics.tsx | 626 ++-- .../features/backtest/hooks/useBacktestV2.ts | 800 ++--- .../backtest/services/backtestApiV2.ts | 476 +-- .../features/backtest/types/backtest.types.ts | 192 +- .../web-app/src/features/charts/ChartPage.tsx | 578 ++-- .../charts/components/ChartOverlay.tsx | 290 +- .../charts/components/IndicatorSettings.tsx | 552 ++-- .../charts/components/SymbolChart.tsx | 931 +++--- .../src/features/charts/hooks/useChartData.ts | 295 +- .../charts/services/chartDataService.ts | 449 +-- .../src/features/charts/utils/indicators.ts | 616 ++-- .../components/AddProviderMappingDialog.tsx | 38 +- .../monitoring/hooks/useMonitoring.ts | 7 + .../src/features/monitoring/types/index.ts | 6 +- .../src/features/pipeline/PipelinePage.tsx | 319 +- .../src/features/symbols/SymbolsPage.tsx | 394 ++- .../symbols/components/SymbolsTable.tsx | 214 +- .../web-app/src/hooks/useChartManager.ts | 315 +- apps/stock/web-app/src/hooks/useWebSocket.ts | 395 +-- apps/stock/web-app/src/utils/browserLog.ts | 24 + .../web-app/src/utils/chartErrorHandler.ts | 98 +- bun.lock | 214 +- eslint.config.js | 22 + libs/core/cache/src/redis-cache.ts | 12 +- libs/core/cache/src/types.ts | 9 +- libs/core/config/package.json | 3 +- .../config/src/schemas/unified-app.schema.ts | 10 +- libs/core/config/src/utils/secrets.ts | 14 +- libs/core/config/src/utils/validation.ts | 13 +- libs/core/config/test/env.loader.test.ts | 2 +- libs/core/config/test/file.loader.test.ts | 2 +- libs/core/config/test/schemas.test.ts | 4 +- libs/core/config/test/utils.test.ts | 7 +- libs/core/config/tsconfig.json | 6 +- libs/core/di/package.json | 3 +- libs/core/di/src/container/builder.ts | 8 +- libs/core/di/src/index.ts | 5 +- libs/core/di/src/operation-context.ts | 10 +- .../registrations/database.registration.ts | 11 +- .../src/registrations/service.registration.ts | 19 +- libs/core/di/src/scanner/handler-scanner.ts | 63 +- libs/core/di/src/service-application.ts | 66 +- libs/core/di/src/types.ts | 12 +- libs/core/di/test/handler-scanner.test.ts | 2 +- libs/core/di/test/registration.test.ts | 2 +- libs/core/di/test/service-application.test.ts | 6 +- libs/core/di/test/types.test.ts | 2 +- libs/core/di/tsconfig.json | 19 +- libs/core/event-bus/package.json | 3 +- libs/core/event-bus/src/event-bus.ts | 13 +- libs/core/event-bus/src/simple-event-bus.ts | 11 +- libs/core/event-bus/src/types.ts | 4 +- libs/core/event-bus/tsconfig.json | 9 +- libs/core/handler-registry/src/types.ts | 16 +- .../test/registry-edge-cases.test.ts | 7 +- libs/core/handlers/src/base/BaseHandler.ts | 60 +- .../handlers/src/decorators/decorators.ts | 59 +- .../handlers/src/decorators/rate-limit.ts | 220 +- .../handlers/test/base-handler-config.test.ts | 6 +- .../handlers/test/base-handler-http.test.ts | 1 - libs/core/handlers/test/base-handler.test.ts | 13 +- .../handlers/test/create-job-handler.test.ts | 6 +- .../test/decorators-edge-cases.test.ts | 2 +- libs/core/handlers/test/handlers.test.ts | 5 +- libs/core/handlers/test/index.test.ts | 10 +- libs/core/invariants/package.json | 18 + libs/core/invariants/src/index.ts | 15 + libs/core/invariants/tsconfig.json | 5 + libs/core/logger/src/logger.ts | 27 +- libs/core/logger/src/types.ts | 6 +- libs/core/queue/package.json | 3 +- libs/core/queue/src/batch-processor.ts | 18 +- libs/core/queue/src/queue-manager.ts | 25 +- libs/core/queue/src/queue.ts | 83 +- libs/core/queue/src/rate-limiter.ts | 783 ++--- libs/core/queue/src/service-cache.ts | 19 +- libs/core/queue/src/types.ts | 16 +- libs/core/queue/test/batch-processor.test.ts | 5 +- libs/core/queue/test/queue-class.test.ts | 4 +- libs/core/queue/test/queue-manager.test.ts | 2 +- libs/core/queue/test/queue.test.ts | 2 +- libs/core/queue/tsconfig.json | 19 +- libs/core/services/src/index.ts | 15 +- libs/core/shutdown/src/shutdown.ts | 52 +- .../test/shutdown-comprehensive.test.ts | 117 +- .../shutdown/test/shutdown-signals.test.ts | 16 +- libs/core/types/src/decorators.ts | 54 +- libs/core/types/src/index.ts | 11 + libs/data/mongodb/src/client.ts | 122 +- libs/data/mongodb/test/mongodb.test.ts | 2 +- .../{src => test/support}/simple-mongodb.ts | 4 +- libs/data/postgres/package.json | 3 +- libs/data/postgres/src/client.ts | 33 +- libs/data/postgres/src/query-builder.ts | 28 +- libs/data/postgres/src/types.ts | 10 +- libs/data/postgres/test/postgres.test.ts | 4 +- .../{src => test/support}/simple-postgres.ts | 8 +- libs/data/postgres/tsconfig.json | 12 +- libs/data/questdb/package.json | 3 +- libs/data/questdb/src/client.ts | 34 +- libs/data/questdb/src/health.ts | 3 +- libs/data/questdb/src/query-builder.ts | 5 +- libs/data/questdb/src/schema.ts | 8 +- libs/data/questdb/src/types.ts | 6 +- libs/data/questdb/tsconfig.json | 12 +- libs/services/browser/src/browser.ts | 5 +- libs/services/browser/test/browser.test.ts | 2 +- .../{src => test/support}/simple-browser.ts | 2 +- libs/services/proxy/src/proxy-manager.ts | 7 +- libs/utils/package.json | 7 +- libs/utils/src/assertions.ts | 1 + libs/utils/src/calculations/index.ts | 4 +- .../src/calculations/technical-indicators.ts | 21 +- libs/utils/src/fetch.ts | 6 +- libs/utils/src/generic-functions.ts | 17 +- libs/utils/src/index.ts | 1 + libs/utils/src/user-agent.ts | 4 +- libs/utils/tsconfig.json | 19 +- package.json | 2 +- scripts/check.ts | 1 + scripts/test/backend-boundaries.test.ts | 46 + scripts/test/coverage-integrity.test.ts | 25 + scripts/test/native-bindings.test.ts | 25 +- scripts/test/orchestrator-container.test.ts | 12 + test/integration/ingestion-backtest.test.ts | 144 + tools/coverage-cli/package.json | 76 +- tools/coverage-cli/src/config.ts | 321 +- tools/coverage-cli/src/index.ts | 254 +- tools/coverage-cli/src/processor.ts | 600 ++-- .../src/reporters/html-compact.ts | 740 ++--- tools/coverage-cli/src/reporters/html.ts | 820 ++--- tools/coverage-cli/src/reporters/index.ts | 82 +- tools/coverage-cli/src/reporters/markdown.ts | 355 ++- tools/coverage-cli/src/reporters/terminal.ts | 376 +-- tools/coverage-cli/src/reporters/text.ts | 432 +-- tools/coverage-cli/src/runner.ts | 988 +++--- tools/coverage-cli/src/types.ts | 172 +- tools/coverage-cli/tsconfig.json | 24 +- 310 files changed, 33318 insertions(+), 31189 deletions(-) delete mode 100644 .eslintignore create mode 100644 apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts create mode 100644 apps/stock/orchestrator/examples/example-runtime.ts create mode 100644 apps/stock/orchestrator/src/backtest/native-result.ts delete mode 100644 apps/stock/web-api/src/routes/backtests-v2.router.ts create mode 100644 apps/stock/web-app/src/utils/browserLog.ts create mode 100644 libs/core/invariants/package.json create mode 100644 libs/core/invariants/src/index.ts create mode 100644 libs/core/invariants/tsconfig.json rename libs/data/mongodb/{src => test/support}/simple-mongodb.ts (96%) rename libs/data/postgres/{src => test/support}/simple-postgres.ts (95%) rename libs/services/browser/{src => test/support}/simple-browser.ts (98%) create mode 100644 libs/utils/src/assertions.ts create mode 100644 scripts/test/backend-boundaries.test.ts create mode 100644 scripts/test/coverage-integrity.test.ts create mode 100644 scripts/test/orchestrator-container.test.ts create mode 100644 test/integration/ingestion-backtest.test.ts diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index f3f3b157..00000000 --- a/.eslintignore +++ /dev/null @@ -1,81 +0,0 @@ -# Dependencies -node_modules/ -**/node_modules/ - -# Build outputs -dist/ -build/ -**/dist/ -**/build/ -.next/ -**/.next/ - -# Cache directories -.turbo/ -**/.turbo/ -.cache/ -**/.cache/ - -# Environment files -.env -.env.local -.env.production -.env.staging -**/.env* - -# Lock files -package-lock.json -yarn.lock -bun.lockb -pnpm-lock.yaml - -# Logs -*.log -logs/ -**/logs/ - -# Database files -*.db -*.sqlite -*.sqlite3 - -# Temporary files -*.tmp -*.temp -.DS_Store -Thumbs.db - -# Generated files -*.d.ts -**/*.d.ts - -# JavaScript files (we're focusing on TypeScript) -*.js -*.mjs -!.eslintrc.js -!eslint.config.js - -# Scripts and config directories -scripts/ -monitoring/ -database/ -docker-compose*.yml -Dockerfile* - -# Documentation -*.md -docs/ - -# Test coverage -coverage/ -**/coverage/ - -# IDE/Editor files -.vscode/ -.idea/ -*.swp -*.swo - -# Angular specific -**/.angular/ -**/src/polyfills.ts diff --git a/.prettierrc b/.prettierrc index 4073a4fc..9a6f6aee 100644 --- a/.prettierrc +++ b/.prettierrc @@ -10,7 +10,9 @@ "bracketSpacing": true, "bracketSameLine": false, "quoteProps": "as-needed", - "plugins": ["@ianvs/prettier-plugin-sort-imports"], + "plugins": [ + "@ianvs/prettier-plugin-sort-imports" + ], "importOrder": [ "^(node:.*|fs|path|crypto|url|os|util|events|stream|buffer|child_process|cluster|http|https|net|tls|dgram|dns|readline|repl|vm|zlib|querystring|punycode|assert|timers|constants)$", "", @@ -22,5 +24,20 @@ "^\\.(?!/?$)", "^\\./?$" ], - "importOrderParserPlugins": ["typescript", "decorators-legacy"] + "importOrderParserPlugins": [ + "typescript", + "decorators-legacy" + ], + "overrides": [ + { + "files": "**/*.tsx", + "options": { + "importOrderParserPlugins": [ + "typescript", + "jsx", + "decorators-legacy" + ] + } + } + ] } diff --git a/README.md b/README.md index 86010f7c..85d718f5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ the root workspace checks. ## Build and verify Use Bun 1.2.17, Node.js 18 or newer, and a Rust toolchain with a native linker. CI uses Rust -1.88. Building and the tooling/contract checks do not require running databases or provider +1.88. Building and the tooling/contract/integration checks do not require running databases or provider credentials. ```sh @@ -26,17 +26,19 @@ native engine. `bun run build --dry=json` shows the actual Turbo task plan. | `bun run typecheck` | Check library, stock application, and tool source directly | | `bun run test:contracts` | Compile positive and negative service-contract assertions | | `bun run test:tooling` | Run workspace and service-consumer regression tests without infrastructure | +| `bun run test:integration` | Replay fixed prices through ingestion, storage, and the real native backtest engine | | `bun run lint:check` | Lint stock applications, libraries, and tools with zero warnings allowed | -| `bun run check` | Run build, type checking, contract tests, tooling tests, and lint; report every failed gate | +| `bun run check` | Run build, type checking, contract tests, tooling/integration tests, and lint; report every failed gate | -`check` exits nonzero if any gate fails. Existing application type/lint errors are reported; -they are not suppressed or baselined. The larger existing `bun run test` suite is separate: +`check` exits nonzero if any gate fails. Type/lint errors are not suppressed or baselined. +The larger existing `bun run test` suite is separate: some tests need databases, Redis, browsers, or native-engine fixes. Native builds generate `apps/stock/engine/dist/engine.node` and `dist/index.d.ts`. The public ESM/CommonJS loaders and declaration facade use those generated artifacts. Rebuild after -changing Rust APIs. TensorFlow is an optional orchestrator peer dependency used by the ML -strategy; install it when using that strategy. +changing Rust APIs. TensorFlow is loaded only when starting the optional ML strategy. +Its TypeScript dependency is present for checking; using ML also requires installing its +platform-specific native binding. Dependency install scripts were not enabled for verification. ## Service contracts @@ -53,3 +55,28 @@ The DI and handler packages re-export `IServiceContainer` for existing consumers managers and individual queues are separate capabilities: obtain queues through `container.queueManager`, submit with `queue.add`, and await results with `queue.waitForJob`. Use `getFullQueueName(service, handler)` when addressing another service's queue. + +Use `requireServices(container, 'mongodb', 'queueManager')` at consumer boundaries when +those capabilities are required. Missing/disabled adapters fail explicitly before work begins. +`@stock-bot/invariants` provides small, dependency-free checks for required values and +indexed array reads; browser code can use it without importing server utilities. + +Handler initializers receive their scanner/registry explicitly through the DI application +initialization context. WebSocket connections and completion timers belong to the socket +handler and are released on close/shutdown. + +## Backtest data integrity + +Historical storage no longer invents prices when a database is unavailable. Configure a +historical store, or explicitly set `services.orchestrator.backtesting.allowSyntheticData` +for offline demos, with `syntheticSeed` for repeatability. Synthetic data is disabled by +default and must not be used to assess trading performance. MongoDB's normalized EOD +store currently supports daily bars only; intraday requests require QuestDB. + +The integration test uses an in-memory persistence transport and the real storage/native +engine path. It checks idempotent ingestion, invalid-price rejection, repeatable trades, +and explicit failures for missing data or unsupported strategies. No live provider or broker +is contacted. Native SMA and MACD regressions are covered by the repository checks. + +Coverage reports contain measured LCOV data only. Missing coverage or an empty package +selection fails the coverage command instead of producing an estimated score. diff --git a/apps/stock/config/src/schemas/stock-app.schema.ts b/apps/stock/config/src/schemas/stock-app.schema.ts index fb425b6f..a29f131f 100644 --- a/apps/stock/config/src/schemas/stock-app.schema.ts +++ b/apps/stock/config/src/schemas/stock-app.schema.ts @@ -91,6 +91,9 @@ export const stockAppSchema = baseAppSchema.extend({ backtesting: z .object({ maxConcurrent: z.number().default(5), + useRustEngine: z.boolean().default(true), + allowSyntheticData: z.boolean().default(false), + syntheticSeed: z.number().int().default(42), defaultSpeed: z.string().default('max'), dataResolutions: z.array(z.string()).default(['1m', '5m', '15m', '1h', '1d']), }) diff --git a/apps/stock/data-ingestion/package.json b/apps/stock/data-ingestion/package.json index 6396253b..f37ae3d6 100644 --- a/apps/stock/data-ingestion/package.json +++ b/apps/stock/data-ingestion/package.json @@ -29,7 +29,8 @@ "@stock-bot/proxy": "*", "hono": "^4.0.0", "pako": "^2.1.0", - "cheerio": "^1.0.0" + "cheerio": "^1.0.0", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "typescript": "^5.0.0" diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts index f506e025..20e3a340 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-channels.action.ts @@ -35,33 +35,40 @@ export async function getChannels(this: CeoHandler, payload: number | undefined) const channels = results.channel_categories[0].channels; const totalChannels = results.channel_categories[0].total_channels; const totalPages = Math.ceil(totalChannels / channels.length); - const exchanges: { exchange: string; countryCode: string }[] = []; - const symbols = channels.map((channel: any) => { - // check if exchange is in the exchanges array object - if (!exchanges.find((e: any) => e.exchange === channel.exchange)) { - exchanges.push({ + const exchanges: { exchange: string; countryCode: string; source: string }[] = []; + const symbols = channels.map( + (channel: { + exchange: string; + symbol: string; + title: string; + type: string; + channel: string; + company_details?: Record; + }) => { + // check if exchange is in the exchanges array object + if (!exchanges.find(e => e.exchange === channel.exchange)) { + exchanges.push({ source: 'ceo', exchange: channel.exchange, countryCode: 'CA' }); + } + const details = channel.company_details || {}; + return { + source: 'ceo', + symbol: channel.symbol, exchange: channel.exchange, - countryCode: 'CA', - }); + name: channel.title, + type: channel.type, + ceoId: channel.channel, + marketCap: details.market_cap, + volumeRatio: details.volume_ratio, + avgVolume: details.avg_volume, + stockType: details.stock_type, + issueType: details.issue_type, + sharesOutstanding: details.shares_outstanding, + float: details.float, + lastSeen: new Date(), + active: true, + }; } - const details = channel.company_details || {}; - return { - symbol: channel.symbol, - exchange: channel.exchange, - name: channel.title, - type: channel.type, - ceoId: channel.channel, - marketCap: details.market_cap, - volumeRatio: details.volume_ratio, - avgVolume: details.avg_volume, - stockType: details.stock_type, - issueType: details.issue_type, - sharesOutstanding: details.shares_outstanding, - float: details.float, - lastSeen: new Date(), - active: true, - }; - }); + ); await this.mongodb.batchUpsert('ceoSymbols', symbols, ['symbol', 'exchange']); await this.mongodb.batchUpsert('ceoExchanges', exchanges, ['exchange']); @@ -75,8 +82,11 @@ export async function getChannels(this: CeoHandler, payload: number | undefined) this.logger.info(`Fetched CEO channels for page ${page}/${totalPages}`); return { page, totalPages }; - } catch (error: any) { + } catch (error) { this.logger.error(`Error fetching CEO channels for page ${page} with proxy ${proxy}:`, error); - throw new Error(`Failed to fetch CEO channels: ${error.message}`); + throw new Error( + `Failed to fetch CEO channels: ${error instanceof Error ? error.message : String(error)}`, + { cause: error } + ); } } diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts index cb6c31b0..97cd432b 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-posts.action.ts @@ -1,7 +1,11 @@ import { getRandomUserAgent } from '@stock-bot/utils'; import type { CeoHandler } from '../ceo.handler'; -export async function getPosts(this: CeoHandler, payload: any, _context: any): Promise { +export async function getPosts( + this: CeoHandler, + payload: { ceoId: string; symbol: string; timestamp?: number; finished?: boolean }, + _context: unknown +): Promise { const { ceoId, symbol, timestamp, finished } = payload; const proxy = this.proxy?.getProxy(); if (!proxy) { @@ -31,7 +35,9 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P throw new Error(`Failed to fetch details for ceoId ${ceoId}: ${response.statusText}`); } - const data = await response.json(); + const data = (await response.json()) as { + spiels: Array & { timestamp: number }>; + }; const spielCount = data.spiels.length; if (spielCount === 0) { @@ -56,7 +62,8 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P // Extract timestamps clearly const oldestPostInBatch = data.spiels[0]?.timestamp; const newestPostInBatch = data.spiels[data.spiels.length - 1]?.timestamp; - const posts = data.spiels.map((spiel: any) => ({ + const posts = data.spiels.map(spiel => ({ + source: 'ceo', ceoId, spiel: spiel.spiel, spielReplyToId: spiel.spiel_reply_to_id, @@ -125,7 +132,7 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P symbolData?.newestPostTimestamp || symbolData?.lastSpielTime || 0; // Filter to only posts newer than what we've seen - const newPosts = posts.filter((p: any) => p.timestamp > lastKnownNewestTimestamp); + const newPosts = posts.filter(p => p.timestamp > lastKnownNewestTimestamp); if (newPosts.length === 0) { this.logger.info(`No new posts for ${ceoId}, all ${posts.length} posts already collected`); @@ -146,7 +153,11 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P // If all posts in batch were new, there might be more in the gap // Continue paginating until we hit posts we've already seen - if (newPosts.length === posts.length && oldestPostInBatch > lastKnownNewestTimestamp) { + if ( + newPosts.length === posts.length && + oldestPostInBatch !== undefined && + oldestPostInBatch > lastKnownNewestTimestamp + ) { this.logger.info(`All posts were new, checking for more in the gap`); await this.scheduleOperation( 'get-posts', @@ -171,12 +182,12 @@ export async function getPosts(this: CeoHandler, payload: any, _context: any): P this.logger.info(`Successfully processed channel ${ceoId}`); return { ceoId, spielCount, timestamp }; - } catch (error: any) { + } catch (error) { this.logger.error(`Failed to process individual symbol ${symbol}`, { error, ceoId, timestamp, }); - throw new Error(`Failed to process individual symbol ${symbol}`, error.message); + throw new Error(`Failed to process individual symbol ${symbol}`, { cause: error }); } } diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts index de9bfa2a..e626aa7a 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts @@ -1,7 +1,11 @@ import { getRandomUserAgent } from '@stock-bot/utils'; import type { CeoHandler } from '../ceo.handler'; -export async function getShorts(this: CeoHandler, payload: any, _context: any): Promise { +export async function getShorts( + this: CeoHandler, + payload: { ceoId: string; symbol: string; timestamp?: number }, + _context: unknown +): Promise { const { ceoId, symbol, timestamp } = payload; const proxy = this.proxy?.getProxy(); if (!proxy) { diff --git a/apps/stock/data-ingestion/src/handlers/ceo/actions/update-unique-symbols.action.ts b/apps/stock/data-ingestion/src/handlers/ceo/actions/update-unique-symbols.action.ts index 77eeb366..030fe424 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/actions/update-unique-symbols.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/actions/update-unique-symbols.action.ts @@ -2,7 +2,7 @@ import type { CeoHandler } from '../ceo.handler'; export async function updateUniqueSymbols( this: CeoHandler, - payload: any, + payload: { action?: string } | undefined, _context: unknown ): Promise { const action = payload?.action || 'get-posts'; // Default to get-posts if no action specified diff --git a/apps/stock/data-ingestion/src/handlers/ceo/ceo.handler.ts b/apps/stock/data-ingestion/src/handlers/ceo/ceo.handler.ts index 26ea79f2..2c2bf41f 100644 --- a/apps/stock/data-ingestion/src/handlers/ceo/ceo.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/ceo/ceo.handler.ts @@ -1,18 +1,14 @@ -import { - BaseHandler, - Disabled, - Handler, - Operation, - ScheduledOperation, -} from '@stock-bot/handlers'; -import { getChannels, getPosts, getShorts, updateUniqueSymbols } from './actions'; +import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import { resolveIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types'; +import { getChannels, getPosts, getShorts, updateUniqueSymbols } from './actions'; @Handler('ceo') @Disabled() export class CeoHandler extends BaseHandler { - constructor(services: any) { - super(services); // Handler name read from @Handler decorator + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'ceo')); // Handler name read from @Handler decorator } @ScheduledOperation('get-channels', '0 */15 * * *', { diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts index bd9741ae..89f1d6e2 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/corporate-actions.ts @@ -1,233 +1,249 @@ -import type { EodHandler } from '../eod.handler'; -import { EOD_CONFIG } from '../shared'; - -interface FetchCorporateActionsInput { - eodSearchCode: string; - actionType: 'dividends' | 'splits'; -} - -export async function scheduleFetchCorporateActions( - this: EodHandler -): Promise<{ success: boolean; jobsScheduled: number }> { - const logger = this.logger; - - try { - logger.info('Scheduling corporate actions fetch jobs'); - - // Get Canadian exchanges for now - const canadianExchanges = ['TO', 'V', 'CN', 'NEO']; - - // Use OperationTracker to find stale symbols for both dividends and splits - const allStaleDividends = await this.operationRegistry.getStaleSymbols('eod', 'dividends_update', { - limit: 50000 // Get all symbols needing update - }); - - const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', { - limit: 50000 // Get all symbols needing update - }); - - // Filter for Canadian exchanges and non-delisted symbols - const staleSymbolsDividends = allStaleDividends.filter(item => - canadianExchanges.includes(item.symbol.Exchange) && - item.symbol.delisted === false - ); // Remove the slice limit to process all symbols - - const staleSymbolsSplits = allStaleSplits.filter(item => - canadianExchanges.includes(item.symbol.Exchange) && - item.symbol.delisted === false - ); // Remove the slice limit to process all symbols - - if ((!staleSymbolsDividends || staleSymbolsDividends.length === 0) && - (!staleSymbolsSplits || staleSymbolsSplits.length === 0)) { - logger.info('No symbols need corporate actions update'); - return { success: true, jobsScheduled: 0 }; - } - - logger.info(`Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update`); - - let jobsScheduled = 0; - - // Schedule dividends jobs - for (let i = 0; i < staleSymbolsDividends.length; i++) { - const { symbol } = staleSymbolsDividends[i]; - - await this.scheduleOperation('fetch-corporate-actions', { - eodSearchCode: symbol.eodSearchCode, - actionType: 'dividends' - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 5000 - }, - delay: i * 200 // Stagger jobs by 200ms per symbol - }); - jobsScheduled++; - } - - // Schedule splits jobs - for (let i = 0; i < staleSymbolsSplits.length; i++) { - const { symbol } = staleSymbolsSplits[i]; - - await this.scheduleOperation('fetch-corporate-actions', { - eodSearchCode: symbol.eodSearchCode, - actionType: 'splits' - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 5000 - }, - delay: (i * 200) + 100 // Offset splits by 100ms from dividends - }); - jobsScheduled++; - } - - logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`); - - return { - success: true, - jobsScheduled - }; - } catch (error) { - logger.error('Failed to schedule corporate actions fetch jobs', { error }); - throw error; - } -} - -export async function fetchCorporateActions( - this: EodHandler, - input: FetchCorporateActionsInput -): Promise<{ success: boolean; recordsCount: number }> { - const logger = this.logger; - const { eodSearchCode, actionType } = input; - - // Declare variables for catch block - let symbol: string = ''; - let exchange: string = ''; - - try { - // Lookup symbol using eodSearchCode - const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ - eodSearchCode: eodSearchCode - }); - - if (!symbolDoc) { - logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); - throw new Error(`Symbol not found: ${eodSearchCode}`); - } - - symbol = symbolDoc.Code; - exchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const country = symbolDoc.Country; - - logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`); - - // Get API key - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - // Build URL based on action type - // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) - const endpoint = actionType === 'dividends' ? 'div' : 'splits'; - const url = new URL(`https://eodhd.com/api/${endpoint}/${eodSearchCode}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - - // Fetch data - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`); - } - - const data = await response.json(); - - // EOD returns an array of corporate actions - if (!Array.isArray(data)) { - throw new Error('Invalid response format from EOD API - expected array'); - } - - logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`); - - // Log sample records if any - if (data.length > 0) { - logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, { - count: data.length, - samples: data.slice(0, 3).map(record => ({ - date: record.date, - value: record.value || record.split || record.amount, - ...record - })) - }); - } - - if (data.length === 0) { - // Update symbol to indicate we checked but found no data - await this.mongodb.collection('eodSymbols').updateOne( - { eodSearchCode: eodSearchCode }, - { - $set: { - [`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(), - [`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false - } - } - ); - - return { success: true, recordsCount: 0 }; - } - - // Add metadata to each record - const recordsWithMetadata = data.map(record => ({ - symbol, - exchange, - eodSearchCode, - ...record, - actionType, - updatedAt: new Date(), - source: 'eod' - })); - - // Determine collection name based on action type - const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits'; - - // Save to MongoDB - use date and eodSearchCode as unique identifier - const result = await this.mongodb.batchUpsert( - collectionName, - recordsWithMetadata, - ['date', 'eodSearchCode'] - ); - - // Update operation tracker based on action type - const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; - await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { - status: 'success', - recordCount: result.insertedCount, - metadata: { - actionType: actionType, - exchange: exchange, - hasData: result.insertedCount > 0 - } - }); - - logger.info(`Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}`); - - return { - success: true, - recordsCount: result.insertedCount - }; - } catch (error) { - logger.error('Failed to fetch corporate actions', { error, symbol, exchange, actionType }); - - // Update operation tracker with failure - const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; - await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { - status: 'failure', - error: error instanceof Error ? error.message : String(error) - }); - - throw error; - } -} \ No newline at end of file +import { at } from '@stock-bot/utils'; +import type { EodHandler } from '../eod.handler'; +import { EOD_CONFIG } from '../shared'; + +interface FetchCorporateActionsInput { + eodSearchCode: string; + actionType: 'dividends' | 'splits'; +} + +export async function scheduleFetchCorporateActions( + this: EodHandler +): Promise<{ success: boolean; jobsScheduled: number }> { + const logger = this.logger; + + try { + logger.info('Scheduling corporate actions fetch jobs'); + + // Get Canadian exchanges for now + const canadianExchanges = ['TO', 'V', 'CN', 'NEO']; + + // Use OperationTracker to find stale symbols for both dividends and splits + const allStaleDividends = await this.operationRegistry.getStaleSymbols( + 'eod', + 'dividends_update', + { + limit: 50000, // Get all symbols needing update + } + ); + + const allStaleSplits = await this.operationRegistry.getStaleSymbols('eod', 'splits_update', { + limit: 50000, // Get all symbols needing update + }); + + // Filter for Canadian exchanges and non-delisted symbols + const staleSymbolsDividends = allStaleDividends.filter( + item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false + ); // Remove the slice limit to process all symbols + + const staleSymbolsSplits = allStaleSplits.filter( + item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false + ); // Remove the slice limit to process all symbols + + if ( + (!staleSymbolsDividends || staleSymbolsDividends.length === 0) && + (!staleSymbolsSplits || staleSymbolsSplits.length === 0) + ) { + logger.info('No symbols need corporate actions update'); + return { success: true, jobsScheduled: 0 }; + } + + logger.info( + `Found ${staleSymbolsDividends.length} symbols needing dividends update and ${staleSymbolsSplits.length} symbols needing splits update` + ); + + let jobsScheduled = 0; + + // Schedule dividends jobs + for (let i = 0; i < staleSymbolsDividends.length; i++) { + const { symbol } = at(staleSymbolsDividends, i); + + await this.scheduleOperation( + 'fetch-corporate-actions', + { + eodSearchCode: symbol.eodSearchCode, + actionType: 'dividends', + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000, + }, + delay: i * 200, // Stagger jobs by 200ms per symbol + } + ); + jobsScheduled++; + } + + // Schedule splits jobs + for (let i = 0; i < staleSymbolsSplits.length; i++) { + const { symbol } = at(staleSymbolsSplits, i); + + await this.scheduleOperation( + 'fetch-corporate-actions', + { + eodSearchCode: symbol.eodSearchCode, + actionType: 'splits', + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000, + }, + delay: i * 200 + 100, // Offset splits by 100ms from dividends + } + ); + jobsScheduled++; + } + + logger.info(`Successfully scheduled ${jobsScheduled} corporate actions fetch jobs`); + + return { + success: true, + jobsScheduled, + }; + } catch (error) { + logger.error('Failed to schedule corporate actions fetch jobs', { error }); + throw error; + } +} + +export async function fetchCorporateActions( + this: EodHandler, + input: FetchCorporateActionsInput +): Promise<{ success: boolean; recordsCount: number }> { + const logger = this.logger; + const { eodSearchCode, actionType } = input; + + // Declare variables for catch block + let symbol: string = ''; + let exchange: string = ''; + + try { + // Lookup symbol using eodSearchCode + const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ + eodSearchCode: eodSearchCode, + }); + + if (!symbolDoc) { + logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); + throw new Error(`Symbol not found: ${eodSearchCode}`); + } + + symbol = symbolDoc.Code; + exchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const _country = symbolDoc.Country; + + logger.info(`Fetching ${actionType} for ${symbol}.${exchange}`); + + // Get API key + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + // Build URL based on action type + // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) + const endpoint = actionType === 'dividends' ? 'div' : 'splits'; + const url = new URL(`https://eodhd.com/api/${endpoint}/${eodSearchCode}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + + // Fetch data + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error(`EOD ${actionType} API returned ${response.status}: ${response.statusText}`); + } + + const data = await response.json(); + + // EOD returns an array of corporate actions + if (!Array.isArray(data)) { + throw new Error('Invalid response format from EOD API - expected array'); + } + + logger.info(`Fetched ${data.length} ${actionType} records for ${symbol}.${exchange}`); + + // Log sample records if any + if (data.length > 0) { + logger.debug(`Sample ${actionType} for ${symbol}.${exchange}:`, { + count: data.length, + samples: data.slice(0, 3).map(record => ({ + date: record.date, + value: record.value || record.split || record.amount, + ...record, + })), + }); + } + + if (data.length === 0) { + // Update symbol to indicate we checked but found no data + await this.mongodb.collection('eodSymbols').updateOne( + { eodSearchCode: eodSearchCode }, + { + $set: { + [`last${actionType.charAt(0).toUpperCase() + actionType.slice(1)}Update`]: new Date(), + [`has${actionType.charAt(0).toUpperCase() + actionType.slice(1)}`]: false, + }, + } + ); + + return { success: true, recordsCount: 0 }; + } + + // Add metadata to each record + const recordsWithMetadata = data.map(record => ({ + symbol, + exchange, + eodSearchCode, + ...record, + actionType, + updatedAt: new Date(), + source: 'eod', + })); + + // Determine collection name based on action type + const collectionName = actionType === 'dividends' ? 'eodDividends' : 'eodSplits'; + + // Save to MongoDB - use date and eodSearchCode as unique identifier + const result = await this.mongodb.batchUpsert(collectionName, recordsWithMetadata, [ + 'date', + 'eodSearchCode', + ]); + + // Update operation tracker based on action type + const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; + await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { + status: 'success', + recordCount: result.insertedCount, + metadata: { + actionType: actionType, + exchange: exchange, + hasData: result.insertedCount > 0, + }, + }); + + logger.info( + `Successfully saved ${result.insertedCount} ${actionType} records for ${symbol}.${exchange}` + ); + + return { + success: true, + recordsCount: result.insertedCount, + }; + } catch (error) { + logger.error('Failed to fetch corporate actions', { error, symbol, exchange, actionType }); + + // Update operation tracker with failure + const operationName = actionType === 'dividends' ? 'dividends_update' : 'splits_update'; + await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, { + status: 'failure', + error: error instanceof Error ? error.message : String(error), + }); + + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts index f8b1ebb8..cf8b4827 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/fundamentals.ts @@ -1,376 +1,403 @@ -import type { EodHandler } from '../eod.handler'; -import { EOD_CONFIG } from '../shared'; -interface BulkFundamentalsInput { - eodSearchCodes: string[]; -} - -interface FetchSingleFundamentalsInput { - eodSearchCode: string; -} - -export async function scheduleFetchFundamentals( - this: EodHandler -): Promise<{ success: boolean; jobsScheduled: number }> { - const logger = this.logger; - - try { - logger.info('Scheduling fundamentals fetch jobs'); - - // Get Canadian exchanges for now - const canadianExchanges = ['TO', 'V', 'CN', 'NEO']; - - // Use OperationTracker to find stale symbols - const allStaleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'fundamentals_update', { - limit: 50000 // Get all symbols needing update - }); - - // Filter for Canadian exchanges and non-delisted symbols - const staleSymbols = allStaleSymbols.filter(item => - canadianExchanges.includes(item.symbol.Exchange) && - item.symbol.delisted === false - ); // Remove the slice limit to process all symbols - - if (!staleSymbols || staleSymbols.length === 0) { - logger.info('No symbols need fundamentals update'); - return { success: true, jobsScheduled: 0 }; - } - - logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`); - - // Separate ETFs from regular stocks - const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF'); - const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF'); - - logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, { - etfSamples: etfs.slice(0, 5).map(e => ({ - symbol: e.symbol.Code, - exchange: e.symbol.Exchange, - name: e.symbol.Name - })), - nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({ - symbol: s.symbol.Code, - exchange: s.symbol.Exchange, - name: s.symbol.Name, - type: s.symbol.Type - })) - }); - - let jobsScheduled = 0; - - // Schedule individual jobs for ETFs - for (let i = 0; i < etfs.length; i++) { - const { symbol: etf } = etfs[i]; - await this.scheduleOperation('fetch-single-fundamentals', { - eodSearchCode: etf.eodSearchCode - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 10000 - }, - delay: jobsScheduled * 1000 // Stagger by 1 second - }); - jobsScheduled++; - } - - if (etfs.length > 0) { - logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`); - } - - // Create batches of 500 symbols for non-ETFs - const batchSize = 500; // EOD allows up to 500 symbols per bulk request - - for (let i = 0; i < nonEtfs.length; i += batchSize) { - const batch = nonEtfs.slice(i, i + batchSize); - - // Convert to array of eodSearchCodes - const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode); - - await this.scheduleOperation('fetch-bulk-fundamentals', { - eodSearchCodes: eodSearchCodes - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 10000 - }, - delay: jobsScheduled * 5000 // Stagger batches by 5 seconds - }); - - jobsScheduled++; - logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`); - } - - logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`); - - return { - success: true, - jobsScheduled - }; - } catch (error) { - logger.error('Failed to schedule fundamentals fetch jobs', { error }); - throw error; - } -} - -export async function fetchBulkFundamentals( - this: EodHandler, - input: BulkFundamentalsInput -): Promise<{ success: boolean; symbolsProcessed: number }> { - const logger = this.logger; - const { eodSearchCodes } = input; - - try { - logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length }); - - // Lookup all symbols - const symbolDocs = await this.mongodb.collection('eodSymbols').find({ - eodSearchCode: { $in: eodSearchCodes } - }).toArray(); - - if (symbolDocs.length === 0) { - logger.error('No symbols found for provided eodSearchCodes'); - return { success: true, symbolsProcessed: 0 }; - } - - // Get API key - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - // Group symbols by actual exchange for API endpoint - // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) - const exchangeGroups = symbolDocs.reduce((acc, symbolDoc) => { - const exchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const eodSearchCode = symbolDoc.eodSearchCode; - - if (!acc[exchange]) { - acc[exchange] = []; - } - // eodSearchCode already has the correct format (e.g., AAPL.US) - acc[exchange].push(eodSearchCode); - return acc; - }, {} as Record); - - let totalProcessed = 0; - - // Process each exchange group - for (const [exchange, symbolList] of Object.entries(exchangeGroups)) { - // Build URL - using the exchange as the endpoint - const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - url.searchParams.append('symbols', symbolList.join(',')); - - logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, { - exchange, - count: symbolList.length, - samples: symbolList.slice(0, 5) - }); - - // Fetch data - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}`); - } - - const data = await response.json(); - - // EOD bulk fundamentals returns an object with symbol keys - if (typeof data !== 'object' || !data) { - throw new Error('Invalid response format from EOD API - expected object'); - } - - // Process each symbol's fundamentals - const fundamentalsToSave = []; - const symbolsToUpdate = []; - - for (const [symbolExchange, fundamentals] of Object.entries(data)) { - if (!fundamentals || typeof fundamentals !== 'object') { - logger.warn(`No fundamentals data for ${symbolExchange}`); - continue; - } - - // Extract symbol and exchange from the key - const [symbol, exchangeSuffix] = symbolExchange.split('.'); - - // Find the original symbol doc to get the actual exchange code - const symbolDoc = symbolDocs.find(doc => - doc.Code === symbol && - (doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix) - ); - - if (!symbolDoc) { - logger.warn(`Could not find symbol doc for ${symbolExchange}`); - continue; - } - - const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const eodSearchCode = symbolDoc.eodSearchCode; - - // Add metadata - const fundamentalsWithMetadata = { - symbol, - exchange: actualExchange, - eodSearchCode, - ...fundamentals, - updatedAt: new Date(), - source: 'eod' - }; - - fundamentalsToSave.push(fundamentalsWithMetadata); - symbolsToUpdate.push({ eodSearchCode }); - } - - if (fundamentalsToSave.length > 0) { - // Save fundamentals to MongoDB - const result = await this.mongodb.batchUpsert( - 'eodFundamentals', - fundamentalsToSave, - ['eodSearchCode'] - ); - - logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`); - - // Update operation tracker for each symbol - const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => { - return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { - status: 'success', - recordCount: 1, - metadata: { - hasData: true, - exchange: exchange - } - }); - }); - - await Promise.all(updatePromises); - totalProcessed += fundamentalsToSave.length; - } - } - - logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`); - - return { - success: true, - symbolsProcessed: totalProcessed - }; - } catch (error) { - logger.error('Failed to fetch bulk fundamentals', { error }); - - // Mark all symbols as failed - const failPromises = eodSearchCodes.map((eodSearchCode) => { - return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { - status: 'failure', - error: error.message - }); - }); - - await Promise.all(failPromises); - throw error; - } -} - -export async function fetchSingleFundamentals( - this: EodHandler, - input: FetchSingleFundamentalsInput -): Promise<{ success: boolean; saved: boolean }> { - const logger = this.logger; - const { eodSearchCode } = input; - - // Declare variables for catch block - let symbol: string = ''; - let exchange: string = ''; - - try { - // Lookup symbol using eodSearchCode - const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ - eodSearchCode: eodSearchCode - }); - - if (!symbolDoc) { - logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); - throw new Error(`Symbol not found: ${eodSearchCode}`); - } - - symbol = symbolDoc.Code; - exchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const country = symbolDoc.Country; - - logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`); - - // Get API key - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - // Build URL for single fundamentals endpoint - // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) - const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - - // Fetch data - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD Single Fundamentals API returned ${response.status}: ${response.statusText}`); - } - - const fundamentals = await response.json(); - - // Check if we got valid data - if (!fundamentals || typeof fundamentals !== 'object') { - logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`); - return { success: true, saved: false }; - } - - // Add metadata - const fundamentalsWithMetadata = { - symbol, - exchange, - eodSearchCode, - ...fundamentals, - updatedAt: new Date(), - source: 'eod' - }; - - // Save to MongoDB - const result = await this.mongodb.batchUpsert( - 'eodFundamentals', - [fundamentalsWithMetadata], - ['eodSearchCode'] - ); - - // Update operation tracker - await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { - status: 'success', - recordCount: result.insertedCount, - metadata: { - hasData: true, - exchange: exchange, - saved: result.insertedCount > 0 - } - }); - - logger.info(`Successfully saved fundamentals for ${symbol}.${exchange}`); - - return { - success: true, - saved: result.insertedCount > 0 - }; - } catch (error) { - logger.error('Failed to fetch single fundamentals', { error, symbol, exchange }); - - // Update operation tracker with failure - await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { - status: 'failure', - error: error.message - }); - - throw error; - } -} \ No newline at end of file +import { at } from '@stock-bot/utils'; +import type { EodHandler } from '../eod.handler'; +import { EOD_CONFIG } from '../shared'; + +interface BulkFundamentalsInput { + eodSearchCodes: string[]; +} + +interface FetchSingleFundamentalsInput { + eodSearchCode: string; +} + +export async function scheduleFetchFundamentals( + this: EodHandler +): Promise<{ success: boolean; jobsScheduled: number }> { + const logger = this.logger; + + try { + logger.info('Scheduling fundamentals fetch jobs'); + + // Get Canadian exchanges for now + const canadianExchanges = ['TO', 'V', 'CN', 'NEO']; + + // Use OperationTracker to find stale symbols + const allStaleSymbols = await this.operationRegistry.getStaleSymbols( + 'eod', + 'fundamentals_update', + { + limit: 50000, // Get all symbols needing update + } + ); + + // Filter for Canadian exchanges and non-delisted symbols + const staleSymbols = allStaleSymbols.filter( + item => canadianExchanges.includes(item.symbol.Exchange) && item.symbol.delisted === false + ); // Remove the slice limit to process all symbols + + if (!staleSymbols || staleSymbols.length === 0) { + logger.info('No symbols need fundamentals update'); + return { success: true, jobsScheduled: 0 }; + } + + logger.info(`Found ${staleSymbols.length} symbols needing fundamentals update`); + + // Separate ETFs from regular stocks + const etfs = staleSymbols.filter(s => s.symbol.Type === 'ETF'); + const nonEtfs = staleSymbols.filter(s => s.symbol.Type !== 'ETF'); + + logger.info(`Found ${etfs.length} ETFs and ${nonEtfs.length} non-ETFs`, { + etfSamples: etfs.slice(0, 5).map(e => ({ + symbol: e.symbol.Code, + exchange: e.symbol.Exchange, + name: e.symbol.Name, + })), + nonEtfSamples: nonEtfs.slice(0, 5).map(s => ({ + symbol: s.symbol.Code, + exchange: s.symbol.Exchange, + name: s.symbol.Name, + type: s.symbol.Type, + })), + }); + + let jobsScheduled = 0; + + // Schedule individual jobs for ETFs + for (let i = 0; i < etfs.length; i++) { + const { symbol: etf } = at(etfs, i); + await this.scheduleOperation( + 'fetch-single-fundamentals', + { + eodSearchCode: etf.eodSearchCode, + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 10000, + }, + delay: jobsScheduled * 1000, // Stagger by 1 second + } + ); + jobsScheduled++; + } + + if (etfs.length > 0) { + logger.info(`Scheduled ${etfs.length} individual ETF fundamentals jobs`); + } + + // Create batches of 500 symbols for non-ETFs + const batchSize = 500; // EOD allows up to 500 symbols per bulk request + + for (let i = 0; i < nonEtfs.length; i += batchSize) { + const batch = nonEtfs.slice(i, i + batchSize); + + // Convert to array of eodSearchCodes + const eodSearchCodes = batch.map(s => s.symbol.eodSearchCode); + + await this.scheduleOperation( + 'fetch-bulk-fundamentals', + { + eodSearchCodes: eodSearchCodes, + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 10000, + }, + delay: jobsScheduled * 5000, // Stagger batches by 5 seconds + } + ); + + jobsScheduled++; + logger.info(`Scheduled fundamentals batch with ${eodSearchCodes.length} non-ETF symbols`); + } + + logger.info(`Successfully scheduled ${jobsScheduled} fundamentals fetch jobs`); + + return { + success: true, + jobsScheduled, + }; + } catch (error) { + logger.error('Failed to schedule fundamentals fetch jobs', { error }); + throw error; + } +} + +export async function fetchBulkFundamentals( + this: EodHandler, + input: BulkFundamentalsInput +): Promise<{ success: boolean; symbolsProcessed: number }> { + const logger = this.logger; + const { eodSearchCodes } = input; + + try { + logger.info('Fetching bulk fundamentals', { symbolCount: eodSearchCodes.length }); + + // Lookup all symbols + const symbolDocs = await this.mongodb + .collection('eodSymbols') + .find({ + eodSearchCode: { $in: eodSearchCodes }, + }) + .toArray(); + + if (symbolDocs.length === 0) { + logger.error('No symbols found for provided eodSearchCodes'); + return { success: true, symbolsProcessed: 0 }; + } + + // Get API key + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + // Group symbols by actual exchange for API endpoint + // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) + const exchangeGroups = symbolDocs.reduce( + (acc, symbolDoc) => { + const exchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const eodSearchCode = symbolDoc.eodSearchCode; + + if (!acc[exchange]) { + acc[exchange] = []; + } + // eodSearchCode already has the correct format (e.g., AAPL.US) + acc[exchange].push(eodSearchCode); + return acc; + }, + {} as Record + ); + + let totalProcessed = 0; + + // Process each exchange group + for (const [exchange, symbolList] of Object.entries(exchangeGroups)) { + // Build URL - using the exchange as the endpoint + const url = new URL(`https://eodhd.com/api/bulk-fundamentals/${exchange}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + url.searchParams.append('symbols', symbolList.join(',')); + + logger.info(`Fetching bulk fundamentals for ${symbolList.length} ${exchange} symbols`, { + exchange, + count: symbolList.length, + samples: symbolList.slice(0, 5), + }); + + // Fetch data + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error( + `EOD Bulk Fundamentals API returned ${response.status}: ${response.statusText}` + ); + } + + const data = await response.json(); + + // EOD bulk fundamentals returns an object with symbol keys + if (typeof data !== 'object' || !data) { + throw new Error('Invalid response format from EOD API - expected object'); + } + + // Process each symbol's fundamentals + const fundamentalsToSave = []; + const symbolsToUpdate = []; + + for (const [symbolExchange, fundamentals] of Object.entries(data)) { + if (!fundamentals || typeof fundamentals !== 'object') { + logger.warn(`No fundamentals data for ${symbolExchange}`); + continue; + } + + // Extract symbol and exchange from the key + const [symbol, exchangeSuffix] = symbolExchange.split('.'); + + // Find the original symbol doc to get the actual exchange code + const symbolDoc = symbolDocs.find( + doc => + doc.Code === symbol && + (doc.eodExchange === exchangeSuffix || doc.Exchange === exchangeSuffix) + ); + + if (!symbolDoc) { + logger.warn(`Could not find symbol doc for ${symbolExchange}`); + continue; + } + + const actualExchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const eodSearchCode = symbolDoc.eodSearchCode; + + // Add metadata + const fundamentalsWithMetadata = { + symbol, + exchange: actualExchange, + eodSearchCode, + ...fundamentals, + updatedAt: new Date(), + source: 'eod', + }; + + fundamentalsToSave.push(fundamentalsWithMetadata); + symbolsToUpdate.push({ eodSearchCode }); + } + + if (fundamentalsToSave.length > 0) { + // Save fundamentals to MongoDB + const result = await this.mongodb.batchUpsert('eodFundamentals', fundamentalsToSave, [ + 'eodSearchCode', + ]); + + logger.info(`Saved ${result.insertedCount} fundamentals records for ${exchange}`); + + // Update operation tracker for each symbol + const updatePromises = symbolsToUpdate.map(({ eodSearchCode }) => { + return this.operationRegistry.updateOperation( + 'eod', + eodSearchCode, + 'fundamentals_update', + { + status: 'success', + recordCount: 1, + metadata: { + hasData: true, + exchange: exchange, + }, + } + ); + }); + + await Promise.all(updatePromises); + totalProcessed += fundamentalsToSave.length; + } + } + + logger.info(`Successfully processed fundamentals for ${totalProcessed} symbols`); + + return { + success: true, + symbolsProcessed: totalProcessed, + }; + } catch (error) { + logger.error('Failed to fetch bulk fundamentals', { error }); + + // Mark all symbols as failed + const failPromises = eodSearchCodes.map(eodSearchCode => { + return this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { + status: 'failure', + error: error instanceof Error ? error.message : String(error), + }); + }); + + await Promise.all(failPromises); + throw error; + } +} + +export async function fetchSingleFundamentals( + this: EodHandler, + input: FetchSingleFundamentalsInput +): Promise<{ success: boolean; saved: boolean }> { + const logger = this.logger; + const { eodSearchCode } = input; + + // Declare variables for catch block + let symbol: string = ''; + let exchange: string = ''; + + try { + // Lookup symbol using eodSearchCode + const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ + eodSearchCode: eodSearchCode, + }); + + if (!symbolDoc) { + logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); + throw new Error(`Symbol not found: ${eodSearchCode}`); + } + + symbol = symbolDoc.Code; + exchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const _country = symbolDoc.Country; + + logger.info(`Fetching single fundamentals for ${symbol}.${exchange}`); + + // Get API key + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + // Build URL for single fundamentals endpoint + // eodSearchCode already contains the symbol with exchange suffix (e.g., AAPL.US) + const url = new URL(`https://eodhd.com/api/fundamentals/${eodSearchCode}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + + // Fetch data + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error( + `EOD Single Fundamentals API returned ${response.status}: ${response.statusText}` + ); + } + + const fundamentals = await response.json(); + + // Check if we got valid data + if (!fundamentals || typeof fundamentals !== 'object') { + logger.warn(`No fundamentals data returned for ${symbol}.${exchange}`); + return { success: true, saved: false }; + } + + // Add metadata + const fundamentalsWithMetadata = { + symbol, + exchange, + eodSearchCode, + ...fundamentals, + updatedAt: new Date(), + source: 'eod', + }; + + // Save to MongoDB + const result = await this.mongodb.batchUpsert( + 'eodFundamentals', + [fundamentalsWithMetadata], + ['eodSearchCode'] + ); + + // Update operation tracker + await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { + status: 'success', + recordCount: result.insertedCount, + metadata: { + hasData: true, + exchange: exchange, + saved: result.insertedCount > 0, + }, + }); + + logger.info(`Successfully saved fundamentals for ${symbol}.${exchange}`); + + return { + success: true, + saved: result.insertedCount > 0, + }; + } catch (error) { + logger.error('Failed to fetch single fundamentals', { error, symbol, exchange }); + + // Update operation tracker with failure + await this.operationRegistry.updateOperation('eod', eodSearchCode, 'fundamentals_update', { + status: 'failure', + error: error instanceof Error ? error.message : String(error), + }); + + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts index c64c08f4..70ff19f6 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts @@ -1,569 +1,603 @@ - -import type { EodHandler } from '../eod.handler'; -import { EOD_CONFIG } from '../shared'; - -interface FetchIntradayInput { - eodSearchCode: string; - interval: '1m' | '5m' | '1h'; - fromDate?: Date; - toDate?: Date; -} - -interface CrawlIntradayInput { - eodSearchCode: string; - interval: '1m' | '5m' | '1h'; - fromDate?: Date; - toDate?: Date; - isInitial?: boolean; // To distinguish initial vs continuation jobs -} - -interface ScheduleIntradayConfig { - exchanges?: string[]; // Optional: limit to specific exchanges - symbolTypes?: string[]; // Optional: limit to specific symbol types (e.g., ['Common Stock']) - limit?: number; // Optional: limit total number of symbols to process -} - -// Max days per interval based on EOD limits -const MAX_DAYS_PER_INTERVAL = { - '1m': 120, - '5m': 600, - '1h': 7200 -}; - -// Default exchanges to process for intraday data -// const DEFAULT_INTRADAY_EXCHANGES = [],//['US', 'TO', 'V', 'CN', 'NEO', 'CC']; - -export async function scheduleIntradayCrawl( - this: EodHandler, - config?: ScheduleIntradayConfig -): Promise<{ success: boolean; jobsScheduled: number }> { - const logger = this.logger; - - try { - logger.info('Scheduling intraday crawl jobs', { - config: { - exchanges: config?.exchanges, //|| DEFAULT_INTRADAY_EXCHANGES, - symbolTypes: config?.symbolTypes || 'all', - limit: config?.limit || 'unlimited' - } - }); - - // Check if operation registry is initialized - if (!this.operationRegistry) { - logger.error('Operation registry not initialized!'); - return { success: false, jobsScheduled: 0 }; - } - - logger.debug('Operation registry status:', { - hasRegistry: !!this.operationRegistry, - hasProvider: this.operationRegistry.hasProvider ? this.operationRegistry.hasProvider('eod') : 'no hasProvider method' - }); - - // Use OperationTracker to find symbols needing intraday crawl - const intervals: Array<'1m' | '5m' | '1h'> = ['1m', '5m', '1h']; - const operationNames: string[] = ['intraday_1m', 'intraday_5m', 'intraday_1h']; - - const allSymbolsForCrawl: any[] = []; - - // Get symbols needing crawl for each interval - for (let i = 0; i < intervals.length; i++) { - const interval = intervals[i]; - const operationName = operationNames[i]!; // Non-null assertion since we know the array has 3 elements - - // Use getStaleSymbols to find symbols needing intraday updates - logger.debug(`Getting stale symbols for ${operationName}...`); - - // Get symbols with all filters applied at the database level - const targetExchanges = config?.exchanges //|| DEFAULT_INTRADAY_EXCHANGES; - const desiredLimit = config?.limit || 1000000; - - const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', operationName, { - limit: desiredLimit, - exchanges: targetExchanges, - }); - - logger.debug(`getStaleSymbols returned ${staleSymbols.length} symbols for ${operationName}`); - - // Process the returned symbols - for (const staleSymbol of staleSymbols) { - const { symbol, operations } = staleSymbol; - const operationStatus = operations?.[operationName]; - - // Apply symbol type filter if specified (this is the only filter not in the DB query) - if (config?.symbolTypes && !config.symbolTypes.includes(symbol.Type)) { - logger.debug(`Skipping ${symbol.Code} - type ${symbol.Type} not in filter`); - continue; - } - - // Include symbols that: - // 1. Have never been processed (!operationStatus) - // 2. Are not finished (!operationStatus.finished) - // 3. Are finished but need new data (newest date > 1 day old) - const needsNewData = operationStatus?.finished && operationStatus?.newestDateReached && - new Date(operationStatus.newestDateReached) < new Date(Date.now() - 30* 24 * 60 * 60 * 1000); - - if (!operationStatus || !operationStatus.finished || needsNewData) { - // Calculate initial date range for the job - const maxDays = MAX_DAYS_PER_INTERVAL[interval]; - let toDate = new Date(); - let fromDate = new Date(); - let isInitial = true; - - if (operationStatus?.lastProcessedDate) { - // Continue from where we left off - toDate = new Date(operationStatus.lastProcessedDate); - isInitial = false; - } - - // Calculate from date (going backwards) - fromDate = new Date(toDate); - fromDate.setDate(fromDate.getDate() - maxDays); - - allSymbolsForCrawl.push({ - symbol: symbol, - interval: interval, - operationName: operationName, - lastRun: staleSymbol.lastRun, - lastSuccess: staleSymbol.lastSuccess, - fromDate: fromDate, - toDate: toDate, - isInitial: isInitial - }); - - logger.debug(`Added ${symbol.Code}.${symbol.Exchange} for ${interval} crawl`, { - hasOperation: !!operationStatus, - finished: operationStatus?.finished, - needsNewData, - dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, - isInitial - }); - } - } - } - - if (!allSymbolsForCrawl || allSymbolsForCrawl.length === 0) { - logger.info('No symbols need intraday crawl'); - return { success: true, jobsScheduled: 0 }; - } - - logger.info(`Found ${allSymbolsForCrawl.length} symbol/interval combinations needing intraday data`, { - count: allSymbolsForCrawl.length, - byInterval: { - '1m': allSymbolsForCrawl.filter(s => s.interval === '1m').length, - '5m': allSymbolsForCrawl.filter(s => s.interval === '5m').length, - '1h': allSymbolsForCrawl.filter(s => s.interval === '1h').length - }, - symbols: allSymbolsForCrawl.map(s => ({ - symbol: s.symbol.Code, - exchange: s.symbol.Exchange, - name: s.symbol.Name, - eodSearchCode: s.symbol.eodSearchCode, - interval: s.interval, - dateRange: `${s.fromDate.toISOString().split('T')[0]} to ${s.toDate.toISOString().split('T')[0]}`, - isInitial: s.isInitial, - lastRun: s.lastRun ? new Date(s.lastRun).toISOString() : 'never', - lastSuccess: s.lastSuccess ? new Date(s.lastSuccess).toISOString() : 'never' - })) - }); - - let jobsScheduled = 0; - - // Schedule crawl jobs for each symbol/interval combination - for (const item of allSymbolsForCrawl) { - const { symbol, interval, fromDate, toDate, isInitial } = item; - - // Create jobId based on whether it's initial or continuation - const dateStr = isInitial ? 'initial' : `${fromDate.toISOString().split('T')[0]}-${toDate.toISOString().split('T')[0]}`; - const jobId = `crawl-intraday-${symbol.eodSearchCode}-${interval}-${dateStr}`; - - try { - await this.scheduleOperation('crawl-intraday', { - eodSearchCode: symbol.eodSearchCode, - interval, - fromDate, - toDate, - isInitial - }, { - jobId, - priority: isInitial ? 5 : 3, // Initial crawl jobs get lower priority - attempts: 3, - backoff: { - type: 'exponential', - delay: 10000 - }, - delay: jobsScheduled * 500 // Stagger jobs by 500ms - }); - jobsScheduled++; - - logger.debug(`Scheduled crawl job`, { - jobId, - symbol: symbol.Code, - exchange: symbol.Exchange, - interval, - dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, - isInitial - }); - } catch (error: any) { - if (error?.message?.includes('Job already exists')) { - logger.debug(`Job already exists: ${jobId}`); - } else { - throw error; - } - } - } - - logger.info(`Successfully scheduled ${jobsScheduled} intraday crawl jobs`); - - return { - success: true, - jobsScheduled - }; - } catch (error) { - logger.error('Failed to schedule intraday crawl jobs', { error }); - throw error; - } -} - -export async function crawlIntraday( - this: EodHandler, - input: CrawlIntradayInput -): Promise<{ success: boolean; recordsProcessed: number; finished: boolean }> { - const logger = this.logger; - const { eodSearchCode, interval, fromDate: providedFromDate, toDate: providedToDate, isInitial } = input; - - try { - // Lookup symbol using eodSearchCode - const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ - eodSearchCode: eodSearchCode - }); - - if (!symbolDoc) { - logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); - throw new Error(`Symbol not found: ${eodSearchCode}`); - } - - const symbol = symbolDoc.Code; - const exchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const country = symbolDoc.Country; - - logger.info(`Starting intraday crawl for ${symbol}.${exchange} - ${interval}`, { - symbol, - exchange, - interval, - country, - eodSearchCode - }); - - logger.debug('Found symbol document', { - symbol, - exchange, - hasOperations: !!symbolDoc.operations, - operationKeys: Object.keys(symbolDoc.operations || {}) - }); - - // Get operation status from tracker - const operationName = `intraday_${interval}`; - const operationStatus = symbolDoc.operations?.[operationName] || {}; - - logger.info(`Current crawl state for ${symbol}.${exchange} - ${interval}`, { - hasOperationStatus: !!symbolDoc.operations?.[operationName], - operationStatus: operationStatus, - lastProcessedDate: operationStatus.lastProcessedDate, - finished: operationStatus.finished - }); - - // Determine date range for this batch - const maxDays = MAX_DAYS_PER_INTERVAL[interval]; - let toDate: Date; - let fromDate: Date; - - // Use provided dates if available (from scheduled job) - if (providedFromDate && providedToDate) { - fromDate = new Date(providedFromDate); - toDate = new Date(providedToDate); - logger.info(`Using provided date range for ${symbol}.${exchange} - ${interval}`, { - fromDate: fromDate.toISOString(), - toDate: toDate.toISOString(), - isInitial - }); - } else { - // Fallback to original logic (for backward compatibility) - toDate = new Date(); - fromDate = new Date(); - - if (operationStatus.lastProcessedDate) { - // Continue from where we left off - the last processed date becomes the new toDate - toDate = new Date(operationStatus.lastProcessedDate); - } - - // Calculate from date (going backwards) - fromDate = new Date(toDate); - fromDate.setDate(fromDate.getDate() - maxDays); - - logger.info(`Calculated date range for ${symbol}.${exchange} - ${interval}`, { - fromDate: fromDate.toISOString(), - toDate: toDate.toISOString(), - basedOn: operationStatus.lastProcessedDate ? 'lastProcessedDate' : 'current date' - }); - } - - logger.info(`Fetching intraday batch for ${symbol}.${exchange} - ${interval} from ${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, { - symbol, - exchange, - interval, - fromDate: fromDate.toISOString(), - toDate: toDate.toISOString(), - maxDays, - operationStatus: { - lastProcessedDate: operationStatus.lastProcessedDate, - totalDaysProcessed: operationStatus.totalDaysProcessed || 0 - } - }); - - // Fetch data for this batch - const result = await fetchIntraday.call(this, { - eodSearchCode, - interval, - fromDate, - toDate - }); - - // Prepare update data - const updateData: any = { - status: 'partial', - recordCount: result.recordsSaved, - finished: false, - lastProcessedDate: fromDate, // Store the fromDate so next batch continues from here - totalDaysProcessed: (operationStatus.totalDaysProcessed || 0) + maxDays - }; - - // Set oldest date reached - if (!operationStatus.oldestDateReached || fromDate < operationStatus.oldestDateReached) { - updateData.oldestDateReached = fromDate; - } else { - updateData.oldestDateReached = operationStatus.oldestDateReached; - } - - // Set newest date reached - if (!operationStatus.newestDateReached || toDate > operationStatus.newestDateReached) { - updateData.newestDateReached = toDate; - } else { - updateData.newestDateReached = operationStatus.newestDateReached; - } - - // Check if we're finished - // Only mark as finished if: - // 1. We got no data from the API (empty response) - // 2. We've been crawling for a while and consistently getting no new records - if (result.recordsSaved === 0 && result.recordsFetched === 0) { - // No data returned from API - we've reached the end - updateData.finished = true; - updateData.status = 'success'; - logger.info(`Intraday crawl finished for ${symbol}.${exchange} - ${interval} (no more data available)`, { - symbol, - exchange, - interval, - oldestDate: updateData.oldestDateReached?.toISOString(), - newestDate: updateData.newestDateReached?.toISOString(), - totalDaysProcessed: updateData.totalDaysProcessed, - noDataReturned: true - }); - } else if (result.recordsSaved === 0 && result.recordsFetched > 0) { - // Data was fetched but all records already exist - continue crawling - logger.info(`All ${result.recordsFetched} records already exist for ${symbol}.${exchange} - ${interval}, continuing crawl`, { - symbol, - exchange, - interval, - fromDate: fromDate.toISOString(), - toDate: toDate.toISOString(), - recordsFetched: result.recordsFetched - }); - } - - // Update operation tracker - logger.info(`Updating operation tracker for ${symbol}.${exchange} - ${interval}`, { - status: updateData.status, - recordCount: result.recordsSaved, - lastProcessedDate: updateData.lastProcessedDate, - finished: updateData.finished - }); - - await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, updateData); - - logger.info(`Operation tracker updated for ${symbol}.${exchange} - ${interval}`); - - // If not finished, schedule next batch - if (!updateData.finished) { - // Calculate next batch date range - const nextToDate = fromDate; // Next batch's toDate is current batch's fromDate - const nextFromDate = new Date(nextToDate); - nextFromDate.setDate(nextFromDate.getDate() - maxDays); - - const dateStr = `${nextFromDate.toISOString().split('T')[0]}-${nextToDate.toISOString().split('T')[0]}`; - const jobId = `crawl-intraday-${eodSearchCode}-${interval}-${dateStr}`; - - await this.scheduleOperation('crawl-intraday', { - eodSearchCode, - interval, - fromDate: nextFromDate, - toDate: nextToDate, - isInitial: false - }, { - jobId, - priority: 3, // Continuation jobs get higher priority (3) than initial jobs (5) - attempts: 3, - backoff: { - type: 'exponential', - delay: 10000 - }, - delay: 5000 // Wait 5 seconds before next batch - }); - - logger.info(`Scheduled next intraday batch for ${symbol}.${exchange} - ${interval}`, { - symbol, - exchange, - interval, - jobId, - currentBatch: { - from: fromDate.toISOString().split('T')[0], - to: toDate.toISOString().split('T')[0], - recordsSaved: result.recordsSaved - }, - nextBatch: { - from: nextFromDate.toISOString().split('T')[0], - to: nextToDate.toISOString().split('T')[0] - }, - totalDaysProcessed: updateData.totalDaysProcessed - }); - } - - return { - success: true, - recordsProcessed: result.recordsSaved, - finished: updateData.finished - }; - } catch (error) { - logger.error('Failed to crawl intraday data', { error, eodSearchCode, interval }); - throw error; - } -} - -export async function fetchIntraday( - this: EodHandler, - input: FetchIntradayInput -): Promise<{ success: boolean; recordsSaved: number; recordsFetched: number }> { - const logger = this.logger; - const { eodSearchCode, interval, fromDate, toDate } = input; - - // Declare variables for catch block - let symbol: string = ''; - let exchange: string = ''; - - try { - // Lookup symbol using eodSearchCode - const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ - eodSearchCode: eodSearchCode - }); - - if (!symbolDoc) { - logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); - throw new Error(`Symbol not found: ${eodSearchCode}`); - } - - symbol = symbolDoc.Code; - exchange = symbolDoc.eodExchange || symbolDoc.Exchange; - const country = symbolDoc.Country; - - logger.info(`Fetching intraday data for ${symbol}.${exchange} - ${interval}`, { - symbol, - exchange, - interval, - from: fromDate?.toISOString().split('T')[0], - to: toDate?.toISOString().split('T')[0], - country, - url: `https://eodhd.com/api/intraday/${symbol}.${exchange}` - }); - - // Get API key - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - // Build URL - // Note: 'exchange' parameter here is already the eodExchange from scheduling - const url = new URL(`https://eodhd.com/api/intraday/${symbol}.${exchange}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - url.searchParams.append('interval', interval); - - // Add date range if provided - if (fromDate) { - url.searchParams.append('from', Math.floor(fromDate.getTime() / 1000).toString()); - } - if (toDate) { - url.searchParams.append('to', Math.floor(toDate.getTime() / 1000).toString()); - } - - // Fetch data - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD Intraday API returned ${response.status}: ${response.statusText}`); - } - - const data = await response.json(); - - // EOD returns an array of intraday bars - if (!Array.isArray(data)) { - throw new Error('Invalid response format from EOD API - expected array'); - } - - if (data.length === 0) { - logger.info('No intraday data returned', { symbol, exchange, interval }); - return { success: true, recordsSaved: 0, recordsFetched: 0 }; - } - - logger.info(`Fetched ${data.length} intraday records for ${symbol}.${exchange} - ${interval}`); - - // Add metadata to each record - const recordsWithMetadata = data.map(bar => ({ - symbol, - exchange, - eodSearchCode, - datetime: bar.datetime, - timestamp: bar.timestamp, - gmtoffset: bar.gmtoffset, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - source: 'eod' - })); - - // Save to MongoDB - use timestamp and eodSearchCode as unique identifier - const collectionName = `eodIntraday${interval.toUpperCase()}`; - const result = await this.mongodb.batchUpsert( - collectionName, - recordsWithMetadata, - ['timestamp', 'eodSearchCode'] - ); - - logger.info(`Saved ${result.insertedCount} intraday records`, { - symbol, - exchange, - interval, - collection: collectionName - }); - - return { - success: true, - recordsSaved: result.insertedCount, - recordsFetched: data.length - }; - } catch (error) { - logger.error('Failed to fetch intraday data', { error, symbol, exchange, interval }); - throw error; - } -} \ No newline at end of file +import type { Document } from 'mongodb'; +import { defined } from '@stock-bot/invariants'; +import type { OperationUpdate } from '../../../shared/operation-manager/types'; +import type { EodHandler } from '../eod.handler'; +import { EOD_CONFIG } from '../shared'; + +interface FetchIntradayInput { + eodSearchCode: string; + interval: '1m' | '5m' | '1h'; + fromDate?: Date; + toDate?: Date; +} + +interface CrawlIntradayInput { + eodSearchCode: string; + interval: '1m' | '5m' | '1h'; + fromDate?: Date; + toDate?: Date; + isInitial?: boolean; // To distinguish initial vs continuation jobs +} + +interface ScheduleIntradayConfig { + exchanges?: string[]; // Optional: limit to specific exchanges + symbolTypes?: string[]; // Optional: limit to specific symbol types (e.g., ['Common Stock']) + limit?: number; // Optional: limit total number of symbols to process +} + +// Max days per interval based on EOD limits +const MAX_DAYS_PER_INTERVAL = { + '1m': 120, + '5m': 600, + '1h': 7200, +}; + +// Default exchanges to process for intraday data +// const DEFAULT_INTRADAY_EXCHANGES = [],//['US', 'TO', 'V', 'CN', 'NEO', 'CC']; + +export async function scheduleIntradayCrawl( + this: EodHandler, + config?: ScheduleIntradayConfig +): Promise<{ success: boolean; jobsScheduled: number }> { + const logger = this.logger; + + try { + logger.info('Scheduling intraday crawl jobs', { + config: { + exchanges: config?.exchanges, //|| DEFAULT_INTRADAY_EXCHANGES, + symbolTypes: config?.symbolTypes || 'all', + limit: config?.limit || 'unlimited', + }, + }); + + // Check if operation registry is initialized + if (!this.operationRegistry) { + logger.error('Operation registry not initialized!'); + return { success: false, jobsScheduled: 0 }; + } + + logger.debug('Operation registry status:', { + hasRegistry: !!this.operationRegistry, + hasProvider: this.operationRegistry.hasProvider + ? this.operationRegistry.hasProvider('eod') + : 'no hasProvider method', + }); + + // Use OperationTracker to find symbols needing intraday crawl + const intervals: Array<'1m' | '5m' | '1h'> = ['1m', '5m', '1h']; + const operationNames: string[] = ['intraday_1m', 'intraday_5m', 'intraday_1h']; + + const allSymbolsForCrawl: Document[] = []; + + // Get symbols needing crawl for each interval + for (let i = 0; i < intervals.length; i++) { + const interval = intervals[i]; + const operationName = defined(operationNames[i]); // Non-null assertion since we know the array has 3 elements + + // Use getStaleSymbols to find symbols needing intraday updates + logger.debug(`Getting stale symbols for ${operationName}...`); + + // Get symbols with all filters applied at the database level + const targetExchanges = config?.exchanges; //|| DEFAULT_INTRADAY_EXCHANGES; + const desiredLimit = config?.limit || 1000000; + + const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', operationName, { + limit: desiredLimit, + exchanges: targetExchanges, + }); + + logger.debug(`getStaleSymbols returned ${staleSymbols.length} symbols for ${operationName}`); + + // Process the returned symbols + for (const staleSymbol of staleSymbols) { + const { symbol, operations } = staleSymbol; + const operationStatus = operations?.[operationName]; + + // Apply symbol type filter if specified (this is the only filter not in the DB query) + if (config?.symbolTypes && !config.symbolTypes.includes(symbol.Type)) { + logger.debug(`Skipping ${symbol.Code} - type ${symbol.Type} not in filter`); + continue; + } + + // Include symbols that: + // 1. Have never been processed (!operationStatus) + // 2. Are not finished (!operationStatus.finished) + // 3. Are finished but need new data (newest date > 1 day old) + const needsNewData = + operationStatus?.finished && + operationStatus?.newestDateReached && + new Date(operationStatus.newestDateReached) < + new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); + + if (!operationStatus || !operationStatus.finished || needsNewData) { + // Calculate initial date range for the job + const maxDays = MAX_DAYS_PER_INTERVAL[interval ?? '5m']; + let toDate = new Date(); + let fromDate = new Date(); + let isInitial = true; + + if (operationStatus?.lastProcessedDate) { + // Continue from where we left off + toDate = new Date(operationStatus.lastProcessedDate); + isInitial = false; + } + + // Calculate from date (going backwards) + fromDate = new Date(toDate); + fromDate.setDate(fromDate.getDate() - maxDays); + + allSymbolsForCrawl.push({ + symbol: symbol, + interval: interval, + operationName: operationName, + lastRun: staleSymbol.lastRun, + lastSuccess: staleSymbol.lastSuccess, + fromDate: fromDate, + toDate: toDate, + isInitial: isInitial, + }); + + logger.debug(`Added ${symbol.Code}.${symbol.Exchange} for ${interval} crawl`, { + hasOperation: !!operationStatus, + finished: operationStatus?.finished, + needsNewData, + dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, + isInitial, + }); + } + } + } + + if (!allSymbolsForCrawl || allSymbolsForCrawl.length === 0) { + logger.info('No symbols need intraday crawl'); + return { success: true, jobsScheduled: 0 }; + } + + logger.info( + `Found ${allSymbolsForCrawl.length} symbol/interval combinations needing intraday data`, + { + count: allSymbolsForCrawl.length, + byInterval: { + '1m': allSymbolsForCrawl.filter(s => s.interval === '1m').length, + '5m': allSymbolsForCrawl.filter(s => s.interval === '5m').length, + '1h': allSymbolsForCrawl.filter(s => s.interval === '1h').length, + }, + symbols: allSymbolsForCrawl.map(s => ({ + symbol: s.symbol.Code, + exchange: s.symbol.Exchange, + name: s.symbol.Name, + eodSearchCode: s.symbol.eodSearchCode, + interval: s.interval, + dateRange: `${s.fromDate.toISOString().split('T')[0]} to ${s.toDate.toISOString().split('T')[0]}`, + isInitial: s.isInitial, + lastRun: s.lastRun ? new Date(s.lastRun).toISOString() : 'never', + lastSuccess: s.lastSuccess ? new Date(s.lastSuccess).toISOString() : 'never', + })), + } + ); + + let jobsScheduled = 0; + + // Schedule crawl jobs for each symbol/interval combination + for (const item of allSymbolsForCrawl) { + const { symbol, interval, fromDate, toDate, isInitial } = item; + + // Create jobId based on whether it's initial or continuation + const dateStr = isInitial + ? 'initial' + : `${fromDate.toISOString().split('T')[0]}-${toDate.toISOString().split('T')[0]}`; + const jobId = `crawl-intraday-${symbol.eodSearchCode}-${interval}-${dateStr}`; + + try { + await this.scheduleOperation( + 'crawl-intraday', + { + eodSearchCode: symbol.eodSearchCode, + interval, + fromDate, + toDate, + isInitial, + }, + { + jobId, + priority: isInitial ? 5 : 3, // Initial crawl jobs get lower priority + attempts: 3, + backoff: { + type: 'exponential', + delay: 10000, + }, + delay: jobsScheduled * 500, // Stagger jobs by 500ms + } + ); + jobsScheduled++; + + logger.debug(`Scheduled crawl job`, { + jobId, + symbol: symbol.Code, + exchange: symbol.Exchange, + interval, + dateRange: `${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, + isInitial, + }); + } catch (error) { + if (error instanceof Error && error.message.includes('Job already exists')) { + logger.debug(`Job already exists: ${jobId}`); + } else { + throw error; + } + } + } + + logger.info(`Successfully scheduled ${jobsScheduled} intraday crawl jobs`); + + return { + success: true, + jobsScheduled, + }; + } catch (error) { + logger.error('Failed to schedule intraday crawl jobs', { error }); + throw error; + } +} + +export async function crawlIntraday( + this: EodHandler, + input: CrawlIntradayInput +): Promise<{ success: boolean; recordsProcessed: number; finished: boolean }> { + const logger = this.logger; + const { + eodSearchCode, + interval, + fromDate: providedFromDate, + toDate: providedToDate, + isInitial, + } = input; + + try { + // Lookup symbol using eodSearchCode + const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ + eodSearchCode: eodSearchCode, + }); + + if (!symbolDoc) { + logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); + throw new Error(`Symbol not found: ${eodSearchCode}`); + } + + const symbol = symbolDoc.Code; + const exchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const country = symbolDoc.Country; + + logger.info(`Starting intraday crawl for ${symbol}.${exchange} - ${interval}`, { + symbol, + exchange, + interval, + country, + eodSearchCode, + }); + + logger.debug('Found symbol document', { + symbol, + exchange, + hasOperations: !!symbolDoc.operations, + operationKeys: Object.keys(symbolDoc.operations || {}), + }); + + // Get operation status from tracker + const operationName = `intraday_${interval}`; + const operationStatus = symbolDoc.operations?.[operationName] || {}; + + logger.info(`Current crawl state for ${symbol}.${exchange} - ${interval}`, { + hasOperationStatus: !!symbolDoc.operations?.[operationName], + operationStatus: operationStatus, + lastProcessedDate: operationStatus.lastProcessedDate, + finished: operationStatus.finished, + }); + + // Determine date range for this batch + const maxDays = MAX_DAYS_PER_INTERVAL[interval]; + let toDate: Date; + let fromDate: Date; + + // Use provided dates if available (from scheduled job) + if (providedFromDate && providedToDate) { + fromDate = new Date(providedFromDate); + toDate = new Date(providedToDate); + logger.info(`Using provided date range for ${symbol}.${exchange} - ${interval}`, { + fromDate: fromDate.toISOString(), + toDate: toDate.toISOString(), + isInitial, + }); + } else { + // Fallback to original logic (for backward compatibility) + toDate = new Date(); + fromDate = new Date(); + + if (operationStatus.lastProcessedDate) { + // Continue from where we left off - the last processed date becomes the new toDate + toDate = new Date(operationStatus.lastProcessedDate); + } + + // Calculate from date (going backwards) + fromDate = new Date(toDate); + fromDate.setDate(fromDate.getDate() - maxDays); + + logger.info(`Calculated date range for ${symbol}.${exchange} - ${interval}`, { + fromDate: fromDate.toISOString(), + toDate: toDate.toISOString(), + basedOn: operationStatus.lastProcessedDate ? 'lastProcessedDate' : 'current date', + }); + } + + logger.info( + `Fetching intraday batch for ${symbol}.${exchange} - ${interval} from ${fromDate.toISOString().split('T')[0]} to ${toDate.toISOString().split('T')[0]}`, + { + symbol, + exchange, + interval, + fromDate: fromDate.toISOString(), + toDate: toDate.toISOString(), + maxDays, + operationStatus: { + lastProcessedDate: operationStatus.lastProcessedDate, + totalDaysProcessed: operationStatus.totalDaysProcessed || 0, + }, + } + ); + + // Fetch data for this batch + const result = await fetchIntraday.call(this, { + eodSearchCode, + interval, + fromDate, + toDate, + }); + + // Prepare update data + const updateData: OperationUpdate = { + status: 'partial', + recordCount: result.recordsSaved, + finished: false, + lastProcessedDate: fromDate, // Store the fromDate so next batch continues from here + totalDaysProcessed: (operationStatus.totalDaysProcessed || 0) + maxDays, + }; + + // Set oldest date reached + if (!operationStatus.oldestDateReached || fromDate < operationStatus.oldestDateReached) { + updateData.oldestDateReached = fromDate; + } else { + updateData.oldestDateReached = operationStatus.oldestDateReached; + } + + // Set newest date reached + if (!operationStatus.newestDateReached || toDate > operationStatus.newestDateReached) { + updateData.newestDateReached = toDate; + } else { + updateData.newestDateReached = operationStatus.newestDateReached; + } + + // Check if we're finished + // Only mark as finished if: + // 1. We got no data from the API (empty response) + // 2. We've been crawling for a while and consistently getting no new records + if (result.recordsSaved === 0 && result.recordsFetched === 0) { + // No data returned from API - we've reached the end + updateData.finished = true; + updateData.status = 'success'; + logger.info( + `Intraday crawl finished for ${symbol}.${exchange} - ${interval} (no more data available)`, + { + symbol, + exchange, + interval, + oldestDate: updateData.oldestDateReached?.toISOString(), + newestDate: updateData.newestDateReached?.toISOString(), + totalDaysProcessed: updateData.totalDaysProcessed, + noDataReturned: true, + } + ); + } else if (result.recordsSaved === 0 && result.recordsFetched > 0) { + // Data was fetched but all records already exist - continue crawling + logger.info( + `All ${result.recordsFetched} records already exist for ${symbol}.${exchange} - ${interval}, continuing crawl`, + { + symbol, + exchange, + interval, + fromDate: fromDate.toISOString(), + toDate: toDate.toISOString(), + recordsFetched: result.recordsFetched, + } + ); + } + + // Update operation tracker + logger.info(`Updating operation tracker for ${symbol}.${exchange} - ${interval}`, { + status: updateData.status, + recordCount: result.recordsSaved, + lastProcessedDate: updateData.lastProcessedDate, + finished: updateData.finished ?? false, + }); + + await this.operationRegistry.updateOperation('eod', eodSearchCode, operationName, updateData); + + logger.info(`Operation tracker updated for ${symbol}.${exchange} - ${interval}`); + + // If not finished, schedule next batch + if (!updateData.finished) { + // Calculate next batch date range + const nextToDate = fromDate; // Next batch's toDate is current batch's fromDate + const nextFromDate = new Date(nextToDate); + nextFromDate.setDate(nextFromDate.getDate() - maxDays); + + const dateStr = `${nextFromDate.toISOString().split('T')[0]}-${nextToDate.toISOString().split('T')[0]}`; + const jobId = `crawl-intraday-${eodSearchCode}-${interval}-${dateStr}`; + + await this.scheduleOperation( + 'crawl-intraday', + { + eodSearchCode, + interval, + fromDate: nextFromDate, + toDate: nextToDate, + isInitial: false, + }, + { + jobId, + priority: 3, // Continuation jobs get higher priority (3) than initial jobs (5) + attempts: 3, + backoff: { + type: 'exponential', + delay: 10000, + }, + delay: 5000, // Wait 5 seconds before next batch + } + ); + + logger.info(`Scheduled next intraday batch for ${symbol}.${exchange} - ${interval}`, { + symbol, + exchange, + interval, + jobId, + currentBatch: { + from: fromDate.toISOString().split('T')[0], + to: toDate.toISOString().split('T')[0], + recordsSaved: result.recordsSaved, + }, + nextBatch: { + from: nextFromDate.toISOString().split('T')[0], + to: nextToDate.toISOString().split('T')[0], + }, + totalDaysProcessed: updateData.totalDaysProcessed, + }); + } + + return { + success: true, + recordsProcessed: result.recordsSaved, + finished: updateData.finished ?? false, + }; + } catch (error) { + logger.error('Failed to crawl intraday data', { error, eodSearchCode, interval }); + throw error; + } +} + +export async function fetchIntraday( + this: EodHandler, + input: FetchIntradayInput +): Promise<{ success: boolean; recordsSaved: number; recordsFetched: number }> { + const logger = this.logger; + const { eodSearchCode, interval, fromDate, toDate } = input; + + // Declare variables for catch block + let symbol: string = ''; + let exchange: string = ''; + + try { + // Lookup symbol using eodSearchCode + const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ + eodSearchCode: eodSearchCode, + }); + + if (!symbolDoc) { + logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); + throw new Error(`Symbol not found: ${eodSearchCode}`); + } + + symbol = symbolDoc.Code; + exchange = symbolDoc.eodExchange || symbolDoc.Exchange; + const country = symbolDoc.Country; + + logger.info(`Fetching intraday data for ${symbol}.${exchange} - ${interval}`, { + symbol, + exchange, + interval, + from: fromDate?.toISOString().split('T')[0], + to: toDate?.toISOString().split('T')[0], + country, + url: `https://eodhd.com/api/intraday/${symbol}.${exchange}`, + }); + + // Get API key + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + // Build URL + // Note: 'exchange' parameter here is already the eodExchange from scheduling + const url = new URL(`https://eodhd.com/api/intraday/${symbol}.${exchange}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + url.searchParams.append('interval', interval); + + // Add date range if provided + if (fromDate) { + url.searchParams.append('from', Math.floor(fromDate.getTime() / 1000).toString()); + } + if (toDate) { + url.searchParams.append('to', Math.floor(toDate.getTime() / 1000).toString()); + } + + // Fetch data + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error(`EOD Intraday API returned ${response.status}: ${response.statusText}`); + } + + const data = await response.json(); + + // EOD returns an array of intraday bars + if (!Array.isArray(data)) { + throw new Error('Invalid response format from EOD API - expected array'); + } + + if (data.length === 0) { + logger.info('No intraday data returned', { symbol, exchange, interval }); + return { success: true, recordsSaved: 0, recordsFetched: 0 }; + } + + logger.info(`Fetched ${data.length} intraday records for ${symbol}.${exchange} - ${interval}`); + + // Add metadata to each record + const recordsWithMetadata = data.map(bar => ({ + symbol, + exchange, + eodSearchCode, + datetime: bar.datetime, + timestamp: bar.timestamp, + gmtoffset: bar.gmtoffset, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + source: 'eod', + })); + + // Save to MongoDB - use timestamp and eodSearchCode as unique identifier + const collectionName = `eodIntraday${interval.toUpperCase()}`; + const result = await this.mongodb.batchUpsert(collectionName, recordsWithMetadata, [ + 'timestamp', + 'eodSearchCode', + ]); + + logger.info(`Saved ${result.insertedCount} intraday records`, { + symbol, + exchange, + interval, + collection: collectionName, + }); + + return { + success: true, + recordsSaved: result.insertedCount, + recordsFetched: data.length, + }; + } catch (error) { + logger.error('Failed to fetch intraday data', { error, symbol, exchange, interval }); + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts index 648aceec..7b043bad 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/prices.ts @@ -1,197 +1,187 @@ -import type { EodHandler } from '../eod.handler'; -import { EOD_CONFIG } from '../shared'; - -interface FetchPricesInput { - eodSearchCode: string; -} - -export async function scheduleFetchPrices( - this: EodHandler -): Promise<{ success: boolean; jobsScheduled: number }> { - const logger = this.logger; - - try { - logger.info('Scheduling price fetch jobs for all symbols'); - - // Use OperationTracker to find stale symbols - const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'price_update', { - limit: 100000 // Higher limit to process all symbols - }); - - if (!staleSymbols || staleSymbols.length === 0) { - logger.info('No symbols need price updates'); - return { success: true, jobsScheduled: 0 }; - } - - logger.info(`Found ${staleSymbols.length} symbols needing price updates`, { - symbols: staleSymbols.slice(0, 10).map(s => ({ - symbol: s.symbol.Code, - exchange: s.symbol.Exchange, - name: s.symbol.Name, - lastUpdate: s.lastRun - })) - }); - - let jobsScheduled = 0; - - // Schedule jobs with staggered delays - for (let i = 0; i < staleSymbols.length; i++) { - const staleSymbol = staleSymbols[i]; - if (!staleSymbol || !staleSymbol.symbol) { - logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol }); - continue; - } - const { symbol } = staleSymbol; - const jobId = `fetch-prices-${symbol.eodSearchCode}`; - logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, { - name: symbol.Name, - lastUpdate: staleSymbol.lastRun, - delay: i * 100, - jobId - }); - - try { - await this.scheduleOperation('fetch-prices', { - eodSearchCode: symbol.eodSearchCode - }, { - jobId, - attempts: 3, - backoff: { - type: 'exponential', - delay: 5000 - }, - delay: i * 100 // Stagger jobs by 100ms per symbol to avoid rate limit spikes - }); - jobsScheduled++; - } catch (error: any) { - if (error?.message?.includes('Job already exists')) { - logger.debug(`Job already exists: ${jobId}`); - } else { - throw error; - } - } - } - - logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`); - - return { - success: true, - jobsScheduled - }; - } catch (error) { - logger.error('Failed to schedule price fetch jobs', { error }); - throw error; - } -} - -export async function fetchPrices( - this: EodHandler, - input: FetchPricesInput -): Promise<{ success: boolean; priceCount: number }> { - const logger = this.logger; - const { eodSearchCode } = input; - - // Declare variables that need to be accessible in catch block - let symbol: string = ''; - let exchange: string = ''; - - try { - // Lookup symbol using eodSearchCode - const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ - eodSearchCode: eodSearchCode - }); - - if (!symbolDoc) { - logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); - throw new Error(`Symbol not found: ${eodSearchCode}`); - } - - symbol = symbolDoc.Code; - exchange = symbolDoc.Exchange; - - logger.info(`Fetching prices for ${eodSearchCode}`); - - // Get API key from config - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - // Fetch price data from EOD API - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`); - } - - const priceData = await response.json(); - - // EOD returns an array of historical prices - if (!Array.isArray(priceData)) { - throw new Error('Invalid response format from EOD API - expected array'); - } - - logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`); - - // Log date range of prices - if (priceData.length > 0) { - logger.debug(`Price data range for ${eodSearchCode}:`, { - oldest: priceData[0].date, - newest: priceData[priceData.length - 1].date, - count: priceData.length - }); - } - - // Add metadata to each price record - const pricesWithMetadata = priceData.map(price => ({ - symbol, - exchange, - eodSearchCode, - date: price.date, - open: price.open, - high: price.high, - low: price.low, - close: price.close, - adjustedClose: price.adjusted_close, - volume: price.volume, - })); - - // Save to MongoDB - use date and eodSearchCode as unique identifier - const result = await this.mongodb.batchUpsert( - 'eodPrices', - pricesWithMetadata, - ['date', 'eodSearchCode'] - ); - - // Update operation tracker instead of directly updating the symbol - await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', { - status: 'success', - lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null, - recordCount: priceData.length, - metadata: { - insertedCount: result.insertedCount, - updatedCount: priceData.length - result.insertedCount - } - }); - - logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`); - - return { - success: true, - priceCount: result.insertedCount - }; - } catch (error: unknown) { - logger.error('Failed to fetch or save prices', { error, symbol, exchange }); - - // Update operation tracker with failure - await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', { - status: 'failure', - error: error instanceof Error ? error.message : String(error) - }); - - throw error; - } -} \ No newline at end of file +import type { EodHandler } from '../eod.handler'; +import { EOD_CONFIG } from '../shared'; +import { persistEodPrices } from '../shared/price-storage'; + +interface FetchPricesInput { + eodSearchCode: string; +} + +export async function scheduleFetchPrices( + this: EodHandler +): Promise<{ success: boolean; jobsScheduled: number }> { + const logger = this.logger; + + try { + logger.info('Scheduling price fetch jobs for all symbols'); + + // Use OperationTracker to find stale symbols + const staleSymbols = await this.operationRegistry.getStaleSymbols('eod', 'price_update', { + limit: 100000, // Higher limit to process all symbols + }); + + if (!staleSymbols || staleSymbols.length === 0) { + logger.info('No symbols need price updates'); + return { success: true, jobsScheduled: 0 }; + } + + logger.info(`Found ${staleSymbols.length} symbols needing price updates`, { + symbols: staleSymbols.slice(0, 10).map(s => ({ + symbol: s.symbol.Code, + exchange: s.symbol.Exchange, + name: s.symbol.Name, + lastUpdate: s.lastRun, + })), + }); + + let jobsScheduled = 0; + + // Schedule jobs with staggered delays + for (let i = 0; i < staleSymbols.length; i++) { + const staleSymbol = staleSymbols[i]; + if (!staleSymbol || !staleSymbol.symbol) { + logger.warn(`Skipping invalid stale symbol at index ${i}`, { staleSymbol }); + continue; + } + const { symbol } = staleSymbol; + const jobId = `fetch-prices-${symbol.eodSearchCode}`; + logger.debug(`Scheduling price fetch for ${symbol.Code}.${symbol.Exchange}`, { + name: symbol.Name, + lastUpdate: staleSymbol.lastRun, + delay: i * 100, + jobId, + }); + + try { + await this.scheduleOperation( + 'fetch-prices', + { + eodSearchCode: symbol.eodSearchCode, + }, + { + jobId, + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000, + }, + delay: i * 100, // Stagger jobs by 100ms per symbol to avoid rate limit spikes + } + ); + jobsScheduled++; + } catch (error) { + if (error instanceof Error && error.message.includes('Job already exists')) { + logger.debug(`Job already exists: ${jobId}`); + } else { + throw error; + } + } + } + + logger.info(`Successfully scheduled ${jobsScheduled} price fetch jobs`); + + return { + success: true, + jobsScheduled, + }; + } catch (error) { + logger.error('Failed to schedule price fetch jobs', { error }); + throw error; + } +} + +export async function fetchPrices( + this: EodHandler, + input: FetchPricesInput +): Promise<{ success: boolean; priceCount: number }> { + const logger = this.logger; + const { eodSearchCode } = input; + + // Declare variables that need to be accessible in catch block + let symbol: string = ''; + let exchange: string = ''; + + try { + // Lookup symbol using eodSearchCode + const symbolDoc = await this.mongodb.collection('eodSymbols').findOne({ + eodSearchCode: eodSearchCode, + }); + + if (!symbolDoc) { + logger.error(`Symbol not found for eodSearchCode: ${eodSearchCode}`); + throw new Error(`Symbol not found: ${eodSearchCode}`); + } + + symbol = symbolDoc.Code; + exchange = symbolDoc.Exchange; + + logger.info(`Fetching prices for ${eodSearchCode}`); + + // Get API key from config + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + const url = new URL(`https://eodhd.com/api/eod/${eodSearchCode}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + // Fetch price data from EOD API + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error(`EOD Prices API returned ${response.status}: ${response.statusText}`); + } + + const priceData = await response.json(); + + // EOD returns an array of historical prices + if (!Array.isArray(priceData)) { + throw new Error('Invalid response format from EOD API - expected array'); + } + + logger.info(`Fetched ${priceData.length} price records for ${eodSearchCode}`); + + // Log date range of prices + if (priceData.length > 0) { + logger.debug(`Price data range for ${eodSearchCode}:`, { + oldest: priceData[0].date, + newest: priceData[priceData.length - 1].date, + count: priceData.length, + }); + } + + const result = await persistEodPrices( + this.mongodb, + { symbol, exchange, eodSearchCode }, + priceData + ); + + // Update operation tracker instead of directly updating the symbol + await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', { + status: 'success', + lastRecordDate: priceData.length > 0 ? priceData[priceData.length - 1].date : null, + recordCount: priceData.length, + metadata: { + insertedCount: result.insertedCount, + updatedCount: priceData.length - result.insertedCount, + }, + }); + + logger.info(`Successfully saved ${result.insertedCount} price records for ${eodSearchCode}`); + + return { + success: true, + priceCount: result.insertedCount, + }; + } catch (error: unknown) { + logger.error('Failed to fetch or save prices', { error, symbol, exchange }); + + // Update operation tracker with failure + await this.operationRegistry.updateOperation('eod', eodSearchCode, 'price_update', { + status: 'failure', + error: error instanceof Error ? error.message : String(error), + }); + + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/actions/symbols.ts b/apps/stock/data-ingestion/src/handlers/eod/actions/symbols.ts index 4c06b8ab..51c579c3 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/actions/symbols.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/actions/symbols.ts @@ -1,153 +1,162 @@ -import type { BaseHandler } from '@stock-bot/handlers'; -import type { DataIngestionServices } from '../../../types'; -import { EOD_CONFIG } from '../shared'; - -interface FetchSymbolsInput { - exchangeCode: string; - delisted: boolean; -} - - -export async function scheduleFetchSymbols( - this: BaseHandler -): Promise<{ success: boolean; jobsCreated: number }> { - const logger = this.logger; - - try { - logger.info('Starting symbol fetch job scheduling'); - - // Get all exchanges from MongoDB - const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray(); - - if (!exchanges || exchanges.length === 0) { - logger.warn('No exchanges found in database - run fetch-exchanges first'); - return { success: true, jobsCreated: 0 }; - } - - logger.info(`Found ${exchanges.length} exchanges to process`, { - exchanges: exchanges.map((e: any) => ({ code: e.Code, name: e.Name, country: e.Country })) - }); - - let jobsCreated = 0; - - // Create jobs for each exchange - both active and delisted symbols - for (const exchange of exchanges) { - const exchangeCode = exchange.Code; - - // Job for active symbols - await this.scheduleOperation('fetch-symbols', { - exchangeCode, - delisted: false - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 5000 - } - }); - jobsCreated++; - - // Job for delisted symbols - await this.scheduleOperation('fetch-symbols', { - exchangeCode, - delisted: true - }, { - attempts: 3, - backoff: { - type: 'exponential', - delay: 5000 - } - }); - jobsCreated++; - } - - logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`); - - return { - success: true, - jobsCreated - }; - } catch (error) { - logger.error('Failed to schedule symbol fetch jobs', { error }); - throw error; - } -} - -export async function fetchSymbols( - this: BaseHandler, - input: FetchSymbolsInput -): Promise<{ success: boolean; count: number }> { - const logger = this.logger; - const { exchangeCode, delisted } = input; - - try { - logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); - - // Get API key from config - const apiKey = EOD_CONFIG.API_TOKEN; - if (!apiKey) { - throw new Error('EOD API key not configured'); - } - - // Build URL with query parameters - const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`); - url.searchParams.append('api_token', apiKey); - url.searchParams.append('fmt', 'json'); - - if (delisted) { - url.searchParams.append('delisted', '1'); - } - - // Fetch symbols from EOD API using Bun fetch - const response = await fetch(url.toString()); - - if (!response.ok) { - throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`); - } - - const symbols = await response.json(); - - if (!Array.isArray(symbols)) { - throw new Error('Invalid response format from EOD API - expected array'); - } - - logger.info(`Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); - - // Log some sample symbols - if (symbols.length > 0) { - logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, { - count: symbols.length, - samples: symbols.slice(0, 5).map(s => ({ - symbol: s.Code, - name: s.Name, - type: s.Type - })) - }); - } - - // Add metadata to each symbol - const symbolsWithMetadata = symbols.map(symbol => ({ - ...symbol, - eodExchange: exchangeCode, // Store the correct exchange code used to fetch this symbol - eodSearchCode: `${symbol.Code}.${exchangeCode}`, // Create unique search code like AAPL.US - delisted: delisted, - })); - - // Save to MongoDB - use Code as unique identifier along with exchange - const result = await this.mongodb.batchUpsert( - 'eodSymbols', - symbolsWithMetadata, - ['eodSearchCode'] - ); - - logger.info(`Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); - - return { - success: true, - count: result.insertedCount - }; - } catch (error) { - logger.error('Failed to fetch or save symbols', { error, exchangeCode, delisted }); - throw error; - } -} \ No newline at end of file +import type { BaseHandler } from '@stock-bot/handlers'; +import type { DataIngestionServices } from '../../../types'; +import { EOD_CONFIG } from '../shared'; + +interface FetchSymbolsInput { + exchangeCode: string; + delisted: boolean; +} + +export async function scheduleFetchSymbols( + this: BaseHandler +): Promise<{ success: boolean; jobsCreated: number }> { + const logger = this.logger; + + try { + logger.info('Starting symbol fetch job scheduling'); + + // Get all exchanges from MongoDB + const exchanges = await this.mongodb.collection('eodExchanges').find({}).toArray(); + + if (!exchanges || exchanges.length === 0) { + logger.warn('No exchanges found in database - run fetch-exchanges first'); + return { success: true, jobsCreated: 0 }; + } + + logger.info(`Found ${exchanges.length} exchanges to process`, { + exchanges: exchanges.map(e => ({ code: e.Code, name: e.Name, country: e.Country })), + }); + + let jobsCreated = 0; + + // Create jobs for each exchange - both active and delisted symbols + for (const exchange of exchanges) { + const exchangeCode = exchange.Code; + + // Job for active symbols + await this.scheduleOperation( + 'fetch-symbols', + { + exchangeCode, + delisted: false, + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000, + }, + } + ); + jobsCreated++; + + // Job for delisted symbols + await this.scheduleOperation( + 'fetch-symbols', + { + exchangeCode, + delisted: true, + }, + { + attempts: 3, + backoff: { + type: 'exponential', + delay: 5000, + }, + } + ); + jobsCreated++; + } + + logger.info(`Successfully created ${jobsCreated} symbol fetch jobs`); + + return { + success: true, + jobsCreated, + }; + } catch (error) { + logger.error('Failed to schedule symbol fetch jobs', { error }); + throw error; + } +} + +export async function fetchSymbols( + this: BaseHandler, + input: FetchSymbolsInput +): Promise<{ success: boolean; count: number }> { + const logger = this.logger; + const { exchangeCode, delisted } = input; + + try { + logger.info(`Fetching ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}`); + + // Get API key from config + const apiKey = EOD_CONFIG.API_TOKEN; + if (!apiKey) { + throw new Error('EOD API key not configured'); + } + + // Build URL with query parameters + const url = new URL(`https://eodhd.com/api/exchange-symbol-list/${exchangeCode}`); + url.searchParams.append('api_token', apiKey); + url.searchParams.append('fmt', 'json'); + + if (delisted) { + url.searchParams.append('delisted', '1'); + } + + // Fetch symbols from EOD API using Bun fetch + const response = await fetch(url.toString()); + + if (!response.ok) { + throw new Error(`EOD Symbols API returned ${response.status}: ${response.statusText}`); + } + + const symbols = await response.json(); + + if (!Array.isArray(symbols)) { + throw new Error('Invalid response format from EOD API - expected array'); + } + + logger.info( + `Fetched ${symbols.length} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}` + ); + + // Log some sample symbols + if (symbols.length > 0) { + logger.debug(`Sample ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}:`, { + count: symbols.length, + samples: symbols.slice(0, 5).map(s => ({ + symbol: s.Code, + name: s.Name, + type: s.Type, + })), + }); + } + + // Add metadata to each symbol + const symbolsWithMetadata = symbols.map(symbol => ({ + ...symbol, + eodExchange: exchangeCode, // Store the correct exchange code used to fetch this symbol + eodSearchCode: `${symbol.Code}.${exchangeCode}`, // Create unique search code like AAPL.US + delisted: delisted, + })); + + // Save to MongoDB - use Code as unique identifier along with exchange + const result = await this.mongodb.batchUpsert('eodSymbols', symbolsWithMetadata, [ + 'eodSearchCode', + ]); + + logger.info( + `Successfully saved ${result.insertedCount} ${delisted ? 'delisted' : 'active'} symbols for ${exchangeCode}` + ); + + return { + success: true, + count: result.insertedCount, + }; + } catch (error) { + logger.error('Failed to fetch or save symbols', { error, exchangeCode, delisted }); + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/eod.handler.ts b/apps/stock/data-ingestion/src/handlers/eod/eod.handler.ts index a9332fe2..2aa27006 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/eod.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/eod.handler.ts @@ -1,186 +1,189 @@ -import { - BaseHandler, - Disabled, - Handler, - Operation, - RateLimit, - ScheduledOperation -} from '@stock-bot/handlers'; -import type { OperationRegistry } from '../../shared/operation-manager'; -import type { DataIngestionServices } from '../../types'; -import { - crawlIntraday, - fetchBulkFundamentals, - fetchCorporateActions, - fetchExchanges, - fetchIntraday, - fetchPrices, - fetchSingleFundamentals, - fetchSymbolChangeHistory, - fetchSymbols, - scheduleFetchCorporateActions, - scheduleFetchFundamentals, - scheduleFetchPrices, - scheduleFetchSymbols, - scheduleIntradayCrawl -} from './actions'; -import { createEODOperationRegistry } from './shared'; - -/** - * EOD (End of Day) Handler demonstrating advanced rate limiting - * - * Handler-level limits apply to all operations unless overridden - * Operations can specify just a cost to use handler limits, or override with custom limits - */ -@Handler('eod') -@Disabled() -@RateLimit({ - limits: [ - { points: 900, duration: 60 }, // 1000 points per minute - { points: 100500, duration: 86400 }, // 100,500 points per day - ], -}) -export class EodHandler extends BaseHandler { - public operationRegistry!: OperationRegistry; - - constructor(services: any) { - super(services); - - // Use pre-initialized registry if available, otherwise create new one - if ((EodHandler as any).operationRegistry) { - this.operationRegistry = (EodHandler as any).operationRegistry; - this.logger.info('Using pre-initialized EOD operation registry'); - } else { - // Fallback: Initialize operation registry with EOD provider - createEODOperationRegistry(this.mongodb, this.logger) - .then(registry => { - this.operationRegistry = registry; - this.logger.info('EOD operation registry initialized successfully'); - }) - .catch(error => { - this.logger.error('Failed to initialize EOD operations', { error }); - }); - } - } - - /** - * Fetch exchanges list from EOD - * Runs weekly on Sundays at midnight - */ - @Operation('fetch-exchanges') - @ScheduledOperation('fetch-exchanges', '0 0 * * 0') - @RateLimit(1) // 1 point per call - fetchExchanges = fetchExchanges; - - /** - * Schedule symbol fetching for all exchanges - * Runs daily at 1 AM - */ - @Operation('schedule-fetch-symbols') - @ScheduledOperation('schedule-fetch-symbols', '0 1 * * *') - @RateLimit(1) // 1 point for scheduling - scheduleFetchSymbols = scheduleFetchSymbols; - - /** - * Fetch symbols for a specific exchange - * Called by schedule-fetch-symbols for each exchange - */ - @Operation('fetch-symbols') - @RateLimit(1) // 1 point per exchange - fetchSymbols = fetchSymbols; - - /** - * Schedule price fetching for all symbols not updated in last week - * Runs daily at 2 AM - */ - @Operation('schedule-fetch-prices') - @ScheduledOperation('schedule-fetch-prices', '0 2 * * *') - @RateLimit(1) // 1 point for scheduling - scheduleFetchPrices = scheduleFetchPrices; - - /** - * Fetch historical prices for a specific symbol - * Called by schedule-fetch-prices for each symbol - */ - @Operation('fetch-prices') - @RateLimit(1) // 1 point per price fetch - fetchPrices = fetchPrices; - - /** - * Schedule intraday crawl for symbols needing intraday data - * Runs daily at 3 AM - */ - @Operation('schedule-intraday-crawl') - @ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', { - immediately: true, - }) - @RateLimit(1) // 1 point for scheduling - scheduleIntradayCrawl = scheduleIntradayCrawl; - - /** - * Crawl intraday data for a specific symbol and interval - * Handles resumption and batch processing - */ - @Operation('crawl-intraday') - @RateLimit(5) // 5 points per crawl batch - crawlIntraday = crawlIntraday; - - /** - * Fetch intraday data for a specific date range - * Called by crawl-intraday - */ - @Operation('fetch-intraday') - @RateLimit(5) // 5 points per intraday fetch - fetchIntraday = fetchIntraday; - - /** - * Schedule bulk fundamentals fetch for symbols - * DISABLED - Not scheduled automatically - */ - @Operation('schedule-fetch-fundamentals') - // @ScheduledOperation('schedule-fetch-fundamentals', '0 4 * * 0') // Disabled - would run weekly at 4 AM on Sundays - @RateLimit(1) // 1 point for scheduling - scheduleFetchFundamentals = scheduleFetchFundamentals; - - /** - * Fetch fundamentals for up to 500 symbols in bulk - * Called by schedule-fetch-fundamentals for non-ETFs - */ - @Operation('fetch-bulk-fundamentals') - @RateLimit(600) // 100 base + up to 500 symbols = 600 points max - fetchBulkFundamentals = fetchBulkFundamentals; - - /** - * Fetch fundamentals for a single symbol - * Called by schedule-fetch-fundamentals for ETFs - */ - @Operation('fetch-single-fundamentals') - @RateLimit(10) // 10 points per single fundamentals fetch - fetchSingleFundamentals = fetchSingleFundamentals; - - /** - * Fetch symbol change history - * Runs weekly on Mondays at 5 AM - */ - @Operation('fetch-symbol-change-history') - @ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1') - @RateLimit(5) // 5 points per request - fetchSymbolChangeHistory = fetchSymbolChangeHistory; - - /** - * Schedule corporate actions (dividends and splits) fetch - * DISABLED - Corporate actions likely come with fundamentals - */ - @Operation('schedule-fetch-corporate-actions') - // @ScheduledOperation('schedule-fetch-corporate-actions', '0 6 1 * *') // Disabled - would run monthly on the 1st at 6 AM - @RateLimit(1) // 1 point for scheduling - scheduleFetchCorporateActions = scheduleFetchCorporateActions; - - /** - * Fetch dividends or splits for a specific symbol - * Called by schedule-fetch-corporate-actions - */ - @Operation('fetch-corporate-actions') - @RateLimit(10) // 10 points per fetch - fetchCorporateActions = fetchCorporateActions; -} \ No newline at end of file +import { + BaseHandler, + Disabled, + Handler, + Operation, + RateLimit, + ScheduledOperation, +} from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import type { OperationRegistry } from '../../shared/operation-manager'; +import { resolveIngestionServices } from '../../types'; +import type { DataIngestionServices } from '../../types'; +import { + crawlIntraday, + fetchBulkFundamentals, + fetchCorporateActions, + fetchExchanges, + fetchIntraday, + fetchPrices, + fetchSingleFundamentals, + fetchSymbolChangeHistory, + fetchSymbols, + scheduleFetchCorporateActions, + scheduleFetchFundamentals, + scheduleFetchPrices, + scheduleFetchSymbols, + scheduleIntradayCrawl, +} from './actions'; +import { createEODOperationRegistry } from './shared'; + +/** + * EOD (End of Day) Handler demonstrating advanced rate limiting + * + * Handler-level limits apply to all operations unless overridden + * Operations can specify just a cost to use handler limits, or override with custom limits + */ +@Handler('eod') +@Disabled() +@RateLimit({ + limits: [ + { points: 900, duration: 60 }, // 1000 points per minute + { points: 100500, duration: 86400 }, // 100,500 points per day + ], +}) +export class EodHandler extends BaseHandler { + static operationRegistry?: OperationRegistry; + public operationRegistry!: OperationRegistry; + + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'eod')); + + // Use pre-initialized registry if available, otherwise create new one + if (EodHandler.operationRegistry) { + this.operationRegistry = EodHandler.operationRegistry; + this.logger.info('Using pre-initialized EOD operation registry'); + } else { + // Fallback: Initialize operation registry with EOD provider + createEODOperationRegistry(this.mongodb, this.logger) + .then(registry => { + this.operationRegistry = registry; + this.logger.info('EOD operation registry initialized successfully'); + }) + .catch(error => { + this.logger.error('Failed to initialize EOD operations', { error }); + }); + } + } + + /** + * Fetch exchanges list from EOD + * Runs weekly on Sundays at midnight + */ + @Operation('fetch-exchanges') + @ScheduledOperation('fetch-exchanges', '0 0 * * 0') + @RateLimit(1) // 1 point per call + fetchExchanges = fetchExchanges; + + /** + * Schedule symbol fetching for all exchanges + * Runs daily at 1 AM + */ + @Operation('schedule-fetch-symbols') + @ScheduledOperation('schedule-fetch-symbols', '0 1 * * *') + @RateLimit(1) // 1 point for scheduling + scheduleFetchSymbols = scheduleFetchSymbols; + + /** + * Fetch symbols for a specific exchange + * Called by schedule-fetch-symbols for each exchange + */ + @Operation('fetch-symbols') + @RateLimit(1) // 1 point per exchange + fetchSymbols = fetchSymbols; + + /** + * Schedule price fetching for all symbols not updated in last week + * Runs daily at 2 AM + */ + @Operation('schedule-fetch-prices') + @ScheduledOperation('schedule-fetch-prices', '0 2 * * *') + @RateLimit(1) // 1 point for scheduling + scheduleFetchPrices = scheduleFetchPrices; + + /** + * Fetch historical prices for a specific symbol + * Called by schedule-fetch-prices for each symbol + */ + @Operation('fetch-prices') + @RateLimit(1) // 1 point per price fetch + fetchPrices = fetchPrices; + + /** + * Schedule intraday crawl for symbols needing intraday data + * Runs daily at 3 AM + */ + @Operation('schedule-intraday-crawl') + @ScheduledOperation('schedule-intraday-crawl', '0 3 * * *', { + immediately: true, + }) + @RateLimit(1) // 1 point for scheduling + scheduleIntradayCrawl = scheduleIntradayCrawl; + + /** + * Crawl intraday data for a specific symbol and interval + * Handles resumption and batch processing + */ + @Operation('crawl-intraday') + @RateLimit(5) // 5 points per crawl batch + crawlIntraday = crawlIntraday; + + /** + * Fetch intraday data for a specific date range + * Called by crawl-intraday + */ + @Operation('fetch-intraday') + @RateLimit(5) // 5 points per intraday fetch + fetchIntraday = fetchIntraday; + + /** + * Schedule bulk fundamentals fetch for symbols + * DISABLED - Not scheduled automatically + */ + @Operation('schedule-fetch-fundamentals') + // @ScheduledOperation('schedule-fetch-fundamentals', '0 4 * * 0') // Disabled - would run weekly at 4 AM on Sundays + @RateLimit(1) // 1 point for scheduling + scheduleFetchFundamentals = scheduleFetchFundamentals; + + /** + * Fetch fundamentals for up to 500 symbols in bulk + * Called by schedule-fetch-fundamentals for non-ETFs + */ + @Operation('fetch-bulk-fundamentals') + @RateLimit(600) // 100 base + up to 500 symbols = 600 points max + fetchBulkFundamentals = fetchBulkFundamentals; + + /** + * Fetch fundamentals for a single symbol + * Called by schedule-fetch-fundamentals for ETFs + */ + @Operation('fetch-single-fundamentals') + @RateLimit(10) // 10 points per single fundamentals fetch + fetchSingleFundamentals = fetchSingleFundamentals; + + /** + * Fetch symbol change history + * Runs weekly on Mondays at 5 AM + */ + @Operation('fetch-symbol-change-history') + @ScheduledOperation('fetch-symbol-change-history', '0 5 * * 1') + @RateLimit(5) // 5 points per request + fetchSymbolChangeHistory = fetchSymbolChangeHistory; + + /** + * Schedule corporate actions (dividends and splits) fetch + * DISABLED - Corporate actions likely come with fundamentals + */ + @Operation('schedule-fetch-corporate-actions') + // @ScheduledOperation('schedule-fetch-corporate-actions', '0 6 1 * *') // Disabled - would run monthly on the 1st at 6 AM + @RateLimit(1) // 1 point for scheduling + scheduleFetchCorporateActions = scheduleFetchCorporateActions; + + /** + * Fetch dividends or splits for a specific symbol + * Called by schedule-fetch-corporate-actions + */ + @Operation('fetch-corporate-actions') + @RateLimit(10) // 10 points per fetch + fetchCorporateActions = fetchCorporateActions; +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/shared/operation-provider.ts b/apps/stock/data-ingestion/src/handlers/eod/shared/operation-provider.ts index 54a1fede..71987ccc 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/shared/operation-provider.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/shared/operation-provider.ts @@ -1,118 +1,127 @@ -/** - * EOD Operation Provider - Defines operations for EOD Historical Data source - */ - -import { BaseOperationProvider, OperationRegistry, type OperationConfig, type ProviderConfig } from '../../../shared/operation-manager'; - -/** - * EOD operation definitions - */ -export const EOD_OPERATIONS: OperationConfig[] = [ - // Exchange data - { - name: 'exchange_update', - type: 'standard', - description: 'Update exchange list', - defaultStaleHours: 24 * 7 // Weekly - }, - - // Symbol data - { - name: 'symbol_update', - type: 'standard', - description: 'Update symbol list for exchange', - defaultStaleHours: 24 // Daily - }, - - // Price data - { - name: 'price_update', - type: 'standard', - description: 'Update daily price data', - defaultStaleHours: 24 * 7 // Weekly - EOD's schedule-fetch-prices runs for symbols not updated in last week - }, - - // Intraday data - { - name: 'intraday_1m', - type: 'intraday_crawl', - description: 'Crawl 1-minute intraday data', - requiresFinishedFlag: true, - defaultStaleHours: 50000 // Daily check for new data - }, - { - name: 'intraday_5m', - type: 'intraday_crawl', - description: 'Crawl 5-minute intraday data', - requiresFinishedFlag: true, - defaultStaleHours: 50000 // Daily check for new data - }, - { - name: 'intraday_1h', - type: 'intraday_crawl', - description: 'Crawl 1-hour intraday data', - requiresFinishedFlag: true, - defaultStaleHours: 50000 // Daily check for new data - }, - - // Fundamental data - { - name: 'fundamentals_update', - type: 'standard', - description: 'Update fundamental data', - defaultStaleHours: 24 * 7 // Weekly - }, - - // Corporate actions - { - name: 'dividends_update', - type: 'standard', - description: 'Update dividend data', - defaultStaleHours: 24 * 30 // Monthly - }, - { - name: 'splits_update', - type: 'standard', - description: 'Update stock split data', - defaultStaleHours: 24 * 30 // Monthly - }, - - // Symbol changes - { - name: 'symbol_change_update', - type: 'standard', - description: 'Update symbol change history', - defaultStaleHours: 24 * 7 // Weekly - } -]; - -/** - * EOD Operation Provider - */ -export class EODOperationProvider extends BaseOperationProvider { - getProviderConfig(): ProviderConfig { - return { - name: 'eod', - collectionName: 'eodSymbols', - symbolField: 'eodSearchCode', - description: 'EOD Historical Data provider' - }; - } - - getOperations(): OperationConfig[] { - return EOD_OPERATIONS; - } -} - -/** - * Create and initialize EOD operation registry - */ -export async function createEODOperationRegistry( - mongodb: any, - logger: any -): Promise { - const registry = new OperationRegistry({ mongodb, logger }); - const provider = new EODOperationProvider({ mongodb, logger }); - await registry.registerProvider(provider); - return registry; -} \ No newline at end of file +import type { Logger, MongoDBClient } from '@stock-bot/services'; +/** + * EOD Operation Provider - Defines operations for EOD Historical Data source + */ + +import { + BaseOperationProvider, + OperationRegistry, + type OperationConfig, + type ProviderConfig, +} from '../../../shared/operation-manager'; + +/** + * EOD operation definitions + */ +export const EOD_OPERATIONS: OperationConfig[] = [ + // Exchange data + { + name: 'exchange_update', + type: 'standard', + description: 'Update exchange list', + defaultStaleHours: 24 * 7, // Weekly + }, + + // Symbol data + { + name: 'symbol_update', + type: 'standard', + description: 'Update symbol list for exchange', + defaultStaleHours: 24, // Daily + }, + + // Price data + { + name: 'price_update', + type: 'standard', + description: 'Update daily price data', + defaultStaleHours: 24 * 7, // Weekly - EOD's schedule-fetch-prices runs for symbols not updated in last week + }, + + // Intraday data + { + name: 'intraday_1m', + type: 'intraday_crawl', + description: 'Crawl 1-minute intraday data', + requiresFinishedFlag: true, + defaultStaleHours: 50000, // Daily check for new data + }, + { + name: 'intraday_5m', + type: 'intraday_crawl', + description: 'Crawl 5-minute intraday data', + requiresFinishedFlag: true, + defaultStaleHours: 50000, // Daily check for new data + }, + { + name: 'intraday_1h', + type: 'intraday_crawl', + description: 'Crawl 1-hour intraday data', + requiresFinishedFlag: true, + defaultStaleHours: 50000, // Daily check for new data + }, + + // Fundamental data + { + name: 'fundamentals_update', + type: 'standard', + description: 'Update fundamental data', + defaultStaleHours: 24 * 7, // Weekly + }, + + // Corporate actions + { + name: 'dividends_update', + type: 'standard', + description: 'Update dividend data', + defaultStaleHours: 24 * 30, // Monthly + }, + { + name: 'splits_update', + type: 'standard', + description: 'Update stock split data', + defaultStaleHours: 24 * 30, // Monthly + }, + + // Symbol changes + { + name: 'symbol_change_update', + type: 'standard', + description: 'Update symbol change history', + defaultStaleHours: 24 * 7, // Weekly + }, +]; + +/** + * EOD Operation Provider + */ +export class EODOperationProvider extends BaseOperationProvider { + getProviderConfig(): ProviderConfig { + return { + name: 'eod', + collectionName: 'eodSymbols', + symbolField: 'eodSearchCode', + description: 'EOD Historical Data provider', + }; + } + + getOperations(): OperationConfig[] { + return EOD_OPERATIONS; + } +} + +/** + * Create and initialize EOD operation registry + */ +export async function createEODOperationRegistry( + mongodb: MongoDBClient | null | undefined, + logger: Logger +): Promise { + if (!mongodb) { + throw new Error('Operation registry requires MongoDB'); + } + const registry = new OperationRegistry({ mongodb, logger }); + const provider = new EODOperationProvider({ mongodb, logger }); + await registry.registerProvider(provider); + return registry; +} diff --git a/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts b/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts new file mode 100644 index 00000000..b3366a1a --- /dev/null +++ b/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts @@ -0,0 +1,47 @@ +import type { MongoDBClient } from '@stock-bot/services'; + +export interface EodPrice { + date: string; + open: number; + high: number; + low: number; + close: number; + adjusted_close?: number; + volume: number; +} + +/** Shared persistence boundary used by the HTTP action and deterministic replay tests. */ +export async function persistEodPrices( + mongodb: Pick, + identity: { symbol: string; exchange: string; eodSearchCode: string }, + prices: readonly EodPrice[] +) { + const documents = prices.map(price => { + if ( + typeof price.date !== 'string' || + !/^\d{4}-\d{2}-\d{2}$/.test(price.date) || + !Number.isFinite(Date.parse(price.date)) || + new Date(price.date).toISOString().slice(0, 10) !== price.date || + ![price.open, price.high, price.low, price.close, price.volume].every(Number.isFinite) || + (price.adjusted_close !== undefined && !Number.isFinite(price.adjusted_close)) || + price.low <= 0 || + price.high < Math.max(price.open, price.close) || + price.low > Math.min(price.open, price.close) || + price.volume < 0 + ) { + throw new Error(`Invalid OHLCV price record for ${identity.eodSearchCode}`); + } + return { + ...identity, + source: 'eod', + date: price.date, + open: price.open, + high: price.high, + low: price.low, + close: price.close, + adjustedClose: price.adjusted_close ?? price.close, + volume: price.volume, + }; + }); + return mongodb.batchUpsert('eodPrices', documents, ['date', 'eodSearchCode']); +} diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges-and-symbols.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges-and-symbols.action.ts index 59926016..4710a95a 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges-and-symbols.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-exchanges-and-symbols.action.ts @@ -1,3 +1,4 @@ +import type { IServiceContainer } from '@stock-bot/services'; import { fetchExchanges } from './fetch-exchanges.action'; import { fetchSession } from './fetch-session.action'; import { fetchSymbols } from './fetch-symbols.action'; diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-session.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-session.action.ts index 02b7eacb..f85ec308 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-session.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-session.action.ts @@ -1,19 +1,20 @@ -import { Browser } from '@stock-bot/browser'; import type { IServiceContainer } from '@stock-bot/handlers'; +import { requireServices } from '@stock-bot/services'; import { IB_CONFIG } from '../shared/config'; export async function fetchSession( services: IServiceContainer ): Promise | undefined> { try { - await Browser.initialize({ + const { browser } = requireServices(services, 'browser'); + await browser.initialize({ headless: true, timeout: IB_CONFIG.BROWSER_TIMEOUT, blockResources: false, }); services.logger.info('✅ Browser initialized'); - const { page } = await Browser.createPageWithProxy( + const { page } = await browser.createPageWithProxy( IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE, IB_CONFIG.DEFAULT_PROXY ); diff --git a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts index 92882b1e..57d979df 100644 --- a/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts +++ b/apps/stock/data-ingestion/src/handlers/ib/actions/fetch-symbols.action.ts @@ -1,4 +1,5 @@ import type { IServiceContainer } from '@stock-bot/handlers'; +import { requireServices } from '@stock-bot/services'; import { IB_CONFIG } from '../shared/config'; import { fetchSession } from './fetch-session.action'; @@ -104,7 +105,10 @@ export async function fetchSymbols(services: IServiceContainer): Promise { +export async function initializeAllHandlers( + serviceContainer: IServiceContainer, + context: HandlerInitializationContext +): Promise { try { // Initialize operation registries first logger.info('Initializing operation registries'); - + const mongodb = serviceContainer.mongodb; const operationLogger = serviceContainer.logger; - + // Create operation registries try { eodOperationRegistry = await createEODOperationRegistry(mongodb, operationLogger); logger.info('EOD operation registry created'); - + // Attach to handler class so instances can access it - (EodHandler as any).operationRegistry = eodOperationRegistry; + EodHandler.operationRegistry = eodOperationRegistry; } catch (error) { logger.error('Failed to create EOD operation registry', { error }); } - + try { qmOperationRegistry = await createQMOperationRegistry(mongodb, operationLogger); logger.info('QM operation registry created'); - + // Attach to handler class so instances can access it - (QMHandler as any).operationRegistry = qmOperationRegistry; + QMHandler.operationRegistry = qmOperationRegistry; } catch (error) { logger.error('Failed to create QM operation registry', { error }); } - + // The HandlerScanner in the DI container will handle the actual registration // We just need to ensure handlers are imported so their decorators run - const handlers = [CeoHandler, IbHandler, QMHandler, WebShareHandler, TradingViewHandler, TeHandler, EodHandler, TtHandler]; + const handlers = [ + CeoHandler, + IbHandler, + QMHandler, + WebShareHandler, + TradingViewHandler, + TeHandler, + EodHandler, + TtHandler, + ]; logger.info('Handler imports loaded', { count: handlers.length, - handlers: handlers.map(h => (h as any).__handlerName || h.name), + handlers: handlers.map(h => (h as DecoratedHandlerClass).__handlerName || h.name), }); // Log what metadata the handlers have for (const HandlerClass of handlers) { - const metadata = (HandlerClass as any).__handlerMetadata; + const metadata = HandlerClass.extractMetadata(); logger.info(`Handler ${HandlerClass.name} metadata`, { hasMetadata: !!metadata, handlerName: metadata?.name, @@ -82,11 +97,11 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer) } // Get the DI container from the service container - const diContainer = (serviceContainer as any)._diContainer; + const diContainer = context; - if (diContainer?.resolve) { + if (diContainer) { // Get handler scanner from DI container - const scanner = diContainer.resolve('handlerScanner'); + const scanner = context.handlerScanner; if (scanner?.registerHandlerClass) { for (const HandlerClass of handlers) { scanner.registerHandlerClass(HandlerClass, { serviceName: 'data-ingestion' }); @@ -97,13 +112,13 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer) } // Also check the handler registry directly - const handlerRegistry = diContainer.resolve('handlerRegistry'); + const handlerRegistry = context.handlerRegistry; if (handlerRegistry) { logger.info('Handler registry state after registration', { registeredHandlers: handlerRegistry.getHandlerNames(), handlersWithSchedule: handlerRegistry.getAllHandlersWithSchedule().size, }); - + // Initialize handlers that have onInit method // We need to instantiate handlers and call their onInit for (const HandlerClass of handlers) { @@ -111,7 +126,8 @@ export async function initializeAllHandlers(serviceContainer: IServiceContainer) // Create handler instance with service container const handlerInstance = new HandlerClass(serviceContainer); if (handlerInstance && typeof handlerInstance.onInit === 'function') { - const handlerName = (HandlerClass as any).__handlerName || HandlerClass.name; + const handlerName = + (HandlerClass as DecoratedHandlerClass).__handlerName || HandlerClass.name; logger.info(`Calling onInit for handler: ${handlerName}`); await handlerInstance.onInit(); } diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts index 455480b2..d509733f 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts @@ -1,3 +1,4 @@ +import type { Document } from 'mongodb'; /** * QM Events Actions - Fetch and update dividends, splits, and earnings together */ @@ -30,7 +31,7 @@ export async function updateEvents( }; }> { const { symbol, exchange, qmSearchCode } = input; - + this.logger.info(`Fetching events ${qmSearchCode}`, { symbol, exchange, qmSearchCode }); const sessionManager = QMSessionManager.getInstance(); @@ -39,7 +40,7 @@ export async function updateEvents( // Get a session - you'll need to add the appropriate session ID const sessionId = QM_SESSION_IDS.PRICES; // TODO: Update with correct session ID const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM events ${qmSearchCode}`); } @@ -50,10 +51,9 @@ export async function updateEvents( earnings: 'true', splits: 'true', dividends: 'true', - symbol: qmSearchCode, + symbol: qmSearchCode, }); - // TODO: Update with correct events endpoint const apiUrl = `${QM_CONFIG.EVENTS_URL}?${searchParams.toString()}`; @@ -75,111 +75,121 @@ export async function updateEvents( }); throw new Error(`Invalid response structure from QM API for ${qmSearchCode}`); } - + // Update session success stats await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); - let dividendCount = 0; let splitCount = 0; let earningsCount = 0; // Process dividends - if (results.dividends[0].dividend && results.dividends[0].dividend.length > 0 && Array.isArray(results.dividends[0].dividend)) { + if ( + results.dividends[0].dividend && + results.dividends[0].dividend.length > 0 && + Array.isArray(results.dividends[0].dividend) + ) { await this.mongodb.batchUpsert( 'qmDividends', - results.dividends[0].dividend.map((dividend: any) => ({ + results.dividends[0].dividend.map((dividend: Document) => ({ ...dividend, symbol, exchange, qmSearchCode, reportDate: new Date(dividend.date), })), - ['qmSearchCode','reportDate'] + ['qmSearchCode', 'reportDate'] ); dividendCount = results.dividends[0].dividend.length; } // Process splits - if (results.splits[0].split && results.splits[0].split.length > 0 && Array.isArray(results.splits[0].split)) { + if ( + results.splits[0].split && + results.splits[0].split.length > 0 && + Array.isArray(results.splits[0].split) + ) { await this.mongodb.batchUpsert( 'qmSplits', - results.splits[0].split.map((split: any) => ({ + results.splits[0].split.map((split: Document) => ({ ...split, symbol, exchange, qmSearchCode, reportDate: new Date(split.date), })), - ['qmSearchCode','reportDate'] + ['qmSearchCode', 'reportDate'] ); splitCount = results.splits[0].split.length; } // Process earnings - if (results.earnings[0].earning && results.earnings[0].earning.length > 0 && Array.isArray(results.earnings[0].earning)) { + if ( + results.earnings[0].earning && + results.earnings[0].earning.length > 0 && + Array.isArray(results.earnings[0].earning) + ) { await this.mongodb.batchUpsert( 'qmEarnings', - results.earnings[0].earning.map((earning: any) => ({ + results.earnings[0].earning.map((earning: Document) => ({ ...earning, symbol, exchange, qmSearchCode, reportDate: new Date(earning.reportDate[0]), })), - ['qmSearchCode','reportDate'] + ['qmSearchCode', 'reportDate'] ); earningsCount = results.earnings[0].earning.length; } // Update tracking for events const updateTime = new Date(); - + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', { status: 'success', lastRecordDate: updateTime, - recordCount: dividendCount + splitCount + earningsCount + recordCount: dividendCount + splitCount + earningsCount, }); - this.logger.info(`Events updated successfully ${qmSearchCode}`, { + this.logger.info(`Events updated successfully ${qmSearchCode}`, { symbol, dividendCount, splitCount, - earningsCount + earningsCount, }); return { success: true, symbol, message: `Events updated for ${qmSearchCode}`, - data: { + data: { dividends: dividendCount, splits: splitCount, - earnings: earningsCount - } + earnings: earningsCount, + }, }; - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error fetching events', { + this.logger.error('Error fetching events', { symbol, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + // Track failure for events - + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'events_update', { - status: 'failure' + status: 'failure', }); - + return { success: false, symbol, - message: `Failed to fetch events: ${error instanceof Error ? error.message : 'Unknown error'}` + message: `Failed to fetch events: ${error instanceof Error ? error.message : 'Unknown error'}`, }; } } @@ -200,14 +210,14 @@ export async function scheduleEventsUpdates( errors: number; }> { const { limit = 100000, forceUpdate = false } = input; - + this.logger.info('Scheduling events updates', { limit, forceUpdate }); try { // Get symbols that need events updates const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'events_update', { minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly - limit + limit, }); if (staleSymbols.length === 0) { @@ -215,7 +225,7 @@ export async function scheduleEventsUpdates( return { message: 'No symbols need events updates', symbolsQueued: 0, - errors: 0 + errors: 0, }; } @@ -227,15 +237,19 @@ export async function scheduleEventsUpdates( // Schedule individual update jobs for each symbol for (const item of staleSymbols) { try { - await this.scheduleOperation('update-events', { - symbol: item.symbol.symbol, - exchange: item.symbol.exchange, - qmSearchCode: item.symbol.qmSearchCode - }, { - priority: 4, - delay: queued * 0.05 // 1.5 seconds between jobs - }); - + await this.scheduleOperation( + 'update-events', + { + symbol: item.symbol.symbol, + exchange: item.symbol.exchange, + qmSearchCode: item.symbol.qmSearchCode, + }, + { + priority: 4, + delay: queued * 0.05, // 1.5 seconds between jobs + } + ); + queued++; } catch (error) { this.logger.error(`Failed to schedule events update for ${item.symbol.symbol}`, { error }); @@ -246,16 +260,16 @@ export async function scheduleEventsUpdates( this.logger.info('Events update scheduling completed', { symbolsQueued: queued, errors, - total: staleSymbols.length + total: staleSymbols.length, }); return { message: `Scheduled events updates for ${queued} symbols`, symbolsQueued: queued, - errors + errors, }; } catch (error) { this.logger.error('Events scheduling failed', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts index 3906f6e0..6730805b 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts @@ -1,3 +1,4 @@ +import type { Document } from 'mongodb'; /** * QM Filings Actions - Fetch and update SEC filings */ @@ -25,11 +26,14 @@ export async function updateFilings( success: boolean; symbol: string; message: string; - data?: any; + data?: unknown; }> { const { qmSearchCode, page, symbol, exchange, lastRecordDate, totalPages } = input; - - this.logger.info(`Fetching filings ${qmSearchCode} - ${page}/${totalPages}`, { qmSearchCode, page }); + + this.logger.info(`Fetching filings ${qmSearchCode} - ${page}/${totalPages}`, { + qmSearchCode, + page, + }); const sessionManager = QMSessionManager.getInstance(); await sessionManager.initialize(this.cache, this.logger); @@ -37,7 +41,7 @@ export async function updateFilings( // Get a session - you'll need to add the appropriate session ID for filings const sessionId = QM_SESSION_IDS.LOOKUP; // TODO: Update with correct session ID const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM filings`); } @@ -52,12 +56,12 @@ export async function updateFilings( // inclIxbrl: "true", // inclXbrl: "true", // resultsPerPage: "25", - webmasterId: "500", + webmasterId: '500', token: session.headers['Datatool-Token'] || '', }); - delete session?.headers?.["Datatool-Token"] - + delete session?.headers?.['Datatool-Token']; + const formData = new FormData(); formData.append('symbol', qmSearchCode); formData.append('inclXbrl', 'true'); @@ -68,11 +72,11 @@ export async function updateFilings( formData.append('xbrlSubDoc', 'true'); // https://app.quotemedia.com/data/getCompanyFilings.json?page=1&webmasterId=500&symbol=AAPL&xbrlSubDoc=true&inclIxbrl=true&inclXbrl=true&resultsPerPage=25 - + // TODO: Update with correct filings endpoint const apiUrl = `${QM_CONFIG.FILING_URL}?${searchParams.toString()}`; - console.log('Fetching filings from:', apiUrl, formData, session.headers); + this.logger.debug('Fetching filings', { apiUrl }); const response = await fetch(apiUrl, { method: 'POST', @@ -87,19 +91,26 @@ export async function updateFilings( const filingsData = await response.json(); - if( parseInt(filingsData.results.pagenumber) * filingsData.results.count >= filingsData.results.totalCount) { - await this.scheduleOperation('update-filings', { - symbol: symbol, - exchange: exchange, - qmSearchCode: qmSearchCode, - lastRecordDate: lastRecordDate || null, - page: parseInt(filingsData.results.pagenumber) + 1, - totalPages: (filingsData.results.totalCount / filingsData.results.count) + 1 - }, { - priority: 5, // Lower priority than financial data - }); + if ( + parseInt(filingsData.results.pagenumber) * filingsData.results.count >= + filingsData.results.totalCount + ) { + await this.scheduleOperation( + 'update-filings', + { + symbol: symbol, + exchange: exchange, + qmSearchCode: qmSearchCode, + lastRecordDate: lastRecordDate || null, + page: parseInt(filingsData.results.pagenumber) + 1, + totalPages: filingsData.results.totalCount / filingsData.results.count + 1, + }, + { + priority: 5, // Lower priority than financial data + } + ); } - + // Update session success stats await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); @@ -108,7 +119,7 @@ export async function updateFilings( // Store filings in a separate collection await this.mongodb.batchUpsert( 'qmFilings', - filingsData.results.filings.filing[0].map((filing: any) => ({ + filingsData.results.filings.filing[0].map((filing: Document) => ({ ...filing, symbol, exchange, @@ -120,28 +131,28 @@ export async function updateFilings( await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { status: 'success', lastRecordDate: new Date(), - recordCount: filingsData.length + recordCount: filingsData.length, }); - this.logger.info(`Filings updated successfully ${qmSearchCode} - ${page}/${totalPages}`, { + this.logger.info(`Filings updated successfully ${qmSearchCode} - ${page}/${totalPages}`, { qmSearchCode, page, totalPages, - filingsCount: filingsData.length + filingsCount: filingsData.length, }); return { success: true, symbol, message: `Filings updated for ${symbol}`, - data: { count: filingsData.length } + data: { count: filingsData.length }, }; } else { // Some symbols may not have filings (non-US companies, etc) await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { status: 'success', lastRecordDate: new Date(), - recordCount: 0 + recordCount: 0, }); this.logger.info('No filings found for symbol', { symbol }); @@ -149,30 +160,29 @@ export async function updateFilings( success: true, symbol, message: `No filings found for ${symbol}`, - data: { count: 0 } + data: { count: 0 }, }; } - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error fetching filings', { + this.logger.error('Error fetching filings', { symbol, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + // Track failure await this.operationRegistry.updateOperation('qm', qmSearchCode, 'filings_update', { - status: 'failure' + status: 'failure', }); - + return { success: false, symbol, - message: `Failed to fetch filings: ${error instanceof Error ? error.message : 'Unknown error'}` + message: `Failed to fetch filings: ${error instanceof Error ? error.message : 'Unknown error'}`, }; } } @@ -193,7 +203,7 @@ export async function scheduleFilingsUpdates( errors: number; }> { const { limit = 1, forceUpdate = false } = input; - + this.logger.info('Scheduling filings updates', { limit, forceUpdate }); try { @@ -203,25 +213,29 @@ export async function scheduleFilingsUpdates( // limit // }); - const staleSymbols = ['AAPL'] + const staleSymbols = ['AAPL']; if (staleSymbols.length === 0) { this.logger.info('No symbols need filings updates'); return { message: 'No symbols need filings updates', symbolsQueued: 0, - errors: 0 + errors: 0, }; } this.logger.info(`Found ${staleSymbols.length} symbols needing filings updates`); // Get full symbol data to include symbolId - const symbolDocs = await this.mongodb.find('qmSymbols', { - qmSearchCode: { $in: staleSymbols } - }, { - projection: { qmSearchCode: 1, operations: 1, symbol: 1, exchange: 1 } - }); + const symbolDocs = await this.mongodb.find( + 'qmSymbols', + { + qmSearchCode: { $in: staleSymbols }, + }, + { + projection: { qmSearchCode: 1, operations: 1, symbol: 1, exchange: 1 }, + } + ); let queued = 0; let errors = 0; @@ -229,15 +243,19 @@ export async function scheduleFilingsUpdates( // Schedule individual update jobs for each symbol for (const doc of symbolDocs) { try { - await this.scheduleOperation('update-filings', { - symbol: doc.symbol, - exchange: doc.exchange, - qmSearchCode: doc.qmSearchCode, - lastRecordDate: doc.operations?.filings_update?.lastRecordDate || null, - }, { - priority: 5, // Lower priority than financial data - }); - + await this.scheduleOperation( + 'update-filings', + { + symbol: doc.symbol, + exchange: doc.exchange, + qmSearchCode: doc.qmSearchCode, + lastRecordDate: doc.operations?.filings_update?.lastRecordDate || null, + }, + { + priority: 5, // Lower priority than financial data + } + ); + queued++; } catch (error) { this.logger.error(`Failed to schedule filings update for ${doc.symbol}`, { error }); @@ -248,16 +266,16 @@ export async function scheduleFilingsUpdates( this.logger.info('Filings update scheduling completed', { symbolsQueued: queued, errors, - total: staleSymbols.length + total: staleSymbols.length, }); return { message: `Scheduled filings updates for ${queued} symbols`, symbolsQueued: queued, - errors + errors, }; } catch (error) { this.logger.error('Filings scheduling failed', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts index 77f17f2e..60d909dc 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/financials.action.ts @@ -1,8 +1,10 @@ +import type { Document } from 'mongodb'; /** * QM Financials Actions - Fetch and update financial statements */ import type { ExecutionContext } from '@stock-bot/handlers'; +import { defined } from '@stock-bot/invariants'; import type { QMHandler } from '../qm.handler'; import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; import { QMSessionManager } from '../shared/session-manager'; @@ -24,10 +26,10 @@ export async function updateFinancials( success: boolean; qmSearchCode: string; message: string; - data?: any; + data?: unknown; }> { const { symbol, exchange, qmSearchCode, reportType, lastRecordDate } = input; - + this.logger.info('Fetching financials', { symbol, exchange, qmSearchCode }); const sessionManager = QMSessionManager.getInstance(); @@ -36,7 +38,7 @@ export async function updateFinancials( // Get a session - you'll need to add the appropriate session ID for financials const sessionId = QM_SESSION_IDS.FINANCIALS; // TODO: Update with correct session ID const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM financials`); } @@ -69,9 +71,10 @@ export async function updateFinancials( const financialData = await response.json(); let reports = []; - if(Array.isArray(financialData.results.Company)){ //WEIRD BUG ON THEIR END FOR SOME REASON FOR ONE COMP ITS A ARRAY INSTEAD OF OBJECT + if (Array.isArray(financialData.results.Company)) { + //WEIRD BUG ON THEIR END FOR SOME REASON FOR ONE COMP ITS A ARRAY INSTEAD OF OBJECT reports = financialData?.results?.Company[0].Report || []; - }else{ + } else { reports = financialData?.results?.Company.Report || []; } @@ -80,62 +83,74 @@ export async function updateFinancials( // Store financial statements in a separate collection await this.mongodb.batchUpsert( 'qmFinancials-new', - reports.map((statement: any) => ({ + reports.map((statement: Document) => ({ ...statement, symbol, exchange, - qmSearchCode + qmSearchCode, })), ['qmSearchCode', 'reportPeriod', 'reportDate'] // Unique keys ); // Update symbol to track last financials update - await this.operationRegistry.updateOperation('qm', qmSearchCode, `financials_update_${reportType === 'Q'? 'quarterly' : 'annual'}`, { - status: 'success', - lastRecordDate: new Date(), - recordCount: reports.length - }); - - this.logger.info(`Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`, { + await this.operationRegistry.updateOperation( + 'qm', qmSearchCode, - statementCount: reports.length - }); + `financials_update_${reportType === 'Q' ? 'quarterly' : 'annual'}`, + { + status: 'success', + lastRecordDate: new Date(), + recordCount: reports.length, + } + ); + + this.logger.info( + `Financials updated successfully ${reportType} - ${qmSearchCode} (${reports.length})`, + { + qmSearchCode, + statementCount: reports.length, + } + ); return { success: true, qmSearchCode, message: `Financials updated for ${qmSearchCode} - ${reportType} - ${reports.length}`, - data: { count: reports.length } + data: { count: reports.length }, }; } else { this.logger.warn('No financial data returned from API', { qmSearchCode }); return { success: false, qmSearchCode, - message: `No financial data found for symbol ${qmSearchCode}` + message: `No financial data found for symbol ${qmSearchCode}`, }; } - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error fetching financials', { + this.logger.error('Error fetching financials', { symbol, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + // Track failure - await this.operationRegistry.updateOperation('qm', qmSearchCode, `financials_update_${reportType === 'Q'? 'quarterly' : 'annual'}`, { - status: 'failure', - }); - + await this.operationRegistry.updateOperation( + 'qm', + qmSearchCode, + `financials_update_${reportType === 'Q' ? 'quarterly' : 'annual'}`, + { + status: 'failure', + } + ); + return { success: false, qmSearchCode, - message: `Failed to fetch financials: ${error instanceof Error ? error.message : 'Unknown error'}` + message: `Failed to fetch financials: ${error instanceof Error ? error.message : 'Unknown error'}`, }; } } @@ -156,51 +171,64 @@ export async function scheduleFinancialsUpdates( errors: number; }> { const { limit = 100000, forceUpdate = false } = input; - + this.logger.info('Scheduling financials updates', { limit, forceUpdate }); try { // Get symbols that need updating for both quarterly and annual - const staleSymbolsQ = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_quarterly', { - minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default - limit - }); - const staleSymbolsA = await this.operationRegistry.getStaleSymbols('qm', 'financials_update_annual', { - minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default - limit - }); + const staleSymbolsQ = await this.operationRegistry.getStaleSymbols( + 'qm', + 'financials_update_quarterly', + { + minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default + limit, + } + ); + const staleSymbolsA = await this.operationRegistry.getStaleSymbols( + 'qm', + 'financials_update_annual', + { + minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default + limit, + } + ); if (staleSymbolsQ.length === 0 && staleSymbolsA.length === 0) { this.logger.info('No symbols need financials updates'); return { message: 'No symbols need financials updates', symbolsQueued: 0, - errors: 0 + errors: 0, }; } - this.logger.info(`Found ${staleSymbolsQ.length} symbols needing quarterly updates and ${staleSymbolsA.length} symbols needing annual updates`); + this.logger.info( + `Found ${staleSymbolsQ.length} symbols needing quarterly updates and ${staleSymbolsA.length} symbols needing annual updates` + ); // Create a map of symbols needing updates - const symbolsNeedingUpdates = new Map(); - + const symbolsNeedingUpdates = new Map< + string, + { quarterly: boolean; annual: boolean; item: Document } + >(); + // Add quarterly symbols for (const item of staleSymbolsQ) { const key = item.symbol.qmSearchCode; if (!symbolsNeedingUpdates.has(key)) { symbolsNeedingUpdates.set(key, { quarterly: true, annual: false, item }); } else { - symbolsNeedingUpdates.get(key)!.quarterly = true; + defined(symbolsNeedingUpdates.get(key)).quarterly = true; } } - + // Add annual symbols for (const item of staleSymbolsA) { const key = item.symbol.qmSearchCode; if (!symbolsNeedingUpdates.has(key)) { symbolsNeedingUpdates.set(key, { quarterly: false, annual: true, item }); } else { - symbolsNeedingUpdates.get(key)!.annual = true; + defined(symbolsNeedingUpdates.get(key)).annual = true; } } @@ -212,20 +240,26 @@ export async function scheduleFinancialsUpdates( // Schedule quarterly updates if needed if (quarterly) { try { - await this.scheduleOperation('update-financials', { - symbol: item.symbol.symbol, - exchange: item.symbol.exchange, - qmSearchCode: qmSearchCode, - reportType: 'Q', - lastRecordDate: item.operations?.financials_update_quarterly?.lastRecordDate, - }, { - priority: 4, - delay: queued // 1 second between jobs - }); - + await this.scheduleOperation( + 'update-financials', + { + symbol: item.symbol.symbol, + exchange: item.symbol.exchange, + qmSearchCode: qmSearchCode, + reportType: 'Q', + lastRecordDate: item.operations?.financials_update_quarterly?.lastRecordDate, + }, + { + priority: 4, + delay: queued, // 1 second between jobs + } + ); + queued++; } catch (error) { - this.logger.error(`Failed to schedule quarterly financials update for ${qmSearchCode}`, { error }); + this.logger.error(`Failed to schedule quarterly financials update for ${qmSearchCode}`, { + error, + }); errors++; } } @@ -233,20 +267,26 @@ export async function scheduleFinancialsUpdates( // Schedule annual updates if needed if (annual) { try { - await this.scheduleOperation('update-financials', { - symbol: item.symbol.symbol, - exchange: item.symbol.exchange, - qmSearchCode: qmSearchCode, - reportType: 'A', - lastRecordDate: item.operations?.financials_update_annual?.lastRecordDate, - }, { - priority: 4, - delay: queued // 1 second between jobs - }); - + await this.scheduleOperation( + 'update-financials', + { + symbol: item.symbol.symbol, + exchange: item.symbol.exchange, + qmSearchCode: qmSearchCode, + reportType: 'A', + lastRecordDate: item.operations?.financials_update_annual?.lastRecordDate, + }, + { + priority: 4, + delay: queued, // 1 second between jobs + } + ); + queued++; } catch (error) { - this.logger.error(`Failed to schedule annual financials update for ${qmSearchCode}`, { error }); + this.logger.error(`Failed to schedule annual financials update for ${qmSearchCode}`, { + error, + }); errors++; } } @@ -256,16 +296,16 @@ export async function scheduleFinancialsUpdates( symbolsQueued: queued, errors, totalQuarterly: staleSymbolsQ.length, - totalAnnual: staleSymbolsA.length + totalAnnual: staleSymbolsA.length, }); return { message: `Scheduled ${queued} financials updates (${staleSymbolsQ.length} quarterly, ${staleSymbolsA.length} annual)`, symbolsQueued: queued, - errors + errors, }; } catch (error) { this.logger.error('Financials scheduling failed', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/insiders.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/insiders.action.ts index ee2ae8f7..5bba981f 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/insiders.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/insiders.action.ts @@ -1,279 +1,284 @@ -/** - * QM Insiders Actions - Fetch and update insider trading data - */ - -import type { ExecutionContext } from '@stock-bot/handlers'; -import type { QMHandler } from '../qm.handler'; -import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; -import { QMSessionManager } from '../shared/session-manager'; - -/** - * Update insider transactions for a single symbol - */ -export async function updateInsiders( - this: QMHandler, - input: { - symbol: string; - symbolId: number; - qmSearchCode: string; - lookbackDays?: number; - }, - _context?: ExecutionContext -): Promise<{ - success: boolean; - symbol: string; - message: string; - data?: any; -}> { - const { symbol, symbolId, qmSearchCode, lookbackDays = 365 } = input; - - this.logger.info('Fetching insider transactions', { symbol, symbolId, lookbackDays }); - - const sessionManager = QMSessionManager.getInstance(); - await sessionManager.initialize(this.cache, this.logger); - - const sessionId = QM_SESSION_IDS.LOOKUP; - const session = await sessionManager.getSession(sessionId); - - if (!session || !session.uuid) { - throw new Error(`No active session found for QM insiders`); - } - - try { - // Calculate date range - const endDate = new Date(); - const startDate = new Date(); - startDate.setDate(startDate.getDate() - lookbackDays); - - // Build API request for insider transactions - const searchParams = new URLSearchParams({ - symbol: symbol, - symbolId: symbolId.toString(), - qmodTool: 'InsiderActivity', - webmasterId: '500', - startDate: startDate.toISOString().split('T')[0], - endDate: endDate.toISOString().split('T')[0], - includeOptions: 'true', - pageSize: '100' - } as Record); - - const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/insiders.json?${searchParams.toString()}`; - - const response = await fetch(apiUrl, { - method: 'GET', - headers: session.headers, - proxy: session.proxy, - }); - - if (!response.ok) { - throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); - } - - const insiderData = await response.json(); - - // Update session success stats - await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); - - // Process and store insider data - if (insiderData && insiderData.transactions && insiderData.transactions.length > 0) { - const processedTransactions = insiderData.transactions.map((transaction: any) => ({ - symbol, - symbolId, - transactionDate: new Date(transaction.transactionDate), - filingDate: new Date(transaction.filingDate), - insiderName: transaction.insiderName, - insiderTitle: transaction.insiderTitle || 'Unknown', - transactionType: transaction.transactionType, - shares: parseFloat(transaction.shares) || 0, - pricePerShare: parseFloat(transaction.pricePerShare) || 0, - totalValue: parseFloat(transaction.totalValue) || 0, - sharesOwned: parseFloat(transaction.sharesOwned) || 0, - ownershipType: transaction.ownershipType || 'Direct', - formType: transaction.formType || 'Form 4', - transactionCode: transaction.transactionCode, - updated_at: new Date() - })); - - // Store in MongoDB - await this.mongodb.batchUpsert( - 'qmInsiders', - processedTransactions, - ['symbol', 'transactionDate', 'insiderName', 'transactionType'] // Unique keys - ); - - // Calculate summary statistics - const totalBuys = processedTransactions.filter((t: any) => - t.transactionType === 'Buy' || t.transactionType === 'Purchase' - ).length; - - const totalSells = processedTransactions.filter((t: any) => - t.transactionType === 'Sell' || t.transactionType === 'Sale' - ).length; - - const totalBuyValue = processedTransactions - .filter((t: any) => t.transactionType === 'Buy' || t.transactionType === 'Purchase') - .reduce((sum: number, t: any) => sum + t.totalValue, 0); - - const totalSellValue = processedTransactions - .filter((t: any) => t.transactionType === 'Sell' || t.transactionType === 'Sale') - .reduce((sum: number, t: any) => sum + t.totalValue, 0); - - // Update operation tracking - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { - status: 'success', - lastRecordDate: endDate, - recordCount: processedTransactions.length, - metadata: { - totalBuys, - totalSells, - totalBuyValue, - totalSellValue, - netValue: totalBuyValue - totalSellValue, - uniqueInsiders: new Set(processedTransactions.map((t: any) => t.insiderName)).size - } - }); - - this.logger.info('Insider transactions updated successfully', { - symbol, - transactionCount: processedTransactions.length, - totalBuys, - totalSells, - netValue: totalBuyValue - totalSellValue - }); - - return { - success: true, - symbol, - message: `Updated ${processedTransactions.length} insider transactions`, - data: { - count: processedTransactions.length, - totalBuys, - totalSells, - totalBuyValue, - totalSellValue, - netValue: totalBuyValue - totalSellValue - } - }; - } else { - // No insider data - this.logger.info('No insider transactions found', { symbol }); - - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { - status: 'success', - lastRecordDate: endDate, - recordCount: 0 - }); - - return { - success: true, - symbol, - message: 'No insider transactions found', - data: { count: 0 } - }; - } - - } catch (error) { - // Update session failure stats - if (session.uuid) { - await sessionManager.incrementFailedCalls(sessionId, session.uuid); - } - - this.logger.error('Error fetching insider transactions', { - symbol, - error: error instanceof Error ? error.message : 'Unknown error' - }); - - // Update operation tracking for failure - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { - status: 'failure', - error: error instanceof Error ? error.message : 'Unknown error' - }); - - return { - success: false, - symbol, - message: `Failed to fetch insider transactions: ${error instanceof Error ? error.message : 'Unknown error'}` - }; - } -} - -/** - * Schedule insider updates for symbols - */ -export async function scheduleInsidersUpdates( - this: QMHandler, - input: { - limit?: number; - minHoursSinceRun?: number; - forceUpdate?: boolean; - } = {}, - _context?: ExecutionContext -): Promise<{ - message: string; - symbolsQueued: number; - errors: number; -}> { - const { limit = 100, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; - - this.logger.info('Scheduling insider updates', { limit, minHoursSinceRun, forceUpdate }); - - try { - // Get symbols that need insider updates - const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'insiders_update', { - minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, - limit - }); - - if (staleSymbols.length === 0) { - this.logger.info('No symbols need insider updates'); - return { - message: 'No symbols need insider updates', - symbolsQueued: 0, - errors: 0 - }; - } - - this.logger.info(`Found ${staleSymbols.length} symbols for insider updates`); - - let symbolsQueued = 0; - let errors = 0; - - // Schedule update jobs - for (const item of staleSymbols) { - try { - if (!item.symbol.symbolId) { - this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); - continue; - } - - await this.scheduleOperation('update-insiders', { - symbol: item.symbol.symbol, - symbolId: item.symbol.symbolId, - qmSearchCode: item.symbol.qmSearchCode - }, { - priority: 5, // Medium priority - delay: symbolsQueued * 1000 // 1 second between jobs - }); - - symbolsQueued++; - } catch (error) { - this.logger.error(`Failed to schedule insider update for ${item.symbol.symbol}`, { error }); - errors++; - } - } - - this.logger.info('Insider update scheduling completed', { - symbolsQueued, - errors - }); - - return { - message: `Scheduled insider updates for ${symbolsQueued} symbols`, - symbolsQueued, - errors - }; - } catch (error) { - this.logger.error('Insider scheduling failed', { error }); - throw error; - } -} \ No newline at end of file +/** + * QM Insiders Actions - Fetch and update insider trading data + */ + +import type { ExecutionContext } from '@stock-bot/handlers'; +import type { QMHandler } from '../qm.handler'; +import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; +import { QMSessionManager } from '../shared/session-manager'; +import type { QMInsiderTransaction } from '../shared/types'; + +/** + * Update insider transactions for a single symbol + */ +export async function updateInsiders( + this: QMHandler, + input: { + symbol: string; + symbolId: number; + qmSearchCode: string; + lookbackDays?: number; + }, + _context?: ExecutionContext +): Promise<{ + success: boolean; + symbol: string; + message: string; + data?: unknown; +}> { + const { symbol, symbolId, qmSearchCode, lookbackDays = 365 } = input; + + this.logger.info('Fetching insider transactions', { symbol, symbolId, lookbackDays }); + + const sessionManager = QMSessionManager.getInstance(); + await sessionManager.initialize(this.cache, this.logger); + + const sessionId = QM_SESSION_IDS.LOOKUP; + const session = await sessionManager.getSession(sessionId); + + if (!session || !session.uuid) { + throw new Error(`No active session found for QM insiders`); + } + + try { + // Calculate date range + const endDate = new Date(); + const startDate = new Date(); + startDate.setDate(startDate.getDate() - lookbackDays); + + // Build API request for insider transactions + const searchParams = new URLSearchParams({ + symbol: symbol, + symbolId: symbolId.toString(), + qmodTool: 'InsiderActivity', + webmasterId: '500', + startDate: startDate.toISOString().split('T')[0], + endDate: endDate.toISOString().split('T')[0], + includeOptions: 'true', + pageSize: '100', + } as Record); + + const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/insiders.json?${searchParams.toString()}`; + + const response = await fetch(apiUrl, { + method: 'GET', + headers: session.headers, + proxy: session.proxy, + }); + + if (!response.ok) { + throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); + } + + const insiderData = (await response.json()) as { transactions?: QMInsiderTransaction[] }; + + // Update session success stats + await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); + + // Process and store insider data + if (insiderData && insiderData.transactions && insiderData.transactions.length > 0) { + const processedTransactions = insiderData.transactions.map(transaction => ({ + source: 'qm', + symbol, + symbolId, + transactionDate: new Date(transaction.transactionDate), + filingDate: new Date(transaction.filingDate), + insiderName: transaction.insiderName, + insiderTitle: transaction.insiderTitle || 'Unknown', + transactionType: transaction.transactionType, + shares: Number(transaction.shares) || 0, + pricePerShare: Number(transaction.pricePerShare) || 0, + totalValue: Number(transaction.totalValue) || 0, + sharesOwned: Number(transaction.sharesOwned) || 0, + ownershipType: transaction.ownershipType || 'Direct', + formType: transaction.formType || 'Form 4', + transactionCode: transaction.transactionCode, + updated_at: new Date(), + })); + + // Store in MongoDB + await this.mongodb.batchUpsert( + 'qmInsiders', + processedTransactions, + ['symbol', 'transactionDate', 'insiderName', 'transactionType'] // Unique keys + ); + + // Calculate summary statistics + const totalBuys = processedTransactions.filter( + t => t.transactionType === 'Buy' || t.transactionType === 'Purchase' + ).length; + + const totalSells = processedTransactions.filter( + t => t.transactionType === 'Sell' || t.transactionType === 'Sale' + ).length; + + const totalBuyValue = processedTransactions + .filter(t => t.transactionType === 'Buy' || t.transactionType === 'Purchase') + .reduce((sum, t) => sum + t.totalValue, 0); + + const totalSellValue = processedTransactions + .filter(t => t.transactionType === 'Sell' || t.transactionType === 'Sale') + .reduce((sum, t) => sum + t.totalValue, 0); + + // Update operation tracking + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { + status: 'success', + lastRecordDate: endDate, + recordCount: processedTransactions.length, + metadata: { + totalBuys, + totalSells, + totalBuyValue, + totalSellValue, + netValue: totalBuyValue - totalSellValue, + uniqueInsiders: new Set(processedTransactions.map(t => t.insiderName)).size, + }, + }); + + this.logger.info('Insider transactions updated successfully', { + symbol, + transactionCount: processedTransactions.length, + totalBuys, + totalSells, + netValue: totalBuyValue - totalSellValue, + }); + + return { + success: true, + symbol, + message: `Updated ${processedTransactions.length} insider transactions`, + data: { + count: processedTransactions.length, + totalBuys, + totalSells, + totalBuyValue, + totalSellValue, + netValue: totalBuyValue - totalSellValue, + }, + }; + } else { + // No insider data + this.logger.info('No insider transactions found', { symbol }); + + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { + status: 'success', + lastRecordDate: endDate, + recordCount: 0, + }); + + return { + success: true, + symbol, + message: 'No insider transactions found', + data: { count: 0 }, + }; + } + } catch (error) { + // Update session failure stats + if (session.uuid) { + await sessionManager.incrementFailedCalls(sessionId, session.uuid); + } + + this.logger.error('Error fetching insider transactions', { + symbol, + error: error instanceof Error ? error.message : 'Unknown error', + }); + + // Update operation tracking for failure + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'insiders_update', { + status: 'failure', + error: error instanceof Error ? error.message : 'Unknown error', + }); + + return { + success: false, + symbol, + message: `Failed to fetch insider transactions: ${error instanceof Error ? error.message : 'Unknown error'}`, + }; + } +} + +/** + * Schedule insider updates for symbols + */ +export async function scheduleInsidersUpdates( + this: QMHandler, + input: { + limit?: number; + minHoursSinceRun?: number; + forceUpdate?: boolean; + } = {}, + _context?: ExecutionContext +): Promise<{ + message: string; + symbolsQueued: number; + errors: number; +}> { + const { limit = 100, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; + + this.logger.info('Scheduling insider updates', { limit, minHoursSinceRun, forceUpdate }); + + try { + // Get symbols that need insider updates + const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'insiders_update', { + minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, + limit, + }); + + if (staleSymbols.length === 0) { + this.logger.info('No symbols need insider updates'); + return { + message: 'No symbols need insider updates', + symbolsQueued: 0, + errors: 0, + }; + } + + this.logger.info(`Found ${staleSymbols.length} symbols for insider updates`); + + let symbolsQueued = 0; + let errors = 0; + + // Schedule update jobs + for (const item of staleSymbols) { + try { + if (!item.symbol.symbolId) { + this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); + continue; + } + + await this.scheduleOperation( + 'update-insiders', + { + symbol: item.symbol.symbol, + symbolId: item.symbol.symbolId, + qmSearchCode: item.symbol.qmSearchCode, + }, + { + priority: 5, // Medium priority + delay: symbolsQueued * 1000, // 1 second between jobs + } + ); + + symbolsQueued++; + } catch (error) { + this.logger.error(`Failed to schedule insider update for ${item.symbol.symbol}`, { error }); + errors++; + } + } + + this.logger.info('Insider update scheduling completed', { + symbolsQueued, + errors, + }); + + return { + message: `Scheduled insider updates for ${symbolsQueued} symbols`, + symbolsQueued, + errors, + }; + } catch (error) { + this.logger.error('Insider scheduling failed', { error }); + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts index c2e82dee..3d06c982 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts @@ -1,423 +1,425 @@ -/** - * QM Intraday Crawl Actions - Sophisticated crawling with resumption support - */ - -import type { ExecutionContext } from '@stock-bot/handlers'; -import type { CrawlState } from '../../../shared/operation-manager/types'; -import type { QMHandler } from '../qm.handler'; -import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; -import { QMSessionManager } from '../shared/session-manager'; - -interface IntradayCrawlInput { - symbol: string; - exchange: string; - qmSearchCode: string; - targetOldestDate?: string; // ISO date string for how far back to crawl - existingCrawlState?: CrawlState; // Pass existing crawl state to avoid re-querying - gaps?: { forward?: boolean; backward?: boolean }; // Pass gap information -} - - -/** - * Main intraday crawl handler - crawls backwards week by week (Sunday to Sunday) - */ -export async function crawlIntradayData( - this: QMHandler, - input: IntradayCrawlInput, - _context?: ExecutionContext -): Promise<{ - success: boolean; - symbol: string; - exchange: string; - qmSearchCode: string; - message: string; - data?: any; -}> { - const { - symbol, - exchange, - qmSearchCode, - targetOldestDate = '1960-01-01', // Default to ~5 years of data - existingCrawlState, - gaps - } = input; - - this.logger.info('Starting intraday crawl', { - symbol, - exchange, - targetOldestDate, - hasExistingState: !!existingCrawlState, - gaps - }); - - const sessionManager = QMSessionManager.getInstance(); - await sessionManager.initialize(this.cache, this.logger); - - const sessionId = QM_SESSION_IDS.PRICES; - const session = await sessionManager.getSession(sessionId); - - if (!session || !session.uuid) { - throw new Error(`No active session found for QM intraday`); - } - - try { - // Use passed crawl state if available, otherwise query for it - let currentCrawlState: CrawlState; - - if (existingCrawlState) { - currentCrawlState = existingCrawlState; - } else { - // Only query if not passed - const symbolData = await this.mongodb.findOne('qmSymbols', { - qmSearchCode - }); - - currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || { - finished: false - }; - } - - // Determine starting point for crawl - let currentWeek: Date; - if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) { - // Start from oldest date reached - currentWeek = new Date(currentCrawlState.oldestDateReached); - } else if (currentCrawlState.lastProcessedDate) { - // Resume from last processed date - currentWeek = new Date(currentCrawlState.lastProcessedDate); - } else { - // New crawl, start from today - currentWeek = new Date(); - // console.log('Current week before adjustment:', currentWeek); - } - - - // Get the Sunday of the current week - currentWeek = getLastWeek(currentWeek); - - const targetOldest = new Date(targetOldestDate); - targetOldest.setHours(0, 0, 0, 0); - - // Check if already finished - if (currentCrawlState.finished || currentWeek <= targetOldest) { - this.logger.info('Intraday crawl already complete', { symbol }); - return { - success: true, - qmSearchCode, - symbol, - exchange, - message: 'Intraday crawl already complete' - }; - } - - let totalRecords = 0; - let weeksProcessed = 0; - const errors: string[] = []; - - const endOfWeek = new Date(currentWeek) - endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday - // Build API request for the week - const searchParams = new URLSearchParams({ - adjType:'none', - adjusted:'true', - freq:'day', - interval:'1', - marketSession:'mkt', - pathName:'/demo/portal/company-quotes.php', - qmodTool:'InteractiveChart', - start: currentWeek.toISOString().split('T')[0], - end: endOfWeek.toISOString().split('T')[0], // Next Sunday - symbol: qmSearchCode, - unadjusted:'false', - webmasterId:'500', - zeroTradeDays:'false', - } as Record); - - try { - const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, { - method: 'GET', - headers: session.headers, - proxy: session.proxy, - }); - - if (!response.ok) { - throw new Error(`API request failed: ${response.status}`); - } - - const barsResults = await response.json(); - - // Parse the results based on the API response structure - const barsData = barsResults.results?.intraday?.[0]?.interval || null; - const barsLength = barsData !== null ? barsData.length : 0; - this.logger.info(`Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`, { - qmSearchCode, - currentWeek, - records: barsLength - }); - - // Update session success stats - await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); - - // Process and store data if we got any - if (barsData !== null && barsLength > 0) { - const processedBars = barsData.map((bar: any) => ({ - ...bar, - qmSearchCode, - symbol, - exchange, - timestamp: new Date(bar.startdatetime || bar.date || bar.datetime), - })); - - await this.mongodb.batchUpsert( - 'qmIntraday', - processedBars, - ['qmSearchCode', 'timestamp'] - ); - - totalRecords += barsLength; - } - - weeksProcessed = 1; - const nextWeek = getLastWeek(new Date(currentWeek)); - const finished = (barsData === null) && nextWeek < new Date('2024-01-01') - this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { - status: 'success', - crawlState: { - finished: finished, - oldestDateReached: currentCrawlState.oldestDateReached, - lastProcessedDate: currentWeek - } - }); - - // Calculate next week to process (previous Sunday) - - // console.log(barsData === null , existingCrawlState); - if(!finished) { - currentCrawlState.lastProcessedDate = nextWeek; - await this.scheduleOperation('crawl-intraday-data', { - symbol: symbol, - exchange: exchange, - qmSearchCode: qmSearchCode, - targetOldestDate, - // Pass existing crawl state and gaps to avoid re-querying - existingCrawlState: currentCrawlState, - gaps: gaps - }, { - priority: 4, // Standard priority for backward crawls - }); - } - - return { - success: true, - symbol, - exchange, - qmSearchCode, - message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`, - data: { - totalRecords, - weeksProcessed, - nextWeek: nextWeek.toISOString().split('T')[0], - errors: errors.length > 0 ? errors : undefined - } - } - - } catch (error) { - this.logger.error('Intraday crawl failed', { - symbol, - error: error instanceof Error ? error.message : 'Unknown error' - }); - - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { - status: 'failure', - error: error instanceof Error ? error.message : 'Unknown error' - }); - - return { - success: false, - symbol, - exchange, - qmSearchCode, - message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}` - }; - } - }catch (error) { - return { - success: false, - symbol, - exchange, - qmSearchCode, - message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}` - }; - } -} - -/** - * Schedule intraday crawls for multiple symbols - */ -export async function scheduleIntradayCrawls( - this: QMHandler, - input: { - limit?: number; - targetOldestDate?: string; - priorityMode?: 'never_run' | 'incomplete' | 'all'; - } = {}, - _context?: ExecutionContext -): Promise<{ - message: string; - symbolsQueued: number; - errors: number; -}> { - const { - limit = 999999999, - targetOldestDate = '1960-01-01', - priorityMode = 'all' - } = input; - - this.logger.info('Scheduling intraday crawls', { - limit, - targetOldestDate, - priorityMode - }); - - try { - // Get symbols based on priority mode - let symbolsToProcess: any[] = []; - const tracker = this.operationRegistry.getTracker('qm'); - - switch (priorityMode) { - case 'never_run': - // Get symbols that have never been crawled - symbolsToProcess = await this.mongodb.find('qmSymbols', { - 'operations.intraday_bars': { $exists: false }, - active: { $ne: false } - }, { - limit, - projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 } - }); - break; - - case 'incomplete': - // Get symbols with incomplete crawls - symbolsToProcess = await tracker.getSymbolsForIntradayCrawl( - 'intraday_bars', - { - limit, - targetOldestDate: new Date(targetOldestDate), - includeNewDataGaps: false, // Only backward gaps - // symbolFilter: { symbol: 'ETU' } // Filter for testing - } - ); - break; - - - case 'all': - default: - // Get all symbols that need any processing - symbolsToProcess = await tracker.getSymbolsForIntradayCrawl( - 'intraday_bars', - { - limit, - targetOldestDate: new Date(targetOldestDate), - includeNewDataGaps: false, // Only backward gaps since we removed forward crawling - // symbolFilter: { symbol: 'AAPL' } // Filter for testing - } - ); - break; - } - - if (symbolsToProcess.length === 0) { - return { - message: `No symbols found for priority mode: ${priorityMode}`, - symbolsQueued: 0, - errors: 0 - }; - } - - this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', { - count: symbolsToProcess.length, - firstSymbol: symbolsToProcess[0] ? { - symbol: symbolsToProcess[0].symbol, - gaps: symbolsToProcess[0].gaps, - hasOperationStatus: !!symbolsToProcess[0].operationStatus, - crawlState: symbolsToProcess[0].operationStatus?.crawlState - } : null - }); - - // Get full symbol data if needed - if (priorityMode !== 'never_run') { - const qmSearchCodes = symbolsToProcess.map(s => s.symbol); - const fullSymbols = await this.mongodb.find('qmSymbols', { - qmSearchCode: { $in: qmSearchCodes } - }, { - projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 } - }); - - // Map back the full data while preserving gaps and operation status - symbolsToProcess = symbolsToProcess.map(sp => { - const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol); - if (full) { - return { - ...full, - gaps: sp.gaps, // Preserve gap information - operationStatus: sp.operationStatus // Preserve original operation status - }; - } - return sp; - }); - } - - this.logger.info('After mapping, symbols to process', { - count: symbolsToProcess.length, - firstSymbol: symbolsToProcess[0] ? { - symbol: symbolsToProcess[0].symbol, - exchange: symbolsToProcess[0].exchange, - qmSearchCode: symbolsToProcess[0].qmSearchCode, - gaps: symbolsToProcess[0].gaps, - hasOperationStatus: !!symbolsToProcess[0].operationStatus, - crawlState: symbolsToProcess[0].operationStatus?.crawlState - } : null - }); - - let symbolsQueued = 0; - let errors = 0; - - - // Schedule crawl jobs - for (const doc of symbolsToProcess) { - try { - await this.scheduleOperation('crawl-intraday-data', { - symbol: doc.symbol, - exchange: doc.exchange, - qmSearchCode: doc.qmSearchCode, - targetOldestDate, - // Pass existing crawl state and gaps to avoid re-querying - existingCrawlState: doc.operationStatus?.crawlState, - gaps: doc.gaps - }, { - priority: 6, // Standard priority for backward crawls - }); - - symbolsQueued++; - } catch (error) { - this.logger.error(`Failed to schedule intraday crawl for ${doc.symbol}`, { error }); - errors++; - } - } - - this.logger.info('Intraday crawl scheduling completed', { - priorityMode, - symbolsQueued, - errors - }); - - return { - message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`, - symbolsQueued, - errors - }; - - } catch (error) { - this.logger.error('Intraday crawl scheduling failed', { error }); - throw error; - } -} \ No newline at end of file +import type { Document } from 'mongodb'; +/** + * QM Intraday Crawl Actions - Sophisticated crawling with resumption support + */ + +import type { ExecutionContext } from '@stock-bot/handlers'; +import type { OperationStatus } from '../../../shared/operation-manager/types'; +import type { QMHandler } from '../qm.handler'; +import { getLastWeek, QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; +import { QMSessionManager } from '../shared/session-manager'; + +interface IntradayCrawlInput { + symbol: string; + exchange: string; + qmSearchCode: string; + targetOldestDate?: string; // ISO date string for how far back to crawl + existingCrawlState?: Partial; // Pass existing crawl state to avoid re-querying + gaps?: { forward?: boolean; backward?: boolean }; // Pass gap information +} + +/** + * Main intraday crawl handler - crawls backwards week by week (Sunday to Sunday) + */ +export async function crawlIntradayData( + this: QMHandler, + input: IntradayCrawlInput, + _context?: ExecutionContext +): Promise<{ + success: boolean; + symbol: string; + exchange: string; + qmSearchCode: string; + message: string; + data?: unknown; +}> { + const { + symbol, + exchange, + qmSearchCode, + targetOldestDate = '1960-01-01', // Default to ~5 years of data + existingCrawlState, + gaps, + } = input; + + this.logger.info('Starting intraday crawl', { + symbol, + exchange, + targetOldestDate, + hasExistingState: !!existingCrawlState, + gaps, + }); + + const sessionManager = QMSessionManager.getInstance(); + await sessionManager.initialize(this.cache, this.logger); + + const sessionId = QM_SESSION_IDS.PRICES; + const session = await sessionManager.getSession(sessionId); + + if (!session || !session.uuid) { + throw new Error(`No active session found for QM intraday`); + } + + try { + // Use passed crawl state if available, otherwise query for it + let currentCrawlState: Partial; + + if (existingCrawlState) { + currentCrawlState = existingCrawlState; + } else { + // Only query if not passed + const symbolData = await this.mongodb.findOne('qmSymbols', { + qmSearchCode, + }); + + currentCrawlState = symbolData?.operations?.intraday_bars?.crawlState || { + finished: false, + }; + } + + // Determine starting point for crawl + let currentWeek: Date; + if (currentCrawlState.oldestDateReached && !currentCrawlState.finished) { + // Start from oldest date reached + currentWeek = new Date(currentCrawlState.oldestDateReached); + } else if (currentCrawlState.lastProcessedDate) { + // Resume from last processed date + currentWeek = new Date(currentCrawlState.lastProcessedDate); + } else { + // New crawl, start from today + currentWeek = new Date(); + // console.log('Current week before adjustment:', currentWeek); + } + + // Get the Sunday of the current week + currentWeek = getLastWeek(currentWeek); + + const targetOldest = new Date(targetOldestDate); + targetOldest.setHours(0, 0, 0, 0); + + // Check if already finished + if (currentCrawlState.finished || currentWeek <= targetOldest) { + this.logger.info('Intraday crawl already complete', { symbol }); + return { + success: true, + qmSearchCode, + symbol, + exchange, + message: 'Intraday crawl already complete', + }; + } + + let totalRecords = 0; + let weeksProcessed = 0; + const errors: string[] = []; + + const endOfWeek = new Date(currentWeek); + endOfWeek.setDate(endOfWeek.getDate() + 6); // Set to next Saturday + // Build API request for the week + const searchParams = new URLSearchParams({ + adjType: 'none', + adjusted: 'true', + freq: 'day', + interval: '1', + marketSession: 'mkt', + pathName: '/demo/portal/company-quotes.php', + qmodTool: 'InteractiveChart', + start: currentWeek.toISOString().split('T')[0], + end: endOfWeek.toISOString().split('T')[0], // Next Sunday + symbol: qmSearchCode, + unadjusted: 'false', + webmasterId: '500', + zeroTradeDays: 'false', + } as Record); + + try { + const response = await fetch(`${QM_CONFIG.PRICES_URL}?${searchParams.toString()}`, { + method: 'GET', + headers: session.headers, + proxy: session.proxy, + }); + + if (!response.ok) { + throw new Error(`API request failed: ${response.status}`); + } + + const barsResults = await response.json(); + + // Parse the results based on the API response structure + const barsData = barsResults.results?.intraday?.[0]?.interval || null; + const barsLength = barsData !== null ? barsData.length : 0; + this.logger.info( + `Fetched ${barsLength} bars for ${qmSearchCode} for week of ${currentWeek}`, + { + qmSearchCode, + currentWeek, + records: barsLength, + } + ); + + // Update session success stats + await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); + + // Process and store data if we got any + if (barsData !== null && barsLength > 0) { + const processedBars = barsData.map((bar: Document) => ({ + ...bar, + qmSearchCode, + symbol, + exchange, + timestamp: new Date(bar.startdatetime || bar.date || bar.datetime), + })); + + await this.mongodb.batchUpsert('qmIntraday', processedBars, ['qmSearchCode', 'timestamp']); + + totalRecords += barsLength; + } + + weeksProcessed = 1; + const nextWeek = getLastWeek(new Date(currentWeek)); + const finished = barsData === null && nextWeek < new Date('2024-01-01'); + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { + status: 'success', + finished, + oldestDateReached: currentCrawlState.oldestDateReached, + lastProcessedDate: currentWeek, + }); + + // Calculate next week to process (previous Sunday) + + // console.log(barsData === null , existingCrawlState); + if (!finished) { + currentCrawlState.lastProcessedDate = nextWeek; + await this.scheduleOperation( + 'crawl-intraday-data', + { + symbol: symbol, + exchange: exchange, + qmSearchCode: qmSearchCode, + targetOldestDate, + // Pass existing crawl state and gaps to avoid re-querying + existingCrawlState: currentCrawlState, + gaps: gaps, + }, + { + priority: 4, // Standard priority for backward crawls + } + ); + } + + return { + success: true, + symbol, + exchange, + qmSearchCode, + message: `Intraday crawl completed for ${symbol} - Processed ${weeksProcessed} week(s), ${totalRecords} records`, + data: { + totalRecords, + weeksProcessed, + nextWeek: nextWeek.toISOString().split('T')[0], + errors: errors.length > 0 ? errors : undefined, + }, + }; + } catch (error) { + this.logger.error('Intraday crawl failed', { + symbol, + error: error instanceof Error ? error.message : 'Unknown error', + }); + + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'intraday_bars', { + status: 'failure', + error: error instanceof Error ? error.message : 'Unknown error', + }); + + return { + success: false, + symbol, + exchange, + qmSearchCode, + message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`, + }; + } + } catch (error) { + return { + success: false, + symbol, + exchange, + qmSearchCode, + message: `Intraday crawl failed: ${error instanceof Error ? error.message : 'Unknown error'}`, + }; + } +} + +/** + * Schedule intraday crawls for multiple symbols + */ +export async function scheduleIntradayCrawls( + this: QMHandler, + input: { + limit?: number; + targetOldestDate?: string; + priorityMode?: 'never_run' | 'incomplete' | 'all'; + } = {}, + _context?: ExecutionContext +): Promise<{ + message: string; + symbolsQueued: number; + errors: number; +}> { + const { limit = 999999999, targetOldestDate = '1960-01-01', priorityMode = 'all' } = input; + + this.logger.info('Scheduling intraday crawls', { + limit, + targetOldestDate, + priorityMode, + }); + + try { + // Get symbols based on priority mode + let symbolsToProcess: Document[] = []; + const tracker = this.operationRegistry.getTracker('qm'); + + switch (priorityMode) { + case 'never_run': + // Get symbols that have never been crawled + symbolsToProcess = await this.mongodb.find( + 'qmSymbols', + { + 'operations.intraday_bars': { $exists: false }, + active: { $ne: false }, + }, + { + limit, + projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 }, + } + ); + break; + + case 'incomplete': + // Get symbols with incomplete crawls + symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { + limit, + targetOldestDate: new Date(targetOldestDate), + includeNewDataGaps: false, // Only backward gaps + // symbolFilter: { symbol: 'ETU' } // Filter for testing + }); + break; + + case 'all': + default: + // Get all symbols that need any processing + symbolsToProcess = await tracker.getSymbolsForIntradayCrawl('intraday_bars', { + limit, + targetOldestDate: new Date(targetOldestDate), + includeNewDataGaps: false, // Only backward gaps since we removed forward crawling + // symbolFilter: { symbol: 'AAPL' } // Filter for testing + }); + break; + } + + if (symbolsToProcess.length === 0) { + return { + message: `No symbols found for priority mode: ${priorityMode}`, + symbolsQueued: 0, + errors: 0, + }; + } + + this.logger.info('Symbols to process from getSymbolsForIntradayCrawl', { + count: symbolsToProcess.length, + firstSymbol: symbolsToProcess[0] + ? { + symbol: symbolsToProcess[0].symbol, + gaps: symbolsToProcess[0].gaps, + hasOperationStatus: !!symbolsToProcess[0].operationStatus, + crawlState: symbolsToProcess[0].operationStatus?.crawlState, + } + : null, + }); + + // Get full symbol data if needed + if (priorityMode !== 'never_run') { + const qmSearchCodes = symbolsToProcess.map(s => s.symbol); + const fullSymbols = await this.mongodb.find( + 'qmSymbols', + { + qmSearchCode: { $in: qmSearchCodes }, + }, + { + projection: { symbol: 1, exchange: 1, qmSearchCode: 1, operations: 1 }, + } + ); + + // Map back the full data while preserving gaps and operation status + symbolsToProcess = symbolsToProcess.map(sp => { + const full = fullSymbols.find(f => f.qmSearchCode === sp.symbol); + if (full) { + return { + ...full, + gaps: sp.gaps, // Preserve gap information + operationStatus: sp.operationStatus, // Preserve original operation status + }; + } + return sp; + }); + } + + this.logger.info('After mapping, symbols to process', { + count: symbolsToProcess.length, + firstSymbol: symbolsToProcess[0] + ? { + symbol: symbolsToProcess[0].symbol, + exchange: symbolsToProcess[0].exchange, + qmSearchCode: symbolsToProcess[0].qmSearchCode, + gaps: symbolsToProcess[0].gaps, + hasOperationStatus: !!symbolsToProcess[0].operationStatus, + crawlState: symbolsToProcess[0].operationStatus?.crawlState, + } + : null, + }); + + let symbolsQueued = 0; + let errors = 0; + + // Schedule crawl jobs + for (const doc of symbolsToProcess) { + try { + await this.scheduleOperation( + 'crawl-intraday-data', + { + symbol: doc.symbol, + exchange: doc.exchange, + qmSearchCode: doc.qmSearchCode, + targetOldestDate, + // Pass existing crawl state and gaps to avoid re-querying + existingCrawlState: doc.operationStatus?.crawlState, + gaps: doc.gaps, + }, + { + priority: 6, // Standard priority for backward crawls + } + ); + + symbolsQueued++; + } catch (error) { + this.logger.error(`Failed to schedule intraday crawl for ${doc.symbol}`, { error }); + errors++; + } + } + + this.logger.info('Intraday crawl scheduling completed', { + priorityMode, + symbolsQueued, + errors, + }); + + return { + message: `Scheduled ${symbolsQueued} symbols for intraday crawl (${priorityMode} mode)`, + symbolsQueued, + errors, + }; + } catch (error) { + this.logger.error('Intraday crawl scheduling failed', { error }); + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/news.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/news.action.ts index d7073891..b06b4c81 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/news.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/news.action.ts @@ -1,441 +1,438 @@ -/** - * QM News Actions - Fetch symbol-specific and general market news - */ - -import type { ExecutionContext } from '@stock-bot/handlers'; -import type { QMHandler } from '../qm.handler'; -import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; -import { QMSessionManager } from '../shared/session-manager'; - -interface NewsArticle { - id: string; - publishedDate: Date; - title: string; - summary: string; - source: string; - url: string; - symbols?: string[]; - categories?: string[]; - sentiment?: { - score: number; - label: string; // positive, negative, neutral - }; - imageUrl?: string; -} - -/** - * Update news for a single symbol - */ -export async function updateSymbolNews( - this: QMHandler, - input: { - symbol: string; - symbolId: number; - qmSearchCode: string; - lookbackDays?: number; - }, - _context?: ExecutionContext -): Promise<{ - success: boolean; - symbol: string; - message: string; - data?: any; -}> { - const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input; - - this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays }); - - const sessionManager = QMSessionManager.getInstance(); - await sessionManager.initialize(this.cache, this.logger); - - const sessionId = QM_SESSION_IDS.LOOKUP; - const session = await sessionManager.getSession(sessionId); - - if (!session || !session.uuid) { - throw new Error(`No active session found for QM news`); - } - - try { - // Calculate date range - const endDate = new Date(); - const startDate = new Date(); - startDate.setDate(startDate.getDate() - lookbackDays); - - // Build API request for symbol news - const searchParams = new URLSearchParams({ - symbol: symbol, - symbolId: symbolId.toString(), - qmodTool: 'News', - webmasterId: '500', - startDate: startDate.toISOString().split('T')[0], - endDate: endDate.toISOString().split('T')[0], - includeContent: 'true', - pageSize: '50' - } as Record); - - const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`; - - const response = await fetch(apiUrl, { - method: 'GET', - headers: session.headers, - proxy: session.proxy, - }); - - if (!response.ok) { - throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); - } - - const newsData = await response.json(); - - // Update session success stats - await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); - - // Process and store news data - if (newsData && newsData.articles && newsData.articles.length > 0) { - const processedArticles = newsData.articles.map((article: any) => ({ - articleId: article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`, - symbol, - symbolId, - publishedDate: new Date(article.publishedDate), - title: article.title, - summary: article.summary || article.content?.substring(0, 500), - source: article.source || 'Unknown', - url: article.url, - symbols: article.symbols || [symbol], - categories: article.categories || [], - sentiment: article.sentiment ? { - score: parseFloat(article.sentiment.score) || 0, - label: article.sentiment.label || 'neutral' - } : null, - imageUrl: article.imageUrl, - isSymbolSpecific: true, - updated_at: new Date() - })); - - // Store in MongoDB - await this.mongodb.batchUpsert( - 'qmNews', - processedArticles, - ['articleId'] // Unique key - ); - - // Calculate sentiment summary - const sentimentCounts = processedArticles.reduce((acc: any, article: any) => { - if (article.sentiment) { - acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1; - } - return acc; - }, {}); - - // Update operation tracking - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { - status: 'success', - lastRecordDate: endDate, - recordCount: processedArticles.length, - metadata: { - sentimentCounts, - uniqueSources: new Set(processedArticles.map((a: any) => a.source)).size, - avgSentimentScore: processedArticles - .filter((a: any) => a.sentiment?.score) - .reduce((sum: number, a: any, i: number, arr: any[]) => - i === arr.length - 1 ? (sum + a.sentiment.score) / arr.length : sum + a.sentiment.score, 0 - ) - } - }); - - this.logger.info('Symbol news updated successfully', { - symbol, - articleCount: processedArticles.length, - sentimentCounts - }); - - return { - success: true, - symbol, - message: `Updated ${processedArticles.length} news articles`, - data: { - count: processedArticles.length, - sentimentCounts, - sources: new Set(processedArticles.map((a: any) => a.source)).size - } - }; - } else { - // No news found - this.logger.info('No news articles found', { symbol }); - - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { - status: 'success', - lastRecordDate: endDate, - recordCount: 0 - }); - - return { - success: true, - symbol, - message: 'No news articles found', - data: { count: 0 } - }; - } - - } catch (error) { - // Update session failure stats - if (session.uuid) { - await sessionManager.incrementFailedCalls(sessionId, session.uuid); - } - - this.logger.error('Error fetching symbol news', { - symbol, - error: error instanceof Error ? error.message : 'Unknown error' - }); - - // Update operation tracking for failure - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { - status: 'failure', - error: error instanceof Error ? error.message : 'Unknown error' - }); - - return { - success: false, - symbol, - message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}` - }; - } -} - -/** - * Update general market news - */ -export async function updateGeneralNews( - this: QMHandler, - input: { - categories?: string[]; - lookbackMinutes?: number; - } = {}, - _context?: ExecutionContext -): Promise<{ - success: boolean; - message: string; - data?: any; -}> { - const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input; - - this.logger.info('Fetching general news', { categories, lookbackMinutes }); - - const sessionManager = QMSessionManager.getInstance(); - await sessionManager.initialize(this.cache, this.logger); - - const sessionId = QM_SESSION_IDS.LOOKUP; - const session = await sessionManager.getSession(sessionId); - - if (!session || !session.uuid) { - throw new Error(`No active session found for QM general news`); - } - - try { - // Calculate time range - const endDate = new Date(); - const startDate = new Date(); - startDate.setMinutes(startDate.getMinutes() - lookbackMinutes); - - // Build API request for general news - const searchParams = new URLSearchParams({ - qmodTool: 'MarketNews', - webmasterId: '500', - categories: categories.join(','), - startDateTime: startDate.toISOString(), - endDateTime: endDate.toISOString(), - includeContent: 'true', - pageSize: '100' - } as Record); - - const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`; - - const response = await fetch(apiUrl, { - method: 'GET', - headers: session.headers, - proxy: session.proxy, - }); - - if (!response.ok) { - throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); - } - - const newsData = await response.json(); - - // Update session success stats - await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); - - // Process and store general news - if (newsData && newsData.articles && newsData.articles.length > 0) { - const processedArticles = newsData.articles.map((article: any) => ({ - articleId: article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`, - publishedDate: new Date(article.publishedDate), - title: article.title, - summary: article.summary || article.content?.substring(0, 500), - source: article.source || 'Unknown', - url: article.url, - symbols: article.symbols || [], - categories: article.categories || categories, - sentiment: article.sentiment ? { - score: parseFloat(article.sentiment.score) || 0, - label: article.sentiment.label || 'neutral' - } : null, - imageUrl: article.imageUrl, - isSymbolSpecific: false, - isMarketMoving: article.isMarketMoving || false, - importance: article.importance || 'medium', - updated_at: new Date() - })); - - // Store in MongoDB - await this.mongodb.batchUpsert( - 'qmNews', - processedArticles, - ['articleId'] // Unique key - ); - - // Find high-importance articles - const highImportanceCount = processedArticles.filter((a: any) => - a.importance === 'high' || a.isMarketMoving - ).length; - - // Update a general tracking document - await this.mongodb.updateOne( - 'qmOperationStats', - { operation: 'general_news_update' }, - { - $set: { - lastRunAt: new Date(), - lastRecordCount: processedArticles.length, - highImportanceCount, - categories, - updated_at: new Date() - } - }, - { upsert: true } - ); - - this.logger.info('General news updated successfully', { - articleCount: processedArticles.length, - highImportanceCount, - categories - }); - - return { - success: true, - message: `Updated ${processedArticles.length} general news articles`, - data: { - count: processedArticles.length, - highImportanceCount, - categories, - sources: new Set(processedArticles.map((a: any) => a.source)).size - } - }; - } else { - // No news found - this.logger.info('No general news articles found'); - - return { - success: true, - message: 'No general news articles found', - data: { count: 0 } - }; - } - - } catch (error) { - // Update session failure stats - if (session.uuid) { - await sessionManager.incrementFailedCalls(sessionId, session.uuid); - } - - this.logger.error('Error fetching general news', { - error: error instanceof Error ? error.message : 'Unknown error' - }); - - return { - success: false, - message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}` - }; - } -} - -/** - * Schedule symbol news updates - */ -export async function scheduleSymbolNewsUpdates( - this: QMHandler, - input: { - limit?: number; - minHoursSinceRun?: number; - forceUpdate?: boolean; - } = {}, - _context?: ExecutionContext -): Promise<{ - message: string; - symbolsQueued: number; - errors: number; -}> { - const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; - - this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate }); - - try { - // Get symbols that need news updates - const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', { - minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, - limit - }); - - if (staleSymbols.length === 0) { - this.logger.info('No symbols need news updates'); - return { - message: 'No symbols need news updates', - symbolsQueued: 0, - errors: 0 - }; - } - - this.logger.info(`Found ${staleSymbols.length} symbols for news updates`); - - let symbolsQueued = 0; - let errors = 0; - - // Schedule update jobs - for (const item of staleSymbols) { - try { - if (!item.symbol.symbolId) { - this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); - continue; - } - - await this.scheduleOperation('update-symbol-news', { - symbol: item.symbol.symbol, - symbolId: item.symbol.symbolId, - qmSearchCode: item.symbol.qmSearchCode - }, { - priority: 4, // Lower priority than price data - delay: symbolsQueued * 500 // 0.5 seconds between jobs - }); - - symbolsQueued++; - } catch (error) { - this.logger.error(`Failed to schedule news update for ${item.symbol.symbol}`, { error }); - errors++; - } - } - - this.logger.info('Symbol news update scheduling completed', { - symbolsQueued, - errors - }); - - return { - message: `Scheduled news updates for ${symbolsQueued} symbols`, - symbolsQueued, - errors - }; - } catch (error) { - this.logger.error('Symbol news scheduling failed', { error }); - throw error; - } -} \ No newline at end of file +/** + * QM News Actions - Fetch symbol-specific and general market news + */ + +import type { ExecutionContext } from '@stock-bot/handlers'; +import type { QMHandler } from '../qm.handler'; +import { QM_CONFIG, QM_SESSION_IDS } from '../shared/config'; +import { QMSessionManager } from '../shared/session-manager'; +import type { QMNewsArticle } from '../shared/types'; + +/** + * Update news for a single symbol + */ +export async function updateSymbolNews( + this: QMHandler, + input: { + symbol: string; + symbolId: number; + qmSearchCode: string; + lookbackDays?: number; + }, + _context?: ExecutionContext +): Promise<{ + success: boolean; + symbol: string; + message: string; + data?: unknown; +}> { + const { symbol, symbolId, qmSearchCode, lookbackDays = 30 } = input; + + this.logger.info('Fetching symbol news', { symbol, symbolId, lookbackDays }); + + const sessionManager = QMSessionManager.getInstance(); + await sessionManager.initialize(this.cache, this.logger); + + const sessionId = QM_SESSION_IDS.LOOKUP; + const session = await sessionManager.getSession(sessionId); + + if (!session || !session.uuid) { + throw new Error(`No active session found for QM news`); + } + + try { + // Calculate date range + const endDate = new Date(); + const startDate = new Date(); + startDate.setDate(startDate.getDate() - lookbackDays); + + // Build API request for symbol news + const searchParams = new URLSearchParams({ + symbol: symbol, + symbolId: symbolId.toString(), + qmodTool: 'News', + webmasterId: '500', + startDate: startDate.toISOString().split('T')[0], + endDate: endDate.toISOString().split('T')[0], + includeContent: 'true', + pageSize: '50', + } as Record); + + const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/news.json?${searchParams.toString()}`; + + const response = await fetch(apiUrl, { + method: 'GET', + headers: session.headers, + proxy: session.proxy, + }); + + if (!response.ok) { + throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); + } + + const newsData = (await response.json()) as { articles?: QMNewsArticle[] }; + + // Update session success stats + await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); + + // Process and store news data + if (newsData && newsData.articles && newsData.articles.length > 0) { + const processedArticles = newsData.articles.map(article => ({ + articleId: + article.id || `${symbol}_${article.publishedDate}_${article.title.substring(0, 20)}`, + symbol, + symbolId, + publishedDate: new Date(article.publishedDate), + title: article.title, + summary: article.summary || article.content?.substring(0, 500), + source: article.source || 'Unknown', + url: article.url, + symbols: article.symbols || [symbol], + categories: article.categories || [], + sentiment: article.sentiment + ? { + score: Number(article.sentiment.score) || 0, + label: article.sentiment.label || 'neutral', + } + : null, + imageUrl: article.imageUrl, + isSymbolSpecific: true, + updated_at: new Date(), + })); + + // Store in MongoDB + await this.mongodb.batchUpsert( + 'qmNews', + processedArticles, + ['articleId'] // Unique key + ); + + // Calculate sentiment summary + const sentimentCounts = processedArticles.reduce>((acc, article) => { + if (article.sentiment) { + acc[article.sentiment.label] = (acc[article.sentiment.label] || 0) + 1; + } + return acc; + }, {}); + + // Update operation tracking + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { + status: 'success', + lastRecordDate: endDate, + recordCount: processedArticles.length, + metadata: { + sentimentCounts, + uniqueSources: new Set(processedArticles.map(a => a.source)).size, + avgSentimentScore: processedArticles + .filter(a => a.sentiment?.score) + .reduce( + (sum, a, i, arr) => + i === arr.length - 1 + ? (sum + (a.sentiment?.score ?? 0)) / arr.length + : sum + (a.sentiment?.score ?? 0), + 0 + ), + }, + }); + + this.logger.info('Symbol news updated successfully', { + symbol, + articleCount: processedArticles.length, + sentimentCounts, + }); + + return { + success: true, + symbol, + message: `Updated ${processedArticles.length} news articles`, + data: { + count: processedArticles.length, + sentimentCounts, + sources: new Set(processedArticles.map(a => a.source)).size, + }, + }; + } else { + // No news found + this.logger.info('No news articles found', { symbol }); + + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { + status: 'success', + lastRecordDate: endDate, + recordCount: 0, + }); + + return { + success: true, + symbol, + message: 'No news articles found', + data: { count: 0 }, + }; + } + } catch (error) { + // Update session failure stats + if (session.uuid) { + await sessionManager.incrementFailedCalls(sessionId, session.uuid); + } + + this.logger.error('Error fetching symbol news', { + symbol, + error: error instanceof Error ? error.message : 'Unknown error', + }); + + // Update operation tracking for failure + await this.operationRegistry.updateOperation('qm', qmSearchCode, 'news_update', { + status: 'failure', + error: error instanceof Error ? error.message : 'Unknown error', + }); + + return { + success: false, + symbol, + message: `Failed to fetch news: ${error instanceof Error ? error.message : 'Unknown error'}`, + }; + } +} + +/** + * Update general market news + */ +export async function updateGeneralNews( + this: QMHandler, + input: { + categories?: string[]; + lookbackMinutes?: number; + } = {}, + _context?: ExecutionContext +): Promise<{ + success: boolean; + message: string; + data?: unknown; +}> { + const { categories = ['market', 'economy', 'politics'], lookbackMinutes = 60 } = input; + + this.logger.info('Fetching general news', { categories, lookbackMinutes }); + + const sessionManager = QMSessionManager.getInstance(); + await sessionManager.initialize(this.cache, this.logger); + + const sessionId = QM_SESSION_IDS.LOOKUP; + const session = await sessionManager.getSession(sessionId); + + if (!session || !session.uuid) { + throw new Error(`No active session found for QM general news`); + } + + try { + // Calculate time range + const endDate = new Date(); + const startDate = new Date(); + startDate.setMinutes(startDate.getMinutes() - lookbackMinutes); + + // Build API request for general news + const searchParams = new URLSearchParams({ + qmodTool: 'MarketNews', + webmasterId: '500', + categories: categories.join(','), + startDateTime: startDate.toISOString(), + endDateTime: endDate.toISOString(), + includeContent: 'true', + pageSize: '100', + } as Record); + + const apiUrl = `${QM_CONFIG.BASE_URL}/datatool/marketnews.json?${searchParams.toString()}`; + + const response = await fetch(apiUrl, { + method: 'GET', + headers: session.headers, + proxy: session.proxy, + }); + + if (!response.ok) { + throw new Error(`QM API request failed: ${response.status} ${response.statusText}`); + } + + const newsData = (await response.json()) as { articles?: QMNewsArticle[] }; + + // Update session success stats + await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); + + // Process and store general news + if (newsData && newsData.articles && newsData.articles.length > 0) { + const processedArticles = newsData.articles.map(article => ({ + articleId: + article.id || `general_${article.publishedDate}_${article.title.substring(0, 20)}`, + publishedDate: new Date(article.publishedDate), + title: article.title, + summary: article.summary || article.content?.substring(0, 500), + source: article.source || 'Unknown', + url: article.url, + symbols: article.symbols || [], + categories: article.categories || categories, + sentiment: article.sentiment + ? { + score: Number(article.sentiment.score) || 0, + label: article.sentiment.label || 'neutral', + } + : null, + imageUrl: article.imageUrl, + isSymbolSpecific: false, + isMarketMoving: article.isMarketMoving || false, + importance: article.importance || 'medium', + updated_at: new Date(), + })); + + // Store in MongoDB + await this.mongodb.batchUpsert( + 'qmNews', + processedArticles, + ['articleId'] // Unique key + ); + + // Find high-importance articles + const highImportanceCount = processedArticles.filter( + a => a.importance === 'high' || a.isMarketMoving + ).length; + + // Update a general tracking document + await this.mongodb.updateOne( + 'qmOperationStats', + { operation: 'general_news_update' }, + { + $set: { + lastRunAt: new Date(), + lastRecordCount: processedArticles.length, + highImportanceCount, + categories, + updated_at: new Date(), + }, + }, + { upsert: true } + ); + + this.logger.info('General news updated successfully', { + articleCount: processedArticles.length, + highImportanceCount, + categories, + }); + + return { + success: true, + message: `Updated ${processedArticles.length} general news articles`, + data: { + count: processedArticles.length, + highImportanceCount, + categories, + sources: new Set(processedArticles.map(a => a.source)).size, + }, + }; + } else { + // No news found + this.logger.info('No general news articles found'); + + return { + success: true, + message: 'No general news articles found', + data: { count: 0 }, + }; + } + } catch (error) { + // Update session failure stats + if (session.uuid) { + await sessionManager.incrementFailedCalls(sessionId, session.uuid); + } + + this.logger.error('Error fetching general news', { + error: error instanceof Error ? error.message : 'Unknown error', + }); + + return { + success: false, + message: `Failed to fetch general news: ${error instanceof Error ? error.message : 'Unknown error'}`, + }; + } +} + +/** + * Schedule symbol news updates + */ +export async function scheduleSymbolNewsUpdates( + this: QMHandler, + input: { + limit?: number; + minHoursSinceRun?: number; + forceUpdate?: boolean; + } = {}, + _context?: ExecutionContext +): Promise<{ + message: string; + symbolsQueued: number; + errors: number; +}> { + const { limit = 200, minHoursSinceRun = 24 * 7, forceUpdate = false } = input; + + this.logger.info('Scheduling symbol news updates', { limit, minHoursSinceRun, forceUpdate }); + + try { + // Get symbols that need news updates + const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'news_update', { + minHoursSinceRun: forceUpdate ? 0 : minHoursSinceRun, + limit, + }); + + if (staleSymbols.length === 0) { + this.logger.info('No symbols need news updates'); + return { + message: 'No symbols need news updates', + symbolsQueued: 0, + errors: 0, + }; + } + + this.logger.info(`Found ${staleSymbols.length} symbols for news updates`); + + let symbolsQueued = 0; + let errors = 0; + + // Schedule update jobs + for (const item of staleSymbols) { + try { + if (!item.symbol.symbolId) { + this.logger.warn(`Symbol ${item.symbol.symbol} missing symbolId, skipping`); + continue; + } + + await this.scheduleOperation( + 'update-symbol-news', + { + symbol: item.symbol.symbol, + symbolId: item.symbol.symbolId, + qmSearchCode: item.symbol.qmSearchCode, + }, + { + priority: 4, // Lower priority than price data + delay: symbolsQueued * 500, // 0.5 seconds between jobs + } + ); + + symbolsQueued++; + } catch (error) { + this.logger.error(`Failed to schedule news update for ${item.symbol.symbol}`, { error }); + errors++; + } + } + + this.logger.info('Symbol news update scheduling completed', { + symbolsQueued, + errors, + }); + + return { + message: `Scheduled news updates for ${symbolsQueued} symbols`, + symbolsQueued, + errors, + }; + } catch (error) { + this.logger.error('Symbol news scheduling failed', { error }); + throw error; + } +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts index 0406ba73..b92b0ee9 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts @@ -1,3 +1,4 @@ +import type { Document } from 'mongodb'; /** * QM Prices Actions - Fetch and update daily price data */ @@ -23,10 +24,10 @@ export async function updatePrices( success: boolean; qmSearchCode: string; message: string; - data?: any; + data?: unknown; }> { const { qmSearchCode, lastRecordDate, symbol, exchange } = input; - + this.logger.info(`Fetching daily prices ${qmSearchCode}`, { qmSearchCode }); const sessionManager = QMSessionManager.getInstance(); @@ -35,7 +36,7 @@ export async function updatePrices( // Get a session - you'll need to add the appropriate session ID for prices const sessionId = QM_SESSION_IDS.PRICES; const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM prices`); } @@ -43,16 +44,18 @@ export async function updatePrices( try { // Build API request for daily prices const searchParams = new URLSearchParams({ - zeroTradeDays: 'false', - start: lastRecordDate ? new Date(lastRecordDate).toISOString().split('T')[0] + '' : '1960-01-01', - interval: '1', - marketSession: 'mkt', - freq: 'day', - adjusted: 'false', - adjustmentType: 'none', - unadjusted: 'true', - datatype: 'eod', - symbol: qmSearchCode, + zeroTradeDays: 'false', + start: lastRecordDate + ? new Date(lastRecordDate).toISOString().split('T')[0] + '' + : '1960-01-01', + interval: '1', + marketSession: 'mkt', + freq: 'day', + adjusted: 'false', + adjustmentType: 'none', + unadjusted: 'true', + datatype: 'eod', + symbol: qmSearchCode, }); // https://app.quotemedia.com/datatool/getEnhancedChartData.json?zeroTradeDays=false&start=2025-06-22&interval=1&marketSession=mkt&freq=day&adjusted=true&adjustmentType=none&unadjusted=false&datatype=int&symbol=AAPL // TODO: Update with correct prices endpoint @@ -72,26 +75,26 @@ export async function updatePrices( // Update session success stats await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); // Update symbol to track last price update - + const priceData = responseData.results?.history[0].eoddata || []; - - if(!priceData || priceData.length === 0) { + + if (!priceData || priceData.length === 0) { this.logger.warn(`No price data found for symbol ${qmSearchCode}`); await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { status: 'success', - recordCount: priceData.length + recordCount: priceData.length, }); return { success: false, qmSearchCode, - message: `No price data found for symbol ${qmSearchCode}` + message: `No price data found for symbol ${qmSearchCode}`, }; } // Process and store price data if (priceData && priceData.length > 0) { // Store prices in a separate collection - const processedPrices = priceData.map((price: any) => ({ + const processedPrices = priceData.map((price: Document) => ({ ...price, symbol, exchange, @@ -106,62 +109,60 @@ export async function updatePrices( ); // Find the latest price date - const latestDate = processedPrices.reduce((latest: Date, price: any) => - price.dateTime > latest ? price.dateTime : latest, + const latestDate = processedPrices.reduce( + (latest: Date, price: Document) => (price.dateTime > latest ? price.dateTime : latest), new Date(0) ); - await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { status: 'success', lastRecordDate: latestDate, - recordCount: priceData.length + recordCount: priceData.length, }); - this.logger.info('Prices updated successfully', { + this.logger.info('Prices updated successfully', { qmSearchCode, priceCount: priceData.length, - latestDate + latestDate, }); return { success: true, qmSearchCode, message: `Prices updated for ${qmSearchCode}`, - data: { + data: { count: priceData.length, - latestDate - } + latestDate, + }, }; } else { this.logger.warn('No price data returned from API', { qmSearchCode }); return { success: false, qmSearchCode, - message: `No price data found for qmSearchCode ${qmSearchCode}` + message: `No price data found for qmSearchCode ${qmSearchCode}`, }; } - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error fetching prices', { + this.logger.error('Error fetching prices', { qmSearchCode, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + // Track failure await this.operationRegistry.updateOperation('qm', qmSearchCode, 'price_update', { - status: 'failure' + status: 'failure', }); - + return { success: false, qmSearchCode, - message: `Failed to fetch prices: ${error instanceof Error ? error.message : 'Unknown error'}` + message: `Failed to fetch prices: ${error instanceof Error ? error.message : 'Unknown error'}`, }; } } @@ -182,14 +183,14 @@ export async function schedulePriceUpdates( errors: number; }> { const { limit = 50000, forceUpdate = false } = input; - + this.logger.info('Scheduling price updates', { limit, forceUpdate }); try { // Get symbols that need updating const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'price_update', { minHoursSinceRun: forceUpdate ? 0 : 24, // Daily updates - limit + limit, }); if (staleSymbols.length === 0) { @@ -197,7 +198,7 @@ export async function schedulePriceUpdates( return { message: 'No symbols need price updates', symbolsQueued: 0, - errors: 0 + errors: 0, }; } @@ -209,19 +210,25 @@ export async function schedulePriceUpdates( // Schedule individual update jobs for each symbol for (const item of staleSymbols) { try { - await this.scheduleOperation('update-prices', { - qmSearchCode: item.symbol.qmSearchCode, - lastRecordDate: item.operations?.price_update?.lastRecordDate, - symbol: item.symbol.symbol, - exchange: item.symbol.exchange - }, { - priority: 7, // High priority for price data - delay: queued * 100 // 0.1 seconds between jobs - }); - + await this.scheduleOperation( + 'update-prices', + { + qmSearchCode: item.symbol.qmSearchCode, + lastRecordDate: item.operations?.price_update?.lastRecordDate, + symbol: item.symbol.symbol, + exchange: item.symbol.exchange, + }, + { + priority: 7, // High priority for price data + delay: queued * 100, // 0.1 seconds between jobs + } + ); + queued++; } catch (error) { - this.logger.error(`Failed to schedule price update for ${item.symbol.qmSearchCode}`, { error }); + this.logger.error(`Failed to schedule price update for ${item.symbol.qmSearchCode}`, { + error, + }); errors++; } } @@ -229,16 +236,16 @@ export async function schedulePriceUpdates( this.logger.info('Price update scheduling completed', { symbolsQueued: queued, errors, - total: staleSymbols.length + total: staleSymbols.length, }); return { message: `Scheduled price updates for ${queued} symbols`, symbolsQueued: queued, - errors + errors, }; } catch (error) { this.logger.error('Price scheduling failed', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts index 64d8a426..b46321b5 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts @@ -1,3 +1,4 @@ +import type { Document } from 'mongodb'; /** * QM Symbol Deduplication and Exchange Statistics * - Updates exchange statistics (symbol count, market cap) @@ -6,6 +7,7 @@ */ import type { ExecutionContext } from '@stock-bot/handlers'; +import { at, defined } from '@stock-bot/invariants'; import type { QMHandler } from '../qm.handler'; import type { ExchangeStats } from '../shared/types'; @@ -14,26 +16,26 @@ import type { ExchangeStats } from '../shared/types'; */ const EXCHANGE_PRIORITIES: Record = { // Major US exchanges - 'NYSE': 10, - 'NASDAQ': 10, + NYSE: 10, + NASDAQ: 10, 'NYSE American': 9, - + // Other US exchanges - 'EDGX': 5, - 'BZX': 5, - 'ARCA': 5, - + EDGX: 5, + BZX: 5, + ARCA: 5, + // Canadian main exchanges - 'TSX': 8, - 'TSXV': 8, - 'CSE': 7, - + TSX: 8, + TSXV: 8, + CSE: 7, + // Canadian quote exchanges 'CCQ TSX': 3, 'CCQ TSXV': 3, - + // Default for others - 'default': 1 + default: 1, }; /** @@ -41,7 +43,7 @@ const EXCHANGE_PRIORITIES: Record = { */ export async function updateExchangeStats( this: QMHandler, - _input: any, + _input: unknown, _context: ExecutionContext ): Promise<{ message: string; exchangesUpdated: number }> { this.logger.info('Updating exchange statistics'); @@ -49,32 +51,32 @@ export async function updateExchangeStats( try { // Get all exchanges const exchanges = await this.mongodb.find('qmExchanges', {}); - + if (!exchanges || exchanges.length === 0) { return { message: 'No exchanges found', exchangesUpdated: 0 }; } // Calculate stats for each exchange const bulkOps = []; - + for (const exchange of exchanges) { // Get symbol statistics for this exchange - const stats = await this.mongodb.aggregate('qmSymbols', [ + const stats = await this.mongodb.aggregate('qmSymbols', [ { $match: { exchange: exchange.exchange } }, { $group: { _id: null, symbolCount: { $sum: 1 }, totalMarketCap: { $sum: { $ifNull: ['$marketCap', 0] } }, - avgMarketCap: { $avg: { $ifNull: ['$marketCap', 0] } } - } - } + avgMarketCap: { $avg: { $ifNull: ['$marketCap', 0] } }, + }, + }, ]); const exchangeStats: ExchangeStats = stats[0] || { symbolCount: 0, totalMarketCap: 0, - avgMarketCap: 0 + avgMarketCap: 0, }; // Get priority for this exchange @@ -90,10 +92,10 @@ export async function updateExchangeStats( 'stats.totalMarketCap': exchangeStats.totalMarketCap, 'stats.avgMarketCap': Math.round(exchangeStats.avgMarketCap), priority, - updated_at: new Date() - } - } - } + updated_at: new Date(), + }, + }, + }, }); } @@ -103,13 +105,11 @@ export async function updateExchangeStats( await collection.bulkWrite(bulkOps); } - this.logger.info(`Updated statistics for ${exchanges.length} exchanges`); - return { - message: `Updated statistics for ${exchanges.length} exchanges`, - exchangesUpdated: exchanges.length + return { + message: `Updated statistics for ${exchanges.length} exchanges`, + exchangesUpdated: exchanges.length, }; - } catch (error) { this.logger.error('Failed to update exchange statistics', { error }); throw error; @@ -121,7 +121,7 @@ export async function updateExchangeStats( */ export async function deduplicateSymbols( this: QMHandler, - _input: any, + _input: unknown, _context: ExecutionContext ): Promise<{ message: string; symbolsProcessed: number; deactivated: number }> { this.logger.info('Starting symbol deduplication'); @@ -138,11 +138,11 @@ export async function deduplicateSymbols( exchange: '$exchange', countryCode: '$countryCode', marketCap: { $ifNull: ['$marketCap', 0] }, - _id: '$_id' - } - } - } - } + _id: '$_id', + }, + }, + }, + }, ]); let totalProcessed = 0; @@ -150,9 +150,13 @@ export async function deduplicateSymbols( const bulkOps = []; // Get exchange priorities for sorting - const exchangePriorities = await this.mongodb.find('qmExchanges', {}, { - projection: { exchange: 1, priority: 1 } - }); + const exchangePriorities = await this.mongodb.find( + 'qmExchanges', + {}, + { + projection: { exchange: 1, priority: 1 }, + } + ); const priorityMap = new Map(exchangePriorities.map(e => [e.exchange, e.priority || 1])); for (const group of symbolGroups) { @@ -160,13 +164,13 @@ export async function deduplicateSymbols( const documents = group.symbols; // Group by country - const byCountry = new Map(); + const byCountry = new Map(); for (const doc of documents) { const country = doc.countryCode || 'UNKNOWN'; if (!byCountry.has(country)) { byCountry.set(country, []); } - byCountry.get(country)!.push(doc); + defined(byCountry.get(country)).push(doc); } // Process each country separately @@ -175,9 +179,9 @@ export async function deduplicateSymbols( // Only one symbol in this country, mark as active bulkOps.push({ updateOne: { - filter: { _id: countryDocs[0]._id }, - update: { $set: { active: true } } - } + filter: { _id: at(countryDocs, 0)._id }, + update: { $set: { active: true } }, + }, }); totalProcessed++; continue; @@ -201,10 +205,12 @@ export async function deduplicateSymbols( countryDocs.sort((a, b) => { const priorityA = priorityMap.get(a.exchange) || 1; const priorityB = priorityMap.get(b.exchange) || 1; - if (priorityA !== priorityB) { return priorityB - priorityA } + if (priorityA !== priorityB) { + return priorityB - priorityA; + } return (b.marketCap || 0) - (a.marketCap || 0); }); - activeDoc = countryDocs[0]; + activeDoc = at(countryDocs, 0); } // Mark active and inactive documents @@ -213,11 +219,13 @@ export async function deduplicateSymbols( bulkOps.push({ updateOne: { filter: { _id: doc._id }, - update: { $set: { active: isActive } } - } + update: { $set: { active: isActive } }, + }, }); totalProcessed++; - if (!isActive) { totalDeactivated++ } + if (!isActive) { + totalDeactivated++; + } } } } @@ -228,14 +236,14 @@ export async function deduplicateSymbols( await collection.bulkWrite(bulkOps, { ordered: false }); } - - this.logger.info(`Deduplication complete: processed ${totalProcessed} symbols, deactivated ${totalDeactivated}`); + this.logger.info( + `Deduplication complete: processed ${totalProcessed} symbols, deactivated ${totalDeactivated}` + ); return { message: `Processed ${totalProcessed} symbols, deactivated ${totalDeactivated} duplicates`, symbolsProcessed: totalProcessed, - deactivated: totalDeactivated + deactivated: totalDeactivated, }; - } catch (error) { this.logger.error('Failed to deduplicate symbols', { error }); throw error; @@ -247,7 +255,7 @@ export async function deduplicateSymbols( */ export async function updateExchangeStatsAndDeduplicate( this: QMHandler, - input: any, + input: { exchange?: string; country?: string }, context: ExecutionContext ): Promise<{ message: string }> { this.logger.info('Running exchange stats update and symbol deduplication'); @@ -255,15 +263,15 @@ export async function updateExchangeStatsAndDeduplicate( try { // First update exchange stats const statsResult = await updateExchangeStats.call(this, input, context); - + // Then deduplicate symbols const dedupResult = await deduplicateSymbols.call(this, input, context); return { - message: `${statsResult.message}. ${dedupResult.message}` + message: `${statsResult.message}. ${dedupResult.message}`, }; } catch (error) { this.logger.error('Failed to update stats and deduplicate', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-info.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-info.action.ts index fa69a64c..377d488e 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-info.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol-info.action.ts @@ -21,10 +21,10 @@ export async function updateSymbolInfo( success: boolean; qmSearchCode: string; message: string; - data?: any; + data?: unknown; }> { const { qmSearchCode } = input; - + this.logger.info(`Fetching symbol info ${qmSearchCode}`, { qmSearchCode }); const sessionManager = QMSessionManager.getInstance(); @@ -33,7 +33,7 @@ export async function updateSymbolInfo( // Get a session const sessionId = QM_SESSION_IDS.SYMBOL; const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM LOOKUP`); } @@ -48,7 +48,7 @@ export async function updateSymbolInfo( pathName: '/demo/portal/company-summary.php', webmasterId: '500', } as Record); - + const apiUrl = `${QM_CONFIG.SYMBOL_URL}?${searchParams.toString()}`; const response = await fetch(apiUrl, { method: 'GET', @@ -61,23 +61,26 @@ export async function updateSymbolInfo( } const symbolData = await response.json(); - + // Update session success stats await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); // Process and store symbol info - if (symbolData && Array.isArray(symbolData?.results?.company) && symbolData?.results?.company.length > 0) { - + if ( + symbolData && + Array.isArray(symbolData?.results?.company) && + symbolData?.results?.company.length > 0 + ) { // Update symbol in database with new metadata const updateData = { qmSearchCode: qmSearchCode, profile: symbolData?.results?.company[0].profile, symbolInfo: symbolData?.results?.company[0].symbolinfo, - } + }; await this.mongodb.updateOne( 'qmSymbols', - { qmSearchCode, }, + { qmSearchCode }, { $set: updateData }, { upsert: true } ); @@ -85,10 +88,10 @@ export async function updateSymbolInfo( // Update operation tracking await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', { status: 'success', - lastRecordDate: new Date() + lastRecordDate: new Date(), }); - this.logger.info(`Symbol info updated successfully ${qmSearchCode}`, { + this.logger.info(`Symbol info updated successfully ${qmSearchCode}`, { qmSearchCode, }); @@ -102,30 +105,29 @@ export async function updateSymbolInfo( return { success: false, qmSearchCode, - message: `No data found for symbol ${qmSearchCode}` + message: `No data found for symbol ${qmSearchCode}`, }; } - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error fetching symbol info', { + this.logger.error('Error fetching symbol info', { qmSearchCode, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + // Update operation tracking for failure await this.operationRegistry.updateOperation('qm', qmSearchCode, 'symbol_info', { - status: 'failure' + status: 'failure', }); - + return { success: false, qmSearchCode, - message: `Failed to fetch symbol info: ${error instanceof Error ? error.message : 'Unknown error'}` + message: `Failed to fetch symbol info: ${error instanceof Error ? error.message : 'Unknown error'}`, }; } } @@ -147,14 +149,14 @@ export async function scheduleSymbolInfoUpdates( errors: number; }> { const { limit = 100000, forceUpdate = false } = input; - + this.logger.info('Scheduling symbol info updates', { limit, forceUpdate }); try { // Get symbols that need updating const staleSymbols = await this.operationRegistry.getStaleSymbols('qm', 'symbol_info', { minHoursSinceRun: forceUpdate ? 0 : 24 * 7, // Weekly by default - limit + limit, }); if (staleSymbols.length === 0) { @@ -162,7 +164,7 @@ export async function scheduleSymbolInfoUpdates( return { message: 'No symbols need info updates', symbolsQueued: 0, - errors: 0 + errors: 0, }; } @@ -174,14 +176,18 @@ export async function scheduleSymbolInfoUpdates( // Schedule individual update jobs for each symbol for (const item of staleSymbols) { try { - await this.scheduleOperation('update-symbol-info', { - qmSearchCode: item.symbol.qmSearchCode - }, { - // priority: 3, - // Add some delay to avoid overwhelming the API - // delay: queued * 1000 // 1 second between jobs - }); - + await this.scheduleOperation( + 'update-symbol-info', + { + qmSearchCode: item.symbol.qmSearchCode, + }, + { + // priority: 3, + // Add some delay to avoid overwhelming the API + // delay: queued * 1000 // 1 second between jobs + } + ); + queued++; } catch (error) { this.logger.error(`Failed to schedule update for ${item.symbol.qmSearchCode}`, { error }); @@ -192,16 +198,16 @@ export async function scheduleSymbolInfoUpdates( this.logger.info('Symbol info update scheduling completed', { symbolsQueued: queued, errors, - total: staleSymbols.length + total: staleSymbols.length, }); return { message: `Scheduled info updates for ${queued} symbols`, symbolsQueued: queued, - errors + errors, }; } catch (error) { this.logger.error('Symbol info scheduling failed', { error }); throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol.action.ts b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol.action.ts index 3adb18a6..a7e784c8 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/actions/symbol.action.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/actions/symbol.action.ts @@ -1,3 +1,4 @@ +import type { Document } from 'mongodb'; /** * QM Symbol Actions - Symbol search and spider operations */ @@ -31,41 +32,49 @@ export async function spiderSymbol( let jobsCreated = 0; for (let i = 0; i < 26; i++) { const letter = String.fromCharCode(65 + i); // A-Z - await this.scheduleOperation('spider-symbols', { - prefix: letter, - depth: 1, - source: 'qm', - maxDepth - }, { - priority: 5 - }); + await this.scheduleOperation( + 'spider-symbols', + { + prefix: letter, + depth: 1, + source: 'qm', + maxDepth, + }, + { + priority: 5, + } + ); jobsCreated++; } this.logger.info('Created root spider jobs', { jobsCreated }); - return { - message: `Queued ${jobsCreated} root jobs (A-Z)`, - jobsCreated + return { + message: `Queued ${jobsCreated} root jobs (A-Z)`, + jobsCreated, }; } try { // Search current prefix const symbols = await searchSymbols.call(this, { query: prefix }); - + if (!symbols || symbols.length === 0) { this.logger.debug('No symbols found for prefix', { prefix }); - return { + return { message: `No symbols found for prefix: ${prefix}`, - symbolsFound: 0 + symbolsFound: 0, }; } - await this.mongodb?.batchUpsert('qmSymbols', symbols, ['qmSearchCode']); - - this.logger.info(`Stored symbols from spider search ${prefix} - ${symbols.length}`, { - prefix, - count: symbols.length + await this.mongodb?.batchUpsert( + 'qmSymbols', + symbols.map(symbol => ({ ...symbol, source: 'qm' })), + ['qmSearchCode'] + ); + + this.logger.info(`Stored symbols from spider search ${prefix} - ${symbols.length}`, { + prefix, + count: symbols.length, }); // Extract and store unique exchanges @@ -83,49 +92,52 @@ export async function spiderSymbol( if (exchanges.length > 0) { await this.mongodb?.batchUpsert('qmExchanges', exchanges, ['exchange']); - this.logger.debug('Stored exchanges from spider search', { - count: exchanges.length + this.logger.debug('Stored exchanges from spider search', { + count: exchanges.length, }); } // If not at max depth and we found symbols, create child jobs if (depth < maxDepth && symbols.length > 0) { let jobsCreated = 0; - + // Only create child jobs if we found a significant number of symbols // This prevents excessive branching on sparse results if (symbols.length >= 50) { for (let i = 0; i < 26; i++) { const nextPrefix = prefix + String.fromCharCode(65 + i); - await this.scheduleOperation('spider-symbols', { - prefix: nextPrefix, - depth: depth + 1, - source: 'qm', - maxDepth - }, { - priority: Math.max(1, 5 - depth) - }); + await this.scheduleOperation( + 'spider-symbols', + { + prefix: nextPrefix, + depth: depth + 1, + source: 'qm', + maxDepth, + }, + { + priority: Math.max(1, 5 - depth), + } + ); jobsCreated++; } } - return { + return { message: `Found ${symbols.length} symbols for ${prefix}, queued ${jobsCreated} child jobs`, symbolsFound: symbols.length, - jobsCreated + jobsCreated, }; } - return { + return { message: `Found ${symbols.length} symbols for ${prefix} (at max depth or too few results)`, - symbolsFound: symbols.length + symbolsFound: symbols.length, }; - } catch (error) { this.logger.error(`Spider search failed ${prefix}`, { prefix, error }); return { message: `Spider search failed for prefix: ${prefix}`, - symbolsFound: 0 + symbolsFound: 0, }; } } @@ -137,9 +149,9 @@ export async function searchSymbols( this: QMHandler, input: { query: string }, _context?: ExecutionContext -): Promise { +): Promise { const { query } = input; - + this.logger.debug('Searching QM symbols', { query }); const sessionManager = QMSessionManager.getInstance(); @@ -148,7 +160,7 @@ export async function searchSymbols( // Get a session const sessionId = QM_SESSION_IDS.LOOKUP; const session = await sessionManager.getSession(sessionId); - + if (!session || !session.uuid) { throw new Error(`No active session found for QM LOOKUP`); } @@ -163,9 +175,9 @@ export async function searchSymbols( searchType: 'symbol', showFree: 'false', showHisa: 'false', - webmasterId: '500' + webmasterId: '500', }); - + const apiUrl = `${QM_CONFIG.LOOKUP_URL}?${searchParams.toString()}`; const response = await fetch(apiUrl, { @@ -179,40 +191,41 @@ export async function searchSymbols( } const symbols = await response.json(); - + // Update session success stats await sessionManager.incrementSuccessfulCalls(sessionId, session.uuid); // Process symbol data - const processedSymbols = Array.isArray(symbols) ? symbols.map((symbol: any) => { - const { exchangeCode, exchangeShortName, ...rest } = symbol; - return { - ...rest, - exchange: exchangeCode, - exchangeName: exchangeShortName, - qmSearchCode: symbol.symbol, - symbol: (symbol.symbol as string)?.split(':')[0], - }; - }) : []; + const processedSymbols = Array.isArray(symbols) + ? symbols.map((symbol: Document) => { + const { exchangeCode, exchangeShortName, ...rest } = symbol; + return { + ...rest, + exchange: exchangeCode, + exchangeName: exchangeShortName, + qmSearchCode: symbol.symbol, + symbol: (symbol.symbol as string)?.split(':')[0], + }; + }) + : []; - this.logger.debug('QM API returned symbols ${query} - ${processedSymbols.length}', { + this.logger.debug('QM API returned symbols ${query} - ${processedSymbols.length}', { query, - count: processedSymbols.length + count: processedSymbols.length, }); return processedSymbols; - } catch (error) { // Update session failure stats if (session.uuid) { await sessionManager.incrementFailedCalls(sessionId, session.uuid); } - this.logger.error('Error searching QM symbols', { + this.logger.error('Error searching QM symbols', { query, - error: error instanceof Error ? error.message : 'Unknown error' + error: error instanceof Error ? error.message : 'Unknown error', }); - + throw error; } -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/qm.handler.ts b/apps/stock/data-ingestion/src/handlers/qm/qm.handler.ts index 9c57b549..89ac4621 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/qm.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/qm.handler.ts @@ -1,12 +1,10 @@ -import { - BaseHandler, - Disabled, - Handler, - Operation, - ScheduledOperation, -} from '@stock-bot/handlers'; +import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; import type { OperationRegistry } from '../../shared/operation-manager'; +import { resolveIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types'; +import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action'; +import { createQMOperationRegistry } from './shared/operation-provider'; import { checkSessions, createSession, @@ -27,22 +25,21 @@ import { updateInsiders, updatePrices, updateSymbolInfo, - updateSymbolNews + updateSymbolNews, } from './actions'; -import { crawlIntradayData, scheduleIntradayCrawls } from './actions/intraday-crawl.action'; -import { createQMOperationRegistry } from './shared/operation-provider'; @Handler('qm') @Disabled() // Disable by default, enable specific operations as needed export class QMHandler extends BaseHandler { + static operationRegistry?: OperationRegistry; public operationRegistry!: OperationRegistry; - constructor(services: any) { - super(services); // Handler name read from @Handler decorator - + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'qm')); // Handler name read from @Handler decorator + // Use pre-initialized registry if available, otherwise create new one - if ((QMHandler as any).operationRegistry) { - this.operationRegistry = (QMHandler as any).operationRegistry; + if (QMHandler.operationRegistry) { + this.operationRegistry = QMHandler.operationRegistry; this.logger.info('Using pre-initialized QM operation registry'); } else { // Fallback: Initialize operation registry with QM provider @@ -79,7 +76,8 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('spider-symbols', '0 0 * * 0', { priority: 9, immediately: false, - description: 'Weekly comprehensive symbol search using QM API spider - runs every Saturday at midnight' + description: + 'Weekly comprehensive symbol search using QM API spider - runs every Saturday at midnight', }) spiderSymbol = spiderSymbol; @@ -98,7 +96,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-exchange-stats-and-dedup', '0 1 * * *', { priority: 7, immediately: false, - description: 'Update exchange statistics and deduplicate symbols daily at 1 AM' + description: 'Update exchange statistics and deduplicate symbols daily at 1 AM', }) scheduleExchangeStatsAndDedup = updateExchangeStatsAndDeduplicate; @@ -112,7 +110,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-symbol-info-updates', '0 */6 * * *', { priority: 7, immediately: false, - description: 'Check for symbols needing info updates every 6 hours' + description: 'Check for symbols needing info updates every 6 hours', }) scheduleSymbolInfoUpdates = scheduleSymbolInfoUpdates; @@ -126,7 +124,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-financials-updates', '0 2 * * *', { priority: 6, immediately: false, - description: 'Check for symbols needing financials updates daily at 2 AM' + description: 'Check for symbols needing financials updates daily at 2 AM', }) scheduleFinancialsUpdates = scheduleFinancialsUpdates; @@ -140,7 +138,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-events-updates', '0 3 * * *', { priority: 6, immediately: false, - description: 'Check for symbols needing events updates daily at 3 AM' + description: 'Check for symbols needing events updates daily at 3 AM', }) scheduleEventsUpdates = scheduleEventsUpdates; @@ -154,7 +152,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-price-updates', '0 */6 * * *', { priority: 8, immediately: false, - description: 'Check for symbols needing price updates every 6 hours' + description: 'Check for symbols needing price updates every 6 hours', }) schedulePriceUpdates = schedulePriceUpdates; @@ -171,11 +169,11 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-intraday-crawls-batch', '0 0 * * 0', { priority: 5, immediately: false, - description: 'Schedule intraday crawls for incomplete symbols every 12 hours' + description: 'Schedule intraday crawls for incomplete symbols every 12 hours', }) scheduleIntradayCrawlsBatch = async () => { return scheduleIntradayCrawls.call(this, { - priorityMode: 'incomplete' + priorityMode: 'incomplete', }); }; @@ -189,7 +187,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-insiders-updates', '0 4 * * 1', { priority: 5, immediately: false, - description: 'Check for symbols needing insider updates weekly on Monday at 4 AM' + description: 'Check for symbols needing insider updates weekly on Monday at 4 AM', }) scheduleInsidersUpdates = scheduleInsidersUpdates; @@ -206,7 +204,7 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('schedule-symbol-news-updates', '0 5 * * 1', { priority: 4, immediately: false, - description: 'Check for symbols needing news updates weekly on Monday at 5 AM' + description: 'Check for symbols needing news updates weekly on Monday at 5 AM', }) scheduleSymbolNewsUpdates = scheduleSymbolNewsUpdates; @@ -214,16 +212,16 @@ export class QMHandler extends BaseHandler { @ScheduledOperation('update-general-news-frequent', '*/1 * * * *', { priority: 9, immediately: true, - description: 'Update general market news every minute' + description: 'Update general market news every minute', }) updateGeneralNewsFrequent = async () => { return updateGeneralNews.call(this, { categories: ['market', 'economy', 'politics', 'breaking'], - lookbackMinutes: 5 // Only look back 5 minutes to avoid duplicates + lookbackMinutes: 5, // Only look back 5 minutes to avoid duplicates }); }; - /** + /** * FILINGS */ // @Operation('update-filings') @@ -236,4 +234,4 @@ export class QMHandler extends BaseHandler { // description: 'Check for symbols needing filings updates every 8 hours' // }) // scheduleFilingsUpdates = scheduleFilingsUpdates; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/operation-provider.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/operation-provider.ts index 39ced65e..626f3d7d 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/operation-provider.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/operation-provider.ts @@ -1,8 +1,14 @@ +import type { Logger, MongoDBClient } from '@stock-bot/services'; /** * QM Operation Provider - Defines operations for QuoteMedia data source */ -import { BaseOperationProvider, OperationRegistry, type OperationConfig, type ProviderConfig } from '../../../shared/operation-manager'; +import { + BaseOperationProvider, + OperationRegistry, + type OperationConfig, + type ProviderConfig, +} from '../../../shared/operation-manager'; /** * QM operation definitions @@ -13,69 +19,69 @@ export const QM_OPERATIONS: OperationConfig[] = [ name: 'symbol_info', type: 'standard', description: 'Update symbol metadata', - defaultStaleHours: 24 * 7 // Weekly + defaultStaleHours: 24 * 7, // Weekly }, - + // Price data { name: 'price_update', type: 'standard', description: 'Update daily price data', - defaultStaleHours: 24 + defaultStaleHours: 24, }, { name: 'intraday_bars', type: 'intraday_crawl', description: 'Crawl intraday price bars from today backwards', requiresFinishedFlag: true, - defaultStaleHours: 1 // Check every hour for new data + defaultStaleHours: 1, // Check every hour for new data }, - + // Fundamental data { name: 'financials_update_quarterly', type: 'standard', description: 'Update quarterly financial statements', - defaultStaleHours: 24 * 7 // Weekly + defaultStaleHours: 24 * 7, // Weekly }, { name: 'financials_update_annual', type: 'standard', description: 'Update annual financial statements', - defaultStaleHours: 24 * 7 // Weekly + defaultStaleHours: 24 * 7, // Weekly }, - + // Corporate actions { name: 'events_update', type: 'standard', description: 'Update events (earnings, dividends, splits)', - defaultStaleHours: 24 * 7 // Weekly + defaultStaleHours: 24 * 7, // Weekly }, - + // Filings { name: 'filings_update', type: 'standard', description: 'Update SEC filings', - defaultStaleHours: 24 // Daily + defaultStaleHours: 24, // Daily }, - + // Insider trading { name: 'insiders_update', type: 'standard', description: 'Update insider transactions', - defaultStaleHours: 24 * 7 // Weekly + defaultStaleHours: 24 * 7, // Weekly }, - + // News { name: 'news_update', type: 'standard', description: 'Update symbol-specific news', - defaultStaleHours: 24 * 7 // Weekly - } + defaultStaleHours: 24 * 7, // Weekly + }, ]; /** @@ -87,7 +93,7 @@ export class QMOperationProvider extends BaseOperationProvider { name: 'qm', collectionName: 'qmSymbols', symbolField: 'qmSearchCode', - description: 'QuoteMedia data provider' + description: 'QuoteMedia data provider', }; } @@ -100,11 +106,14 @@ export class QMOperationProvider extends BaseOperationProvider { * Create and initialize QM operation registry */ export async function createQMOperationRegistry( - mongodb: any, - logger: any + mongodb: MongoDBClient | null | undefined, + logger: Logger ): Promise { + if (!mongodb) { + throw new Error('Operation registry requires MongoDB'); + } const registry = new OperationRegistry({ mongodb, logger }); const provider = new QMOperationProvider({ mongodb, logger }); await registry.registerProvider(provider); return registry; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts index 10239ba7..7346e260 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts @@ -48,7 +48,7 @@ export class QMSessionManagerRedis { try { // Get all session UUIDs for this sessionId const sessionUuids = await this.getSessionUuids(sessionId); - + if (sessionUuids.length === 0) { this.logger?.debug(`No sessions found for ${sessionId}`); return null; @@ -56,7 +56,7 @@ export class QMSessionManagerRedis { // Shuffle and try to find a valid session const shuffled = [...sessionUuids].sort(() => Math.random() - 0.5); - + for (const uuid of shuffled) { const session = await this.getSessionByUuid(sessionId, uuid); if (session && (session.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS) { @@ -114,7 +114,7 @@ export class QMSessionManagerRedis { try { // Store the session data await this.cacheProvider.set(sessionKey, session, this.SESSION_TTL); - + // Add UUID to the session list (using SET to simulate SADD) const uuids = await this.getSessionUuids(sessionId); if (!uuids.includes(session.uuid)) { @@ -143,7 +143,7 @@ export class QMSessionManagerRedis { try { // Remove session data await this.cacheProvider.del(sessionKey); - + // Remove UUID from list const uuids = await this.getSessionUuids(sessionId); const filtered = uuids.filter(u => u !== uuid); @@ -212,7 +212,7 @@ export class QMSessionManagerRedis { for (const sessionId of Object.values(QM_SESSION_IDS)) { const sessions = await this.getSessions(sessionId); - + for (const session of sessions) { if (session.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS) { await this.removeSession(sessionId, session.uuid); @@ -242,14 +242,12 @@ export class QMSessionManagerRedis { async getStats(): Promise> { const stats: Record = {}; - for (const [sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) { + for (const [_sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) { const sessions = await this.getSessions(sessionId); const validSessions = sessions.filter( s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS ); - const failedSessions = sessions.filter( - s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS - ); + const failedSessions = sessions.filter(s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS); stats[sessionId] = { total: sessions.length, @@ -266,18 +264,18 @@ export class QMSessionManagerRedis { */ async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise { const session = await this.getSessionByUuid(sessionId, sessionUuid); - + if (session) { session.failedCalls = (session.failedCalls || 0) + 1; session.lastUsed = new Date(); - + const sessionKey = this.getSessionKey(sessionId, sessionUuid); await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); - + this.logger?.debug(`Incremented failed calls for session`, { sessionUuid, failedCalls: session.failedCalls, - sessionId + sessionId, }); } else { this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); @@ -289,18 +287,18 @@ export class QMSessionManagerRedis { */ async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise { const session = await this.getSessionByUuid(sessionId, sessionUuid); - + if (session) { session.successfulCalls = (session.successfulCalls || 0) + 1; session.lastUsed = new Date(); - + const sessionKey = this.getSessionKey(sessionId, sessionUuid); await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); - + this.logger?.debug(`Incremented successful calls for session`, { sessionUuid, successfulCalls: session.successfulCalls, - sessionId + sessionId, }); } else { this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); @@ -355,7 +353,8 @@ export class QMSessionManagerRedis { for (const id of oldSessionIds) { const oldSessionKey = `qm:sessions:${sessionType.toLowerCase()}:${id}`; - const oldSession = await this.cacheProvider.get(oldSessionKey); + const oldSession = + await this.cacheProvider.get(oldSessionKey); if (oldSession && oldSession.uuid) { const session: QMSession = { diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts index 9d0b210b..b3ad7e0a 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts @@ -18,9 +18,9 @@ export class SessionManagerWrapper { private constructor() { // Use Redis implementation if env var is set or if in production - const useRedis = process.env.REDIS_SESSION_MANAGER === 'true' || - process.env.NODE_ENV === 'production'; - + const useRedis = + process.env.REDIS_SESSION_MANAGER === 'true' || process.env.NODE_ENV === 'production'; + if (useRedis) { this.implementation = QMSessionManagerRedis.getInstance(); } else { @@ -85,7 +85,7 @@ export class SessionManagerWrapper { if (this.implementation instanceof QMSessionManagerRedis) { return this.implementation.getSessionCount(sessionId); } else { - return this.implementation.getSessionCount(); + return this.implementation.getSessionCount(sessionId ?? ''); } } @@ -110,7 +110,7 @@ export class SessionManagerWrapper { } // Additional methods for memory implementation - isAtCapacity(sessionId: string): boolean { + async isAtCapacity(sessionId: string): Promise { if (this.implementation instanceof QMSessionManager) { return this.implementation.isAtCapacity(sessionId); } diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/types.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/types.ts index 0563f160..efe147ed 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/types.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/types.ts @@ -12,6 +12,37 @@ export interface QMSession { createdAt: Date; } +export interface QMNewsArticle { + id?: string; + title: string; + publishedDate: string; + content?: string; + summary?: string; + source?: string; + url?: string; + symbols?: string[]; + categories?: string[]; + sentiment?: { score: string | number; label?: string }; + imageUrl?: string; + isMarketMoving?: boolean; + importance?: string; +} + +export interface QMInsiderTransaction { + transactionDate: string; + filingDate: string; + insiderName: string; + insiderTitle?: string; + transactionType: string; + shares: string | number; + pricePerShare: string | number; + totalValue: string | number; + sharesOwned: string | number; + ownershipType?: string; + formType?: string; + transactionCode?: string; +} + export interface SymbolSpiderJob { prefix: string | null; // null = root job (A-Z) depth: number; // 1=A, 2=AA, 3=AAA, etc. @@ -62,4 +93,4 @@ export interface ExchangeStats { symbolCount: number; totalMarketCap: number; avgMarketCap: number; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/crawl-scheduler.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/crawl-scheduler.action.ts index 2a45a615..3b04553e 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/crawl-scheduler.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/crawl-scheduler.action.ts @@ -1,3 +1,4 @@ +import { at } from '@stock-bot/invariants'; import type { TeHandler } from '../te.handler'; const STALE_DAYS = 30; @@ -7,16 +8,17 @@ export async function crawlScheduler(this: TeHandler): Promise<{ scheduled: numb const cutoff = new Date(Date.now() - STALE_DAYS * 24 * 60 * 60 * 1000); - const staleUrls = await mongodb?.find('teUrls', { - $or: [ - { lastCrawled: { $exists: false } }, - { lastCrawled: { $lt: cutoff } } - ], - skipReason: { $exists: false } - }, { - sort: { lastCrawled: 1 }, - projection: { url: 1 } - }); + const staleUrls = await mongodb?.find( + 'teUrls', + { + $or: [{ lastCrawled: { $exists: false } }, { lastCrawled: { $lt: cutoff } }], + skipReason: { $exists: false }, + }, + { + sort: { lastCrawled: 1 }, + projection: { url: 1 }, + } + ); if (!staleUrls?.length) { logger.debug('No stale URLs to schedule'); @@ -26,12 +28,16 @@ export async function crawlScheduler(this: TeHandler): Promise<{ scheduled: numb logger.info(`Scheduling ${staleUrls.length} stale/uncrawled URLs for spidering`); for (let i = 0; i < staleUrls.length; i++) { - const { url } = staleUrls[i]; - await this.scheduleOperation('te-spider', { url }, { - jobId: `spider-${url.replace(/\//g, '-')}`, - priority: 8, - delay: i * 200 - }); + const { url } = at(staleUrls, i); + await this.scheduleOperation( + 'te-spider', + { url }, + { + jobId: `spider-${url.replace(/\//g, '-')}`, + priority: 8, + delay: i * 200, + } + ); } return { scheduled: staleUrls.length }; diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts index 85e3e387..1c267295 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/data-fetch.action.ts @@ -5,13 +5,18 @@ import type { TeHandler } from '../te.handler'; export async function dataFetch( this: TeHandler, - payload: TeDataFetchPayload, + payload: TeDataFetchPayload ): Promise<{ success: boolean; recordCount: number }> { const { logger, mongodb, http, proxy } = this; const { teSymbol, url, isInitialFetch } = payload; const teDoc = await mongodb?.findOne('teUrls', { url }); - if (!teDoc?.teChartsDatasource || !teDoc?.teChartToken || !teDoc?.teChart || !teDoc?.teLastUpdate) { + if ( + !teDoc?.teChartsDatasource || + !teDoc?.teChartToken || + !teDoc?.teChart || + !teDoc?.teLastUpdate + ) { logger.error(`Missing CDN fields for ${teSymbol} (${url})`); return { success: false, recordCount: 0 }; } @@ -23,7 +28,9 @@ export async function dataFetch( } // Build CDN URL - const cdnUrl = new URL(`${teDoc.teChartsDatasource}/${pathSegment}/${encodeURIComponent(teSymbol.toLowerCase())}`); + const cdnUrl = new URL( + `${teDoc.teChartsDatasource}/${pathSegment}/${encodeURIComponent(teSymbol.toLowerCase())}` + ); if (isInitialFetch) { cdnUrl.searchParams.set('span', 'max'); } @@ -34,7 +41,7 @@ export async function dataFetch( const response = await http.get(cdnUrl.toString(), { proxy: proxy?.getProxy(), - headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, + headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, }); if (!response.ok) { @@ -54,61 +61,35 @@ export async function dataFetch( if (!serie?.data?.length) { logger.warn(`No data points decoded for ${teSymbol}`); - await mongodb?.updateOne('teUrls', { url }, { - $set: { - lastDataFetch: new Date(), - lastDataFetchUpdate: teDoc.teLastUpdate, - lastDataFetchCount: 0, - }, - }); + await mongodb?.updateOne( + 'teUrls', + { url }, + { + $set: { + lastDataFetch: new Date(), + lastDataFetchUpdate: teDoc.teLastUpdate, + lastDataFetchCount: 0, + }, + } + ); return { success: true, recordCount: 0 }; } // Transform data points: [value, epoch, null, "YYYY-MM-DD"] → { d, v } const dataPoints = serie.data.map(([value, _epoch, _null, date]) => ({ d: date, v: value })); - const forecastPoints = serie.forecast?.map(([value, _epoch, _null, date]) => ({ d: date, v: value })) ?? []; + const forecastPoints = + serie.forecast?.map(([value, _epoch, _null, date]) => ({ d: date, v: value })) ?? []; - logger.info(`Storing ${dataPoints.length} points + ${forecastPoints.length} forecast for ${teSymbol}`); + logger.info( + `Storing ${dataPoints.length} points + ${forecastPoints.length} forecast for ${teSymbol}` + ); if (isInitialFetch) { // Initial: upsert the full document - await mongodb?.updateOne('teData', { teSymbol }, { - $set: { - teSymbol, - name: serie.name, - unit: serie.unit, - source: serie.source, - frequency: serie.frequency, - country: serie.country, - category: serie.category, - data: dataPoints, - forecast: forecastPoints, - lastUpdated: new Date(), - }, - $setOnInsert: { createdAt: new Date() }, - }, { upsert: true }); - } else { - // Update: merge new points into existing data array by date - const existing = await mongodb?.findOne('teData', { teSymbol }); - if (existing?.data) { - const dateMap = new Map(existing.data.map((p: any) => [p.d, p.v])); - for (const p of dataPoints) { - dateMap.set(p.d, p.v); - } - const merged = Array.from(dateMap.entries()) - .sort(([a], [b]) => a.localeCompare(b)) - .map(([d, v]) => ({ d, v })); - - await mongodb?.updateOne('teData', { teSymbol }, { - $set: { - data: merged, - forecast: forecastPoints, - lastUpdated: new Date(), - }, - }); - } else { - // No existing doc (shouldn't happen but handle gracefully) - await mongodb?.updateOne('teData', { teSymbol }, { + await mongodb?.updateOne( + 'teData', + { teSymbol }, + { $set: { teSymbol, name: serie.name, @@ -122,19 +103,72 @@ export async function dataFetch( lastUpdated: new Date(), }, $setOnInsert: { createdAt: new Date() }, - }, { upsert: true }); + }, + { upsert: true } + ); + } else { + // Update: merge new points into existing data array by date + const existing = await mongodb?.findOne('teData', { teSymbol }); + if (existing?.data) { + const dateMap = new Map( + (existing.data as { d: string; v: number }[]).map(p => [p.d, p.v]) + ); + for (const p of dataPoints) { + dateMap.set(p.d, p.v); + } + const merged = Array.from(dateMap.entries()) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([d, v]) => ({ d, v })); + + await mongodb?.updateOne( + 'teData', + { teSymbol }, + { + $set: { + data: merged, + forecast: forecastPoints, + lastUpdated: new Date(), + }, + } + ); + } else { + // No existing doc (shouldn't happen but handle gracefully) + await mongodb?.updateOne( + 'teData', + { teSymbol }, + { + $set: { + teSymbol, + name: serie.name, + unit: serie.unit, + source: serie.source, + frequency: serie.frequency, + country: serie.country, + category: serie.category, + data: dataPoints, + forecast: forecastPoints, + lastUpdated: new Date(), + }, + $setOnInsert: { createdAt: new Date() }, + }, + { upsert: true } + ); } } const totalPoints = dataPoints.length + forecastPoints.length; - await mongodb?.updateOne('teUrls', { url }, { - $set: { - lastDataFetch: new Date(), - lastDataFetchUpdate: teDoc.teLastUpdate, - lastDataFetchCount: totalPoints, - }, - }); + await mongodb?.updateOne( + 'teUrls', + { url }, + { + $set: { + lastDataFetch: new Date(), + lastDataFetchUpdate: teDoc.teLastUpdate, + lastDataFetchCount: totalPoints, + }, + } + ); return { success: true, recordCount: totalPoints }; } diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts index 95b6a2e9..549d47ed 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-countries.action.ts @@ -1,5 +1,5 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; import * as cheerio from 'cheerio'; +import { getRandomUserAgent } from '@stock-bot/utils'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; @@ -10,7 +10,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number } proxy: proxy?.getProxy(), headers: { 'User-Agent': getRandomUserAgent(), - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', }, }); @@ -40,6 +40,7 @@ export async function fetchCountries(this: TeHandler): Promise<{ count: number } logger.info(`Found ${countries.size} countries`); const docs = Array.from(countries.entries()).map(([slug, name]) => ({ + source: 'te', slug, name, url: `/${slug}`, diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts index d7753842..00d8cb84 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/fetch-indicators.action.ts @@ -1,5 +1,5 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; import * as cheerio from 'cheerio'; +import { getRandomUserAgent } from '@stock-bot/utils'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; @@ -12,7 +12,7 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number proxy: proxy?.getProxy(), headers: { 'User-Agent': getRandomUserAgent(), - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', }, }); @@ -28,20 +28,27 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number $('li.list-group-item.active').each((_, groupEl) => { const group = $(groupEl).text().trim(); - if (SKIP_GROUPS.has(group)) return; + if (SKIP_GROUPS.has(group)) { + return; + } - $(groupEl).nextAll('li.list-group-item').each((_, li) => { - if ($(li).hasClass('active')) return false; // next group - const $a = $(li).find('a[href*="/country-list/"]'); - if ($a.length) { - const href = $a.attr('href') || ''; - const name = $a.text().trim(); - const slug = href.replace('/country-list/', ''); - if (slug && name) { - indicators.push({ group, slug, name, url: href }); + $(groupEl) + .nextAll('li.list-group-item') + .each((_, li) => { + if ($(li).hasClass('active')) { + return false; + } // next group + const $a = $(li).find('a[href*="/country-list/"]'); + if ($a.length) { + const href = $a.attr('href') || ''; + const name = $a.text().trim(); + const slug = href.replace('/country-list/', ''); + if (slug && name) { + indicators.push({ group, slug, name, url: href }); + } } - } - }); + return undefined; + }); }); if (!indicators.length) { @@ -50,7 +57,11 @@ export async function fetchIndicators(this: TeHandler): Promise<{ count: number logger.info(`Found ${indicators.length} indicators across groups`); - await mongodb?.batchUpsert('teIndicators', indicators, ['slug']); + await mongodb?.batchUpsert( + 'teIndicators', + indicators.map(indicator => ({ ...indicator, source: 'te' })), + ['slug'] + ); logger.info(`Upserted ${indicators.length} indicators into teIndicators`); return { count: indicators.length }; diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts index 8da90a6d..c3443368 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts @@ -24,16 +24,16 @@ interface MkDataPoint { async function fetchMkSerie( handler: TeHandler, cdnBase: string, - params: Record, + params: Record ): Promise { const url = new URL(cdnBase); for (const [k, v] of Object.entries(params)) { url.searchParams.set(k, v); } - const response = await handler.http.get(url.toString(), { + const response = await handler.fetchMarketSeries(url.toString(), { proxy: handler.proxy?.getProxy(), - headers: { 'Accept': '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, + headers: { Accept: '*/*', 'User-Agent': TE_CONFIG.USER_AGENT }, }); if (!response.ok) { @@ -41,18 +41,31 @@ async function fetchMkSerie( } const rawText = (await response.text()).replaceAll('"', ''); - if (!rawText.length) return null; + if (!rawText.length) { + return null; + } const decoded = decodeTEData<{ series: TeMkCdnSerie[] }>(rawText, TE_CONFIG.KEY); return decoded?.series?.[0] ?? null; } -function toPoints(data: any[]): MkDataPoint[] { - return data.map(([t, _c, pc, ac, o, h, l, c]: number[]) => ({ t, o, h, l, c, pc, ac })); +function toPoints(data: TeMkCdnSerie['data']): MkDataPoint[] { + return data.map(row => { + if ( + row.length < 8 || + !row.every( + (value, index) => ((index === 2 || index === 3) && value === null) || Number.isFinite(value) + ) + ) { + throw new Error('Invalid market-data OHLC row'); + } + const [t, _c, pc, ac, o, h, l, c] = row; + return { t, o, h, l, c, pc, ac }; + }); } function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPoint[] { - const map = new Map(existing.map((p) => [p.t, p])); + const map = new Map(existing.map(p => [p.t, p])); for (const p of incoming) { map.set(p.t, p); } @@ -61,7 +74,7 @@ function mergePoints(existing: MkDataPoint[], incoming: MkDataPoint[]): MkDataPo export async function marketDataFetch( this: TeHandler, - payload: TeMarketDataFetchPayload, + payload: TeMarketDataFetchPayload ): Promise<{ success: boolean; recordCount: number }> { const { logger, mongodb } = this; const { teSymbol, symbolType, url, isInitialFetch } = payload; @@ -94,39 +107,62 @@ export async function marketDataFetch( if (!daily.length && !monthly.length) { logger.warn(`No data points decoded for ${teSymbol}:${symbolType}`); - await mongodb?.updateOne('teUrls', { url }, { - $set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: 0 }, - }); + await mongodb?.updateOne( + 'teUrls', + { url }, + { + $set: { + lastDataFetch: new Date(), + lastDataFetchUpdate: teDoc.teLastUpdate, + lastDataFetchCount: 0, + }, + } + ); return { success: true, recordCount: 0 }; } - logger.info(`Storing ${daily.length} daily + ${monthly.length} monthly OHLC points for ${teSymbol} (${category})`); + logger.info( + `Storing ${daily.length} daily + ${monthly.length} monthly OHLC points for ${teSymbol} (${category})` + ); - await mongodb?.updateOne('teMarketData', { teSymbol }, { - $set: { - teSymbol, - name: serie?.name, - fullName: serie?.full_name, - unit: serie?.unit, - type: serie?.type, - category, - symbolType, - ticker: serie?.ticker, - sector: serie?.sector, - industry: serie?.industry, - frequency: serie?.frequency, - daily, - monthly, - lastUpdated: new Date(), + await mongodb?.updateOne( + 'teMarketData', + { teSymbol }, + { + $set: { + teSymbol, + name: serie?.name, + fullName: serie?.full_name, + unit: serie?.unit, + type: serie?.type, + category, + symbolType, + ticker: serie?.ticker, + sector: serie?.sector, + industry: serie?.industry, + frequency: serie?.frequency, + daily, + monthly, + lastUpdated: new Date(), + }, + $setOnInsert: { createdAt: new Date() }, }, - $setOnInsert: { createdAt: new Date() }, - }, { upsert: true }); + { upsert: true } + ); const totalPoints = daily.length + monthly.length; - await mongodb?.updateOne('teUrls', { url }, { - $set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: totalPoints }, - }); + await mongodb?.updateOne( + 'teUrls', + { url }, + { + $set: { + lastDataFetch: new Date(), + lastDataFetchUpdate: teDoc.teLastUpdate, + lastDataFetchCount: totalPoints, + }, + } + ); return { success: true, recordCount: totalPoints }; } @@ -146,13 +182,25 @@ export async function marketDataFetch( const merged = existing?.daily ? mergePoints(existing.daily, incoming) : incoming; - await mongodb?.updateOne('teMarketData', { teSymbol }, { - $set: { daily: merged, lastUpdated: new Date() }, - }); + await mongodb?.updateOne( + 'teMarketData', + { teSymbol }, + { + $set: { daily: merged, lastUpdated: new Date() }, + } + ); - await mongodb?.updateOne('teUrls', { url }, { - $set: { lastDataFetch: new Date(), lastDataFetchUpdate: teDoc.teLastUpdate, lastDataFetchCount: merged.length }, - }); + await mongodb?.updateOne( + 'teUrls', + { url }, + { + $set: { + lastDataFetch: new Date(), + lastDataFetchUpdate: teDoc.teLastUpdate, + lastDataFetchCount: merged.length, + }, + } + ); return { success: true, recordCount: merged.length }; } diff --git a/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts b/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts index a8e3a0e7..c8e8c5cb 100644 --- a/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts +++ b/apps/stock/data-ingestion/src/handlers/te/actions/spider.action.ts @@ -1,13 +1,16 @@ -import { getRandomUserAgent } from '@stock-bot/utils'; import * as cheerio from 'cheerio'; +import { at, getRandomUserAgent } from '@stock-bot/utils'; import { TE_CONFIG } from '../shared/config'; import type { TeHandler } from '../te.handler'; -export async function spiderUrl(this: TeHandler, payload: { url: string }): Promise { - const { logger, mongodb, proxy, http } = this; +export async function spiderUrl( + this: TeHandler, + payload: { url: string } +): Promise { + const { logger, mongodb, proxy: _proxy, http: _http } = this; const urlPath = payload?.url || '/'; const fullUrl = TE_CONFIG.MAIN_URL + urlPath; - + // 1. Check if already crawled recently (30 days) const record = await mongodb?.findOne('teUrls', { url: urlPath }); if (record?.lastCrawled) { @@ -17,7 +20,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom return null; } } - + // 2. Fetch the page logger.info(`Crawling ${fullUrl}`); const html = await fetchPage.call(this, fullUrl); @@ -27,86 +30,100 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom await mongodb?.updateOne( 'teUrls', { url: urlPath }, - { - $set: { + { + $set: { lastCrawled: new Date(), foundLinks: 0, - error: true - } + error: true, + }, }, { upsert: true } ); return null; } - + // 3. Extract TE data from the HTML let match = html.match(/var TESymbol = '([^']+)'/); const teSymbol = match ? match[1] : undefined; - + match = html.match(/TELastUpdate = '([^']+)'/); const teLastUpdate = match ? match[1] : undefined; - + match = html.match(/TEChart = '([^']+)'/); const teChart = match ? match[1] : undefined; - + match = html.match(/var TEAlertsName\s*=\s*'([^']+)'/); const teAlertsName = match ? match[1] : undefined; - + // Extract from script tags - these appear after TEChartUrl match = html.match(/TEChartUrl = '([^']+)'/); const teChartUrl = match ? match[1] : undefined; - + match = html.match(/TECountry = '([^']+)'/); const teCountry = match ? match[1] : undefined; - + match = html.match(/TECategory = '([^']+)'/); const teCategory = match ? match[1] : undefined; - + match = html.match(/TEType = '([^']+)'/); const teType = match ? match[1] : undefined; - + match = html.match(/TEFrequency = '([^']+)'/); const teFrequency = match ? match[1] : undefined; - + // Extract array data match = html.match(/TEForecast\s*=\s*\[([^\]]+)\]/); const teForecast = match ? JSON.parse('[' + match[1] + ']') : undefined; - + // Extract JSON metadata - use a more flexible regex match = html.match(/TEChartsMeta = (\[[\s\S]*?\]);/); - const teChartsMeta = match ? (() => { - try { - return JSON.parse(match[1]); - } catch (e) { - logger.warn('Failed to parse TEChartsMeta:', e); - return undefined; - } - })() : undefined; - + const teChartsMeta = match + ? (() => { + try { + return JSON.parse(at(match, 1)); + } catch (e) { + logger.warn('Failed to parse TEChartsMeta', { error: e }); + return undefined; + } + })() + : undefined; + // Extract symbol data match = html.match(/symbol = '([^']+)'/); const symbol = match ? match[1] : undefined; - + match = html.match(/symbolType = '([^']+)'/); const symbolType = match ? match[1] : undefined; - + // TEChartsDatasource is the CDN URL for chart data match = html.match(/; var TEChartsDatasource = '([^']+)'/); const teChartsDatasource = match ? match[1] : undefined; - + match = html.match(/; var TEChartsToken = '([^']+)'/); const teChartToken = match ? match[1] : undefined; - + // Log if we found any TE data - const foundData = teSymbol || teLastUpdate || teChartUrl || teChartsDatasource || - teChartToken || teChart || teAlertsName || teCountry || - teCategory || teType || teFrequency || teForecast || - teChartsMeta || symbol || symbolType; - + const foundData = + teSymbol || + teLastUpdate || + teChartUrl || + teChartsDatasource || + teChartToken || + teChart || + teAlertsName || + teCountry || + teCategory || + teType || + teFrequency || + teForecast || + teChartsMeta || + symbol || + symbolType; + if (foundData) { - logger.debug('Found TE data:', { - teSymbol, - teLastUpdate, + logger.debug('Found TE data:', { + teSymbol, + teLastUpdate, teChart, teAlertsName, teChartUrl, @@ -119,32 +136,45 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom symbol, symbolType, teChartsDatasource, - teChartToken + teChartToken, }); } - + // 4. Extract all links const $ = cheerio.load(html); const foundUrls = new Set(); - + // Add some seed URLs if this is the root page if (urlPath === '/') { const seedUrls = [ - '/united-states', '/china', '/eurozone', '/japan', '/united-kingdom', - '/indicators', '/calendar', '/forecasts', '/countries', - '/gdp', '/inflation', '/unemployment', '/interest-rate', - '/stocks', '/bonds', '/commodity', '/currency' + '/united-states', + '/china', + '/eurozone', + '/japan', + '/united-kingdom', + '/indicators', + '/calendar', + '/forecasts', + '/countries', + '/gdp', + '/inflation', + '/unemployment', + '/interest-rate', + '/stocks', + '/bonds', + '/commodity', + '/currency', ]; seedUrls.forEach(url => foundUrls.add(url)); } - + // Extract links from the page $('a[href]').each((_, element) => { const href = $(element).attr('href'); if (!href) { return; } - + // Convert to absolute path let path: string; if (href.startsWith('/')) { @@ -158,27 +188,27 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom } else { return; // Skip external links } - + // Clean the path - path = path.split('?')[0].split('#')[0]; - + path = at(at(path.split('?'), 0).split('#'), 0); + // Basic filtering if (shouldCrawl(path)) { foundUrls.add(path); } }); - + const urls = Array.from(foundUrls); logger.info(`Found ${urls.length} URLs on ${urlPath}`); - + // 5. Update database // Mark current URL as crawled with TE data if found - const updateData: any = { + const updateData: Record = { lastCrawled: new Date(), foundLinks: urls.length, - error: false + error: false, }; - + // Add TE data if found if (teSymbol) { updateData.teSymbol = teSymbol; @@ -193,7 +223,7 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom updateData.teAlertsName = teAlertsName; } if (teChartUrl) { - updateData.teChartUrl = teChartUrl; // Full chart URL with PNG + updateData.teChartUrl = teChartUrl; // Full chart URL with PNG } if (teCountry) { updateData.teCountry = teCountry; @@ -220,31 +250,26 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom updateData.symbolType = symbolType; } if (teChartsDatasource) { - updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data + updateData.teChartsDatasource = teChartsDatasource; // CDN URL for chart data } if (teChartToken) { updateData.teChartToken = teChartToken; } - - await mongodb?.updateOne( - 'teUrls', - { url: urlPath }, - { $set: updateData }, - { upsert: true } - ); - + + await mongodb?.updateOne('teUrls', { url: urlPath }, { $set: updateData }, { upsert: true }); + // Insert new URLs (without lastCrawled so they'll be picked up for crawling) const newUrls: string[] = []; for (const url of urls) { const result = await mongodb?.updateOne( 'teUrls', { url }, - { - $setOnInsert: { - url, + { + $setOnInsert: { + url, createdAt: new Date(), - source: urlPath - } + source: urlPath, + }, }, { upsert: true } ); @@ -253,55 +278,58 @@ export async function spiderUrl(this: TeHandler, payload: { url: string }): Prom newUrls.push(url); } } - + // 6. Schedule individual jobs for each new URL logger.info(`Scheduling ${newUrls.length} new URLs for crawling`); for (const url of newUrls) { - await this.scheduleOperation('te-spider', { url }, { - jobId: `spider-${url.replace(/\//g, '-')}`, - priority: 10, - delay: Math.floor(Math.random() * 10000) // Spread requests over 10 seconds - }); + await this.scheduleOperation( + 'te-spider', + { url }, + { + jobId: `spider-${url.replace(/\//g, '-')}`, + priority: 10, + delay: Math.floor(Math.random() * 10000), // Spread requests over 10 seconds + } + ); } - + return urls; } // Simple fetch with retry using http service with proxy async function fetchPage(this: TeHandler, url: string): Promise { const { http, proxy, logger } = this; - + for (let attempt = 1; attempt <= 3; attempt++) { try { // Get a proxy URL for this request const proxyUrl = proxy?.getProxy(); - + const response = await http.get(url, { proxy: proxyUrl, headers: { 'User-Agent': getRandomUserAgent(), - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', - 'Connection': 'keep-alive', + Connection: 'keep-alive', 'Upgrade-Insecure-Requests': '1', - 'Cache-Control': 'max-age=0' - } + 'Cache-Control': 'max-age=0', + }, }); - + if (response.ok) { return await response.text(); } - + // If not OK, log the status logger.error(`HTTP ${response.status} for ${url}`); - } catch (error) { logger.error(`Attempt ${attempt}/3 failed for ${url}:`, error); if (attempt === 3) { return null; } - + // Wait before retrying (exponential backoff) await new Promise(resolve => setTimeout(resolve, 1000 * attempt)); } @@ -315,18 +343,20 @@ function shouldCrawl(url: string): boolean { if (!url || url === '/') { return false; } - + // Skip static files - if (/\.(pdf|jpg|jpeg|png|gif|svg|css|js|ico|xml|rss|json|txt|csv|xlsx|xls|doc|docx|zip)$/i.test(url)) { + if ( + /\.(pdf|jpg|jpeg|png|gif|svg|css|js|ico|xml|rss|json|txt|csv|xlsx|xls|doc|docx|zip)$/i.test(url) + ) { return false; } - + // Skip deep URLs (more than 4 levels) const depth = (url.match(/\//g) || []).length; if (depth > 4) { return false; } - + // Skip common non-content pages const skipPatterns = [ /\/api\//, @@ -343,13 +373,13 @@ function shouldCrawl(url: string): boolean { /\/rss\//, /#/, ]; - + for (const pattern of skipPatterns) { if (pattern.test(url)) { return false; } } - + // Accept everything else return true; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/te/shared/types.ts b/apps/stock/data-ingestion/src/handlers/te/shared/types.ts index ff90f37d..bd505861 100644 --- a/apps/stock/data-ingestion/src/handlers/te/shared/types.ts +++ b/apps/stock/data-ingestion/src/handlers/te/shared/types.ts @@ -1,79 +1,79 @@ -// Define types and interfaces for the TE handler here - -export interface TeData { - id: string; - name: string; - // Add more fields as needed -} - -export interface TeResponse { - data: TeData[]; - status: string; - timestamp: Date; -} - -export interface TeCountry { - name: string; - code?: string; - region?: string; - url?: string; - updated_at: Date; - created_at?: Date; -} - -export interface TeDataFetchPayload { - teSymbol: string; - url: string; - isInitialFetch: boolean; -} - -export interface TeMarketDataFetchPayload { - teSymbol: string; - symbolType: string; - url: string; - isInitialFetch: boolean; -} - -/** MK/TV CDN series structure (flat, no nested serie wrapper) */ -export interface TeMkCdnSerie { - symbol: string; - name: string; - shortname: string; - full_name: string; - unit: string; - type: string; - ticker: string; - description: string; - sector: string; - industry: string; - frequency: string; - /** Each point: [epoch, value, pctChange, absChange] */ - data: Array<[number, number, number | null, number | null]>; -} - -/** Decoded CDN response wrapper */ -export interface TeCdnResponse { - series: Array<{ - serie: TeCdnSerie; - }>; - span: string; - agr: string; - frequency: string; -} - -/** Serie metadata + data from CDN */ -export interface TeCdnSerie { - s: string; - name: string; - shortname: string; - unit: string; - type: string; - source: string; - frequency: string; - country: string; - category: string; - /** Each point: [value, unix_epoch, null, "YYYY-MM-DD"] */ - data: Array<[number, number, null, string]>; - forecast?: Array<[number, number, null, string]>; - projection?: Array<[number, number, null, string]>; -} \ No newline at end of file +// Define types and interfaces for the TE handler here + +export interface TeData { + id: string; + name: string; + // Add more fields as needed +} + +export interface TeResponse { + data: TeData[]; + status: string; + timestamp: Date; +} + +export interface TeCountry { + name: string; + code?: string; + region?: string; + url?: string; + updated_at: Date; + created_at?: Date; +} + +export interface TeDataFetchPayload { + teSymbol: string; + url: string; + isInitialFetch: boolean; +} + +export interface TeMarketDataFetchPayload { + teSymbol: string; + symbolType: string; + url: string; + isInitialFetch: boolean; +} + +/** MK/TV CDN series structure (flat, no nested serie wrapper) */ +export interface TeMkCdnSerie { + symbol: string; + name: string; + shortname: string; + full_name: string; + unit: string; + type: string; + ticker: string; + description: string; + sector: string; + industry: string; + frequency: string; + /** OHLC endpoint: epoch, close, changes, open, high, low, close. */ + data: Array<[number, number, number | null, number | null, number, number, number, number]>; +} + +/** Decoded CDN response wrapper */ +export interface TeCdnResponse { + series: Array<{ + serie: TeCdnSerie; + }>; + span: string; + agr: string; + frequency: string; +} + +/** Serie metadata + data from CDN */ +export interface TeCdnSerie { + s: string; + name: string; + shortname: string; + unit: string; + type: string; + source: string; + frequency: string; + country: string; + category: string; + /** Each point: [value, unix_epoch, null, "YYYY-MM-DD"] */ + data: Array<[number, number, null, string]>; + forecast?: Array<[number, number, null, string]>; + projection?: Array<[number, number, null, string]>; +} diff --git a/apps/stock/data-ingestion/src/handlers/te/te.handler.ts b/apps/stock/data-ingestion/src/handlers/te/te.handler.ts index fdc4c8b7..81470e28 100644 --- a/apps/stock/data-ingestion/src/handlers/te/te.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/te/te.handler.ts @@ -1,24 +1,35 @@ -import { - BaseHandler, - Handler, - Operation, - ScheduledOperation -} from '@stock-bot/handlers'; +import type { CreateIndexesOptions, IndexSpecification } from 'mongodb'; +import { BaseHandler, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import { resolveIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types'; -import { crawlScheduler, dataFetch, dataScheduler, fetchCountries, fetchIndicators, marketDataFetch, marketDataScheduler, spiderUrl } from './actions'; +import { + crawlScheduler, + dataFetch, + dataScheduler, + fetchCountries, + fetchIndicators, + marketDataFetch, + marketDataScheduler, + spiderUrl, +} from './actions'; @Handler('te') export class TeHandler extends BaseHandler { - constructor(services: any) { - super(services); + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'te')); + } + + fetchMarketSeries(...args: Parameters) { + return this.http.get(...args); } /** * Initialize handler and create necessary indexes */ - async onInit(): Promise { + override async onInit(): Promise { this.logger.info('Initializing TeHandler and creating indexes'); - + if (!this.mongodb) { this.logger.warn('MongoDB not available, skipping index creation'); return; @@ -26,49 +37,49 @@ export class TeHandler extends BaseHandler { try { // Create indexes for teUrls collection - const indexes = [ + const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [ // Compound index for finding URLs to crawl { indexSpec: { lastCrawled: 1, url: 1 }, - options: { + options: { name: 'crawl_status_idx', - background: true - } + background: true, + }, }, // Unique index on URL to prevent duplicates { indexSpec: { url: 1 }, - options: { + options: { name: 'url_unique_idx', unique: true, - background: true - } + background: true, + }, }, // Index for finding URLs by symbol { indexSpec: { teSymbol: 1 }, - options: { + options: { name: 'symbol_idx', sparse: true, - background: true - } + background: true, + }, }, // Index for skip reason filtering { indexSpec: { skipReason: 1 }, - options: { + options: { name: 'skip_reason_idx', sparse: true, - background: true - } + background: true, + }, }, // Compound index for efficient batch queries { indexSpec: { lastCrawled: 1, skipReason: 1 }, - options: { + options: { name: 'batch_query_idx', - background: true - } + background: true, + }, }, // Index for finding URLs with chart data { @@ -76,8 +87,8 @@ export class TeHandler extends BaseHandler { options: { name: 'chart_url_idx', sparse: true, - background: true - } + background: true, + }, }, // Index for data-scheduler: filter by teType + sort by lastDataFetch { @@ -85,8 +96,8 @@ export class TeHandler extends BaseHandler { options: { name: 'data_fetch_schedule_idx', background: true, - } - } + }, + }, ]; for (const index of indexes) { @@ -95,12 +106,12 @@ export class TeHandler extends BaseHandler { this.logger.info(`Created/verified index: ${index.options.name}`); } catch (error) { // Index might already exist, that's OK - this.logger.debug(`Index ${index.options.name} may already exist:`, error); + this.logger.debug(`Index ${index.options.name} may already exist:`, { error }); } } // Indexes for teData collection (one doc per symbol with data array) - const teDataIndexes = [ + const teDataIndexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [ { indexSpec: { teSymbol: 1 }, options: { @@ -123,12 +134,15 @@ export class TeHandler extends BaseHandler { await this.mongodb.createIndex('teData', index.indexSpec, index.options); this.logger.info(`Created/verified teData index: ${index.options.name}`); } catch (error) { - this.logger.debug(`teData index ${index.options.name} may already exist:`, error); + this.logger.debug(`teData index ${index.options.name} may already exist:`, { error }); } } // Indexes for teMarketData collection - const teMarketDataIndexes = [ + const teMarketDataIndexes: { + indexSpec: IndexSpecification; + options: CreateIndexesOptions; + }[] = [ { indexSpec: { teSymbol: 1 }, options: { @@ -151,14 +165,15 @@ export class TeHandler extends BaseHandler { await this.mongodb.createIndex('teMarketData', index.indexSpec, index.options); this.logger.info(`Created/verified teMarketData index: ${index.options.name}`); } catch (error) { - this.logger.debug(`teMarketData index ${index.options.name} may already exist:`, error); + this.logger.debug(`teMarketData index ${index.options.name} may already exist:`, { + error, + }); } } // Check collection stats const count = await this.mongodb.countDocuments('teUrls', {}); this.logger.info(`TeUrls collection has ${count} documents`); - } catch (error) { this.logger.error('Error creating indexes for TeHandler:', error); // Don't throw - allow handler to continue even if indexes fail @@ -212,4 +227,4 @@ export class TeHandler extends BaseHandler { @Operation('te-market-data-fetch') marketDataFetch = marketDataFetch; -} \ No newline at end of file +} diff --git a/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts b/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts index 4f99c24a..b81ed36a 100644 --- a/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts +++ b/apps/stock/data-ingestion/src/handlers/tradingview/actions/fetch-exchanges.action.ts @@ -1,155 +1,171 @@ -import type { TradingViewHandler } from '../tradingview.handler'; -import { TradingViewExchange } from '../shared/types'; -import { TRADINGVIEW_CONFIG } from '../shared/config'; - -export async function fetchExchanges(handler: TradingViewHandler): Promise { - const { logger, mongodb } = handler; - - if (!mongodb?.db) { - logger.error('MongoDB not available'); - return null; - } - - const db = mongodb.db; - - try { - // 1. Fetch the HTML page - const response = await fetch(TRADINGVIEW_CONFIG.DATA_COVERAGE_URL, { - headers: { - 'User-Agent': TRADINGVIEW_CONFIG.USER_AGENT, - }, - }); - - logger.debug('Response status:', { - status: response.status, - statusText: response.statusText, - url: response.url - }); - - if (!response.ok) { - throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`); - } - - const html = await response.text(); - - logger.info('Fetched HTML length:', { length: html.length }); - - // Save HTML for debugging - if (process.env.DEBUG_HTML) { - const fs = await import('fs/promises'); - await fs.writeFile('/tmp/tradingview-data-coverage.html', html); - logger.info('Saved HTML to /tmp/tradingview-data-coverage.html'); - } - - // 2. Parse HTML to extract exchange data from the table - const exchanges: TradingViewExchange[] = []; - - // Match table rows containing exchange data - const rowRegex = /]*class="row-qJcpoITA[^"]*"[^>]*>[\s\S]*?<\/tr>/g; - const rows = html.match(rowRegex) || []; - - logger.debug('Found table rows:', { count: rows.length }); - - for (const row of rows) { - try { - // Extract exchange ID - const exchangeMatch = row.match(/alt="([^"]+)"/); - const exchangeNameMatch = row.match(/]*class="exchangeName-qJcpoITA"[^>]*>([^<]+)<\/span>/); - const descriptionMatch = row.match(/]*class="exchangeDescName-qJcpoITA"[^>]*>([^<]+)<\/span>/); - const countryFlagMatch = row.match(/src="https:\/\/s3-symbol-logo\.tradingview\.com\/country\/([^.]+)\.svg"/); - const countryNameMatch = row.match(/]*class="[^"]*exchangeCountryFlag[^"]*"[^>]*\/>([^<]+)<\/span>/); - - // Extract data types from badges - const badgeMatches = row.matchAll(/]*class="badge-PlSmolIm[^"]*"[^>]*>[\s\S]*?]*class="content-PlSmolIm"[^>]*>([^<]+)<\/span>/g); - const dataTypes: string[] = []; - for (const match of badgeMatches) { - dataTypes.push(match[1].toLowerCase()); - } - - if (exchangeNameMatch && descriptionMatch && countryFlagMatch) { - const exchange: TradingViewExchange = { - exchange: descriptionMatch[1].toLowerCase().replace(/\s+/g, '_').replace(/[()]/g, ''), - name: exchangeNameMatch[1], - description: descriptionMatch[1], - dataType: dataTypes, - countryCode: countryFlagMatch[1].toUpperCase(), - countryName: '', // Will be filled from alt text or other sources - }; - - // Try to extract country name - if (countryNameMatch) { - exchange.countryName = countryNameMatch[1].trim(); - } else if (exchangeMatch) { - // Use alt text to extract country name - const parts = exchangeMatch[1].split(' '); - if (parts.length > 1) { - exchange.countryName = parts[0]; - } - } - - exchanges.push(exchange); - } - } catch (e) { - logger.debug('Failed to parse row', { error: e }); - } - } - - if (exchanges.length === 0) { - throw new Error('No exchanges found in HTML'); - } - - logger.info('Extracted exchanges from HTML', { count: exchanges.length }); - - // Batch update tvExchanges collection - try { - const batchOps = exchanges.map(exchange => ({ - updateOne: { - filter: { exchange: exchange.exchange }, - update: { - $set: { - ...exchange, - updated_at: new Date(), - }, - $setOnInsert: { - created_at: new Date(), - }, - }, - upsert: true, - }, - })); - - if (batchOps.length > 0) { - await db.collection('tvExchanges').bulkWrite(batchOps); - } - - logger.info('TradingView exchanges saved to MongoDB'); - } catch (dbError) { - logger.warn('Failed to save exchanges to MongoDB', { error: dbError }); - } - - logger.info('TradingView exchanges fetched', { - count: exchanges.length, - byType: groupExchangesByType(exchanges), - }); - - return exchanges; - } catch (error) { - logger.error('Failed to fetch TradingView exchanges', { - error: error instanceof Error ? error.message : String(error), - stack: error instanceof Error ? error.stack : undefined, - }); - return null; - } -} - -function groupExchangesByType(exchanges: TradingViewExchange[]) { - const groups: Record = {}; - - for (const exchange of exchanges) { - for (const type of exchange.dataType) { - groups[type] = (groups[type] || 0) + 1; - } - } - - return groups; -} \ No newline at end of file +import { at } from '@stock-bot/utils'; +import { TRADINGVIEW_CONFIG } from '../shared/config'; +import { type TradingViewExchange } from '../shared/types'; +import type { TradingViewHandler } from '../tradingview.handler'; + +export async function fetchExchanges( + handler: TradingViewHandler +): Promise { + const { logger, mongodb } = handler; + + if (!mongodb) { + logger.error('MongoDB not available'); + return null; + } + + const db = mongodb.getDatabase(); + + try { + // 1. Fetch the HTML page + const response = await fetch(TRADINGVIEW_CONFIG.DATA_COVERAGE_URL, { + headers: { + 'User-Agent': TRADINGVIEW_CONFIG.USER_AGENT, + }, + }); + + logger.debug('Response status:', { + status: response.status, + statusText: response.statusText, + url: response.url, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`); + } + + const html = await response.text(); + + logger.info('Fetched HTML length:', { length: html.length }); + + // Save HTML for debugging + if (process.env.DEBUG_HTML) { + const fs = await import('fs/promises'); + await fs.writeFile('/tmp/tradingview-data-coverage.html', html); + logger.info('Saved HTML to /tmp/tradingview-data-coverage.html'); + } + + // 2. Parse HTML to extract exchange data from the table + const exchanges: TradingViewExchange[] = []; + + // Match table rows containing exchange data + const rowRegex = /]*class="row-qJcpoITA[^"]*"[^>]*>[\s\S]*?<\/tr>/g; + const rows = html.match(rowRegex) || []; + + logger.debug('Found table rows:', { count: rows.length }); + + for (const row of rows) { + try { + // Extract exchange ID + const exchangeMatch = row.match(/alt="([^"]+)"/); + const exchangeNameMatch = row.match( + /]*class="exchangeName-qJcpoITA"[^>]*>([^<]+)<\/span>/ + ); + const descriptionMatch = row.match( + /]*class="exchangeDescName-qJcpoITA"[^>]*>([^<]+)<\/span>/ + ); + const countryFlagMatch = row.match( + /src="https:\/\/s3-symbol-logo\.tradingview\.com\/country\/([^.]+)\.svg"/ + ); + const countryNameMatch = row.match( + /]*class="[^"]*exchangeCountryFlag[^"]*"[^>]*\/>([^<]+)<\/span>/ + ); + + // Extract data types from badges + const badgeMatches = row.matchAll( + /]*class="badge-PlSmolIm[^"]*"[^>]*>[\s\S]*?]*class="content-PlSmolIm"[^>]*>([^<]+)<\/span>/g + ); + const dataTypes: string[] = []; + for (const match of badgeMatches) { + dataTypes.push(at(match, 1).toLowerCase()); + } + + if (exchangeNameMatch && descriptionMatch && countryFlagMatch) { + const exchange: TradingViewExchange = { + exchange: at(descriptionMatch, 1) + .toLowerCase() + .replace(/\s+/g, '_') + .replace(/[()]/g, ''), + name: at(exchangeNameMatch, 1), + description: at(descriptionMatch, 1), + dataType: dataTypes, + countryCode: at(countryFlagMatch, 1).toUpperCase(), + countryName: '', // Will be filled from alt text or other sources + }; + + // Try to extract country name + if (countryNameMatch) { + exchange.countryName = at(countryNameMatch, 1).trim(); + } else if (exchangeMatch) { + // Use alt text to extract country name + const parts = at(exchangeMatch, 1).split(' '); + if (parts.length > 1) { + exchange.countryName = at(parts, 0); + } + } + + exchanges.push(exchange); + } + } catch (e) { + logger.debug('Failed to parse row', { error: e }); + } + } + + if (exchanges.length === 0) { + throw new Error('No exchanges found in HTML'); + } + + logger.info('Extracted exchanges from HTML', { count: exchanges.length }); + + // Batch update tvExchanges collection + try { + const batchOps = exchanges.map(exchange => ({ + updateOne: { + filter: { exchange: exchange.exchange }, + update: { + $set: { + ...exchange, + updated_at: new Date(), + }, + $setOnInsert: { + created_at: new Date(), + }, + }, + upsert: true, + }, + })); + + if (batchOps.length > 0) { + await db.collection('tvExchanges').bulkWrite(batchOps); + } + + logger.info('TradingView exchanges saved to MongoDB'); + } catch (dbError) { + logger.warn('Failed to save exchanges to MongoDB', { error: dbError }); + } + + logger.info('TradingView exchanges fetched', { + count: exchanges.length, + byType: groupExchangesByType(exchanges), + }); + + return exchanges; + } catch (error) { + logger.error('Failed to fetch TradingView exchanges', { + error: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + return null; + } +} + +function groupExchangesByType(exchanges: TradingViewExchange[]) { + const groups: Record = {}; + + for (const exchange of exchanges) { + for (const type of exchange.dataType) { + groups[type] = (groups[type] || 0) + 1; + } + } + + return groups; +} diff --git a/apps/stock/data-ingestion/src/handlers/tradingview/shared/types.ts b/apps/stock/data-ingestion/src/handlers/tradingview/shared/types.ts index 22052a7f..e5b93011 100644 --- a/apps/stock/data-ingestion/src/handlers/tradingview/shared/types.ts +++ b/apps/stock/data-ingestion/src/handlers/tradingview/shared/types.ts @@ -1,36 +1,36 @@ -export interface TradingViewExchange { - exchange: string; - name: string; - description: string; - dataType: string[]; - countryCode: string; // All caps - countryName: string; - popularityRank?: number; -} - -// Raw data from TradingView -export interface TradingViewRawExchange { - text_id?: string; - exchange: string; - provider_id?: string | null; - name: string; - description: string; - data_type: string[]; - country: string; - country_name: string; - popularity_rank?: number; - [key: string]: any; // Other fields we don't need -} - -export interface ExchangeGroup { - name: string; - exchanges: TradingViewRawExchange[]; -} - -export interface TradingViewData { - locale: string; - user: any; - is_authenticated: boolean; - exchanges: ExchangeGroup[]; - currency: string; -} \ No newline at end of file +export interface TradingViewExchange { + exchange: string; + name: string; + description: string; + dataType: string[]; + countryCode: string; // All caps + countryName: string; + popularityRank?: number; +} + +// Raw data from TradingView +export interface TradingViewRawExchange { + text_id?: string; + exchange: string; + provider_id?: string | null; + name: string; + description: string; + data_type: string[]; + country: string; + country_name: string; + popularity_rank?: number; + [key: string]: unknown; // Other fields we don't need +} + +export interface ExchangeGroup { + name: string; + exchanges: TradingViewRawExchange[]; +} + +export interface TradingViewData { + locale: string; + user: unknown; + is_authenticated: boolean; + exchanges: ExchangeGroup[]; + currency: string; +} diff --git a/apps/stock/data-ingestion/src/handlers/tradingview/tradingview.handler.ts b/apps/stock/data-ingestion/src/handlers/tradingview/tradingview.handler.ts index 029d8c95..3ec8468a 100644 --- a/apps/stock/data-ingestion/src/handlers/tradingview/tradingview.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/tradingview/tradingview.handler.ts @@ -1,31 +1,27 @@ -import { - BaseHandler, - Disabled, - Handler, - Operation, - ScheduledOperation, -} from '@stock-bot/handlers'; -import { fetchExchanges } from './actions'; - -@Disabled() -@Handler('tradingview') -export class TradingViewHandler extends BaseHandler { - constructor(services: any) { - super(services); - } - - @Operation('fetch-exchanges') - async fetchExchanges(): Promise { - return fetchExchanges(this); - } - - @ScheduledOperation('tradingview-exchanges', '0 0 * * 0', { - priority: 5, - description: 'Fetch and update TradingView exchanges data', - immediately: false, - }) - @Disabled() - async scheduledFetchExchanges(): Promise { - return this.fetchExchanges(); - } -} \ No newline at end of file +import { BaseHandler, Disabled, Handler, Operation, ScheduledOperation } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import { resolveIngestionServices } from '../../types'; +import { fetchExchanges } from './actions'; + +@Disabled() +@Handler('tradingview') +export class TradingViewHandler extends BaseHandler { + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'tradingview')); + } + + @Operation('fetch-exchanges') + async fetchExchanges(): Promise { + return fetchExchanges(this); + } + + @ScheduledOperation('tradingview-exchanges', '0 0 * * 0', { + priority: 5, + description: 'Fetch and update TradingView exchanges data', + immediately: false, + }) + @Disabled() + async scheduledFetchExchanges(): Promise { + return this.fetchExchanges(); + } +} diff --git a/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts b/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts index d902e954..7d7dafbd 100644 --- a/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts +++ b/apps/stock/data-ingestion/src/handlers/tt/actions/import.action.ts @@ -1,16 +1,27 @@ -import * as cheerio from 'cheerio'; -import { getRandomUserAgent } from '@stock-bot/utils'; -import { existsSync, mkdirSync, rmSync, readdirSync, readFileSync } from 'fs'; import { execSync } from 'child_process'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'fs'; import { join } from 'path'; +import * as cheerio from 'cheerio'; +import { defined } from '@stock-bot/invariants'; +import { getRandomUserAgent } from '@stock-bot/utils'; import type { TtHandler } from '../tt.handler'; const BASE_URL = 'https://www.turtletrader.com'; const TMP_DIR = '/tmp/tt'; -const MONTH_MAP: Record = { - F: '01', G: '02', H: '03', J: '04', K: '05', M: '06', - N: '07', Q: '08', U: '09', V: '10', X: '11', Z: '12', +const _MONTH_MAP: Record = { + F: '01', + G: '02', + H: '03', + J: '04', + K: '05', + M: '06', + N: '07', + Q: '08', + U: '09', + V: '10', + X: '11', + Z: '12', }; function parseDate(yymmdd: string): string { @@ -40,7 +51,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe $('a[href$=".zip"]').each((_, el) => { const href = $(el).attr('href') || ''; const name = $(el).text().trim(); - if (href) zipLinks.push({ href, name }); + if (href) { + zipLinks.push({ href, name }); + } }); if (!zipLinks.length) { @@ -60,7 +73,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe try { for (const { href, name } of zipLinks) { const zipUrl = href.startsWith('http') ? href : `${BASE_URL}${href}`; - const symbol = href.split('/').pop()!.replace('.zip', '').toUpperCase(); + const symbol = defined(href.split('/').pop()).replace('.zip', '').toUpperCase(); const zipPath = join(TMP_DIR, `${symbol}.zip`); const extractDir = join(TMP_DIR, symbol); @@ -84,7 +97,7 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe // Parse each txt file const files = readdirSync(extractDir).filter(f => f.endsWith('.txt')); - const records: any[] = []; + const records = []; for (const file of files) { const contract = file.replace('.txt', ''); @@ -101,14 +114,27 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe for (const line of content.split('\n')) { const trimmed = line.trim(); - if (!trimmed) continue; + if (!trimmed) { + continue; + } const parts = trimmed.split(','); - if (parts.length < 7) continue; + if (parts.length < 7) { + continue; + } - const [dateStr, o, h, l, c, v, oi] = parts; + const [dateStr, o, h, l, c, v, oi] = parts as [ + string, + string, + string, + string, + string, + string, + string, + ]; records.push({ + source: 'tt', contract, symbol: sym, name, @@ -128,7 +154,9 @@ export async function importData(this: TtHandler): Promise<{ totalRecords: numbe if (records.length) { await mongodb?.batchUpsert('ttFutures', records, ['contract', 'date']); totalRecords += records.length; - logger.info(`Imported ${records.length} records for ${name} (${symbol}, ${files.length} contracts)`); + logger.info( + `Imported ${records.length} records for ${name} (${symbol}, ${files.length} contracts)` + ); } // Clean up this zip diff --git a/apps/stock/data-ingestion/src/handlers/tt/tt.handler.ts b/apps/stock/data-ingestion/src/handlers/tt/tt.handler.ts index f306d8d4..c332dce0 100644 --- a/apps/stock/data-ingestion/src/handlers/tt/tt.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/tt/tt.handler.ts @@ -1,21 +1,22 @@ -import { - BaseHandler, - Handler, - ScheduledOperation, -} from '@stock-bot/handlers'; +import type { CreateIndexesOptions, IndexSpecification } from 'mongodb'; +import { BaseHandler, Handler, ScheduledOperation } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import { resolveIngestionServices } from '../../types'; import type { DataIngestionServices } from '../../types'; import { importData } from './actions'; @Handler('tt') export class TtHandler extends BaseHandler { - constructor(services: any) { - super(services); + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'tt')); } - async onInit(): Promise { - if (!this.mongodb) return; + override async onInit(): Promise { + if (!this.mongodb) { + return; + } - const indexes = [ + const indexes: { indexSpec: IndexSpecification; options: CreateIndexesOptions }[] = [ { indexSpec: { contract: 1, date: 1 }, options: { name: 'contract_date_unique_idx', unique: true, background: true }, @@ -34,7 +35,7 @@ export class TtHandler extends BaseHandler { try { await this.mongodb.createIndex('ttFutures', index.indexSpec, index.options); } catch (error) { - this.logger.debug(`ttFutures index ${index.options.name} may already exist:`, error); + this.logger.debug(`ttFutures index ${index.options.name} may already exist:`, { error }); } } } diff --git a/apps/stock/data-ingestion/src/handlers/webshare/webshare.handler.ts b/apps/stock/data-ingestion/src/handlers/webshare/webshare.handler.ts index 03215fc7..fba6a9ef 100644 --- a/apps/stock/data-ingestion/src/handlers/webshare/webshare.handler.ts +++ b/apps/stock/data-ingestion/src/handlers/webshare/webshare.handler.ts @@ -5,11 +5,13 @@ import { QueueSchedule, type ExecutionContext, } from '@stock-bot/handlers'; +import type { IServiceContainer } from '@stock-bot/services'; +import { resolveIngestionServices } from '../../types'; @Handler('webshare') export class WebShareHandler extends BaseHandler { - constructor(services: any) { - super(services); + constructor(services: IServiceContainer) { + super(resolveIngestionServices(services, 'webshare')); } @Operation('fetch-proxies') diff --git a/apps/stock/data-ingestion/src/index.ts b/apps/stock/data-ingestion/src/index.ts index 4622d21a..867d33df 100644 --- a/apps/stock/data-ingestion/src/index.ts +++ b/apps/stock/data-ingestion/src/index.ts @@ -5,7 +5,7 @@ import { ServiceApplication } from '@stock-bot/di'; import { getLogger } from '@stock-bot/logger'; -import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config'; +import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; // Local imports import { initializeAllHandlers } from './handlers'; @@ -49,11 +49,11 @@ const app = new ServiceApplication( ); // Container factory function -async function createContainer(config: StockAppConfig) { +async function createContainer(baseConfig: import('@stock-bot/config').UnifiedAppConfig) { const { ServiceContainerBuilder } = await import('@stock-bot/di'); const container = await new ServiceContainerBuilder() - .withConfig(config) + .withConfig({ ...config, ...baseConfig }) .withOptions({ enableQuestDB: false, // Data ingestion doesn't need QuestDB yet enableMongoDB: true, diff --git a/apps/stock/data-ingestion/src/routes/create-routes.ts b/apps/stock/data-ingestion/src/routes/create-routes.ts index f6c29cdb..ea151c1e 100644 --- a/apps/stock/data-ingestion/src/routes/create-routes.ts +++ b/apps/stock/data-ingestion/src/routes/create-routes.ts @@ -21,17 +21,9 @@ export function createRoutes(services: IServiceContainer): Hono { app.route('/api/exchanges', exchangeRoutes); app.route('/api/queue', createQueueRoutes(services)); - // Store services in app context for handlers that need it - app.use('*', async (c, next) => { - c.set('services', services); - await next(); - }); - // Add a new endpoint to test the improved DI app.get('/api/di-test', async c => { try { - const services = c.get('services') as IServiceContainer; - // Test MongoDB connection const mongoStats = services.mongodb?.getPoolMetrics?.() || { status: services.mongodb ? 'connected' : 'disabled', @@ -44,7 +36,7 @@ export function createRoutes(services: IServiceContainer): Hono { const cacheReady = services.cache?.isReady() || false; // Test queue - const queueStats = services.queue?.getGlobalStats() || { status: 'disabled' }; + const queueStats = (await services.queueManager?.getGlobalStats()) || { status: 'disabled' }; return c.json({ success: true, @@ -58,7 +50,6 @@ export function createRoutes(services: IServiceContainer): Hono { timestamp: new Date().toISOString(), }); } catch (error) { - const services = c.get('services') as IServiceContainer; services.logger.error('DI test endpoint failed', { error }); return c.json( { diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts b/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts index c4cf72ee..7b674588 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/BaseOperationProvider.ts @@ -1,13 +1,14 @@ +import type { Document } from 'mongodb'; /** * Base class for operation providers */ import type { Logger, MongoDBClient } from '@stock-bot/services'; -import type { - OperationConfig, - OperationUpdate, +import type { + OperationComponentOptions, + OperationConfig, + OperationUpdate, ProviderConfig, - OperationComponentOptions } from './types'; /** @@ -42,10 +43,10 @@ export abstract class BaseOperationProvider { } this.logger.info(`Initializing ${this.getProviderConfig().name} operation provider`); - + // Allow providers to perform custom initialization await this.onInitialize(); - + this._initialized = true; } @@ -78,16 +79,16 @@ export abstract class BaseOperationProvider { /** * Get the symbol identifier value from a document */ - getSymbolIdentifier(doc: any): string { + getSymbolIdentifier(doc: Document): string { const { symbolField } = this.getProviderConfig(); const value = doc[symbolField]; - + if (!value) { throw new Error( `Symbol field '${symbolField}' not found in document for provider '${this.getProviderConfig().name}'` ); } - + return value; } @@ -110,9 +111,9 @@ export abstract class BaseOperationProvider { * Hook called before operation update (optional override) */ async beforeOperationUpdate( - symbol: string, - operation: string, - data: OperationUpdate + _symbol: string, + _operation: string, + _data: OperationUpdate ): Promise { // Providers can override this for custom logic } @@ -121,9 +122,9 @@ export abstract class BaseOperationProvider { * Hook called after operation update (optional override) */ async afterOperationUpdate( - symbol: string, - operation: string, - data: OperationUpdate + _symbol: string, + _operation: string, + _data: OperationUpdate ): Promise { // Providers can override this for custom logic } @@ -157,7 +158,7 @@ export abstract class BaseOperationProvider { logInfo(): void { const config = this.getProviderConfig(); const operations = this.getOperations(); - + this.logger.info(`Provider: ${config.name}`, { provider: config.name, collection: config.collectionName, @@ -166,8 +167,8 @@ export abstract class BaseOperationProvider { operations: operations.map(op => ({ name: op.name, type: op.type, - defaultStaleHours: op.defaultStaleHours - })) + defaultStaleHours: op.defaultStaleHours, + })), }); } } diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts index 12dc5dc1..1446cf3e 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationRegistry.ts @@ -1,8 +1,10 @@ +import type { Document } from 'mongodb'; /** * Central registry for managing operations across multiple providers */ import type { Logger, MongoDBClient } from '@stock-bot/services'; +import { at } from '@stock-bot/utils'; import { BaseOperationProvider } from './BaseOperationProvider'; import { OperationTracker } from './OperationTracker'; import type { @@ -10,7 +12,7 @@ import type { OperationConfig, OperationStats, OperationUpdate, - StaleSymbolOptions + StaleSymbolOptions, } from './types'; /** @@ -45,7 +47,7 @@ export class OperationRegistry { */ async registerProvider(provider: BaseOperationProvider): Promise { const config = provider.getProviderConfig(); - + if (this.providers.has(config.name)) { throw new Error(`Provider '${config.name}' is already registered`); } @@ -56,11 +58,8 @@ export class OperationRegistry { this.providers.set(config.name, provider); // Create and initialize tracker - const tracker = new OperationTracker( - { mongodb: this.mongodb, logger: this.logger }, - provider - ); - + const tracker = new OperationTracker({ mongodb: this.mongodb, logger: this.logger }, provider); + await tracker.initialize(); this.trackers.set(config.name, tracker); @@ -85,7 +84,7 @@ export class OperationRegistry { this.logger.info('Operation registry initialized', { providerCount: this.providers.size, - providers: Array.from(this.providers.keys()) + providers: Array.from(this.providers.keys()), }); } @@ -146,7 +145,14 @@ export class OperationRegistry { providerName: string, operationName: string, options?: StaleSymbolOptions - ): Promise> { + ): Promise< + Array<{ + symbol: Document; + lastRun?: Date; + lastSuccess?: Date; + operations?: Record; + }> + > { const tracker = this.getTracker(providerName); return tracker.getStaleSymbols(operationName, options); } @@ -154,10 +160,7 @@ export class OperationRegistry { /** * Get operation statistics */ - async getOperationStats( - providerName: string, - operationName: string - ): Promise { + async getOperationStats(providerName: string, operationName: string): Promise { const tracker = this.getTracker(providerName); return tracker.getOperationStats(operationName); } @@ -183,7 +186,7 @@ export class OperationRegistry { getAllOperations(): Array<{ provider: string; operations: OperationConfig[] }> { return Array.from(this.providers.entries()).map(([name, provider]) => ({ provider: name, - operations: provider.getOperations() + operations: provider.getOperations(), })); } @@ -209,15 +212,15 @@ export class OperationRegistry { const operations = provider.getOperations(); const operationStats = await Promise.all( - operations.map(async (op) => ({ + operations.map(async op => ({ name: op.name, - stats: await tracker.getOperationStats(op.name) + stats: await tracker.getOperationStats(op.name), })) ); return { provider: providerName, - operations: operationStats + operations: operationStats, }; } @@ -235,15 +238,16 @@ export class OperationRegistry { }>; }> { const providerStats = await Promise.all( - Array.from(this.providers.keys()).map(async (providerName) => { + Array.from(this.providers.keys()).map(async providerName => { const provider = this.getProvider(providerName); const tracker = this.getTracker(providerName); const operations = provider.getOperations(); - + // Get stats for first operation to get total symbols - const firstOpStats = operations.length > 0 - ? await tracker.getOperationStats(operations[0].name) - : { totalSymbols: 0, processedSymbols: 0 }; + const firstOpStats = + operations.length > 0 + ? await tracker.getOperationStats(at(operations, 0).name) + : { totalSymbols: 0, processedSymbols: 0 }; // Sum processed symbols across all operations let totalProcessed = 0; @@ -256,16 +260,18 @@ export class OperationRegistry { provider: providerName, operationCount: operations.length, totalSymbols: firstOpStats.totalSymbols, - totalProcessed: totalProcessed + totalProcessed: totalProcessed, }; }) ); return { totalProviders: this.providers.size, - totalOperations: Array.from(this.providers.values()) - .reduce((sum, p) => sum + p.getOperations().length, 0), - providerStats + totalOperations: Array.from(this.providers.values()).reduce( + (sum, p) => sum + p.getOperations().length, + 0 + ), + providerStats, }; } @@ -279,9 +285,8 @@ export class OperationRegistry { const results: Array<{ provider: string; operation: OperationConfig }> = []; for (const [providerName, provider] of this.providers) { - const operations = provider.getOperations() - .filter(op => op.type === type); - + const operations = provider.getOperations().filter(op => op.type === type); + operations.forEach(operation => { results.push({ provider: providerName, operation }); }); @@ -297,7 +302,7 @@ export class OperationRegistry { providerName: string, operationName: string, options?: StaleSymbolOptions - ): Promise> { + ): Promise> { const provider = this.getProvider(providerName); const tracker = this.getTracker(providerName); const { collectionName, symbolField } = provider.getProviderConfig(); @@ -310,16 +315,20 @@ export class OperationRegistry { } // Get full symbol data for scheduling - const symbols = await this.mongodb.find(collectionName, { - [symbolField]: { $in: staleSymbols } - }, { - projection: { - [symbolField]: 1, - symbol: 1, - exchange: 1, - // Include any other fields needed for scheduling + const symbols = await this.mongodb.find( + collectionName, + { + [symbolField]: { $in: staleSymbols }, + }, + { + projection: { + [symbolField]: 1, + symbol: 1, + exchange: 1, + // Include any other fields needed for scheduling + }, } - }); + ); return symbols.map(doc => ({ symbol: doc[symbolField], @@ -327,7 +336,7 @@ export class OperationRegistry { symbol: doc.symbol, exchange: doc.exchange, // Include other metadata as needed - } + }, })); } } diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts index 62c8677e..52258450 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/OperationTracker.ts @@ -1,8 +1,10 @@ +import { MongoServerError, type Document, type Filter } from 'mongodb'; /** * General operation tracker that works with any provider */ import type { Logger, MongoDBClient } from '@stock-bot/services'; +import { at } from '@stock-bot/utils'; import type { BaseOperationProvider } from './BaseOperationProvider'; import type { BulkOperationUpdate, @@ -11,7 +13,7 @@ import type { OperationStats, OperationUpdate, StaleSymbolOptions, - SymbolWithOperations + SymbolWithOperations, } from './types'; /** @@ -23,10 +25,7 @@ export class OperationTracker { private provider: BaseOperationProvider; private indexesCreated: Set = new Set(); - constructor( - { mongodb, logger }: OperationComponentOptions, - provider: BaseOperationProvider - ) { + constructor({ mongodb, logger }: OperationComponentOptions, provider: BaseOperationProvider) { this.mongodb = mongodb; this.logger = logger; this.provider = provider; @@ -49,7 +48,7 @@ export class OperationTracker { } this.logger.info(`Operation tracker initialized for ${name}`, { - operationCount: operations.length + operationCount: operations.length, }); } @@ -58,7 +57,7 @@ export class OperationTracker { */ private async createOperationIndexes(operation: OperationConfig): Promise { const { collectionName, symbolField } = this.provider.getProviderConfig(); - + if (this.indexesCreated.has(operation.name)) { return; } @@ -66,61 +65,67 @@ export class OperationTracker { try { const indexes = [ // Index for finding stale symbols - { - [`operations.${operation.name}.lastSuccessAt`]: 1, - [symbolField]: 1 + { + [`operations.${operation.name}.lastSuccessAt`]: 1, + [symbolField]: 1, }, // Index for finding by last record date - { - [`operations.${operation.name}.lastRecordDate`]: 1, - [symbolField]: 1 + { + [`operations.${operation.name}.lastRecordDate`]: 1, + [symbolField]: 1, }, // Index for operation status - { - [`operations.${operation.name}.status`]: 1, - [symbolField]: 1 - } + { + [`operations.${operation.name}.status`]: 1, + [symbolField]: 1, + }, ]; // Add crawl-specific indexes for crawl operations if (operation.type === 'crawl' || operation.type === 'intraday_crawl') { indexes.push( - { - [`operations.${operation.name}.finished`]: 1, - [symbolField]: 1 + { + [`operations.${operation.name}.finished`]: 1, + [symbolField]: 1, }, { [`operations.${operation.name}.newestDateReached`]: 1, - [symbolField]: 1 + [symbolField]: 1, }, { [`operations.${operation.name}.oldestDateReached`]: 1, - [symbolField]: 1 + [symbolField]: 1, } ); } const collection = this.mongodb.collection(collectionName); - + for (const indexSpec of indexes) { try { await collection.createIndex(indexSpec, { background: true, - name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}` + name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}`, }); } catch (indexError) { // Log but don't fail if index already exists or we hit the limit - if (indexError.message?.includes('too many indexes') || indexError.code === 86) { + if ( + indexError instanceof MongoServerError && + (indexError.message.includes('too many indexes') || indexError.code === 86) + ) { this.logger.warn(`Skipping index creation due to limit`, { operation: operation.name, index: Object.keys(indexSpec).join('_'), - error: indexError.message + error: indexError.message, }); - } else if (indexError.code === 11000 || indexError.code === 85) { + } else if ( + indexError instanceof MongoServerError && + (indexError.code === 11000 || indexError.code === 85) + ) { // Index already exists this.logger.debug(`Index already exists`, { operation: operation.name, - index: Object.keys(indexSpec).join('_') + index: Object.keys(indexSpec).join('_'), }); } else { throw indexError; @@ -129,16 +134,16 @@ export class OperationTracker { } this.indexesCreated.add(operation.name); - + this.logger.debug(`Created indexes for operation: ${operation.name}`, { provider: this.provider.getProviderConfig().name, operation: operation.name, - indexCount: indexes.length + indexCount: indexes.length, }); } catch (error) { this.logger.error(`Failed to create indexes for operation: ${operation.name}`, { error, - provider: this.provider.getProviderConfig().name + provider: this.provider.getProviderConfig().name, }); throw error; } @@ -153,19 +158,19 @@ export class OperationTracker { data: OperationUpdate ): Promise { const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig(); - + // Validate operation exists this.provider.validateOperation(operationName); // Call before hook await this.provider.beforeOperationUpdate(symbol, operationName, data); - const update: any = { + const update: Document = { $set: { [`operations.${operationName}.lastRunAt`]: new Date(), [`operations.${operationName}.status`]: data.status, - updated_at: new Date() - } + updated_at: new Date(), + }, }; // Only update lastSuccessAt on successful operations @@ -217,7 +222,7 @@ export class OperationTracker { filter: { [symbolField]: symbol }, symbolField, symbol, - operation: operationName + operation: operationName, }); const updateResult = await this.mongodb.updateOne( @@ -230,7 +235,7 @@ export class OperationTracker { matched: updateResult.matchedCount, modified: updateResult.modifiedCount, symbol, - operation: operationName + operation: operationName, }); // Call after hook @@ -240,7 +245,7 @@ export class OperationTracker { provider: providerName, symbol, operation: operationName, - status: data.status + status: data.status, }); } @@ -248,7 +253,9 @@ export class OperationTracker { * Bulk update symbol operations for performance */ async bulkUpdateSymbolOperations(updates: BulkOperationUpdate[]): Promise { - if (updates.length === 0) {return;} + if (updates.length === 0) { + return; + } const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig(); @@ -256,7 +263,7 @@ export class OperationTracker { const operationGroups = new Map(); for (const update of updates) { this.provider.validateOperation(update.operation); - + const group = operationGroups.get(update.operation) || []; group.push(update); operationGroups.set(update.operation, group); @@ -269,12 +276,12 @@ export class OperationTracker { // Build bulk operations const bulkOps = updates.map(({ symbol, operation, data }) => { - const update: any = { + const update: Document = { $set: { [`operations.${operation}.lastRunAt`]: new Date(), [`operations.${operation}.status`]: data.status, - updated_at: new Date() - } + updated_at: new Date(), + }, }; if (data.status === 'success') { @@ -323,8 +330,8 @@ export class OperationTracker { return { updateOne: { filter: { [symbolField]: symbol }, - update - } + update, + }, }; }); @@ -340,7 +347,7 @@ export class OperationTracker { provider: providerName, totalUpdates: updates.length, modified: result.modifiedCount, - operations: Array.from(operationGroups.keys()) + operations: Array.from(operationGroups.keys()), }); } @@ -350,32 +357,41 @@ export class OperationTracker { async getStaleSymbols( operationName: string, options: StaleSymbolOptions = {} - ): Promise> { + ): Promise< + Array<{ + symbol: Document; + lastRun?: Date; + lastSuccess?: Date; + operations?: Record; + }> + > { const { collectionName, symbolField } = this.provider.getProviderConfig(); - const { - limit = 1000, - excludeSymbols = [], + const { + limit = 1000, + excludeSymbols = [], activeOnly = true, symbolFilter, exchanges, - delisted + delisted, } = options; this.provider.validateOperation(operationName); - const cutoffDate = options.notRunSince || (() => { - const date = new Date(); - const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName); - date.setHours(date.getHours() - hours); - return date; - })(); + const cutoffDate = + options.notRunSince || + (() => { + const date = new Date(); + const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName); + date.setHours(date.getHours() - hours); + return date; + })(); - const filter: any = { + const filter: Filter = { $or: [ { [`operations.${operationName}.lastSuccessAt`]: { $lt: cutoffDate } }, { [`operations.${operationName}.lastSuccessAt`]: { $exists: false } }, - { [`operations.${operationName}`]: { $exists: false } } - ] + { [`operations.${operationName}`]: { $exists: false } }, + ], }; if (activeOnly) { @@ -403,15 +419,15 @@ export class OperationTracker { const symbols = await this.mongodb.find(collectionName, filter, { limit, - projection: { }, // Return all fields - sort: { [`operations.${operationName}.lastSuccessAt`]: 1 } + projection: {}, // Return all fields + sort: { [`operations.${operationName}.lastSuccessAt`]: 1 }, }); return symbols.map(doc => ({ symbol: doc, lastRun: doc.operations?.[operationName]?.lastRunAt, lastSuccess: doc.operations?.[operationName]?.lastSuccessAt, - operations: doc.operations + operations: doc.operations, })); } @@ -430,8 +446,8 @@ export class OperationTracker { this.provider.validateOperation(operationName); - const filter: any = { - active: { $ne: false } + const filter: Filter = { + active: { $ne: false }, }; if (!includeFinished) { @@ -442,17 +458,17 @@ export class OperationTracker { limit, projection: { [symbolField]: 1, - [`operations.${operationName}`]: 1 + [`operations.${operationName}`]: 1, }, sort: { - [`operations.${operationName}.lastRunAt`]: 1 - } + [`operations.${operationName}.lastRunAt`]: 1, + }, }); return symbols.map(doc => ({ symbol: doc[symbolField], lastRecordDate: doc.operations?.[operationName]?.lastRecordDate, - operationStatus: doc.operations?.[operationName] + operationStatus: doc.operations?.[operationName], })); } @@ -469,7 +485,7 @@ export class OperationTracker { status: 'success', finished: true, oldestDateReached, - newestDateReached: newestDateReached || new Date() + newestDateReached: newestDateReached || new Date(), }); this.logger.info('Marked crawl as finished', { @@ -477,7 +493,7 @@ export class OperationTracker { symbol, operation: operationName, oldestDateReached, - newestDateReached + newestDateReached, }); } @@ -499,8 +515,8 @@ export class OperationTracker { this.provider.validateOperation(operationName); // Build filter - const filter: any = { - active: { $ne: false } + const filter: Filter = { + active: { $ne: false }, }; // Add symbol filter if provided @@ -512,18 +528,18 @@ export class OperationTracker { // 1. Have never been crawled // 2. Are not finished // 3. Have gaps (new data since last crawl) - const orConditions = [ + const orConditions: Filter[] = [ { [`operations.${operationName}`]: { $exists: false } }, - { [`operations.${operationName}.finished`]: { $ne: true } } + { [`operations.${operationName}.finished`]: { $ne: true } }, ]; if (includeNewDataGaps) { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); yesterday.setHours(0, 0, 0, 0); - + orConditions.push({ - [`operations.${operationName}.newestDateReached`]: { $lt: yesterday } + [`operations.${operationName}.newestDateReached`]: { $lt: yesterday }, }); } @@ -537,19 +553,19 @@ export class OperationTracker { // Include common fields that might be needed symbol: 1, exchange: 1, - qmSearchCode: 1 + qmSearchCode: 1, }, sort: { - [`operations.${operationName}.lastRunAt`]: 1 - } + [`operations.${operationName}.lastRunAt`]: 1, + }, }); return symbols.map(doc => { const opStatus = doc.operations?.[operationName]; - + // Determine gaps (only backward since we removed forward crawling) const gaps: { forward?: boolean; backward?: boolean } = {}; - + if (opStatus) { // Only check for backward gap (historical data) if (!opStatus.finished) { @@ -570,7 +586,7 @@ export class OperationTracker { gaps, // Include other potentially useful fields exchange: doc.exchange, - qmSearchCode: doc.qmSearchCode || doc[symbolField] + qmSearchCode: doc.qmSearchCode || doc[symbolField], } as SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } }; }); } @@ -584,19 +600,23 @@ export class OperationTracker { targetOldestDate: Date ): Promise { const { collectionName, symbolField } = this.provider.getProviderConfig(); - - const doc = await this.mongodb.findOne(collectionName, { - [symbolField]: symbol - }, { - projection: { [`operations.${operationName}`]: 1 } - }); + + const doc = await this.mongodb.findOne( + collectionName, + { + [symbolField]: symbol, + }, + { + projection: { [`operations.${operationName}`]: 1 }, + } + ); if (!doc?.operations?.[operationName]) { return false; } const opStatus = doc.operations[operationName]; - + // Check if explicitly marked as finished if (opStatus.finished) { return true; @@ -626,8 +646,8 @@ export class OperationTracker { this.provider.validateOperation(operationName); - const filter: any = { - active: { $ne: false } + const filter: Filter = { + active: { $ne: false }, }; if (options.neverRun) { @@ -635,7 +655,7 @@ export class OperationTracker { } else if (options.lastRecordBefore) { filter.$or = [ { [`operations.${operationName}.lastRecordDate`]: { $lt: options.lastRecordBefore } }, - { [`operations.${operationName}`]: { $exists: false } } + { [`operations.${operationName}`]: { $exists: false } }, ]; } @@ -644,15 +664,15 @@ export class OperationTracker { projection: { [symbolField]: 1, [`operations.${operationName}.lastRecordDate`]: 1, - [`operations.${operationName}`]: 1 + [`operations.${operationName}`]: 1, }, - sort: { [`operations.${operationName}.lastRecordDate`]: 1 } + sort: { [`operations.${operationName}.lastRecordDate`]: 1 }, }); return symbols.map(doc => ({ symbol: doc[symbolField], lastRecordDate: doc.operations?.[operationName]?.lastRecordDate, - operationStatus: doc.operations?.[operationName] + operationStatus: doc.operations?.[operationName], })); } @@ -662,60 +682,53 @@ export class OperationTracker { async getOperationStats(operationName: string): Promise { const { collectionName } = this.provider.getProviderConfig(); const operation = this.provider.getOperation(operationName); - + if (!operation) { throw new Error(`Unknown operation: ${operationName}`); } const collection = this.mongodb.collection(collectionName); - - const [ - total, - processed, - successful, - failed, - staleStats, - crawlStats, - recordStats - ] = await Promise.all([ - // Total symbols - collection.countDocuments({}), - - // Processed symbols - collection.countDocuments({ - [`operations.${operationName}`]: { $exists: true } - }), - - // Successful symbols - collection.countDocuments({ - [`operations.${operationName}.status`]: 'success' - }), - - // Failed symbols - collection.countDocuments({ - [`operations.${operationName}.status`]: 'failure' - }), - - // Stale symbols - this.countStaleSymbols(operationName, operation.defaultStaleHours || 24), - - // Crawl stats (if applicable) - (operation.type === 'crawl' || operation.type === 'intraday_crawl') - ? collection.countDocuments({ - [`operations.${operationName}.finished`]: true - }) - : Promise.resolve(undefined), - - // Average records - this.calculateAverageRecords(operationName) - ]); + + const [total, processed, successful, failed, staleStats, crawlStats, recordStats] = + await Promise.all([ + // Total symbols + collection.countDocuments({}), + + // Processed symbols + collection.countDocuments({ + [`operations.${operationName}`]: { $exists: true }, + }), + + // Successful symbols + collection.countDocuments({ + [`operations.${operationName}.status`]: 'success', + }), + + // Failed symbols + collection.countDocuments({ + [`operations.${operationName}.status`]: 'failure', + }), + + // Stale symbols + this.countStaleSymbols(operationName, operation.defaultStaleHours || 24), + + // Crawl stats (if applicable) + operation.type === 'crawl' || operation.type === 'intraday_crawl' + ? collection.countDocuments({ + [`operations.${operationName}.finished`]: true, + }) + : Promise.resolve(undefined), + + // Average records + this.calculateAverageRecords(operationName), + ]); const result: OperationStats = { totalSymbols: total, processedSymbols: processed, staleSymbols: staleStats, successfulSymbols: successful, - failedSymbols: failed + failedSymbols: failed, }; if (crawlStats !== undefined) { @@ -735,15 +748,15 @@ export class OperationTracker { private async countStaleSymbols(operationName: string, staleHours: number): Promise { const { collectionName } = this.provider.getProviderConfig(); const collection = this.mongodb.collection(collectionName); - + const staleDate = new Date(); staleDate.setHours(staleDate.getHours() - staleHours); return collection.countDocuments({ $or: [ { [`operations.${operationName}.lastSuccessAt`]: { $lt: staleDate } }, - { [`operations.${operationName}`]: { $exists: false } } - ] + { [`operations.${operationName}`]: { $exists: false } }, + ], }); } @@ -753,23 +766,25 @@ export class OperationTracker { private async calculateAverageRecords(operationName: string): Promise { const { collectionName } = this.provider.getProviderConfig(); const collection = this.mongodb.collection(collectionName); - - const aggregation = await collection.aggregate([ - { - $match: { - [`operations.${operationName}.recordCount`]: { $exists: true } - } - }, - { - $group: { - _id: null, - avgRecords: { $avg: `$operations.${operationName}.recordCount` } - } - } - ]).toArray(); - if (aggregation.length > 0 && aggregation[0].avgRecords) { - return Math.round(aggregation[0].avgRecords); + const aggregation = await collection + .aggregate([ + { + $match: { + [`operations.${operationName}.recordCount`]: { $exists: true }, + }, + }, + { + $group: { + _id: null, + avgRecords: { $avg: `$operations.${operationName}.recordCount` }, + }, + }, + ]) + .toArray(); + + if (aggregation.length > 0 && at(aggregation, 0).avgRecords) { + return Math.round(at(aggregation, 0).avgRecords); } return undefined; diff --git a/apps/stock/data-ingestion/src/shared/operation-manager/types.ts b/apps/stock/data-ingestion/src/shared/operation-manager/types.ts index bf60c408..b8984888 100644 --- a/apps/stock/data-ingestion/src/shared/operation-manager/types.ts +++ b/apps/stock/data-ingestion/src/shared/operation-manager/types.ts @@ -21,7 +21,7 @@ export interface OperationConfig { /** Whether operation requires a finished flag (for crawl operations) */ requiresFinishedFlag?: boolean; /** Custom metadata for provider-specific needs */ - metadata?: Record; + metadata?: Record; } /** @@ -41,8 +41,8 @@ export interface OperationStatus { /** Error message if status is failure */ error?: string; /** Provider-specific metadata */ - metadata?: Record; - + metadata?: Record; + // Crawl-specific fields (used for crawl and intraday_crawl operations) /** Whether the crawl has completed */ finished?: boolean; @@ -89,8 +89,8 @@ export interface OperationUpdate { /** Error message for failures */ error?: string; /** Additional metadata */ - metadata?: Record; - + metadata?: Record; + // Crawl-specific update fields /** Whether the crawl has completed */ finished?: boolean; @@ -161,7 +161,7 @@ export interface OperationStats { /** Average records per symbol */ avgRecordsPerSymbol?: number; /** Additional provider-specific stats */ - customStats?: Record; + customStats?: Record; } /** @@ -175,7 +175,7 @@ export interface SymbolWithOperations { /** Full operation status */ operationStatus?: OperationStatus; /** Additional symbol data */ - metadata?: Record; + metadata?: Record; } /** diff --git a/apps/stock/data-ingestion/src/types.ts b/apps/stock/data-ingestion/src/types.ts index 7a75ca47..1a9f79a8 100644 --- a/apps/stock/data-ingestion/src/types.ts +++ b/apps/stock/data-ingestion/src/types.ts @@ -1,3 +1,4 @@ +import { requireServices } from '@stock-bot/services'; /** * Data Ingestion Service Types * Defines required services for data ingestion handlers @@ -19,7 +20,22 @@ export type DataIngestionServices = ServiceTypes & { browser: NonNullable; proxy: NonNullable; // Optional services remain optional - postgres: ServiceTypes['postgres']; - questdb: ServiceTypes['questdb']; - globalCache: ServiceTypes['globalCache']; + postgres?: ServiceTypes['postgres']; + questdb?: ServiceTypes['questdb']; + globalCache?: ServiceTypes['globalCache']; }; + +export function resolveIngestionServices( + services: import('@stock-bot/services').IServiceContainer, + handler: string +): DataIngestionServices { + const required = requireServices( + services, + 'mongodb', + 'cache', + 'queueManager', + 'browser', + 'proxy' + ); + return { ...required, queue: required.queueManager.getQueue(handler) }; +} diff --git a/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts b/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts index 4c895f73..5c4ff0b6 100755 --- a/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts +++ b/apps/stock/data-ingestion/test/test-advanced-rate-limit.ts @@ -1,100 +1,99 @@ -#!/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); -}); \ No newline at end of file +#!/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 index 2eb1b7a1..9732f481 100644 --- a/apps/stock/data-ingestion/test/test-intraday-flow.ts +++ b/apps/stock/data-ingestion/test/test-intraday-flow.ts @@ -1,156 +1,163 @@ -/** - * Test script to verify intraday crawl data flow - */ - -import { OperationTracker, OperationRegistry } 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); \ No newline at end of file +/** + * 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 index 83fca7e0..c5f3af41 100644 --- a/apps/stock/data-ingestion/test/test-modified-functions.ts +++ b/apps/stock/data-ingestion/test/test-modified-functions.ts @@ -1,139 +1,139 @@ -/** - * 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); \ No newline at end of file +/** + * 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-symbol-x.ts b/apps/stock/data-ingestion/test/test-symbol-x.ts index a0e88ac1..9c196c56 100644 --- a/apps/stock/data-ingestion/test/test-symbol-x.ts +++ b/apps/stock/data-ingestion/test/test-symbol-x.ts @@ -1,118 +1,122 @@ -/** - * Test script specifically for symbol X operations - */ - -import { QMHandler } from '../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); \ No newline at end of file +/** + * 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 0041c730..1e0ebde8 100644 --- a/apps/stock/data-pipeline/package.json +++ b/apps/stock/data-pipeline/package.json @@ -24,7 +24,8 @@ "@stock-bot/shutdown": "*", "@stock-bot/handlers": "*", "@stock-bot/di": "*", - "hono": "^4.0.0" + "hono": "^4.0.0", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "typescript": "^5.0.0" diff --git a/apps/stock/data-pipeline/src/container-setup.ts b/apps/stock/data-pipeline/src/container-setup.ts index 64df20e1..356de764 100644 --- a/apps/stock/data-pipeline/src/container-setup.ts +++ b/apps/stock/data-pipeline/src/container-setup.ts @@ -3,7 +3,7 @@ * Configures dependency injection for the data pipeline service */ -import type { AppConfig } from '@stock-bot/config'; +import type { UnifiedAppConfig } from '@stock-bot/config'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; @@ -13,7 +13,7 @@ const logger = getLogger('data-pipeline-container'); * Configure the service container for data pipeline workloads */ export function setupServiceContainer( - config: AppConfig, + config: UnifiedAppConfig, container: IServiceContainer ): IServiceContainer { logger.info('Configuring data pipeline service container...'); 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 8db8fdc8..0146f531 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -26,7 +26,7 @@ class ExchangesHandler extends BaseHandler { async syncAllExchanges(payload?: { clearFirst?: boolean }): Promise { const finalPayload = payload || { clearFirst: true }; this.log('info', 'Starting sync of all exchanges', finalPayload); - return syncAllExchanges(finalPayload, this.services); + return syncAllExchanges(finalPayload, this); } /** @@ -39,7 +39,7 @@ class ExchangesHandler extends BaseHandler { }) async syncQMExchanges(): Promise { this.log('info', 'Starting QM exchanges sync...'); - return syncQMExchanges({}, this.services); + return syncQMExchanges({}, this); } /** @@ -52,7 +52,7 @@ class ExchangesHandler extends BaseHandler { }) async syncIBExchanges(): Promise { this.log('info', 'Starting IB exchanges sync...'); - return syncIBExchanges({}, this.services); + return syncIBExchanges({}, this); } /** @@ -65,7 +65,7 @@ class ExchangesHandler extends BaseHandler { }) async syncQMProviderMappings(): Promise { this.log('info', 'Starting QM provider mappings sync...'); - return syncQMProviderMappings({}, this.services); + return syncQMProviderMappings({}, this); } /** @@ -76,7 +76,7 @@ class ExchangesHandler extends BaseHandler { type?: 'exchanges' | 'provider_mappings' | 'all'; }): Promise { this.log('warn', 'Clearing PostgreSQL data', payload); - return clearPostgreSQLData(payload, this.services); + return clearPostgreSQLData(payload, this); } /** @@ -85,7 +85,7 @@ class ExchangesHandler extends BaseHandler { @Operation('get-exchange-stats') async getExchangeStats(): Promise { this.log('info', 'Getting exchange statistics...'); - return getExchangeStats({}, this.services); + return getExchangeStats({}, this); } /** @@ -94,7 +94,7 @@ class ExchangesHandler extends BaseHandler { @Operation('get-provider-mapping-stats') async getProviderMappingStats(): Promise { this.log('info', 'Getting provider mapping statistics...'); - return getProviderMappingStats({}, this.services); + return getProviderMappingStats({}, this); } /** @@ -103,7 +103,7 @@ class ExchangesHandler extends BaseHandler { @Operation('enhanced-sync-status') async getEnhancedSyncStatus(): Promise { this.log('info', 'Getting enhanced sync status...'); - return getSyncStatus({}, this.services); + return getSyncStatus({}, this); } } diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts index 4e0a4d62..401bcf84 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/clear-postgresql-data.operations.ts @@ -1,5 +1,6 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-clear-postgresql-data'); @@ -15,7 +16,7 @@ export async function clearPostgreSQLData( logger.info('Clearing existing PostgreSQL data...'); try { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Start transaction for atomic operations await postgresClient.query('BEGIN'); @@ -29,9 +30,9 @@ export async function clearPostgreSQLData( 'SELECT COUNT(*) as count FROM provider_mappings' ); - const exchangesCleared = parseInt(exchangeCountResult.rows[0].count); - const symbolsCleared = parseInt(symbolCountResult.rows[0].count); - const mappingsCleared = parseInt(mappingCountResult.rows[0].count); + const exchangesCleared = parseInt(at(exchangeCountResult.rows, 0).count); + const symbolsCleared = parseInt(at(symbolCountResult.rows, 0).count); + const mappingsCleared = parseInt(at(mappingCountResult.rows, 0).count); // Clear data in correct order (respect foreign keys) await postgresClient.query('DELETE FROM provider_mappings'); @@ -53,7 +54,7 @@ export async function clearPostgreSQLData( return { exchangesCleared, symbolsCleared, mappingsCleared }; } catch (error) { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); await postgresClient.query('ROLLBACK'); logger.error('Failed to clear PostgreSQL data', { error }); throw error; 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 index c3534d9c..0ea9a797 100644 --- 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 @@ -1,5 +1,5 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; 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'); @@ -11,14 +11,14 @@ export async function getSyncStatus( logger.info('Getting comprehensive sync status...'); try { - const postgresClient = container.postgres; + 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); + const result = await postgresClient.query(query); logger.info(`Retrieved sync status for ${result.rows.length} entries`); return result.rows; diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/exchange-stats.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/exchange-stats.operations.ts index ed14dc0a..836314d2 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/exchange-stats.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/exchange-stats.operations.ts @@ -1,5 +1,6 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-exchange-stats'); @@ -18,7 +19,7 @@ export async function getExchangeStats( logger.info('Getting exchange statistics...'); try { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` SELECT COUNT(*) as total_exchanges, @@ -27,10 +28,10 @@ export async function getExchangeStats( COUNT(DISTINCT currency) as currencies FROM exchanges `; - const result = await postgresClient.query(query); + const result = await postgresClient.query(query); logger.info('Retrieved exchange statistics'); - return result.rows[0]; + return at(result.rows, 0); } catch (error) { logger.error('Failed to get exchange statistics', { error }); throw error; diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/provider-mapping-stats.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/provider-mapping-stats.operations.ts index 7d4962da..ce56be32 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/provider-mapping-stats.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/provider-mapping-stats.operations.ts @@ -1,5 +1,5 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-provider-mapping-stats'); @@ -20,7 +20,7 @@ export async function getProviderMappingStats( logger.info('Getting provider mapping statistics...'); try { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` SELECT provider, @@ -33,7 +33,7 @@ export async function getProviderMappingStats( GROUP BY provider ORDER BY provider `; - const result = await postgresClient.query(query); + const result = await postgresClient.query(query); logger.info('Retrieved provider mapping statistics'); return result.rows; diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts index 69892edb..a2a482f7 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts @@ -1,5 +1,5 @@ import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/services'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('sync-qm-exchanges'); @@ -11,8 +11,8 @@ export async function syncQMExchanges( logger.info('Starting QM exchanges sync...'); try { - const mongoClient = container.mongodb; - const postgresClient = container.postgres; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); + const { postgres: postgresClient } = requireServices(container, 'postgres'); // 1. Get all QM exchanges from MongoDB const qmExchanges = await mongoClient.find('qmExchanges', {}); @@ -64,10 +64,10 @@ interface Exchange { async function findExchange( exchangeCode: string, - postgresClient: IServiceContainer['postgres'] + postgresClient: NonNullable ): Promise { const query = 'SELECT * FROM exchanges WHERE code = $1'; - const result = await postgresClient.query(query, [exchangeCode]); + const result = await postgresClient.query(query, [exchangeCode]); return result.rows[0] || null; } @@ -81,7 +81,7 @@ interface QMExchange { async function createExchange( qmExchange: QMExchange, - postgresClient: IServiceContainer['postgres'] + postgresClient: NonNullable ): Promise { const query = ` INSERT INTO exchanges (code, name, country, currency, visible) @@ -101,7 +101,7 @@ async function createExchange( async function updateExchange( exchangeId: string, qmExchange: QMExchange, - postgresClient: IServiceContainer['postgres'] + postgresClient: NonNullable ): Promise { const query = ` UPDATE exchanges @@ -122,7 +122,7 @@ async function updateSyncStatus( provider: string, dataType: string, count: number, - postgresClient: IServiceContainer['postgres'] + postgresClient: NonNullable ): Promise { const query = ` UPDATE sync_status diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts index ddaf1fba..4eeb8cc2 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts @@ -1,5 +1,6 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import type { PostgresClient } from '@stock-bot/services'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-all-exchanges'); @@ -20,7 +21,7 @@ export async function syncAllExchanges( }; try { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Clear existing data if requested if (clearFirst) { @@ -46,14 +47,14 @@ export async function syncAllExchanges( logger.info('Comprehensive exchange sync completed', result); return result; } catch (error) { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); await postgresClient.query('ROLLBACK'); logger.error('Comprehensive exchange sync failed', { error }); throw error; } } -async function clearPostgreSQLData(postgresClient: any): Promise { +async function clearPostgreSQLData(postgresClient: PostgresClient): Promise { logger.info('Clearing existing PostgreSQL data...'); // Clear data in correct order (respect foreign keys) @@ -70,7 +71,7 @@ async function clearPostgreSQLData(postgresClient: any): Promise { } async function syncEODExchanges(container: IServiceContainer): Promise { - const mongoClient = container.mongodb; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); const exchanges = await mongoClient.find('eodExchanges', { active: true }); const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; @@ -99,7 +100,7 @@ async function syncEODExchanges(container: IServiceContainer): Promise { - const mongoClient = container.mongodb; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); const exchanges = await mongoClient.find('ibExchanges', {}); const result: SyncResult = { processed: 0, created: 0, updated: 0, skipped: 0, errors: 0 }; @@ -140,7 +141,7 @@ async function createProviderExchangeMapping( return; } - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Check if mapping already exists const existingMapping = await findProviderExchangeMapping( @@ -162,6 +163,10 @@ async function createProviderExchangeMapping( container ); + if (!masterExchange) { + throw new Error('Master exchange was not created or resolved'); + } + // Create the provider exchange mapping const query = ` INSERT INTO provider_exchange_mappings @@ -188,8 +193,8 @@ async function findOrCreateMasterExchange( countryCode: string | null, currency: string | null, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); // First, try to find exact match let masterExchange = await findExchangeByCode(providerCode, container); @@ -244,16 +249,16 @@ async function findProviderExchangeMapping( provider: string, providerExchangeCode: string, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; const result = await postgresClient.query(query, [provider, providerExchangeCode]); return result.rows[0] || null; } -async function findExchangeByCode(code: string, container: IServiceContainer): Promise { - const postgresClient = container.postgres; +async function findExchangeByCode(code: string, container: IServiceContainer) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM exchanges WHERE code = $1'; const result = await postgresClient.query(query, [code]); return result.rows[0] || null; @@ -263,7 +268,7 @@ async function updateSyncStatus( provider: string, dataType: string, count: number, - postgresClient: any + postgresClient: PostgresClient ): Promise { const query = ` INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts index 27b87dcf..6d242194 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts @@ -1,13 +1,13 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; import type { MasterExchange } from '@stock-bot/mongodb'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('sync-ib-exchanges'); interface IBExchange { id?: string; - _id?: any; + _id?: unknown; name?: string; code?: string; country_code?: string; @@ -21,7 +21,7 @@ export async function syncIBExchanges( logger.info('Syncing IB exchanges from database...'); try { - const mongoClient = container.mongodb; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); const db = mongoClient.getDatabase(); // Filter by country code US and CA @@ -69,7 +69,7 @@ async function createOrUpdateMasterExchange( ibExchange: IBExchange, container: IServiceContainer ): Promise { - const mongoClient = container.mongodb; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); const db = mongoClient.getDatabase(); const collection = db.collection('masterExchanges'); diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts index 9e1ed568..8b045a20 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts @@ -1,5 +1,5 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-qm-provider-mappings'); @@ -19,8 +19,8 @@ export async function syncQMProviderMappings( }; try { - const mongoClient = container.mongodb; - const postgresClient = container.postgres; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Start transaction await postgresClient.query('BEGIN'); @@ -79,7 +79,7 @@ export async function syncQMProviderMappings( logger.info('QM provider exchange mappings sync completed', result); return result; } catch (error) { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); await postgresClient.query('ROLLBACK'); logger.error('QM provider exchange mappings sync failed', { error }); throw error; @@ -99,7 +99,7 @@ async function createProviderExchangeMapping( return; } - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Check if mapping already exists const existingMapping = await findProviderExchangeMapping( @@ -121,6 +121,10 @@ async function createProviderExchangeMapping( container ); + if (!masterExchange) { + throw new Error('Master exchange was not created or resolved'); + } + // Create the provider exchange mapping const query = ` INSERT INTO provider_exchange_mappings @@ -145,8 +149,8 @@ async function findProviderExchangeMapping( provider: string, providerExchangeCode: string, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2'; const result = await postgresClient.query(query, [provider, providerExchangeCode]); @@ -159,8 +163,8 @@ async function findOrCreateMasterExchange( countryCode: string | null, currency: string | null, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); // First, try to find exact match let masterExchange = await findExchangeByCode(providerCode, container); @@ -211,8 +215,8 @@ function getBasicExchangeMapping(providerCode: string): string | null { return mappings[providerCode.toUpperCase()] || null; } -async function findExchangeByCode(code: string, container: IServiceContainer): Promise { - const postgresClient = container.postgres; +async function findExchangeByCode(code: string, container: IServiceContainer) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM exchanges WHERE code = $1'; const result = await postgresClient.query(query, [code]); return result.rows[0] || null; diff --git a/apps/stock/data-pipeline/src/handlers/index.ts b/apps/stock/data-pipeline/src/handlers/index.ts index 9fef2055..4d150c24 100644 --- a/apps/stock/data-pipeline/src/handlers/index.ts +++ b/apps/stock/data-pipeline/src/handlers/index.ts @@ -1,3 +1,4 @@ +import type { HandlerInitializationContext } from '@stock-bot/di'; /** * Handler registration for data pipeline service */ @@ -13,7 +14,10 @@ const logger = getLogger('pipeline-handler-init'); /** * Initialize and register all handlers */ -export async function initializeAllHandlers(container: IServiceContainer): Promise { +export async function initializeAllHandlers( + _container: IServiceContainer, + context: HandlerInitializationContext +): Promise { logger.info('Initializing data pipeline handlers...'); try { @@ -22,7 +26,7 @@ export async function initializeAllHandlers(container: IServiceContainer): Promi for (const Handler of handlers) { try { - const instance = new Handler(container); + context.handlerScanner.registerHandlerClass(Handler, { serviceName: 'data-pipeline' }); // Register the handler instance if needed logger.info(`Registered handler: ${Handler.name}`); } catch (error) { diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts index d4a38db7..13642c6b 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts @@ -1,5 +1,8 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; +import type { Document } from 'mongodb'; +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; +import type { PostgresClient } from '@stock-bot/services'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('sync-qm-symbols'); @@ -11,8 +14,8 @@ export async function syncQMSymbols( logger.info('Starting QM symbols sync...'); try { - const mongoClient = container.mongodb; - const postgresClient = container.postgres; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); + const { postgres: postgresClient } = requireServices(container, 'postgres'); // 1. Get all QM symbols from MongoDB const qmSymbols = await mongoClient.find('qmSymbols', {}); @@ -69,7 +72,10 @@ export async function syncQMSymbols( } // Helper functions -async function resolveExchange(exchangeCode: string, postgresClient: any): Promise { +async function resolveExchange( + exchangeCode: string, + postgresClient: PostgresClient +): Promise { if (!exchangeCode) { return null; } @@ -94,16 +100,16 @@ async function resolveExchange(exchangeCode: string, postgresClient: any): Promi return result.rows[0]?.id || null; } -async function findSymbol(symbol: string, exchangeId: string, postgresClient: any): Promise { +async function findSymbol(symbol: string, exchangeId: string, postgresClient: PostgresClient) { const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2'; const result = await postgresClient.query(query, [symbol, exchangeId]); return result.rows[0] || null; } async function createSymbol( - qmSymbol: any, + qmSymbol: Document, exchangeId: string, - postgresClient: any + postgresClient: PostgresClient ): Promise { const query = ` INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) @@ -119,10 +125,14 @@ async function createSymbol( qmSymbol.currency || 'USD', ]); - return result.rows[0].id; + return at(result.rows, 0).id; } -async function updateSymbol(symbolId: string, qmSymbol: any, postgresClient: any): Promise { +async function updateSymbol( + symbolId: string, + qmSymbol: Document, + postgresClient: PostgresClient +): Promise { const query = ` UPDATE symbols SET company_name = COALESCE($2, company_name), @@ -143,8 +153,8 @@ async function updateSymbol(symbolId: string, qmSymbol: any, postgresClient: any async function upsertProviderMapping( symbolId: string, provider: string, - qmSymbol: any, - postgresClient: any + qmSymbol: Document, + postgresClient: PostgresClient ): Promise { const query = ` INSERT INTO provider_mappings @@ -169,7 +179,7 @@ async function updateSyncStatus( provider: string, dataType: string, count: number, - postgresClient: any + postgresClient: PostgresClient ): Promise { const query = ` UPDATE sync_status diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-status.operations.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-status.operations.ts index fe5999bc..80c233ba 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-status.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-status.operations.ts @@ -1,5 +1,5 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload } from '../../../types/job-payloads'; const logger = getLogger('sync-status'); @@ -11,7 +11,7 @@ export async function getSyncStatus( logger.info('Getting sync status...'); try { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM sync_status ORDER BY provider, data_type'; const result = await postgresClient.query(query); diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts index 5b332754..032edb23 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts @@ -1,5 +1,8 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; +import type { Document } from 'mongodb'; +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; +import type { PostgresClient } from '@stock-bot/services'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import type { JobPayload, SyncResult } from '../../../types/job-payloads'; const logger = getLogger('enhanced-sync-symbols-from-provider'); @@ -26,8 +29,8 @@ export async function syncSymbolsFromProvider( }; try { - const mongoClient = container.mongodb; - const postgresClient = container.postgres; + const { mongodb: mongoClient } = requireServices(container, 'mongodb'); + const { postgres: postgresClient } = requireServices(container, 'postgres'); // Clear existing data if requested (only symbols and mappings, keep exchanges) if (clearFirst) { @@ -76,21 +79,26 @@ export async function syncSymbolsFromProvider( } // Update sync status - await updateSyncStatus(provider, 'symbols', result.processed, container.postgres); + await updateSyncStatus( + provider, + 'symbols', + result.processed, + requireServices(container, 'postgres').postgres + ); await postgresClient.query('COMMIT'); logger.info(`${provider} symbols sync completed`, result); return result; } catch (error) { - await container.postgres.query('ROLLBACK'); + await requireServices(container, 'postgres').postgres.query('ROLLBACK'); logger.error(`${provider} symbols sync failed`, { error }); throw error; } } async function processSingleSymbol( - symbol: any, + symbol: Document, provider: string, result: SyncResult, container: IServiceContainer @@ -137,8 +145,8 @@ async function findActiveProviderExchangeMapping( provider: string, providerExchangeCode: string, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` SELECT pem.*, e.code as master_exchange_code FROM provider_exchange_mappings pem @@ -153,19 +161,19 @@ async function findSymbolByCodeAndExchange( symbol: string, exchangeId: string, container: IServiceContainer -): Promise { - const postgresClient = container.postgres; +) { + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = 'SELECT * FROM symbols WHERE symbol = $1 AND exchange_id = $2'; const result = await postgresClient.query(query, [symbol, exchangeId]); return result.rows[0] || null; } async function createSymbol( - symbol: any, + symbol: Document, exchangeId: string, container: IServiceContainer ): Promise { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) VALUES ($1, $2, $3, $4, $5) @@ -180,15 +188,15 @@ async function createSymbol( symbol.currency || 'USD', ]); - return result.rows[0].id; + return at(result.rows, 0).id; } async function updateSymbol( symbolId: string, - symbol: any, + symbol: Document, container: IServiceContainer ): Promise { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` UPDATE symbols SET company_name = COALESCE($2, company_name), @@ -209,10 +217,10 @@ async function updateSymbol( async function upsertProviderMapping( symbolId: string, provider: string, - symbol: any, + symbol: Document, container: IServiceContainer ): Promise { - const postgresClient = container.postgres; + const { postgres: postgresClient } = requireServices(container, 'postgres'); const query = ` INSERT INTO provider_mappings (symbol_id, provider, provider_symbol, provider_exchange, last_seen) @@ -236,7 +244,7 @@ async function updateSyncStatus( provider: string, dataType: string, count: number, - postgresClient: any + postgresClient: PostgresClient ): Promise { const query = ` INSERT INTO sync_status (provider, data_type, last_sync_at, last_sync_count, sync_errors) diff --git a/apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts b/apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts index 3d7499ef..c057f29d 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts @@ -24,7 +24,7 @@ class SymbolsHandler extends BaseHandler { }) async syncQMSymbols(): Promise<{ processed: number; created: number; updated: number }> { this.log('info', 'Starting QM symbols sync...'); - return syncQMSymbols({}, this.services); + return syncQMSymbols({}, this); } /** @@ -55,7 +55,7 @@ class SymbolsHandler extends BaseHandler { @Operation('sync-status') async getSyncStatus(): Promise { this.log('info', 'Getting symbol sync status...'); - return getSyncStatus({}, this.services); + return getSyncStatus({}, this); } /** @@ -66,7 +66,7 @@ class SymbolsHandler extends BaseHandler { clearFirst?: boolean; }): Promise { this.log('info', 'Syncing symbols from provider', { provider: payload.provider }); - return syncSymbolsFromProvider(payload, this.services); + return syncSymbolsFromProvider(payload, this); } } diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index df4322fa..4cda4944 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -44,8 +44,7 @@ const app = new ServiceApplication( // Custom lifecycle hooks onContainerReady: container => { // Setup service-specific configuration - const enhancedContainer = setupServiceContainer(config, container); - return enhancedContainer; + setupServiceContainer(config, container); }, onStarted: _port => { const logger = getLogger('data-pipeline'); @@ -55,7 +54,7 @@ const app = new ServiceApplication( ); // Container factory function -async function createContainer(config: any) { +async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) { const { ServiceContainerBuilder } = await import('@stock-bot/di'); const builder = new ServiceContainerBuilder(); diff --git a/apps/stock/data-pipeline/src/routes/create-routes.ts b/apps/stock/data-pipeline/src/routes/create-routes.ts index 356ba42c..d7012b85 100644 --- a/apps/stock/data-pipeline/src/routes/create-routes.ts +++ b/apps/stock/data-pipeline/src/routes/create-routes.ts @@ -13,12 +13,6 @@ import { createSyncRoutes } from './sync.routes'; export function createRoutes(container: IServiceContainer): Hono { const app = new Hono(); - // Add container to context for all routes - app.use('*', async (c, next) => { - c.set('container', container); - await next(); - }); - // Mount routes app.route('/health', healthRoutes); app.route('/sync', createSyncRoutes(container)); diff --git a/apps/stock/data-pipeline/src/types/job-payloads.ts b/apps/stock/data-pipeline/src/types/job-payloads.ts index 98ba1531..b261db29 100644 --- a/apps/stock/data-pipeline/src/types/job-payloads.ts +++ b/apps/stock/data-pipeline/src/types/job-payloads.ts @@ -1,4 +1,6 @@ export interface JobPayload { + provider?: string; + clearFirst?: boolean; [key: string]: unknown; } diff --git a/apps/stock/engine/src/api/backtest.rs b/apps/stock/engine/src/api/backtest.rs index cf4e3f7c..cfea7de6 100644 --- a/apps/stock/engine/src/api/backtest.rs +++ b/apps/stock/engine/src/api/backtest.rs @@ -1,473 +1,415 @@ -use napi::bindgen_prelude::*; -use napi_derive::napi; -use std::sync::Arc; -use parking_lot::Mutex; -use crate::backtest::{ - BacktestEngine as RustBacktestEngine, - BacktestConfig, - Strategy, Signal, -}; -use crate::{TradingMode, MarketUpdate}; -use chrono::{DateTime, Utc}; - -#[napi] -pub struct BacktestEngine { - inner: Arc>>, -} - -#[napi] -impl BacktestEngine { - #[napi(constructor)] - pub fn new(config: napi::JsObject, env: Env) -> Result { - let config = parse_backtest_config(config)?; - - // Create mode - let mode = TradingMode::Backtest { - start_time: config.start_time, - end_time: config.end_time, - speed_multiplier: 0.0, // Max speed - }; - - // Create components - let time_provider = crate::core::create_time_provider(&mode); - let market_data_source = crate::core::create_market_data_source(&mode); - let execution_handler = crate::core::create_execution_handler(&mode); - - let engine = RustBacktestEngine::new( - config, - mode, - time_provider, - market_data_source, - execution_handler, - ); - - Ok(Self { - inner: Arc::new(Mutex::new(Some(engine))), - }) - } - - #[napi] - pub fn add_typescript_strategy( - &mut self, - name: String, - id: String, - parameters: napi::JsObject, - _callback: napi::JsFunction, - ) -> Result<()> { - eprintln!("Adding strategy: {}", name); - - // For now, we'll add a native Rust SMA strategy - // In the future, we'll implement proper TypeScript callback support - let fast_period: usize = parameters.get_named_property::("fastPeriod") - .unwrap_or(5.0) as usize; - let slow_period: usize = parameters.get_named_property::("slowPeriod") - .unwrap_or(15.0) as usize; - - if let Some(engine) = self.inner.lock().as_mut() { - engine.add_strategy(Box::new(SimpleSMAStrategy::new( - name.clone(), - id, - fast_period, - slow_period, - ))); - eprintln!("Strategy '{}' added with fast={}, slow={}", name, fast_period, slow_period); - } - - Ok(()) - } - - #[napi] - pub fn add_native_strategy( - &mut self, - strategy_type: String, - name: String, - id: String, - parameters: napi::JsObject, - ) -> Result<()> { - eprintln!("Adding native Rust strategy: {} ({})", name, strategy_type); - - if let Some(engine) = self.inner.lock().as_mut() { - match strategy_type.as_str() { - "sma_crossover" => { - let fast_period: usize = parameters.get_named_property::("fastPeriod") - .unwrap_or(5.0) as usize; - let slow_period: usize = parameters.get_named_property::("slowPeriod") - .unwrap_or(15.0) as usize; - - engine.add_strategy(Box::new(SimpleSMAStrategy::new( - name.clone(), - id, - fast_period, - slow_period, - ))); - } - "mean_reversion" => { - let lookback_period: usize = parameters.get_named_property::("lookbackPeriod") - .unwrap_or(20.0) as usize; - let entry_threshold: f64 = parameters.get_named_property::("entryThreshold") - .unwrap_or(2.0); - let position_size: f64 = parameters.get_named_property::("positionSize") - .unwrap_or(100.0); - - engine.add_strategy(Box::new(crate::strategies::MeanReversionFixedStrategy::new( - name.clone(), - id, - lookback_period, - entry_threshold, - position_size, - ))); - } - "momentum" => { - let lookback_period: usize = parameters.get_named_property::("lookbackPeriod") - .unwrap_or(14.0) as usize; - let momentum_threshold: f64 = parameters.get_named_property::("momentumThreshold") - .unwrap_or(5.0); - let position_size: f64 = parameters.get_named_property::("positionSize") - .unwrap_or(100.0); - - engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new( - name.clone(), - id, - lookback_period, - momentum_threshold, - position_size, - ))); - } - "pairs_trading" => { - let pair_a: String = parameters.get_named_property::("pairA")?; - let pair_b: String = parameters.get_named_property::("pairB")?; - let lookback_period: usize = parameters.get_named_property::("lookbackPeriod") - .unwrap_or(20.0) as usize; - let entry_threshold: f64 = parameters.get_named_property::("entryThreshold") - .unwrap_or(2.0); - let position_size: f64 = parameters.get_named_property::("positionSize") - .unwrap_or(100.0); - - engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new( - name.clone(), - id, - pair_a, - pair_b, - lookback_period, - entry_threshold, - position_size, - ))); - } - _ => { - return Err(Error::from_reason(format!("Unknown strategy type: {}", strategy_type))); - } - } - eprintln!("Native strategy '{}' added successfully", name); - } - - Ok(()) - } - - #[napi] - pub fn run(&mut self) -> Result { - eprintln!("=== BACKTEST RUN START ==="); - let mut engine = self.inner.lock().take() - .ok_or_else(|| Error::from_reason("Engine already consumed"))?; - - // Config and strategies are private, skip detailed logging - - // Run the backtest synchronously for now - let runtime = tokio::runtime::Runtime::new() - .map_err(|e| Error::from_reason(e.to_string()))?; - - let result = runtime.block_on(engine.run()) - .map_err(|e| { - eprintln!("ERROR: Backtest engine failed: {}", e); - Error::from_reason(e) - })?; - - eprintln!("=== BACKTEST RUN COMPLETE ==="); - eprintln!("Total trades: {}", result.trades.len()); - eprintln!("Equity points: {}", result.equity.len()); - eprintln!("OHLC data symbols: {:?}", result.ohlc_data.keys().collect::>()); - for (symbol, data) in &result.ohlc_data { - eprintln!(" {}: {} bars", symbol, data.len()); - } - - // Return result as JSON - serde_json::to_string(&result) - .map_err(|e| Error::from_reason(e.to_string())) - } - - #[napi] - pub fn load_market_data(&self, data: Vec) -> Result<()> { - eprintln!("load_market_data called with {} items", data.len()); - - // Convert JS objects to MarketData - let market_data: Vec = data.into_iter() - .filter_map(|obj| parse_market_data(obj).ok()) - .collect(); - - eprintln!("Parsed {} valid market data items", market_data.len()); - - // Load data into the historical data source - if let Some(engine) = self.inner.lock().as_ref() { - // Access the market data source through the engine - let mut data_source = engine.market_data_source.write(); - if let Some(historical_source) = data_source.as_any_mut() - .downcast_mut::() { - eprintln!("Loading data into HistoricalDataSource"); - historical_source.load_data(market_data); - eprintln!("Data loaded successfully"); - } else { - eprintln!("ERROR: Could not downcast to HistoricalDataSource"); - } - } else { - eprintln!("ERROR: Engine not found"); - } - - Ok(()) - } -} - - -fn parse_backtest_config(obj: napi::JsObject) -> Result { - let name: String = obj.get_named_property("name")?; - let symbols: Vec = obj.get_named_property("symbols")?; - let start_date: String = obj.get_named_property("startDate")?; - let end_date: String = obj.get_named_property("endDate")?; - let initial_capital: f64 = obj.get_named_property("initialCapital")?; - let commission: f64 = obj.get_named_property("commission")?; - let slippage: f64 = obj.get_named_property("slippage")?; - let data_frequency: String = obj.get_named_property("dataFrequency")?; - let strategy: Option = obj.get_named_property("strategy").ok(); - - Ok(BacktestConfig { - name, - strategy, - symbols, - start_time: DateTime::parse_from_rfc3339(&start_date) - .map_err(|e| Error::from_reason(e.to_string()))? - .with_timezone(&Utc), - end_time: DateTime::parse_from_rfc3339(&end_date) - .map_err(|e| Error::from_reason(e.to_string()))? - .with_timezone(&Utc), - initial_capital, - commission, - slippage, - data_frequency, - }) -} - -fn parse_market_data(obj: napi::JsObject) -> Result { - let symbol: String = obj.get_named_property("symbol")?; - let timestamp: i64 = obj.get_named_property("timestamp")?; - let data_type: String = obj.get_named_property("type")?; - - let data = if data_type == "bar" { - crate::MarketDataType::Bar(crate::Bar { - open: obj.get_named_property("open")?, - high: obj.get_named_property("high")?, - low: obj.get_named_property("low")?, - close: obj.get_named_property("close")?, - volume: obj.get_named_property("volume")?, - vwap: obj.get_named_property("vwap").ok(), - }) - } else { - eprintln!("Unsupported market data type: {}", data_type); - return Err(Error::from_reason("Unsupported market data type")); - }; - - // First few items - static mut COUNT: usize = 0; - unsafe { - if COUNT < 3 { - eprintln!("Parsed market data: symbol={}, timestamp={}, close={}", - symbol, timestamp, - if let crate::MarketDataType::Bar(ref bar) = data { bar.close } else { 0.0 }); - COUNT += 1; - } - } - - Ok(crate::MarketUpdate { - symbol, - timestamp: DateTime::::from_timestamp(timestamp / 1000, 0) - .ok_or_else(|| Error::from_reason("Invalid timestamp"))?, - data, - }) -} - -// Simple SMA Strategy for testing -struct SimpleSMAStrategy { - name: String, - id: String, - fast_period: usize, - slow_period: usize, - price_history: std::collections::HashMap>, - positions: std::collections::HashMap, -} - -impl SimpleSMAStrategy { - fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self { - eprintln!("Creating SimpleSMAStrategy: name={}, fast={}, slow={}", name, fast_period, slow_period); - Self { - name, - id, - fast_period, - slow_period, - price_history: std::collections::HashMap::new(), - positions: std::collections::HashMap::new(), - } - } -} - -impl Strategy for SimpleSMAStrategy { - fn on_market_data(&mut self, data: &MarketUpdate) -> Vec { - // Count calls - static mut CALL_COUNT: usize = 0; - unsafe { - CALL_COUNT += 1; - if CALL_COUNT % 100 == 1 { - eprintln!("SimpleSMAStrategy.on_market_data called {} times", CALL_COUNT); - } - } - - let mut signals = Vec::new(); - - // Check if it's bar data - if let crate::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); - - // Debug: Log first few prices - if history.len() <= 3 { - eprintln!("Price history for {}: {:?}", symbol, history); - } else if history.len() == 10 || history.len() == 15 { - eprintln!("Price history length for {}: {} bars", symbol, history.len()); - } - - // Keep only necessary history (need one extra for previous SMA calculation) - if history.len() > self.slow_period + 1 { - history.remove(0); - } - - // Need enough data - if history.len() >= self.slow_period { - // Debug when we first have enough data - if history.len() == self.slow_period { - eprintln!("Now have enough data for {}: {} bars", symbol, history.len()); - } - // Calculate SMAs - let fast_sma = history[history.len() - self.fast_period..].iter().sum::() / self.fast_period as f64; - let slow_sma = history.iter().sum::() / history.len() as f64; - - // Debug: Log SMAs periodically - if history.len() % 10 == 0 || (history.len() > self.slow_period && history.len() < self.slow_period + 5) { - eprintln!("SMAs for {}: fast={:.2}, slow={:.2}, price={:.2}, history_len={}", - symbol, fast_sma, slow_sma, price, history.len()); - - // Also log if they're close to crossing - let diff = (fast_sma - slow_sma).abs(); - let pct_diff = diff / slow_sma * 100.0; - if pct_diff < 1.0 { - eprintln!(" -> SMAs are close! Difference: {:.4} ({:.2}%)", diff, pct_diff); - } - } - - // Previous SMAs (if we have enough history) - if history.len() > self.slow_period { - // Debug: First time checking for crossovers - if history.len() == self.slow_period + 1 { - eprintln!("Starting crossover checks for {}", symbol); - } - let prev_history = &history[..history.len() - 1]; - let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..].iter().sum::() / self.fast_period as f64; - let prev_slow_sma = prev_history.iter().sum::() / prev_history.len() as f64; - - let current_position = self.positions.get(symbol).copied().unwrap_or(0.0); - - // Golden cross - buy signal - if prev_fast_sma <= prev_slow_sma && fast_sma > slow_sma && current_position <= 0.0 { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: crate::backtest::SignalType::Buy, - strength: 1.0, - quantity: Some(100.0), // Fixed quantity for testing - reason: Some("Golden cross".to_string()), - metadata: None, - }); - self.positions.insert(symbol.clone(), 1.0); - eprintln!("Generated BUY signal for {} at price {}", symbol, price); - } - - // Death cross - sell signal - else if prev_fast_sma >= prev_slow_sma && fast_sma < slow_sma && current_position >= 0.0 { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: crate::backtest::SignalType::Sell, - strength: 1.0, - quantity: Some(100.0), // Fixed quantity for testing - reason: Some("Death cross".to_string()), - metadata: None, - }); - self.positions.insert(symbol.clone(), -1.0); - eprintln!("Generated SELL signal for {} at price {}", symbol, price); - } - } - } else { - // Debug: Log when we don't have enough data - if history.len() == 1 || history.len() == 10 || history.len() == 20 { - eprintln!("Not enough data for {}: {} bars (need {})", symbol, history.len(), self.slow_period); - } - } - } - - signals - } - - fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) { - eprintln!("🔸 SMA Strategy - Fill received: {} {} @ ${:.2} - {}", quantity, symbol, price, side); - let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0); - let new_pos = if side == "buy" { current_pos + quantity } else { current_pos - quantity }; - - eprintln!(" Position change: {} -> {}", current_pos, new_pos); - - if new_pos.abs() < 0.0001 { - self.positions.remove(symbol); - eprintln!(" Position closed"); - } else { - self.positions.insert(symbol.to_string(), new_pos); - } - } - - fn get_name(&self) -> &str { - &self.name - } - - fn get_parameters(&self) -> serde_json::Value { - serde_json::json!({ - "fast_period": self.fast_period, - "slow_period": self.slow_period - }) - } -} - -// Error handling for threadsafe functions -struct ErrorStrategy; - -impl From for ErrorStrategy { - fn from(_e: napi::Error) -> Self { - ErrorStrategy - } -} - -// Helper to convert NAPI parameters to JSON -fn napi_params_to_json(obj: napi::JsObject) -> Result { - // For now, just extract the common parameters - let fast_period = obj.get_named_property::("fastPeriod").unwrap_or(5.0); - let slow_period = obj.get_named_property::("slowPeriod").unwrap_or(15.0); - - Ok(serde_json::json!({ - "fastPeriod": fast_period, - "slowPeriod": slow_period - })) -} \ No newline at end of file +use crate::backtest::{BacktestConfig, BacktestEngine as RustBacktestEngine, Signal, Strategy}; +use crate::{MarketUpdate, TradingMode}; +use chrono::{DateTime, Utc}; +use napi::bindgen_prelude::*; +use napi_derive::napi; +use parking_lot::Mutex; +use std::sync::Arc; + +#[napi] +pub struct BacktestEngine { + inner: Arc>>, +} + +#[napi] +impl BacktestEngine { + #[napi(constructor)] + pub fn new(config: napi::JsObject, env: Env) -> Result { + let config = parse_backtest_config(config)?; + + // Create mode + let mode = TradingMode::Backtest { + start_time: config.start_time, + end_time: config.end_time, + speed_multiplier: 0.0, // Max speed + }; + + // Create components + let time_provider = crate::core::create_time_provider(&mode); + let market_data_source = crate::core::create_market_data_source(&mode); + let execution_handler = crate::core::create_execution_handler(&mode); + + let engine = RustBacktestEngine::new( + config, + mode, + time_provider, + market_data_source, + execution_handler, + ); + + Ok(Self { + inner: Arc::new(Mutex::new(Some(engine))), + }) + } + + #[napi] + pub fn add_typescript_strategy( + &mut self, + _name: String, + _id: String, + _parameters: napi::JsObject, + _callback: napi::JsFunction, + ) -> Result<()> { + Err(Error::from_reason( + "TypeScript strategy callbacks are not supported by the native engine", + )) + } + + #[napi] + pub fn add_native_strategy( + &mut self, + strategy_type: String, + name: String, + id: String, + parameters: napi::JsObject, + ) -> Result<()> { + if let Some(engine) = self.inner.lock().as_mut() { + match strategy_type.as_str() { + "sma_crossover" => { + let fast_period: usize = parameters + .get_named_property::("fastPeriod") + .unwrap_or(5.0) as usize; + let slow_period: usize = parameters + .get_named_property::("slowPeriod") + .unwrap_or(15.0) as usize; + + if fast_period == 0 || fast_period >= slow_period { + return Err(Error::from_reason( + "SMA periods must satisfy 0 < fastPeriod < slowPeriod", + )); + } + engine.add_strategy(Box::new(SimpleSMAStrategy::new( + name.clone(), + id, + fast_period, + slow_period, + ))); + } + "mean_reversion" => { + let lookback_period: usize = parameters + .get_named_property::("lookbackPeriod") + .unwrap_or(20.0) as usize; + let entry_threshold: f64 = parameters + .get_named_property::("entryThreshold") + .unwrap_or(2.0); + let position_size: f64 = parameters + .get_named_property::("positionSize") + .unwrap_or(100.0); + + engine.add_strategy(Box::new( + crate::strategies::MeanReversionFixedStrategy::new( + name.clone(), + id, + lookback_period, + entry_threshold, + position_size, + ), + )); + } + "momentum" => { + let lookback_period: usize = parameters + .get_named_property::("lookbackPeriod") + .unwrap_or(14.0) as usize; + let momentum_threshold: f64 = parameters + .get_named_property::("momentumThreshold") + .unwrap_or(5.0); + let position_size: f64 = parameters + .get_named_property::("positionSize") + .unwrap_or(100.0); + + engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new( + name.clone(), + id, + lookback_period, + momentum_threshold, + position_size, + ))); + } + "pairs_trading" => { + let pair_a: String = parameters.get_named_property::("pairA")?; + let pair_b: String = parameters.get_named_property::("pairB")?; + let lookback_period: usize = parameters + .get_named_property::("lookbackPeriod") + .unwrap_or(20.0) as usize; + let entry_threshold: f64 = parameters + .get_named_property::("entryThreshold") + .unwrap_or(2.0); + let position_size: f64 = parameters + .get_named_property::("positionSize") + .unwrap_or(100.0); + + engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new( + name.clone(), + id, + pair_a, + pair_b, + lookback_period, + entry_threshold, + position_size, + ))); + } + _ => { + return Err(Error::from_reason(format!( + "Unknown strategy type: {}", + strategy_type + ))); + } + } + } + + Ok(()) + } + + #[napi] + pub fn run(&mut self) -> Result { + let mut engine = self + .inner + .lock() + .take() + .ok_or_else(|| Error::from_reason("Engine already consumed"))?; + + // Config and strategies are private, skip detailed logging + + // Run the backtest synchronously for now + let runtime = + tokio::runtime::Runtime::new().map_err(|e| Error::from_reason(e.to_string()))?; + + let result = runtime + .block_on(engine.run()) + .map_err(|e| Error::from_reason(e))?; + for (symbol, data) in &result.ohlc_data {} + + // Return result as JSON + serde_json::to_string(&result).map_err(|e| Error::from_reason(e.to_string())) + } + + #[napi] + pub fn load_market_data(&self, data: Vec) -> Result<()> { + // Convert JS objects to MarketData + let market_data: Vec = data + .into_iter() + .filter_map(|obj| parse_market_data(obj).ok()) + .collect(); + + // Load data into the historical data source + if let Some(engine) = self.inner.lock().as_ref() { + // Access the market data source through the engine + let mut data_source = engine.market_data_source.write(); + if let Some(historical_source) = data_source + .as_any_mut() + .downcast_mut::( + ) { + historical_source.load_data(market_data); + } else { + } + } else { + } + + Ok(()) + } +} + +fn parse_backtest_config(obj: napi::JsObject) -> Result { + let name: String = obj.get_named_property("name")?; + let symbols: Vec = obj.get_named_property("symbols")?; + let start_date: String = obj.get_named_property("startDate")?; + let end_date: String = obj.get_named_property("endDate")?; + let initial_capital: f64 = obj.get_named_property("initialCapital")?; + let commission: f64 = obj.get_named_property("commission")?; + let slippage: f64 = obj.get_named_property("slippage")?; + let data_frequency: String = obj.get_named_property("dataFrequency")?; + let strategy: Option = obj.get_named_property("strategy").ok(); + + Ok(BacktestConfig { + name, + strategy, + symbols, + start_time: DateTime::parse_from_rfc3339(&start_date) + .map_err(|e| Error::from_reason(e.to_string()))? + .with_timezone(&Utc), + end_time: DateTime::parse_from_rfc3339(&end_date) + .map_err(|e| Error::from_reason(e.to_string()))? + .with_timezone(&Utc), + initial_capital, + commission, + slippage, + data_frequency, + }) +} + +fn parse_market_data(obj: napi::JsObject) -> Result { + let symbol: String = obj.get_named_property("symbol")?; + let timestamp: i64 = obj.get_named_property("timestamp")?; + let data_type: String = obj.get_named_property("type")?; + + let data = if data_type == "bar" { + crate::MarketDataType::Bar(crate::Bar { + open: obj.get_named_property("open")?, + high: obj.get_named_property("high")?, + low: obj.get_named_property("low")?, + close: obj.get_named_property("close")?, + volume: obj.get_named_property("volume")?, + vwap: obj.get_named_property("vwap").ok(), + }) + } else { + return Err(Error::from_reason("Unsupported market data type")); + }; + + Ok(crate::MarketUpdate { + symbol, + timestamp: DateTime::::from_timestamp(timestamp / 1000, 0) + .ok_or_else(|| Error::from_reason("Invalid timestamp"))?, + data, + }) +} + +// Simple SMA Strategy for testing +struct SimpleSMAStrategy { + name: String, + id: String, + fast_period: usize, + slow_period: usize, + price_history: std::collections::HashMap>, + positions: std::collections::HashMap, +} + +impl SimpleSMAStrategy { + fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self { + Self { + name, + id, + fast_period, + slow_period, + price_history: std::collections::HashMap::new(), + positions: std::collections::HashMap::new(), + } + } +} + +impl Strategy for SimpleSMAStrategy { + fn on_market_data(&mut self, data: &MarketUpdate) -> Vec { + let mut signals = Vec::new(); + + // Check if it's bar data + if let crate::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 (need one extra for previous SMA calculation) + if history.len() > self.slow_period + 1 { + history.remove(0); + } + + // Need enough data + if history.len() >= self.slow_period { + // Calculate SMAs + let fast_sma = history[history.len() - self.fast_period..] + .iter() + .sum::() + / self.fast_period as f64; + let slow_sma = history[history.len() - self.slow_period..] + .iter() + .sum::() + / self.slow_period as f64; + + // Previous SMAs (if we have enough history) + if history.len() > self.slow_period { + let prev_history = &history[..history.len() - 1]; + let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..] + .iter() + .sum::() + / self.fast_period as f64; + let prev_slow_sma = + prev_history.iter().sum::() / prev_history.len() as f64; + + let current_position = self.positions.get(symbol).copied().unwrap_or(0.0); + + // Golden cross - buy signal + if prev_fast_sma <= prev_slow_sma + && fast_sma > slow_sma + && current_position <= 0.0 + { + signals.push(Signal { + symbol: symbol.clone(), + signal_type: crate::backtest::SignalType::Buy, + strength: 1.0, + quantity: Some(100.0), // Fixed quantity for testing + reason: Some("Golden cross".to_string()), + metadata: None, + }); + } + // Death cross - sell signal + else if prev_fast_sma >= prev_slow_sma + && fast_sma < slow_sma + && current_position >= 0.0 + { + signals.push(Signal { + symbol: symbol.clone(), + signal_type: crate::backtest::SignalType::Sell, + strength: 1.0, + quantity: Some(100.0), // Fixed quantity for testing + reason: Some("Death cross".to_string()), + metadata: None, + }); + } + } + } + } + + signals + } + + fn on_fill(&mut self, symbol: &str, quantity: f64, _price: f64, side: &str) { + let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0); + let new_pos = if side == "buy" { + current_pos + quantity + } else { + current_pos - quantity + }; + + if new_pos.abs() < 0.0001 { + self.positions.remove(symbol); + } else { + self.positions.insert(symbol.to_string(), new_pos); + } + } + + fn get_name(&self) -> &str { + &self.name + } + + fn get_parameters(&self) -> serde_json::Value { + serde_json::json!({ + "fast_period": self.fast_period, + "slow_period": self.slow_period + }) + } +} + +// Error handling for threadsafe functions +struct ErrorStrategy; + +impl From for ErrorStrategy { + fn from(_e: napi::Error) -> Self { + ErrorStrategy + } +} + +// Helper to convert NAPI parameters to JSON +fn napi_params_to_json(obj: napi::JsObject) -> Result { + // For now, just extract the common parameters + let fast_period = obj.get_named_property::("fastPeriod").unwrap_or(5.0); + let slow_period = obj.get_named_property::("slowPeriod").unwrap_or(15.0); + + Ok(serde_json::json!({ + "fastPeriod": fast_period, + "slowPeriod": slow_period + })) +} diff --git a/apps/stock/engine/src/indicators/macd.rs b/apps/stock/engine/src/indicators/macd.rs index 25d2e92d..c5ff1c52 100644 --- a/apps/stock/engine/src/indicators/macd.rs +++ b/apps/stock/engine/src/indicators/macd.rs @@ -1,229 +1,231 @@ -use super::{Indicator, IncrementalIndicator, IndicatorResult, IndicatorError, PriceData}; -use super::ema::EMA; - -/// Moving Average Convergence Divergence (MACD) Indicator -/// -/// MACD = Fast EMA - Slow EMA -/// Signal = EMA of MACD -/// Histogram = MACD - Signal -pub struct MACD { - fast_period: usize, - slow_period: usize, - signal_period: usize, - fast_ema: EMA, - slow_ema: EMA, - signal_ema: EMA, - macd_value: Option, -} - -impl MACD { - pub fn new(fast_period: usize, slow_period: usize, signal_period: usize) -> Result { - if fast_period == 0 || slow_period == 0 || signal_period == 0 { - return Err(IndicatorError::InvalidParameter( - "All periods must be greater than 0".to_string() - )); - } - - if fast_period >= slow_period { - return Err(IndicatorError::InvalidParameter( - "Fast period must be less than slow period".to_string() - )); - } - - Ok(Self { - fast_period, - slow_period, - signal_period, - fast_ema: EMA::new(fast_period)?, - slow_ema: EMA::new(slow_period)?, - signal_ema: EMA::new(signal_period)?, - macd_value: None, - }) - } - - /// Standard MACD with 12, 26, 9 periods - pub fn standard() -> Result { - Self::new(12, 26, 9) - } - - /// Calculate MACD for a series of values - pub fn calculate_series( - values: &[f64], - fast_period: usize, - slow_period: usize, - signal_period: usize - ) -> Result<(Vec, Vec, Vec), IndicatorError> { - if fast_period >= slow_period { - return Err(IndicatorError::InvalidParameter( - "Fast period must be less than slow period".to_string() - )); - } - - if values.len() < slow_period { - return Err(IndicatorError::InsufficientData { - required: slow_period, - actual: values.len(), - }); - } - - // Calculate EMAs - let fast_ema = EMA::calculate_series(values, fast_period)?; - let slow_ema = EMA::calculate_series(values, slow_period)?; - - // Calculate MACD line - let mut macd_line = Vec::with_capacity(slow_ema.len()); - for i in 0..slow_ema.len() { - // Align indices - slow EMA starts later - let fast_idx = i + (slow_period - fast_period); - macd_line.push(fast_ema[fast_idx] - slow_ema[i]); - } - - // Calculate signal line (EMA of MACD) - let signal_line = if macd_line.len() >= signal_period { - EMA::calculate_series(&macd_line, signal_period)? - } else { - vec![] - }; - - // Calculate histogram - let mut histogram = Vec::with_capacity(signal_line.len()); - for i in 0..signal_line.len() { - // Align indices - let macd_idx = i + (macd_line.len() - signal_line.len()); - histogram.push(macd_line[macd_idx] - signal_line[i]); - } - - Ok((macd_line, signal_line, histogram)) - } -} - -impl Indicator for MACD { - fn calculate(&mut self, data: &PriceData) -> Result { - let values = &data.close; - - let (macd, signal, histogram) = Self::calculate_series( - values, - self.fast_period, - self.slow_period, - self.signal_period - )?; - - Ok(IndicatorResult::MACD { - macd, - signal, - histogram, - }) - } - - fn reset(&mut self) { - self.fast_ema.reset(); - self.slow_ema.reset(); - self.signal_ema.reset(); - self.macd_value = None; - } - - fn is_ready(&self) -> bool { - self.fast_ema.is_ready() && self.slow_ema.is_ready() && self.signal_ema.is_ready() - } -} - -impl IncrementalIndicator for MACD { - fn update(&mut self, value: f64) -> Result, IndicatorError> { - // Update both EMAs - let fast_result = self.fast_ema.update(value)?; - let slow_result = self.slow_ema.update(value)?; - - // Calculate MACD if both EMAs are ready - if let (Some(fast), Some(slow)) = (fast_result, slow_result) { - let macd = fast - slow; - self.macd_value = Some(macd); - - // Update signal line - if let Some(signal) = self.signal_ema.update(macd)? { - // Return histogram value - Ok(Some(macd - signal)) - } else { - Ok(None) - } - } else { - Ok(None) - } - } - - fn current(&self) -> Option { - // Return current histogram value - if let (Some(fast), Some(slow), Some(signal)) = ( - self.fast_ema.current(), - self.slow_ema.current(), - self.signal_ema.current() - ) { - let macd = fast - slow; - Some(macd - signal) - } else { - None - } - } -} - -/// Structure to hold all MACD values for incremental updates -pub struct MACDValues { - pub macd: f64, - pub signal: f64, - pub histogram: f64, -} - -impl MACD { - /// Get all current MACD values - pub fn current_values(&self) -> Option { - if let (Some(fast), Some(slow), Some(signal)) = ( - self.fast_ema.current(), - self.slow_ema.current(), - self.signal_ema.current() - ) { - let macd = fast - slow; - Some(MACDValues { - macd, - signal, - histogram: macd - signal, - }) - } else { - None - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_macd_calculation() { - let values = vec![ - 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, - 14.0, 14.5, 15.0, 14.5, 14.0, 13.5, 13.0, 12.5, - 12.0, 11.5, 11.0, 10.5, 10.0, 10.5, 11.0, 11.5, - 12.0, 12.5, 13.0, 13.5, 14.0, 14.5 - ]; - - let (macd, signal, histogram) = MACD::calculate_series(&values, 12, 26, 9).unwrap(); - - // Should have values after slow period - assert!(!macd.is_empty()); - assert!(!signal.is_empty()); - assert!(!histogram.is_empty()); - - // Histogram should equal MACD - Signal - for i in 0..histogram.len() { - let expected = macd[macd.len() - histogram.len() + i] - signal[i]; - assert!((histogram[i] - expected).abs() < 1e-10); - } - } - - #[test] - fn test_standard_macd() { - let macd = MACD::standard().unwrap(); - assert_eq!(macd.fast_period, 12); - assert_eq!(macd.slow_period, 26); - assert_eq!(macd.signal_period, 9); - } -} \ No newline at end of file +use super::ema::EMA; +use super::{IncrementalIndicator, Indicator, IndicatorError, IndicatorResult, PriceData}; + +/// Moving Average Convergence Divergence (MACD) Indicator +/// +/// MACD = Fast EMA - Slow EMA +/// Signal = EMA of MACD +/// Histogram = MACD - Signal +pub struct MACD { + fast_period: usize, + slow_period: usize, + signal_period: usize, + fast_ema: EMA, + slow_ema: EMA, + signal_ema: EMA, + macd_value: Option, +} + +impl MACD { + pub fn new( + fast_period: usize, + slow_period: usize, + signal_period: usize, + ) -> Result { + if fast_period == 0 || slow_period == 0 || signal_period == 0 { + return Err(IndicatorError::InvalidParameter( + "All periods must be greater than 0".to_string(), + )); + } + + if fast_period >= slow_period { + return Err(IndicatorError::InvalidParameter( + "Fast period must be less than slow period".to_string(), + )); + } + + Ok(Self { + fast_period, + slow_period, + signal_period, + fast_ema: EMA::new(fast_period)?, + slow_ema: EMA::new(slow_period)?, + signal_ema: EMA::new(signal_period)?, + macd_value: None, + }) + } + + /// Standard MACD with 12, 26, 9 periods + pub fn standard() -> Result { + Self::new(12, 26, 9) + } + + /// Calculate MACD for a series of values + pub fn calculate_series( + values: &[f64], + fast_period: usize, + slow_period: usize, + signal_period: usize, + ) -> Result<(Vec, Vec, Vec), IndicatorError> { + if fast_period >= slow_period { + return Err(IndicatorError::InvalidParameter( + "Fast period must be less than slow period".to_string(), + )); + } + + if values.len() < slow_period { + return Err(IndicatorError::InsufficientData { + required: slow_period, + actual: values.len(), + }); + } + + // Calculate EMAs + let fast_ema = EMA::calculate_series(values, fast_period)?; + let slow_ema = EMA::calculate_series(values, slow_period)?; + + // Calculate MACD line + let mut macd_line = Vec::with_capacity(slow_ema.len()); + for i in 0..slow_ema.len() { + // Both EMA series are aligned to the complete input series. + macd_line.push(fast_ema[i] - slow_ema[i]); + } + + // Calculate signal line (EMA of MACD) + let signal_line = if macd_line.len() >= signal_period { + EMA::calculate_series(&macd_line, signal_period)? + } else { + vec![] + }; + + // Calculate histogram + let mut histogram = Vec::with_capacity(signal_line.len()); + for i in 0..signal_line.len() { + // Align indices + let macd_idx = i + (macd_line.len() - signal_line.len()); + histogram.push(macd_line[macd_idx] - signal_line[i]); + } + + Ok((macd_line, signal_line, histogram)) + } +} + +impl Indicator for MACD { + fn calculate(&mut self, data: &PriceData) -> Result { + let values = &data.close; + + let (macd, signal, histogram) = Self::calculate_series( + values, + self.fast_period, + self.slow_period, + self.signal_period, + )?; + + Ok(IndicatorResult::MACD { + macd, + signal, + histogram, + }) + } + + fn reset(&mut self) { + self.fast_ema.reset(); + self.slow_ema.reset(); + self.signal_ema.reset(); + self.macd_value = None; + } + + fn is_ready(&self) -> bool { + self.fast_ema.is_ready() && self.slow_ema.is_ready() && self.signal_ema.is_ready() + } +} + +impl IncrementalIndicator for MACD { + fn update(&mut self, value: f64) -> Result, IndicatorError> { + // Update both EMAs + let fast_result = self.fast_ema.update(value)?; + let slow_result = self.slow_ema.update(value)?; + + // Calculate MACD if both EMAs are ready + if let (Some(fast), Some(slow)) = (fast_result, slow_result) { + let macd = fast - slow; + self.macd_value = Some(macd); + + // Update signal line + if let Some(signal) = self.signal_ema.update(macd)? { + // Return histogram value + Ok(Some(macd - signal)) + } else { + Ok(None) + } + } else { + Ok(None) + } + } + + fn current(&self) -> Option { + // Return current histogram value + if let (Some(fast), Some(slow), Some(signal)) = ( + self.fast_ema.current(), + self.slow_ema.current(), + self.signal_ema.current(), + ) { + let macd = fast - slow; + Some(macd - signal) + } else { + None + } + } +} + +/// Structure to hold all MACD values for incremental updates +pub struct MACDValues { + pub macd: f64, + pub signal: f64, + pub histogram: f64, +} + +impl MACD { + /// Get all current MACD values + pub fn current_values(&self) -> Option { + if let (Some(fast), Some(slow), Some(signal)) = ( + self.fast_ema.current(), + self.slow_ema.current(), + self.signal_ema.current(), + ) { + let macd = fast - slow; + Some(MACDValues { + macd, + signal, + histogram: macd - signal, + }) + } else { + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_macd_calculation() { + let values = vec![ + 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 14.5, 14.0, 13.5, + 13.0, 12.5, 12.0, 11.5, 11.0, 10.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, + 14.0, 14.5, + ]; + + let (macd, signal, histogram) = MACD::calculate_series(&values, 12, 26, 9).unwrap(); + + // Should have values after slow period + assert!(!macd.is_empty()); + assert!(!signal.is_empty()); + assert!(!histogram.is_empty()); + + // Histogram should equal MACD - Signal + for i in 0..histogram.len() { + let expected = macd[macd.len() - histogram.len() + i] - signal[i]; + assert!((histogram[i] - expected).abs() < 1e-10); + } + } + + #[test] + fn test_standard_macd() { + let macd = MACD::standard().unwrap(); + assert_eq!(macd.fast_period, 12); + assert_eq!(macd.slow_period, 26); + assert_eq!(macd.signal_period, 9); + } +} diff --git a/apps/stock/orchestrator/examples/advanced-risk-management.ts b/apps/stock/orchestrator/examples/advanced-risk-management.ts index 0f7d8c8e..7ddb7eca 100644 --- a/apps/stock/orchestrator/examples/advanced-risk-management.ts +++ b/apps/stock/orchestrator/examples/advanced-risk-management.ts @@ -1,272 +1,278 @@ -/** - * 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.90, 150.10, 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(); -} \ No newline at end of file +/** + * 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/debug-position-tracking.ts b/apps/stock/orchestrator/examples/debug-position-tracking.ts index c6c83a4f..60b7fd47 100644 --- a/apps/stock/orchestrator/examples/debug-position-tracking.ts +++ b/apps/stock/orchestrator/examples/debug-position-tracking.ts @@ -1,113 +1,93 @@ -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'; - -async function debugPositionTracking() { - // Create service container with detailed logging - const container: IServiceContainer = { - logger: { - info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args), - error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), - warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args), - debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args), - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - // Set services in container - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // 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'], - 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: any) => { - console.log('\n📊 STRATEGY ORDER EVENT:', orderEvent); - }); - - // Configure backtest - const config = { - mode: 'backtest' as const, - name: 'Position Tracking Debug', - strategy: 'sma-crossover', - symbols: ['AAPL'], - 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); \ No newline at end of file +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'], + 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'], + 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 index 3bc3b856..1cda8312 100644 --- a/apps/stock/orchestrator/examples/debug-rust-short-trades.ts +++ b/apps/stock/orchestrator/examples/debug-rust-short-trades.ts @@ -1,129 +1,130 @@ -import { TradingEngine } from '@stock-bot/engine'; - -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: any, 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: any, 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); \ No newline at end of file +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 new file mode 100644 index 00000000..4fcbc916 --- /dev/null +++ b/apps/stock/orchestrator/examples/example-runtime.ts @@ -0,0 +1,33 @@ +import { ServiceContainerBuilder } from '@stock-bot/di'; +import { defined } from '@stock-bot/invariants'; +import { registerOrchestratorServices } from '../src/container'; +import type { OrchestratorServices } from '../src/types'; + +/** Offline examples explicitly opt into seeded synthetic data. No provider credentials are used. */ +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(); + await registerOrchestratorServices(di, { + initializeMode: false, + allowSyntheticData: true, + syntheticSeed: 42, + }); + const container = di.resolve('serviceContainer') as OrchestratorServices; + return { + container, + storageService: defined(container.custom?.StorageService), + marketDataService: defined(container.custom?.MarketDataService), + executionService: defined(container.custom?.ExecutionService), + modeManager: defined(container.custom?.ModeManager), + strategyManager: defined(container.custom?.StrategyManager), + }; +} diff --git a/apps/stock/orchestrator/examples/force-both-trade-types.ts b/apps/stock/orchestrator/examples/force-both-trade-types.ts index 5f48b0a5..9dfe7bf9 100644 --- a/apps/stock/orchestrator/examples/force-both-trade-types.ts +++ b/apps/stock/orchestrator/examples/force-both-trade-types.ts @@ -1,161 +1,138 @@ -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'; - -// 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: IServiceContainer = { - logger: { - info: (msg: string, ...args: any[]) => { - if (msg.includes('cross detected') || msg.includes('Generated') || msg.includes('Position update')) { - console.log('[INFO]', msg, ...args); - } - }, - error: console.error, - warn: () => {}, - debug: () => {}, - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // 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'], - 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'], - 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); \ No newline at end of file +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'], + 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'], + 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 index f8a50559..908da238 100644 --- a/apps/stock/orchestrator/examples/indicator-usage.ts +++ b/apps/stock/orchestrator/examples/indicator-usage.ts @@ -1,217 +1,238 @@ -/** - * 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: [], high: [], low: [], volume: [] } as any; - 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 - TechnicalAnalysis.latest(bb.lower)!) / - (TechnicalAnalysis.latest(bb.upper)! - 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: [], high: [], low: [], volume: [] } as any; - 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(); -} \ No newline at end of file +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/show-order-flow.ts b/apps/stock/orchestrator/examples/show-order-flow.ts index c45300d5..42148535 100644 --- a/apps/stock/orchestrator/examples/show-order-flow.ts +++ b/apps/stock/orchestrator/examples/show-order-flow.ts @@ -1,99 +1,75 @@ -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'; - -async function showOrderFlow() { - // Create service container - const container: IServiceContainer = { - logger: { - info: (msg: string, ...args: any[]) => { - // Only log order-related messages - if (msg.includes('order') || msg.includes('Order') || msg.includes('Filling') || msg.includes('cross detected')) { - console.log('[INFO]', msg, ...args); - } - }, - error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), - warn: (msg: string, ...args: any[]) => {}, - debug: (msg: string, ...args: any[]) => {}, - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - // Set services in container - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // 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'], - 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'], - 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); \ No newline at end of file +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'], + 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'], + 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 index 016ad635..038ccca1 100644 --- a/apps/stock/orchestrator/examples/simple-backtest-test.ts +++ b/apps/stock/orchestrator/examples/simple-backtest-test.ts @@ -1,115 +1,92 @@ -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 runSimpleBacktest() { - // Create service container - const container: IServiceContainer = { - logger: { - info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args), - error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), - warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args), - debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args), - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - // Set services in container - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // 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'], - 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'], // 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); \ No newline at end of file +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'], + 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'], // 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/sophisticated-backtest.ts b/apps/stock/orchestrator/examples/sophisticated-backtest.ts index 87e61b16..dba48750 100644 --- a/apps/stock/orchestrator/examples/sophisticated-backtest.ts +++ b/apps/stock/orchestrator/examples/sophisticated-backtest.ts @@ -1,286 +1,299 @@ -#!/usr/bin/env bun - -/** - * Example of running a sophisticated backtest with all advanced features - */ - -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { StrategyManager } from '../src/strategies/StrategyManager'; -import { StorageService } from '../src/services/StorageService'; -import { AnalyticsService } from '../src/services/AnalyticsService'; -import { MeanReversionStrategy } from '../src/strategies/examples/MeanReversionStrategy'; -import { MLEnhancedStrategy } from '../src/strategies/examples/MLEnhancedStrategy'; -import { logger } from '@stock-bot/logger'; - -async function runSophisticatedBacktest() { - // Initialize services - const storageService = new StorageService(); - await storageService.initialize({ mode: 'backtest' }); - - const analyticsService = new AnalyticsService({ - analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003' - }); - - const strategyManager = new StrategyManager(); - - // Create backtest engine - const backtestEngine = new BacktestEngine(storageService, strategyManager); - - // Configure backtest with advanced options - const config = { - mode: 'backtest' as const, - startDate: '2023-01-01T00:00:00Z', - endDate: '2023-12-31T23:59:59Z', - symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'], - initialCapital: 1_000_000, - dataFrequency: '5m' as const, // 5-minute bars for detailed analysis - - // Advanced fill model configuration - fillModel: { - slippage: 'realistic' as const, - marketImpact: true, - partialFills: true, - // Use sophisticated market impact models - impactModel: 'AlmgrenChriss', - // Model hidden liquidity and dark pools - includeHiddenLiquidity: true, - darkPoolParticipation: 0.2, // 20% of volume in dark pools - // Realistic latency simulation - latencyMs: { - mean: 1, - std: 0.5, - tail: 10 // Occasional high latency - } - }, - - // Risk limits - riskLimits: { - maxPositionSize: 100_000, - maxDailyLoss: 50_000, - maxDrawdown: 0.20, // 20% max drawdown - maxLeverage: 2.0, - maxConcentration: 0.30 // Max 30% in single position - }, - - // Transaction costs - costs: { - commission: 0.0005, // 5 bps - borrowRate: 0.03, // 3% annual for shorts - slippageModel: 'volumeDependent' - }, - - // Strategies to test - strategies: [ - { - id: 'mean_reversion_1', - name: 'Mean Reversion Strategy', - type: 'MeanReversion', - enabled: true, - allocation: 0.5, - symbols: ['AAPL', 'GOOGL', 'MSFT'], - parameters: { - lookback: 20, - entryZScore: 2.0, - exitZScore: 0.5, - minVolume: 1_000_000, - stopLoss: 0.05 // 5% stop loss - } - }, - { - id: 'ml_enhanced_1', - name: 'ML Enhanced Strategy', - type: 'MLEnhanced', - enabled: true, - allocation: 0.5, - symbols: ['AMZN', 'TSLA'], - parameters: { - modelPath: './models/ml_strategy_v1', - updateFrequency: 1440, // Daily retraining - minConfidence: 0.6 - } - } - ] - }; - - logger.info('Starting sophisticated backtest...'); - - try { - // Run the backtest - const result = await backtestEngine.runBacktest(config); - - logger.info('Backtest completed successfully'); - logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`); - logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`); - logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`); - - // Run statistical validation - logger.info('Running statistical validation...'); - const validationResult = await analyticsService.validateBacktest({ - backtestId: result.id, - returns: result.dailyReturns, - trades: result.trades, - parameters: extractParameters(config.strategies) - }); - - if (validationResult.is_overfit) { - logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!'); - logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`); - logger.warn('Recommendations:'); - validationResult.recommendations.forEach(rec => { - logger.warn(` - ${rec}`); - }); - } else { - logger.info('✅ Backtest passed statistical validation'); - logger.info(`PSR: ${validationResult.psr.toFixed(3)}`); - logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`); - } - - // Generate comprehensive report - logger.info('Generating performance report...'); - const report = await backtestEngine.exportResults('html'); - - // Save report - const fs = require('fs'); - const reportPath = `./reports/backtest_${result.id}.html`; - fs.writeFileSync(reportPath, report); - logger.info(`Report saved to: ${reportPath}`); - - // Advanced analytics - logger.info('Running advanced analytics...'); - - // Factor attribution - const factorAnalysis = await analyticsService.analyzeFactors({ - returns: result.dailyReturns, - positions: result.finalPositions, - marketReturns: await getMarketReturns(config.startDate, config.endDate) - }); - - logger.info('Factor Attribution:'); - logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`); - logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`); - logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`); - - // Transaction cost analysis - const tcaReport = await analyticsService.analyzeTCA({ - trades: result.trades, - orders: result.orders - }); - - logger.info('Transaction Cost Analysis:'); - logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`); - logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`); - logger.info(` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps`); - - // Performance by time period - const periodAnalysis = analyzeByPeriod(result); - logger.info('Performance by Period:'); - Object.entries(periodAnalysis).forEach(([period, metrics]) => { - logger.info(` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})`); - }); - - // Strategy correlation analysis - if (config.strategies.length > 1) { - const correlations = await calculateStrategyCorrelations(result); - logger.info('Strategy Correlations:'); - correlations.forEach(({ pair, correlation }) => { - logger.info(` ${pair}: ${correlation.toFixed(3)}`); - }); - } - - // Monte Carlo simulation - logger.info('Running Monte Carlo simulation...'); - const monteCarloResults = await runMonteCarloSimulation(result, 1000); - logger.info(`Monte Carlo 95% VaR: ${monteCarloResults.var95.toFixed(2)}%`); - logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`); - - // Walk-forward analysis suggestion - if (result.performance.totalTrades > 100) { - logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation'); - logger.info('Example: bun run examples/walk-forward-analysis.ts'); - } - - } catch (error) { - logger.error('Backtest failed:', error); - } finally { - await storageService.shutdown(); - } -} - -// Helper functions - -function extractParameters(strategies: any[]): Record { - const params: Record = {}; - strategies.forEach(strategy => { - Object.entries(strategy.parameters).forEach(([key, value]) => { - params[`${strategy.id}_${key}`] = value; - }); - }); - return params; -} - -async function getMarketReturns(startDate: string, endDate: string): Promise { - // In real implementation, would fetch SPY or market index returns - // For demo, return synthetic market returns - const days = Math.floor((new Date(endDate).getTime() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24)); - return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02); -} - -function analyzeByPeriod(result: any): Record { - const periods = { - 'Q1': { start: 0, end: 63 }, - 'Q2': { start: 63, end: 126 }, - 'Q3': { start: 126, end: 189 }, - 'Q4': { start: 189, end: 252 } - }; - - const analysis: Record = {}; - - Object.entries(periods).forEach(([name, { start, end }]) => { - const periodReturns = result.dailyReturns.slice(start, end); - if (periodReturns.length > 0) { - const avgReturn = periodReturns.reduce((a, b) => a + b, 0) / periodReturns.length; - const std = Math.sqrt(periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length); - - analysis[name] = { - return: avgReturn * periodReturns.length * 100, - sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0 - }; - } - }); - - return analysis; -} - -async function calculateStrategyCorrelations(result: any): Promise> { - // In real implementation, would calculate actual strategy return correlations - // For demo, return sample correlations - return [ - { pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 } - ]; -} - -async function runMonteCarloSimulation(result: any, numSims: number): Promise<{ var95: number; cvar95: number }> { - const returns = result.dailyReturns; - const simulatedReturns: number[] = []; - - for (let i = 0; i < numSims; i++) { - // Bootstrap resample returns - let cumReturn = 0; - for (let j = 0; j < returns.length; j++) { - const randomIndex = Math.floor(Math.random() * returns.length); - cumReturn += returns[randomIndex]; - } - simulatedReturns.push(cumReturn * 100); - } - - // Calculate VaR and CVaR - simulatedReturns.sort((a, b) => a - b); - const index95 = Math.floor(numSims * 0.05); - const var95 = Math.abs(simulatedReturns[index95]); - const cvar95 = Math.abs(simulatedReturns.slice(0, index95).reduce((a, b) => a + b, 0) / index95); - - return { var95, cvar95 }; -} - -// Run the backtest -runSophisticatedBacktest().catch(console.error); \ No newline at end of file +#!/usr/bin/env bun + +/** + * Example of running a sophisticated backtest with all advanced features + */ +import { BacktestEngine } from '../src/backtest/BacktestEngine'; +import { AnalyticsService } from '../src/services/AnalyticsService'; +import { StorageService } from '../src/services/StorageService'; +import { StrategyManager } from '../src/strategies/StrategyManager'; +import '../src/strategies/examples/MeanReversionStrategy'; +import '../src/strategies/examples/MLEnhancedStrategy'; +import { logger } from '@stock-bot/logger'; + +async function runSophisticatedBacktest() { + // Initialize services + const storageService = new StorageService(); + await storageService.initialize({ mode: 'backtest' }); + + const analyticsService = new AnalyticsService({ + analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003', + }); + + const strategyManager = new StrategyManager(); + + // Create backtest engine + const backtestEngine = new BacktestEngine(storageService, strategyManager); + + // Configure backtest with advanced options + const config = { + mode: 'backtest' as const, + startDate: '2023-01-01T00:00:00Z', + endDate: '2023-12-31T23:59:59Z', + symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'], + initialCapital: 1_000_000, + dataFrequency: '5m' as const, // 5-minute bars for detailed analysis + + // Advanced fill model configuration + fillModel: { + slippage: 'realistic' as const, + marketImpact: true, + partialFills: true, + // Use sophisticated market impact models + impactModel: 'AlmgrenChriss', + // Model hidden liquidity and dark pools + includeHiddenLiquidity: true, + darkPoolParticipation: 0.2, // 20% of volume in dark pools + // Realistic latency simulation + latencyMs: { + mean: 1, + std: 0.5, + tail: 10, // Occasional high latency + }, + }, + + // Risk limits + riskLimits: { + maxPositionSize: 100_000, + maxDailyLoss: 50_000, + maxDrawdown: 0.2, // 20% max drawdown + maxLeverage: 2.0, + maxConcentration: 0.3, // Max 30% in single position + }, + + // Transaction costs + costs: { + commission: 0.0005, // 5 bps + borrowRate: 0.03, // 3% annual for shorts + slippageModel: 'volumeDependent', + }, + + // Strategies to test + strategies: [ + { + id: 'mean_reversion_1', + name: 'Mean Reversion Strategy', + type: 'MeanReversion', + enabled: true, + allocation: 0.5, + symbols: ['AAPL', 'GOOGL', 'MSFT'], + parameters: { + lookback: 20, + entryZScore: 2.0, + exitZScore: 0.5, + minVolume: 1_000_000, + stopLoss: 0.05, // 5% stop loss + }, + }, + { + id: 'ml_enhanced_1', + name: 'ML Enhanced Strategy', + type: 'MLEnhanced', + enabled: true, + allocation: 0.5, + symbols: ['AMZN', 'TSLA'], + parameters: { + modelPath: './models/ml_strategy_v1', + updateFrequency: 1440, // Daily retraining + minConfidence: 0.6, + }, + }, + ], + }; + + logger.info('Starting sophisticated backtest...'); + + try { + // Run the backtest + const result = await backtestEngine.runBacktest(config); + + logger.info('Backtest completed successfully'); + logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`); + logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`); + logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`); + + // Run statistical validation + logger.info('Running statistical validation...'); + const validationResult = await analyticsService.validateBacktest({ + backtestId: result.id, + returns: result.dailyReturns, + trades: result.trades, + parameters: extractParameters(config.strategies), + }); + + if (validationResult.is_overfit) { + logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!'); + logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`); + logger.warn('Recommendations:'); + validationResult.recommendations.forEach(rec => { + logger.warn(` - ${rec}`); + }); + } else { + logger.info('✅ Backtest passed statistical validation'); + logger.info(`PSR: ${validationResult.psr.toFixed(3)}`); + logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`); + } + + // Generate comprehensive report + logger.info('Generating performance report...'); + const report = await backtestEngine.exportResults('html'); + + // Save report + const fs = require('fs'); + const reportPath = `./reports/backtest_${result.id}.html`; + fs.writeFileSync(reportPath, report); + logger.info(`Report saved to: ${reportPath}`); + + // Advanced analytics + logger.info('Running advanced analytics...'); + + // Factor attribution + const factorAnalysis = await analyticsService.analyzeFactors({ + returns: result.dailyReturns, + positions: result.finalPositions, + marketReturns: await getMarketReturns(config.startDate, config.endDate), + }); + + logger.info('Factor Attribution:'); + logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`); + logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`); + logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`); + + // Transaction cost analysis + const tcaReport = await analyticsService.analyzeTCA({ + trades: result.trades, + orders: result.orders, + }); + + logger.info('Transaction Cost Analysis:'); + logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`); + logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`); + logger.info( + ` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps` + ); + + // Performance by time period + const periodAnalysis = analyzeByPeriod(result); + logger.info('Performance by Period:'); + Object.entries(periodAnalysis).forEach(([period, metrics]) => { + logger.info( + ` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})` + ); + }); + + // Strategy correlation analysis + if (config.strategies.length > 1) { + const correlations = await calculateStrategyCorrelations(result); + logger.info('Strategy Correlations:'); + correlations.forEach(({ pair, correlation }) => { + logger.info(` ${pair}: ${correlation.toFixed(3)}`); + }); + } + + // Monte Carlo simulation + logger.info('Running Monte Carlo simulation...'); + const monteCarloResults = await runMonteCarloSimulation(result, 1000); + logger.info(`Monte Carlo 95% VaR: ${monteCarloResults.var95.toFixed(2)}%`); + logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`); + + // Walk-forward analysis suggestion + if (result.performance.totalTrades > 100) { + logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation'); + logger.info('Example: bun run examples/walk-forward-analysis.ts'); + } + } catch (error) { + logger.error('Backtest failed:', error); + } finally { + await storageService.shutdown(); + } +} + +// Helper functions + +function extractParameters( + strategies: { id: string; parameters: Record }[] +): Record { + const params: Record = {}; + strategies.forEach(strategy => { + Object.entries(strategy.parameters).forEach(([key, value]) => { + params[`${strategy.id}_${key}`] = value; + }); + }); + return params; +} + +async function getMarketReturns(startDate: string, endDate: string): Promise { + // In real implementation, would fetch SPY or market index returns + // For demo, return synthetic market returns + const days = Math.floor( + (new Date(endDate).getTime() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24) + ); + return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02); +} + +function analyzeByPeriod(result: { + dailyReturns: number[]; +}): Record { + const periods = { + Q1: { start: 0, end: 63 }, + Q2: { start: 63, end: 126 }, + Q3: { start: 126, end: 189 }, + Q4: { start: 189, end: 252 }, + }; + + const analysis: Record = {}; + + Object.entries(periods).forEach(([name, { start, end }]) => { + const periodReturns = result.dailyReturns.slice(start, end); + if (periodReturns.length > 0) { + const avgReturn = periodReturns.reduce((a, b) => a + b, 0) / periodReturns.length; + const std = Math.sqrt( + periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length + ); + + analysis[name] = { + return: avgReturn * periodReturns.length * 100, + sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0, + }; + } + }); + + return analysis; +} + +async function calculateStrategyCorrelations(_result: { + dailyReturns: number[]; +}): Promise> { + // In real implementation, would calculate actual strategy return correlations + // For demo, return sample correlations + return [{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }]; +} + +async function runMonteCarloSimulation( + result: { dailyReturns: number[] }, + numSims: number +): Promise<{ var95: number; cvar95: number }> { + const returns = result.dailyReturns; + const simulatedReturns: number[] = []; + + for (let i = 0; i < numSims; i++) { + // Bootstrap resample returns + let cumReturn = 0; + for (let j = 0; j < returns.length; j++) { + const randomIndex = Math.floor(Math.random() * returns.length); + cumReturn += returns[randomIndex]; + } + simulatedReturns.push(cumReturn * 100); + } + + // Calculate VaR and CVaR + simulatedReturns.sort((a, b) => a - b); + const index95 = Math.floor(numSims * 0.05); + const var95 = Math.abs(simulatedReturns[index95]); + const cvar95 = Math.abs(simulatedReturns.slice(0, index95).reduce((a, b) => a + b, 0) / index95); + + return { var95, cvar95 }; +} + +// Run the backtest +runSophisticatedBacktest().catch(console.error); diff --git a/apps/stock/orchestrator/examples/test-short-trades.ts b/apps/stock/orchestrator/examples/test-short-trades.ts index ce1f945f..d2c213d6 100644 --- a/apps/stock/orchestrator/examples/test-short-trades.ts +++ b/apps/stock/orchestrator/examples/test-short-trades.ts @@ -1,103 +1,84 @@ -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'; - -async function testShortTrades() { - // Create service container - const container: IServiceContainer = { - logger: { - info: () => {}, - error: console.error, - warn: () => {}, - debug: () => {}, - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL'], - 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'], - 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); \ No newline at end of file +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'], + 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'], + 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 index 68cd5be7..893ddc7e 100644 --- a/apps/stock/orchestrator/examples/trace-short-positions.ts +++ b/apps/stock/orchestrator/examples/trace-short-positions.ts @@ -1,188 +1,139 @@ -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'; - -async function traceShortPositions() { - let orderCount = 0; - let fillCount = 0; - const orderTracker: any[] = []; - const fillTracker: any[] = []; - - // Create service container with detailed logging - const container: IServiceContainer = { - logger: { - info: (msg: string, ...args: any[]) => { - // Log all order and fill events - if (msg.includes('order') || msg.includes('Order') || - msg.includes('fill') || msg.includes('Fill') || - msg.includes('position') || msg.includes('Position')) { - console.log('[INFO]', msg, ...args); - } - - // Track order submissions - if (msg.includes('Submitting order')) { - orderCount++; - const orderData = args[0]; - orderTracker.push({ - count: orderCount, - symbol: orderData.symbol, - side: orderData.side, - quantity: orderData.quantity, - type: orderData.type - }); - console.log(`\n🔵 ORDER #${orderCount}:`, orderData.side.toUpperCase(), orderData.symbol); - } - - // Track fills - if (msg.includes('Order filled')) { - fillCount++; - const fillData = args[0]; - fillTracker.push({ - count: fillCount, - orderId: fillData.orderId, - symbol: fillData.symbol, - side: fillData.side, - price: fillData.price, - quantity: fillData.quantity - }); - console.log(`\n🟢 FILL #${fillCount}:`, fillData.side.toUpperCase(), fillData.symbol, '@', fillData.price); - } - }, - error: console.error, - warn: () => {}, - debug: () => {}, - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // Listen to strategy events - strategyManager.on('signal', (signal: any) => { - 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'], - 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'], - 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); \ No newline at end of file +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'], + 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'], + 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 index d4ae8c48..0fbf0ce5 100644 --- a/apps/stock/orchestrator/examples/verify-both-trade-types.ts +++ b/apps/stock/orchestrator/examples/verify-both-trade-types.ts @@ -1,133 +1,115 @@ -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'; - -async function verifyBothTradeTypes() { - // Create service container - const container: IServiceContainer = { - logger: { - info: console.log, - error: console.error, - warn: console.warn, - debug: console.log, - } as any, - custom: {} - }; - - // Initialize services - const storageService = new StorageService(); - const marketDataService = new MarketDataService(container); - const executionService = new ExecutionService(container); - const modeManager = new ModeManager(container, marketDataService, executionService, storageService); - const strategyManager = new StrategyManager(container); - - container.custom = { - MarketDataService: marketDataService, - ExecutionService: executionService, - ModeManager: modeManager, - StorageService: storageService - }; - - // Initialize backtest mode - await modeManager.initializeMode({ - mode: 'backtest', - startDate: '2023-01-01T00:00:00Z', - endDate: '2024-01-01T00:00:00Z', - speed: 'max', - symbols: ['AAPL'], - 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'], - 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); \ No newline at end of file +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'], + 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'], + 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 c0ca19db..982910ce 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -6,7 +6,7 @@ "main": "dist/index.js", "scripts": { "dev": "bun --watch src/index.ts", - "build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node", + "build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core", "start": "bun dist/index.js", "test": "bun test", "test:indicators": "bun test tests/indicators.test.ts", @@ -31,7 +31,11 @@ "zod": "^3.22.0", "uuid": "^9.0.0", "axios": "^1.6.0", - "simple-statistics": "^7.8.3" + "simple-statistics": "^7.8.3", + "@stock-bot/services": "workspace:*", + "@stock-bot/mongodb": "workspace:*", + "@stock-bot/postgres": "workspace:*", + "@stock-bot/invariants": "workspace:*" }, "peerDependencies": { "@tensorflow/tfjs-node": "^4.0.0" @@ -43,6 +47,7 @@ }, "devDependencies": { "@types/node": "^20.0.0", - "typescript": "^5.0.0" + "typescript": "^5.0.0", + "@tensorflow/tfjs-node": "^4.0.0" } } diff --git a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts index d2456f20..cf83c418 100644 --- a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts +++ b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts @@ -1,654 +1,702 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('PerformanceAnalyzer'); -import * as stats from 'simple-statistics'; - -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; // in minutes - mae: number; // Maximum Adverse Excursion - mfe: number; // Maximum Favorable Excursion -} - -export interface PerformanceMetrics { - // Return metrics - totalReturn: number; - annualizedReturn: number; - cagr: number; // Compound Annual Growth Rate - - // Risk metrics - volatility: number; - downVolatility: number; - maxDrawdown: number; - maxDrawdownDuration: number; // days - var95: number; // Value at Risk 95% - cvar95: number; // Conditional VaR 95% - - // Risk-adjusted returns - sharpeRatio: number; - sortinoRatio: number; - calmarRatio: number; - informationRatio: number; - - // Trade statistics - totalTrades: number; - winRate: number; - avgWin: number; - avgLoss: number; - avgWinLoss: number; - profitFactor: number; - expectancy: number; - payoffRatio: number; - - // Trade analysis - avgHoldingPeriod: number; - avgTradesPerDay: number; - maxConsecutiveWins: number; - maxConsecutiveLosses: number; - largestWin: number; - largestLoss: number; - - // Statistical measures - skewness: number; - kurtosis: number; - tailRatio: number; - - // Kelly criterion - kellyFraction: number; - optimalLeverage: number; -} - -export interface DrawdownAnalysis { - maxDrawdown: number; - maxDrawdownDuration: number; - currentDrawdown: number; - drawdownPeriods: Array<{ - start: Date; - end: Date; - depth: number; - duration: number; - recovery: number; - }>; - underwaterCurve: Array<{ date: Date; drawdown: number }>; -} - -export interface FactorAttribution { - alpha: number; - beta: number; - correlation: number; - treynorRatio: number; - trackingError: number; - upCapture: number; - downCapture: number; -} - -export class PerformanceAnalyzer { - private equityCurve: Array<{ date: Date; value: number }> = []; - private trades: Trade[] = []; - private dailyReturns: number[] = []; - private benchmarkReturns?: number[]; - - constructor(private initialCapital: number = 100000) {} - - addEquityPoint(date: Date, value: number): void { - this.equityCurve.push({ date, value }); - // Don't calculate daily returns on every point - wait until analyze() is called - } - - addTrade(trade: Trade): void { - this.trades.push(trade); - } - - setBenchmark(returns: number[]): void { - this.benchmarkReturns = returns; - } - - analyze(): PerformanceMetrics { - if (this.equityCurve.length < 2) { - return this.getEmptyMetrics(); - } - - // Calculate daily returns before analysis - this.calculateDailyReturns(); - - // Calculate returns - const totalReturn = this.calculateTotalReturn(); - const annualizedReturn = this.calculateAnnualizedReturn(); - const cagr = this.calculateCAGR(); - - // Risk metrics - const volatility = this.calculateVolatility(); - const downVolatility = this.calculateDownsideVolatility(); - const drawdownAnalysis = this.analyzeDrawdowns(); - const { var95, cvar95 } = this.calculateVaR(); - - // Risk-adjusted returns - const sharpeRatio = this.calculateSharpeRatio(annualizedReturn, volatility); - const sortinoRatio = this.calculateSortinoRatio(annualizedReturn, downVolatility); - const calmarRatio = drawdownAnalysis.maxDrawdown > 0 ? annualizedReturn / (drawdownAnalysis.maxDrawdown * 100) : 0; - const informationRatio = this.calculateInformationRatio(); - - // Trade statistics - const tradeStats = this.analyzeTradeStatistics(); - - // Statistical measures - const { skewness, kurtosis } = this.calculateDistributionMetrics(); - const tailRatio = this.calculateTailRatio(); - - // Kelly criterion - const { kellyFraction, optimalLeverage } = this.calculateKellyCriterion(tradeStats); - - return { - totalReturn, - annualizedReturn, - cagr, - volatility: volatility * 100, // Convert to percentage for display - downVolatility: downVolatility * 100, // Convert to percentage for display - maxDrawdown: drawdownAnalysis.maxDrawdown, - maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration, - var95, - cvar95, - sharpeRatio, - sortinoRatio, - calmarRatio, - informationRatio, - totalTrades: tradeStats.totalTrades ?? 0, - winRate: tradeStats.winRate ?? 0, - avgWin: tradeStats.avgWin ?? 0, - avgLoss: tradeStats.avgLoss ?? 0, - avgWinLoss: tradeStats.avgWinLoss ?? 0, - profitFactor: tradeStats.profitFactor ?? 0, - expectancy: tradeStats.expectancy ?? 0, - payoffRatio: tradeStats.payoffRatio ?? 0, - avgHoldingPeriod: tradeStats.avgHoldingPeriod ?? 0, - avgTradesPerDay: tradeStats.avgTradesPerDay ?? 0, - maxConsecutiveWins: tradeStats.maxConsecutiveWins ?? 0, - maxConsecutiveLosses: tradeStats.maxConsecutiveLosses ?? 0, - largestWin: tradeStats.largestWin ?? 0, - largestLoss: tradeStats.largestLoss ?? 0, - skewness, - kurtosis, - tailRatio, - kellyFraction, - optimalLeverage - }; - } - - analyzeDrawdowns(): DrawdownAnalysis { - const drawdowns: number[] = []; - const underwaterCurve: Array<{ date: Date; drawdown: number }> = []; - - // Handle empty equity curve - if (this.equityCurve.length === 0) { - return { - maxDrawdown: 0, - maxDrawdownDuration: 0, - underwaterCurve: [], - drawdownPeriods: [], - currentDrawdown: 0 - }; - } - - let peak = this.equityCurve[0].value; - let maxDrawdown = 0; - let currentDrawdownStart: Date | null = null; - let drawdownPeriods: DrawdownAnalysis['drawdownPeriods'] = []; - - for (let i = 0; i < this.equityCurve.length; i++) { - const point = this.equityCurve[i]; - - if (point.value > peak) { - // New peak - end current drawdown if any - if (currentDrawdownStart) { - const period = { - start: currentDrawdownStart, - end: point.date, - depth: maxDrawdown, - duration: this.daysBetween(currentDrawdownStart, point.date), - recovery: i - }; - drawdownPeriods.push(period); - currentDrawdownStart = null; - } - peak = point.value; - } - - const drawdown = (point.value - peak) / peak; - drawdowns.push(drawdown); - underwaterCurve.push({ date: point.date, drawdown }); - - if (drawdown < 0 && !currentDrawdownStart) { - currentDrawdownStart = point.date; - } - - if (drawdown < maxDrawdown) { - maxDrawdown = drawdown; - } - } - - // Handle ongoing drawdown - const currentDrawdown = drawdowns[drawdowns.length - 1]; - - // Calculate max drawdown duration - const maxDrawdownDuration = Math.max( - ...drawdownPeriods.map(p => p.duration), - currentDrawdownStart ? this.daysBetween(currentDrawdownStart, new Date()) : 0 - ); - - return { - maxDrawdown: Math.abs(maxDrawdown), - maxDrawdownDuration, - currentDrawdown: Math.abs(currentDrawdown), - drawdownPeriods, - underwaterCurve - }; - } - - calculateFactorAttribution(benchmarkReturns: number[]): FactorAttribution { - if (this.dailyReturns.length !== benchmarkReturns.length) { - throw new Error('Returns and benchmark must have same length'); - } - - // Calculate beta using linear regression - const regression = stats.linearRegression( - this.dailyReturns.map((r, i) => [benchmarkReturns[i], r]) - ); - const beta = regression.m; - const alpha = regression.b * 252; // Annualized - - // Correlation - const correlation = stats.sampleCorrelation(this.dailyReturns, benchmarkReturns); - - // Treynor ratio - const excessReturn = this.calculateAnnualizedReturn() - 0.02; // Assume 2% risk-free - const treynorRatio = beta !== 0 ? excessReturn / beta : 0; - - // Tracking error - const returnDiffs = this.dailyReturns.map((r, i) => r - benchmarkReturns[i]); - const trackingError = stats.standardDeviation(returnDiffs) * Math.sqrt(252); - - // Up/down capture - const upDays = benchmarkReturns - .map((r, i) => r > 0 ? { bench: r, port: this.dailyReturns[i] } : null) - .filter(d => d !== null) as Array<{ bench: number; port: number }>; - - const downDays = benchmarkReturns - .map((r, i) => r < 0 ? { bench: r, port: this.dailyReturns[i] } : null) - .filter(d => d !== null) as Array<{ bench: number; port: number }>; - - const upCapture = upDays.length > 0 ? - stats.mean(upDays.map(d => d.port)) / stats.mean(upDays.map(d => d.bench)) : 0; - - const downCapture = downDays.length > 0 ? - stats.mean(downDays.map(d => d.port)) / stats.mean(downDays.map(d => d.bench)) : 0; - - return { - alpha, - beta, - correlation, - treynorRatio, - trackingError, - upCapture, - downCapture - }; - } - - private calculateDailyReturns(): void { - this.dailyReturns = []; - - // First, aggregate equity curve by day (taking last value of each day) - const dailyEquity = new Map(); - - for (const point of this.equityCurve) { - const dateKey = point.date.toISOString().split('T')[0]; - dailyEquity.set(dateKey, point); // This will keep the last value of each day - } - - // Convert to sorted array - const dailyPoints = Array.from(dailyEquity.values()) - .sort((a, b) => a.date.getTime() - b.date.getTime()); - - // Calculate returns from daily points - for (let i = 1; i < dailyPoints.length; i++) { - const prevValue = dailyPoints[i - 1].value; - const currValue = dailyPoints[i].value; - if (prevValue > 0) { - this.dailyReturns.push((currValue - prevValue) / prevValue); - } - } - } - - private calculateTotalReturn(): number { - const finalValue = this.equityCurve[this.equityCurve.length - 1].value; - return ((finalValue - this.initialCapital) / this.initialCapital) * 100; - } - - private calculateAnnualizedReturn(): number { - const totalReturn = this.calculateTotalReturn() / 100; - const years = this.getYears(); - return (Math.pow(1 + totalReturn, 1 / years) - 1) * 100; - } - - private calculateCAGR(): number { - const finalValue = this.equityCurve[this.equityCurve.length - 1].value; - const years = this.getYears(); - return (Math.pow(finalValue / this.initialCapital, 1 / years) - 1) * 100; - } - - private calculateVolatility(): number { - if (this.dailyReturns.length === 0) return 0; - // Return volatility as a decimal percentage (not multiplied by 100) - return stats.standardDeviation(this.dailyReturns) * Math.sqrt(252); - } - - private calculateDownsideVolatility(): number { - const negativeReturns = this.dailyReturns.filter(r => r < 0); - if (negativeReturns.length === 0) return 0; - // Return volatility as a decimal percentage (not multiplied by 100) - return stats.standardDeviation(negativeReturns) * Math.sqrt(252); - } - - private calculateVaR(): { var95: number; cvar95: number } { - if (this.dailyReturns.length === 0) return { var95: 0, cvar95: 0 }; - - const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b); - const index95 = Math.floor(sortedReturns.length * 0.05); - - // Handle edge case where we don't have enough data points - if (index95 === 0 || sortedReturns.length < 20) { - return { var95: 0, cvar95: 0 }; - } - - const var95 = Math.abs(sortedReturns[index95]) * 100; - const tailReturns = sortedReturns.slice(0, index95); - const cvar95 = tailReturns.length > 0 ? Math.abs(stats.mean(tailReturns)) * 100 : 0; - - return { var95, cvar95 }; - } - - private calculateSharpeRatio(annualReturn: number, volatility: number, riskFree: number = 2): number { - if (volatility === 0) return 0; - // Both annualReturn and volatility should be in percentage form - const volatilityPct = volatility * 100; - return (annualReturn - riskFree) / volatilityPct; - } - - private calculateSortinoRatio(annualReturn: number, downVolatility: number, riskFree: number = 2): number { - if (downVolatility === 0) return 0; - // Both annualReturn and downVolatility should be in percentage form - const downVolatilityPct = downVolatility * 100; - return (annualReturn - riskFree) / downVolatilityPct; - } - - private calculateInformationRatio(): number { - if (!this.benchmarkReturns || this.benchmarkReturns.length !== this.dailyReturns.length) { - return 0; - } - - const excessReturns = this.dailyReturns.map((r, i) => r - this.benchmarkReturns![i]); - const trackingError = stats.standardDeviation(excessReturns); - - if (trackingError === 0) return 0; - - const avgExcessReturn = stats.mean(excessReturns); - return (avgExcessReturn * 252) / (trackingError * Math.sqrt(252)); - } - - private analyzeTradeStatistics(): Partial { - if (this.trades.length === 0) { - return { - totalTrades: 0, - winRate: 0, - avgWin: 0, - avgLoss: 0, - avgWinLoss: 0, - profitFactor: 0, - expectancy: 0, - payoffRatio: 0, - avgHoldingPeriod: 0, - avgTradesPerDay: 0, - maxConsecutiveWins: 0, - maxConsecutiveLosses: 0, - largestWin: 0, - largestLoss: 0 - }; - } - - // Filter out trades with 0 or undefined P&L - const validTrades = this.trades.filter(t => t.pnl !== undefined && t.pnl !== null); - const wins = validTrades.filter(t => t.pnl > 0); - const losses = validTrades.filter(t => t.pnl < 0); - - // Log trade analysis for debugging - logger.debug(`Trade Analysis: Total=${this.trades.length}, Valid=${validTrades.length}, Wins=${wins.length}, Losses=${losses.length}`); - - const totalWins = wins.reduce((sum, t) => sum + t.pnl, 0); - const totalLosses = Math.abs(losses.reduce((sum, t) => sum + t.pnl, 0)); - - const avgWin = wins.length > 0 ? totalWins / wins.length : 0; - const avgLoss = losses.length > 0 ? totalLosses / losses.length : 0; - - const winRate = validTrades.length > 0 ? (wins.length / validTrades.length) * 100 : 0; - const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0; - const expectancy = (winRate / 100 * avgWin) - ((100 - winRate) / 100 * avgLoss); - const payoffRatio = avgLoss > 0 ? avgWin / avgLoss : 0; - - // Holding period analysis - const holdingPeriods = this.trades.map(t => t.holdingPeriod); - const avgHoldingPeriod = stats.mean(holdingPeriods); - - // Trades per day - const tradingDays = this.getTradingDays(); - const avgTradesPerDay = tradingDays > 0 ? this.trades.length / tradingDays : 0; - - // Consecutive wins/losses - const { maxConsecutiveWins, maxConsecutiveLosses } = this.calculateConsecutiveStats(); - - // Largest win/loss - const largestWin = Math.max(...this.trades.map(t => t.pnl), 0); - const largestLoss = Math.abs(Math.min(...this.trades.map(t => t.pnl), 0)); - - return { - totalTrades: this.trades.length, - winRate, - avgWin, - avgLoss, - avgWinLoss: avgWin - avgLoss, - profitFactor, - expectancy, - payoffRatio, - avgHoldingPeriod, - avgTradesPerDay, - maxConsecutiveWins, - maxConsecutiveLosses, - largestWin, - largestLoss - }; - } - - private calculateDistributionMetrics(): { skewness: number; kurtosis: number } { - if (this.dailyReturns.length < 4) { - return { skewness: 0, kurtosis: 0 }; - } - - const mean = stats.mean(this.dailyReturns); - const std = stats.standardDeviation(this.dailyReturns); - - if (std === 0) { - return { skewness: 0, kurtosis: 0 }; - } - - const n = this.dailyReturns.length; - - // Skewness - const skewSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 3), 0); - const skewness = (n / ((n - 1) * (n - 2))) * skewSum; - - // Kurtosis - const kurtSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 4), 0); - const kurtosis = (n * (n + 1) / ((n - 1) * (n - 2) * (n - 3))) * kurtSum - - (3 * (n - 1) * (n - 1)) / ((n - 2) * (n - 3)); - - return { skewness, kurtosis }; - } - - private calculateTailRatio(): number { - if (this.dailyReturns.length < 20) return 0; - - const sorted = [...this.dailyReturns].sort((a, b) => b - a); - const percentile95 = sorted[Math.floor(sorted.length * 0.05)]; - const percentile5 = sorted[Math.floor(sorted.length * 0.95)]; - - return Math.abs(percentile5) > 0 ? percentile95 / Math.abs(percentile5) : 0; - } - - private calculateKellyCriterion(tradeStats: Partial): - { kellyFraction: number; optimalLeverage: number } { - const winRate = (tradeStats.winRate || 0) / 100; - const payoffRatio = tradeStats.payoffRatio || 0; - - if (payoffRatio === 0) { - return { kellyFraction: 0, optimalLeverage: 1 }; - } - - // Kelly formula: f = p - q/b - // where p = win probability, q = loss probability, b = payoff ratio - const kellyFraction = winRate - (1 - winRate) / payoffRatio; - - // Conservative Kelly (25% of full Kelly) - const conservativeKelly = Math.max(0, Math.min(0.25, kellyFraction * 0.25)); - - // Optimal leverage based on Sharpe ratio - const sharpe = this.calculateSharpeRatio( - this.calculateAnnualizedReturn(), - this.calculateVolatility() - ); - const optimalLeverage = Math.max(1, Math.min(3, sharpe / 2)); - - return { - kellyFraction: conservativeKelly, - optimalLeverage - }; - } - - private calculateConsecutiveStats(): { maxConsecutiveWins: number; maxConsecutiveLosses: number } { - let maxWins = 0, maxLosses = 0; - let currentWins = 0, currentLosses = 0; - - for (const trade of this.trades) { - if (trade.pnl > 0) { - currentWins++; - currentLosses = 0; - maxWins = Math.max(maxWins, currentWins); - } else if (trade.pnl < 0) { - currentLosses++; - currentWins = 0; - maxLosses = Math.max(maxLosses, currentLosses); - } - } - - return { maxConsecutiveWins: maxWins, maxConsecutiveLosses: maxLosses }; - } - - private getYears(): number { - if (this.equityCurve.length < 2) return 1; - const start = this.equityCurve[0].date; - const end = this.equityCurve[this.equityCurve.length - 1].date; - return this.daysBetween(start, end) / 365; - } - - private getTradingDays(): number { - if (this.equityCurve.length < 2) return 0; - const start = this.equityCurve[0].date; - const end = this.equityCurve[this.equityCurve.length - 1].date; - return this.daysBetween(start, end) * (252 / 365); // Approximate trading days - } - - private daysBetween(start: Date, end: Date): number { - return (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24); - } - - private getEmptyMetrics(): PerformanceMetrics { - return { - totalReturn: 0, - annualizedReturn: 0, - cagr: 0, - volatility: 0, - downVolatility: 0, - maxDrawdown: 0, - maxDrawdownDuration: 0, - var95: 0, - cvar95: 0, - sharpeRatio: 0, - sortinoRatio: 0, - calmarRatio: 0, - informationRatio: 0, - totalTrades: 0, - winRate: 0, - avgWin: 0, - avgLoss: 0, - avgWinLoss: 0, - profitFactor: 0, - expectancy: 0, - payoffRatio: 0, - avgHoldingPeriod: 0, - avgTradesPerDay: 0, - maxConsecutiveWins: 0, - maxConsecutiveLosses: 0, - largestWin: 0, - largestLoss: 0, - skewness: 0, - kurtosis: 0, - tailRatio: 0, - kellyFraction: 0, - optimalLeverage: 1 - }; - } - - exportReport(): string { - const metrics = this.analyze(); - const drawdowns = this.analyzeDrawdowns(); - - return ` -# Performance Report - -## Summary Statistics -- Total Return: ${metrics.totalReturn.toFixed(2)}% -- Annualized Return: ${metrics.annualizedReturn.toFixed(2)}% -- CAGR: ${metrics.cagr.toFixed(2)}% -- Volatility: ${metrics.volatility.toFixed(2)}% -- Max Drawdown: ${metrics.maxDrawdown.toFixed(2)}% -- Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)} -- Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)} - -## Trade Analysis -- Total Trades: ${metrics.totalTrades} -- Win Rate: ${metrics.winRate.toFixed(1)}% -- Profit Factor: ${metrics.profitFactor.toFixed(2)} -- Average Win: $${metrics.avgWin.toFixed(2)} -- Average Loss: $${metrics.avgLoss.toFixed(2)} -- Expectancy: $${metrics.expectancy.toFixed(2)} - -## Risk Metrics -- VaR (95%): ${metrics.var95.toFixed(2)}% -- CVaR (95%): ${metrics.cvar95.toFixed(2)}% -- Downside Volatility: ${metrics.downVolatility.toFixed(2)}% -- Tail Ratio: ${metrics.tailRatio.toFixed(2)} -- Skewness: ${metrics.skewness.toFixed(2)} -- Kurtosis: ${metrics.kurtosis.toFixed(2)} - -## Optimal Position Sizing -- Kelly Fraction: ${(metrics.kellyFraction * 100).toFixed(1)}% -- Optimal Leverage: ${metrics.optimalLeverage.toFixed(1)}x -`; - } -} \ No newline at end of file +import * as stats from 'simple-statistics'; +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; + +const logger = getLogger('PerformanceAnalyzer'); + +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; // in minutes + mae: number; // Maximum Adverse Excursion + mfe: number; // Maximum Favorable Excursion +} + +export interface PerformanceMetrics { + // Return metrics + totalReturn: number; + annualizedReturn: number; + cagr: number; // Compound Annual Growth Rate + + // Risk metrics + volatility: number; + downVolatility: number; + maxDrawdown: number; + maxDrawdownDuration: number; // days + var95: number; // Value at Risk 95% + cvar95: number; // Conditional VaR 95% + + // Risk-adjusted returns + sharpeRatio: number; + sortinoRatio: number; + calmarRatio: number; + informationRatio: number; + + // Trade statistics + totalTrades: number; + winRate: number; + avgWin: number; + avgLoss: number; + avgWinLoss: number; + profitFactor: number; + expectancy: number; + payoffRatio: number; + + // Trade analysis + avgHoldingPeriod: number; + avgTradesPerDay: number; + maxConsecutiveWins: number; + maxConsecutiveLosses: number; + largestWin: number; + largestLoss: number; + + // Statistical measures + skewness: number; + kurtosis: number; + tailRatio: number; + + // Kelly criterion + kellyFraction: number; + optimalLeverage: number; +} + +export interface DrawdownAnalysis { + maxDrawdown: number; + maxDrawdownDuration: number; + currentDrawdown: number; + drawdownPeriods: Array<{ + start: Date; + end: Date; + depth: number; + duration: number; + recovery: number; + }>; + underwaterCurve: Array<{ date: Date; drawdown: number }>; +} + +export interface FactorAttribution { + alpha: number; + beta: number; + correlation: number; + treynorRatio: number; + trackingError: number; + upCapture: number; + downCapture: number; +} + +export class PerformanceAnalyzer { + private equityCurve: Array<{ date: Date; value: number }> = []; + private trades: Trade[] = []; + private dailyReturns: number[] = []; + private benchmarkReturns?: number[]; + + constructor(private initialCapital: number = 100000) {} + + addEquityPoint(date: Date, value: number): void { + this.equityCurve.push({ date, value }); + // Don't calculate daily returns on every point - wait until analyze() is called + } + + addTrade(trade: Trade): void { + this.trades.push(trade); + } + + setBenchmark(returns: number[]): void { + this.benchmarkReturns = returns; + } + + analyze(): PerformanceMetrics { + if (this.equityCurve.length < 2) { + return this.getEmptyMetrics(); + } + + // Calculate daily returns before analysis + this.calculateDailyReturns(); + + // Calculate returns + const totalReturn = this.calculateTotalReturn(); + const annualizedReturn = this.calculateAnnualizedReturn(); + const cagr = this.calculateCAGR(); + + // Risk metrics + const volatility = this.calculateVolatility(); + const downVolatility = this.calculateDownsideVolatility(); + const drawdownAnalysis = this.analyzeDrawdowns(); + const { var95, cvar95 } = this.calculateVaR(); + + // Risk-adjusted returns + const sharpeRatio = this.calculateSharpeRatio(annualizedReturn, volatility); + const sortinoRatio = this.calculateSortinoRatio(annualizedReturn, downVolatility); + const calmarRatio = + drawdownAnalysis.maxDrawdown > 0 + ? annualizedReturn / (drawdownAnalysis.maxDrawdown * 100) + : 0; + const informationRatio = this.calculateInformationRatio(); + + // Trade statistics + const tradeStats = this.analyzeTradeStatistics(); + + // Statistical measures + const { skewness, kurtosis } = this.calculateDistributionMetrics(); + const tailRatio = this.calculateTailRatio(); + + // Kelly criterion + const { kellyFraction, optimalLeverage } = this.calculateKellyCriterion(tradeStats); + + return { + totalReturn, + annualizedReturn, + cagr, + volatility: volatility * 100, // Convert to percentage for display + downVolatility: downVolatility * 100, // Convert to percentage for display + maxDrawdown: drawdownAnalysis.maxDrawdown, + maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration, + var95, + cvar95, + sharpeRatio, + sortinoRatio, + calmarRatio, + informationRatio, + totalTrades: tradeStats.totalTrades ?? 0, + winRate: tradeStats.winRate ?? 0, + avgWin: tradeStats.avgWin ?? 0, + avgLoss: tradeStats.avgLoss ?? 0, + avgWinLoss: tradeStats.avgWinLoss ?? 0, + profitFactor: tradeStats.profitFactor ?? 0, + expectancy: tradeStats.expectancy ?? 0, + payoffRatio: tradeStats.payoffRatio ?? 0, + avgHoldingPeriod: tradeStats.avgHoldingPeriod ?? 0, + avgTradesPerDay: tradeStats.avgTradesPerDay ?? 0, + maxConsecutiveWins: tradeStats.maxConsecutiveWins ?? 0, + maxConsecutiveLosses: tradeStats.maxConsecutiveLosses ?? 0, + largestWin: tradeStats.largestWin ?? 0, + largestLoss: tradeStats.largestLoss ?? 0, + skewness, + kurtosis, + tailRatio, + kellyFraction, + optimalLeverage, + }; + } + + analyzeDrawdowns(): DrawdownAnalysis { + const drawdowns: number[] = []; + const underwaterCurve: Array<{ date: Date; drawdown: number }> = []; + + // Handle empty equity curve + if (this.equityCurve.length === 0) { + return { + maxDrawdown: 0, + maxDrawdownDuration: 0, + underwaterCurve: [], + drawdownPeriods: [], + currentDrawdown: 0, + }; + } + + let peak = at(this.equityCurve, 0).value; + let maxDrawdown = 0; + let currentDrawdownStart: Date | null = null; + const drawdownPeriods: DrawdownAnalysis['drawdownPeriods'] = []; + + for (let i = 0; i < this.equityCurve.length; i++) { + const point = at(this.equityCurve, i); + + if (point.value > peak) { + // New peak - end current drawdown if any + if (currentDrawdownStart) { + const period = { + start: currentDrawdownStart, + end: point.date, + depth: maxDrawdown, + duration: this.daysBetween(currentDrawdownStart, point.date), + recovery: i, + }; + drawdownPeriods.push(period); + currentDrawdownStart = null; + } + peak = point.value; + } + + const drawdown = (point.value - peak) / peak; + drawdowns.push(drawdown); + underwaterCurve.push({ date: point.date, drawdown }); + + if (drawdown < 0 && !currentDrawdownStart) { + currentDrawdownStart = point.date; + } + + if (drawdown < maxDrawdown) { + maxDrawdown = drawdown; + } + } + + // Handle ongoing drawdown + const currentDrawdown = at(drawdowns, drawdowns.length - 1); + + // Calculate max drawdown duration + const maxDrawdownDuration = Math.max( + ...drawdownPeriods.map(p => p.duration), + currentDrawdownStart ? this.daysBetween(currentDrawdownStart, new Date()) : 0 + ); + + return { + maxDrawdown: Math.abs(maxDrawdown), + maxDrawdownDuration, + currentDrawdown: Math.abs(currentDrawdown), + drawdownPeriods, + underwaterCurve, + }; + } + + calculateFactorAttribution(benchmarkReturns: number[]): FactorAttribution { + if (this.dailyReturns.length !== benchmarkReturns.length) { + throw new Error('Returns and benchmark must have same length'); + } + + // Calculate beta using linear regression + const regression = stats.linearRegression( + this.dailyReturns.map((r, i) => [at(benchmarkReturns, i), r]) + ); + const beta = regression.m; + const alpha = regression.b * 252; // Annualized + + // Correlation + const correlation = stats.sampleCorrelation(this.dailyReturns, benchmarkReturns); + + // Treynor ratio + const excessReturn = this.calculateAnnualizedReturn() - 0.02; // Assume 2% risk-free + const treynorRatio = beta !== 0 ? excessReturn / beta : 0; + + // Tracking error + const returnDiffs = this.dailyReturns.map((r, i) => r - at(benchmarkReturns, i)); + const trackingError = stats.standardDeviation(returnDiffs) * Math.sqrt(252); + + // Up/down capture + const upDays = benchmarkReturns + .map((r, i) => (r > 0 ? { bench: r, port: this.dailyReturns[i] } : null)) + .filter(d => d !== null) as Array<{ bench: number; port: number }>; + + const downDays = benchmarkReturns + .map((r, i) => (r < 0 ? { bench: r, port: this.dailyReturns[i] } : null)) + .filter(d => d !== null) as Array<{ bench: number; port: number }>; + + const upCapture = + upDays.length > 0 + ? stats.mean(upDays.map(d => d.port)) / stats.mean(upDays.map(d => d.bench)) + : 0; + + const downCapture = + downDays.length > 0 + ? stats.mean(downDays.map(d => d.port)) / stats.mean(downDays.map(d => d.bench)) + : 0; + + return { + alpha, + beta, + correlation, + treynorRatio, + trackingError, + upCapture, + downCapture, + }; + } + + private calculateDailyReturns(): void { + this.dailyReturns = []; + + // First, aggregate equity curve by day (taking last value of each day) + const dailyEquity = new Map(); + + for (const point of this.equityCurve) { + const dateKey = at(point.date.toISOString().split('T'), 0); + dailyEquity.set(dateKey, point); // This will keep the last value of each day + } + + // Convert to sorted array + const dailyPoints = Array.from(dailyEquity.values()).sort( + (a, b) => a.date.getTime() - b.date.getTime() + ); + + // Calculate returns from daily points + for (let i = 1; i < dailyPoints.length; i++) { + const prevValue = at(dailyPoints, i - 1).value; + const currValue = at(dailyPoints, i).value; + if (prevValue > 0) { + this.dailyReturns.push((currValue - prevValue) / prevValue); + } + } + } + + private calculateTotalReturn(): number { + const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value; + return ((finalValue - this.initialCapital) / this.initialCapital) * 100; + } + + private calculateAnnualizedReturn(): number { + const totalReturn = this.calculateTotalReturn() / 100; + const years = this.getYears(); + return (Math.pow(1 + totalReturn, 1 / years) - 1) * 100; + } + + private calculateCAGR(): number { + const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value; + const years = this.getYears(); + return (Math.pow(finalValue / this.initialCapital, 1 / years) - 1) * 100; + } + + private calculateVolatility(): number { + if (this.dailyReturns.length === 0) { + return 0; + } + // Return volatility as a decimal percentage (not multiplied by 100) + return stats.standardDeviation(this.dailyReturns) * Math.sqrt(252); + } + + private calculateDownsideVolatility(): number { + const negativeReturns = this.dailyReturns.filter(r => r < 0); + if (negativeReturns.length === 0) { + return 0; + } + // Return volatility as a decimal percentage (not multiplied by 100) + return stats.standardDeviation(negativeReturns) * Math.sqrt(252); + } + + private calculateVaR(): { var95: number; cvar95: number } { + if (this.dailyReturns.length === 0) { + return { var95: 0, cvar95: 0 }; + } + + const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b); + const index95 = Math.floor(sortedReturns.length * 0.05); + + // Handle edge case where we don't have enough data points + if (index95 === 0 || sortedReturns.length < 20) { + return { var95: 0, cvar95: 0 }; + } + + const var95 = Math.abs(at(sortedReturns, index95)) * 100; + const tailReturns = sortedReturns.slice(0, index95); + const cvar95 = tailReturns.length > 0 ? Math.abs(stats.mean(tailReturns)) * 100 : 0; + + return { var95, cvar95 }; + } + + private calculateSharpeRatio( + annualReturn: number, + volatility: number, + riskFree: number = 2 + ): number { + if (volatility === 0) { + return 0; + } + // Both annualReturn and volatility should be in percentage form + const volatilityPct = volatility * 100; + return (annualReturn - riskFree) / volatilityPct; + } + + private calculateSortinoRatio( + annualReturn: number, + downVolatility: number, + riskFree: number = 2 + ): number { + if (downVolatility === 0) { + return 0; + } + // Both annualReturn and downVolatility should be in percentage form + const downVolatilityPct = downVolatility * 100; + return (annualReturn - riskFree) / downVolatilityPct; + } + + private calculateInformationRatio(): number { + if (!this.benchmarkReturns || this.benchmarkReturns.length !== this.dailyReturns.length) { + return 0; + } + + const excessReturns = this.dailyReturns.map( + (r, i) => r - at(defined(this.benchmarkReturns), i) + ); + const trackingError = stats.standardDeviation(excessReturns); + + if (trackingError === 0) { + return 0; + } + + const avgExcessReturn = stats.mean(excessReturns); + return (avgExcessReturn * 252) / (trackingError * Math.sqrt(252)); + } + + private analyzeTradeStatistics(): Partial { + if (this.trades.length === 0) { + return { + totalTrades: 0, + winRate: 0, + avgWin: 0, + avgLoss: 0, + avgWinLoss: 0, + profitFactor: 0, + expectancy: 0, + payoffRatio: 0, + avgHoldingPeriod: 0, + avgTradesPerDay: 0, + maxConsecutiveWins: 0, + maxConsecutiveLosses: 0, + largestWin: 0, + largestLoss: 0, + }; + } + + // Filter out trades with 0 or undefined P&L + const validTrades = this.trades.filter(t => t.pnl !== undefined && t.pnl !== null); + const wins = validTrades.filter(t => t.pnl > 0); + const losses = validTrades.filter(t => t.pnl < 0); + + // Log trade analysis for debugging + logger.debug( + `Trade Analysis: Total=${this.trades.length}, Valid=${validTrades.length}, Wins=${wins.length}, Losses=${losses.length}` + ); + + const totalWins = wins.reduce((sum, t) => sum + t.pnl, 0); + const totalLosses = Math.abs(losses.reduce((sum, t) => sum + t.pnl, 0)); + + const avgWin = wins.length > 0 ? totalWins / wins.length : 0; + const avgLoss = losses.length > 0 ? totalLosses / losses.length : 0; + + const winRate = validTrades.length > 0 ? (wins.length / validTrades.length) * 100 : 0; + const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0; + const expectancy = (winRate / 100) * avgWin - ((100 - winRate) / 100) * avgLoss; + const payoffRatio = avgLoss > 0 ? avgWin / avgLoss : 0; + + // Holding period analysis + const holdingPeriods = this.trades.map(t => t.holdingPeriod); + const avgHoldingPeriod = stats.mean(holdingPeriods); + + // Trades per day + const tradingDays = this.getTradingDays(); + const avgTradesPerDay = tradingDays > 0 ? this.trades.length / tradingDays : 0; + + // Consecutive wins/losses + const { maxConsecutiveWins, maxConsecutiveLosses } = this.calculateConsecutiveStats(); + + // Largest win/loss + const largestWin = Math.max(...this.trades.map(t => t.pnl), 0); + const largestLoss = Math.abs(Math.min(...this.trades.map(t => t.pnl), 0)); + + return { + totalTrades: this.trades.length, + winRate, + avgWin, + avgLoss, + avgWinLoss: avgWin - avgLoss, + profitFactor, + expectancy, + payoffRatio, + avgHoldingPeriod, + avgTradesPerDay, + maxConsecutiveWins, + maxConsecutiveLosses, + largestWin, + largestLoss, + }; + } + + private calculateDistributionMetrics(): { skewness: number; kurtosis: number } { + if (this.dailyReturns.length < 4) { + return { skewness: 0, kurtosis: 0 }; + } + + const mean = stats.mean(this.dailyReturns); + const std = stats.standardDeviation(this.dailyReturns); + + if (std === 0) { + return { skewness: 0, kurtosis: 0 }; + } + + const n = this.dailyReturns.length; + + // Skewness + const skewSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 3), 0); + const skewness = (n / ((n - 1) * (n - 2))) * skewSum; + + // Kurtosis + const kurtSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 4), 0); + const kurtosis = + ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * kurtSum - + (3 * (n - 1) * (n - 1)) / ((n - 2) * (n - 3)); + + return { skewness, kurtosis }; + } + + private calculateTailRatio(): number { + if (this.dailyReturns.length < 20) { + return 0; + } + + const sorted = [...this.dailyReturns].sort((a, b) => b - a); + const percentile95 = at(sorted, Math.floor(sorted.length * 0.05)); + const percentile5 = at(sorted, Math.floor(sorted.length * 0.95)); + + return Math.abs(percentile5) > 0 ? percentile95 / Math.abs(percentile5) : 0; + } + + private calculateKellyCriterion(tradeStats: Partial): { + kellyFraction: number; + optimalLeverage: number; + } { + const winRate = (tradeStats.winRate || 0) / 100; + const payoffRatio = tradeStats.payoffRatio || 0; + + if (payoffRatio === 0) { + return { kellyFraction: 0, optimalLeverage: 1 }; + } + + // Kelly formula: f = p - q/b + // where p = win probability, q = loss probability, b = payoff ratio + const kellyFraction = winRate - (1 - winRate) / payoffRatio; + + // Conservative Kelly (25% of full Kelly) + const conservativeKelly = Math.max(0, Math.min(0.25, kellyFraction * 0.25)); + + // Optimal leverage based on Sharpe ratio + const sharpe = this.calculateSharpeRatio( + this.calculateAnnualizedReturn(), + this.calculateVolatility() + ); + const optimalLeverage = Math.max(1, Math.min(3, sharpe / 2)); + + return { + kellyFraction: conservativeKelly, + optimalLeverage, + }; + } + + private calculateConsecutiveStats(): { + maxConsecutiveWins: number; + maxConsecutiveLosses: number; + } { + let maxWins = 0, + maxLosses = 0; + let currentWins = 0, + currentLosses = 0; + + for (const trade of this.trades) { + if (trade.pnl > 0) { + currentWins++; + currentLosses = 0; + maxWins = Math.max(maxWins, currentWins); + } else if (trade.pnl < 0) { + currentLosses++; + currentWins = 0; + maxLosses = Math.max(maxLosses, currentLosses); + } + } + + return { maxConsecutiveWins: maxWins, maxConsecutiveLosses: maxLosses }; + } + + private getYears(): number { + if (this.equityCurve.length < 2) { + return 1; + } + const start = at(this.equityCurve, 0).date; + const end = at(this.equityCurve, this.equityCurve.length - 1).date; + return this.daysBetween(start, end) / 365; + } + + private getTradingDays(): number { + if (this.equityCurve.length < 2) { + return 0; + } + const start = at(this.equityCurve, 0).date; + const end = at(this.equityCurve, this.equityCurve.length - 1).date; + return this.daysBetween(start, end) * (252 / 365); // Approximate trading days + } + + private daysBetween(start: Date, end: Date): number { + return (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24); + } + + private getEmptyMetrics(): PerformanceMetrics { + return { + totalReturn: 0, + annualizedReturn: 0, + cagr: 0, + volatility: 0, + downVolatility: 0, + maxDrawdown: 0, + maxDrawdownDuration: 0, + var95: 0, + cvar95: 0, + sharpeRatio: 0, + sortinoRatio: 0, + calmarRatio: 0, + informationRatio: 0, + totalTrades: 0, + winRate: 0, + avgWin: 0, + avgLoss: 0, + avgWinLoss: 0, + profitFactor: 0, + expectancy: 0, + payoffRatio: 0, + avgHoldingPeriod: 0, + avgTradesPerDay: 0, + maxConsecutiveWins: 0, + maxConsecutiveLosses: 0, + largestWin: 0, + largestLoss: 0, + skewness: 0, + kurtosis: 0, + tailRatio: 0, + kellyFraction: 0, + optimalLeverage: 1, + }; + } + + exportReport(): string { + const metrics = this.analyze(); + const _drawdowns = this.analyzeDrawdowns(); + + return ` +# Performance Report + +## Summary Statistics +- Total Return: ${metrics.totalReturn.toFixed(2)}% +- Annualized Return: ${metrics.annualizedReturn.toFixed(2)}% +- CAGR: ${metrics.cagr.toFixed(2)}% +- Volatility: ${metrics.volatility.toFixed(2)}% +- Max Drawdown: ${metrics.maxDrawdown.toFixed(2)}% +- Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)} +- Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)} + +## Trade Analysis +- Total Trades: ${metrics.totalTrades} +- Win Rate: ${metrics.winRate.toFixed(1)}% +- Profit Factor: ${metrics.profitFactor.toFixed(2)} +- Average Win: $${metrics.avgWin.toFixed(2)} +- Average Loss: $${metrics.avgLoss.toFixed(2)} +- Expectancy: $${metrics.expectancy.toFixed(2)} + +## Risk Metrics +- VaR (95%): ${metrics.var95.toFixed(2)}% +- CVaR (95%): ${metrics.cvar95.toFixed(2)}% +- Downside Volatility: ${metrics.downVolatility.toFixed(2)}% +- Tail Ratio: ${metrics.tailRatio.toFixed(2)} +- Skewness: ${metrics.skewness.toFixed(2)} +- Kurtosis: ${metrics.kurtosis.toFixed(2)} + +## Optimal Position Sizing +- Kelly Fraction: ${(metrics.kellyFraction * 100).toFixed(1)}% +- Optimal Leverage: ${metrics.optimalLeverage.toFixed(1)}x +`; + } +} diff --git a/apps/stock/orchestrator/src/api/rest/analytics.ts b/apps/stock/orchestrator/src/api/rest/analytics.ts index a06da608..027bef94 100644 --- a/apps/stock/orchestrator/src/api/rest/analytics.ts +++ b/apps/stock/orchestrator/src/api/rest/analytics.ts @@ -1,179 +1,215 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { IServiceContainer } from '@stock-bot/di'; -import { AnalyticsService } from '../../services/AnalyticsService'; - -const DateRangeSchema = z.object({ - startDate: z.string().datetime(), - endDate: z.string().datetime() -}); - -const OptimizationRequestSchema = z.object({ - symbols: z.array(z.string()), - returns: z.array(z.array(z.number())), - constraints: z.object({ - minWeight: z.number().optional(), - maxWeight: z.number().optional(), - targetReturn: z.number().optional(), - maxRisk: z.number().optional() - }).optional() -}); - -export function createAnalyticsRoutes(container: IServiceContainer): Hono { - const app = new Hono(); - const analyticsService = container.custom?.AnalyticsService as AnalyticsService; - - // Get performance metrics - app.get('/performance/:portfolioId', async (c) => { - try { - const portfolioId = c.req.param('portfolioId'); - const query = c.req.query(); - - const { startDate, endDate } = DateRangeSchema.parse({ - startDate: query.start_date, - endDate: query.end_date - }); - - const metrics = await analyticsService.getPerformanceMetrics( - portfolioId, - new Date(startDate), - new Date(endDate) - ); - - return c.json(metrics); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid date range', - details: error.errors - }, 400); - } - - container.logger.error('Error getting performance metrics:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to get performance metrics' - }, 500); - } - }); - - // Portfolio optimization - app.post('/optimize', async (c) => { - try { - const body = await c.req.json(); - const request = OptimizationRequestSchema.parse(body); - - const result = await analyticsService.optimizePortfolio({ - returns: request.returns, - constraints: request.constraints - }); - - return c.json(result); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid optimization request', - details: error.errors - }, 400); - } - - container.logger.error('Error optimizing portfolio:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to optimize portfolio' - }, 500); - } - }); - - // Get risk metrics - app.get('/risk/:portfolioId', async (c) => { - try { - const portfolioId = c.req.param('portfolioId'); - const metrics = await analyticsService.getRiskMetrics(portfolioId); - - return c.json(metrics); - } 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); - } - }); - - // Market regime detection - app.get('/regime', async (c) => { - try { - const regime = await analyticsService.detectMarketRegime(); - - return c.json({ - regime, - timestamp: new Date().toISOString() - }); - } catch (error) { - container.logger.error('Error detecting market regime:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to detect market regime' - }, 500); - } - }); - - // Calculate correlation matrix - app.post('/correlation', async (c) => { - try { - const body = await c.req.json(); - const { symbols } = z.object({ - symbols: z.array(z.string()).min(2) - }).parse(body); - - const matrix = await analyticsService.calculateCorrelationMatrix(symbols); - - return c.json({ - symbols, - matrix - }); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid correlation request', - details: error.errors - }, 400); - } - - container.logger.error('Error calculating correlation:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to calculate correlation' - }, 500); - } - }); - - // ML model prediction - app.post('/predict', async (c) => { - try { - const body = await c.req.json(); - const { modelId, features } = z.object({ - modelId: z.string(), - features: z.record(z.number()) - }).parse(body); - - const prediction = await analyticsService.predictWithModel(modelId, features); - - if (prediction) { - return c.json(prediction); - } else { - return c.json({ error: 'Model not found or prediction failed' }, 404); - } - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid prediction request', - details: error.errors - }, 400); - } - - container.logger.error('Error making prediction:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to make prediction' - }, 500); - } - }); - - return app; -} \ No newline at end of file +import { Hono } from 'hono'; +import { z } from 'zod'; +import { AnalyticsService } from '../../services/AnalyticsService'; +import type { OrchestratorServices as IServiceContainer } from '../../types'; + +const DateRangeSchema = z.object({ + startDate: z.string().datetime(), + endDate: z.string().datetime(), +}); + +const OptimizationRequestSchema = z.object({ + symbols: z.array(z.string()), + returns: z.array(z.array(z.number())), + constraints: z + .object({ + minWeight: z.number().optional(), + maxWeight: z.number().optional(), + targetReturn: z.number().optional(), + maxRisk: z.number().optional(), + }) + .optional(), +}); + +export function createAnalyticsRoutes(container: IServiceContainer): Hono { + const app = new Hono(); + const analyticsService = container.custom?.AnalyticsService as AnalyticsService; + + // Get performance metrics + app.get('/performance/:portfolioId', async c => { + try { + const portfolioId = c.req.param('portfolioId'); + const query = c.req.query(); + + const { startDate, endDate } = DateRangeSchema.parse({ + startDate: query.start_date, + endDate: query.end_date, + }); + + const metrics = await analyticsService.getPerformanceMetrics( + portfolioId, + new Date(startDate), + new Date(endDate) + ); + + return c.json(metrics); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid date range', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error getting performance metrics:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to get performance metrics', + }, + 500 + ); + } + }); + + // Portfolio optimization + app.post('/optimize', async c => { + try { + const body = await c.req.json(); + const request = OptimizationRequestSchema.parse(body); + + const result = await analyticsService.optimizePortfolio({ + returns: request.returns, + constraints: request.constraints, + }); + + return c.json(result); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid optimization request', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error optimizing portfolio:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to optimize portfolio', + }, + 500 + ); + } + }); + + // Get risk metrics + app.get('/risk/:portfolioId', async c => { + try { + const portfolioId = c.req.param('portfolioId'); + const metrics = await analyticsService.getRiskMetrics(portfolioId); + + return c.json(metrics); + } 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 + ); + } + }); + + // Market regime detection + app.get('/regime', async c => { + try { + const regime = await analyticsService.detectMarketRegime(); + + return c.json({ + regime, + timestamp: new Date().toISOString(), + }); + } catch (error) { + container.logger.error('Error detecting market regime:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to detect market regime', + }, + 500 + ); + } + }); + + // Calculate correlation matrix + app.post('/correlation', async c => { + try { + const body = await c.req.json(); + const { symbols } = z + .object({ + symbols: z.array(z.string()).min(2), + }) + .parse(body); + + const matrix = await analyticsService.calculateCorrelationMatrix(symbols); + + return c.json({ + symbols, + matrix, + }); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid correlation request', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error calculating correlation:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to calculate correlation', + }, + 500 + ); + } + }); + + // ML model prediction + app.post('/predict', async c => { + try { + const body = await c.req.json(); + const { modelId, features } = z + .object({ + modelId: z.string(), + features: z.record(z.number()), + }) + .parse(body); + + const prediction = await analyticsService.predictWithModel(modelId, features); + + if (prediction) { + return c.json(prediction); + } else { + return c.json({ error: 'Model not found or prediction failed' }, 404); + } + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid prediction request', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error making prediction:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to make prediction', + }, + 500 + ); + } + }); + + return app; +} diff --git a/apps/stock/orchestrator/src/api/rest/backtest.ts b/apps/stock/orchestrator/src/api/rest/backtest.ts index c99dbf89..d5816190 100644 --- a/apps/stock/orchestrator/src/api/rest/backtest.ts +++ b/apps/stock/orchestrator/src/api/rest/backtest.ts @@ -1,245 +1,278 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { IServiceContainer } from '@stock-bot/di'; -import { BacktestConfigSchema } from '../../types'; -import { BacktestEngine } from '../../backtest/BacktestEngine'; -import { ModeManager } from '../../core/ModeManager'; - -const BacktestIdSchema = z.object({ - backtestId: z.string() -}); - -export function createBacktestRoutes(container: IServiceContainer): Hono { - const app = new Hono(); - const backtestEngine = container.custom?.BacktestEngine as BacktestEngine; - const modeManager = container.custom?.ModeManager as ModeManager; - - // Default POST to / is the same as /run for backward compatibility - app.post('/', async (c) => { - try { - const body = await c.req.json(); - const config = BacktestConfigSchema.parse(body); - - // Initialize backtest mode - await modeManager.initializeMode(config); - - // Run backtest - const result = await backtestEngine.runBacktest(config); - - return c.json(result, 201); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid backtest configuration', - details: error.errors - }, 400); - } - - container.logger.error('Error running backtest:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to run backtest' - }, 500); - } - }); - - // Run new backtest (same as above but at /run) - app.post('/run', async (c) => { - try { - const body = await c.req.json(); - const config = BacktestConfigSchema.parse(body); - - // Initialize backtest mode - await modeManager.initializeMode(config); - - // Run backtest - const result = await backtestEngine.runBacktest(config); - - return c.json(result, 201); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - error: 'Invalid backtest configuration', - details: error.errors - }, 400); - } - - container.logger.error('Error running backtest:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to run backtest' - }, 500); - } - }); - - // Stop running backtest - app.post('/stop', async (c) => { - try { - await backtestEngine.stopBacktest(); - - return c.json({ - message: 'Backtest stop requested', - timestamp: new Date().toISOString() - }); - } catch (error) { - container.logger.error('Error stopping backtest:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to stop backtest' - }, 500); - } - }); - - // Pause running backtest - app.post('/pause', async (c) => { - try { - await backtestEngine.pauseBacktest(); - - return c.json({ - message: 'Backtest paused', - timestamp: new Date().toISOString() - }); - } catch (error) { - container.logger.error('Error pausing backtest:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to pause backtest' - }, 500); - } - }); - - // Resume paused backtest - app.post('/resume', async (c) => { - try { - await backtestEngine.resumeBacktest(); - - return c.json({ - message: 'Backtest resumed', - timestamp: new Date().toISOString() - }); - } catch (error) { - container.logger.error('Error resuming backtest:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to resume backtest' - }, 500); - } - }); - - // Set backtest speed - app.post('/speed', async (c) => { - try { - const body = await c.req.json(); - const speed = body.speed ?? 1; - - backtestEngine.setSpeedMultiplier(speed); - - return c.json({ - message: 'Backtest speed updated', - speed: speed === null ? 'unlimited' : speed, - timestamp: new Date().toISOString() - }); - } catch (error) { - container.logger.error('Error setting backtest speed:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to set speed' - }, 500); - } - }); - - // Get backtest progress - app.get('/progress', async (c) => { - try { - const status = backtestEngine.getStatus(); - - return c.json({ - status: status.isPaused ? 'paused' : (status.isRunning ? 'running' : 'idle'), - progress: status.progress, - currentTime: new Date(status.currentTime).toISOString(), - isRunning: status.isRunning, - isPaused: status.isPaused - }); - } catch (error) { - container.logger.error('Error getting backtest progress:', error); - return c.json({ - error: error instanceof Error ? error.message : 'Failed to get progress' - }, 500); - } - }); - - // Stream backtest events (Server-Sent Events) - app.get('/stream', async (c) => { - c.header('Content-Type', 'text/event-stream'); - c.header('Cache-Control', 'no-cache'); - c.header('Connection', 'keep-alive'); - - const stream = new ReadableStream({ - start(controller) { - // Listen for backtest events - const onProgress = (data: any) => { - controller.enqueue(`data: ${JSON.stringify(data)}\n\n`); - }; - - const onComplete = (data: any) => { - controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`); - controller.close(); - }; - - backtestEngine.on('progress', onProgress); - backtestEngine.on('complete', onComplete); - - // Cleanup on close - c.req.raw.signal.addEventListener('abort', () => { - backtestEngine.off('progress', onProgress); - backtestEngine.off('complete', onComplete); - controller.close(); - }); - } - }); - - return new Response(stream); - }); - - // Validate backtest configuration - app.post('/validate', async (c) => { - try { - const body = await c.req.json(); - const config = BacktestConfigSchema.parse(body); - - // Additional validation logic - const validation = { - valid: true, - warnings: [] as string[], - estimatedDuration: 0 - }; - - // Check data availability - const startDate = new Date(config.startDate); - const endDate = new Date(config.endDate); - const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24); - - if (days > 365) { - validation.warnings.push('Large date range may take significant time to process'); - } - - if (config.symbols.length > 100) { - validation.warnings.push('Large number of symbols may impact performance'); - } - - // Estimate duration (simplified) - validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds - - return c.json(validation); - } catch (error) { - if (error instanceof z.ZodError) { - return c.json({ - valid: false, - error: 'Invalid configuration', - details: error.errors - }, 400); - } - - return c.json({ - valid: false, - error: error instanceof Error ? error.message : 'Validation failed' - }, 500); - } - }); - - return app; -} \ No newline at end of file +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'; +import { BacktestConfigSchema } from '../../types'; + +const _BacktestIdSchema = z.object({ + backtestId: z.string(), +}); + +export function createBacktestRoutes(container: IServiceContainer): Hono { + const app = new Hono(); + const backtestEngine = defined(container.custom?.BacktestEngine); + const modeManager = container.custom?.ModeManager as ModeManager; + + // Default POST to / is the same as /run for backward compatibility + app.post('/', async c => { + try { + const body = await c.req.json(); + const config = BacktestConfigSchema.parse(body); + + // Initialize backtest mode + await modeManager.initializeMode(config); + + // Run backtest + const result = await backtestEngine.runBacktest(config); + + return c.json(result, 201); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid backtest configuration', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error running backtest:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to run backtest', + }, + 500 + ); + } + }); + + // Run new backtest (same as above but at /run) + app.post('/run', async c => { + try { + const body = await c.req.json(); + const config = BacktestConfigSchema.parse(body); + + // Initialize backtest mode + await modeManager.initializeMode(config); + + // Run backtest + const result = await backtestEngine.runBacktest(config); + + return c.json(result, 201); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + error: 'Invalid backtest configuration', + details: error.errors, + }, + 400 + ); + } + + container.logger.error('Error running backtest:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to run backtest', + }, + 500 + ); + } + }); + + // Stop running backtest + app.post('/stop', async c => { + try { + await backtestEngine.stopBacktest(); + + return c.json({ + message: 'Backtest stop requested', + timestamp: new Date().toISOString(), + }); + } catch (error) { + container.logger.error('Error stopping backtest:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to stop backtest', + }, + 500 + ); + } + }); + + // Pause running backtest + app.post('/pause', async c => { + try { + await backtestEngine.pauseBacktest(); + + return c.json({ + message: 'Backtest paused', + timestamp: new Date().toISOString(), + }); + } catch (error) { + container.logger.error('Error pausing backtest:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to pause backtest', + }, + 500 + ); + } + }); + + // Resume paused backtest + app.post('/resume', async c => { + try { + await backtestEngine.resumeBacktest(); + + return c.json({ + message: 'Backtest resumed', + timestamp: new Date().toISOString(), + }); + } catch (error) { + container.logger.error('Error resuming backtest:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to resume backtest', + }, + 500 + ); + } + }); + + // Set backtest speed + app.post('/speed', async c => { + try { + const body = await c.req.json(); + const speed = body.speed ?? 1; + + backtestEngine.setSpeedMultiplier(speed); + + return c.json({ + message: 'Backtest speed updated', + speed: speed === null ? 'unlimited' : speed, + timestamp: new Date().toISOString(), + }); + } catch (error) { + container.logger.error('Error setting backtest speed:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to set speed', + }, + 500 + ); + } + }); + + // Get backtest progress + app.get('/progress', async c => { + try { + const status = backtestEngine.getStatus(); + + return c.json({ + status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle', + progress: status.progress, + currentTime: new Date(status.currentTime).toISOString(), + isRunning: status.isRunning, + isPaused: status.isPaused, + }); + } catch (error) { + container.logger.error('Error getting backtest progress:', error); + return c.json( + { + error: error instanceof Error ? error.message : 'Failed to get progress', + }, + 500 + ); + } + }); + + // Stream backtest events (Server-Sent Events) + app.get('/stream', async c => { + c.header('Content-Type', 'text/event-stream'); + c.header('Cache-Control', 'no-cache'); + c.header('Connection', 'keep-alive'); + + const stream = new ReadableStream({ + start(controller) { + // Listen for backtest events + const onProgress = (data: unknown) => { + controller.enqueue(`data: ${JSON.stringify(data)}\n\n`); + }; + + const onComplete = (data: unknown) => { + controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`); + controller.close(); + }; + + backtestEngine.on('progress', onProgress); + backtestEngine.on('complete', onComplete); + + // Cleanup on close + c.req.raw.signal.addEventListener('abort', () => { + backtestEngine.off('progress', onProgress); + backtestEngine.off('complete', onComplete); + controller.close(); + }); + }, + }); + + return new Response(stream); + }); + + // Validate backtest configuration + app.post('/validate', async c => { + try { + const body = await c.req.json(); + const config = BacktestConfigSchema.parse(body); + + // Additional validation logic + const validation = { + valid: true, + warnings: [] as string[], + estimatedDuration: 0, + }; + + // Check data availability + const startDate = new Date(config.startDate); + const endDate = new Date(config.endDate); + const days = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24); + + if (days > 365) { + validation.warnings.push('Large date range may take significant time to process'); + } + + if (config.symbols.length > 100) { + validation.warnings.push('Large number of symbols may impact performance'); + } + + // Estimate duration (simplified) + validation.estimatedDuration = days * config.symbols.length * 0.1; // seconds + + return c.json(validation); + } catch (error) { + if (error instanceof z.ZodError) { + return c.json( + { + valid: false, + error: 'Invalid configuration', + details: error.errors, + }, + 400 + ); + } + + return c.json( + { + valid: false, + error: error instanceof Error ? error.message : 'Validation failed', + }, + 500 + ); + } + }); + + return app; +} diff --git a/apps/stock/orchestrator/src/api/rest/orders.ts b/apps/stock/orchestrator/src/api/rest/orders.ts index 43a3da3d..565f1f23 100644 --- a/apps/stock/orchestrator/src/api/rest/orders.ts +++ b/apps/stock/orchestrator/src/api/rest/orders.ts @@ -1,111 +1,129 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { IServiceContainer } from '@stock-bot/di'; -import { OrderRequestSchema } from '../../types'; -import { ExecutionService } from '../../services/ExecutionService'; - -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.parse(body); - - const result = await executionService.submitOrder(orderRequest); - - return c.json(result, 201); - } catch (error) { - 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).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; -} \ No newline at end of file +import { Hono } from 'hono'; +import { z } from 'zod'; +import { ExecutionService } 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.parse(body); + + const result = await executionService.submitOrder(orderRequest); + + return c.json(result, 201); + } catch (error) { + 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).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/positions.ts b/apps/stock/orchestrator/src/api/rest/positions.ts index aef92265..ec092740 100644 --- a/apps/stock/orchestrator/src/api/rest/positions.ts +++ b/apps/stock/orchestrator/src/api/rest/positions.ts @@ -1,121 +1,139 @@ -import { Hono } from 'hono'; -import { z } from 'zod'; -import { IServiceContainer } from '@stock-bot/di'; -import { ModeManager } from '../../core/ModeManager'; - -const SymbolSchema = z.object({ - symbol: z.string() -}); - -export function createPositionRoutes(container: IServiceContainer): Hono { - const app = new Hono(); - const modeManager = container.custom?.ModeManager as ModeManager; - - // Get all positions - app.get('/', async (c) => { - try { - const tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getAllPositions()); - - 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 tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getOpenPositions()); - - 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 tradingEngine = modeManager.getTradingEngine(); - - const positionJson = tradingEngine.getPosition(symbol); - const position = positionJson ? JSON.parse(positionJson) : null; - - 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 tradingEngine = modeManager.getTradingEngine(); - const [realizedPnl, unrealizedPnl] = tradingEngine.getTotalPnl(); - - 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 tradingEngine = modeManager.getTradingEngine(); - const metrics = JSON.parse(tradingEngine.getRiskMetrics()); - - 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; -} \ No newline at end of file +import { Hono } from 'hono'; +import { z } from 'zod'; +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 modeManager = container.custom?.ModeManager as ModeManager; + + // Get all positions + app.get('/', async c => { + try { + const tradingEngine = modeManager.getTradingEngine(); + const positions = JSON.parse(tradingEngine.getAllPositions()); + + 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 tradingEngine = modeManager.getTradingEngine(); + const positions = JSON.parse(tradingEngine.getOpenPositions()); + + 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 tradingEngine = modeManager.getTradingEngine(); + + const positionJson = tradingEngine.getPosition(symbol); + const position = positionJson ? JSON.parse(positionJson) : null; + + 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 tradingEngine = modeManager.getTradingEngine(); + const [realizedPnl = 0, unrealizedPnl = 0] = tradingEngine.getTotalPnl(); + + 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 tradingEngine = modeManager.getTradingEngine(); + const metrics = JSON.parse(tradingEngine.getRiskMetrics()); + + 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 index 96ee2245..80d037c7 100644 --- a/apps/stock/orchestrator/src/api/websocket/index.ts +++ b/apps/stock/orchestrator/src/api/websocket/index.ts @@ -1,194 +1,195 @@ -import { Server as SocketIOServer, Socket } from 'socket.io'; -import { z } from 'zod'; -import { IServiceContainer } from '@stock-bot/di'; -import { MarketDataService } from '../../services/MarketDataService'; -import { ExecutionService } from '../../services/ExecutionService'; -import { ModeManager } from '../../core/ModeManager'; - -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: any, callback?: Function) => { - try { - const { symbols, dataTypes } = SubscribeSchema.parse(data); - const subscriptions = 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: any, callback?: Function) => { - try { - const { symbols } = UnsubscribeSchema.parse(data); - const subscriptions = 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: any, callback?: Function) => { - try { - const result = await executionService.submitOrder(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 tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getAllPositions()); - - 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('marketData', (data: any) => { - 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: any) => { - io.emit('orderUpdate', update); - }); - - // Forward fills to all clients - executionService.on('fill', (fill: any) => { - io.emit('fill', fill); - }); - - // Mode change notifications - modeManager.on('modeChanged', (config: any) => { - io.emit('modeChanged', { - mode: config.mode, - timestamp: new Date().toISOString() - }); - }); - - container.logger.info('WebSocket handlers initialized'); -} \ No newline at end of file +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 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(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 tradingEngine = modeManager.getTradingEngine(); + const positions = JSON.parse(tradingEngine.getAllPositions()); + + 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('marketData', data => { + 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 index 8a478b90..7d957271 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -1,1329 +1,1454 @@ -import { EventEmitter } from 'events'; -import { IServiceContainer } from '@stock-bot/di'; -import { PerformanceAnalyzer } from '../analytics/PerformanceAnalyzer'; -import { DataManager } from '../data/DataManager'; -import { StorageService } from '../services/StorageService'; -import { StrategyManager } from '../strategies/StrategyManager'; -import { BacktestConfigSchema, MarketData, MarketMicrostructure, PerformanceMetrics } from '../types'; -import { MarketSimulator } from './MarketSimulator'; - -interface BacktestEvent { - timestamp: number; - type: 'market_data' | 'strategy_signal' | 'order_fill'; - data: any; -} - -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; - maxDrawdown: number; - winRate: number; - totalTrades: number; - profitFactor: number; - profitableTrades: number; - avgWin: number; - avgLoss: number; - expectancy: number; - calmarRatio: number; - sortinoRatio: number; - }; - - // 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; - }; -} - -export class BacktestEngine extends EventEmitter { - private eventQueue: BacktestEvent[] = []; - private currentTime: number = 0; - private equityCurve: { timestamp: number; value: number }[] = []; - private isRunning = false; - private isPaused = false; - private speedMultiplier: number | null = 1; // null means unlimited speed - private lastProcessTime = 0; - private dataManager: DataManager; - private marketSimulator: MarketSimulator; - private performanceAnalyzer!: PerformanceAnalyzer; - private microstructures: Map = new Map(); - private container: IServiceContainer; - private runId: string | null = null; - private progressUpdateInterval = 100; // Update progress every 100 events - private totalEvents = 0; - private initialCapital: number = 100000; - private commission: number = 0.001; // Default 0.1% - private slippage: number = 0.0001; // Default 0.01% - private pendingOrders: Map = new Map(); - private ordersListenerSetup = false; - - constructor( - container: IServiceContainer, - private storageService: StorageService, - private strategyManager: StrategyManager - ) { - super(); - this.container = container; - this.dataManager = new DataManager(storageService); - this.marketSimulator = new MarketSimulator({ - useHistoricalSpreads: true, - modelHiddenLiquidity: true, - includeDarkPools: true, - latencyMs: 1 - }); - // Don't create performance analyzer here - wait for runBacktest - // this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); - - // Set up order listener immediately - this.setupOrderListener(); - } - - async runBacktest(config: any): Promise { - // Validate config - const validatedConfig = BacktestConfigSchema.parse(config); - - this.container.logger.info(`Starting backtest from ${validatedConfig.startDate} to ${validatedConfig.endDate}`); - - // Reset state - this.reset(); - this.isRunning = true; - this.initialCapital = validatedConfig.initialCapital; - this.commission = validatedConfig.commission ?? 0.001; - this.slippage = validatedConfig.slippage ?? 0.0001; - - // Recreate performance analyzer with correct initial capital - this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); - - // Initialize equity curve with starting capital - this.equityCurve.push({ - timestamp: new Date(validatedConfig.startDate).getTime(), - value: this.initialCapital - }); - - // Initialize performance analyzer with starting capital - this.performanceAnalyzer.addEquityPoint( - new Date(validatedConfig.startDate), - this.initialCapital - ); - - this.container.logger.info(`[BacktestEngine] Initial capital set to ${this.initialCapital}, equity curve initialized with ${this.equityCurve.length} points`); - - // Generate backtest ID and store runId if provided - const backtestId = `backtest_${Date.now()}`; - this.runId = config.runId || null; - - // Set speed multiplier from config - if (validatedConfig.speed) { - switch (validatedConfig.speed) { - case 'max': - this.speedMultiplier = null; // Unlimited speed - break; - case 'realtime': - this.speedMultiplier = 1; - break; - case '2x': - this.speedMultiplier = 2; - break; - case '5x': - this.speedMultiplier = 5; - break; - case '10x': - this.speedMultiplier = 10; - break; - default: - this.speedMultiplier = null; // Default to max speed - } - this.container.logger.info(`[BacktestEngine] Speed set to: ${validatedConfig.speed} (multiplier: ${this.speedMultiplier})`); - } - - try { - // Load historical data with multi-resolution support - const dataMap = await this.dataManager.loadHistoricalData( - validatedConfig.symbols, - new Date(validatedConfig.startDate), - new Date(validatedConfig.endDate), - validatedConfig.dataFrequency, - true // Include extended hours - ); - - // Load market microstructure for each symbol - await this.loadMarketMicrostructure(validatedConfig.symbols); - - // Convert to flat array and sort by time - const marketData: MarketData[] = []; - dataMap.forEach((data, symbol) => { - marketData.push(...data); - }); - marketData.sort((a, b) => a.data.timestamp - b.data.timestamp); - - this.container.logger.info(`Loaded ${marketData.length} market data points`); - - // Initialize strategies - const strategies = validatedConfig.strategies || [{ - id: `${validatedConfig.strategy}-${Date.now()}`, - name: validatedConfig.strategy, - enabled: true, - parameters: { - symbols: validatedConfig.symbols, - initialCapital: validatedConfig.initialCapital, - // Add any default strategy parameters here - }, - symbols: validatedConfig.symbols, - allocation: 1.0 // Use 100% of capital - }]; - - await this.strategyManager.initializeStrategies(strategies); - this.container.logger.info(`Initialized ${strategies.length} strategies`); - - // Don't setup strategy order listeners - we already listen to StrategyManager - // this.setupStrategyOrderListeners(); - - // Convert market data to events - this.populateEventQueue(marketData); - - // Main backtest loop - await this.processEvents(); - - // Get trade history from Rust core - const tradingEngine = this.strategyManager.getTradingEngine(); - let closedTrades: any[] = []; - let tradeCount = 0; - if (tradingEngine) { - if (tradingEngine.getClosedTrades) { - try { - const tradesJson = tradingEngine.getClosedTrades(); - closedTrades = JSON.parse(tradesJson); - this.container.logger.info(`Retrieved ${closedTrades.length} closed trades from Rust core`); - } catch (error) { - this.container.logger.warn('Failed to get closed trades from Rust core:', error); - } - } - if (tradingEngine.getTradeCount) { - try { - tradeCount = tradingEngine.getTradeCount(); - this.container.logger.info(`Total trades executed: ${tradeCount}`); - } catch (error) { - this.container.logger.warn('Failed to get trade count from Rust core:', error); - } - } - } - - // Calculate final metrics - const performance = this.calculatePerformance(closedTrades); - - // Get final positions - const finalPositions = await this.getFinalPositions(); - - // Create comprehensive frontend-ready result - const result: BacktestResult = { - // Identification - backtestId, - status: 'completed' as const, - completedAt: new Date().toISOString(), - - // Configuration used - config: { - name: validatedConfig.name || 'Backtest', - strategy: validatedConfig.strategy, - symbols: validatedConfig.symbols, - startDate: validatedConfig.startDate, - endDate: validatedConfig.endDate, - initialCapital: validatedConfig.initialCapital, - commission: validatedConfig.commission || 0, - slippage: validatedConfig.slippage || 0, - dataFrequency: validatedConfig.dataFrequency || '1d' - }, - - // Performance metrics (frontend-ready) - metrics: { - totalReturn: performance.totalReturn, - sharpeRatio: performance.sharpeRatio, - maxDrawdown: performance.maxDrawdown, - winRate: performance.winRate, - totalTrades: tradeCount || performance.totalTrades, - profitFactor: performance.profitFactor || 0, - profitableTrades: Math.round(performance.totalTrades * performance.winRate / 100), - avgWin: performance.avgWin || 0, - avgLoss: performance.avgLoss || 0, - expectancy: performance.expectancy || 0, - calmarRatio: performance.calmarRatio || 0, - sortinoRatio: performance.sortinoRatio || 0 - }, - - // Chart data (frontend-ready format) - equity: this.equityCurve - .sort((a, b) => a.timestamp - b.timestamp) - .map(point => ({ - date: new Date(point.timestamp).toISOString(), - value: point.value - })), - - // OHLC data for charts - ohlcData: this.getOHLCData(marketData, validatedConfig.symbols), - - // 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.avgPrice, - currentPrice: pos.currentPrice || pos.avgPrice, - unrealizedPnl: pos.unrealizedPnl || 0, - realizedPnl: pos.realizedPnl || 0 - })), - - // Additional analytics - analytics: { - drawdownSeries: this.calculateDrawdown(), - dailyReturns: this.calculateDailyReturns(), - monthlyReturns: this.calculateMonthlyReturns(), - exposureTime: this.calculateExposureTime(closedTrades), - riskMetrics: this.calculateRiskMetrics(closedTrades) - } - }; - - await this.storeResults(result); - - this.container.logger.info(`Backtest completed: ${performance.totalTrades} trades, ${performance.totalReturn}% return`); - - return result; - - } catch (error) { - this.container.logger.error('Backtest failed:', error); - throw error; - } finally { - this.isRunning = false; - this.reset(); - } - } - - private async loadHistoricalData(config: any): Promise { - const data: MarketData[] = []; - const startDate = new Date(config.startDate); - const endDate = new Date(config.endDate); - - try { - for (const symbol of config.symbols) { - const bars = await this.storageService.getHistoricalBars( - symbol, - startDate, - endDate, - config.dataFrequency - ); - - // If no data found, use mock data - if (!bars || bars.length === 0) { - this.container.logger.warn(`No historical data found for ${symbol}, using mock data`); - - // Tell the Rust core to generate mock data - const tradingEngine = this.strategyManager.getTradingEngine(); - if (tradingEngine && tradingEngine.generateMockData) { - await tradingEngine.generateMockData( - symbol, - startDate.getTime(), - endDate.getTime(), - 42 // seed for reproducibility - ); - - // For now, we'll generate mock data on the TypeScript side - // as the Rust integration needs more work - const mockData = this.generateMockData(symbol, startDate, endDate); - data.push(...mockData); - } else { - // Fallback to TypeScript mock data generation - const mockData = this.generateMockData(symbol, startDate, endDate); - data.push(...mockData); - } - } else { - // Convert to MarketData format - bars.forEach(bar => { - data.push({ - type: 'bar', - 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() - } - }); - }); - } - } - } catch (error) { - this.container.logger.warn('Error loading historical data, using mock data:', error); - - // Generate mock data for all symbols - for (const symbol of config.symbols) { - const mockData = this.generateMockData(symbol, startDate, endDate); - data.push(...mockData); - } - } - - // Sort by timestamp - data.sort((a, b) => { - const timeA = a.data.timestamp; - const timeB = b.data.timestamp; - return timeA - timeB; - }); - - return data; - } - - private generateMockData(symbol: string, startDate: Date, endDate: Date): MarketData[] { - const data: MarketData[] = []; - const startTime = startDate.getTime(); - const endTime = endDate.getTime(); - const interval = 24 * 60 * 60 * 1000; // 1 day in milliseconds - - let price = 100; // Base price - let currentTime = startTime; - let trend = 0; // Current trend direction - let trendStrength = 0; - let trendDuration = 0; - - while (currentTime <= endTime) { - // Every 10-30 days, change trend (more frequent for testing) - if (trendDuration <= 0) { - trend = Math.random() > 0.5 ? 1 : -1; - trendStrength = 0.003 + Math.random() * 0.005; // 0.3% to 0.8% daily trend - trendDuration = Math.floor(10 + Math.random() * 20); // Shorter trends - } - - // Generate price movement with trend and noise - const trendComponent = trend * trendStrength; - const noiseComponent = (Math.random() - 0.5) * 0.03; // +/- 1.5% noise - const changePercent = trendComponent + noiseComponent; - price = price * (1 + changePercent); - - // Generate OHLC with realistic intraday movement - const open = price * (1 + (Math.random() - 0.5) * 0.005); - const dayRange = 0.01 + Math.random() * 0.02; // 1-3% daily range - const high = Math.max(open, price) * (1 + Math.random() * dayRange); - const low = Math.min(open, price) * (1 - Math.random() * dayRange); - const close = low + Math.random() * (high - low); - const volume = Math.random() * 1000000 + 500000; - - trendDuration--; - - data.push({ - type: 'bar', - data: { - symbol, - open, - high, - low, - close, - volume, - vwap: (open + high + low + close) / 4, - timestamp: currentTime - } - }); - - currentTime += interval; - price = close; // Next bar opens at previous close - } - - return data; - } - - private populateEventQueue(marketData: MarketData[]): void { - // Convert market data to events - marketData.forEach(data => { - this.eventQueue.push({ - timestamp: data.data.timestamp, - type: 'market_data', - data - }); - }); - - // Sort by timestamp (should already be sorted) - this.eventQueue.sort((a, b) => a.timestamp - b.timestamp); - } - - private async processEvents(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - let lastEquityUpdate = 0; - const equityUpdateInterval = 60000; // Update equity every minute - - this.totalEvents = this.eventQueue.length; - this.container.logger.info(`[BacktestEngine] Processing ${this.totalEvents} events with speed multiplier: ${this.speedMultiplier}`); - - let processedCount = 0; - - while (this.eventQueue.length > 0 && this.isRunning) { - // Check if paused - if (this.isPaused) { - await new Promise(resolve => setTimeout(resolve, 100)); - continue; - } - - const event = this.eventQueue.shift()!; - processedCount++; - - // Apply speed control if not unlimited - if (this.speedMultiplier !== null && this.speedMultiplier > 0) { - // Base delay in milliseconds for processing each event - // For 1x speed: 1000ms per event (1 event per second) - // For 2x speed: 500ms per event (2 events per second) - // For 10x speed: 100ms per event (10 events per second) - const baseDelay = 1000; // milliseconds - const actualDelay = baseDelay / this.speedMultiplier; - - // Add the delay - if (actualDelay > 1) { - if (processedCount % 50 === 0) { // Log every 50 events to avoid spam - this.container.logger.debug(`[BacktestEngine] Applying delay: ${actualDelay}ms (speed: ${this.speedMultiplier}x)`); - } - await new Promise(resolve => setTimeout(resolve, actualDelay)); - } - - // Also send progress updates more frequently at slower speeds - if (processedCount % Math.max(1, Math.floor(10 / this.speedMultiplier)) === 0) { - const progress = Math.round((processedCount / this.totalEvents) * 100); - this.sendProgressUpdate(progress, new Date(event.timestamp).toISOString()); - } - } - - this.lastProcessTime = Date.now(); - - // Advance time - this.currentTime = event.timestamp; - if (tradingEngine) { - await tradingEngine.advanceTime(this.currentTime); - } - - // Process event based on type - switch (event.type) { - case 'market_data': - await this.processMarketData(event.data); - break; - - case 'strategy_signal': - await this.processStrategySignal(event.data); - break; - - case 'order_fill': - await this.processFill(event.data); - break; - } - - // Update equity curve periodically - if (this.currentTime - lastEquityUpdate > equityUpdateInterval) { - await this.updateEquityCurve(); - lastEquityUpdate = this.currentTime; - } - - // Send progress update via WebSocket (unless already sent in speed control) - if (this.speedMultiplier === null && processedCount % this.progressUpdateInterval === 0) { - const progress = Math.round((processedCount / this.totalEvents) * 100); - this.sendProgressUpdate(progress, new Date(this.currentTime).toISOString()); - - // Also emit local progress event - this.emit('progress', { - processed: processedCount, - total: this.totalEvents, - remaining: this.eventQueue.length, - currentTime: new Date(this.currentTime), - progress - }); - } - } - - // Final equity update - await this.updateEquityCurve(); - - // Send 100% progress - this.sendProgressUpdate(100, new Date(this.currentTime).toISOString()); - } - - private async processMarketData(data: MarketData): Promise { - this.container.logger.info(`[BacktestEngine] processMarketData called for ${data.data.symbol} @ ${data.data.close}`); - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) { - this.container.logger.warn(`[BacktestEngine] No trading engine available`); - return; - } - - // Process through market simulator for realistic orderbook - const orderbook = this.marketSimulator.processMarketData(data); - - if (orderbook) { - // Update trading engine with simulated orderbook - if (orderbook.bids.length > 0 && orderbook.asks.length > 0) { - tradingEngine.updateQuote( - orderbook.symbol, - orderbook.bids[0].price, - orderbook.asks[0].price, - orderbook.bids[0].size, - orderbook.asks[0].size - ); - } - - // Set microstructure in trading core for realistic fills - const microstructure = this.microstructures.get(orderbook.symbol); - if (microstructure && tradingEngine.setMicrostructure) { - tradingEngine.setMicrostructure(orderbook.symbol, microstructure); - } - } else { - // Fallback to simple processing - switch (data.type) { - case 'quote': - tradingEngine.updateQuote( - data.data.symbol, - data.data.bid, - data.data.ask, - data.data.bidSize, - data.data.askSize - ); - break; - - case 'trade': - tradingEngine.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; - - tradingEngine.updateQuote( - data.data.symbol, - data.data.close - halfSpread, - data.data.close + halfSpread, - data.data.volume / 100, - data.data.volume / 100 - ); - break; - } - } - - // Let strategies process the data - this.container.logger.info(`[BacktestEngine] Forwarding data to strategy manager for ${data.data.symbol}`); - await this.strategyManager.onMarketData(data); - - // Check for any pending orders that should be filled - await this.checkAndFillOrders(data); - - // Track performance - this.performanceAnalyzer.addEquityPoint( - new Date(this.currentTime), - await this.getPortfolioValue() - ); - } - - private async processStrategySignal(signal: any): Promise { - // Strategy signals are handled by strategy manager - // This is here for future extensions - } - - private async processFill(fill: any): Promise { - this.container.logger.info(`[BacktestEngine] Processing fill: ${fill.side} ${fill.quantity} ${fill.symbol} @ ${fill.price} with timestamp ${fill.timestamp}`); - - // Process fill in trading engine for position tracking - const tradingEngine = this.strategyManager.getTradingEngine(); - if (tradingEngine) { - this.container.logger.info(`[BacktestEngine] Trading engine available, processing fill`); - this.container.logger.info(`[BacktestEngine] Current time in trading engine before advance: ${tradingEngine.getCurrentTime()}`); - - // Make sure time is properly advanced - if (fill.timestamp) { - await tradingEngine.advanceTime(fill.timestamp); - this.container.logger.info(`[BacktestEngine] Advanced trading engine time to ${fill.timestamp}, current time now: ${tradingEngine.getCurrentTime()}`); - } - - // Use the new process_fill_with_metadata method if available - if (tradingEngine.processFillWithMetadata) { - const fillResult = await tradingEngine.processFillWithMetadata( - fill.symbol, - fill.price, - fill.quantity, - fill.side, - fill.commission || 0, - fill.orderId || null, - fill.strategyId || null - ); - this.container.logger.debug('Fill processed with tracking:', fillResult); - } else { - // Fallback to old method - const fillResult = await tradingEngine.processFill( - fill.symbol, - fill.price, - fill.quantity, - fill.side, - fill.commission || 0 - ); - this.container.logger.debug('Fill processed:', fillResult); - } - } else { - this.container.logger.warn(`[BacktestEngine] No trading engine available to process fill!`); - } - - // Notify strategies of fill - const strategy = fill.strategyId ? this.strategyManager.getStrategy(fill.strategyId) : null; - if (strategy) { - await strategy.onOrderUpdate({ - orderId: fill.orderId, - symbol: fill.symbol, - side: fill.side, - status: 'filled', - fills: [fill] - }); - } - - // Store in database - await this.storageService.storeFill(fill); - } - - private async updateEquityCurve(): Promise { - const totalEquity = await this.getPortfolioValue(); - - this.container.logger.debug(`[updateEquityCurve] currentTime=${this.currentTime}, totalEquity=${totalEquity}, initialCapital=${this.initialCapital}`); - - // Don't add duplicate points at the same timestamp - const lastPoint = this.equityCurve[this.equityCurve.length - 1]; - if (lastPoint && lastPoint.timestamp === this.currentTime) { - // Update the value instead of adding a duplicate - this.container.logger.debug(`[updateEquityCurve] Updating existing point at ${this.currentTime}: ${lastPoint.value} -> ${totalEquity}`); - lastPoint.value = totalEquity; - } else { - this.container.logger.debug(`[updateEquityCurve] Adding new point at ${this.currentTime}: ${totalEquity}`); - this.equityCurve.push({ - timestamp: this.currentTime, - value: totalEquity - }); - } - } - - private async getPortfolioValue(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) { - this.container.logger.debug(`[getPortfolioValue] No trading engine, returning initialCapital: ${this.initialCapital}`); - return this.initialCapital; - } - - try { - // Get current P&L - const [realized, unrealized] = tradingEngine.getTotalPnl(); - const totalValue = this.initialCapital + realized + unrealized; - - this.container.logger.debug(`[getPortfolioValue] P&L: realized=${realized}, unrealized=${unrealized}, initialCapital=${this.initialCapital}, totalValue=${totalValue}`); - - // Ensure we never return 0 or negative values that would cause spikes - // This handles the case where getTotalPnl might not be initialized yet - if (totalValue <= 0 || isNaN(totalValue)) { - this.container.logger.debug(`[getPortfolioValue] Invalid totalValue, returning initialCapital: ${this.initialCapital}`); - return this.initialCapital; - } - - return totalValue; - } catch (error) { - // If getTotalPnl fails, return initial capital - this.container.logger.warn('Failed to get total P&L, using initial capital:', error); - return this.initialCapital; - } - } - - private calculatePerformance(closedTrades: any[] = []): PerformanceMetrics { - // Use sophisticated performance analyzer - // Add closed trades from Rust core - closedTrades.forEach(trade => { - this.performanceAnalyzer.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 - }); - }); - - const metrics = this.performanceAnalyzer.analyze(); - - // Add drawdown analysis - const drawdownAnalysis = this.performanceAnalyzer.analyzeDrawdowns(); - - return { - ...metrics, - maxDrawdown: drawdownAnalysis.maxDrawdown, - maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration - }; - } - - private sendProgressUpdate(progress: number, currentDate: string): void { - if (!this.runId) return; - - try { - // Try to send WebSocket update to web-api - const url = `http://localhost:2003/api/runs/${this.runId}/progress`; - fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ progress, currentDate }) - }).catch(err => { - // Ignore errors - WebSocket updates are best-effort - this.container.logger.debug('Failed to send progress update:', err); - }); - } catch (error) { - // Ignore errors - } - } - - private calculateDrawdown(): { timestamp: number; value: number }[] { - const drawdowns: { timestamp: number; value: number }[] = []; - let peak = this.equityCurve[0]?.value || 0; - - for (const point of this.equityCurve) { - if (point.value > peak) { - peak = point.value; - } - const drawdown = ((point.value - peak) / peak) * 100; - drawdowns.push({ - timestamp: point.timestamp, - value: drawdown - }); - } - - return drawdowns; - } - - private calculateMonthlyReturns(): Record { - const monthlyReturns: Record = {}; - const monthlyEquity = new Map(); - - for (const point of this.equityCurve) { - const date = new Date(point.timestamp); - const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; - - if (!monthlyEquity.has(monthKey)) { - monthlyEquity.set(monthKey, { start: point.value, end: point.value }); - } else { - const month = monthlyEquity.get(monthKey)!; - month.end = point.value; - } - } - - for (const [month, values] of monthlyEquity) { - monthlyReturns[month] = ((values.end - values.start) / values.start) * 100; - } - - return monthlyReturns; - } - - private calculateExposureTime(closedTrades: any[] = []): 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 ? this.equityCurve[0].timestamp : 0; - const endTime = this.equityCurve.length > 0 ? this.equityCurve[this.equityCurve.length - 1].timestamp : 0; - const totalTime = endTime - startTime; - - return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0; - } - - private calculateRiskMetrics(closedTrades: any[] = []): Record { - const returns = this.calculateDailyReturns(); - - // Calculate various risk metrics - const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length; - const variance = returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - // Downside deviation (for Sortino) - const downsideReturns = returns.filter(r => r < 0); - const downsideVariance = downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) / downsideReturns.length; - const downsideDeviation = Math.sqrt(downsideVariance); - - return { - volatility: stdDev * Math.sqrt(252), // Annualized - downsideDeviation: downsideDeviation * Math.sqrt(252), - var95: this.calculateVaR(returns, 0.95), - var99: this.calculateVaR(returns, 0.99), - cvar95: this.calculateCVaR(returns, 0.95), - maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades) - }; - } - - private calculateVaR(returns: number[], confidence: number): number { - const sorted = [...returns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sorted.length); - return sorted[index] || 0; - } - - private calculateCVaR(returns: number[], confidence: number): number { - const sorted = [...returns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sorted.length); - const tail = sorted.slice(0, index + 1); - return tail.reduce((a, b) => a + b, 0) / tail.length; - } - - private calculateMaxConsecutiveLosses(closedTrades: any[] = []): number { - let maxLosses = 0; - let currentLosses = 0; - - for (const trade of closedTrades) { - if (trade.pnl && trade.pnl < 0) { - currentLosses++; - maxLosses = Math.max(maxLosses, currentLosses); - } else { - currentLosses = 0; - } - } - - return maxLosses; - } - - private calculateDailyReturns(): number[] { - const dailyReturns: number[] = []; - const dailyEquity = new Map(); - - // Group equity by day - for (const point of this.equityCurve) { - const date = new Date(point.timestamp).toDateString(); - dailyEquity.set(date, point.value); - } - - // Calculate returns - const dates = Array.from(dailyEquity.keys()).sort(); - for (let i = 1; i < dates.length; i++) { - const prevValue = dailyEquity.get(dates[i - 1])!; - const currValue = dailyEquity.get(dates[i])!; - const dailyReturn = ((currValue - prevValue) / prevValue) * 100; - dailyReturns.push(dailyReturn); - } - - return dailyReturns; - } - - private async getFinalPositions(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) {return [];} - - const positions = JSON.parse(tradingEngine.getOpenPositions()); - return positions; - } - - private async storeResults(result: BacktestResult): Promise { - // Store performance metrics - await this.storageService.storeStrategyPerformance( - result.id, - result.performance - ); - - // Could also store detailed results in a separate table or file - this.container.logger.debug(`Backtest results stored with ID: ${result.id}`); - } - - private reset(): void { - this.eventQueue = []; - this.currentTime = 0; - this.equityCurve = []; - this.pendingOrders.clear(); - this.ordersListenerSetup = false; - this.isPaused = false; - this.speedMultiplier = 1; - this.lastProcessTime = 0; - this.marketSimulator.reset(); - } - - private async loadMarketMicrostructure(symbols: string[]): Promise { - // 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: 2 + Math.random() * 3, // 2-5 bps - dailyVolume: 10_000_000 * (1 + Math.random() * 9), // 10-100M shares - avgTradeSize: 100 + Math.random() * 400, // 100-500 shares - volatility: 0.15 + Math.random() * 0.25, // 15-40% annual vol - tickSize: 0.01, - lotSize: 1, - intradayVolumeProfile: this.generateIntradayProfile() - }; - - this.microstructures.set(symbol, microstructure); - this.marketSimulator.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); - } - - - async stopBacktest(): Promise { - this.isRunning = false; - this.container.logger.info('Backtest stop requested'); - } - - async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise { - // Get trades from Rust core - const tradingEngine = this.strategyManager.getTradingEngine(); - let closedTrades: any[] = []; - if (tradingEngine && tradingEngine.getClosedTrades) { - try { - const tradesJson = tradingEngine.getClosedTrades(); - closedTrades = JSON.parse(tradesJson); - } catch (error) { - this.container.logger.warn('Failed to get closed trades for export:', error); - } - } - - const result = { - summary: this.calculatePerformance(closedTrades), - trades: closedTrades, - equityCurve: this.equityCurve, - drawdowns: this.calculateDrawdown(), - dataQuality: this.dataManager.getDataQualityReport(), - performanceReport: this.performanceAnalyzer.exportReport() - }; - - switch (format) { - case 'json': - return JSON.stringify(result, null, 2); - case 'csv': - // Convert to CSV format - return this.convertToCSV(result); - case 'html': - // Generate HTML report - return this.generateHTMLReport(result); - default: - return JSON.stringify(result); - } - } - - private convertToCSV(result: any): string { - // Simple CSV conversion for trades - const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%']; - const rows = result.trades.map(t => [ - new Date(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.join(',')).join('\n'); - } - - private generateHTMLReport(result: any): string { - return ` - - - - Backtest Report - - - -

Backtest Performance Report

- -

Summary Statistics

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

Detailed Performance Metrics

-
${result.performanceReport}
- -

Trade History

- - - - - - - - - - - - ${result.trades.map(t => ` - - - - - - - - - - - `).join('')} -
DateSymbolSideEntry PriceExit PriceQuantityP&LReturn %
${new Date(t.entryTime).toLocaleDateString()}${t.symbol}${t.side}$${t.entryPrice.toFixed(2)}$${t.exitPrice.toFixed(2)}${t.quantity}$${t.pnl.toFixed(2)}${t.returnPct.toFixed(2)}%
- - - `; - } - - private getOHLCData(marketData: MarketData[], symbols: string[]): Record { - const ohlcData: Record = {}; - - symbols.forEach(symbol => { - const symbolData = marketData - .filter(d => d.type === 'bar' && d.data.symbol === symbol) - .map(d => ({ - time: Math.floor(d.data.timestamp / 1000), // Convert to seconds for lightweight-charts - open: d.data.open, - high: d.data.high, - low: d.data.low, - close: d.data.close, - volume: d.data.volume - })) - .sort((a, b) => a.time - b.time); // Ensure data is sorted by time - - ohlcData[symbol] = symbolData; - }); - - return ohlcData; - } - - private setupOrderListener(): void { - if (this.ordersListenerSetup) return; - - // Listen for orders from strategy manager - this.strategyManager.on('order', async (orderEvent: any) => { - this.container.logger.info('[BacktestEngine] Order from StrategyManager:', orderEvent); - this.pendingOrders.set(orderEvent.orderId, { - ...orderEvent, - timestamp: this.currentTime - }); - }); - - this.ordersListenerSetup = true; - } - - private setupStrategyOrderListeners(): void { - // Listen for orders directly from strategies - const strategies = this.strategyManager.getAllStrategies(); - this.container.logger.info(`Setting up order listeners for ${strategies.length} strategies`); - - strategies.forEach(strategy => { - this.container.logger.info(`Setting up order listener for strategy: ${strategy.config.id}`); - - const orderHandler = async (order: any) => { - const orderId = `${strategy.config.id}-${Date.now()}-${Math.random()}`; - this.container.logger.info(`[BacktestEngine] 🔔 Order from strategy ${strategy.config.id}:`, order); - this.container.logger.info(`[BacktestEngine] Adding order ${orderId} to pendingOrders. Current size: ${this.pendingOrders.size}`); - this.pendingOrders.set(orderId, { - strategyId: strategy.config.id, - orderId, - order, - timestamp: this.currentTime - }); - this.container.logger.info(`[BacktestEngine] After adding, pendingOrders size: ${this.pendingOrders.size}`); - }; - - strategy.on('order', orderHandler); - - // Also listen for signals - strategy.on('signal', (signal: any) => { - this.container.logger.info(`[BacktestEngine] 📊 Signal from strategy ${strategy.config.id}:`, signal); - }); - }); - } - - private async checkAndFillOrders(data: MarketData): Promise { - if (data.type !== 'bar') return; - - const symbol = data.data.symbol; - const currentPrice = data.data.close; - - // Check pending orders for this symbol - const ordersToFill: string[] = []; - - this.container.logger.info(`[checkAndFillOrders] Checking ${this.pendingOrders.size} pending orders for ${symbol}`); - - for (const [orderId, orderEvent] of this.pendingOrders) { - if (orderEvent.order.symbol === symbol) { - // For market orders, fill immediately at current price - if (orderEvent.order.orderType === 'market') { - this.container.logger.info(`[checkAndFillOrders] Found market order ${orderId} for ${symbol}`); - ordersToFill.push(orderId); - } - } - } - - // Process fills - for (const orderId of ordersToFill) { - const orderEvent = this.pendingOrders.get(orderId); - if (!orderEvent) continue; - - const fillPrice = orderEvent.order.side === 'buy' ? - currentPrice * (1 + this.slippage) : - currentPrice * (1 - this.slippage); - - const fill = { - orderId, - symbol: orderEvent.order.symbol, - side: orderEvent.order.side, - quantity: orderEvent.order.quantity, - price: fillPrice, - timestamp: this.currentTime, - commission: orderEvent.order.quantity * fillPrice * this.commission, - strategyId: orderEvent.strategyId - }; - - this.container.logger.info(`✅ Filling ${orderEvent.order.side} order for ${symbol} @ ${fillPrice} at timestamp ${this.currentTime} (${new Date(this.currentTime).toISOString()})`); - - // Remove from pending BEFORE processing to avoid duplicate fills - this.pendingOrders.delete(orderId); - - // Process the fill (this will update trading engine AND notify strategies) - await this.processFill(fill); - } - } - - // Playback control methods - async pauseBacktest(): Promise { - this.isPaused = true; - this.container.logger.info('Backtest paused'); - } - - async resumeBacktest(): Promise { - this.isPaused = false; - this.container.logger.info('Backtest resumed'); - } - - async stopBacktest(): Promise { - this.isRunning = false; - this.isPaused = false; - } - - setSpeedMultiplier(speed: number | null): void { - this.speedMultiplier = speed; - this.container.logger.info(`Backtest speed multiplier set to: ${speed === null ? 'unlimited' : speed}`); - } - - getStatus(): { isRunning: boolean; isPaused: boolean; progress: number; currentTime: number } { - const progress = this.totalEvents > 0 - ? Math.round(((this.totalEvents - this.eventQueue.length) / this.totalEvents) * 100) - : 0; - - return { - isRunning: this.isRunning, - isPaused: this.isPaused, - progress, - currentTime: this.currentTime - }; - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { defined } from '@stock-bot/invariants'; +import { at } from '@stock-bot/utils'; +import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; +import { DataManager } from '../data/DataManager'; +import type { StrategyFill } from '../services/ExecutionService'; +import { StorageService } from '../services/StorageService'; +import type { Signal } from '../strategies/BaseStrategy'; +import { StrategyManager } from '../strategies/StrategyManager'; +import type { + BacktestConfig, + OrchestratorServices as IServiceContainer, + OrderRequest, +} from '../types'; +import { BacktestConfigSchema, type MarketData, type MarketMicrostructure } from '../types'; +import { MarketSimulator } from './MarketSimulator'; +import { closedTradesSchema, openPositionsSchema, type ClosedTrade } from './native-result'; + +type BacktestEvent = { timestamp: number } & ( + | { type: 'market_data'; data: MarketData } + | { type: 'strategy_signal'; data: Signal } + | { type: 'order_fill'; data: StrategyFill } +); +interface PendingOrder { + strategyId: string; + orderId: string; + order: OrderRequest; + timestamp: number; +} +interface OHLCBar { + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; +} +interface ExportResult { + summary: PerformanceMetrics; + trades: ClosedTrade[]; + performanceReport: string; +} + +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; + maxDrawdown: number; + winRate: number; + totalTrades: number; + profitFactor: number; + profitableTrades: number; + avgWin: number; + avgLoss: number; + expectancy: number; + calmarRatio: number; + sortinoRatio: number; + }; + + // 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; + }; +} + +export class BacktestEngine extends EventEmitter { + private eventQueue: BacktestEvent[] = []; + private currentTime: number = 0; + private equityCurve: { timestamp: number; value: number }[] = []; + private isRunning = false; + private isPaused = false; + private speedMultiplier: number | null = 1; // null means unlimited speed + private lastProcessTime = 0; + private dataManager: DataManager; + private marketSimulator: MarketSimulator; + private performanceAnalyzer!: PerformanceAnalyzer; + private microstructures: Map = new Map(); + private container: IServiceContainer; + private runId: string | null = null; + private progressUpdateInterval = 100; // Update progress every 100 events + private totalEvents = 0; + private initialCapital: number = 100000; + private commission: number = 0.001; // Default 0.1% + private slippage: number = 0.0001; // Default 0.01% + private pendingOrders: Map = new Map(); + private ordersListenerSetup = false; + + constructor( + container: IServiceContainer, + private storageService: StorageService, + private strategyManager: StrategyManager + ) { + super(); + this.container = container; + this.dataManager = new DataManager(storageService); + this.marketSimulator = new MarketSimulator({ + useHistoricalSpreads: true, + modelHiddenLiquidity: true, + includeDarkPools: true, + latencyMs: 1, + }); + // Don't create performance analyzer here - wait for runBacktest + // this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); + + // Set up order listener immediately + this.setupOrderListener(); + } + + async runBacktest(config: unknown): Promise { + // Validate config + const validatedConfig = BacktestConfigSchema.parse(config); + + this.container.logger.info( + `Starting backtest from ${validatedConfig.startDate} to ${validatedConfig.endDate}` + ); + + // Reset state + this.reset(); + this.isRunning = true; + this.initialCapital = validatedConfig.initialCapital; + this.commission = validatedConfig.commission ?? 0.001; + this.slippage = validatedConfig.slippage ?? 0.0001; + + // Recreate performance analyzer with correct initial capital + this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); + + // Initialize equity curve with starting capital + this.equityCurve.push({ + timestamp: new Date(validatedConfig.startDate).getTime(), + value: this.initialCapital, + }); + + // Initialize performance analyzer with starting capital + this.performanceAnalyzer.addEquityPoint( + new Date(validatedConfig.startDate), + this.initialCapital + ); + + this.container.logger.info( + `[BacktestEngine] Initial capital set to ${this.initialCapital}, equity curve initialized with ${this.equityCurve.length} points` + ); + + // Generate backtest ID and store runId if provided + const backtestId = `backtest_${Date.now()}`; + this.runId = validatedConfig.runId || null; + + // Set speed multiplier from config + if (validatedConfig.speed) { + switch (validatedConfig.speed) { + case 'max': + this.speedMultiplier = null; // Unlimited speed + break; + case 'realtime': + this.speedMultiplier = 1; + break; + case '2x': + this.speedMultiplier = 2; + break; + case '5x': + this.speedMultiplier = 5; + break; + case '10x': + this.speedMultiplier = 10; + break; + default: + this.speedMultiplier = null; // Default to max speed + } + this.container.logger.info( + `[BacktestEngine] Speed set to: ${validatedConfig.speed} (multiplier: ${this.speedMultiplier})` + ); + } + + try { + // Load historical data with multi-resolution support + const dataMap = await this.dataManager.loadHistoricalData( + validatedConfig.symbols, + new Date(validatedConfig.startDate), + new Date(validatedConfig.endDate), + validatedConfig.dataFrequency, + true // Include extended hours + ); + + // Load market microstructure for each symbol + await this.loadMarketMicrostructure(validatedConfig.symbols); + + // Convert to flat array and sort by time + const marketData: MarketData[] = []; + dataMap.forEach((data, _symbol) => { + marketData.push(...data); + }); + marketData.sort((a, b) => a.data.timestamp - b.data.timestamp); + + this.container.logger.info(`Loaded ${marketData.length} market data points`); + + // Initialize strategies + const strategies = validatedConfig.strategies?.map((strategy, index) => ({ + id: `${strategy.name}-${index}`, + name: strategy.name, + enabled: strategy.enabled, + parameters: { ...strategy.config, initialCapital: validatedConfig.initialCapital }, + symbols: validatedConfig.symbols, + allocation: 1 / (validatedConfig.strategies?.length ?? 1), + })) || [ + { + id: `${validatedConfig.strategy}-${Date.now()}`, + name: validatedConfig.strategy, + enabled: true, + parameters: { + symbols: validatedConfig.symbols, + initialCapital: validatedConfig.initialCapital, + // Add any default strategy parameters here + }, + symbols: validatedConfig.symbols, + allocation: 1.0, // Use 100% of capital + }, + ]; + + await this.strategyManager.initializeStrategies(strategies); + this.container.logger.info(`Initialized ${strategies.length} strategies`); + + // Don't setup strategy order listeners - we already listen to StrategyManager + // this.setupStrategyOrderListeners(); + + // Convert market data to events + this.populateEventQueue(marketData); + + // Main backtest loop + await this.processEvents(); + + // Get trade history from Rust core + const tradingEngine = this.strategyManager.getTradingEngine(); + let closedTrades: ClosedTrade[] = []; + let tradeCount = 0; + if (tradingEngine) { + if (tradingEngine.getClosedTrades) { + try { + const tradesJson = tradingEngine.getClosedTrades(); + closedTrades = closedTradesSchema.parse(JSON.parse(tradesJson)); + this.container.logger.info( + `Retrieved ${closedTrades.length} closed trades from Rust core` + ); + } catch (error) { + this.container.logger.warn('Failed to get closed trades from Rust core:', { + value: error, + }); + } + } + if (tradingEngine.getTradeCount) { + try { + tradeCount = tradingEngine.getTradeCount(); + this.container.logger.info(`Total trades executed: ${tradeCount}`); + } catch (error) { + this.container.logger.warn('Failed to get trade count from Rust core:', { + value: error, + }); + } + } + } + + // Calculate final metrics + const performance = this.calculatePerformance(closedTrades); + + // Get final positions + const finalPositions = await this.getFinalPositions(); + + // Create comprehensive frontend-ready result + const result: BacktestResult = { + // Identification + backtestId, + status: 'completed' as const, + completedAt: new Date().toISOString(), + + // Configuration used + config: { + name: validatedConfig.name || 'Backtest', + strategy: validatedConfig.strategy, + symbols: validatedConfig.symbols, + startDate: validatedConfig.startDate, + endDate: validatedConfig.endDate, + initialCapital: validatedConfig.initialCapital, + commission: validatedConfig.commission || 0, + slippage: validatedConfig.slippage || 0, + dataFrequency: validatedConfig.dataFrequency || '1d', + }, + + // Performance metrics (frontend-ready) + metrics: { + totalReturn: performance.totalReturn, + sharpeRatio: performance.sharpeRatio, + maxDrawdown: performance.maxDrawdown, + winRate: performance.winRate, + totalTrades: tradeCount || performance.totalTrades, + profitFactor: performance.profitFactor || 0, + profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100), + avgWin: performance.avgWin || 0, + avgLoss: performance.avgLoss || 0, + expectancy: performance.expectancy || 0, + calmarRatio: performance.calmarRatio || 0, + sortinoRatio: performance.sortinoRatio || 0, + }, + + // Chart data (frontend-ready format) + equity: this.equityCurve + .sort((a, b) => a.timestamp - b.timestamp) + .map(point => ({ + date: new Date(point.timestamp).toISOString(), + value: point.value, + })), + + // OHLC data for charts + ohlcData: this.getOHLCData(marketData, validatedConfig.symbols), + + // 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: this.calculateDrawdown(), + dailyReturns: this.calculateDailyReturns(), + monthlyReturns: this.calculateMonthlyReturns(), + exposureTime: this.calculateExposureTime(closedTrades), + riskMetrics: this.calculateRiskMetrics(closedTrades), + }, + }; + + await this.storeResults(result); + + this.container.logger.info( + `Backtest completed: ${performance.totalTrades} trades, ${performance.totalReturn}% return` + ); + + return result; + } catch (error) { + this.container.logger.error('Backtest failed:', error); + throw error; + } finally { + this.isRunning = false; + this.reset(); + } + } + + private async loadHistoricalData(config: BacktestConfig): Promise { + const data: MarketData[] = []; + const startDate = new Date(config.startDate); + const endDate = new Date(config.endDate); + + try { + for (const symbol of config.symbols) { + const bars = await this.storageService.getHistoricalBars( + symbol, + startDate, + endDate, + config.dataFrequency + ); + + // If no data found, use mock data + if (!bars || bars.length === 0) { + this.container.logger.warn(`No historical data found for ${symbol}, using mock data`); + + // Tell the Rust core to generate mock data + const tradingEngine = this.strategyManager.getTradingEngine(); + if (tradingEngine && tradingEngine.generateMockData) { + await tradingEngine.generateMockData( + symbol, + startDate.getTime(), + endDate.getTime(), + 42 // seed for reproducibility + ); + + // For now, we'll generate mock data on the TypeScript side + // as the Rust integration needs more work + const mockData = this.generateMockData(symbol, startDate, endDate); + data.push(...mockData); + } else { + // Fallback to TypeScript mock data generation + const mockData = this.generateMockData(symbol, startDate, endDate); + data.push(...mockData); + } + } else { + // Convert to MarketData format + bars.forEach(bar => { + data.push({ + type: 'bar', + 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(), + }, + }); + }); + } + } + } catch (error) { + this.container.logger.warn('Error loading historical data, using mock data:', { + value: error, + }); + + // Generate mock data for all symbols + for (const symbol of config.symbols) { + const mockData = this.generateMockData(symbol, startDate, endDate); + data.push(...mockData); + } + } + + // Sort by timestamp + data.sort((a, b) => { + const timeA = a.data.timestamp; + const timeB = b.data.timestamp; + return timeA - timeB; + }); + + return data; + } + + private generateMockData(symbol: string, startDate: Date, endDate: Date): MarketData[] { + const data: MarketData[] = []; + const startTime = startDate.getTime(); + const endTime = endDate.getTime(); + const interval = 24 * 60 * 60 * 1000; // 1 day in milliseconds + + let price = 100; // Base price + let currentTime = startTime; + let trend = 0; // Current trend direction + let trendStrength = 0; + let trendDuration = 0; + + while (currentTime <= endTime) { + // Every 10-30 days, change trend (more frequent for testing) + if (trendDuration <= 0) { + trend = Math.random() > 0.5 ? 1 : -1; + trendStrength = 0.003 + Math.random() * 0.005; // 0.3% to 0.8% daily trend + trendDuration = Math.floor(10 + Math.random() * 20); // Shorter trends + } + + // Generate price movement with trend and noise + const trendComponent = trend * trendStrength; + const noiseComponent = (Math.random() - 0.5) * 0.03; // +/- 1.5% noise + const changePercent = trendComponent + noiseComponent; + price = price * (1 + changePercent); + + // Generate OHLC with realistic intraday movement + const open = price * (1 + (Math.random() - 0.5) * 0.005); + const dayRange = 0.01 + Math.random() * 0.02; // 1-3% daily range + const high = Math.max(open, price) * (1 + Math.random() * dayRange); + const low = Math.min(open, price) * (1 - Math.random() * dayRange); + const close = low + Math.random() * (high - low); + const volume = Math.random() * 1000000 + 500000; + + trendDuration--; + + data.push({ + type: 'bar', + data: { + symbol, + open, + high, + low, + close, + volume, + vwap: (open + high + low + close) / 4, + timestamp: currentTime, + }, + }); + + currentTime += interval; + price = close; // Next bar opens at previous close + } + + return data; + } + + private populateEventQueue(marketData: MarketData[]): void { + // Convert market data to events + marketData.forEach(data => { + this.eventQueue.push({ + timestamp: data.data.timestamp, + type: 'market_data', + data, + }); + }); + + // Sort by timestamp (should already be sorted) + this.eventQueue.sort((a, b) => a.timestamp - b.timestamp); + } + + private async processEvents(): Promise { + const tradingEngine = this.strategyManager.getTradingEngine(); + let lastEquityUpdate = 0; + const equityUpdateInterval = 60000; // Update equity every minute + + this.totalEvents = this.eventQueue.length; + this.container.logger.info( + `[BacktestEngine] Processing ${this.totalEvents} events with speed multiplier: ${this.speedMultiplier}` + ); + + let processedCount = 0; + + while (this.eventQueue.length > 0 && this.isRunning) { + // Check if paused + if (this.isPaused) { + await new Promise(resolve => setTimeout(resolve, 100)); + continue; + } + + const event = defined(this.eventQueue.shift()); + processedCount++; + + // Apply speed control if not unlimited + if (this.speedMultiplier !== null && this.speedMultiplier > 0) { + // Base delay in milliseconds for processing each event + // For 1x speed: 1000ms per event (1 event per second) + // For 2x speed: 500ms per event (2 events per second) + // For 10x speed: 100ms per event (10 events per second) + const baseDelay = 1000; // milliseconds + const actualDelay = baseDelay / this.speedMultiplier; + + // Add the delay + if (actualDelay > 1) { + if (processedCount % 50 === 0) { + // Log every 50 events to avoid spam + this.container.logger.debug( + `[BacktestEngine] Applying delay: ${actualDelay}ms (speed: ${this.speedMultiplier}x)` + ); + } + await new Promise(resolve => setTimeout(resolve, actualDelay)); + } + + // Also send progress updates more frequently at slower speeds + if (processedCount % Math.max(1, Math.floor(10 / this.speedMultiplier)) === 0) { + const progress = Math.round((processedCount / this.totalEvents) * 100); + this.sendProgressUpdate(progress, new Date(event.timestamp).toISOString()); + } + } + + this.lastProcessTime = Date.now(); + + // Advance time + this.currentTime = event.timestamp; + if (tradingEngine) { + await tradingEngine.advanceTime(this.currentTime); + } + + // Process event based on type + switch (event.type) { + case 'market_data': + await this.processMarketData(event.data); + break; + + case 'strategy_signal': + await this.processStrategySignal(event.data); + break; + + case 'order_fill': + await this.processFill(event.data); + break; + } + + // Update equity curve periodically + if (this.currentTime - lastEquityUpdate > equityUpdateInterval) { + await this.updateEquityCurve(); + lastEquityUpdate = this.currentTime; + } + + // Send progress update via WebSocket (unless already sent in speed control) + if (this.speedMultiplier === null && processedCount % this.progressUpdateInterval === 0) { + const progress = Math.round((processedCount / this.totalEvents) * 100); + this.sendProgressUpdate(progress, new Date(this.currentTime).toISOString()); + + // Also emit local progress event + this.emit('progress', { + processed: processedCount, + total: this.totalEvents, + remaining: this.eventQueue.length, + currentTime: new Date(this.currentTime), + progress, + }); + } + } + + // Final equity update + await this.updateEquityCurve(); + + // Send 100% progress + this.sendProgressUpdate(100, new Date(this.currentTime).toISOString()); + } + + private async processMarketData(data: MarketData): Promise { + this.container.logger.info( + `[BacktestEngine] processMarketData called for ${data.data.symbol} (${data.type})` + ); + const tradingEngine = this.strategyManager.getTradingEngine(); + if (!tradingEngine) { + this.container.logger.warn(`[BacktestEngine] No trading engine available`); + return; + } + + // Process through market simulator for realistic orderbook + const orderbook = this.marketSimulator.processMarketData(data); + + if (orderbook) { + // Update trading engine with simulated orderbook + if (orderbook.bids.length > 0 && orderbook.asks.length > 0) { + tradingEngine.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 && tradingEngine.setMicrostructure) { + tradingEngine.setMicrostructure(orderbook.symbol, microstructure); + } + } else { + // Fallback to simple processing + switch (data.type) { + case 'quote': + tradingEngine.updateQuote( + data.data.symbol, + data.data.bid, + data.data.ask, + data.data.bidSize, + data.data.askSize + ); + break; + + case 'trade': + tradingEngine.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; + + tradingEngine.updateQuote( + data.data.symbol, + data.data.close - halfSpread, + data.data.close + halfSpread, + data.data.volume / 100, + data.data.volume / 100 + ); + break; + } + } + } + + // Let strategies process the data + this.container.logger.info( + `[BacktestEngine] Forwarding data to strategy manager for ${data.data.symbol}` + ); + await this.strategyManager.onMarketData(data); + + // Check for any pending orders that should be filled + await this.checkAndFillOrders(data); + + // Track performance + this.performanceAnalyzer.addEquityPoint( + new Date(this.currentTime), + await this.getPortfolioValue() + ); + } + + private async processStrategySignal(_signal: Signal): Promise { + // Strategy signals are handled by strategy manager + // This is here for future extensions + } + + private async processFill(fill: StrategyFill): Promise { + this.container.logger.info( + `[BacktestEngine] Processing fill: ${fill.side} ${fill.quantity} ${fill.symbol} @ ${fill.price} with timestamp ${fill.timestamp}` + ); + + // Process fill in trading engine for position tracking + const tradingEngine = this.strategyManager.getTradingEngine(); + if (tradingEngine) { + this.container.logger.info(`[BacktestEngine] Trading engine available, processing fill`); + this.container.logger.info( + `[BacktestEngine] Current time in trading engine before advance: ${tradingEngine.getCurrentTime()}` + ); + + // Make sure time is properly advanced + if (fill.timestamp) { + await tradingEngine.advanceTime(fill.timestamp); + this.container.logger.info( + `[BacktestEngine] Advanced trading engine time to ${fill.timestamp}, current time now: ${tradingEngine.getCurrentTime()}` + ); + } + + // Use the new process_fill_with_metadata method if available + if (tradingEngine.processFillWithMetadata) { + const fillResult = await tradingEngine.processFillWithMetadata( + fill.symbol, + fill.price, + fill.quantity, + fill.side, + fill.commission || 0, + fill.orderId || null, + fill.strategyId || null + ); + this.container.logger.debug('Fill processed with tracking:', { value: fillResult }); + } else { + // Fallback to old method + const fillResult = await tradingEngine.processFill( + fill.symbol, + fill.price, + fill.quantity, + fill.side, + fill.commission || 0 + ); + this.container.logger.debug('Fill processed:', { value: fillResult }); + } + } else { + this.container.logger.warn(`[BacktestEngine] No trading engine available to process fill!`); + } + + // Notify strategies of fill + const strategy = fill.strategyId ? this.strategyManager.getStrategy(fill.strategyId) : null; + if (strategy) { + await strategy.onOrderUpdate({ + orderId: fill.orderId, + symbol: fill.symbol, + side: fill.side, + status: 'filled', + fills: [fill], + }); + } + + // Store in database + await this.storageService.storeFill(fill); + } + + private async updateEquityCurve(): Promise { + const totalEquity = await this.getPortfolioValue(); + + this.container.logger.debug( + `[updateEquityCurve] currentTime=${this.currentTime}, totalEquity=${totalEquity}, initialCapital=${this.initialCapital}` + ); + + // Don't add duplicate points at the same timestamp + const lastPoint = this.equityCurve[this.equityCurve.length - 1]; + if (lastPoint && lastPoint.timestamp === this.currentTime) { + // Update the value instead of adding a duplicate + this.container.logger.debug( + `[updateEquityCurve] Updating existing point at ${this.currentTime}: ${lastPoint.value} -> ${totalEquity}` + ); + lastPoint.value = totalEquity; + } else { + this.container.logger.debug( + `[updateEquityCurve] Adding new point at ${this.currentTime}: ${totalEquity}` + ); + this.equityCurve.push({ + timestamp: this.currentTime, + value: totalEquity, + }); + } + } + + private async getPortfolioValue(): Promise { + const tradingEngine = this.strategyManager.getTradingEngine(); + if (!tradingEngine) { + this.container.logger.debug( + `[getPortfolioValue] No trading engine, returning initialCapital: ${this.initialCapital}` + ); + return this.initialCapital; + } + + try { + // Get current P&L + const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); + const totalValue = this.initialCapital + realized + unrealized; + + this.container.logger.debug( + `[getPortfolioValue] P&L: realized=${realized}, unrealized=${unrealized}, initialCapital=${this.initialCapital}, totalValue=${totalValue}` + ); + + // Ensure we never return 0 or negative values that would cause spikes + // This handles the case where getTotalPnl might not be initialized yet + if (totalValue <= 0 || isNaN(totalValue)) { + this.container.logger.debug( + `[getPortfolioValue] Invalid totalValue, returning initialCapital: ${this.initialCapital}` + ); + return this.initialCapital; + } + + return totalValue; + } catch (error) { + // If getTotalPnl fails, return initial capital + this.container.logger.warn('Failed to get total P&L, using initial capital:', { + value: error, + }); + return this.initialCapital; + } + } + + private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics { + // Use sophisticated performance analyzer + // Add closed trades from Rust core + closedTrades.forEach(trade => { + this.performanceAnalyzer.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 + }); + }); + + const metrics = this.performanceAnalyzer.analyze(); + + // Add drawdown analysis + const drawdownAnalysis = this.performanceAnalyzer.analyzeDrawdowns(); + + return { + ...metrics, + maxDrawdown: drawdownAnalysis.maxDrawdown, + maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration, + }; + } + + private sendProgressUpdate(progress: number, currentDate: string): void { + if (!this.runId) { + return; + } + + try { + // Try to send WebSocket update to web-api + const url = `http://localhost:2003/api/runs/${this.runId}/progress`; + fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ progress, currentDate }), + }).catch(err => { + // Ignore errors - WebSocket updates are best-effort + this.container.logger.debug('Failed to send progress update:', err); + }); + } catch (_error) { + // Ignore errors + } + } + + private calculateDrawdown(): { timestamp: number; value: number }[] { + const drawdowns: { timestamp: number; value: number }[] = []; + let peak = this.equityCurve[0]?.value || 0; + + for (const point of this.equityCurve) { + if (point.value > peak) { + peak = point.value; + } + const drawdown = ((point.value - peak) / peak) * 100; + drawdowns.push({ + timestamp: point.timestamp, + value: drawdown, + }); + } + + return drawdowns; + } + + private calculateMonthlyReturns(): Record { + const monthlyReturns: Record = {}; + const monthlyEquity = new Map(); + + for (const point of this.equityCurve) { + const date = new Date(point.timestamp); + const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; + + if (!monthlyEquity.has(monthKey)) { + monthlyEquity.set(monthKey, { start: point.value, end: point.value }); + } else { + const month = defined(monthlyEquity.get(monthKey)); + month.end = point.value; + } + } + + for (const [month, values] of monthlyEquity) { + monthlyReturns[month] = ((values.end - values.start) / values.start) * 100; + } + + return monthlyReturns; + } + + 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 calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record { + const returns = this.calculateDailyReturns(); + + // Calculate various risk metrics + const avgReturn = returns.reduce((a, b) => a + b, 0) / Math.max(returns.length, 1); + const variance = + returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length; + const stdDev = Math.sqrt(variance); + + // Downside deviation (for Sortino) + const downsideReturns = returns.filter(r => r < 0); + const downsideVariance = + downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) / + Math.max(downsideReturns.length, 1); + const downsideDeviation = Math.sqrt(downsideVariance); + + return { + volatility: stdDev * Math.sqrt(252), // Annualized + downsideDeviation: downsideDeviation * Math.sqrt(252), + var95: this.calculateVaR(returns, 0.95), + var99: this.calculateVaR(returns, 0.99), + cvar95: this.calculateCVaR(returns, 0.95), + maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades), + }; + } + + private calculateVaR(returns: number[], confidence: number): number { + const sorted = [...returns].sort((a, b) => a - b); + const index = Math.floor((1 - confidence) * sorted.length); + return sorted[index] || 0; + } + + private calculateCVaR(returns: number[], confidence: number): number { + const sorted = [...returns].sort((a, b) => a - b); + const index = Math.floor((1 - confidence) * sorted.length); + const tail = sorted.slice(0, index + 1); + return tail.reduce((a, b) => a + b, 0) / Math.max(tail.length, 1); + } + + private calculateMaxConsecutiveLosses(closedTrades: ClosedTrade[] = []): number { + let maxLosses = 0; + let currentLosses = 0; + + for (const trade of closedTrades) { + if (trade.pnl && trade.pnl < 0) { + currentLosses++; + maxLosses = Math.max(maxLosses, currentLosses); + } else { + currentLosses = 0; + } + } + + return maxLosses; + } + + private calculateDailyReturns(): number[] { + const dailyReturns: number[] = []; + const dailyEquity = new Map(); + + // Group equity by day + for (const point of this.equityCurve) { + const date = new Date(point.timestamp).toDateString(); + dailyEquity.set(date, point.value); + } + + // Calculate returns + const dates = Array.from(dailyEquity.keys()).sort(); + for (let i = 1; i < dates.length; i++) { + const prevValue = defined(dailyEquity.get(at(dates, i - 1))); + const currValue = defined(dailyEquity.get(at(dates, i))); + const dailyReturn = ((currValue - prevValue) / prevValue) * 100; + dailyReturns.push(dailyReturn); + } + + return dailyReturns; + } + + private async getFinalPositions(): Promise { + const tradingEngine = this.strategyManager.getTradingEngine(); + if (!tradingEngine) { + return []; + } + + const positions = openPositionsSchema.parse(JSON.parse(tradingEngine.getOpenPositions())); + return positions.map(position => ({ + symbol: position.symbol, + quantity: position.quantity, + averagePrice: position.average_price, + currentPrice: position.average_price, + unrealizedPnl: position.unrealized_pnl, + realizedPnl: position.realized_pnl, + })); + } + + private async storeResults(result: BacktestResult): Promise { + // Store performance metrics + await this.storageService.storeStrategyPerformance(result.backtestId, result.metrics); + + // Could also store detailed results in a separate table or file + this.container.logger.debug(`Backtest results stored with ID: ${result.backtestId}`); + } + + private reset(): void { + this.eventQueue = []; + this.currentTime = 0; + this.equityCurve = []; + this.pendingOrders.clear(); + this.ordersListenerSetup = false; + this.isPaused = false; + this.speedMultiplier = 1; + this.lastProcessTime = 0; + this.marketSimulator.reset(); + } + + private async loadMarketMicrostructure(symbols: string[]): Promise { + // 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: 2 + Math.random() * 3, // 2-5 bps + dailyVolume: 10_000_000 * (1 + Math.random() * 9), // 10-100M shares + avgTradeSize: 100 + Math.random() * 400, // 100-500 shares + volatility: 0.15 + Math.random() * 0.25, // 15-40% annual vol + tickSize: 0.01, + lotSize: 1, + intradayVolumeProfile: this.generateIntradayProfile(), + }; + + this.microstructures.set(symbol, microstructure); + this.marketSimulator.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); + } + + async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise { + // Get trades from Rust core + const tradingEngine = this.strategyManager.getTradingEngine(); + let closedTrades: ClosedTrade[] = []; + if (tradingEngine && tradingEngine.getClosedTrades) { + try { + const tradesJson = tradingEngine.getClosedTrades(); + closedTrades = closedTradesSchema.parse(JSON.parse(tradesJson)); + } catch (error) { + this.container.logger.warn('Failed to get closed trades for export:', { value: error }); + } + } + + const result = { + summary: this.calculatePerformance(closedTrades), + trades: closedTrades, + equityCurve: this.equityCurve, + drawdowns: this.calculateDrawdown(), + dataQuality: this.dataManager.getDataQualityReport(), + performanceReport: this.performanceAnalyzer.exportReport(), + }; + + switch (format) { + case 'json': + return JSON.stringify(result, null, 2); + case 'csv': + // Convert to CSV format + return this.convertToCSV(result); + case 'html': + // Generate HTML report + return this.generateHTMLReport(result); + default: + return JSON.stringify(result); + } + } + + private convertToCSV(result: ExportResult): 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.join(',')).join('\n'); + } + + private generateHTMLReport(result: ExportResult): string { + return ` + + + + Backtest Report + + + +

Backtest Performance Report

+ +

Summary Statistics

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

Detailed Performance Metrics

+
${result.performanceReport}
+ +

Trade History

+ + + + + + + + + + + + ${result.trades + .map( + t => ` + + + + + + + + + + + ` + ) + .join('')} +
DateSymbolSideEntry PriceExit PriceQuantityP&LReturn %
${new Date(t.entry_time).toLocaleDateString()}${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)}%
+ + + `; + } + + private getOHLCData(marketData: MarketData[], symbols: string[]): Record { + const ohlcData: Record = {}; + + symbols.forEach(symbol => { + const symbolData = marketData + .filter( + (d): d is Extract => + d.type === 'bar' && d.data.symbol === symbol + ) + .map(d => ({ + timestamp: d.data.timestamp, + open: d.data.open, + high: d.data.high, + low: d.data.low, + close: d.data.close, + volume: d.data.volume, + })) + .sort((a, b) => a.timestamp - b.timestamp); // Ensure data is sorted by time + + ohlcData[symbol] = symbolData; + }); + + return ohlcData; + } + + private setupOrderListener(): void { + if (this.ordersListenerSetup) { + return; + } + + // Listen for orders from strategy manager + this.strategyManager.on('order', async (orderEvent: PendingOrder) => { + this.container.logger.info('[BacktestEngine] Order from StrategyManager:', orderEvent); + this.pendingOrders.set(orderEvent.orderId, { + ...orderEvent, + timestamp: this.currentTime, + }); + }); + + this.ordersListenerSetup = true; + } + + private setupStrategyOrderListeners(): void { + // Listen for orders directly from strategies + const strategies = this.strategyManager.getAllStrategies(); + this.container.logger.info(`Setting up order listeners for ${strategies.length} strategies`); + + strategies.forEach(strategy => { + this.container.logger.info( + `Setting up order listener for strategy: ${strategy.getConfig().id}` + ); + + const orderHandler = async (order: OrderRequest) => { + const orderId = `${strategy.getConfig().id}-${Date.now()}-${Math.random()}`; + this.container.logger.info( + `[BacktestEngine] 🔔 Order from strategy ${strategy.getConfig().id}:`, + order + ); + this.container.logger.info( + `[BacktestEngine] Adding order ${orderId} to pendingOrders. Current size: ${this.pendingOrders.size}` + ); + this.pendingOrders.set(orderId, { + strategyId: strategy.getConfig().id, + orderId, + order, + timestamp: this.currentTime, + }); + this.container.logger.info( + `[BacktestEngine] After adding, pendingOrders size: ${this.pendingOrders.size}` + ); + }; + + strategy.on('order', orderHandler); + + // Also listen for signals + strategy.on('signal', signal => { + this.container.logger.info( + `[BacktestEngine] 📊 Signal from strategy ${strategy.getConfig().id}:`, + signal + ); + }); + }); + } + + private async checkAndFillOrders(data: MarketData): Promise { + if (data.type !== 'bar') { + return; + } + + const symbol = data.data.symbol; + const currentPrice = data.data.close; + + // Check pending orders for this symbol + const ordersToFill: string[] = []; + + this.container.logger.info( + `[checkAndFillOrders] Checking ${this.pendingOrders.size} pending orders for ${symbol}` + ); + + for (const [orderId, orderEvent] of this.pendingOrders) { + if (orderEvent.order.symbol === symbol) { + // For market orders, fill immediately at current price + if (orderEvent.order.orderType === 'market') { + this.container.logger.info( + `[checkAndFillOrders] Found market order ${orderId} for ${symbol}` + ); + ordersToFill.push(orderId); + } + } + } + + // Process fills + for (const orderId of ordersToFill) { + const orderEvent = this.pendingOrders.get(orderId); + if (!orderEvent) { + continue; + } + + const fillPrice = + orderEvent.order.side === 'buy' + ? currentPrice * (1 + this.slippage) + : currentPrice * (1 - this.slippage); + + const fill = { + orderId, + symbol: orderEvent.order.symbol, + side: orderEvent.order.side, + quantity: orderEvent.order.quantity, + price: fillPrice, + timestamp: this.currentTime, + commission: orderEvent.order.quantity * fillPrice * this.commission, + strategyId: orderEvent.strategyId, + }; + + this.container.logger.info( + `✅ Filling ${orderEvent.order.side} order for ${symbol} @ ${fillPrice} at timestamp ${this.currentTime} (${new Date(this.currentTime).toISOString()})` + ); + + // Remove from pending BEFORE processing to avoid duplicate fills + this.pendingOrders.delete(orderId); + + // Process the fill (this will update trading engine AND notify strategies) + await this.processFill(fill); + } + } + + // Playback control methods + async pauseBacktest(): Promise { + this.isPaused = true; + this.container.logger.info('Backtest paused'); + } + + async resumeBacktest(): Promise { + this.isPaused = false; + this.container.logger.info('Backtest resumed'); + } + + async stopBacktest(): Promise { + this.isRunning = false; + this.isPaused = false; + } + + setSpeedMultiplier(speed: number | null): void { + this.speedMultiplier = speed; + this.container.logger.info( + `Backtest speed multiplier set to: ${speed === null ? 'unlimited' : speed}` + ); + } + + getStatus(): { isRunning: boolean; isPaused: boolean; progress: number; currentTime: number } { + const progress = + this.totalEvents > 0 + ? Math.round(((this.totalEvents - this.eventQueue.length) / this.totalEvents) * 100) + : 0; + + return { + isRunning: this.isRunning, + isPaused: this.isPaused, + progress, + currentTime: this.currentTime, + }; + } +} diff --git a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts index 9fe9ecb4..04ba1a03 100644 --- a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts +++ b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts @@ -1,387 +1,409 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('MarketSimulator'); -import { MarketData, Quote, Trade, Bar, OrderBookSnapshot, PriceLevel } from '../types'; -import { MarketMicrostructure } from '../types/MarketMicrostructure'; - -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; - - 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 = { - 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 + Math.random() * 2 : // 1-3x visible size hidden - 1; - - // Bid levels - const bidPrice = topQuote.bid - (i * micro.tickSize); - const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.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 + Math.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) { - current.bids[0].price = quote.bid; - current.bids[0].size = quote.bidSize; - } - - if (current.asks.length > 0) { - current.asks[0].price = quote.ask; - current.asks[0].size = quote.askSize; - } - - // Adjust deeper levels based on spread changes - const oldSpread = current.asks[0].price - 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 / (current.bids[0].size || quote.bidSize); - current.bids[i].size *= sizeRatio * (0.9 + Math.random() * 0.2); - - // Adjust prices to maintain relative spacing - const spacing = (current.bids[i-1].price - current.bids[i].price) * spreadRatio; - current.bids[i].price = current.bids[i-1].price - spacing; - } - - for (let i = 1; i < current.asks.length; i++) { - const sizeRatio = quote.askSize / (current.asks[0].size || quote.askSize); - current.asks[i].size *= sizeRatio * (0.9 + Math.random() * 0.2); - - const spacing = (current.asks[i].price - current.asks[i-1].price) * spreadRatio; - current.asks[i].price = 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 * Math.random(); // Hidden liquidity probabilistic - } - - const fillSize = Math.min(remainingSize, availableSize); - - // Simulate latency - price might move - if (this.config.latencyMs > 0 && orderType === 'market') { - const priceMovement = microstructure ? - (Math.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 * Math.random(); - - if (darkPoolSize > 0) { - const midPrice = (orderbook.bids[0].price + 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 = (orderbook.bids[0].price + 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(); - } -} \ No newline at end of file +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; +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; + + 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 + Math.random() * 2 // 1-3x visible size hidden + : 1; + + // Bid levels + const bidPrice = topQuote.bid - i * micro.tickSize; + const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.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 + Math.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 + Math.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 + Math.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 * Math.random(); // Hidden liquidity probabilistic + } + + const fillSize = Math.min(remainingSize, availableSize); + + // Simulate latency - price might move + if (this.config.latencyMs > 0 && orderType === 'market') { + const priceMovement = microstructure + ? (((Math.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 * Math.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/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 73a6a9fc..e84394e0 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -1,266 +1,126 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { BacktestEngine as RustEngine } from '@stock-bot/engine'; -import { EventEmitter } from 'events'; -import { StorageService } from '../services/StorageService'; -import { SMACrossoverStrategy, StrategyExecutor } from '../strategies/StrategyExecutor'; -import { BacktestConfig, BacktestResult } from '../types'; - -/** - * Adapter that bridges the orchestrator with the Rust backtest engine - */ -export class RustBacktestAdapter extends EventEmitter { - private container: IServiceContainer; - private storageService: StorageService; - private currentEngine?: RustEngine; - private isRunning = false; - private strategyExecutor: StrategyExecutor; - - constructor(container: IServiceContainer) { - super(); - this.container = container; - this.storageService = container.custom?.StorageService || new StorageService( - container, - container.mongodb, - container.postgres, - null - ); - this.strategyExecutor = new StrategyExecutor(); - } - - async runBacktest(config: BacktestConfig): Promise { - if (this.isRunning) { - throw new Error('Backtest already running'); - } - - this.isRunning = true; - const startTime = Date.now(); - - try { - this.container.logger.info('Starting Rust backtest engine', { - symbols: config.symbols, - startDate: config.startDate, - endDate: config.endDate, - }); - - // Create Rust engine configuration - const rustConfig = { - name: config.name || 'Backtest', - 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 || '1d', - }; - - // Create new Rust engine instance - this.currentEngine = new RustEngine(rustConfig); - - // For now, use a simple strategy mapping - // In the future, strategies should be written in Rust or use a common interface - this.container.logger.info('About to register strategy', { - strategy: config.strategy, - config: config.config - }); - this.registerStrategy(config.strategy, config.config || {}); - - // Load historical data - await this.loadHistoricalData(config); - - // Emit progress events - this.emit('progress', { - progress: 0.1, - message: 'Data loaded, starting backtest...', - }); - - // Run the backtest in Rust - this.container.logger.info('Starting Rust engine execution'); - const resultJson = this.currentEngine.run(); - this.container.logger.info('Rust engine execution completed'); - const rustResult = JSON.parse(resultJson); - - this.container.logger.info('Rust backtest result summary', { - totalTrades: rustResult.metrics?.total_trades, - equityCurveLength: rustResult.equity_curve?.length, - tradesLength: rustResult.trades?.length, - finalPositions: rustResult.final_positions - }); - - // Log first trade structure to understand format - if (rustResult.trades?.length > 0) { - this.container.logger.info('First trade structure:', rustResult.trades[0]); - } - - // Rust result already contains OHLC data from the engine - const result: BacktestResult = rustResult; - - this.emit('complete', result); - return result; - - } catch (error) { - this.container.logger.error('Rust backtest failed', error); - - const errorResult: BacktestResult = { - backtestId: `rust-${Date.now()}`, - status: 'failed', - completedAt: new Date().toISOString(), - 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 || '1d', - }, - metrics: this.getEmptyMetrics(), - equityCurve: [], - trades: [], - dailyReturns: [], - finalPositions: {}, - executionTime: Date.now() - startTime, - error: error instanceof Error ? error.message : 'Unknown error', - }; - - this.emit('error', error); - return errorResult; - - } finally { - this.isRunning = false; - this.currentEngine = undefined; - } - } - - async stopBacktest(): Promise { - if (!this.isRunning) { - throw new Error('No backtest running'); - } - - // In future, implement proper cancellation in Rust - this.isRunning = false; - this.emit('cancelled'); - } - - private async loadHistoricalData(config: BacktestConfig): Promise { - const startDate = new Date(config.startDate); - const endDate = new Date(config.endDate); - const allMarketData = []; - - // Collect all data for all symbols - for (const symbol of config.symbols) { - const bars = await this.storageService.getHistoricalBars( - symbol, - startDate, - endDate, - config.dataFrequency || '1d' - ); - - // Convert to Rust format - const marketData = bars.map(bar => ({ - symbol, - timestamp: bar.timestamp.getTime(), - type: 'bar', - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3, - })); - - allMarketData.push(...marketData); - this.container.logger.info(`Collected ${marketData.length} bars for ${symbol}`); - } - - // Sort all data by timestamp to ensure chronological order - allMarketData.sort((a, b) => a.timestamp - b.timestamp); - - // Load all data at once into Rust engine - if (this.currentEngine) { - this.container.logger.info(`Loading ${allMarketData.length} total bars into Rust engine`); - this.currentEngine.loadMarketData(allMarketData); - } - } - - private registerStrategy(strategyName: string, parameters: any): void { - if (!this.currentEngine) {return;} - - this.container.logger.info('Registering strategy', { - strategyName, - parameters - }); - - // Check if we should use TypeScript or native Rust implementation - const useTypeScript = parameters.useTypeScriptImplementation || false; - - if (useTypeScript) { - // Register TypeScript strategy - this.container.logger.info('Using TypeScript strategy implementation'); - - // For now, we'll use the SMACrossoverStrategy - if (strategyName.toLowerCase().includes('sma') || strategyName.toLowerCase().includes('crossover')) { - const strategyId = `strategy-${Date.now()}`; - this.strategyExecutor.registerStrategy(strategyId, SMACrossoverStrategy); - - // Create a callback that uses the strategy executor - const callback = (callJson: string) => { - try { - const call = JSON.parse(callJson); - - if (call.method === 'on_market_data') { - const signals = this.strategyExecutor.onMarketData(call.data); - return JSON.stringify({ signals }); - } else if (call.method === 'on_fill') { - const { symbol, quantity, price, side } = call.data; - this.strategyExecutor.onFill(symbol, quantity, price, side); - return JSON.stringify({ signals: [] }); - } - - return JSON.stringify({ signals: [] }); - } catch (error) { - this.container.logger.error('Strategy execution error:', error); - return JSON.stringify({ signals: [] }); - } - }; - - // Register with Rust engine - this.currentEngine.addTypescriptStrategy( - strategyName, - strategyId, - parameters, - callback - ); - } - } else { - // Use native Rust strategy for maximum performance - this.container.logger.info('Using native Rust strategy implementation'); - - // Map strategy names to their Rust strategy types - let strategyType = 'sma_crossover'; // default - - if (strategyName.toLowerCase().includes('mean') || strategyName.toLowerCase().includes('reversion')) { - strategyType = 'mean_reversion'; - } else if (strategyName.toLowerCase().includes('momentum')) { - strategyType = 'momentum'; - } else if (strategyName.toLowerCase().includes('pairs')) { - strategyType = 'pairs_trading'; - } else if (strategyName.toLowerCase().includes('sma') || strategyName.toLowerCase().includes('crossover')) { - strategyType = 'sma_crossover'; - } - - this.container.logger.info(`Mapped strategy '${strategyName}' to type '${strategyType}'`); - - // Use the addNativeStrategy method instead - this.currentEngine.addNativeStrategy( - strategyType, - strategyName, - `strategy-${Date.now()}`, - parameters - ); - } - } - -} \ No newline at end of file +import { EventEmitter } from 'node:events'; +import { BacktestEngine as RustEngine } from '@stock-bot/engine'; +import { StorageService } from '../services/StorageService'; +import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types'; +import { nativeResultSchema, type NativeBacktestResult } from './native-result'; + +export type BacktestResult = NativeBacktestResult; + +/** Validates the native boundary; all historical data comes from the storage owner. */ +export class RustBacktestAdapter extends EventEmitter { + private readonly storageService: StorageService; + private isRunning = false; + private currentTime = 0; + constructor(private readonly container: OrchestratorServices) { + super(); + this.storageService = + container.custom?.StorageService ?? + new StorageService( + container, + container.mongodb, + container.postgres, + container.questdb ?? null + ); + } + + async runBacktest(input: BacktestConfig): Promise { + if (this.isRunning) { + throw new Error('Backtest already running'); + } + const config = BacktestConfigSchema.parse(input); + this.isRunning = true; + try { + const engine = new RustEngine({ + 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, + }); + const parameters = config.config ?? {}; + if (parameters.useTypeScriptImplementation) { + throw new Error('The native engine does not execute TypeScript strategy callbacks'); + } + const name = config.strategy.toLowerCase(); + const strategy = + name.includes('mean') || name.includes('reversion') + ? 'mean_reversion' + : name.includes('momentum') + ? 'momentum' + : name.includes('pairs') + ? 'pairs_trading' + : name.includes('sma') || name.includes('crossover') || name === 'moving-average' + ? 'sma_crossover' + : undefined; + if (!strategy) { + throw new Error(`Unknown native strategy: ${config.strategy}`); + } + engine.addNativeStrategy(strategy, config.strategy, 'backtest-strategy', parameters); + const data = []; + for (const symbol of config.symbols) { + const bars = await this.storageService.getHistoricalBars( + symbol, + new Date(config.startDate), + new Date(config.endDate), + config.dataFrequency + ); + if (!bars.length) { + throw new Error(`No historical data for ${symbol}`); + } + data.push( + ...bars.map(bar => ({ + symbol, + timestamp: bar.timestamp.getTime(), + type: 'bar', + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3, + })) + ); + } + data.sort((a, b) => a.timestamp - b.timestamp); + engine.loadMarketData(data); + this.emit('progress', { progress: 0, message: 'Historical data loaded' }); + const result = nativeResultSchema.parse(JSON.parse(engine.run())); + this.currentTime = new Date(config.endDate).getTime(); + this.emit('complete', result); + return result; + } catch (error) { + this.container.logger.error('Native backtest failed', { error }); + if (this.listenerCount('error') > 0) { + this.emit('error', error); + } + throw error; + } finally { + this.isRunning = false; + } + } + + getStatus() { + return { + isRunning: this.isRunning, + isPaused: false, + progress: this.isRunning ? 0 : 100, + currentTime: this.currentTime, + }; + } + async stopBacktest(): Promise { + throw new Error('Native synchronous backtests do not support cancellation'); + } + async pauseBacktest(): Promise { + throw new Error('Native synchronous backtests do not support pause'); + } + async resumeBacktest(): Promise { + throw new Error('Native synchronous backtests do not support resume'); + } + setSpeedMultiplier(_speed: number | null): void { + throw new Error('Native synchronous backtests run at maximum speed'); + } +} diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts b/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts index 8f890368..f2498f16 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts @@ -1,187 +1,188 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { BacktestEngine as RustEngine } from '@stock-bot/engine'; -import { StorageService } from '../services/StorageService'; -import { RustStrategy } from '../strategies/RustStrategy'; -import { BacktestConfig } from '../types'; - -export interface RustBacktestConfig { - name: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - commission: number; - slippage: number; - dataFrequency: string; -} - -export interface RustBacktestResult { - config: RustBacktestConfig; - metrics: { - totalReturn: number; - totalTrades: number; - profitableTrades: number; - winRate: number; - profitFactor: number; - sharpeRatio: number; - maxDrawdown: number; - totalPnl: number; - avgWin: number; - avgLoss: number; - }; - equityCurve: Array<{ date: string; value: number }>; - trades: any[]; - finalPositions: Record; -} - -export class RustBacktestEngine { - private engine: RustEngine; - private container: IServiceContainer; - private storageService: StorageService; - private config: RustBacktestConfig; - - constructor( - container: IServiceContainer, - storageService: StorageService, - config: BacktestConfig - ) { - this.container = container; - this.storageService = storageService; - - // Convert config for Rust - const rustConfig: RustBacktestConfig = { - name: config.name || 'Backtest', - 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 || '1d', - }; - - this.config = rustConfig; - this.engine = new RustEngine(rustConfig as any); - } - - /** - * Add a TypeScript strategy to the backtest - */ - addStrategy(strategy: RustStrategy): void { - strategy.register(this.engine); - } - - /** - * Load historical data for the backtest - */ - async loadData(): Promise { - // Get config from engine - const config = this.getConfig(); - - const startDate = new Date(config.startDate); - const endDate = new Date(config.endDate); - - // Load data for each symbol - for (const symbol of config.symbols) { - const bars = await this.storageService.getHistoricalBars( - symbol, - startDate, - endDate, - config.dataFrequency - ); - - // Convert to Rust format - const marketData = bars.map(bar => ({ - symbol, - timestamp: bar.timestamp.getTime(), // Convert to milliseconds - type: 'bar', - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3, - })); - - // Load into Rust engine - console.log(`Loading ${marketData.length} bars for ${symbol}`); - this.engine.loadMarketData(marketData as any); - } - } - - /** - * Run the backtest - */ - async run(): Promise { - console.log('Starting backtest run...'); - - // Load data first - await this.loadData(); - - // Run backtest in Rust - const resultJson = await this.engine.run(); - - // Parse result and convert snake_case to camelCase - const rustResult = JSON.parse(resultJson); - - const result: RustBacktestResult = { - config: rustResult.config, - metrics: { - totalReturn: rustResult.metrics.total_return, - totalTrades: rustResult.metrics.total_trades, - profitableTrades: rustResult.metrics.profitable_trades, - winRate: rustResult.metrics.win_rate, - profitFactor: rustResult.metrics.profit_factor, - sharpeRatio: rustResult.metrics.sharpe_ratio, - maxDrawdown: rustResult.metrics.max_drawdown, - totalPnl: rustResult.metrics.total_pnl, - avgWin: rustResult.metrics.avg_win, - avgLoss: rustResult.metrics.avg_loss, - }, - equityCurve: rustResult.equity_curve.map((point: any) => ({ - date: point[0], - value: point[1], - })), - trades: rustResult.trades, - finalPositions: rustResult.final_positions, - }; - - // Log results - this.container.logger.info('Rust backtest completed', { - totalReturn: result.metrics.totalReturn, - totalTrades: result.metrics.totalTrades, - sharpeRatio: result.metrics.sharpeRatio, - }); - - return result; - } - - /** - * Get the backtest configuration - */ - private getConfig(): RustBacktestConfig { - return this.config; - } -} - -/** - * Factory function to create a Rust-powered backtest - */ -export async function createRustBacktest( - container: IServiceContainer, - config: BacktestConfig, - strategies: RustStrategy[] -): Promise { - const storageService = container.custom?.StorageService || new StorageService(); - - // Create engine - const engine = new RustBacktestEngine(container, storageService, config); - - // Add strategies - for (const strategy of strategies) { - engine.addStrategy(strategy); - } - - // Run backtest - return await engine.run(); -} \ No newline at end of file +import { BacktestEngine as RustEngine } from '@stock-bot/engine'; +import { StorageService } from '../services/StorageService'; +import { RustStrategy } from '../strategies/RustStrategy'; +import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types'; +import { nativeResultSchema } from './native-result'; + +export interface RustBacktestConfig { + name: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + commission: number; + slippage: number; + dataFrequency: string; +} + +export interface RustBacktestResult { + config: RustBacktestConfig; + metrics: { + totalReturn: number; + totalTrades: number; + profitableTrades: number; + winRate: number; + profitFactor: number | null; + sharpeRatio: number; + maxDrawdown: number; + totalPnl: number; + avgWin: number; + avgLoss: number; + }; + equityCurve: Array<{ date: string; value: number }>; + trades: import('./native-result').NativeBacktestResult['trades']; + finalPositions: Record; +} + +export class RustBacktestEngine { + private engine: RustEngine; + private container: IServiceContainer; + private storageService: StorageService; + private config: RustBacktestConfig; + + constructor( + container: IServiceContainer, + storageService: StorageService, + config: BacktestConfig + ) { + this.container = container; + this.storageService = storageService; + + // Convert config for Rust + const rustConfig: RustBacktestConfig = { + name: config.name || 'Backtest', + 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 || '1d', + }; + + this.config = rustConfig; + this.engine = new RustEngine(rustConfig); + } + + /** + * Add a TypeScript strategy to the backtest + */ + addStrategy(strategy: RustStrategy): void { + strategy.register(this.engine); + } + + /** + * Load historical data for the backtest + */ + async loadData(): Promise { + // Get config from engine + const config = this.getConfig(); + + const startDate = new Date(config.startDate); + const endDate = new Date(config.endDate); + + // Load data for each symbol + for (const symbol of config.symbols) { + const bars = await this.storageService.getHistoricalBars( + symbol, + startDate, + endDate, + config.dataFrequency + ); + + // Convert to Rust format + const marketData = bars.map(bar => ({ + symbol, + timestamp: bar.timestamp.getTime(), // Convert to milliseconds + type: 'bar', + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: bar.volume, + vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3, + })); + + // Load into Rust engine + this.container.logger.info(`Loading ${marketData.length} bars for ${symbol}`); + this.engine.loadMarketData(marketData); + } + } + + /** + * Run the backtest + */ + async run(): Promise { + this.container.logger.info('Starting backtest run...'); + + // Load data first + await this.loadData(); + + // Run backtest in Rust + const resultJson = await this.engine.run(); + + // Parse result and convert snake_case to camelCase + const rustResult = nativeResultSchema.parse(JSON.parse(resultJson)); + + const result: RustBacktestResult = { + config: this.config, + metrics: { + totalReturn: rustResult.metrics.totalReturn, + totalTrades: rustResult.metrics.totalTrades, + profitableTrades: rustResult.trades.filter(trade => (trade.pnl ?? 0) > 0).length, + winRate: rustResult.metrics.winRate, + profitFactor: rustResult.metrics.profitFactor, + sharpeRatio: rustResult.metrics.sharpeRatio, + maxDrawdown: rustResult.metrics.maxDrawdown, + totalPnl: rustResult.trades.reduce((sum, trade) => sum + (trade.pnl ?? 0), 0), + avgWin: rustResult.metrics.avgWin, + avgLoss: rustResult.metrics.avgLoss, + }, + equityCurve: rustResult.equity, + trades: rustResult.trades, + finalPositions: Object.fromEntries( + rustResult.positions.map(position => [position.symbol, position]) + ), + }; + + // Log results + this.container.logger.info('Rust backtest completed', { + totalReturn: result.metrics.totalReturn, + totalTrades: result.metrics.totalTrades, + sharpeRatio: result.metrics.sharpeRatio, + }); + + return result; + } + + /** + * Get the backtest configuration + */ + private getConfig(): RustBacktestConfig { + return this.config; + } +} + +/** + * Factory function to create a Rust-powered backtest + */ +export async function createRustBacktest( + container: IServiceContainer, + config: BacktestConfig, + strategies: RustStrategy[] +): Promise { + const storageService = + container.custom?.StorageService || + new StorageService(container, container.mongodb, container.postgres, container.questdb ?? null); + + // Create engine + const engine = new RustBacktestEngine(container, storageService, config); + + // Add strategies + for (const strategy of strategies) { + engine.addStrategy(strategy); + } + + // Run backtest + return await engine.run(); +} diff --git a/apps/stock/orchestrator/src/backtest/native-result.ts b/apps/stock/orchestrator/src/backtest/native-result.ts new file mode 100644 index 00000000..02f888a7 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/native-result.ts @@ -0,0 +1,89 @@ +import { z } from 'zod'; + +/** Serialized contract of engine/src/backtest/simple_results.rs. */ +export const nativeResultSchema = z + .object({ + backtestId: z.string(), + status: z.enum(['completed', 'failed', 'cancelled']), + completedAt: z.string(), + config: z + .object({ + name: z.string(), + symbols: z.array(z.string()), + startDate: z.string(), + endDate: z.string(), + initialCapital: z.number(), + }) + .passthrough(), + metrics: z + .object({ + totalReturn: z.number(), + sharpeRatio: z.number(), + maxDrawdown: z.number(), + winRate: z.number(), + totalTrades: z.number(), + profitFactor: z.number().nullable(), + avgWin: z.number(), + avgLoss: z.number(), + }) + .passthrough(), + equity: z.array(z.object({ date: z.string(), value: z.number() })), + trades: z.array( + z.object({ + id: z.string(), + symbol: z.string(), + timestamp: z.string(), + side: z.enum(['buy', 'sell']), + price: z.number(), + quantity: z.number(), + commission: z.number(), + positionAfter: z.number(), + pnl: z.number().optional(), + }) + ), + positions: z.array( + z.object({ + symbol: z.string(), + quantity: z.number(), + averagePrice: z.number(), + currentPrice: z.number(), + unrealizedPnl: z.number(), + realizedPnl: z.number(), + }) + ), + analytics: z.object({ exposureTime: z.number() }).passthrough(), + ohlcData: z.record(z.array(z.record(z.unknown()))), + executionTime: z.number(), + error: z.string().optional(), + }) + .passthrough(); + +export type NativeBacktestResult = z.infer; + +/** Serialized contracts of engine/src/positions/mod.rs. */ +export const closedTradesSchema = z.array( + z.object({ + id: z.string(), + symbol: z.string(), + entry_time: z.string(), + exit_time: z.string(), + entry_price: z.number(), + exit_price: z.number(), + quantity: z.number(), + side: z.enum(['Buy', 'Sell']), + pnl: z.number(), + pnl_percent: z.number(), + commission: z.number(), + duration_ms: z.number(), + }) +); +export type ClosedTrade = z.infer[number]; +export const openPositionsSchema = z.array( + z.object({ + symbol: z.string(), + quantity: z.number(), + average_price: z.number(), + realized_pnl: z.number(), + unrealized_pnl: z.number(), + }) +); diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 4633de8f..5fb923f1 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -1,101 +1,122 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { ModeManager } from './core/ModeManager'; -import { MarketDataService } from './services/MarketDataService'; -import { ExecutionService } from './services/ExecutionService'; -import { AnalyticsService } from './services/AnalyticsService'; -import { StorageService } from './services/StorageService'; -import { StrategyManager } from './strategies/StrategyManager'; -import { BacktestEngine } from './backtest/BacktestEngine'; -import { PaperTradingManager } from './paper/PaperTradingManager'; - -/** - * Register orchestrator-specific services in the DI container - */ -export async function registerOrchestratorServices(container: any): Promise { - // Create a service adapter that provides the expected interface - const services: IServiceContainer = { - logger: container.cradle.logger, - cache: container.cradle.cache, - globalCache: container.cradle.globalCache, - mongodb: container.cradle.mongoClient, - postgres: container.cradle.postgresClient, - questdb: container.cradle.questdbClient, - browser: container.cradle.browser, - proxy: container.cradle.proxyManager, - queueManager: container.cradle.queueManager, - queue: undefined, // Will be set if needed - custom: {} - }; - - // Create storage service first as it's needed by other services - const storageService = new StorageService( - services, - services.mongodb!, - services.postgres!, - services.questdb || null - ); - - // Create other services - const marketDataService = new MarketDataService(services); - const executionService = new ExecutionService(services, storageService); - const analyticsService = new AnalyticsService(services, storageService); - const strategyManager = new StrategyManager(services); - const backtestEngine = new BacktestEngine(services, storageService, strategyManager); - const paperTradingManager = new PaperTradingManager( - services, - storageService, - marketDataService, - executionService - ); - const modeManager = new ModeManager( - services, - marketDataService, - executionService, - storageService - ); - - // Store custom services - services.custom = { - StorageService: storageService, - MarketDataService: marketDataService, - ExecutionService: executionService, - AnalyticsService: analyticsService, - StrategyManager: strategyManager, - BacktestEngine: backtestEngine, - PaperTradingManager: paperTradingManager, - ModeManager: modeManager - }; - - // Register services in the Awilix container for resolution - container.register({ - StorageService: { value: storageService }, - MarketDataService: { value: marketDataService }, - ExecutionService: { value: executionService }, - AnalyticsService: { value: analyticsService }, - StrategyManager: { value: strategyManager }, - BacktestEngine: { value: backtestEngine }, - PaperTradingManager: { value: paperTradingManager }, - ModeManager: { value: modeManager }, - orchestratorServices: { value: services } - }); - - // Update the serviceContainer to include our custom services - const serviceContainer = container.cradle.serviceContainer; - if (serviceContainer && serviceContainer.custom) { - Object.assign(serviceContainer.custom, services.custom); - } - - // Setup event listeners after all services are registered - strategyManager.setupEventListeners(); - - // Initialize mode manager with default paper trading mode - await modeManager.initializeMode({ - mode: 'paper', - startingCapital: 100000 - }); -} - -// For backward compatibility, export a container getter -export function getContainer(): IServiceContainer { - throw new Error('Container should be accessed through ServiceApplication. Update your code to use dependency injection.'); -} \ No newline at end of file +import { asValue, type AwilixContainer } from 'awilix'; +import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di'; +import { BacktestEngine } from './backtest/BacktestEngine'; +import { RustBacktestAdapter } from './backtest/RustBacktestAdapter'; +import { ModeManager } from './core/ModeManager'; +import { PaperTradingManager } from './paper/PaperTradingManager'; +import { AnalyticsService } from './services/AnalyticsService'; +import { ExecutionService } from './services/ExecutionService'; +import { MarketDataService } from './services/MarketDataService'; +import { StorageService } from './services/StorageService'; +import { StrategyManager } from './strategies/StrategyManager'; +import type { OrchestratorServices as IServiceContainer } from './types'; + +/** + * Register orchestrator-specific services in the DI container + */ +export async function registerOrchestratorServices( + container: AwilixContainer, + options: { + initializeMode?: boolean; + useRustEngine?: boolean; + allowSyntheticData?: boolean; + syntheticSeed?: number; + } = {} +): Promise { + // Create a service adapter that provides the expected interface + const services = container.resolve('serviceContainer') as IServiceContainer; + const custom = services.custom ?? {}; + if (!services.custom) { + Object.defineProperty(services, 'custom', { value: custom, enumerable: true }); + } + + // Create storage service first as it's needed by other services + const storageService = new StorageService( + services, + services.mongodb, + services.postgres, + services.questdb || null, + options + ); + + // Create other services + const marketDataService = new MarketDataService(services); + const executionService = new ExecutionService(services, storageService); + const analyticsService = new AnalyticsService(services, storageService); + const strategyManager = new StrategyManager(services); + Object.assign(custom, { StorageService: storageService }); + const backtestEngine = options.useRustEngine + ? new RustBacktestAdapter(services) + : new BacktestEngine(services, storageService, strategyManager); + const paperTradingManager = new PaperTradingManager( + services, + storageService, + marketDataService, + executionService + ); + const modeManager = new ModeManager( + services, + marketDataService, + executionService, + storageService + ); + + // Store custom services + Object.assign(services.custom ?? {}, { + StorageService: storageService, + MarketDataService: marketDataService, + ExecutionService: executionService, + AnalyticsService: analyticsService, + StrategyManager: strategyManager, + BacktestEngine: backtestEngine, + PaperTradingManager: paperTradingManager, + ModeManager: modeManager, + }); + + // Register services in the Awilix container for resolution + const orchestratorContainer = container as AwilixContainer< + ServiceDefinitions & { + StorageService: StorageService; + MarketDataService: MarketDataService; + ExecutionService: ExecutionService; + AnalyticsService: AnalyticsService; + StrategyManager: StrategyManager; + BacktestEngine: BacktestEngine | RustBacktestAdapter; + PaperTradingManager: PaperTradingManager; + ModeManager: ModeManager; + orchestratorServices: IServiceContainer; + } + >; + orchestratorContainer.register({ + StorageService: asValue(storageService), + MarketDataService: asValue(marketDataService), + ExecutionService: asValue(executionService), + AnalyticsService: asValue(analyticsService), + StrategyManager: asValue(strategyManager), + BacktestEngine: asValue(backtestEngine), + PaperTradingManager: asValue(paperTradingManager), + ModeManager: asValue(modeManager), + orchestratorServices: asValue(services), + }); + + // Update the serviceContainer to include our custom services + const serviceContainer = container.cradle.serviceContainer; + if (serviceContainer && serviceContainer.custom) { + Object.assign(serviceContainer.custom, services.custom); + } + + // Setup event listeners after all services are registered + strategyManager.setupEventListeners(); + + // Initialize mode manager with default paper trading mode + if (options.initializeMode !== false) { + await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 }); + } +} + +// For backward compatibility, export a container getter +export function getContainer(): IServiceContainer { + throw new Error( + 'Container should be accessed through ServiceApplication. Update your code to use dependency injection.' + ); +} diff --git a/apps/stock/orchestrator/src/core/ModeManager.ts b/apps/stock/orchestrator/src/core/ModeManager.ts index 4152b3bb..c049ae37 100644 --- a/apps/stock/orchestrator/src/core/ModeManager.ts +++ b/apps/stock/orchestrator/src/core/ModeManager.ts @@ -1,166 +1,185 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { TradingEngine } from '@stock-bot/engine'; -import { EventEmitter } from 'events'; -import { ExecutionService } from '../services/ExecutionService'; -import { MarketDataService } from '../services/MarketDataService'; -import { StorageService } from '../services/StorageService'; -import { BacktestConfigSchema, LiveConfigSchema, ModeConfig, PaperConfigSchema, TradingMode } from '../types'; - -export class ModeManager extends EventEmitter { - private mode: TradingMode = 'paper'; - private config: ModeConfig | null = null; - private tradingEngine: TradingEngine | null = null; - private isInitialized = false; - private container: IServiceContainer; - - constructor( - container: IServiceContainer, - private marketDataService: MarketDataService, - private executionService: ExecutionService, - private storageService: StorageService - ) { - super(); - this.container = container; - } - - async initializeMode(config: ModeConfig): Promise { - // Validate config based on mode - switch (config.mode) { - case 'backtest': - BacktestConfigSchema.parse(config); - break; - case 'paper': - PaperConfigSchema.parse(config); - break; - case 'live': - LiveConfigSchema.parse(config); - break; - } - - // Shutdown current mode if initialized - if (this.isInitialized) { - await this.shutdown(); - } - - 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); - - // Initialize services for the mode - await this.initializeServices(config); - - this.isInitialized = true; - this.emit('modeChanged', config); - - this.container.logger.info(`Trading mode initialized: ${config.mode}`); - } - - private createEngineConfig(config: ModeConfig): any { - 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): Promise { - // Configure market data service - await this.marketDataService.initialize(config); - - // Configure execution service - await this.executionService.initialize(config, this.tradingEngine!); - - // Configure storage - await this.storageService.initialize(config); - } - - 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 (fromMode === 'paper' && toMode === 'live') { - // Special handling for paper to live transition - this.container.logger.info('Transitioning from paper to live trading...'); - - // 1. Get current paper positions - const paperPositions = await this.tradingEngine!.getOpenPositions(); - - // 2. Initialize new mode - await this.initializeMode(config); - - // 3. Reconcile positions (this would be handled by a reconciliation service) - this.container.logger.info(`Paper positions to reconcile: ${paperPositions}`); - } else { - // Standard mode switch - await this.initializeMode(config); - } - } - - async shutdown(): Promise { - if (!this.isInitialized) {return;} - - this.container.logger.info(`Shutting down ${this.mode} mode...`); - - // Shutdown services - await this.marketDataService.shutdown(); - await this.executionService.shutdown(); - await this.storageService.shutdown(); - - // Cleanup trading engine - this.tradingEngine = null; - this.isInitialized = false; - - this.emit('shutdown'); - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { TradingEngine } from '@stock-bot/engine'; +import { defined } from '@stock-bot/invariants'; +import { ExecutionService } from '../services/ExecutionService'; +import { MarketDataService } from '../services/MarketDataService'; +import { StorageService } from '../services/StorageService'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { + BacktestConfigSchema, + LiveConfigSchema, + PaperConfigSchema, + type ModeConfig, + type TradingMode, +} from '../types'; + +export class ModeManager extends EventEmitter { + private mode: TradingMode = 'paper'; + private config: ModeConfig | null = null; + private tradingEngine: TradingEngine | null = null; + private isInitialized = false; + private container: IServiceContainer; + + constructor( + container: IServiceContainer, + private marketDataService: MarketDataService, + private executionService: ExecutionService, + private storageService: StorageService + ) { + super(); + this.container = container; + } + + async initializeMode(config: ModeConfig): Promise { + // Validate config based on mode + switch (config.mode) { + case 'backtest': + BacktestConfigSchema.parse(config); + break; + case 'paper': + PaperConfigSchema.parse(config); + break; + case 'live': + LiveConfigSchema.parse(config); + break; + } + + // Shutdown current mode if initialized + if (this.isInitialized) { + await this.shutdown(); + } + + 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); + + // Initialize services for the mode + await this.initializeServices(config); + + this.isInitialized = true; + this.emit('modeChanged', config); + + this.container.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): Promise { + // Configure market data service + await this.marketDataService.initialize(config); + + // Configure execution service + await this.executionService.initialize(config, defined(this.tradingEngine)); + + // Configure storage + await this.storageService.initialize(config); + } + + 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 (fromMode === 'paper' && toMode === 'live') { + // Special handling for paper to live transition + this.container.logger.info('Transitioning from paper to live trading...'); + + // 1. Get current paper positions + const paperPositions = await defined(this.tradingEngine).getOpenPositions(); + + // 2. Initialize new mode + await this.initializeMode(config); + + // 3. Reconcile positions (this would be handled by a reconciliation service) + this.container.logger.info(`Paper positions to reconcile: ${paperPositions}`); + } else { + // Standard mode switch + await this.initializeMode(config); + } + } + + async shutdown(): Promise { + if (!this.isInitialized) { + return; + } + + this.container.logger.info(`Shutting down ${this.mode} mode...`); + + // Shutdown services + await this.marketDataService.shutdown(); + await this.executionService.shutdown(); + await this.storageService.shutdown(); + + // Cleanup trading engine + this.tradingEngine = null; + this.isInitialized = false; + + this.emit('shutdown'); + } +} diff --git a/apps/stock/orchestrator/src/data/DataManager.ts b/apps/stock/orchestrator/src/data/DataManager.ts index 23874320..e45da091 100644 --- a/apps/stock/orchestrator/src/data/DataManager.ts +++ b/apps/stock/orchestrator/src/data/DataManager.ts @@ -1,501 +1,504 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('DataManager'); -import { StorageService } from '../services/StorageService'; -import { MarketData, Bar } from '../types'; -import { EventEmitter } from 'events'; - -export interface DataResolution { - interval: string; - milliseconds: number; -} - -export interface CorporateAction { - symbol: string; - date: Date; - type: 'split' | 'dividend' | 'spinoff'; - factor?: number; - amount?: number; - newSymbol?: string; -} - -export interface DataQualityIssue { - timestamp: Date; - symbol: string; - issue: string; - severity: 'warning' | 'error'; - details?: any; -} - -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 corporateActions: Map = new Map(); - private dataQualityIssues: DataQualityIssue[] = []; - - constructor(private storageService: StorageService) { - 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 - let data = await this.storageService.getHistoricalBars( - symbol, - startDate, - endDate, - resolution - ); - - // If no data found, generate mock data - if (!data || data.length === 0) { - logger.warn(`No historical data found for ${symbol}, generating mock data`); - data = this.generateMockBars(symbol, startDate, endDate, resolution); - } - - // Apply corporate actions - const adjustedData = await this.applyCorporateActions(symbol, data, startDate, endDate); - - // Quality checks - const cleanedData = this.performQualityChecks(symbol, adjustedData); - - // Convert to MarketData format - const marketData = this.convertToMarketData(symbol, cleanedData); - - 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 }); - } - } - - return result; - } - - async applyCorporateActions( - symbol: string, - data: any[], - startDate: Date, - endDate: Date - ): Promise { - // Load corporate actions for the period - const actions = await this.loadCorporateActions(symbol, startDate, endDate); - if (actions.length === 0) return data; - - // Sort actions by date (newest first) - actions.sort((a, b) => b.date.getTime() - a.date.getTime()); - - // Apply adjustments - return data.map(bar => { - const barDate = new Date(bar.timestamp); - let adjustedBar = { ...bar }; - - for (const action of actions) { - if (barDate < action.date) { - switch (action.type) { - case 'split': - if (action.factor) { - adjustedBar.open /= action.factor; - adjustedBar.high /= action.factor; - adjustedBar.low /= action.factor; - adjustedBar.close /= action.factor; - adjustedBar.volume *= action.factor; - } - break; - - case 'dividend': - if (action.amount) { - // Adjust for dividends (simplified) - const adjustment = 1 - (action.amount / adjustedBar.close); - adjustedBar.open *= adjustment; - adjustedBar.high *= adjustment; - adjustedBar.low *= adjustment; - adjustedBar.close *= adjustment; - } - break; - } - } - } - - return adjustedBar; - }); - } - - performQualityChecks(symbol: string, data: any[]): any[] { - const cleaned: any[] = []; - - for (let i = 0; i < data.length; i++) { - const bar = data[i]; - const prevBar = i > 0 ? data[i - 1] : null; - const issues: string[] = []; - - // Check for missing data - if (!bar.open || !bar.high || !bar.low || !bar.close || bar.volume === undefined) { - issues.push('Missing OHLCV data'); - } - - // Check for invalid prices - if (bar.low > bar.high) { - issues.push('Low > High'); - } - if (bar.open > bar.high || bar.open < bar.low) { - issues.push('Open outside High/Low range'); - } - if (bar.close > bar.high || bar.close < bar.low) { - issues.push('Close outside High/Low range'); - } - - // Check for zero or negative prices - if (bar.open <= 0 || bar.high <= 0 || bar.low <= 0 || bar.close <= 0) { - issues.push('Zero or negative prices'); - } - - // Check for extreme price movements (>20% in one bar) - if (prevBar) { - const priceChange = Math.abs((bar.close - prevBar.close) / prevBar.close); - if (priceChange > 0.2) { - issues.push(`Extreme price movement: ${(priceChange * 100).toFixed(1)}%`); - } - } - - // Check for volume spikes (>10x average) - if (i >= 20) { - const avgVolume = data.slice(i - 20, i) - .reduce((sum, b) => sum + b.volume, 0) / 20; - if (bar.volume > avgVolume * 10) { - issues.push('Volume spike detected'); - } - } - - // Handle issues - if (issues.length > 0) { - const severity = issues.some(issue => - issue.includes('Missing') || issue.includes('Zero') - ) ? 'error' : 'warning'; - - this.dataQualityIssues.push({ - timestamp: new Date(bar.timestamp), - symbol, - issue: issues.join(', '), - severity, - details: bar - }); - - // For errors, try to interpolate or skip - if (severity === 'error') { - if (prevBar && i < data.length - 1) { - // Interpolate from surrounding bars - const nextBar = data[i + 1]; - cleaned.push({ - ...bar, - open: (prevBar.close + nextBar.open) / 2, - high: Math.max(prevBar.high, nextBar.high) * 0.9, - low: Math.min(prevBar.low, nextBar.low) * 1.1, - close: (prevBar.close + nextBar.close) / 2, - volume: (prevBar.volume + nextBar.volume) / 2, - interpolated: true - }); - } - // Skip if we can't interpolate - continue; - } - } - - cleaned.push(bar); - } - - return cleaned; - } - - 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(currentBar.high!, bar.high); - currentBar.low = Math.min(currentBar.low!, bar.low); - currentBar.close = bar.close; - currentBar.volume! += bar.volume; - - // Recalculate VWAP if available - if (bar.vwap && currentBar.vwap) { - const totalValue = (currentBar.vwap * (currentBar.volume! - bar.volume)) + - (bar.vwap * bar.volume); - currentBar.vwap = totalValue / 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(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 = downsampled[downsampled.length - 1]; - const prevTime = prevPoint.data.timestamp; - const prevPrice = this.getPrice(prevPoint); - - // Calculate average of next bucket for area calculation - let 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 += data[j].data.timestamp; - avgPrice += this.getPrice(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 = data[j].data.timestamp; - const price = this.getPrice(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(data[maxAreaPoint]); - } - - // Always include last point - downsampled.push(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: any[]): 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 - } - })); - } - - private async loadCorporateActions( - symbol: string, - startDate: Date, - endDate: Date - ): Promise { - // Check cache first - const cached = this.corporateActions.get(symbol); - if (cached) { - return cached.filter(action => - action.date >= startDate && action.date <= endDate - ); - } - - // In real implementation, load from database - // For now, return empty array - return []; - } - - 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]++; - } - - return { - totalIssues: this.dataQualityIssues.length, - bySymbol, - bySeverity, - issues: this.dataQualityIssues - }; - } - - clearCache(): void { - this.dataCache.clear(); - this.aggregatedCache.clear(); - this.dataQualityIssues = []; - } - - private generateMockBars( - symbol: string, - startDate: Date, - endDate: Date, - resolution: string - ): any[] { - const bars: any[] = []; - const resolutionMs = DataManager.RESOLUTIONS[resolution]?.milliseconds || 86400000; // Default to 1 day - - let currentTime = startDate.getTime(); - const endTime = endDate.getTime(); - - // Base price varies by symbol - let basePrice = 100; - if (symbol === 'AAPL') basePrice = 150; - else if (symbol === 'GOOGL') basePrice = 140; - else if (symbol === 'MSFT') basePrice = 380; - else if (symbol === 'TSLA') basePrice = 250; - - let price = basePrice; - - while (currentTime <= endTime) { - // Generate realistic intraday movement - const volatility = 0.02; // 2% daily volatility - const trend = 0.0001; // Slight upward trend - - // Random walk with trend - const changePercent = (Math.random() - 0.5) * volatility + trend; - price = price * (1 + changePercent); - - // Generate OHLC - const open = price; - const intraDayVolatility = volatility / 4; - const high = price * (1 + Math.random() * intraDayVolatility); - const low = price * (1 - Math.random() * intraDayVolatility); - const close = low + Math.random() * (high - low); - - // Volume with some randomness - const baseVolume = 10000000; // 10M shares - const volume = baseVolume * (0.5 + Math.random()); - - bars.push({ - timestamp: new Date(currentTime), - open: Number(open.toFixed(2)), - high: Number(high.toFixed(2)), - low: Number(low.toFixed(2)), - close: Number(close.toFixed(2)), - volume: Math.floor(volume), - vwap: Number(((high + low + close) / 3).toFixed(2)) - }); - - currentTime += resolutionMs; - price = close; // Next bar opens at previous close - } - - return bars; - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; +import { StorageService, type HistoricalBar } from '../services/StorageService'; +import { type Bar, type MarketData } from '../types'; + +const logger = getLogger('DataManager'); + +export interface DataResolution { + interval: string; + milliseconds: number; +} + +export interface CorporateAction { + symbol: string; + date: Date; + type: 'split' | 'dividend' | 'spinoff'; + factor?: number; + amount?: number; + newSymbol?: string; +} + +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 corporateActions: Map = new Map(); + private dataQualityIssues: DataQualityIssue[] = []; + + constructor(private storageService: StorageService) { + 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 + let data = await this.storageService.getHistoricalBars( + symbol, + startDate, + endDate, + resolution + ); + + // If no data found, generate mock data + if (!data || data.length === 0) { + logger.warn(`No historical data found for ${symbol}, generating mock data`); + data = this.generateMockBars(symbol, startDate, endDate, resolution); + } + + // Apply corporate actions + const adjustedData = await this.applyCorporateActions(symbol, data, startDate, endDate); + + // Quality checks + const cleanedData = this.performQualityChecks(symbol, adjustedData); + + // Convert to MarketData format + const marketData = this.convertToMarketData(symbol, cleanedData); + + 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 }); + } + } + + return result; + } + + async applyCorporateActions( + symbol: string, + data: HistoricalBar[], + startDate: Date, + endDate: Date + ): Promise { + // Load corporate actions for the period + const actions = await this.loadCorporateActions(symbol, startDate, endDate); + if (actions.length === 0) { + return data; + } + + // Sort actions by date (newest first) + actions.sort((a, b) => b.date.getTime() - a.date.getTime()); + + // Apply adjustments + return data.map(bar => { + const barDate = new Date(bar.timestamp); + const adjustedBar = { ...bar }; + + for (const action of actions) { + if (barDate < action.date) { + switch (action.type) { + case 'split': + if (action.factor) { + adjustedBar.open /= action.factor; + adjustedBar.high /= action.factor; + adjustedBar.low /= action.factor; + adjustedBar.close /= action.factor; + adjustedBar.volume *= action.factor; + } + break; + + case 'dividend': + if (action.amount) { + // Adjust for dividends (simplified) + const adjustment = 1 - action.amount / adjustedBar.close; + adjustedBar.open *= adjustment; + adjustedBar.high *= adjustment; + adjustedBar.low *= adjustment; + adjustedBar.close *= adjustment; + } + break; + } + } + } + + return adjustedBar; + }); + } + + performQualityChecks(symbol: string, data: HistoricalBar[]): HistoricalBar[] { + const cleaned: HistoricalBar[] = []; + + for (let i = 0; i < data.length; i++) { + const bar = at(data, i); + const prevBar = i > 0 ? data[i - 1] : null; + const issues: string[] = []; + + // Check for missing data + if (!bar.open || !bar.high || !bar.low || !bar.close || bar.volume === undefined) { + issues.push('Missing OHLCV data'); + } + + // Check for invalid prices + if (bar.low > bar.high) { + issues.push('Low > High'); + } + if (bar.open > bar.high || bar.open < bar.low) { + issues.push('Open outside High/Low range'); + } + if (bar.close > bar.high || bar.close < bar.low) { + issues.push('Close outside High/Low range'); + } + + // Check for zero or negative prices + if (bar.open <= 0 || bar.high <= 0 || bar.low <= 0 || bar.close <= 0) { + issues.push('Zero or negative prices'); + } + + // Check for extreme price movements (>20% in one bar) + if (prevBar) { + const priceChange = Math.abs((bar.close - prevBar.close) / prevBar.close); + if (priceChange > 0.2) { + issues.push(`Extreme price movement: ${(priceChange * 100).toFixed(1)}%`); + } + } + + // Check for volume spikes (>10x average) + if (i >= 20) { + const avgVolume = data.slice(i - 20, i).reduce((sum, b) => sum + b.volume, 0) / 20; + if (bar.volume > avgVolume * 10) { + issues.push('Volume spike detected'); + } + } + + // Handle issues + if (issues.length > 0) { + const severity = issues.some(issue => issue.includes('Missing') || issue.includes('Zero')) + ? 'error' + : 'warning'; + + this.dataQualityIssues.push({ + timestamp: new Date(bar.timestamp), + symbol, + issue: issues.join(', '), + severity, + details: bar, + }); + + // For errors, try to interpolate or skip + if (severity === 'error') { + if (prevBar && i < data.length - 1) { + // Interpolate from surrounding bars + const nextBar = at(data, i + 1); + cleaned.push({ + ...bar, + open: (prevBar.close + nextBar.open) / 2, + high: Math.max(prevBar.high, nextBar.high) * 0.9, + low: Math.min(prevBar.low, nextBar.low) * 1.1, + close: (prevBar.close + nextBar.close) / 2, + volume: (prevBar.volume + nextBar.volume) / 2, + interpolated: true, + }); + } + // Skip if we can't interpolate + continue; + } + } + + cleaned.push(bar); + } + + return cleaned; + } + + 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, + }, + })); + } + + private async loadCorporateActions( + symbol: string, + startDate: Date, + endDate: Date + ): Promise { + // Check cache first + const cached = this.corporateActions.get(symbol); + if (cached) { + return cached.filter(action => action.date >= startDate && action.date <= endDate); + } + + // In real implementation, load from database + // For now, return empty array + return []; + } + + 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 = []; + } + + private generateMockBars( + symbol: string, + startDate: Date, + endDate: Date, + resolution: string + ): HistoricalBar[] { + const bars: HistoricalBar[] = []; + const resolutionMs = DataManager.RESOLUTIONS[resolution]?.milliseconds || 86400000; // Default to 1 day + + let currentTime = startDate.getTime(); + const endTime = endDate.getTime(); + + // Base price varies by symbol + let basePrice = 100; + if (symbol === 'AAPL') { + basePrice = 150; + } else if (symbol === 'GOOGL') { + basePrice = 140; + } else if (symbol === 'MSFT') { + basePrice = 380; + } else if (symbol === 'TSLA') { + basePrice = 250; + } + + let price = basePrice; + + while (currentTime <= endTime) { + // Generate realistic intraday movement + const volatility = 0.02; // 2% daily volatility + const trend = 0.0001; // Slight upward trend + + // Random walk with trend + const changePercent = (Math.random() - 0.5) * volatility + trend; + price = price * (1 + changePercent); + + // Generate OHLC + const open = price; + const intraDayVolatility = volatility / 4; + const high = price * (1 + Math.random() * intraDayVolatility); + const low = price * (1 - Math.random() * intraDayVolatility); + const close = low + Math.random() * (high - low); + + // Volume with some randomness + const baseVolume = 10000000; // 10M shares + const volume = baseVolume * (0.5 + Math.random()); + + bars.push({ + symbol, + timestamp: new Date(currentTime), + open: Number(open.toFixed(2)), + high: Number(high.toFixed(2)), + low: Number(low.toFixed(2)), + close: Number(close.toFixed(2)), + volume: Math.floor(volume), + vwap: Number(((high + low + close) / 3).toFixed(2)), + }); + + currentTime += resolutionMs; + price = close; // Next bar opens at previous close + } + + return bars; + } +} diff --git a/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts b/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts index 3f6de01b..3fc53fc1 100644 --- a/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts +++ b/apps/stock/orchestrator/src/handlers/backtest/backtest.handler.ts @@ -1,121 +1,120 @@ -import { - BaseHandler, - Handler, - Operation, -} from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; -import type { OrchestratorServices } from '../../types'; - -const logger = getLogger('backtest-handler'); - -interface BacktestPayload { - backtestId: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config?: Record; -} - -interface CancelBacktestPayload { - backtestId: string; -} - -@Handler('orchestrator') -export class BacktestHandler extends BaseHandler { - - @Operation('run-backtest') - async runBacktest(payload: BacktestPayload) { - const { backtestId, strategy, symbols, startDate, endDate, initialCapital, config } = payload; - - logger.info('Starting backtest', { backtestId, strategy, symbolCount: symbols.length }); - - try { - // Update status in web-api (via Redis or direct DB update) - await this.updateBacktestStatus(backtestId, 'running'); - - // TODO: Call Rust core via NAPI bindings - // For now, we'll simulate the backtest - const results = await this.simulateBacktest({ - strategy, - symbols, - startDate, - endDate, - initialCapital, - config, - }); - - // Store results - await this.storeBacktestResults(backtestId, results); - - // Update status to completed - await this.updateBacktestStatus(backtestId, 'completed'); - - logger.info('Backtest completed', { backtestId }); - - return { success: true, backtestId, results }; - } catch (error) { - logger.error('Backtest failed', { backtestId, error }); - - await this.updateBacktestStatus(backtestId, 'failed', error.message); - - throw error; - } - } - - @Operation('cancel-backtest') - async cancelBacktest(payload: CancelBacktestPayload) { - const { backtestId } = payload; - - logger.info('Cancelling backtest', { backtestId }); - - // TODO: Implement actual cancellation logic - // For now, just update the status - await this.updateBacktestStatus(backtestId, 'cancelled'); - - return { success: true, backtestId }; - } - - private async updateBacktestStatus(backtestId: string, status: string, error?: string) { - // TODO: Update in MongoDB or notify web-api - logger.info('Updating backtest status', { backtestId, status, error }); - } - - private async storeBacktestResults(backtestId: string, results: any) { - // TODO: Store in MongoDB - logger.info('Storing backtest results', { backtestId }); - } - - private async simulateBacktest(params: Omit) { - // Simulate some processing time - await new Promise(resolve => setTimeout(resolve, 2000)); - - // Return mock results - return { - metrics: { - totalReturn: 0.15, - sharpeRatio: 1.2, - maxDrawdown: -0.08, - winRate: 0.55, - totalTrades: 150, - profitFactor: 1.8, - }, - equity: [ - { date: params.startDate, value: params.initialCapital }, - { date: params.endDate, value: params.initialCapital * 1.15 }, - ], - trades: [ - { - symbol: params.symbols[0], - entryDate: params.startDate, - exitDate: params.endDate, - entryPrice: 100, - exitPrice: 115, - quantity: 100, - pnl: 1500, - }, - ], - }; - } -} \ No newline at end of file +import { BaseHandler, Handler, Operation } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; +import type { OrchestratorServices } from '../../types'; + +const logger = getLogger('backtest-handler'); + +interface BacktestPayload { + backtestId: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config?: Record; +} + +interface CancelBacktestPayload { + backtestId: string; +} + +@Handler('orchestrator') +export class BacktestHandler extends BaseHandler { + @Operation('run-backtest') + async runBacktest(payload: BacktestPayload) { + const { backtestId, strategy, symbols, startDate, endDate, initialCapital, config } = payload; + + logger.info('Starting backtest', { backtestId, strategy, symbolCount: symbols.length }); + + try { + // Update status in web-api (via Redis or direct DB update) + await this.updateBacktestStatus(backtestId, 'running'); + + // TODO: Call Rust core via NAPI bindings + // For now, we'll simulate the backtest + const results = await this.simulateBacktest({ + strategy, + symbols, + startDate, + endDate, + initialCapital, + config, + }); + + // Store results + await this.storeBacktestResults(backtestId, results); + + // Update status to completed + await this.updateBacktestStatus(backtestId, 'completed'); + + logger.info('Backtest completed', { backtestId }); + + return { success: true, backtestId, results }; + } catch (error) { + logger.error('Backtest failed', { backtestId, error }); + + await this.updateBacktestStatus( + backtestId, + 'failed', + error instanceof Error ? error.message : String(error) + ); + + throw error; + } + } + + @Operation('cancel-backtest') + async cancelBacktest(payload: CancelBacktestPayload) { + const { backtestId } = payload; + + logger.info('Cancelling backtest', { backtestId }); + + // TODO: Implement actual cancellation logic + // For now, just update the status + await this.updateBacktestStatus(backtestId, 'cancelled'); + + return { success: true, backtestId }; + } + + private async updateBacktestStatus(backtestId: string, status: string, error?: string) { + // TODO: Update in MongoDB or notify web-api + logger.info('Updating backtest status', { backtestId, status, error }); + } + + private async storeBacktestResults(backtestId: string, _results: unknown) { + // TODO: Store in MongoDB + logger.info('Storing backtest results', { backtestId }); + } + + private async simulateBacktest(params: Omit) { + // Simulate some processing time + await new Promise(resolve => setTimeout(resolve, 2000)); + + // Return mock results + return { + metrics: { + totalReturn: 0.15, + sharpeRatio: 1.2, + maxDrawdown: -0.08, + winRate: 0.55, + totalTrades: 150, + profitFactor: 1.8, + }, + equity: [ + { date: params.startDate, value: params.initialCapital }, + { date: params.endDate, value: params.initialCapital * 1.15 }, + ], + trades: [ + { + symbol: params.symbols[0], + entryDate: params.startDate, + exitDate: params.endDate, + entryPrice: 100, + exitPrice: 115, + quantity: 100, + pnl: 1500, + }, + ], + }; + } +} diff --git a/apps/stock/orchestrator/src/index.ts b/apps/stock/orchestrator/src/index.ts index 49599b32..1c8a3108 100644 --- a/apps/stock/orchestrator/src/index.ts +++ b/apps/stock/orchestrator/src/index.ts @@ -1,150 +1,161 @@ -/** - * Stock Bot Orchestrator Service - * Coordinates between Rust core, data feeds, and analytics - */ - -import { getLogger } from '@stock-bot/logger'; -import { initializeStockConfig } from '@stock-bot/stock-config'; -import { Hono } from 'hono'; -import { cors } from 'hono/cors'; -import { createRoutes } from './routes/create-routes'; -import { createContainer } from './simple-container'; - -// Initialize configuration with service-specific overrides -const config = initializeStockConfig('orchestrator'); -const logger = getLogger('orchestrator'); - -// Get service-specific config -const serviceConfig = config.services?.orchestrator || { - port: 2004, - defaultMode: 'paper', - paperTradingCapital: 100000, - enableWebSocket: true -}; - -const PORT = serviceConfig.port; - -// Log the configuration -logger.info('Service configuration:', { - port: PORT, - defaultMode: serviceConfig.defaultMode, - enableWebSocket: serviceConfig.enableWebSocket, - backtesting: serviceConfig.backtesting, - strategies: serviceConfig.strategies -}); - -async function main() { - let server: any; // Declare server in outer scope for shutdown - - try { - // Initialize container with all services using configuration - const services = await createContainer(config); - - // Initialize Hono app - const app = new Hono(); - - // CORS middleware - use config for origins - app.use('*', cors({ - origin: config.services?.webApi?.cors?.origins || ['http://localhost:4200', 'http://localhost:3000', 'http://localhost:5173', 'http://localhost:5174'], - allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], - allowHeaders: ['Content-Type', 'Authorization'], - credentials: config.services?.webApi?.cors?.credentials ?? true, - })); - - // Logging middleware - app.use('*', async (c, next) => { - const start = Date.now(); - await next(); - const ms = Date.now() - start; - services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`); - }); - - // Create and mount routes (without Socket.IO for now) - const routes = createRoutes(services); - app.route('/', routes); - - // Start Bun server - try { - server = Bun.serve({ - port: PORT, - hostname: '0.0.0.0', // Explicitly bind to all interfaces - fetch: async (req) => { - services.logger.debug(`Incoming request: ${req.method} ${req.url}`); - try { - const response = await app.fetch(req); - return response; - } catch (error) { - services.logger.error('Request handling error:', error); - return new Response('Internal Server Error', { status: 500 }); - } - }, - error: (error) => { - services.logger.error('Server error:', error); - return new Response('Internal Server Error', { status: 500 }); - }, - }); - - services.logger.info(`Orchestrator service started on port ${server.port}`); - services.logger.info(`Server hostname: ${server.hostname}`); - services.logger.info(`Server URL: http://${server.hostname}:${server.port}`); - - // Test that server is actually listening - setTimeout(async () => { - try { - const testResponse = await fetch(`http://localhost:${server.port}/health`); - services.logger.info(`Server self-test: ${testResponse.status} ${testResponse.statusText}`); - } catch (error) { - services.logger.error('Server self-test failed:', error); - } - }, 1000); - } catch (error) { - services.logger.error('Failed to start Bun server:', error); - throw error; - } - services.logger.info('Service metadata:', { - version: '1.0.0', - description: 'Trading System Orchestrator', - defaultMode: serviceConfig.defaultMode, - enableWebSocket: serviceConfig.enableWebSocket, - endpoints: { - health: '/health', - orders: '/api/orders', - positions: '/api/positions', - analytics: '/api/analytics', - backtest: '/api/backtest', - } - }); - - // Note: Socket.IO with Bun requires a different setup - // For now, we'll disable Socket.IO to avoid the CORS error - if (serviceConfig.enableWebSocket) { - services.logger.info('WebSocket support is enabled but Socket.IO integration with Bun requires additional setup'); - } - - // Graceful shutdown - process.on('SIGINT', async () => { - services.logger.info('Orchestrator service shutting down...'); - - // Cleanup any active trading sessions - const modeManager = services.custom?.ModeManager; - if (modeManager) { - await modeManager.shutdown(); - } - - if (server) { - server.stop(); - } - process.exit(0); - }); - - } catch (error) { - logger.error('Failed to start orchestrator service:', error); - process.exit(1); - } -} - -// Start the service -main().catch(error => { - logger.error('Unhandled error:', error); - process.exit(1); -}); \ No newline at end of file +/** + * Stock Bot Orchestrator Service + * Coordinates between Rust core, data feeds, and analytics + */ + +import { Hono } from 'hono'; +import { cors } from 'hono/cors'; +import { getLogger } from '@stock-bot/logger'; +import { initializeStockConfig } from '@stock-bot/stock-config'; +import { createRoutes } from './routes/create-routes'; +import { createContainer } from './simple-container'; + +// Initialize configuration with service-specific overrides +const config = initializeStockConfig('orchestrator'); +const logger = getLogger('orchestrator'); + +// Get service-specific config +const serviceConfig = config.services?.orchestrator || { + port: 2004, + defaultMode: 'paper', + paperTradingCapital: 100000, + enableWebSocket: true, +}; + +const PORT = serviceConfig.port; + +// Log the configuration +logger.info('Service configuration:', { + port: PORT, + defaultMode: serviceConfig.defaultMode, + enableWebSocket: serviceConfig.enableWebSocket, + backtesting: serviceConfig.backtesting, + strategies: serviceConfig.strategies, +}); + +async function main() { + let server: ReturnType | undefined; // Declare server in outer scope for shutdown + + try { + // Initialize container with all services using configuration + const services = await createContainer(config); + + // Initialize Hono app + const app = new Hono(); + + // CORS middleware - use config for origins + app.use( + '*', + cors({ + origin: config.services?.webApi?.cors?.origins || [ + 'http://localhost:4200', + 'http://localhost:3000', + 'http://localhost:5173', + 'http://localhost:5174', + ], + allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + allowHeaders: ['Content-Type', 'Authorization'], + credentials: config.services?.webApi?.cors?.credentials ?? true, + }) + ); + + // Logging middleware + app.use('*', async (c, next) => { + const start = Date.now(); + await next(); + const ms = Date.now() - start; + services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`); + }); + + // Create and mount routes (without Socket.IO for now) + const routes = createRoutes(services); + app.route('/', routes); + + // Start Bun server + try { + server = Bun.serve({ + port: PORT, + hostname: '0.0.0.0', // Explicitly bind to all interfaces + fetch: async req => { + services.logger.debug(`Incoming request: ${req.method} ${req.url}`); + try { + const response = await app.fetch(req); + return response; + } catch (error) { + services.logger.error('Request handling error:', error); + return new Response('Internal Server Error', { status: 500 }); + } + }, + error: error => { + services.logger.error('Server error:', error); + return new Response('Internal Server Error', { status: 500 }); + }, + }); + + services.logger.info(`Orchestrator service started on port ${server?.port ?? PORT}`); + services.logger.info(`Server hostname: ${server.hostname}`); + services.logger.info(`Server URL: http://${server.hostname}:${server.port}`); + + // Test that server is actually listening + setTimeout(async () => { + try { + const testResponse = await fetch(`http://localhost:${server?.port ?? PORT}/health`); + services.logger.info( + `Server self-test: ${testResponse.status} ${testResponse.statusText}` + ); + } catch (error) { + services.logger.error('Server self-test failed:', error); + } + }, 1000); + } catch (error) { + services.logger.error('Failed to start Bun server:', error); + throw error; + } + services.logger.info('Service metadata:', { + version: '1.0.0', + description: 'Trading System Orchestrator', + defaultMode: serviceConfig.defaultMode, + enableWebSocket: serviceConfig.enableWebSocket, + endpoints: { + health: '/health', + orders: '/api/orders', + positions: '/api/positions', + analytics: '/api/analytics', + backtest: '/api/backtest', + }, + }); + + // Note: Socket.IO with Bun requires a different setup + // For now, we'll disable Socket.IO to avoid the CORS error + if (serviceConfig.enableWebSocket) { + services.logger.info( + 'WebSocket support is enabled but Socket.IO integration with Bun requires additional setup' + ); + } + + // Graceful shutdown + process.on('SIGINT', async () => { + services.logger.info('Orchestrator service shutting down...'); + + // Cleanup any active trading sessions + const modeManager = services.custom?.ModeManager; + if (modeManager) { + await modeManager.shutdown(); + } + + if (server) { + server.stop(); + } + process.exit(0); + }); + } catch (error) { + logger.error('Failed to start orchestrator service:', error); + process.exit(1); + } +} + +// Start the service +main().catch(error => { + logger.error('Unhandled error:', error); + process.exit(1); +}); diff --git a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts b/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts index c98d3aa5..ec25a754 100644 --- a/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts +++ b/apps/stock/orchestrator/src/indicators/TechnicalAnalysis.ts @@ -1,305 +1,342 @@ -import { BollingerBandsResult, IncrementalEMA, IncrementalRSI, IncrementalSMA, MacdResult, StochasticResult, TechnicalIndicators } from '@stock-bot/engine'; - -/** - * 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 = series1[series1.length - 2]; - const curr1 = series1[series1.length - 1]; - const prev2 = series2[series2.length - 2]; - const curr2 = 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 = series1[series1.length - 2]; - const curr1 = series1[series1.length - 1]; - const prev2 = series2[series2.length - 2]; - const curr2 = 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(); - } - } - - 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 = 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' - }; - } -} \ No newline at end of file +import { + IncrementalEMA, + IncrementalRSI, + IncrementalSMA, + TechnicalIndicators, +} from '@stock-bot/engine'; +import { at } from '@stock-bot/utils'; + +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/PaperTradingManager.ts b/apps/stock/orchestrator/src/paper/PaperTradingManager.ts index 07b0c873..ba9a7584 100644 --- a/apps/stock/orchestrator/src/paper/PaperTradingManager.ts +++ b/apps/stock/orchestrator/src/paper/PaperTradingManager.ts @@ -1,374 +1,384 @@ -import { EventEmitter } from 'events'; -import { IServiceContainer } from '@stock-bot/di'; -import { OrderRequest, Position } from '../types'; -import { StorageService } from '../services/StorageService'; -import { MarketDataService } from '../services/MarketDataService'; -import { ExecutionService } from '../services/ExecutionService'; - -interface VirtualAccount { - balance: number; - buyingPower: number; - positions: Map; - orders: Map; - trades: VirtualTrade[]; - equity: number; - marginUsed: number; -} - -interface VirtualPosition { - symbol: string; - quantity: number; - averagePrice: number; - marketValue: number; - unrealizedPnl: number; - realizedPnl: number; -} - -interface VirtualOrder { - id: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - orderType: string; - limitPrice?: number; - status: string; - submittedAt: Date; -} - -interface VirtualTrade { - orderId: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - timestamp: Date; - pnl?: number; -} - -export class PaperTradingManager extends EventEmitter { - private account: VirtualAccount; - private marketPrices = new Map(); - private readonly COMMISSION_RATE = 0.001; // 0.1% - private readonly MARGIN_REQUIREMENT = 0.25; // 25% margin requirement - private container: IServiceContainer; - - constructor( - container: IServiceContainer, - private storageService: StorageService, - private marketDataService: MarketDataService, - private executionService: ExecutionService, - initialBalance: number = 100000 - ) { - super(); - this.container = container; - - this.account = { - balance: initialBalance, - buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), - positions: new Map(), - orders: new Map(), - trades: [], - equity: initialBalance, - marginUsed: 0 - }; - - this.setupEventListeners(); - } - - private setupEventListeners(): void { - // Listen for market data updates to track prices - // In real implementation, would connect to market data service - } - - updateMarketPrice(symbol: string, bid: number, ask: number): void { - this.marketPrices.set(symbol, { bid, ask }); - - // Update position values - const position = this.account.positions.get(symbol); - if (position) { - const midPrice = (bid + ask) / 2; - position.marketValue = position.quantity * midPrice; - position.unrealizedPnl = position.quantity * (midPrice - position.averagePrice); - } - - // Update account equity - this.updateAccountEquity(); - } - - async executeOrder(order: OrderRequest): Promise { - // Validate order - const validation = this.validateOrder(order); - if (!validation.valid) { - return { - status: 'rejected', - reason: validation.reason - }; - } - - // Check buying power - const requiredCapital = this.calculateRequiredCapital(order); - if (requiredCapital > this.account.buyingPower) { - return { - status: 'rejected', - reason: 'Insufficient buying power' - }; - } - - // Create virtual order - const virtualOrder: VirtualOrder = { - id: `paper_${Date.now()}`, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - status: 'pending', - submittedAt: new Date() - }; - - this.account.orders.set(virtualOrder.id, virtualOrder); - - // Simulate order execution based on type - if (order.orderType === 'market') { - await this.executeMarketOrder(virtualOrder); - } else if (order.orderType === 'limit') { - // Limit orders would be checked periodically - virtualOrder.status = 'accepted'; - } - - return { - orderId: virtualOrder.id, - status: virtualOrder.status - }; - } - - private async executeMarketOrder(order: VirtualOrder): Promise { - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) { - order.status = 'rejected'; - this.emit('orderUpdate', { - orderId: order.id, - status: 'rejected', - reason: 'No market data available' - }); - return; - } - - // Simulate realistic fill with slippage - const fillPrice = order.side === 'buy' - ? marketPrice.ask * (1 + this.getSlippage(order.quantity)) - : marketPrice.bid * (1 - this.getSlippage(order.quantity)); - - const commission = fillPrice * order.quantity * this.COMMISSION_RATE; - - // Create trade - const trade: VirtualTrade = { - orderId: order.id, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - price: fillPrice, - commission, - timestamp: new Date() - }; - - // Update position - this.updatePosition(trade); - - // Update account - const totalCost = (fillPrice * order.quantity) + commission; - if (order.side === 'buy') { - this.account.balance -= totalCost; - } else { - this.account.balance += (fillPrice * order.quantity) - commission; - } - - // Record trade - this.account.trades.push(trade); - order.status = 'filled'; - - // Update buying power and margin - this.updateBuyingPower(); - - // Emit events - this.emit('fill', { - orderId: order.id, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - price: fillPrice, - commission, - timestamp: new Date() - }); - - this.emit('orderUpdate', { - orderId: order.id, - status: 'filled' - }); - } - - private updatePosition(trade: VirtualTrade): void { - const position = this.account.positions.get(trade.symbol) || { - symbol: trade.symbol, - quantity: 0, - averagePrice: 0, - marketValue: 0, - unrealizedPnl: 0, - realizedPnl: 0 - }; - - const oldQuantity = position.quantity; - const oldAvgPrice = position.averagePrice; - - if (trade.side === 'buy') { - // Adding to position - const newQuantity = oldQuantity + trade.quantity; - position.averagePrice = oldQuantity >= 0 - ? ((oldQuantity * oldAvgPrice) + (trade.quantity * trade.price)) / newQuantity - : trade.price; - position.quantity = newQuantity; - } else { - // Reducing position - const newQuantity = oldQuantity - trade.quantity; - - if (oldQuantity > 0) { - // Realize P&L on closed portion - const realizedPnl = trade.quantity * (trade.price - oldAvgPrice) - trade.commission; - position.realizedPnl += realizedPnl; - trade.pnl = realizedPnl; - } - - position.quantity = newQuantity; - - if (Math.abs(newQuantity) < 0.0001) { - // Position closed - this.account.positions.delete(trade.symbol); - return; - } - } - - this.account.positions.set(trade.symbol, position); - } - - private validateOrder(order: OrderRequest): { valid: boolean; reason?: string } { - if (order.quantity <= 0) { - return { valid: false, reason: 'Invalid quantity' }; - } - - if (order.orderType === 'limit' && !order.limitPrice) { - return { valid: false, reason: 'Limit price required for limit orders' }; - } - - return { valid: true }; - } - - private calculateRequiredCapital(order: OrderRequest): number { - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) return Infinity; - - const price = order.side === 'buy' ? marketPrice.ask : marketPrice.bid; - const notional = price * order.quantity; - const commission = notional * this.COMMISSION_RATE; - const marginRequired = notional * this.MARGIN_REQUIREMENT; - - return order.side === 'buy' ? marginRequired + commission : commission; - } - - private updateBuyingPower(): void { - let totalMarginUsed = 0; - - for (const position of this.account.positions.values()) { - totalMarginUsed += Math.abs(position.marketValue) * this.MARGIN_REQUIREMENT; - } - - this.account.marginUsed = totalMarginUsed; - this.account.buyingPower = (this.account.equity - totalMarginUsed) / this.MARGIN_REQUIREMENT; - } - - private updateAccountEquity(): void { - let totalUnrealizedPnl = 0; - - for (const position of this.account.positions.values()) { - totalUnrealizedPnl += position.unrealizedPnl; - } - - this.account.equity = this.account.balance + totalUnrealizedPnl; - } - - private getSlippage(quantity: number): number { - // Simple slippage model - increases with order size - const baseSlippage = 0.0001; // 1 basis point - const sizeImpact = quantity / 10000; // Impact increases with size - return baseSlippage + (sizeImpact * 0.0001); - } - - checkLimitOrders(): void { - // Called periodically to check if limit orders can be filled - for (const [orderId, order] of this.account.orders) { - if (order.status !== 'accepted' || order.orderType !== 'limit') continue; - - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) continue; - - const canFill = order.side === 'buy' - ? marketPrice.ask <= order.limitPrice! - : marketPrice.bid >= order.limitPrice!; - - if (canFill) { - this.executeMarketOrder(order); - } - } - } - - getAccount(): VirtualAccount { - return { ...this.account }; - } - - getPosition(symbol: string): VirtualPosition | undefined { - return this.account.positions.get(symbol); - } - - getAllPositions(): VirtualPosition[] { - return Array.from(this.account.positions.values()); - } - - getPerformanceMetrics(): any { - const totalTrades = this.account.trades.length; - const winningTrades = this.account.trades.filter(t => t.pnl && t.pnl > 0); - const losingTrades = this.account.trades.filter(t => t.pnl && t.pnl < 0); - - const totalPnl = this.account.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); - const totalCommission = this.account.trades.reduce((sum, t) => sum + t.commission, 0); - - return { - totalTrades, - winningTrades: winningTrades.length, - losingTrades: losingTrades.length, - winRate: totalTrades > 0 ? (winningTrades.length / totalTrades) * 100 : 0, - totalPnl, - totalCommission, - netPnl: totalPnl - totalCommission, - currentEquity: this.account.equity, - currentPositions: this.account.positions.size - }; - } - - reset(): void { - const initialBalance = this.account.balance + - Array.from(this.account.positions.values()) - .reduce((sum, p) => sum + p.marketValue, 0); - - this.account = { - balance: initialBalance, - buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), - positions: new Map(), - orders: new Map(), - trades: [], - equity: initialBalance, - marginUsed: 0 - }; - - this.container.logger.info('Paper trading account reset'); - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { defined } from '@stock-bot/invariants'; +import { ExecutionService } from '../services/ExecutionService'; +import { MarketDataService } from '../services/MarketDataService'; +import { StorageService } from '../services/StorageService'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { type OrderRequest } from '../types'; + +interface VirtualAccount { + balance: number; + buyingPower: number; + positions: Map; + orders: Map; + trades: VirtualTrade[]; + equity: number; + marginUsed: number; +} + +interface VirtualPosition { + symbol: string; + quantity: number; + averagePrice: number; + marketValue: number; + unrealizedPnl: number; + realizedPnl: number; +} + +interface VirtualOrder { + id: string; + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + orderType: string; + limitPrice?: number; + status: string; + submittedAt: Date; +} + +interface VirtualTrade { + orderId: string; + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + price: number; + commission: number; + timestamp: Date; + pnl?: number; +} + +export class PaperTradingManager extends EventEmitter { + private account: VirtualAccount; + private marketPrices = new Map(); + private readonly COMMISSION_RATE = 0.001; // 0.1% + private readonly MARGIN_REQUIREMENT = 0.25; // 25% margin requirement + private container: IServiceContainer; + + constructor( + container: IServiceContainer, + private storageService: StorageService, + private marketDataService: MarketDataService, + private executionService: ExecutionService, + initialBalance: number = 100000 + ) { + super(); + this.container = container; + + this.account = { + balance: initialBalance, + buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), + positions: new Map(), + orders: new Map(), + trades: [], + equity: initialBalance, + marginUsed: 0, + }; + + this.setupEventListeners(); + } + + private setupEventListeners(): void { + // Listen for market data updates to track prices + // In real implementation, would connect to market data service + } + + updateMarketPrice(symbol: string, bid: number, ask: number): void { + this.marketPrices.set(symbol, { bid, ask }); + + // Update position values + const position = this.account.positions.get(symbol); + if (position) { + const midPrice = (bid + ask) / 2; + position.marketValue = position.quantity * midPrice; + position.unrealizedPnl = position.quantity * (midPrice - position.averagePrice); + } + + // Update account equity + this.updateAccountEquity(); + } + + async executeOrder(order: OrderRequest) { + // Validate order + const validation = this.validateOrder(order); + if (!validation.valid) { + return { + status: 'rejected', + reason: validation.reason, + }; + } + + // Check buying power + const requiredCapital = this.calculateRequiredCapital(order); + if (requiredCapital > this.account.buyingPower) { + return { + status: 'rejected', + reason: 'Insufficient buying power', + }; + } + + // Create virtual order + const virtualOrder: VirtualOrder = { + id: `paper_${Date.now()}`, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + orderType: order.orderType, + limitPrice: order.limitPrice, + status: 'pending', + submittedAt: new Date(), + }; + + this.account.orders.set(virtualOrder.id, virtualOrder); + + // Simulate order execution based on type + if (order.orderType === 'market') { + await this.executeMarketOrder(virtualOrder); + } else if (order.orderType === 'limit') { + // Limit orders would be checked periodically + virtualOrder.status = 'accepted'; + } + + return { + orderId: virtualOrder.id, + status: virtualOrder.status, + }; + } + + private async executeMarketOrder(order: VirtualOrder): Promise { + const marketPrice = this.marketPrices.get(order.symbol); + if (!marketPrice) { + order.status = 'rejected'; + this.emit('orderUpdate', { + orderId: order.id, + status: 'rejected', + reason: 'No market data available', + }); + return; + } + + // Simulate realistic fill with slippage + const fillPrice = + order.side === 'buy' + ? marketPrice.ask * (1 + this.getSlippage(order.quantity)) + : marketPrice.bid * (1 - this.getSlippage(order.quantity)); + + const commission = fillPrice * order.quantity * this.COMMISSION_RATE; + + // Create trade + const trade: VirtualTrade = { + orderId: order.id, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + price: fillPrice, + commission, + timestamp: new Date(), + }; + + // Update position + this.updatePosition(trade); + + // Update account + const totalCost = fillPrice * order.quantity + commission; + if (order.side === 'buy') { + this.account.balance -= totalCost; + } else { + this.account.balance += fillPrice * order.quantity - commission; + } + + // Record trade + this.account.trades.push(trade); + order.status = 'filled'; + + // Update buying power and margin + this.updateBuyingPower(); + + // Emit events + this.emit('fill', { + orderId: order.id, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + price: fillPrice, + commission, + timestamp: new Date(), + }); + + this.emit('orderUpdate', { + orderId: order.id, + status: 'filled', + }); + } + + private updatePosition(trade: VirtualTrade): void { + const position = this.account.positions.get(trade.symbol) || { + symbol: trade.symbol, + quantity: 0, + averagePrice: 0, + marketValue: 0, + unrealizedPnl: 0, + realizedPnl: 0, + }; + + const oldQuantity = position.quantity; + const oldAvgPrice = position.averagePrice; + + if (trade.side === 'buy') { + // Adding to position + const newQuantity = oldQuantity + trade.quantity; + position.averagePrice = + oldQuantity >= 0 + ? (oldQuantity * oldAvgPrice + trade.quantity * trade.price) / newQuantity + : trade.price; + position.quantity = newQuantity; + } else { + // Reducing position + const newQuantity = oldQuantity - trade.quantity; + + if (oldQuantity > 0) { + // Realize P&L on closed portion + const realizedPnl = trade.quantity * (trade.price - oldAvgPrice) - trade.commission; + position.realizedPnl += realizedPnl; + trade.pnl = realizedPnl; + } + + position.quantity = newQuantity; + + if (Math.abs(newQuantity) < 0.0001) { + // Position closed + this.account.positions.delete(trade.symbol); + return; + } + } + + this.account.positions.set(trade.symbol, position); + } + + private validateOrder(order: OrderRequest): { valid: boolean; reason?: string } { + if (order.quantity <= 0) { + return { valid: false, reason: 'Invalid quantity' }; + } + + if (order.orderType === 'limit' && !order.limitPrice) { + return { valid: false, reason: 'Limit price required for limit orders' }; + } + + return { valid: true }; + } + + private calculateRequiredCapital(order: OrderRequest): number { + const marketPrice = this.marketPrices.get(order.symbol); + if (!marketPrice) { + return Infinity; + } + + const price = order.side === 'buy' ? marketPrice.ask : marketPrice.bid; + const notional = price * order.quantity; + const commission = notional * this.COMMISSION_RATE; + const marginRequired = notional * this.MARGIN_REQUIREMENT; + + return order.side === 'buy' ? marginRequired + commission : commission; + } + + private updateBuyingPower(): void { + let totalMarginUsed = 0; + + for (const position of this.account.positions.values()) { + totalMarginUsed += Math.abs(position.marketValue) * this.MARGIN_REQUIREMENT; + } + + this.account.marginUsed = totalMarginUsed; + this.account.buyingPower = (this.account.equity - totalMarginUsed) / this.MARGIN_REQUIREMENT; + } + + private updateAccountEquity(): void { + let totalUnrealizedPnl = 0; + + for (const position of this.account.positions.values()) { + totalUnrealizedPnl += position.unrealizedPnl; + } + + this.account.equity = this.account.balance + totalUnrealizedPnl; + } + + private getSlippage(quantity: number): number { + // Simple slippage model - increases with order size + const baseSlippage = 0.0001; // 1 basis point + const sizeImpact = quantity / 10000; // Impact increases with size + return baseSlippage + sizeImpact * 0.0001; + } + + checkLimitOrders(): void { + // Called periodically to check if limit orders can be filled + for (const [_orderId, order] of this.account.orders) { + if (order.status !== 'accepted' || order.orderType !== 'limit') { + continue; + } + + const marketPrice = this.marketPrices.get(order.symbol); + if (!marketPrice) { + continue; + } + + const canFill = + order.side === 'buy' + ? marketPrice.ask <= defined(order.limitPrice) + : marketPrice.bid >= defined(order.limitPrice); + + if (canFill) { + this.executeMarketOrder(order); + } + } + } + + getAccount(): VirtualAccount { + return { ...this.account }; + } + + getPosition(symbol: string): VirtualPosition | undefined { + return this.account.positions.get(symbol); + } + + getAllPositions(): VirtualPosition[] { + return Array.from(this.account.positions.values()); + } + + getPerformanceMetrics() { + const totalTrades = this.account.trades.length; + const winningTrades = this.account.trades.filter(t => t.pnl && t.pnl > 0); + const losingTrades = this.account.trades.filter(t => t.pnl && t.pnl < 0); + + const totalPnl = this.account.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); + const totalCommission = this.account.trades.reduce((sum, t) => sum + t.commission, 0); + + return { + totalTrades, + winningTrades: winningTrades.length, + losingTrades: losingTrades.length, + winRate: totalTrades > 0 ? (winningTrades.length / totalTrades) * 100 : 0, + totalPnl, + totalCommission, + netPnl: totalPnl - totalCommission, + currentEquity: this.account.equity, + currentPositions: this.account.positions.size, + }; + } + + reset(): void { + const initialBalance = + this.account.balance + + Array.from(this.account.positions.values()).reduce((sum, p) => sum + p.marketValue, 0); + + this.account = { + balance: initialBalance, + buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), + positions: new Map(), + orders: new Map(), + trades: [], + equity: initialBalance, + marginUsed: 0, + }; + + this.container.logger.info('Paper trading account reset'); + } +} diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index 24daed88..9b93dea2 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -1,52 +1,49 @@ -import { Hono } from 'hono'; -import { IServiceContainer } from '@stock-bot/di'; -import { createOrderRoutes } from '../api/rest/orders'; -import { createPositionRoutes } from '../api/rest/positions'; -import { createAnalyticsRoutes } from '../api/rest/analytics'; -import { createBacktestRoutes } from '../api/rest/backtest'; -import { setupWebSocketHandlers } from '../api/websocket'; -import { Server as SocketIOServer } from 'socket.io'; - -/** - * Create all routes for the orchestrator service - */ -export function createRoutes( - services: IServiceContainer, - io?: SocketIOServer -): Hono { - const app = new Hono(); - services.logger.info('Creating orchestrator routes'); - - // Health check with mode status - app.get('/health', (c) => { - const modeManager = services.custom?.ModeManager; - return c.json({ - status: 'healthy', - service: 'orchestrator', - mode: modeManager?.getCurrentMode() || 'unknown', - timestamp: new Date().toISOString() - }); - }); - - // Mount REST API routes - app.route('/api/orders', createOrderRoutes(services)); - app.route('/api/positions', createPositionRoutes(services)); - app.route('/api/analytics', createAnalyticsRoutes(services)); - app.route('/api/backtest', createBacktestRoutes(services)); - - // Setup WebSocket handlers if Socket.IO is provided - if (io) { - setupWebSocketHandlers(io, services); - services.logger.info('WebSocket handlers configured'); - } - - // Add request logging middleware - app.use('*', async (c, next) => { - const start = Date.now(); - await next(); - const ms = Date.now() - start; - services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`); - }); - - return app; -} \ No newline at end of file +import { Hono } from 'hono'; +import { Server as SocketIOServer } from 'socket.io'; +import { createAnalyticsRoutes } from '../api/rest/analytics'; +import { createBacktestRoutes } from '../api/rest/backtest'; +import { createOrderRoutes } from '../api/rest/orders'; +import { createPositionRoutes } from '../api/rest/positions'; +import { setupWebSocketHandlers } from '../api/websocket'; +import type { OrchestratorServices as IServiceContainer } from '../types'; + +/** + * Create all routes for the orchestrator service + */ +export function createRoutes(services: IServiceContainer, io?: SocketIOServer): Hono { + const app = new Hono(); + services.logger.info('Creating orchestrator routes'); + + // Health check with mode status + app.get('/health', c => { + const modeManager = services.custom?.ModeManager; + return c.json({ + status: 'healthy', + service: 'orchestrator', + mode: modeManager?.getCurrentMode() || 'unknown', + timestamp: new Date().toISOString(), + }); + }); + + // Mount REST API routes + app.route('/api/orders', createOrderRoutes(services)); + app.route('/api/positions', createPositionRoutes(services)); + app.route('/api/analytics', createAnalyticsRoutes(services)); + app.route('/api/backtest', createBacktestRoutes(services)); + + // Setup WebSocket handlers if Socket.IO is provided + if (io) { + setupWebSocketHandlers(io, services); + services.logger.info('WebSocket handlers configured'); + } + + // Add request logging middleware + app.use('*', async (c, next) => { + const start = Date.now(); + await next(); + const ms = Date.now() - start; + services.logger.debug(`${c.req.method} ${c.req.url} - ${ms}ms`); + }); + + return app; +} diff --git a/apps/stock/orchestrator/src/services/AnalyticsService.ts b/apps/stock/orchestrator/src/services/AnalyticsService.ts index cd67162b..dc2d4e32 100644 --- a/apps/stock/orchestrator/src/services/AnalyticsService.ts +++ b/apps/stock/orchestrator/src/services/AnalyticsService.ts @@ -1,214 +1,228 @@ -import axios from 'axios'; -import { IServiceContainer } from '@stock-bot/di'; -import { PerformanceMetrics, RiskMetrics } from '../types'; -import { StorageService } from './StorageService'; - -interface OptimizationParams { - returns: number[][]; - constraints?: { - minWeight?: number; - maxWeight?: number; - targetReturn?: number; - maxRisk?: number; - }; -} - -interface PortfolioWeights { - symbols: string[]; - weights: number[]; - expectedReturn: number; - expectedRisk: number; - sharpeRatio: number; -} - -export class AnalyticsService { - private analyticsUrl: string; - private cache = new Map(); - private readonly CACHE_TTL_MS = 60000; // 1 minute cache - private container: IServiceContainer; - private storageService: StorageService; - - constructor(container: IServiceContainer, storageService: StorageService) { - this.container = container; - this.storageService = storageService; - this.analyticsUrl = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003'; - } - - async getPerformanceMetrics( - portfolioId: string, - startDate: Date, - endDate: Date - ): Promise { - const cacheKey = `perf_${portfolioId}_${startDate.toISOString()}_${endDate.toISOString()}`; - const cached = this.getFromCache(cacheKey); - if (cached) return cached; - - try { - const response = await axios.get(`${this.analyticsUrl}/analytics/performance/${portfolioId}`, { - params: { - start_date: startDate.toISOString(), - end_date: endDate.toISOString() - } - }); - - const metrics = response.data as PerformanceMetrics; - this.setCache(cacheKey, metrics); - return metrics; - } catch (error) { - this.container.logger.error('Error fetching performance metrics:', error); - // Return default metrics if analytics service is unavailable - return this.getDefaultPerformanceMetrics(); - } - } - - async optimizePortfolio(params: OptimizationParams): Promise { - try { - const response = await axios.post(`${this.analyticsUrl}/optimize/portfolio`, params); - return response.data as PortfolioWeights; - } catch (error) { - this.container.logger.error('Error optimizing portfolio:', error); - // Return equal weights as fallback - return this.getEqualWeights(params.returns[0].length); - } - } - - async getRiskMetrics(portfolioId: string): Promise { - const cacheKey = `risk_${portfolioId}`; - const cached = this.getFromCache(cacheKey); - if (cached) return cached; - - try { - const response = await axios.get(`${this.analyticsUrl}/analytics/risk/${portfolioId}`); - const metrics = response.data as RiskMetrics; - this.setCache(cacheKey, metrics); - return metrics; - } catch (error) { - this.container.logger.error('Error fetching risk metrics:', error); - return this.getDefaultRiskMetrics(); - } - } - - async detectMarketRegime(): Promise { - const cacheKey = 'market_regime'; - const cached = this.getFromCache(cacheKey); - if (cached) return cached; - - try { - const response = await axios.get(`${this.analyticsUrl}/analytics/regime`); - const regime = response.data.regime as string; - this.setCache(cacheKey, regime, 300000); // Cache for 5 minutes - return regime; - } catch (error) { - this.container.logger.error('Error detecting market regime:', error); - return 'normal'; // Default regime - } - } - - async calculateCorrelationMatrix(symbols: string[]): Promise { - try { - const response = await axios.post(`${this.analyticsUrl}/analytics/correlation`, { symbols }); - return response.data.matrix as number[][]; - } catch (error) { - this.container.logger.error('Error calculating correlation matrix:', error); - // Return identity matrix as fallback - return this.getIdentityMatrix(symbols.length); - } - } - - async runBacktestAnalysis(backtestId: string): Promise { - try { - const response = await axios.get(`${this.analyticsUrl}/analytics/backtest/${backtestId}`); - return response.data; - } catch (error) { - this.container.logger.error('Error running backtest analysis:', error); - return null; - } - } - - async predictWithModel(modelId: string, features: Record): Promise { - try { - const response = await axios.post(`${this.analyticsUrl}/models/predict`, { - model_id: modelId, - features - }); - return response.data; - } catch (error) { - this.container.logger.error('Error getting model prediction:', error); - return null; - } - } - - // Cache management - private getFromCache(key: string): any | null { - const cached = this.cache.get(key); - if (!cached) return null; - - const now = Date.now(); - if (now - cached.timestamp > this.CACHE_TTL_MS) { - this.cache.delete(key); - return null; - } - - return cached.data; - } - - private setCache(key: string, data: any, ttl?: number): void { - this.cache.set(key, { - data, - timestamp: Date.now() - }); - - // Auto-cleanup after TTL - setTimeout(() => { - this.cache.delete(key); - }, ttl || this.CACHE_TTL_MS); - } - - // Fallback methods when analytics service is unavailable - private getDefaultPerformanceMetrics(): PerformanceMetrics { - return { - totalReturn: 0, - sharpeRatio: 0, - sortinoRatio: 0, - maxDrawdown: 0, - winRate: 0, - profitFactor: 0, - avgWin: 0, - avgLoss: 0, - totalTrades: 0 - }; - } - - private getDefaultRiskMetrics(): RiskMetrics { - return { - currentExposure: 0, - dailyPnl: 0, - positionCount: 0, - grossExposure: 0, - var95: 0, - cvar95: 0 - }; - } - - private getEqualWeights(n: number): PortfolioWeights { - const weight = 1 / n; - return { - symbols: Array(n).fill('').map((_, i) => `Asset${i + 1}`), - weights: Array(n).fill(weight), - expectedReturn: 0, - expectedRisk: 0, - sharpeRatio: 0 - }; - } - - private getIdentityMatrix(n: number): number[][] { - const matrix: number[][] = []; - for (let i = 0; i < n; i++) { - matrix[i] = []; - for (let j = 0; j < n; j++) { - matrix[i][j] = i === j ? 1 : 0; - } - } - return matrix; - } -} \ No newline at end of file +import axios from 'axios'; +import { at } from '@stock-bot/utils'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { type PerformanceMetrics, type RiskMetrics } from '../types'; +import { StorageService } from './StorageService'; + +interface OptimizationParams { + returns: number[][]; + constraints?: { + minWeight?: number; + maxWeight?: number; + targetReturn?: number; + maxRisk?: number; + }; +} + +interface PortfolioWeights { + symbols: string[]; + weights: number[]; + expectedReturn: number; + expectedRisk: number; + sharpeRatio: number; +} + +export class AnalyticsService { + private analyticsUrl: string; + private cache = new Map(); + private readonly CACHE_TTL_MS = 60000; // 1 minute cache + private container: IServiceContainer; + private storageService: StorageService; + + constructor(container: IServiceContainer, storageService: StorageService) { + this.container = container; + this.storageService = storageService; + this.analyticsUrl = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003'; + } + + async getPerformanceMetrics( + portfolioId: string, + startDate: Date, + endDate: Date + ): Promise { + const cacheKey = `perf_${portfolioId}_${startDate.toISOString()}_${endDate.toISOString()}`; + const cached = this.getFromCache(cacheKey); + if (cached) { + return cached; + } + + try { + const response = await axios.get( + `${this.analyticsUrl}/analytics/performance/${portfolioId}`, + { + params: { + start_date: startDate.toISOString(), + end_date: endDate.toISOString(), + }, + } + ); + + const metrics = response.data as PerformanceMetrics; + this.setCache(cacheKey, metrics); + return metrics; + } catch (error) { + this.container.logger.error('Error fetching performance metrics:', error); + // Return default metrics if analytics service is unavailable + return this.getDefaultPerformanceMetrics(); + } + } + + async optimizePortfolio(params: OptimizationParams): Promise { + try { + const response = await axios.post(`${this.analyticsUrl}/optimize/portfolio`, params); + return response.data as PortfolioWeights; + } catch (error) { + this.container.logger.error('Error optimizing portfolio:', error); + // Return equal weights as fallback + return this.getEqualWeights(at(params.returns, 0).length); + } + } + + async getRiskMetrics(portfolioId: string): Promise { + const cacheKey = `risk_${portfolioId}`; + const cached = this.getFromCache(cacheKey); + if (cached) { + return cached; + } + + try { + const response = await axios.get(`${this.analyticsUrl}/analytics/risk/${portfolioId}`); + const metrics = response.data as RiskMetrics; + this.setCache(cacheKey, metrics); + return metrics; + } catch (error) { + this.container.logger.error('Error fetching risk metrics:', error); + return this.getDefaultRiskMetrics(); + } + } + + async detectMarketRegime(): Promise { + const cacheKey = 'market_regime'; + const cached = this.getFromCache(cacheKey); + if (cached) { + return cached; + } + + try { + const response = await axios.get(`${this.analyticsUrl}/analytics/regime`); + const regime = response.data.regime as string; + this.setCache(cacheKey, regime, 300000); // Cache for 5 minutes + return regime; + } catch (error) { + this.container.logger.error('Error detecting market regime:', error); + return 'normal'; // Default regime + } + } + + async calculateCorrelationMatrix(symbols: string[]): Promise { + try { + const response = await axios.post(`${this.analyticsUrl}/analytics/correlation`, { symbols }); + return response.data.matrix as number[][]; + } catch (error) { + this.container.logger.error('Error calculating correlation matrix:', error); + // Return identity matrix as fallback + return this.getIdentityMatrix(symbols.length); + } + } + + async runBacktestAnalysis(backtestId: string) { + try { + const response = await axios.get(`${this.analyticsUrl}/analytics/backtest/${backtestId}`); + return response.data; + } catch (error) { + this.container.logger.error('Error running backtest analysis:', error); + return null; + } + } + + async predictWithModel(modelId: string, features: Record) { + try { + const response = await axios.post(`${this.analyticsUrl}/models/predict`, { + model_id: modelId, + features, + }); + return response.data; + } catch (error) { + this.container.logger.error('Error getting model prediction:', error); + return null; + } + } + + // Cache management + private getFromCache(key: string): T | null { + const cached = this.cache.get(key); + if (!cached) { + return null; + } + + const now = Date.now(); + if (now - cached.timestamp > this.CACHE_TTL_MS) { + this.cache.delete(key); + return null; + } + + return cached.data as T; + } + + private setCache(key: string, data: unknown, ttl?: number): void { + this.cache.set(key, { + data, + timestamp: Date.now(), + }); + + // Auto-cleanup after TTL + setTimeout(() => { + this.cache.delete(key); + }, ttl || this.CACHE_TTL_MS); + } + + // Fallback methods when analytics service is unavailable + private getDefaultPerformanceMetrics(): PerformanceMetrics { + return { + totalReturn: 0, + sharpeRatio: 0, + sortinoRatio: 0, + maxDrawdown: 0, + winRate: 0, + profitFactor: 0, + avgWin: 0, + avgLoss: 0, + totalTrades: 0, + }; + } + + private getDefaultRiskMetrics(): RiskMetrics { + return { + currentExposure: 0, + dailyPnl: 0, + positionCount: 0, + grossExposure: 0, + var95: 0, + cvar95: 0, + }; + } + + private getEqualWeights(n: number): PortfolioWeights { + const weight = 1 / n; + return { + symbols: Array(n) + .fill('') + .map((_, i) => `Asset${i + 1}`), + weights: Array(n).fill(weight), + expectedReturn: 0, + expectedRisk: 0, + sharpeRatio: 0, + }; + } + + private getIdentityMatrix(n: number): number[][] { + const matrix: number[][] = []; + for (let i = 0; i < n; i++) { + matrix[i] = []; + for (let j = 0; j < n; j++) { + at(matrix, i)[j] = i === j ? 1 : 0; + } + } + return matrix; + } +} diff --git a/apps/stock/orchestrator/src/services/ExecutionService.ts b/apps/stock/orchestrator/src/services/ExecutionService.ts index 16a2389b..1a15a613 100644 --- a/apps/stock/orchestrator/src/services/ExecutionService.ts +++ b/apps/stock/orchestrator/src/services/ExecutionService.ts @@ -1,316 +1,329 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { TradingEngine } from '@stock-bot/engine'; -import { EventEmitter } from 'events'; -import { v4 as uuidv4 } from 'uuid'; -import { ModeConfig, OrderRequest, OrderRequestSchema } from '../types'; -import { StorageService } from './StorageService'; - -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; -} - -interface Fill { - price: number; - quantity: number; - commission: number; - timestamp: number; -} - -export class ExecutionService extends EventEmitter { - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private tradingEngine: TradingEngine | null = null; - private brokerClient: any = null; // Would be specific broker API client - private pendingOrders = new Map(); - private container: IServiceContainer; - private storageService: StorageService; - - constructor(container: IServiceContainer, storageService: StorageService) { - super(); - this.container = container; - this.storageService = storageService; - } - - async initialize(config: ModeConfig, tradingEngine: TradingEngine): Promise { - this.mode = config.mode; - this.tradingEngine = tradingEngine; - - if (config.mode === 'live') { - // Initialize broker connection - await this.initializeBroker(config.broker, config.accountId); - } - } - - private async initializeBroker(broker: string, accountId: string): Promise { - // In real implementation, would initialize specific broker API - // For example: Alpaca, Interactive Brokers, etc. - this.container.logger.info(`Initializing ${broker} broker connection for account ${accountId}`); - } - - async submitOrder(orderRequest: OrderRequest): Promise { - // Validate order request - const validatedOrder = OrderRequestSchema.parse(orderRequest); - - // Generate order ID - const orderId = uuidv4(); - const clientOrderId = validatedOrder.clientOrderId || orderId; - - // Store pending order - this.pendingOrders.set(orderId, validatedOrder); - - try { - // Check risk before submitting - const riskResult = await this.checkRisk(validatedOrder); - if (!riskResult.passed) { - return this.createRejectionReport( - orderId, - clientOrderId, - validatedOrder, - `Risk check failed: ${riskResult.violations.join(', ')}` - ); - } - - // Submit based on mode - let result: ExecutionReport; - - switch (this.mode) { - case 'backtest': - case 'paper': - result = await this.submitToSimulation(orderId, clientOrderId, validatedOrder); - break; - case 'live': - result = await this.submitToBroker(orderId, clientOrderId, validatedOrder); - break; - } - - // Emit order event - this.emit('orderUpdate', result); - - // If filled, update positions - if (result.fills.length > 0) { - await this.processFills(result); - } - - return result; - - } catch (error) { - this.container.logger.error('Error submitting order:', error); - return this.createRejectionReport( - orderId, - clientOrderId, - validatedOrder, - error instanceof Error ? error.message : 'Unknown error' - ); - } - } - - private async checkRisk(order: OrderRequest): Promise { - if (!this.tradingEngine) { - throw new Error('Trading engine not initialized'); - } - - // Convert to engine format - const engineOrder = { - id: uuidv4(), - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce - }; - - const result = this.tradingEngine.checkRisk(engineOrder); - return JSON.parse(result); - } - - private async submitToSimulation( - orderId: string, - clientOrderId: string, - order: OrderRequest - ): Promise { - if (!this.tradingEngine) { - throw new Error('Trading engine not initialized'); - } - - // Convert to engine format - const engineOrder = { - id: orderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce - }; - - // Submit to engine - const result = await this.tradingEngine.submitOrder(engineOrder); - const engineResult = JSON.parse(result); - - // Convert back to our format - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: this.mapEngineStatus(engineResult.status), - fills: engineResult.fills || [], - timestamp: Date.now() - }; - } - - private async submitToBroker( - orderId: string, - clientOrderId: string, - order: OrderRequest - ): Promise { - // In real implementation, would submit to actual broker - // This is a placeholder - this.container.logger.info(`Submitting order ${orderId} to broker`); - - // Simulate broker response - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: 'pending', - fills: [], - timestamp: Date.now() - }; - } - - async cancelOrder(orderId: string): Promise { - const order = this.pendingOrders.get(orderId); - if (!order) { - this.container.logger.warn(`Order ${orderId} not found`); - return false; - } - - try { - switch (this.mode) { - case 'backtest': - case 'paper': - // Cancel in simulation - if (this.tradingEngine) { - await this.tradingEngine.cancelOrder(orderId); - } - break; - case 'live': - // Cancel with broker - if (this.brokerClient) { - await this.brokerClient.cancelOrder(orderId); - } - break; - } - - this.pendingOrders.delete(orderId); - - // Emit cancellation event - this.emit('orderUpdate', { - orderId, - status: 'cancelled', - timestamp: Date.now() - }); - - return true; - - } catch (error) { - this.container.logger.error(`Error cancelling order ${orderId}:`, error); - return false; - } - } - - private async processFills(executionReport: ExecutionReport): Promise { - if (!this.tradingEngine) {return;} - - for (const fill of executionReport.fills) { - // Update position in engine - const result = this.tradingEngine.processFill( - executionReport.symbol, - fill.price, - fill.quantity, - executionReport.side, - fill.commission - ); - - // Emit fill event - this.emit('fill', { - orderId: executionReport.orderId, - symbol: executionReport.symbol, - side: executionReport.side, - ...fill, - positionUpdate: JSON.parse(result) - }); - } - } - - private createRejectionReport( - orderId: string, - clientOrderId: string, - order: OrderRequest, - reason: string - ): ExecutionReport { - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: 'rejected', - fills: [], - rejectionReason: reason, - timestamp: Date.now() - }; - } - - private mapEngineStatus(engineStatus: string): ExecutionReport['status'] { - const statusMap: Record = { - 'Pending': 'pending', - 'Accepted': 'accepted', - 'PartiallyFilled': 'partiallyFilled', - 'Filled': 'filled', - 'Cancelled': 'cancelled', - 'Rejected': 'rejected' - }; - - return statusMap[engineStatus] || 'rejected'; - } - - async routeOrderToExchange(order: OrderRequest, exchange: string): Promise { - // This would route orders to specific exchanges in live mode - // For now, just a placeholder - this.container.logger.info(`Routing order to ${exchange}:`, order); - } - - async getOrderStatus(orderId: string): Promise { - // In real implementation, would query broker or internal state - return null; - } - - async shutdown(): Promise { - // Cancel all pending orders - for (const orderId of this.pendingOrders.keys()) { - await this.cancelOrder(orderId); - } - - // Disconnect from broker - if (this.brokerClient) { - // await this.brokerClient.disconnect(); - this.brokerClient = null; - } - - this.tradingEngine = null; - this.removeAllListeners(); - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { randomUUID as uuidv4 } from 'node:crypto'; +import { TradingEngine } from '@stock-bot/engine'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { OrderRequestSchema, type ModeConfig, type OrderRequest } from '../types'; +import { StorageService } from './StorageService'; + +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; +} + +export interface Fill { + price: number; + quantity: number; + commission: number; + timestamp: number; + pnl?: number; +} + +export type StrategyOrderUpdate = Pick< + ExecutionReport, + 'orderId' | 'symbol' | 'side' | 'status' | 'fills' +>; +export interface StrategyFill extends Fill { + orderId: string; + symbol: string; + side: 'buy' | 'sell'; + strategyId?: string; + positionUpdate?: unknown; +} + +export class ExecutionService extends EventEmitter { + private mode: 'backtest' | 'paper' | 'live' = 'paper'; + private tradingEngine: TradingEngine | null = null; + private brokerClient: { cancelOrder(orderId: string): Promise } | null = null; // Would be specific broker API client + private pendingOrders = new Map(); + private container: IServiceContainer; + private storageService: StorageService; + + constructor(container: IServiceContainer, storageService: StorageService) { + super(); + this.container = container; + this.storageService = storageService; + } + + async initialize(config: ModeConfig, tradingEngine: TradingEngine): Promise { + this.mode = config.mode; + this.tradingEngine = tradingEngine; + + if (config.mode === 'live') { + // Initialize broker connection + await this.initializeBroker(config.broker, config.accountId); + } + } + + private async initializeBroker(broker: string, accountId: string): Promise { + // In real implementation, would initialize specific broker API + // For example: Alpaca, Interactive Brokers, etc. + this.container.logger.info(`Initializing ${broker} broker connection for account ${accountId}`); + } + + async submitOrder(orderRequest: OrderRequest): Promise { + // Validate order request + const validatedOrder = OrderRequestSchema.parse(orderRequest); + + // Generate order ID + const orderId = uuidv4(); + const clientOrderId = validatedOrder.clientOrderId || orderId; + + // Store pending order + this.pendingOrders.set(orderId, validatedOrder); + + try { + // Check risk before submitting + const riskResult = await this.checkRisk(validatedOrder); + if (!riskResult.passed) { + return this.createRejectionReport( + orderId, + clientOrderId, + validatedOrder, + `Risk check failed: ${riskResult.violations.join(', ')}` + ); + } + + // Submit based on mode + let result: ExecutionReport; + + switch (this.mode) { + case 'backtest': + case 'paper': + result = await this.submitToSimulation(orderId, clientOrderId, validatedOrder); + break; + case 'live': + result = await this.submitToBroker(orderId, clientOrderId, validatedOrder); + break; + } + + // Emit order event + this.emit('orderUpdate', result); + + // If filled, update positions + if (result.fills.length > 0) { + await this.processFills(result); + } + + return result; + } catch (error) { + this.container.logger.error('Error submitting order:', error); + return this.createRejectionReport( + orderId, + clientOrderId, + validatedOrder, + error instanceof Error ? error.message : 'Unknown error' + ); + } + } + + private async checkRisk(order: OrderRequest) { + if (!this.tradingEngine) { + throw new Error('Trading engine not initialized'); + } + + // Convert to engine format + const engineOrder = { + id: uuidv4(), + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + orderType: order.orderType, + limitPrice: order.limitPrice, + timeInForce: order.timeInForce, + }; + + const result = this.tradingEngine.checkRisk(engineOrder); + return JSON.parse(result); + } + + private async submitToSimulation( + orderId: string, + clientOrderId: string, + order: OrderRequest + ): Promise { + if (!this.tradingEngine) { + throw new Error('Trading engine not initialized'); + } + + // Convert to engine format + const engineOrder = { + id: orderId, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + orderType: order.orderType, + limitPrice: order.limitPrice, + timeInForce: order.timeInForce, + }; + + // Submit to engine + const result = await this.tradingEngine.submitOrder(engineOrder); + const engineResult = JSON.parse(result); + + // Convert back to our format + return { + orderId, + clientOrderId, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + status: this.mapEngineStatus(engineResult.status), + fills: engineResult.fills || [], + timestamp: Date.now(), + }; + } + + private async submitToBroker( + orderId: string, + clientOrderId: string, + order: OrderRequest + ): Promise { + // In real implementation, would submit to actual broker + // This is a placeholder + this.container.logger.info(`Submitting order ${orderId} to broker`); + + // Simulate broker response + return { + orderId, + clientOrderId, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + status: 'pending', + fills: [], + timestamp: Date.now(), + }; + } + + async cancelOrder(orderId: string): Promise { + const order = this.pendingOrders.get(orderId); + if (!order) { + this.container.logger.warn(`Order ${orderId} not found`); + return false; + } + + try { + switch (this.mode) { + case 'backtest': + case 'paper': + // Cancel in simulation + if (this.tradingEngine) { + throw new Error('The native simulation engine does not support order cancellation'); + } + break; + case 'live': + // Cancel with broker + if (this.brokerClient) { + await this.brokerClient.cancelOrder(orderId); + } + break; + } + + this.pendingOrders.delete(orderId); + + // Emit cancellation event + this.emit('orderUpdate', { + orderId, + status: 'cancelled', + timestamp: Date.now(), + }); + + return true; + } catch (error) { + this.container.logger.error(`Error cancelling order ${orderId}:`, error); + return false; + } + } + + private async processFills(executionReport: ExecutionReport): Promise { + if (!this.tradingEngine) { + return; + } + + for (const fill of executionReport.fills) { + // Update position in engine + const result = this.tradingEngine.processFill( + executionReport.symbol, + fill.price, + fill.quantity, + executionReport.side, + fill.commission + ); + + // Emit fill event + this.emit('fill', { + orderId: executionReport.orderId, + symbol: executionReport.symbol, + side: executionReport.side, + ...fill, + positionUpdate: JSON.parse(result), + }); + } + } + + private createRejectionReport( + orderId: string, + clientOrderId: string, + order: OrderRequest, + reason: string + ): ExecutionReport { + return { + orderId, + clientOrderId, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + status: 'rejected', + fills: [], + rejectionReason: reason, + timestamp: Date.now(), + }; + } + + private mapEngineStatus(engineStatus: string): ExecutionReport['status'] { + const statusMap: Record = { + Pending: 'pending', + Accepted: 'accepted', + PartiallyFilled: 'partiallyFilled', + Filled: 'filled', + Cancelled: 'cancelled', + Rejected: 'rejected', + }; + + return statusMap[engineStatus] || 'rejected'; + } + + async routeOrderToExchange(order: OrderRequest, exchange: string): Promise { + // This would route orders to specific exchanges in live mode + // For now, just a placeholder + this.container.logger.info(`Routing order to ${exchange}:`, order); + } + + async getOrderStatus(_orderId: string): Promise { + // In real implementation, would query broker or internal state + return null; + } + + async shutdown(): Promise { + // Cancel all pending orders + for (const orderId of this.pendingOrders.keys()) { + await this.cancelOrder(orderId); + } + + // Disconnect from broker + if (this.brokerClient) { + // await this.brokerClient.disconnect(); + this.brokerClient = null; + } + + this.tradingEngine = null; + this.removeAllListeners(); + } +} diff --git a/apps/stock/orchestrator/src/services/MarketDataService.ts b/apps/stock/orchestrator/src/services/MarketDataService.ts index a9767e67..519e0b6a 100644 --- a/apps/stock/orchestrator/src/services/MarketDataService.ts +++ b/apps/stock/orchestrator/src/services/MarketDataService.ts @@ -1,286 +1,300 @@ -import { io, Socket } from 'socket.io-client'; -import { EventEmitter } from 'events'; -import { IServiceContainer } from '@stock-bot/di'; -import { ModeConfig, MarketData, QuoteSchema, TradeSchema, BarSchema } from '../types'; -import { QuestDBClient } from '@stock-bot/questdb'; - -export class MarketDataService extends EventEmitter { - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private dataIngestionSocket: Socket | null = null; - private questdbClient: QuestDBClient | 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; - private container: IServiceContainer; - - constructor(container: IServiceContainer) { - super(); - this.container = container; - } - - async initialize(config: ModeConfig): Promise { - this.mode = config.mode; - - if (config.mode === 'backtest') { - // Initialize QuestDB client for historical data - this.questdbClient = new QuestDBClient({ - host: process.env.QUESTDB_HOST || 'localhost', - port: parseInt(process.env.QUESTDB_PORT || '9000'), - database: process.env.QUESTDB_DATABASE || 'trading' - }); - } else { - // 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.container.logger.info('Connected to data-ingestion service'); - // Re-subscribe to symbols - this.subscriptions.forEach(symbol => { - this.dataIngestionSocket!.emit('subscribe', { symbol }); - }); - }); - - this.dataIngestionSocket.on('disconnect', () => { - this.container.logger.warn('Disconnected from data-ingestion service'); - }); - - this.dataIngestionSocket.on('marketData', (data: any) => { - this.handleMarketData(data); - }); - - this.dataIngestionSocket.on('error', (error: any) => { - this.container.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.container.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.container.logger.debug(`Unsubscribed from ${symbol}`); - } - - private handleMarketData(data: any): void { - try { - // Validate and transform data - let marketData: MarketData; - - 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.container.logger.warn('Unknown market data format:', data); - return; - } - - // Add to batch buffer - 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.container.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); - - // Also emit individual events for strategies that need them - batch.forEach(data => { - this.emit('marketData', data); - }); - } - - async loadHistoricalData( - symbols: string[], - startTime: Date, - endTime: Date, - interval: string = '1m' - ): Promise { - if (!this.questdbClient) { - throw new Error('QuestDB client not initialized'); - } - - const data: MarketData[] = []; - - for (const symbol of symbols) { - // Query for bars - const bars = await this.questdbClient.query(` - SELECT - timestamp, - open, - high, - low, - close, - volume, - vwap - FROM bars_${interval} - WHERE symbol = '${symbol}' - AND timestamp >= '${startTime.toISOString()}' - AND timestamp < '${endTime.toISOString()}' - ORDER BY timestamp - `); - - // Convert to MarketData format - bars.forEach((row: any) => { - data.push({ - type: 'bar', - data: { - symbol, - open: row.open, - high: row.high, - low: row.low, - close: row.close, - volume: row.volume, - vwap: row.vwap, - timestamp: new Date(row.timestamp).getTime() - } - }); - }); - - // Also query for trades if needed for more granular simulation - if (interval === '1m' || interval === 'tick') { - const trades = await this.questdbClient.query(` - SELECT - timestamp, - price, - size, - side - FROM trades - WHERE symbol = '${symbol}' - AND timestamp >= '${startTime.toISOString()}' - AND timestamp < '${endTime.toISOString()}' - ORDER BY timestamp - `); - - trades.forEach((row: any) => { - data.push({ - type: 'trade', - data: { - symbol, - price: row.price, - size: row.size, - side: row.side, - timestamp: new Date(row.timestamp).getTime() - } - }); - }); - } - } - - // Sort all data by timestamp - data.sort((a, b) => { - const timeA = a.type === 'bar' ? a.data.timestamp : - a.type === 'trade' ? a.data.timestamp : - a.data.timestamp; - const timeB = b.type === 'bar' ? b.data.timestamp : - b.type === 'trade' ? b.data.timestamp : - b.data.timestamp; - return timeA - timeB; - }); - - return data; - } - - async shutdown(): Promise { - // Clear batch timer - if (this.batchTimer) { - clearTimeout(this.batchTimer); - this.batchTimer = null; - } - - // Process any remaining data - if (this.batchBuffer.length > 0) { - this.processBatch(); - } - - // Disconnect from data ingestion - if (this.dataIngestionSocket) { - this.dataIngestionSocket.disconnect(); - this.dataIngestionSocket = null; - } - - // Close QuestDB connection - if (this.questdbClient) { - await this.questdbClient.disconnect(); - this.questdbClient = null; - } - - this.subscriptions.clear(); - this.removeAllListeners(); - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { io, Socket } from 'socket.io-client'; +import { defined } from '@stock-bot/invariants'; +import { QuestDBClient } from '@stock-bot/questdb'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { BarSchema, QuoteSchema, TradeSchema, type MarketData, type ModeConfig } from '../types'; + +export class MarketDataService extends EventEmitter { + private mode: 'backtest' | 'paper' | 'live' = 'paper'; + private dataIngestionSocket: Socket | null = null; + private questdbClient: QuestDBClient | 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; + private container: IServiceContainer; + + constructor(container: IServiceContainer) { + super(); + this.container = container; + } + + async initialize(config: ModeConfig): Promise { + this.mode = config.mode; + + if (config.mode === 'backtest') { + // Initialize QuestDB client for historical data + this.questdbClient = new QuestDBClient({ + host: process.env.QUESTDB_HOST || 'localhost', + httpPort: parseInt(process.env.QUESTDB_HTTP_PORT || '9000'), + pgPort: parseInt(process.env.QUESTDB_PG_PORT || '8812'), + influxPort: parseInt(process.env.QUESTDB_INFLUX_PORT || '9009'), + database: process.env.QUESTDB_DATABASE || 'trading', + }); + } else { + // 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.container.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.container.logger.warn('Disconnected from data-ingestion service'); + }); + + this.dataIngestionSocket.on('marketData', data => { + this.handleMarketData(data); + }); + + this.dataIngestionSocket.on('error', error => { + this.container.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.container.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.container.logger.debug(`Unsubscribed from ${symbol}`); + } + + private handleMarketData(input: unknown): void { + if (!input || typeof input !== 'object') { + throw new Error('Invalid market data'); + } + const data = input as Record; + try { + // Validate and transform data + let marketData: MarketData; + + 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.container.logger.warn('Unknown market data format:', data); + return; + } + + // Add to batch buffer + 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.container.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); + + // Also emit individual events for strategies that need them + batch.forEach(data => { + this.emit('marketData', data); + }); + } + + async loadHistoricalData( + symbols: string[], + startTime: Date, + endTime: Date, + interval: string = '1m' + ): Promise { + if (!this.questdbClient) { + throw new Error('QuestDB client not initialized'); + } + + const data: MarketData[] = []; + + for (const symbol of symbols) { + // Query for bars + const bars = await this.questdbClient.query(` + SELECT + timestamp, + open, + high, + low, + close, + volume, + vwap + FROM bars_${interval} + WHERE symbol = '${symbol}' + AND timestamp >= '${startTime.toISOString()}' + AND timestamp < '${endTime.toISOString()}' + ORDER BY timestamp + `); + + // Convert to MarketData format + bars.rows.forEach(row => { + data.push({ + type: 'bar', + data: { + symbol, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + volume: row.volume, + vwap: row.vwap, + timestamp: new Date(row.timestamp).getTime(), + }, + }); + }); + + // Also query for trades if needed for more granular simulation + if (interval === '1m' || interval === 'tick') { + const trades = await this.questdbClient.query(` + SELECT + timestamp, + price, + size, + side + FROM trades + WHERE symbol = '${symbol}' + AND timestamp >= '${startTime.toISOString()}' + AND timestamp < '${endTime.toISOString()}' + ORDER BY timestamp + `); + + trades.rows.forEach(row => { + data.push({ + type: 'trade', + data: { + symbol, + price: row.price, + size: row.size, + side: row.side, + timestamp: new Date(row.timestamp).getTime(), + }, + }); + }); + } + } + + // Sort all data by timestamp + data.sort((a, b) => { + const timeA = + a.type === 'bar' + ? a.data.timestamp + : a.type === 'trade' + ? a.data.timestamp + : a.data.timestamp; + const timeB = + b.type === 'bar' + ? b.data.timestamp + : b.type === 'trade' + ? b.data.timestamp + : b.data.timestamp; + return timeA - timeB; + }); + + return data; + } + + async shutdown(): Promise { + // Clear batch timer + if (this.batchTimer) { + clearTimeout(this.batchTimer); + this.batchTimer = null; + } + + // Process any remaining data + if (this.batchBuffer.length > 0) { + this.processBatch(); + } + + // Disconnect from data ingestion + if (this.dataIngestionSocket) { + this.dataIngestionSocket.disconnect(); + this.dataIngestionSocket = null; + } + + // Close QuestDB connection + if (this.questdbClient) { + await this.questdbClient.disconnect(); + this.questdbClient = null; + } + + this.subscriptions.clear(); + this.removeAllListeners(); + } +} diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index b44a1a3a..fb6a1e71 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -1,378 +1,497 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { QuestDBClient } from '@stock-bot/questdb'; -import { PostgresClient } from '@stock-bot/postgres'; -import { MongoDBClient } from '@stock-bot/mongodb'; -import { ModeConfig, MarketData, Position } from '../types'; - -export class StorageService { - private questdb: QuestDBClient | null = null; - private postgres: PostgresClient | null = null; - private mongodb: MongoDBClient | null = null; - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private container: IServiceContainer; - - constructor( - container: IServiceContainer, - mongoClient: MongoDBClient, - postgresClient: PostgresClient, - questdbClient: QuestDBClient | null - ) { - this.container = container; - this.mongodb = mongoClient; - this.postgres = postgresClient; - this.questdb = questdbClient; - } - - async initialize(config: ModeConfig): Promise { - this.mode = config.mode; - // Clients are already injected via DI - await this.createTables(); - } - - private async createTables(): Promise { - // Create tables if they don't exist - if (this.postgres) { - // Orders table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS orders ( - id UUID PRIMARY KEY, - client_order_id VARCHAR(255), - symbol VARCHAR(50) NOT NULL, - side VARCHAR(10) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - order_type VARCHAR(20) NOT NULL, - limit_price DECIMAL(20, 8), - stop_price DECIMAL(20, 8), - time_in_force VARCHAR(10) NOT NULL, - status VARCHAR(20) NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT NOW(), - updated_at TIMESTAMP NOT NULL DEFAULT NOW(), - mode VARCHAR(10) NOT NULL - ) - `); - - // Fills table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS fills ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - order_id UUID NOT NULL REFERENCES orders(id), - symbol VARCHAR(50) NOT NULL, - price DECIMAL(20, 8) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - commission DECIMAL(20, 8) NOT NULL, - side VARCHAR(10) NOT NULL, - timestamp TIMESTAMP NOT NULL, - mode VARCHAR(10) NOT NULL - ) - `); - - // Positions table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS positions ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - symbol VARCHAR(50) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - average_price DECIMAL(20, 8) NOT NULL, - realized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, - unrealized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, - updated_at TIMESTAMP NOT NULL DEFAULT NOW(), - mode VARCHAR(10) NOT NULL, - UNIQUE(symbol, mode) - ) - `); - - // Strategy performance table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS strategy_performance ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - strategy_id VARCHAR(255) NOT NULL, - timestamp TIMESTAMP NOT NULL, - total_return DECIMAL(20, 8), - sharpe_ratio DECIMAL(20, 8), - max_drawdown DECIMAL(20, 8), - win_rate DECIMAL(20, 8), - total_trades INTEGER, - mode VARCHAR(10) NOT NULL - ) - `); - } - } - - async storeMarketData(data: MarketData[]): Promise { - if (!this.questdb) return; - - for (const item of data) { - try { - switch (item.type) { - case 'quote': - await this.questdb.insert('quotes', { - symbol: item.data.symbol, - bid: item.data.bid, - ask: item.data.ask, - bid_size: item.data.bidSize, - ask_size: item.data.askSize, - timestamp: new Date(item.data.timestamp) - }); - break; - - case 'trade': - await this.questdb.insert('trades', { - symbol: item.data.symbol, - price: item.data.price, - size: item.data.size, - side: item.data.side, - timestamp: new Date(item.data.timestamp) - }); - break; - - case 'bar': - const interval = '1m'; // Would be determined from context - await this.questdb.insert(`bars_${interval}`, { - symbol: item.data.symbol, - open: item.data.open, - high: item.data.high, - low: item.data.low, - close: item.data.close, - volume: item.data.volume, - vwap: item.data.vwap || null, - timestamp: new Date(item.data.timestamp) - }); - break; - } - } catch (error) { - logger.error('Error storing market data:', error); - } - } - } - - async storeOrder(order: any): Promise { - if (!this.postgres) return; - - await this.postgres.query(` - INSERT INTO orders ( - id, client_order_id, symbol, side, quantity, - order_type, limit_price, stop_price, time_in_force, - status, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) - `, [ - order.id, - order.clientOrderId, - order.symbol, - order.side, - order.quantity, - order.orderType, - order.limitPrice || null, - order.stopPrice || null, - order.timeInForce, - order.status, - this.mode - ]); - } - - async updateOrderStatus(orderId: string, status: string): Promise { - if (!this.postgres) return; - - await this.postgres.query(` - UPDATE orders - SET status = $1, updated_at = NOW() - WHERE id = $2 - `, [status, orderId]); - } - - async storeFill(fill: any): Promise { - if (!this.postgres) return; - - await this.postgres.query(` - INSERT INTO fills ( - order_id, symbol, price, quantity, commission, side, timestamp, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - `, [ - fill.orderId, - fill.symbol, - fill.price, - fill.quantity, - fill.commission, - fill.side, - new Date(fill.timestamp), - this.mode - ]); - } - - async updatePosition(position: Position): Promise { - if (!this.postgres) return; - - await this.postgres.query(` - INSERT INTO positions ( - symbol, quantity, average_price, realized_pnl, unrealized_pnl, mode - ) VALUES ($1, $2, $3, $4, $5, $6) - ON CONFLICT (symbol, mode) DO UPDATE SET - quantity = $2, - average_price = $3, - realized_pnl = $4, - unrealized_pnl = $5, - updated_at = NOW() - `, [ - position.symbol, - position.quantity, - position.averagePrice, - position.realizedPnl, - position.unrealizedPnl, - this.mode - ]); - } - - async getPositions(): Promise { - if (!this.postgres) return []; - - const result = await this.postgres.query(` - SELECT * FROM positions WHERE mode = $1 - `, [this.mode]); - - return result.rows.map((row: any) => ({ - symbol: row.symbol, - quantity: parseFloat(row.quantity), - averagePrice: parseFloat(row.average_price), - realizedPnl: parseFloat(row.realized_pnl), - unrealizedPnl: parseFloat(row.unrealized_pnl), - totalCost: parseFloat(row.quantity) * parseFloat(row.average_price), - lastUpdate: row.updated_at - })); - } - - async storeStrategyPerformance(strategyId: string, metrics: any): Promise { - if (!this.postgres) return; - - await this.postgres.query(` - INSERT INTO strategy_performance ( - strategy_id, timestamp, total_return, sharpe_ratio, - max_drawdown, win_rate, total_trades, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - `, [ - strategyId, - new Date(), - metrics.totalReturn, - metrics.sharpeRatio, - metrics.maxDrawdown, - metrics.winRate, - metrics.totalTrades, - this.mode - ]); - } - - async getHistoricalBars( - symbol: string, - startTime: Date, - endTime: Date, - interval: string = '1m' - ): Promise { - // If QuestDB is available, use real data - if (this.questdb) { - const result = await this.questdb.query(` - SELECT * FROM bars_${interval} - WHERE symbol = '${symbol}' - AND timestamp >= '${startTime.toISOString()}' - AND timestamp < '${endTime.toISOString()}' - ORDER BY timestamp - `); - return result; - } - - // Otherwise, generate mock data for testing - this.container.logger.info('Generating mock data for backtest', { - symbol, - startTime: startTime.toISOString(), - endTime: endTime.toISOString(), - interval - }); - - return this.generateMockBars(symbol, startTime, endTime, interval); - } - - private generateMockBars( - symbol: string, - startTime: Date, - endTime: Date, - interval: string - ): any[] { - const bars = []; - const msPerInterval = this.getIntervalMilliseconds(interval); - let currentTime = new Date(startTime); - - // Use current timestamp to seed randomness for different data each run - const seed = Date.now(); - const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds - - // Starting price based on symbol with some randomness - let basePrice = symbol === 'AAPL' ? 150 + (seedMultiplier * 20 - 10) : - symbol === 'MSFT' ? 300 + (seedMultiplier * 30 - 15) : - symbol === 'GOOGL' ? 120 + (seedMultiplier * 15 - 7.5) : - 100 + (seedMultiplier * 10 - 5); - - // Random walk seed to make each run different - let walkSeed = seedMultiplier; - - while (currentTime <= endTime) { - // Use a pseudo-random based on walkSeed for deterministic but different results - walkSeed = (walkSeed * 9.73 + 0.27) % 1; - - // Random walk with trend - increased volatility for testing - const trend = 0.0002; // Slight upward trend - const volatility = 0.01; // 1% volatility - const change = (walkSeed - 0.5 + trend) * volatility; - - basePrice *= (1 + change); - - // Generate OHLC data with more realistic volatility - const openSeed = (walkSeed * 7.13 + 0.31) % 1; - const highSeed = (walkSeed * 5.17 + 0.41) % 1; - const lowSeed = (walkSeed * 3.19 + 0.59) % 1; - const volumeSeed = (walkSeed * 11.23 + 0.67) % 1; - - const open = basePrice * (1 + (openSeed - 0.5) * 0.005); - const close = basePrice; - const high = Math.max(open, close) * (1 + highSeed * 0.008); - const low = Math.min(open, close) * (1 - lowSeed * 0.008); - const volume = 1000000 + volumeSeed * 500000; - - bars.push({ - symbol, - timestamp: new Date(currentTime), - open, - high, - low, - close, - volume, - vwap: (high + low + close) / 3 - }); - - currentTime = new Date(currentTime.getTime() + msPerInterval); - } - - this.container.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`); - - return bars; - } - - private getIntervalMilliseconds(interval: string): number { - switch (interval) { - case '1m': return 60 * 1000; - case '5m': return 5 * 60 * 1000; - case '15m': return 15 * 60 * 1000; - case '1h': return 60 * 60 * 1000; - case '1d': return 24 * 60 * 60 * 1000; - default: return 60 * 1000; // Default to 1 minute - } - } - - async shutdown(): Promise { - if (this.questdb) { - await this.questdb.disconnect(); - this.questdb = null; - } - - if (this.postgres) { - await this.postgres.disconnect(); - this.postgres = null; - } - } -} \ No newline at end of file +import type { + IServiceContainer, + MongoDBClient, + PostgresClient, + QuestDBClient, +} from '@stock-bot/services'; +import type { MarketData, ModeConfig, OrderRequest, PerformanceMetrics, Position } from '../types'; + +export interface HistoricalBar { + symbol: string; + timestamp: Date; + open: number; + high: number; + low: number; + close: number; + volume: number; + vwap?: number; + interpolated?: boolean; +} +export interface StoredFill { + orderId: string; + symbol: string; + price: number; + quantity: number; + commission: number; + side: string; + timestamp: number; +} + +export class StorageService { + private questdb: QuestDBClient | null = null; + private postgres: PostgresClient | null = null; + private mongodb: MongoDBClient | null = null; + private mode: 'backtest' | 'paper' | 'live' = 'paper'; + private container: IServiceContainer; + + constructor( + container: IServiceContainer, + mongoClient: MongoDBClient | null | undefined, + postgresClient: PostgresClient | null | undefined, + questdbClient: QuestDBClient | null, + private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {} + ) { + this.container = container; + this.mongodb = mongoClient ?? null; + this.postgres = postgresClient ?? null; + this.questdb = questdbClient; + } + + async initialize(config: ModeConfig): Promise { + this.mode = config.mode; + // Clients are already injected via DI + await this.createTables(); + } + + private async createTables(): Promise { + // Create tables if they don't exist + if (this.postgres) { + // Orders table + await this.postgres.query(` + CREATE TABLE IF NOT EXISTS orders ( + id UUID PRIMARY KEY, + client_order_id VARCHAR(255), + symbol VARCHAR(50) NOT NULL, + side VARCHAR(10) NOT NULL, + quantity DECIMAL(20, 8) NOT NULL, + order_type VARCHAR(20) NOT NULL, + limit_price DECIMAL(20, 8), + stop_price DECIMAL(20, 8), + time_in_force VARCHAR(10) NOT NULL, + status VARCHAR(20) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + mode VARCHAR(10) NOT NULL + ) + `); + + // Fills table + await this.postgres.query(` + CREATE TABLE IF NOT EXISTS fills ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + order_id UUID NOT NULL REFERENCES orders(id), + symbol VARCHAR(50) NOT NULL, + price DECIMAL(20, 8) NOT NULL, + quantity DECIMAL(20, 8) NOT NULL, + commission DECIMAL(20, 8) NOT NULL, + side VARCHAR(10) NOT NULL, + timestamp TIMESTAMP NOT NULL, + mode VARCHAR(10) NOT NULL + ) + `); + + // Positions table + await this.postgres.query(` + CREATE TABLE IF NOT EXISTS positions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + symbol VARCHAR(50) NOT NULL, + quantity DECIMAL(20, 8) NOT NULL, + average_price DECIMAL(20, 8) NOT NULL, + realized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, + unrealized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + mode VARCHAR(10) NOT NULL, + UNIQUE(symbol, mode) + ) + `); + + // Strategy performance table + await this.postgres.query(` + CREATE TABLE IF NOT EXISTS strategy_performance ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + strategy_id VARCHAR(255) NOT NULL, + timestamp TIMESTAMP NOT NULL, + total_return DECIMAL(20, 8), + sharpe_ratio DECIMAL(20, 8), + max_drawdown DECIMAL(20, 8), + win_rate DECIMAL(20, 8), + total_trades INTEGER, + mode VARCHAR(10) NOT NULL + ) + `); + } + } + + private async insertTimeSeries(table: string, data: Record): Promise { + if (!this.questdb) { + throw new Error('QuestDB is unavailable'); + } + if (!/^[a-z0-9_]+$/.test(table)) { + throw new Error('Invalid time-series table'); + } + const columns = Object.keys(data); + const placeholders = columns.map((_, i) => '$' + (i + 1)); + await this.questdb.query( + `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`, + Object.values(data) + ); + } + + async storeMarketData(data: MarketData[]): Promise { + if (!this.questdb) { + return; + } + + for (const item of data) { + try { + switch (item.type) { + case 'quote': + await this.insertTimeSeries('quotes', { + symbol: item.data.symbol, + bid: item.data.bid, + ask: item.data.ask, + bid_size: item.data.bidSize, + ask_size: item.data.askSize, + timestamp: new Date(item.data.timestamp), + }); + break; + + case 'trade': + await this.insertTimeSeries('trades', { + symbol: item.data.symbol, + price: item.data.price, + size: item.data.size, + side: item.data.side, + timestamp: new Date(item.data.timestamp), + }); + break; + + case 'bar': { + const interval = '1m'; // Would be determined from context + await this.insertTimeSeries(`bars_${interval}`, { + symbol: item.data.symbol, + open: item.data.open, + high: item.data.high, + low: item.data.low, + close: item.data.close, + volume: item.data.volume, + vwap: item.data.vwap || null, + timestamp: new Date(item.data.timestamp), + }); + break; + } + } + } catch (error) { + this.container.logger.error('Error storing market data:', error); + } + } + } + + async storeOrder(order: OrderRequest & { id: string; status: string }): Promise { + if (!this.postgres) { + return; + } + + await this.postgres.query( + ` + INSERT INTO orders ( + id, client_order_id, symbol, side, quantity, + order_type, limit_price, stop_price, time_in_force, + status, mode + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + `, + [ + order.id, + order.clientOrderId, + order.symbol, + order.side, + order.quantity, + order.orderType, + order.limitPrice || null, + order.stopPrice || null, + order.timeInForce, + order.status, + this.mode, + ] + ); + } + + async updateOrderStatus(orderId: string, status: string): Promise { + if (!this.postgres) { + return; + } + + await this.postgres.query( + ` + UPDATE orders + SET status = $1, updated_at = NOW() + WHERE id = $2 + `, + [status, orderId] + ); + } + + async storeFill(fill: StoredFill): Promise { + if (!this.postgres) { + return; + } + + await this.postgres.query( + ` + INSERT INTO fills ( + order_id, symbol, price, quantity, commission, side, timestamp, mode + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + `, + [ + fill.orderId, + fill.symbol, + fill.price, + fill.quantity, + fill.commission, + fill.side, + new Date(fill.timestamp), + this.mode, + ] + ); + } + + async updatePosition(position: Position): Promise { + if (!this.postgres) { + return; + } + + await this.postgres.query( + ` + INSERT INTO positions ( + symbol, quantity, average_price, realized_pnl, unrealized_pnl, mode + ) VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (symbol, mode) DO UPDATE SET + quantity = $2, + average_price = $3, + realized_pnl = $4, + unrealized_pnl = $5, + updated_at = NOW() + `, + [ + position.symbol, + position.quantity, + position.averagePrice, + position.realizedPnl, + position.unrealizedPnl, + this.mode, + ] + ); + } + + async getPositions(): Promise { + if (!this.postgres) { + return []; + } + + const result = await this.postgres.query( + ` + SELECT * FROM positions WHERE mode = $1 + `, + [this.mode] + ); + + return result.rows.map(row => ({ + symbol: row.symbol, + quantity: parseFloat(row.quantity), + averagePrice: parseFloat(row.average_price), + realizedPnl: parseFloat(row.realized_pnl), + unrealizedPnl: parseFloat(row.unrealized_pnl), + totalCost: parseFloat(row.quantity) * parseFloat(row.average_price), + lastUpdate: row.updated_at, + })); + } + + async storeStrategyPerformance( + strategyId: string, + metrics: Pick< + PerformanceMetrics, + 'totalReturn' | 'sharpeRatio' | 'maxDrawdown' | 'winRate' | 'totalTrades' + > + ): Promise { + if (!this.postgres) { + return; + } + + await this.postgres.query( + ` + INSERT INTO strategy_performance ( + strategy_id, timestamp, total_return, sharpe_ratio, + max_drawdown, win_rate, total_trades, mode + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + `, + [ + strategyId, + new Date(), + metrics.totalReturn, + metrics.sharpeRatio, + metrics.maxDrawdown, + metrics.winRate, + metrics.totalTrades, + this.mode, + ] + ); + } + + async getHistoricalBars( + symbol: string, + startTime: Date, + endTime: Date, + interval: string = '1m' + ): Promise { + // If QuestDB is available, use real data + if (this.questdb) { + if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { + throw new Error('Unsupported historical interval'); + } + const result = await this.questdb.query( + `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, + [symbol, startTime, endTime] + ); + return result.rows; + } + + if (this.mongodb) { + if (interval !== '1d') { + throw new Error('Daily provider storage cannot satisfy an intraday request'); + } + const prices = await this.mongodb.find<{ + date: string; + open: number; + high: number; + low: number; + close: number; + volume: number; + }>( + 'eodPrices', + { + symbol, + date: { + $gte: startTime.toISOString().slice(0, 10), + $lt: endTime.toISOString().slice(0, 10), + }, + }, + { sort: { date: 1 } } + ); + return prices.map(price => ({ + symbol, + timestamp: new Date(price.date), + open: price.open, + high: price.high, + low: price.low, + close: price.close, + volume: price.volume, + })); + } + if (!this.options.allowSyntheticData) { + throw new Error( + 'No historical data store configured; synthetic data requires explicit opt-in' + ); + } + return this.generateMockBars(symbol, startTime, endTime, interval); + } + + private generateMockBars( + symbol: string, + startTime: Date, + endTime: Date, + interval: string + ): HistoricalBar[] { + const bars = []; + const msPerInterval = this.getIntervalMilliseconds(interval); + let currentTime = new Date(startTime); + + // Synthetic data is only generated with explicit opt-in and a stable seed. + const seed = this.options.syntheticSeed ?? 42; + const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds + + // Starting price based on symbol with some randomness + let basePrice = + symbol === 'AAPL' + ? 150 + (seedMultiplier * 20 - 10) + : symbol === 'MSFT' + ? 300 + (seedMultiplier * 30 - 15) + : symbol === 'GOOGL' + ? 120 + (seedMultiplier * 15 - 7.5) + : 100 + (seedMultiplier * 10 - 5); + + // Random walk seed to make each run different + let walkSeed = seedMultiplier; + + while (currentTime < endTime) { + // Use a pseudo-random based on walkSeed for deterministic but different results + walkSeed = (walkSeed * 9.73 + 0.27) % 1; + + // Random walk with trend - increased volatility for testing + const trend = 0.0002; // Slight upward trend + const volatility = 0.01; // 1% volatility + const change = (walkSeed - 0.5 + trend) * volatility; + + basePrice *= 1 + change; + + // Generate OHLC data with more realistic volatility + const openSeed = (walkSeed * 7.13 + 0.31) % 1; + const highSeed = (walkSeed * 5.17 + 0.41) % 1; + const lowSeed = (walkSeed * 3.19 + 0.59) % 1; + const volumeSeed = (walkSeed * 11.23 + 0.67) % 1; + + const open = basePrice * (1 + (openSeed - 0.5) * 0.005); + const close = basePrice; + const high = Math.max(open, close) * (1 + highSeed * 0.008); + const low = Math.min(open, close) * (1 - lowSeed * 0.008); + const volume = 1000000 + volumeSeed * 500000; + + bars.push({ + symbol, + timestamp: new Date(currentTime), + open, + high, + low, + close, + volume, + vwap: (high + low + close) / 3, + }); + + currentTime = new Date(currentTime.getTime() + msPerInterval); + } + + this.container.logger.info( + `Generated ${bars.length} mock bars for ${symbol} with seed ${seed}` + ); + + return bars; + } + + private getIntervalMilliseconds(interval: string): number { + switch (interval) { + case '1m': + return 60 * 1000; + case '5m': + return 5 * 60 * 1000; + case '15m': + return 15 * 60 * 1000; + case '1h': + return 60 * 60 * 1000; + case '1d': + return 24 * 60 * 60 * 1000; + default: + return 60 * 1000; // Default to 1 minute + } + } + + async shutdown(): Promise { + if (this.questdb) { + await this.questdb.disconnect(); + this.questdb = null; + } + + if (this.postgres) { + await this.postgres.disconnect(); + this.postgres = null; + } + } +} diff --git a/apps/stock/orchestrator/src/simple-container.ts b/apps/stock/orchestrator/src/simple-container.ts index b96250e7..ead0bf8e 100644 --- a/apps/stock/orchestrator/src/simple-container.ts +++ b/apps/stock/orchestrator/src/simple-container.ts @@ -1,146 +1,26 @@ -import { getLogger } from '@stock-bot/logger'; -import { MongoDBClient } from '@stock-bot/mongodb'; -import { PostgreSQLClient } from '@stock-bot/postgres'; -import { createCache } from '@stock-bot/cache'; -import { QueueManager, Queue } from '@stock-bot/queue'; -import { IServiceContainer } from '@stock-bot/handlers'; -import { ModeManager } from './core/ModeManager'; -import { MarketDataService } from './services/MarketDataService'; -import { ExecutionService } from './services/ExecutionService'; -import { AnalyticsService } from './services/AnalyticsService'; -import { StorageService } from './services/StorageService'; -import { StrategyManager } from './strategies/StrategyManager'; -import { BacktestEngine } from './backtest/BacktestEngine'; -import { RustBacktestAdapter } from './backtest/RustBacktestAdapter'; -import { PaperTradingManager } from './paper/PaperTradingManager'; - -/** - * Creates a simplified service container without the DI framework - * All configuration comes from the config object - */ -export async function createContainer(config: any): Promise { - const logger = getLogger('orchestrator'); - - // Initialize database clients if enabled - let mongoClient: MongoDBClient | undefined; - if (config.database.mongodb.enabled) { - mongoClient = new MongoDBClient(config.database.mongodb, logger); - await mongoClient.connect(); - } - - let postgresClient: PostgreSQLClient | undefined; - if (config.database.postgres.enabled) { - postgresClient = new PostgreSQLClient({ - host: config.database.postgres.host, - port: config.database.postgres.port, - database: config.database.postgres.database, - username: config.database.postgres.user, - password: config.database.postgres.password, - poolSettings: { - min: 1, - max: config.database.postgres.poolSize || 20, - idleTimeoutMillis: config.database.postgres.idleTimeout || 10000 - } - }); - await postgresClient.connect(); - } - - // Initialize cache if enabled - let cache: any; - if (config.database.dragonfly.enabled) { - cache = createCache({ - redisConfig: { - host: config.database.dragonfly.host, - port: config.database.dragonfly.port, - db: config.database.dragonfly.db, - keyPrefix: config.database.dragonfly.keyPrefix - }, - ttl: 3600, - enableMetrics: true - }); - } - - // Initialize queue if enabled - let queue: Queue | undefined; - let queueManager: QueueManager | undefined; - if (config.queue.enabled) { - queue = new Queue('orchestrator', { - redis: { - host: config.queue.redis.host, - port: config.queue.redis.port, - db: config.queue.redis.db - } - }); - queueManager = new QueueManager(config, logger); - } - - // Create base services container - const services: IServiceContainer = { - logger, - cache, - mongodb: mongoClient, - postgres: postgresClient, - queue, - queueManager, - config, - custom: {} - }; - - // Create orchestrator services - const storageService = new StorageService( - services, - mongoClient!, - postgresClient!, - null // QuestDB not needed for now - ); - - const marketDataService = new MarketDataService(services); - const executionService = new ExecutionService(services, storageService); - const analyticsService = new AnalyticsService(services, storageService); - const strategyManager = new StrategyManager(services); - - // Add strategy manager to custom services early so RustBacktestAdapter can access it - services.custom.StrategyManager = strategyManager; - - // Use Rust backtest engine if configured - const useRustEngine = config.services?.orchestrator?.backtesting?.useRustEngine !== false; - const backtestEngine = useRustEngine - ? new RustBacktestAdapter(services) - : new BacktestEngine(services, storageService, strategyManager); - const paperTradingManager = new PaperTradingManager( - services, - storageService, - marketDataService, - executionService - ); - const modeManager = new ModeManager( - services, - marketDataService, - executionService, - storageService - ); - - // Store custom services (before creating RustBacktestAdapter) - services.custom = { - StorageService: storageService, - MarketDataService: marketDataService, - ExecutionService: executionService, - AnalyticsService: analyticsService, - StrategyManager: strategyManager, - BacktestEngine: backtestEngine, - PaperTradingManager: paperTradingManager, - ModeManager: modeManager - }; - - // Setup event listeners after all services are registered - strategyManager.setupEventListeners(); - - // Initialize mode manager with configured default mode - const serviceConfig = config.services?.orchestrator || {}; - await modeManager.initializeMode({ - mode: serviceConfig.defaultMode || 'paper', - startingCapital: serviceConfig.paperTradingCapital || 100000 - }); - - return services; -} \ No newline at end of file +import { ServiceContainerBuilder } from '@stock-bot/di'; +import type { StockAppConfig } from '@stock-bot/stock-config'; +import { registerOrchestratorServices } from './container'; +import type { OrchestratorServices } from './types'; + +/** Use the shared builder for connection setup and adapter ownership. */ +export async function createContainer(config: StockAppConfig) { + const container = await new ServiceContainerBuilder() + .withConfig(config) + .withOptions({ + enableMongoDB: config.database?.mongodb?.enabled ?? false, + enablePostgres: config.database?.postgres?.enabled ?? false, + enableCache: config.database?.dragonfly?.enabled ?? false, + enableQueue: config.queue?.enabled ?? false, + enableQuestDB: config.database?.questdb?.enabled ?? false, + enableBrowser: false, + enableProxy: false, + }) + .build(); + await registerOrchestratorServices(container, { + useRustEngine: config.services?.orchestrator?.backtesting?.useRustEngine ?? true, + allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false, + syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42, + }); + return container.resolve('serviceContainer') as OrchestratorServices; +} diff --git a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts b/apps/stock/orchestrator/src/strategies/BaseStrategy.ts index e9e8bc09..2e9e7ee7 100644 --- a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/BaseStrategy.ts @@ -1,270 +1,292 @@ -import { EventEmitter } from 'events'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('BaseStrategy'); -import { MarketData, StrategyConfig, OrderRequest } from '../types'; -import { ModeManager } from '../core/ModeManager'; -import { ExecutionService } from '../services/ExecutionService'; - -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; - 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 = config; - } - - async initialize(): Promise { - logger.info(`Initializing strategy: ${this.config.name}`); - // 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}`); - this.onStart(); - } - - async stop(): Promise { - this.isActive = false; - - // 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}`); - this.onStop(); - } - - async shutdown(): Promise { - await this.stop(); - this.removeAllListeners(); - logger.info(`Shutdown strategy: ${this.config.name}`); - } - - // 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; - } - - try { - // Update any indicators or state - this.updateIndicators(data); - - // Generate signals - const signal = await this.generateSignal(data); - - if (signal) { - this.emit('signal', signal); - - // Convert signal to order if strong enough - const order = await this.signalToOrder(signal); - if (order) { - this.emit('order', order); - } - } - } catch (error) { - logger.error(`Strategy ${this.config.id} error:`, error); - } - } - - 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); - } - } - - // Order and fill handling - async onOrderUpdate(update: any): Promise { - logger.debug(`Strategy ${this.config.id} order update:`, update); - - if (update.status === 'filled') { - // Remove from pending - this.pendingOrders.delete(update.orderId); - - // Update position tracking - const fill = update.fills[0]; // Assuming single fill for simplicity - if (fill) { - const currentPos = this.positions.get(update.symbol) || 0; - const newPos = update.side === 'buy' - ? currentPos + fill.quantity - : currentPos - fill.quantity; - - logger.info(`[BaseStrategy] Position update for ${update.symbol}: ${currentPos} -> ${newPos} (${update.side} ${fill.quantity})`); - - if (Math.abs(newPos) < 0.0001) { - this.positions.delete(update.symbol); - } else { - this.positions.set(update.symbol, newPos); - } - } - } else if (update.status === 'rejected' || update.status === 'cancelled') { - this.pendingOrders.delete(update.orderId); - } - } - - async onOrderError(order: OrderRequest, error: any): Promise { - logger.error(`Strategy ${this.config.id} order error:`, error); - // Strategies can override to handle errors - } - - async onFill(fill: any): Promise { - // Update performance metrics - this.performance.trades++; - - if (fill.pnl > 0) { - this.performance.wins++; - } else if (fill.pnl < 0) { - this.performance.losses++; - } - - this.performance.totalPnl += fill.pnl; - - // 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 - currentEquity) / this.performance.peakEquity; - this.performance.maxDrawdown = Math.max(this.performance.maxDrawdown, this.performance.currentDrawdown); - } - } - - // Configuration - async updateConfig(updates: Partial): Promise { - this.config = { ...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(this.positions.get(symbol)!) > 0.0001; - } - - getPosition(symbol: string): number { - return this.positions.get(symbol) || 0; - } - - getPerformance(): any { - 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 = 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 = 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 {} - protected onStop(): void {} - protected onConfigUpdate(updates: Partial): void {} -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { ModeManager } from '../core/ModeManager'; +import type { StrategyFill, StrategyOrderUpdate } from '../services/ExecutionService'; +import { ExecutionService } from '../services/ExecutionService'; +import { type MarketData, type OrderRequest, type StrategyConfig } from '../types'; + +const logger = getLogger('BaseStrategy'); + +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; + 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 = config; + } + + async initialize(): Promise { + logger.info(`Initializing strategy: ${this.config.name}`); + // 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; + + // 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.stop(); + this.removeAllListeners(); + logger.info(`Shutdown strategy: ${this.config.name}`); + } + + // 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; + } + + try { + // Update any indicators or state + this.updateIndicators(data); + + // Generate signals + const signal = await this.generateSignal(data); + + if (signal) { + this.emit('signal', signal); + + // Convert signal to order if strong enough + const order = await this.signalToOrder(signal); + if (order) { + this.emit('order', order); + } + } + } catch (error) { + logger.error(`Strategy ${this.config.id} error:`, error); + } + } + + 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 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 (update.status === 'filled') { + // Remove from pending + this.pendingOrders.delete(update.orderId); + + // Update position tracking + const fill = update.fills[0]; // Assuming single fill for simplicity + if (fill) { + const currentPos = this.positions.get(update.symbol) || 0; + const newPos = + update.side === 'buy' ? currentPos + fill.quantity : currentPos - fill.quantity; + + logger.info( + `[BaseStrategy] Position update for ${update.symbol}: ${currentPos} -> ${newPos} (${update.side} ${fill.quantity})` + ); + + if (Math.abs(newPos) < 0.0001) { + this.positions.delete(update.symbol); + } else { + this.positions.set(update.symbol, newPos); + } + } + } else if (update.status === 'rejected' || update.status === 'cancelled') { + this.pendingOrders.delete(update.orderId); + } + } + + 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 { + // 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 - currentEquity) / this.performance.peakEquity; + this.performance.maxDrawdown = Math.max( + this.performance.maxDrawdown, + this.performance.currentDrawdown + ); + } + } + + // Configuration + async updateConfig(updates: Partial): Promise { + this.config = { ...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 {} +} diff --git a/apps/stock/orchestrator/src/strategies/RustStrategy.ts b/apps/stock/orchestrator/src/strategies/RustStrategy.ts index 225357ed..b28116d6 100644 --- a/apps/stock/orchestrator/src/strategies/RustStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/RustStrategy.ts @@ -1,139 +1,130 @@ -import { BacktestEngine } from '@stock-bot/engine'; -import { MarketData } from '../types'; - -export interface Signal { - symbol: string; - signal_type: 'Buy' | 'Sell' | 'Close'; - strength: number; // -1.0 to 1.0 - quantity?: number; - reason?: string; - metadata?: any; -} - -export interface StrategyCall { - method: string; - data: any; -} - -export interface StrategyResponse { - signals: Signal[]; -} - -/** - * Base class for TypeScript strategies that run in the Rust backtest engine - */ -export abstract class RustStrategy { - protected name: string; - protected id: string; - protected parameters: Record; - protected positions: Map = new Map(); - - constructor(name: string, id: string, parameters: Record = {}) { - this.name = name; - this.id = id; - this.parameters = parameters; - } - - /** - * Main callback that Rust will call - */ - public handleCall(call: StrategyCall): StrategyResponse { - switch (call.method) { - case 'on_market_data': - const signals = this.onMarketData(call.data); - return { signals }; - - case 'on_fill': - this.onFill( - call.data.symbol, - call.data.quantity, - call.data.price, - call.data.side - ); - return { signals: [] }; - - default: - return { signals: [] }; - } - } - - /** - * Called when new market data is received - */ - protected abstract onMarketData(data: MarketData): Signal[]; - - /** - * Called when an order is filled - */ - protected onFill(symbol: string, quantity: number, price: number, side: string): void { - const currentPosition = this.positions.get(symbol) || 0; - const newPosition = side === 'buy' ? - currentPosition + quantity : - currentPosition - quantity; - - if (Math.abs(newPosition) < 0.0001) { - this.positions.delete(symbol); - } else { - this.positions.set(symbol, newPosition); - } - } - - /** - * Helper to create a buy signal - */ - protected buySignal(symbol: string, strength: number = 1.0, reason?: string): Signal { - return { - symbol, - signal_type: 'Buy', - strength, - reason, - }; - } - - /** - * Helper to create a sell signal - */ - protected sellSignal(symbol: string, strength: number = 1.0, reason?: string): Signal { - return { - symbol, - signal_type: 'Sell', - strength, - reason, - }; - } - - /** - * Helper to create a close position signal - */ - protected closeSignal(symbol: string, reason?: string): Signal { - return { - symbol, - signal_type: 'Close', - strength: 1.0, - reason, - }; - } - - /** - * Register this strategy with a backtest engine - */ - public register(engine: BacktestEngine): void { - console.log(`Registering strategy ${this.name} with id ${this.id}`); - - // Convert the handleCall method to what Rust expects - const callback = (callJson: string) => { - console.log('Strategy callback called with:', callJson); - const call: StrategyCall = JSON.parse(callJson); - const response = this.handleCall(call); - console.log('Strategy response:', response); - return JSON.stringify(response); - }; - - engine.addTypescriptStrategy( - this.name, - this.id, - this.parameters, - callback as any - ); - } -} \ No newline at end of file +import { BacktestEngine } from '@stock-bot/engine'; +import { getLogger } from '@stock-bot/logger'; +import { type MarketData } from '../types'; + +const logger = getLogger('rust-strategy'); + +export interface Signal { + symbol: string; + signal_type: 'Buy' | 'Sell' | 'Close'; + strength: number; // -1.0 to 1.0 + quantity?: number; + reason?: string; + metadata?: unknown; +} + +export type StrategyCall = + | { method: 'on_market_data'; data: MarketData } + | { method: 'on_fill'; data: { symbol: string; quantity: number; price: number; side: string } }; + +export interface StrategyResponse { + signals: Signal[]; +} + +/** + * Base class for TypeScript strategies that run in the Rust backtest engine + */ +export abstract class RustStrategy { + protected name: string; + protected id: string; + protected parameters: Record; + protected positions: Map = new Map(); + + constructor(name: string, id: string, parameters: Record = {}) { + this.name = name; + this.id = id; + this.parameters = parameters; + } + + /** + * Main callback that Rust will call + */ + public handleCall(call: StrategyCall): StrategyResponse { + switch (call.method) { + case 'on_market_data': { + const signals = this.onMarketData(call.data); + return { signals }; + } + + case 'on_fill': + this.onFill(call.data.symbol, call.data.quantity, call.data.price, call.data.side); + return { signals: [] }; + + default: + return { signals: [] }; + } + } + + /** + * Called when new market data is received + */ + protected abstract onMarketData(data: MarketData): Signal[]; + + /** + * Called when an order is filled + */ + protected onFill(symbol: string, quantity: number, price: number, side: string): void { + const currentPosition = this.positions.get(symbol) || 0; + const newPosition = side === 'buy' ? currentPosition + quantity : currentPosition - quantity; + + if (Math.abs(newPosition) < 0.0001) { + this.positions.delete(symbol); + } else { + this.positions.set(symbol, newPosition); + } + } + + /** + * Helper to create a buy signal + */ + protected buySignal(symbol: string, strength: number = 1.0, reason?: string): Signal { + return { + symbol, + signal_type: 'Buy', + strength, + reason, + }; + } + + /** + * Helper to create a sell signal + */ + protected sellSignal(symbol: string, strength: number = 1.0, reason?: string): Signal { + return { + symbol, + signal_type: 'Sell', + strength, + reason, + }; + } + + /** + * Helper to create a close position signal + */ + protected closeSignal(symbol: string, reason?: string): Signal { + return { + symbol, + signal_type: 'Close', + strength: 1.0, + reason, + }; + } + + /** + * Register this strategy with a backtest engine + */ + public register(engine: BacktestEngine): void { + logger.debug(`Registering strategy ${this.name} with id ${this.id}`); + + // Convert the handleCall method to what Rust expects + const callback = (callJson: string) => { + logger.debug('Strategy callback', { callJson }); + const call: StrategyCall = JSON.parse(callJson); + const response = this.handleCall(call); + logger.debug('Strategy response:', response); + return JSON.stringify(response); + }; + + engine.addTypescriptStrategy(this.name, this.id, this.parameters, callback); + } +} diff --git a/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts b/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts index 6a487e72..c615836f 100644 --- a/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts +++ b/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts @@ -1,135 +1,151 @@ -import { MarketData, Signal } from '../types'; - -export interface IStrategyExecutor { - onMarketData(data: MarketData): Signal[]; - onFill(symbol: string, quantity: number, price: number, side: string): void; - getState(): any; - setState(state: any): void; -} - -/** - * Executes strategies in-process for backtesting - * This avoids the complexity of async callbacks between Rust and TypeScript - */ -export class StrategyExecutor implements IStrategyExecutor { - private strategies: Map = new Map(); - private strategyStates: Map = new Map(); - - registerStrategy(id: string, strategy: any) { - this.strategies.set(id, strategy); - this.strategyStates.set(id, { - priceHistory: new Map(), - positions: new Map(), - }); - } - - onMarketData(data: MarketData): Signal[] { - const allSignals: Signal[] = []; - - for (const [id, strategy] of this.strategies) { - const state = this.strategyStates.get(id)!; - const signals = strategy.onMarketData(data, state); - - if (signals && signals.length > 0) { - allSignals.push(...signals); - } - } - - return allSignals; - } - - onFill(symbol: string, quantity: number, price: number, side: string): void { - for (const [id, strategy] of this.strategies) { - const state = this.strategyStates.get(id)!; - - if (strategy.onFill) { - strategy.onFill({ symbol, quantity, price, side }, state); - } - - // Update position tracking - const currentPos = state.positions.get(symbol) || 0; - const newPos = side === 'buy' ? currentPos + quantity : currentPos - quantity; - - if (Math.abs(newPos) < 0.0001) { - state.positions.delete(symbol); - } else { - state.positions.set(symbol, newPos); - } - } - } - - getState(): any { - return Object.fromEntries(this.strategyStates); - } - - setState(state: any): void { - this.strategyStates = new Map(Object.entries(state)); - } -} - -// Example SMA Crossover Strategy -export const SMACrossoverStrategy = { - onMarketData(data: MarketData, state: any): Signal[] { - const signals: Signal[] = []; - - // Check if it's bar data - if (data.type !== 'bar') return signals; - - const { symbol, close } = data.data; - const fastPeriod = 5; - const slowPeriod = 15; - - // Update price history - if (!state.priceHistory.has(symbol)) { - state.priceHistory.set(symbol, []); - } - - const history = state.priceHistory.get(symbol)!; - history.push(close); - - // Keep only necessary history - if (history.length > slowPeriod + 1) { - history.shift(); - } - - // Need enough data - if (history.length >= slowPeriod) { - // Calculate SMAs - const fastSMA = history.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; - const slowSMA = history.reduce((a, b) => a + b, 0) / history.length; - - // Previous SMAs (if we have enough history) - if (history.length > slowPeriod) { - const prevHistory = history.slice(0, -1); - const prevFastSMA = prevHistory.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; - const prevSlowSMA = prevHistory.reduce((a, b) => a + b, 0) / prevHistory.length; - - const currentPosition = state.positions.get(symbol) || 0; - - // Golden cross - buy signal - if (prevFastSMA <= prevSlowSMA && fastSMA > slowSMA && currentPosition <= 0) { - signals.push({ - symbol, - signal_type: 'Buy', - strength: 1.0, - quantity: 100, - reason: 'Golden cross', - }); - } - - // Death cross - sell signal - else if (prevFastSMA >= prevSlowSMA && fastSMA < slowSMA && currentPosition >= 0) { - signals.push({ - symbol, - signal_type: 'Sell', - strength: 1.0, - quantity: 100, - reason: 'Death cross', - }); - } - } - } - - return signals; - }, -}; \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import type { MarketData } from '../types'; +import type { Signal } from './RustStrategy'; + +interface StrategyState { + priceHistory: Map; + positions: Map; +} +interface InlineStrategy { + onMarketData(data: MarketData, state: StrategyState): Signal[]; + onFill?( + fill: { symbol: string; quantity: number; price: number; side: string }, + state: StrategyState + ): void; +} + +export interface IStrategyExecutor { + onMarketData(data: MarketData): Signal[]; + onFill(symbol: string, quantity: number, price: number, side: string): void; + getState(): Record; + setState(state: Record): void; +} + +/** + * Executes strategies in-process for backtesting + * This avoids the complexity of async callbacks between Rust and TypeScript + */ +export class StrategyExecutor implements IStrategyExecutor { + private strategies: Map = new Map(); + private strategyStates: Map = new Map(); + + registerStrategy(id: string, strategy: InlineStrategy) { + this.strategies.set(id, strategy); + this.strategyStates.set(id, { + priceHistory: new Map(), + positions: new Map(), + }); + } + + onMarketData(data: MarketData): Signal[] { + const allSignals: Signal[] = []; + + for (const [id, strategy] of this.strategies) { + const state = defined(this.strategyStates.get(id)); + const signals = strategy.onMarketData(data, state); + + if (signals && signals.length > 0) { + allSignals.push(...signals); + } + } + + return allSignals; + } + + onFill(symbol: string, quantity: number, price: number, side: string): void { + for (const [id, strategy] of this.strategies) { + const state = defined(this.strategyStates.get(id)); + + if (strategy.onFill) { + strategy.onFill({ symbol, quantity, price, side }, state); + } + + // Update position tracking + const currentPos = state.positions.get(symbol) || 0; + const newPos = side === 'buy' ? currentPos + quantity : currentPos - quantity; + + if (Math.abs(newPos) < 0.0001) { + state.positions.delete(symbol); + } else { + state.positions.set(symbol, newPos); + } + } + } + + getState() { + return Object.fromEntries(this.strategyStates); + } + + setState(state: Record): void { + this.strategyStates = new Map(Object.entries(state)); + } +} + +// Example SMA Crossover Strategy +export const SMACrossoverStrategy = { + onMarketData(data: MarketData, state: StrategyState): Signal[] { + const signals: Signal[] = []; + + // Check if it's bar data + if (data.type !== 'bar') { + return signals; + } + + const { symbol, close } = data.data; + const fastPeriod = 5; + const slowPeriod = 15; + + // Update price history + if (!state.priceHistory.has(symbol)) { + state.priceHistory.set(symbol, []); + } + + const history = defined(state.priceHistory.get(symbol)); + history.push(close); + + // Keep only necessary history + if (history.length > slowPeriod + 1) { + history.shift(); + } + + // Need enough data + if (history.length >= slowPeriod) { + // Calculate SMAs + const fastSMA = history.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; + const slowSMA = history.reduce((a, b) => a + b, 0) / history.length; + + // Previous SMAs (if we have enough history) + if (history.length > slowPeriod) { + const prevHistory = history.slice(0, -1); + const prevFastSMA = prevHistory.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; + const prevSlowSMA = prevHistory.reduce((a, b) => a + b, 0) / prevHistory.length; + + const currentPosition = state.positions.get(symbol) || 0; + + // Golden cross - buy signal + if (prevFastSMA <= prevSlowSMA && fastSMA > slowSMA && currentPosition <= 0) { + signals.push({ + symbol, + signal_type: 'Buy', + strength: 1.0, + quantity: 100, + reason: 'Golden cross', + }); + } + + // Death cross - sell signal + else if (prevFastSMA >= prevSlowSMA && fastSMA < slowSMA && currentPosition >= 0) { + signals.push({ + symbol, + signal_type: 'Sell', + strength: 1.0, + quantity: 100, + reason: 'Death cross', + }); + } + } + } + + return signals; + }, +}; diff --git a/apps/stock/orchestrator/src/strategies/StrategyManager.ts b/apps/stock/orchestrator/src/strategies/StrategyManager.ts index 6d733879..ca8d394d 100644 --- a/apps/stock/orchestrator/src/strategies/StrategyManager.ts +++ b/apps/stock/orchestrator/src/strategies/StrategyManager.ts @@ -1,294 +1,299 @@ -import { IServiceContainer } from '@stock-bot/di'; -import { TradingEngine } from '@stock-bot/engine'; -import { EventEmitter } from 'events'; -import { MarketData, OrderRequest, StrategyConfig } from '../types'; -import { BaseStrategy } from './BaseStrategy'; - -export class StrategyManager extends EventEmitter { - private strategies = new Map(); - private activeStrategies = new Set(); - private tradingEngine: TradingEngine | null = null; - private container: IServiceContainer; - - constructor(container: IServiceContainer) { - super(); - this.container = container; - } - - setupEventListeners(): void { - const marketDataService = this.container.custom?.MarketDataService; - const executionService = this.container.custom?.ExecutionService; - - if (!marketDataService || !executionService) { - this.container.logger.error('Required services not found in container'); - return; - } - - // Listen for market data - marketDataService.on('marketData', (data: MarketData) => { - this.handleMarketData(data); - }); - - // Listen for market data batches (more efficient) - marketDataService.on('marketDataBatch', (batch: MarketData[]) => { - this.handleMarketDataBatch(batch); - }); - - // Listen for fills - executionService.on('fill', (fill: any) => { - this.handleFill(fill); - }); - } - - async initializeStrategies(configs: StrategyConfig[]): Promise { - // Clear existing strategies - for (const [id, strategy] of this.strategies) { - await strategy.shutdown(); - } - this.strategies.clear(); - this.activeStrategies.clear(); - - // Get trading engine from mode manager - const modeManager = this.container.custom?.ModeManager; - if (modeManager) { - this.tradingEngine = modeManager.getTradingEngine(); - } - - // 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.container.logger.info(`Initialized strategy: ${config.name} (${config.id})`); - } catch (error) { - this.container.logger.error(`Failed to initialize strategy ${config.name}:`, error); - } - } - } - - private async createStrategy(config: StrategyConfig): Promise { - // Load strategy based on name - let strategy: BaseStrategy; - - switch (config.name.toLowerCase()) { - case 'meanreversion': - case 'mean-reversion': { - const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy'); - strategy = new MeanReversionStrategy( - config, - this.container.custom?.ModeManager, - this.container.custom?.ExecutionService - ); - break; - } - case 'smacrossover': - case 'sma-crossover': - case 'moving-average': { - const { SimpleMovingAverageCrossover } = await import('./examples/SimpleMovingAverageCrossoverFixed'); - strategy = new SimpleMovingAverageCrossover( - config, - this.container.custom?.ModeManager, - this.container.custom?.ExecutionService - ); - break; - } - case 'mlenhanced': - case 'ml-enhanced': { - const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy'); - strategy = new MLEnhancedStrategy( - config, - this.container.custom?.ModeManager, - this.container.custom?.ExecutionService - ); - break; - } - default: - // Default to base strategy - this.container.logger.warn(`Unknown strategy: ${config.name}, using base strategy`); - strategy = new BaseStrategy( - config, - this.container.custom?.ModeManager, - this.container.custom?.ExecutionService - ); - break; - } - - // Set up strategy event handlers - strategy.on('signal', (signal: any) => { - this.handleStrategySignal(config.id, signal); - }); - - strategy.on('order', (order: any) => { - this.handleStrategyOrder(config.id, order); - }); - - strategy.on('error', (error: Error) => { - this.container.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`); - } - - await strategy.initialize(); - await strategy.start(); // Start the strategy to make it active - this.activeStrategies.add(strategyId); - this.container.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`); - } - - await strategy.shutdown(); - this.activeStrategies.delete(strategyId); - this.container.logger.info(`Disabled strategy: ${strategyId}`); - } - - async onMarketData(data: MarketData): Promise { - return this.handleMarketData(data); - } - - private async handleMarketData(data: MarketData): Promise { - // Forward to all active strategies - if (this.activeStrategies.size === 0) { - this.container.logger.info(`[StrategyManager] No active strategies to process market data! All strategies: ${Array.from(this.strategies.keys()).join(', ')}`); - } else { - this.container.logger.info(`[StrategyManager] Forwarding market data to ${this.activeStrategies.size} active strategies: ${Array.from(this.activeStrategies).join(', ')}`); - } - - for (const strategyId of this.activeStrategies) { - const strategy = this.strategies.get(strategyId); - if (strategy) { - try { - await strategy.onMarketData(data); - } catch (error) { - this.container.logger.error(`Error processing market data for strategy ${strategyId}:`, error); - } - } - } - } - - private async handleMarketDataBatch(batch: MarketData[]): Promise { - // Process batch more efficiently - for (const strategyId of this.activeStrategies) { - const strategy = this.strategies.get(strategyId); - if (strategy) { - try { - await strategy.onMarketDataBatch(batch); - } catch (error) { - this.container.logger.error(`Error processing market data batch for strategy ${strategyId}:`, error); - } - } - } - } - - private async handleFill(fill: any): Promise { - // Forward fill to the strategy that created the order - for (const [strategyId, strategy] of this.strategies) { - if (strategy.hasOrder(fill.orderId)) { - try { - await strategy.onFill(fill); - } catch (error) { - this.container.logger.error(`Error processing fill for strategy ${strategyId}:`, error); - } - break; - } - } - } - - private async handleStrategySignal(strategyId: string, signal: any): Promise { - this.container.logger.info(`Strategy ${strategyId} generated signal:`, signal); - // Signals are informational - strategies will convert strong signals to orders - } - - private async handleStrategyOrder(strategyId: string, order: OrderRequest): Promise { - this.container.logger.info(`Strategy ${strategyId} generated order:`, order); - - // Submit order through trading engine (for backtesting) - if (this.tradingEngine) { - try { - // Create order object for Rust API - const orderObj = { - id: `${strategyId}-${Date.now()}`, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce || 'DAY' - }; - - const orderResult = await this.tradingEngine.submitOrder(orderObj); - const result = JSON.parse(orderResult); - this.container.logger.info(`Order placed for strategy ${strategyId}: ${result.order_id}`); - - // Emit order event - this.emit('order', { - strategyId, - orderId: result.order_id, - order - }); - } catch (error) { - this.container.logger.error(`Failed to place order for strategy ${strategyId}:`, error); - } - } else { - // Use execution service for paper/live trading - const executionService = this.container.custom?.ExecutionService; - if (executionService) { - try { - const result = await executionService.submitOrder(order); - this.container.logger.info(`Order submitted for strategy ${strategyId}:`, result); - } catch (error) { - this.container.logger.error(`Failed to submit order for strategy ${strategyId}:`, error); - } - } - } - } - - async onMarketData(data: MarketData): Promise { - await this.handleMarketData(data); - } - - getTradingEngine(): TradingEngine | null { - return this.tradingEngine; - } - - 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.container.logger.info('Shutting down strategy manager...'); - - // Disable all strategies - for (const strategyId of this.activeStrategies) { - await this.disableStrategy(strategyId); - } - - // Clear all strategies - this.strategies.clear(); - this.activeStrategies.clear(); - this.tradingEngine = null; - } -} \ No newline at end of file +import { EventEmitter } from 'events'; +import { TradingEngine } from '@stock-bot/engine'; +import { defined } from '@stock-bot/invariants'; +import type { StrategyFill } from '../services/ExecutionService'; +import type { OrchestratorServices as IServiceContainer } from '../types'; +import { type MarketData, type OrderRequest, type StrategyConfig } from '../types'; +import type { Signal } from './BaseStrategy'; +import { BaseStrategy } from './BaseStrategy'; + +export class StrategyManager extends EventEmitter { + private strategies = new Map(); + private activeStrategies = new Set(); + private tradingEngine: TradingEngine | null = null; + private container: IServiceContainer; + + constructor(container: IServiceContainer) { + super(); + this.container = container; + } + + setupEventListeners(): void { + const marketDataService = this.container.custom?.MarketDataService; + const executionService = this.container.custom?.ExecutionService; + + if (!marketDataService || !executionService) { + this.container.logger.error('Required services not found in container'); + return; + } + + // Listen for market data + marketDataService.on('marketData', (data: MarketData) => { + this.handleMarketData(data); + }); + + // Listen for market data batches (more efficient) + marketDataService.on('marketDataBatch', (batch: MarketData[]) => { + this.handleMarketDataBatch(batch); + }); + + // Listen for fills + executionService.on('fill', fill => { + this.handleFill(fill); + }); + } + + async initializeStrategies(configs: StrategyConfig[]): Promise { + // Clear existing strategies + for (const [_id, strategy] of this.strategies) { + await strategy.shutdown(); + } + this.strategies.clear(); + this.activeStrategies.clear(); + + // Get trading engine from mode manager + const modeManager = this.container.custom?.ModeManager; + if (modeManager) { + this.tradingEngine = modeManager.getTradingEngine(); + } + + // 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.container.logger.info(`Initialized strategy: ${config.name} (${config.id})`); + } catch (error) { + this.container.logger.error(`Failed to initialize strategy ${config.name}:`, error); + throw error; + } + } + } + + private async createStrategy(config: StrategyConfig): Promise { + // Load strategy based on name + let strategy: BaseStrategy; + + switch (config.name.toLowerCase()) { + case 'meanreversion': + case 'mean-reversion': { + const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy'); + strategy = new MeanReversionStrategy( + config, + defined(this.container.custom?.ModeManager), + defined(this.container.custom?.ExecutionService) + ); + break; + } + case 'smacrossover': + case 'sma-crossover': + case 'moving-average': { + const { SimpleMovingAverageCrossover } = await import( + './examples/SimpleMovingAverageCrossoverFixed' + ); + strategy = new SimpleMovingAverageCrossover( + config, + defined(this.container.custom?.ModeManager), + defined(this.container.custom?.ExecutionService) + ); + break; + } + case 'mlenhanced': + case 'ml-enhanced': { + const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy'); + strategy = new MLEnhancedStrategy( + config, + defined(this.container.custom?.ModeManager), + defined(this.container.custom?.ExecutionService) + ); + break; + } + default: + throw new Error(`Unknown strategy: ${config.name}`); + } + + // Set up strategy event handlers + strategy.on('signal', signal => { + this.handleStrategySignal(config.id, signal); + }); + + strategy.on('order', order => { + this.handleStrategyOrder(config.id, order); + }); + + strategy.on('error', (error: Error) => { + this.container.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`); + } + + await strategy.initialize(); + await strategy.start(); // Start the strategy to make it active + this.activeStrategies.add(strategyId); + this.container.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`); + } + + await strategy.shutdown(); + this.activeStrategies.delete(strategyId); + this.container.logger.info(`Disabled strategy: ${strategyId}`); + } + + private async handleMarketData(data: MarketData): Promise { + // Forward to all active strategies + if (this.activeStrategies.size === 0) { + this.container.logger.info( + `[StrategyManager] No active strategies to process market data! All strategies: ${Array.from(this.strategies.keys()).join(', ')}` + ); + } else { + this.container.logger.info( + `[StrategyManager] Forwarding market data to ${this.activeStrategies.size} active strategies: ${Array.from(this.activeStrategies).join(', ')}` + ); + } + + for (const strategyId of this.activeStrategies) { + const strategy = this.strategies.get(strategyId); + if (strategy) { + try { + await strategy.onMarketData(data); + } catch (error) { + this.container.logger.error( + `Error processing market data for strategy ${strategyId}:`, + error + ); + } + } + } + } + + private async handleMarketDataBatch(batch: MarketData[]): Promise { + // Process batch more efficiently + for (const strategyId of this.activeStrategies) { + const strategy = this.strategies.get(strategyId); + if (strategy) { + try { + await strategy.onMarketDataBatch(batch); + } catch (error) { + this.container.logger.error( + `Error processing market data batch for strategy ${strategyId}:`, + error + ); + } + } + } + } + + private async handleFill(fill: StrategyFill): Promise { + // Forward fill to the strategy that created the order + for (const [strategyId, strategy] of this.strategies) { + if (strategy.hasOrder(fill.orderId)) { + try { + await strategy.onFill(fill); + } catch (error) { + this.container.logger.error(`Error processing fill for strategy ${strategyId}:`, error); + } + break; + } + } + } + + private async handleStrategySignal(strategyId: string, signal: Signal): Promise { + this.container.logger.info(`Strategy ${strategyId} generated signal:`, signal); + // Signals are informational - strategies will convert strong signals to orders + } + + private async handleStrategyOrder(strategyId: string, order: OrderRequest): Promise { + this.container.logger.info(`Strategy ${strategyId} generated order:`, order); + + // Submit order through trading engine (for backtesting) + if (this.tradingEngine) { + try { + // Create order object for Rust API + const orderObj = { + id: `${strategyId}-${Date.now()}`, + symbol: order.symbol, + side: order.side, + quantity: order.quantity, + orderType: order.orderType, + limitPrice: order.limitPrice, + timeInForce: order.timeInForce || 'DAY', + }; + + const orderResult = await this.tradingEngine.submitOrder(orderObj); + const result = JSON.parse(orderResult); + this.container.logger.info(`Order placed for strategy ${strategyId}: ${result.order_id}`); + + // Emit order event + this.emit('order', { + strategyId, + orderId: result.order_id, + order, + }); + } catch (error) { + this.container.logger.error(`Failed to place order for strategy ${strategyId}:`, error); + } + } else { + // Use execution service for paper/live trading + const executionService = this.container.custom?.ExecutionService; + if (executionService) { + try { + const result = await executionService.submitOrder(order); + this.container.logger.info(`Order submitted for strategy ${strategyId}:`, result); + } catch (error) { + this.container.logger.error(`Failed to submit order for strategy ${strategyId}:`, error); + } + } + } + } + + async onMarketData(data: MarketData): Promise { + await this.handleMarketData(data); + } + + getTradingEngine(): TradingEngine | null { + return this.tradingEngine; + } + + 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.container.logger.info('Shutting down strategy manager...'); + + // Disable all strategies + for (const strategyId of this.activeStrategies) { + await this.disableStrategy(strategyId); + } + + // Clear all strategies + this.strategies.clear(); + this.activeStrategies.clear(); + this.tradingEngine = null; + } +} diff --git a/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts index fbbf2df9..39aeb991 100644 --- a/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts @@ -1,551 +1,590 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { IndicatorManager } from '../indicators/IndicatorManager'; -import { PositionManager } from '../position/PositionManager'; -import { RiskManager } from '../risk/RiskManager'; -import { SignalManager, CommonRules, CommonFilters } from '../signals/SignalManager'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('AdvancedMultiIndicatorStrategy'); - -export interface AdvancedStrategyConfig { - // Indicator settings - fastMA?: number; - slowMA?: number; - rsiPeriod?: number; - atrPeriod?: number; - - // Risk settings - riskPerTrade?: number; - maxPositions?: number; - maxDrawdown?: number; - useATRStops?: boolean; - atrMultiplier?: number; - - // Signal settings - signalAggregation?: 'weighted' | 'majority' | 'unanimous' | 'threshold'; - minSignalStrength?: number; - minSignalConfidence?: number; - - // Position sizing - positionSizing?: 'fixed' | 'risk' | 'kelly' | 'volatility'; - - // Other - debugMode?: boolean; -} - -/** - * Advanced strategy using multiple indicators, risk management, and signal aggregation - */ -export class AdvancedMultiIndicatorStrategy extends BaseStrategy { - private indicatorManager: IndicatorManager; - private positionManager: PositionManager; - private riskManager: RiskManager; - private signalManager: SignalManager; - - private config: Required; - private stopLosses: Map = new Map(); - private takeProfits: Map = new Map(); - - constructor(strategyConfig: any, modeManager?: any, executionService?: any) { - super(strategyConfig, modeManager, executionService); - - // Initialize config - this.config = { - fastMA: 20, - slowMA: 50, - rsiPeriod: 14, - atrPeriod: 14, - riskPerTrade: 0.02, - maxPositions: 5, - maxDrawdown: 0.2, - useATRStops: true, - atrMultiplier: 2, - signalAggregation: 'weighted', - minSignalStrength: 0.5, - minSignalConfidence: 0.3, - positionSizing: 'risk', - debugMode: false, - ...strategyConfig.params - }; - - // Initialize managers - const initialCapital = strategyConfig.initialCapital || 100000; - this.indicatorManager = new IndicatorManager(); - this.positionManager = new PositionManager(initialCapital); - this.riskManager = new RiskManager(initialCapital, { - maxPositions: this.config.maxPositions, - maxDrawdownPct: this.config.maxDrawdown, - maxPositionSizePct: 0.1 - }); - - this.signalManager = new SignalManager({ - method: this.config.signalAggregation - }); - - // Setup signal rules - this.setupSignalRules(); - - logger.info('AdvancedMultiIndicatorStrategy initialized:', this.config); - } - - private setupSignalRules(): void { - // Moving average rules - this.signalManager.addRule({ - name: `MA Crossover (${this.config.fastMA}/${this.config.slowMA})`, - condition: (indicators) => { - const fast = indicators[`sma${this.config.fastMA}`]; - const slow = indicators[`sma${this.config.slowMA}`]; - const prevFast = indicators[`sma${this.config.fastMA}_prev`]; - const prevSlow = indicators[`sma${this.config.slowMA}_prev`]; - - if (!fast || !slow || !prevFast || !prevSlow) return false; - - // Check for crossover - const crossover = prevFast <= prevSlow && fast > slow; - const crossunder = prevFast >= prevSlow && fast < slow; - - indicators._maCrossDirection = crossover ? 'up' : crossunder ? 'down' : null; - return crossover || crossunder; - }, - weight: 1, - direction: 'both' - }); - - // RSI rules - this.signalManager.addRules([ - CommonRules.rsiOversold(30), - CommonRules.rsiOverbought(70) - ]); - - // MACD rules - this.signalManager.addRules([ - CommonRules.macdBullishCross(), - CommonRules.macdBearishCross() - ]); - - // Bollinger Band rules - this.signalManager.addRules([ - CommonRules.priceAtLowerBand(), - CommonRules.priceAtUpperBand(), - CommonRules.bollingerSqueeze() - ]); - - // Add filters - this.signalManager.addFilter(CommonFilters.minStrength(this.config.minSignalStrength)); - this.signalManager.addFilter(CommonFilters.minConfidence(this.config.minSignalConfidence)); - this.signalManager.addFilter(CommonFilters.trendAlignment('sma200')); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') return; - - const { symbol, timestamp, open, high, low, close, volume } = data.data; - - // First time setup for symbol - if (!this.indicatorManager.getHistoryLength(symbol)) { - this.setupSymbolIndicators(symbol); - } - - // Update price history - this.indicatorManager.updatePrice({ - symbol, - timestamp, - open, - high, - low, - close, - volume - }); - - // Update position market values - this.updatePositionValues(symbol, close); - - // Check stop losses and take profits - this.checkExitConditions(symbol, close); - } - - private setupSymbolIndicators(symbol: string): void { - // Setup incremental indicators - this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { - type: 'sma', - period: this.config.fastMA - }); - - this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { - type: 'sma', - period: this.config.slowMA - }); - - this.indicatorManager.setupIncrementalIndicator(symbol, 'rsi', { - type: 'rsi', - period: this.config.rsiPeriod - }); - - logger.info(`Initialized indicators for ${symbol}`); - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') return null; - - const { symbol, timestamp, close } = data.data; - const historyLength = this.indicatorManager.getHistoryLength(symbol); - - // Need enough data - if (historyLength < Math.max(this.config.slowMA, 26)) { - return null; - } - - // Prepare indicators for signal generation - const indicators = this.prepareIndicators(symbol, close); - if (!indicators) return null; - - // Check risk before generating signals - const currentPositions = this.getCurrentPositionMap(); - const riskCheck = this.riskManager.checkNewPosition( - symbol, - 100, // Dummy size for check - close, - currentPositions - ); - - if (!riskCheck.allowed && !this.positionManager.hasPosition(symbol)) { - if (this.config.debugMode) { - logger.warn(`Risk check failed for ${symbol}: ${riskCheck.reason}`); - } - return null; - } - - // Generate trading signal - const tradingSignal = this.signalManager.generateSignal( - symbol, - timestamp, - indicators, - { position: this.positionManager.getPositionQuantity(symbol) } - ); - - if (!tradingSignal) return null; - - // Log signal if in debug mode - if (this.config.debugMode) { - logger.info(`Signal generated for ${symbol}:`, { - direction: tradingSignal.direction, - strength: tradingSignal.strength.toFixed(2), - confidence: tradingSignal.confidence.toFixed(2), - rules: tradingSignal.rules - }); - } - - // Convert to strategy signal - return this.convertToStrategySignal(tradingSignal, symbol, close); - } - - private prepareIndicators(symbol: string, currentPrice: number): Record | null { - const indicators: Record = { price: currentPrice }; - - // Get moving averages - const fastMA = this.indicatorManager.getSMA(symbol, this.config.fastMA); - const slowMA = this.indicatorManager.getSMA(symbol, this.config.slowMA); - const sma200 = this.indicatorManager.getSMA(symbol, 200); - - if (!fastMA || !slowMA) return null; - - // Current and previous values - indicators[`sma${this.config.fastMA}`] = this.indicatorManager.getLatest(fastMA)!; - indicators[`sma${this.config.slowMA}`] = this.indicatorManager.getLatest(slowMA)!; - - if (fastMA.length >= 2 && slowMA.length >= 2) { - indicators[`sma${this.config.fastMA}_prev`] = fastMA[fastMA.length - 2]; - indicators[`sma${this.config.slowMA}_prev`] = slowMA[slowMA.length - 2]; - } - - if (sma200) { - indicators.sma200 = this.indicatorManager.getLatest(sma200)!; - } - - // RSI - const rsi = this.indicatorManager.getRSI(symbol, this.config.rsiPeriod); - if (rsi) { - indicators.rsi = this.indicatorManager.getLatest(rsi)!; - } - - // MACD - const macd = this.indicatorManager.getMACD(symbol); - if (macd) { - indicators.macd = this.indicatorManager.getLatest(macd.macd)!; - indicators.macd_signal = this.indicatorManager.getLatest(macd.signal)!; - indicators.macd_histogram = this.indicatorManager.getLatest(macd.histogram)!; - - if (macd.macd.length >= 2) { - indicators.macd_prev = macd.macd[macd.macd.length - 2]; - indicators.macd_signal_prev = macd.signal[macd.signal.length - 2]; - } - } - - // Bollinger Bands - const bb = this.indicatorManager.getBollingerBands(symbol); - if (bb) { - indicators.bb_upper = this.indicatorManager.getLatest(bb.upper)!; - indicators.bb_middle = this.indicatorManager.getLatest(bb.middle)!; - indicators.bb_lower = this.indicatorManager.getLatest(bb.lower)!; - } - - // ATR for volatility - const atr = this.indicatorManager.getATR(symbol, this.config.atrPeriod); - if (atr) { - indicators.atr = this.indicatorManager.getLatest(atr)!; - } - - // Volume - const priceHistory = this.indicatorManager.getPriceHistory(symbol); - if (priceHistory) { - indicators.volume = priceHistory.volume[priceHistory.volume.length - 1]; - const avgVolume = priceHistory.volume.slice(-20).reduce((a, b) => a + b, 0) / 20; - indicators.avg_volume = avgVolume; - } - - return indicators; - } - - private convertToStrategySignal( - tradingSignal: TradingSignal, - symbol: string, - currentPrice: number - ): Signal | null { - const currentPosition = this.positionManager.getPositionQuantity(symbol); - - // Determine action based on signal and current position - let type: 'buy' | 'sell' | 'close'; - let quantity: number; - - if (tradingSignal.direction === 'buy') { - if (currentPosition < 0) { - // Close short position - type = 'buy'; - quantity = Math.abs(currentPosition); - } else if (currentPosition === 0) { - // Open long position - type = 'buy'; - quantity = this.calculatePositionSize(symbol, currentPrice, tradingSignal); - } else { - // Already long - return null; - } - } else if (tradingSignal.direction === 'sell') { - if (currentPosition > 0) { - // Close long position - type = 'sell'; - quantity = currentPosition; - } else if (currentPosition === 0 && false) { // Disable shorting for now - // Open short position - type = 'sell'; - quantity = this.calculatePositionSize(symbol, currentPrice, tradingSignal); - } else { - return null; - } - } else { - return null; - } - - return { - type, - symbol, - strength: tradingSignal.strength, - reason: tradingSignal.rules.join(', '), - metadata: { - ...tradingSignal.indicators, - quantity, - confidence: tradingSignal.confidence, - rules: tradingSignal.rules - } - }; - } - - private calculatePositionSize( - symbol: string, - price: number, - signal: TradingSignal - ): number { - const accountBalance = this.positionManager.getAccountBalance(); - - switch (this.config.positionSizing) { - case 'fixed': - // Fixed percentage of account - const fixedValue = accountBalance * this.config.riskPerTrade * 5; - return Math.floor(fixedValue / price); - - case 'risk': - // Risk-based sizing with ATR stop - const atr = signal.indicators.atr; - if (atr && this.config.useATRStops) { - const stopDistance = atr * this.config.atrMultiplier; - return this.positionManager.calculatePositionSize({ - accountBalance, - riskPerTrade: this.config.riskPerTrade, - stopLossDistance: stopDistance - }, price); - } - break; - - case 'kelly': - // Kelly criterion based on historical performance - const metrics = this.positionManager.getPerformanceMetrics(); - if (metrics.totalTrades >= 20) { - return this.positionManager.calculateKellySize( - metrics.winRate / 100, - metrics.avgWin, - metrics.avgLoss, - price - ); - } - break; - - case 'volatility': - // Volatility-adjusted sizing - const atrVol = signal.indicators.atr; - if (atrVol) { - return this.positionManager.calculatePositionSize({ - accountBalance, - riskPerTrade: this.config.riskPerTrade, - volatilityAdjustment: true, - atr: atrVol - }, price); - } - break; - } - - // Default sizing - return this.positionManager.calculatePositionSize({ - accountBalance, - riskPerTrade: this.config.riskPerTrade - }, price); - } - - private updatePositionValues(symbol: string, currentPrice: number): void { - const prices = new Map([[symbol, currentPrice]]); - this.positionManager.updateMarketPrices(prices); - } - - private checkExitConditions(symbol: string, currentPrice: number): void { - const position = this.positionManager.getPosition(symbol); - if (!position) return; - - const stopLoss = this.stopLosses.get(symbol); - const takeProfit = this.takeProfits.get(symbol); - - // Check stop loss - if (stopLoss) { - if ((position.quantity > 0 && currentPrice <= stopLoss) || - (position.quantity < 0 && currentPrice >= stopLoss)) { - logger.info(`Stop loss triggered for ${symbol} at ${currentPrice}`); - this.emit('signal', { - type: 'close', - symbol, - strength: 1, - reason: 'Stop loss triggered', - metadata: { stopLoss, currentPrice } - }); - } - } - - // Check take profit - if (takeProfit) { - if ((position.quantity > 0 && currentPrice >= takeProfit) || - (position.quantity < 0 && currentPrice <= takeProfit)) { - logger.info(`Take profit triggered for ${symbol} at ${currentPrice}`); - this.emit('signal', { - type: 'close', - symbol, - strength: 1, - reason: 'Take profit triggered', - metadata: { takeProfit, currentPrice } - }); - } - } - } - - private getCurrentPositionMap(): Map { - const positionMap = new Map(); - - for (const position of this.positionManager.getOpenPositions()) { - positionMap.set(position.symbol, { - quantity: position.quantity, - value: Math.abs(position.quantity * (position.currentPrice || position.avgPrice)) - }); - } - - return positionMap; - } - - protected async onOrderUpdate(update: any): Promise { - await super.onOrderUpdate(update); - - if (update.status === 'filled' && update.fills?.length > 0) { - for (const fill of update.fills) { - const trade = { - symbol: update.symbol, - side: update.side as 'buy' | 'sell', - quantity: fill.quantity, - price: fill.price, - commission: fill.commission || 0, - timestamp: new Date(fill.timestamp) - }; - - const position = this.positionManager.updatePosition(trade); - - // Update risk manager - if (trade.pnl) { - this.riskManager.updateAfterTrade(trade.pnl); - } - - // Set stop loss and take profit for new positions - if (this.config.useATRStops && position.quantity !== 0) { - const atr = this.indicatorManager.getATR(update.symbol); - if (atr) { - const currentATR = this.indicatorManager.getLatest(atr); - if (currentATR) { - const stopDistance = currentATR * this.config.atrMultiplier; - const profitDistance = currentATR * this.config.atrMultiplier * 2; - - if (position.quantity > 0) { - this.stopLosses.set(update.symbol, fill.price - stopDistance); - this.takeProfits.set(update.symbol, fill.price + profitDistance); - } else { - this.stopLosses.set(update.symbol, fill.price + stopDistance); - this.takeProfits.set(update.symbol, fill.price - profitDistance); - } - - logger.info(`Set stop/take profit for ${update.symbol}: Stop=${this.stopLosses.get(update.symbol)?.toFixed(2)}, TP=${this.takeProfits.get(update.symbol)?.toFixed(2)}`); - } - } - } - - // Clear stops if position closed - if (position.quantity === 0) { - this.stopLosses.delete(update.symbol); - this.takeProfits.delete(update.symbol); - } - } - } - } - - getPerformance(): any { - const basePerf = super.getPerformance(); - const positionMetrics = this.positionManager.getPerformanceMetrics(); - const riskMetrics = this.riskManager.getMetrics(this.getCurrentPositionMap()); - const signalStats = this.signalManager.getSignalStats(); - - return { - ...basePerf, - ...positionMetrics, - risk: riskMetrics, - signals: signalStats - }; - } - - // Daily reset for risk metrics - onDayEnd(): void { - this.riskManager.resetDaily(); - logger.info('Daily risk metrics reset'); - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; +import type { ModeManager } from '../../core/ModeManager'; +import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService'; +import type { StrategyConfig } from '../../types'; +import { type MarketData } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; +import { IndicatorManager } from '../indicators/IndicatorManager'; +import { PositionManager } from '../position/PositionManager'; +import { RiskManager } from '../risk/RiskManager'; +import { + CommonFilters, + CommonRules, + SignalManager, + type TradingSignal, +} from '../signals/SignalManager'; + +const logger = getLogger('AdvancedMultiIndicatorStrategy'); + +export interface AdvancedStrategyConfig { + // Indicator settings + fastMA?: number; + slowMA?: number; + rsiPeriod?: number; + atrPeriod?: number; + + // Risk settings + riskPerTrade?: number; + maxPositions?: number; + maxDrawdown?: number; + useATRStops?: boolean; + atrMultiplier?: number; + + // Signal settings + signalAggregation?: 'weighted' | 'majority' | 'unanimous' | 'threshold'; + minSignalStrength?: number; + minSignalConfidence?: number; + + // Position sizing + positionSizing?: 'fixed' | 'risk' | 'kelly' | 'volatility'; + + // Other + debugMode?: boolean; +} + +/** + * Advanced strategy using multiple indicators, risk management, and signal aggregation + */ +export class AdvancedMultiIndicatorStrategy extends BaseStrategy { + private indicatorManager: IndicatorManager; + private positionManager: PositionManager; + private riskManager: RiskManager; + private signalManager: SignalManager; + + private readonly indicatorConfig: Required; + private stopLosses: Map = new Map(); + private takeProfits: Map = new Map(); + + constructor( + strategyConfig: StrategyConfig, + modeManager: ModeManager, + executionService: ExecutionService + ) { + super(strategyConfig, modeManager, executionService); + + // Initialize config + this.indicatorConfig = { + fastMA: 20, + slowMA: 50, + rsiPeriod: 14, + atrPeriod: 14, + riskPerTrade: 0.02, + maxPositions: 5, + maxDrawdown: 0.2, + useATRStops: true, + atrMultiplier: 2, + signalAggregation: 'weighted', + minSignalStrength: 0.5, + minSignalConfidence: 0.3, + positionSizing: 'risk', + debugMode: false, + ...strategyConfig.parameters, + }; + + // Initialize managers + const initialCapital = Number(strategyConfig.parameters.initialCapital ?? 100000); + this.indicatorManager = new IndicatorManager(); + this.positionManager = new PositionManager(initialCapital); + this.riskManager = new RiskManager(initialCapital, { + maxPositions: this.indicatorConfig.maxPositions, + maxDrawdownPct: this.indicatorConfig.maxDrawdown, + maxPositionSizePct: 0.1, + }); + + this.signalManager = new SignalManager({ + method: this.indicatorConfig.signalAggregation, + }); + + // Setup signal rules + this.setupSignalRules(); + + logger.info('AdvancedMultiIndicatorStrategy initialized:', this.indicatorConfig); + } + + private setupSignalRules(): void { + // Moving average rules + this.signalManager.addRule({ + name: `MA Crossover (${this.indicatorConfig.fastMA}/${this.indicatorConfig.slowMA})`, + condition: indicators => { + const fast = indicators[`sma${this.indicatorConfig.fastMA}`]; + const slow = indicators[`sma${this.indicatorConfig.slowMA}`]; + const prevFast = indicators[`sma${this.indicatorConfig.fastMA}_prev`]; + const prevSlow = indicators[`sma${this.indicatorConfig.slowMA}_prev`]; + + if (!fast || !slow || !prevFast || !prevSlow) { + return false; + } + + // Check for crossover + const crossover = prevFast <= prevSlow && fast > slow; + const crossunder = prevFast >= prevSlow && fast < slow; + + return crossover || crossunder; + }, + weight: 1, + direction: 'both', + }); + + // RSI rules + this.signalManager.addRules([CommonRules.rsiOversold(30), CommonRules.rsiOverbought(70)]); + + // MACD rules + this.signalManager.addRules([CommonRules.macdBullishCross(), CommonRules.macdBearishCross()]); + + // Bollinger Band rules + this.signalManager.addRules([ + CommonRules.priceAtLowerBand(), + CommonRules.priceAtUpperBand(), + CommonRules.bollingerSqueeze(), + ]); + + // Add filters + this.signalManager.addFilter(CommonFilters.minStrength(this.indicatorConfig.minSignalStrength)); + this.signalManager.addFilter( + CommonFilters.minConfidence(this.indicatorConfig.minSignalConfidence) + ); + this.signalManager.addFilter(CommonFilters.trendAlignment('sma200')); + } + + protected updateIndicators(data: MarketData): void { + if (data.type !== 'bar') { + return; + } + + const { symbol, timestamp, open, high, low, close, volume } = data.data; + + // First time setup for symbol + if (!this.indicatorManager.getHistoryLength(symbol)) { + this.setupSymbolIndicators(symbol); + } + + // Update price history + this.indicatorManager.updatePrice({ + symbol, + timestamp, + open, + high, + low, + close, + volume, + }); + + // Update position market values + this.updatePositionValues(symbol, close); + + // Check stop losses and take profits + this.checkExitConditions(symbol, close); + } + + private setupSymbolIndicators(symbol: string): void { + // Setup incremental indicators + this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { + type: 'sma', + period: this.indicatorConfig.fastMA, + }); + + this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { + type: 'sma', + period: this.indicatorConfig.slowMA, + }); + + this.indicatorManager.setupIncrementalIndicator(symbol, 'rsi', { + type: 'rsi', + period: this.indicatorConfig.rsiPeriod, + }); + + logger.info(`Initialized indicators for ${symbol}`); + } + + protected async generateSignal(data: MarketData): Promise { + if (data.type !== 'bar') { + return null; + } + + const { symbol, timestamp, close } = data.data; + const historyLength = this.indicatorManager.getHistoryLength(symbol); + + // Need enough data + if (historyLength < Math.max(this.indicatorConfig.slowMA, 26)) { + return null; + } + + // Prepare indicators for signal generation + const indicators = this.prepareIndicators(symbol, close); + if (!indicators) { + return null; + } + + // Check risk before generating signals + const currentPositions = this.getCurrentPositionMap(); + const riskCheck = this.riskManager.checkNewPosition( + symbol, + 100, // Dummy size for check + close, + currentPositions + ); + + if (!riskCheck.allowed && !this.positionManager.hasPosition(symbol)) { + if (this.indicatorConfig.debugMode) { + logger.warn(`Risk check failed for ${symbol}: ${riskCheck.reason}`); + } + return null; + } + + // Generate trading signal + const tradingSignal = this.signalManager.generateSignal(symbol, timestamp, indicators, { + position: this.positionManager.getPositionQuantity(symbol), + }); + + if (!tradingSignal) { + return null; + } + + // Log signal if in debug mode + if (this.indicatorConfig.debugMode) { + logger.info(`Signal generated for ${symbol}:`, { + direction: tradingSignal.direction, + strength: tradingSignal.strength.toFixed(2), + confidence: tradingSignal.confidence.toFixed(2), + rules: tradingSignal.rules, + }); + } + + // Convert to strategy signal + return this.convertToStrategySignal(tradingSignal, symbol, close); + } + + private prepareIndicators(symbol: string, currentPrice: number): Record | null { + const indicators: Record = { price: currentPrice }; + + // Get moving averages + const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastMA); + const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowMA); + const sma200 = this.indicatorManager.getSMA(symbol, 200); + + if (!fastMA || !slowMA) { + return null; + } + + // Current and previous values + indicators[`sma${this.indicatorConfig.fastMA}`] = defined( + this.indicatorManager.getLatest(fastMA) + ); + indicators[`sma${this.indicatorConfig.slowMA}`] = defined( + this.indicatorManager.getLatest(slowMA) + ); + + if (fastMA.length >= 2 && slowMA.length >= 2) { + indicators[`sma${this.indicatorConfig.fastMA}_prev`] = at(fastMA, fastMA.length - 2); + indicators[`sma${this.indicatorConfig.slowMA}_prev`] = at(slowMA, slowMA.length - 2); + } + + if (sma200) { + indicators.sma200 = defined(this.indicatorManager.getLatest(sma200)); + } + + // RSI + const rsi = this.indicatorManager.getRSI(symbol, this.indicatorConfig.rsiPeriod); + if (rsi) { + indicators.rsi = defined(this.indicatorManager.getLatest(rsi)); + } + + // MACD + const macd = this.indicatorManager.getMACD(symbol); + if (macd) { + indicators.macd = defined(this.indicatorManager.getLatest(macd.macd)); + indicators.macd_signal = defined(this.indicatorManager.getLatest(macd.signal)); + indicators.macd_histogram = defined(this.indicatorManager.getLatest(macd.histogram)); + + if (macd.macd.length >= 2) { + indicators.macd_prev = at(macd.macd, macd.macd.length - 2); + indicators.macd_signal_prev = at(macd.signal, macd.signal.length - 2); + } + } + + // Bollinger Bands + const bb = this.indicatorManager.getBollingerBands(symbol); + if (bb) { + indicators.bb_upper = defined(this.indicatorManager.getLatest(bb.upper)); + indicators.bb_middle = defined(this.indicatorManager.getLatest(bb.middle)); + indicators.bb_lower = defined(this.indicatorManager.getLatest(bb.lower)); + } + + // ATR for volatility + const atr = this.indicatorManager.getATR(symbol, this.indicatorConfig.atrPeriod); + if (atr) { + indicators.atr = defined(this.indicatorManager.getLatest(atr)); + } + + // Volume + const priceHistory = this.indicatorManager.getPriceHistory(symbol); + if (priceHistory) { + indicators.volume = at(priceHistory.volume, priceHistory.volume.length - 1); + const avgVolume = priceHistory.volume.slice(-20).reduce((a, b) => a + b, 0) / 20; + indicators.avg_volume = avgVolume; + } + + return indicators; + } + + private convertToStrategySignal( + tradingSignal: TradingSignal, + symbol: string, + currentPrice: number + ): Signal | null { + const currentPosition = this.positionManager.getPositionQuantity(symbol); + + // Determine action based on signal and current position + let type: 'buy' | 'sell' | 'close'; + let quantity: number; + + if (tradingSignal.direction === 'buy') { + if (currentPosition < 0) { + // Close short position + type = 'buy'; + quantity = Math.abs(currentPosition); + } else if (currentPosition === 0) { + // Open long position + type = 'buy'; + quantity = this.calculateIndicatorPositionSize(symbol, currentPrice, tradingSignal); + } else { + // Already long + return null; + } + } else if (tradingSignal.direction === 'sell') { + if (currentPosition > 0) { + // Close long position + type = 'sell'; + quantity = currentPosition; + } else { + return null; + } + } else { + return null; + } + + return { + type, + symbol, + strength: tradingSignal.strength, + reason: tradingSignal.rules.join(', '), + metadata: { + ...tradingSignal.indicators, + quantity, + confidence: tradingSignal.confidence, + rules: tradingSignal.rules, + }, + }; + } + + private calculateIndicatorPositionSize( + symbol: string, + price: number, + signal: TradingSignal + ): number { + const accountBalance = this.positionManager.getAccountBalance(); + + switch (this.indicatorConfig.positionSizing) { + case 'fixed': // Fixed percentage of account + { + const fixedValue = accountBalance * this.indicatorConfig.riskPerTrade * 5; + return Math.floor(fixedValue / price); + } + + case 'risk': // Risk-based sizing with ATR stop + { + const atr = signal.indicators.atr; + if (atr && this.indicatorConfig.useATRStops) { + const stopDistance = atr * this.indicatorConfig.atrMultiplier; + return this.positionManager.calculatePositionSize( + { + accountBalance, + riskPerTrade: this.indicatorConfig.riskPerTrade, + stopLossDistance: stopDistance, + }, + price + ); + } + break; + } + + case 'kelly': // Kelly criterion based on historical performance + { + const metrics = this.positionManager.getPerformanceMetrics(); + if (metrics.totalTrades >= 20) { + return this.positionManager.calculateKellySize( + metrics.winRate / 100, + metrics.avgWin, + metrics.avgLoss, + price + ); + } + break; + } + + case 'volatility': // Volatility-adjusted sizing + { + const atrVol = signal.indicators.atr; + if (atrVol) { + return this.positionManager.calculatePositionSize( + { + accountBalance, + riskPerTrade: this.indicatorConfig.riskPerTrade, + volatilityAdjustment: true, + atr: atrVol, + }, + price + ); + } + break; + } + } + + // Default sizing + return this.positionManager.calculatePositionSize( + { + accountBalance, + riskPerTrade: this.indicatorConfig.riskPerTrade, + }, + price + ); + } + + private updatePositionValues(symbol: string, currentPrice: number): void { + const prices = new Map([[symbol, currentPrice]]); + this.positionManager.updateMarketPrices(prices); + } + + private checkExitConditions(symbol: string, currentPrice: number): void { + const position = this.positionManager.getPosition(symbol); + if (!position) { + return; + } + + const stopLoss = this.stopLosses.get(symbol); + const takeProfit = this.takeProfits.get(symbol); + + // Check stop loss + if (stopLoss) { + if ( + (position.quantity > 0 && currentPrice <= stopLoss) || + (position.quantity < 0 && currentPrice >= stopLoss) + ) { + logger.info(`Stop loss triggered for ${symbol} at ${currentPrice}`); + this.emit('signal', { + type: 'close', + symbol, + strength: 1, + reason: 'Stop loss triggered', + metadata: { stopLoss, currentPrice }, + }); + } + } + + // Check take profit + if (takeProfit) { + if ( + (position.quantity > 0 && currentPrice >= takeProfit) || + (position.quantity < 0 && currentPrice <= takeProfit) + ) { + logger.info(`Take profit triggered for ${symbol} at ${currentPrice}`); + this.emit('signal', { + type: 'close', + symbol, + strength: 1, + reason: 'Take profit triggered', + metadata: { takeProfit, currentPrice }, + }); + } + } + } + + private getCurrentPositionMap(): Map { + const positionMap = new Map(); + + for (const position of this.positionManager.getOpenPositions()) { + positionMap.set(position.symbol, { + quantity: position.quantity, + value: Math.abs(position.quantity * (position.currentPrice || position.avgPrice)), + }); + } + + return positionMap; + } + + override async onOrderUpdate(update: StrategyOrderUpdate): Promise { + await super.onOrderUpdate(update); + + if (update.status === 'filled' && update.fills?.length > 0) { + for (const fill of update.fills) { + const trade = { + symbol: update.symbol, + side: update.side as 'buy' | 'sell', + quantity: fill.quantity, + price: fill.price, + commission: fill.commission || 0, + timestamp: new Date(fill.timestamp), + }; + + const position = this.positionManager.updatePosition(trade); + + // Update risk manager + if (typeof fill.pnl === 'number') { + this.riskManager.updateAfterTrade(fill.pnl ?? 0); + } + + // Set stop loss and take profit for new positions + if (this.indicatorConfig.useATRStops && position.quantity !== 0) { + const atr = this.indicatorManager.getATR(update.symbol); + if (atr) { + const currentATR = this.indicatorManager.getLatest(atr); + if (currentATR) { + const stopDistance = currentATR * this.indicatorConfig.atrMultiplier; + const profitDistance = currentATR * this.indicatorConfig.atrMultiplier * 2; + + if (position.quantity > 0) { + this.stopLosses.set(update.symbol, fill.price - stopDistance); + this.takeProfits.set(update.symbol, fill.price + profitDistance); + } else { + this.stopLosses.set(update.symbol, fill.price + stopDistance); + this.takeProfits.set(update.symbol, fill.price - profitDistance); + } + + logger.info( + `Set stop/take profit for ${update.symbol}: Stop=${this.stopLosses.get(update.symbol)?.toFixed(2)}, TP=${this.takeProfits.get(update.symbol)?.toFixed(2)}` + ); + } + } + } + + // Clear stops if position closed + if (position.quantity === 0) { + this.stopLosses.delete(update.symbol); + this.takeProfits.delete(update.symbol); + } + } + } + } + + override getPerformance() { + const basePerf = super.getPerformance(); + const positionMetrics = this.positionManager.getPerformanceMetrics(); + const riskMetrics = this.riskManager.getMetrics(this.getCurrentPositionMap()); + const signalStats = this.signalManager.getSignalStats(); + + return { + ...basePerf, + ...positionMetrics, + risk: riskMetrics, + signals: signalStats, + }; + } + + // Daily reset for risk metrics + onDayEnd(): void { + this.riskManager.resetDaily(); + logger.info('Daily risk metrics reset'); + } +} diff --git a/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts index 52dd7cbc..94adaea6 100644 --- a/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts @@ -1,193 +1,85 @@ -import { BaseStrategy } from '../BaseStrategy'; -import { Order } from '../../types'; -import { TechnicalAnalysis, IncrementalIndicators, SignalGenerator, TradingSignal } from '../../indicators/TechnicalAnalysis'; - -interface IndicatorBasedConfig { - symbol: string; - initialCapital: number; - positionSize: number; - useRSI?: boolean; - useMACD?: boolean; - useBollingerBands?: boolean; - useStochastic?: boolean; - minSignalStrength?: number; -} - -/** - * Example strategy using multiple technical indicators from the Rust TA library - */ -export class IndicatorBasedStrategy extends BaseStrategy { - private ta: TechnicalAnalysis; - private incrementalIndicators: IncrementalIndicators; - private signalGenerator: SignalGenerator; - private priceHistory: { - close: number[]; - high: number[]; - low: number[]; - volume: number[]; - }; - private readonly lookbackPeriod = 100; // Keep last 100 bars - private lastSignal: TradingSignal | null = null; - private config: IndicatorBasedConfig; - - constructor(strategyId: string, config: IndicatorBasedConfig) { - super(strategyId, config.symbol, config.initialCapital); - this.config = { - useRSI: true, - useMACD: true, - useBollingerBands: true, - useStochastic: true, - minSignalStrength: 0.6, - ...config - }; - - this.ta = new TechnicalAnalysis(); - this.incrementalIndicators = new IncrementalIndicators(); - this.signalGenerator = new SignalGenerator(); - - this.priceHistory = { - close: [], - high: [], - low: [], - volume: [] - }; - - // Initialize incremental indicators for real-time updates - this.incrementalIndicators.createSMA('sma20', 20); - this.incrementalIndicators.createSMA('sma50', 50); - this.incrementalIndicators.createEMA('ema12', 12); - this.incrementalIndicators.createEMA('ema26', 26); - this.incrementalIndicators.createRSI('rsi14', 14); - } - - onMarketData(data: any): Order | null { - const { timestamp } = data; - - // Update price history - if ('close' in data && 'high' in data && 'low' in data) { - this.priceHistory.close.push(data.close); - this.priceHistory.high.push(data.high); - this.priceHistory.low.push(data.low); - this.priceHistory.volume.push(data.volume || 0); - - // Trim to lookback period - if (this.priceHistory.close.length > this.lookbackPeriod) { - this.priceHistory.close.shift(); - this.priceHistory.high.shift(); - this.priceHistory.low.shift(); - this.priceHistory.volume.shift(); - } - - // Update incremental indicators - this.incrementalIndicators.update('sma20', data.close); - this.incrementalIndicators.update('sma50', data.close); - this.incrementalIndicators.update('ema12', data.close); - this.incrementalIndicators.update('ema26', data.close); - this.incrementalIndicators.update('rsi14', data.close); - } - - // Need enough data for indicators - if (this.priceHistory.close.length < 26) { - return null; - } - - // Generate trading signals - const signal = this.signalGenerator.generateSignals( - this.symbol, - this.priceHistory, - timestamp - ); - - this.lastSignal = signal; - - // Log signal for debugging - if (signal.action !== 'HOLD') { - console.log(`[${new Date(timestamp).toISOString()}] Signal: ${signal.action} (strength: ${signal.strength.toFixed(2)}) - ${signal.reason}`); - } - - // Check if signal is strong enough - if (signal.strength < this.config.minSignalStrength) { - return null; - } - - // Generate orders based on signals and position - const currentPosition = this.positions[this.symbol] || 0; - - if (signal.action === 'BUY' && currentPosition <= 0) { - // Close short position if any - if (currentPosition < 0) { - return this.createOrder('market', 'buy', Math.abs(currentPosition)); - } - // Open long position - return this.createOrder('market', 'buy', this.config.positionSize); - } else if (signal.action === 'SELL' && currentPosition >= 0) { - // Close long position if any - if (currentPosition > 0) { - return this.createOrder('market', 'sell', Math.abs(currentPosition)); - } - // Open short position (if allowed) - // return this.createOrder('market', 'sell', this.config.positionSize); - } - - return null; - } - - getState() { - const incrementalValues: Record = { - sma20: this.incrementalIndicators.current('sma20'), - sma50: this.incrementalIndicators.current('sma50'), - ema12: this.incrementalIndicators.current('ema12'), - ema26: this.incrementalIndicators.current('ema26'), - rsi14: this.incrementalIndicators.current('rsi14') - }; - - return { - ...super.getState(), - priceHistoryLength: this.priceHistory.close.length, - incrementalIndicators: incrementalValues, - lastSignal: this.lastSignal, - config: this.config - }; - } - - /** - * Example of using batch indicator calculation - */ - analyzeHistoricalData(): void { - if (this.priceHistory.close.length < 50) { - console.log('Not enough data for historical analysis'); - return; - } - - const closes = this.priceHistory.close; - - // Calculate various indicators - const sma20 = this.ta.sma(closes, 20); - const sma50 = this.ta.sma(closes, 50); - const rsi = this.ta.rsi(closes, 14); - const macd = this.ta.macd(closes); - const bb = this.ta.bollingerBands(closes, 20, 2); - const atr = this.ta.atr( - this.priceHistory.high, - this.priceHistory.low, - this.priceHistory.close, - 14 - ); - - // Latest values - const currentPrice = closes[closes.length - 1]; - const currentSMA20 = TechnicalAnalysis.latest(sma20); - const currentSMA50 = TechnicalAnalysis.latest(sma50); - const currentRSI = TechnicalAnalysis.latest(rsi); - const currentATR = TechnicalAnalysis.latest(atr); - - console.log('Historical Analysis:'); - console.log(`Current Price: ${currentPrice}`); - console.log(`SMA20: ${currentSMA20?.toFixed(2)}`); - console.log(`SMA50: ${currentSMA50?.toFixed(2)}`); - console.log(`RSI: ${currentRSI?.toFixed(2)}`); - console.log(`ATR: ${currentATR?.toFixed(2)}`); - console.log(`MACD: ${TechnicalAnalysis.latest(macd.macd)?.toFixed(2)}`); - console.log(`BB %B: ${((currentPrice - TechnicalAnalysis.latest(bb.lower)!) / (TechnicalAnalysis.latest(bb.upper)! - TechnicalAnalysis.latest(bb.lower)!)).toFixed(2)}`); - } -} \ No newline at end of file +import type { ModeManager } from '../../core/ModeManager'; +import { + IncrementalIndicators, + SignalGenerator, + type TradingSignal, +} from '../../indicators/TechnicalAnalysis'; +import type { ExecutionService } from '../../services/ExecutionService'; +import type { MarketData, StrategyConfig } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; + +/** Example of the common strategy lifecycle with native incremental indicators. */ +export class IndicatorBasedStrategy extends BaseStrategy { + private readonly incrementalIndicators = new IncrementalIndicators(); + private readonly signalGenerator = new SignalGenerator(); + private readonly priceHistory = { + close: [] as number[], + high: [] as number[], + low: [] as number[], + volume: [] as number[], + }; + private lastSignal: TradingSignal | null = null; + + constructor( + config: StrategyConfig, + modeManager: ModeManager, + executionService: ExecutionService + ) { + super(config, modeManager, executionService); + this.incrementalIndicators.createSMA('sma20', 20); + this.incrementalIndicators.createSMA('sma50', 50); + this.incrementalIndicators.createEMA('ema12', 12); + this.incrementalIndicators.createEMA('ema26', 26); + this.incrementalIndicators.createRSI('rsi14', 14); + } + + protected override updateIndicators(data: MarketData): void { + if (data.type !== 'bar') { + return; + } + const bar = data.data; + this.priceHistory.close.push(bar.close); + this.priceHistory.high.push(bar.high); + this.priceHistory.low.push(bar.low); + this.priceHistory.volume.push(bar.volume); + for (const values of Object.values(this.priceHistory)) { + if (values.length > 100) { + values.shift(); + } + } + for (const key of ['sma20', 'sma50', 'ema12', 'ema26', 'rsi14']) { + this.incrementalIndicators.update(key, bar.close); + } + } + + protected override async generateSignal(data: MarketData): Promise { + if (data.type !== 'bar' || this.priceHistory.close.length < 50) { + return null; + } + const signal = this.signalGenerator.generateSignals( + data.data.symbol, + this.priceHistory, + data.data.timestamp + ); + this.lastSignal = signal; + const minimum = Number(this.config.parameters.minSignalStrength ?? 0.6); + if (signal.action === 'HOLD' || signal.strength < minimum) { + return null; + } + return { + type: signal.action === 'BUY' ? 'buy' : 'sell', + symbol: signal.symbol, + strength: signal.strength, + reason: signal.reason, + metadata: { quantity: Number(this.config.parameters.positionSize ?? 100) }, + }; + } + + getState() { + return { + priceHistoryLength: this.priceHistory.close.length, + lastSignal: this.lastSignal, + config: this.config, + }; + } +} diff --git a/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts index 286b6490..660e2234 100644 --- a/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts @@ -1,416 +1,472 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('MLEnhancedStrategy'); -import * as tf from '@tensorflow/tfjs-node'; - -interface MLModelConfig { - modelPath?: string; - features: string[]; - lookbackPeriod: number; - updateFrequency: number; // How often to retrain in minutes - minTrainingSize: number; -} - -export class MLEnhancedStrategy extends BaseStrategy { - 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 = 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 async onStart(): Promise { - logger.info('ML Enhanced Strategy starting...'); - - // Try to load existing model - if (this.mlConfig.modelPath) { - try { - this.model = await 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 - indicators.prices[indicators.prices.length - 2]) / - 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 = 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.calculatePositionSize(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 { - const indicators = this.indicators.get(symbol); - if (!indicators || indicators.prices.length < 50) return null; - - const features: number[] = []; - - // Price returns - const currentPrice = indicators.prices[indicators.prices.length - 1]; - features.push((currentPrice / indicators.prices[indicators.prices.length - 20] - 1)); // 20-day return - features.push((currentPrice / 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, b) => 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 = 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 = tf.tensor3d([featureBuffer]); - - // Make prediction - const prediction = await this.model.predict(input) as tf.Tensor; - const value = (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 = tf.tensor2d(this.trainingData.features); - const labels = 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 = tf.sequential({ - layers: [ - // LSTM layer for sequence processing - tf.layers.lstm({ - units: 64, - returnSequences: true, - inputShape: [this.mlConfig.lookbackPeriod, this.mlConfig.features.length] - }), - tf.layers.dropout({ rate: 0.2 }), - - // Second LSTM layer - tf.layers.lstm({ - units: 32, - returnSequences: false - }), - tf.layers.dropout({ rate: 0.2 }), - - // Dense layers - tf.layers.dense({ - units: 16, - activation: 'relu' - }), - tf.layers.dropout({ rate: 0.1 }), - - // Output layer - tf.layers.dense({ - units: 1, - activation: 'tanh' // Output between -1 and 1 - }) - ] - }); - - model.compile({ - optimizer: 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 = buffer[buffer.length - 1]; - return { - returns_20: latest[0], - returns_50: latest[1], - volatility_20: latest[2], - rsi_normalized: latest[3], - volume_ratio: latest[4], - price_position: latest[5], - macd_signal: latest[6] - }; - } - - 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 calculatePositionSize(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 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 onConfigUpdate(updates: any): void { - logger.info('ML Enhanced Strategy config updated:', updates); - - if (updates.mlConfig) { - this.mlConfig = { ...this.mlConfig, ...updates.mlConfig }; - } - } -} \ No newline at end of file +import type * as tf from '@tensorflow/tfjs-node'; +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; +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; +} + +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/examples/MeanReversionStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts index 1901b3d0..5915ffde 100644 --- a/apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts @@ -1,194 +1,207 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('MeanReversionStrategy'); - -interface MeanReversionIndicators { - sma20: number; - sma50: number; - stdDev: number; - zScore: number; - rsi: number; -} - -export class MeanReversionStrategy extends BaseStrategy { - private priceHistory = new Map(); - private indicators = new Map(); - - // Strategy parameters - private readonly LOOKBACK_PERIOD = 20; - private readonly Z_SCORE_ENTRY = 2.0; - private readonly Z_SCORE_EXIT = 0.5; - private readonly RSI_OVERSOLD = 30; - private readonly RSI_OVERBOUGHT = 70; - private readonly MIN_VOLUME = 1000000; // $1M daily volume - - 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 = this.priceHistory.get(symbol)!; - history.push(price); - - // Keep only needed history - if (history.length > this.LOOKBACK_PERIOD * 3) { - history.shift(); - } - - // Calculate indicators if we have enough data - if (history.length >= this.LOOKBACK_PERIOD) { - const indicators = this.calculateIndicators(history); - this.indicators.set(symbol, indicators); - } - } - - private calculateIndicators(prices: number[]): MeanReversionIndicators { - const len = prices.length; - - // Calculate SMAs - const sma20 = this.calculateSMA(prices, 20); - const sma50 = len >= 50 ? this.calculateSMA(prices, 50) : sma20; - - // Calculate standard deviation - const stdDev = this.calculateStdDev(prices.slice(-20), sma20); - - // Calculate Z-score - const currentPrice = prices[len - 1]; - const zScore = stdDev > 0 ? (currentPrice - sma20) / stdDev : 0; - - // Calculate RSI - const rsi = this.calculateRSI(prices, 14); - - return { sma20, sma50, 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.MIN_VOLUME) { - return null; - } - - const position = this.getPosition(symbol); - const { zScore, rsi, sma20, sma50 } = indicators; - - // Entry signals - if (position === 0) { - // Long entry: Oversold conditions - if (zScore < -this.Z_SCORE_ENTRY && rsi < this.RSI_OVERSOLD && sma20 > sma50) { - 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.Z_SCORE_ENTRY && rsi > this.RSI_OVERBOUGHT && sma20 < sma50) { - 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.Z_SCORE_EXIT || zScore > this.Z_SCORE_ENTRY) { - 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.Z_SCORE_EXIT || zScore < -this.Z_SCORE_ENTRY) { - return { - type: 'close', - symbol, - strength: 1, - reason: `Exit short: Z-score ${zScore.toFixed(2)}`, - metadata: { indicators } - }; - } - } - - return null; - } - - private calculateSMA(prices: number[], period: number): number { - const relevantPrices = prices.slice(-period); - return relevantPrices.reduce((sum, p) => sum + p, 0) / relevantPrices.length; - } - - private calculateStdDev(prices: number[], mean: number): number { - const squaredDiffs = prices.map(p => Math.pow(p - mean, 2)); - const variance = squaredDiffs.reduce((sum, d) => sum + d, 0) / prices.length; - return Math.sqrt(variance); - } - - private calculateRSI(prices: number[], period: number = 14): number { - if (prices.length < period + 1) return 50; - - let gains = 0; - let losses = 0; - - // Calculate initial average gain/loss - for (let i = 1; i <= period; i++) { - const change = prices[prices.length - i] - prices[prices.length - i - 1]; - if (change > 0) { - gains += change; - } else { - losses += Math.abs(change); - } - } - - const avgGain = gains / period; - const avgLoss = losses / period; - - if (avgLoss === 0) return 100; - - const rs = avgGain / avgLoss; - const rsi = 100 - (100 / (1 + rs)); - - return rsi; - } - - protected onStart(): void { - logger.info(`Mean Reversion Strategy started with symbols: ${this.config.symbols.join(', ')}`); - } - - protected onStop(): void { - logger.info('Mean Reversion Strategy stopped'); - // Clear indicators - this.priceHistory.clear(); - this.indicators.clear(); - } - - protected onConfigUpdate(updates: any): void { - logger.info('Mean Reversion Strategy config updated:', updates); - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; +import type { StrategyConfig } from '../../types'; +import { type MarketData } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; + +const logger = getLogger('MeanReversionStrategy'); + +interface MeanReversionIndicators { + sma20: number; + sma50: number; + stdDev: number; + zScore: number; + rsi: number; +} + +export class MeanReversionStrategy extends BaseStrategy { + private priceHistory = new Map(); + private indicators = new Map(); + + // Strategy parameters + private readonly LOOKBACK_PERIOD = 20; + private readonly Z_SCORE_ENTRY = 2.0; + private readonly Z_SCORE_EXIT = 0.5; + private readonly RSI_OVERSOLD = 30; + private readonly RSI_OVERBOUGHT = 70; + private readonly MIN_VOLUME = 1000000; // $1M daily volume + + 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.LOOKBACK_PERIOD * 3) { + history.shift(); + } + + // Calculate indicators if we have enough data + if (history.length >= this.LOOKBACK_PERIOD) { + const indicators = this.calculateIndicators(history); + this.indicators.set(symbol, indicators); + } + } + + private calculateIndicators(prices: number[]): MeanReversionIndicators { + const len = prices.length; + + // Calculate SMAs + const sma20 = this.calculateSMA(prices, 20); + const sma50 = len >= 50 ? this.calculateSMA(prices, 50) : sma20; + + // Calculate standard deviation + const stdDev = this.calculateStdDev(prices.slice(-20), sma20); + + // Calculate Z-score + const currentPrice = at(prices, len - 1); + const zScore = stdDev > 0 ? (currentPrice - sma20) / stdDev : 0; + + // Calculate RSI + const rsi = this.calculateRSI(prices, 14); + + return { sma20, sma50, 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.MIN_VOLUME) { + return null; + } + + const position = this.getPosition(symbol); + const { zScore, rsi, sma20, sma50 } = indicators; + + // Entry signals + if (position === 0) { + // Long entry: Oversold conditions + if (zScore < -this.Z_SCORE_ENTRY && rsi < this.RSI_OVERSOLD && sma20 > sma50) { + 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.Z_SCORE_ENTRY && rsi > this.RSI_OVERBOUGHT && sma20 < sma50) { + 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.Z_SCORE_EXIT || zScore > this.Z_SCORE_ENTRY) { + 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.Z_SCORE_EXIT || zScore < -this.Z_SCORE_ENTRY) { + return { + type: 'close', + symbol, + strength: 1, + reason: `Exit short: Z-score ${zScore.toFixed(2)}`, + metadata: { indicators }, + }; + } + } + + return null; + } + + private calculateSMA(prices: number[], period: number): number { + const relevantPrices = prices.slice(-period); + return relevantPrices.reduce((sum, p) => sum + p, 0) / relevantPrices.length; + } + + private calculateStdDev(prices: number[], mean: number): number { + const squaredDiffs = prices.map(p => Math.pow(p - mean, 2)); + const variance = squaredDiffs.reduce((sum, d) => sum + d, 0) / prices.length; + return Math.sqrt(variance); + } + + private calculateRSI(prices: number[], period: number = 14): number { + if (prices.length < period + 1) { + return 50; + } + + let gains = 0; + let losses = 0; + + // Calculate initial average gain/loss + for (let i = 1; i <= period; i++) { + const change = at(prices, prices.length - i) - at(prices, prices.length - i - 1); + if (change > 0) { + gains += change; + } else { + losses += Math.abs(change); + } + } + + const avgGain = gains / period; + const avgLoss = losses / period; + + if (avgLoss === 0) { + return 100; + } + + const rs = avgGain / avgLoss; + const rsi = 100 - 100 / (1 + rs); + + return rsi; + } + + 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/examples/SimpleMovingAverageCrossover.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts index cbe155c7..7fa6e77f 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts +++ b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts @@ -1,341 +1,366 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('SimpleMovingAverageCrossover'); - -export class SimpleMovingAverageCrossover extends BaseStrategy { - private priceHistory = new Map(); - private lastTradeTime = new Map(); - private barCount = new Map(); - private totalSignals = 0; - - // Strategy parameters - private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals - private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals - private readonly POSITION_SIZE = 0.1; // 10% of capital per position - private readonly MIN_HOLDING_BARS = 1; // Minimum bars to hold position - private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging - - constructor(config: any, modeManager?: any, executionService?: any) { - super(config, modeManager, executionService); - logger.info(`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`); - } - - 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, []); - this.barCount.set(symbol, 0); - logger.info(`📊 Starting to track ${symbol} @ ${price}`); - } - - const history = 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.SLOW_PERIOD * 2) { - history.shift(); - } - - // Log when we have enough data to start trading - if (history.length === this.SLOW_PERIOD) { - 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.SLOW_PERIOD) { - if (history && history.length % 5 === 0) { - logger.debug(`${symbol} - Not enough history: ${history.length}/${this.SLOW_PERIOD} bars`); - } - return null; - } - - // Calculate moving averages - const fastMA = this.calculateSMA(history, this.FAST_PERIOD); - const slowMA = this.calculateSMA(history, this.SLOW_PERIOD); - - // Get previous MAs for crossover detection - const prevHistory = history.slice(0, -1); - const prevFastMA = this.calculateSMA(prevHistory, this.FAST_PERIOD); - const prevSlowMA = this.calculateSMA(prevHistory, this.SLOW_PERIOD); - - const currentPosition = this.getPosition(symbol); - const currentPrice = data.data.close; - const timestamp = new Date(data.data.timestamp).toISOString().split('T')[0]; - - // Check minimum holding period - const currentBar = this.barCount.get(symbol) || 0; - const lastTradeBar = this.lastTradeTime.get(symbol) || 0; - const barsSinceLastTrade = lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; - - // Detect crossovers FIRST - const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA; - const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA; - - // Enhanced debugging - log more frequently and when MAs are close - const maDiff = fastMA - slowMA; - const maDiffPct = (maDiff / slowMA) * 100; - const masAreClose = Math.abs(maDiffPct) < 1.0; // Within 1% - - if (history.length % this.DEBUG_INTERVAL === 0 || masAreClose || goldenCross || deathCross) { - logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`); - logger.info(` Price: $${currentPrice.toFixed(2)}`); - logger.info(` Fast MA (${this.FAST_PERIOD}): $${fastMA.toFixed(2)}`); - logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.toFixed(2)}`); - logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); - logger.info(` Position: ${currentPosition} shares`); - logger.info(` Bars since last trade: ${barsSinceLastTrade}`); - - if (goldenCross) { - logger.info(` 🟢 GOLDEN CROSS DETECTED!`); - } - if (deathCross) { - logger.info(` 🔴 DEATH CROSS DETECTED!`); - } - } - - // Note: We removed the MIN_HOLDING_BARS check here to allow closing and opening on same bar - // The check is now done individually for new position entries - - if (goldenCross) { - logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - // For golden cross, we want to be long - if (currentPosition < 0) { - // Close short position first - 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) // Buy to close short - } - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else if (currentPosition === 0) { - // No position, open long - logger.info(` No current position, opening long`); - logger.info(` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} > Slow MA: ${slowMA.toFixed(2)}`); - logger.info(` Prev Fast MA: ${prevFastMA.toFixed(2)} <= Prev Slow MA: ${prevSlowMA.toFixed(2)}`); - - // Calculate position size - const positionSize = this.calculatePositionSize(currentPrice); - logger.info(` Opening long position: ${positionSize} shares`); - - const signal: Signal = { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Fast MA crossed above Slow MA', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'golden', - price: currentPrice, - quantity: positionSize - } - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else { - logger.info(` ⚠️ Already long, skipping buy signal`); - } - } else if (deathCross) { - logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - // For death cross, we want to be flat or short - if (currentPosition > 0) { - // Close long position - logger.info(` Closing long position of ${currentPosition} shares`); - logger.info(` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} < Slow MA: ${slowMA.toFixed(2)}`); - logger.info(` Prev Fast MA: ${prevFastMA.toFixed(2)} >= Prev Slow MA: ${prevSlowMA.toFixed(2)}`); - - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Fast MA crossed below Slow MA', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'death', - price: currentPrice, - quantity: currentPosition - } - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else if (currentPosition === 0) { - // Open short position for long/short strategy - logger.info(` No current position, opening short`); - - const positionSize = this.calculatePositionSize(currentPrice); - logger.info(` Opening short position: ${positionSize} shares`); - - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Opening short position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'death', - price: currentPrice, - quantity: positionSize - } - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else { - logger.info(` ⚠️ Already short, skipping sell signal`); - } - } - - // Log near-crossover conditions - const fastApproachingSlow = Math.abs(fastMA - slowMA) / slowMA < 0.01; // Within 1% - if (fastApproachingSlow && history.length % 20 === 0) { - logger.debug(`${symbol} - MAs converging: Fast MA ${fastMA.toFixed(2)} ~ Slow MA ${slowMA.toFixed(2)} (${((Math.abs(fastMA - slowMA) / slowMA) * 100).toFixed(2)}% diff)`); - } - - return null; - } - - private calculateSMA(prices: number[], period: number): number { - if (prices.length < period) { - logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`); - return 0; - } - - const slice = prices.slice(-period); - const sum = slice.reduce((a, b) => a + b, 0); - const sma = sum / period; - - // Sanity check - if (isNaN(sma) || !isFinite(sma)) { - logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`); - return 0; - } - - return sma; - } - - private calculatePositionSize(price: number): number { - // Get account balance from trading engine - const tradingEngine = this.modeManager?.getTradingEngine(); - if (!tradingEngine) { - logger.warn('No trading engine available, using default position size'); - return 100; - } - - // Try to get account balance from trading engine - let accountBalance = 100000; // Default - try { - if (tradingEngine.getAccountBalance) { - accountBalance = tradingEngine.getAccountBalance(); - } else if (tradingEngine.getTotalPnl) { - const [realized, unrealized] = tradingEngine.getTotalPnl(); - accountBalance = 100000 + realized + unrealized; // Assuming 100k initial - } - } catch (error) { - logger.warn('Could not get account balance:', error); - } - - const positionValue = accountBalance * this.POSITION_SIZE; - const shares = Math.floor(positionValue / price); - - logger.debug(`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`); - - return Math.max(1, shares); // At least 1 share - } - - protected onOrderFilled(fill: any): void { - const { symbol, side, quantity, price } = fill; - - logger.info(`✅ ${side.toUpperCase()} filled: ${symbol} - ${quantity} shares @ ${price}`); - - // Position tracking is handled by BaseStrategy.onOrderUpdate - // Just log the current position - const currentPosition = this.getPosition(symbol); - logger.info(`Position for ${symbol}: ${currentPosition} shares`); - } - - // Override to provide custom order generation - protected async signalToOrder(signal: Signal): Promise { - logger.info(`🔄 Converting signal to order:`, signal); - - const currentPosition = this.getPosition(signal.symbol); - - // Get position sizing from metadata - const quantity = signal.metadata?.quantity || 100; - - if (signal.type === 'buy') { - const order: OrderRequest = { - symbol: signal.symbol, - side: 'buy', - quantity, - orderType: 'market', - timeInForce: 'DAY' - }; - logger.info(`📈 Generated BUY order:`, order); - return order; - } else if (signal.type === 'sell') { - const order: OrderRequest = { - symbol: signal.symbol, - side: 'sell', - quantity, - orderType: 'market', - timeInForce: 'DAY' - }; - logger.info(`📉 Generated SELL order:`, order); - return order; - } - - return null; - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import type { ModeManager } from '../../core/ModeManager'; +import type { ExecutionService, StrategyFill } from '../../services/ExecutionService'; +import type { OrderRequest, StrategyConfig } from '../../types'; +import { type MarketData } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; + +const logger = getLogger('SimpleMovingAverageCrossover'); + +export class SimpleMovingAverageCrossover extends BaseStrategy { + private priceHistory = new Map(); + private lastTradeTime = new Map(); + private barCount = new Map(); + private totalSignals = 0; + + // Strategy parameters + private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals + private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals + private readonly POSITION_SIZE = 0.1; // 10% of capital per position + private readonly MIN_HOLDING_BARS = 1; // Minimum bars to hold position + private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging + + constructor( + config: StrategyConfig, + modeManager: ModeManager, + executionService: ExecutionService + ) { + super(config, modeManager, executionService); + logger.info( + `SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}` + ); + } + + 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, []); + this.barCount.set(symbol, 0); + logger.info(`📊 Starting to track ${symbol} @ ${price}`); + } + + 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.SLOW_PERIOD * 2) { + history.shift(); + } + + // Log when we have enough data to start trading + if (history.length === this.SLOW_PERIOD) { + 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.SLOW_PERIOD) { + if (history && history.length % 5 === 0) { + logger.debug(`${symbol} - Not enough history: ${history.length}/${this.SLOW_PERIOD} bars`); + } + return null; + } + + // Calculate moving averages + const fastMA = this.calculateSMA(history, this.FAST_PERIOD); + const slowMA = this.calculateSMA(history, this.SLOW_PERIOD); + + // Get previous MAs for crossover detection + const prevHistory = history.slice(0, -1); + const prevFastMA = this.calculateSMA(prevHistory, this.FAST_PERIOD); + const prevSlowMA = this.calculateSMA(prevHistory, this.SLOW_PERIOD); + + const currentPosition = this.getPosition(symbol); + const currentPrice = data.data.close; + const timestamp = new Date(data.data.timestamp).toISOString().split('T')[0]; + + // Check minimum holding period + const currentBar = this.barCount.get(symbol) || 0; + const lastTradeBar = this.lastTradeTime.get(symbol) || 0; + const barsSinceLastTrade = + lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; + + // Detect crossovers FIRST + const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA; + const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA; + + // Enhanced debugging - log more frequently and when MAs are close + const maDiff = fastMA - slowMA; + const maDiffPct = (maDiff / slowMA) * 100; + const masAreClose = Math.abs(maDiffPct) < 1.0; // Within 1% + + if (history.length % this.DEBUG_INTERVAL === 0 || masAreClose || goldenCross || deathCross) { + logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`); + logger.info(` Price: $${currentPrice.toFixed(2)}`); + logger.info(` Fast MA (${this.FAST_PERIOD}): $${fastMA.toFixed(2)}`); + logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.toFixed(2)}`); + logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); + logger.info(` Position: ${currentPosition} shares`); + logger.info(` Bars since last trade: ${barsSinceLastTrade}`); + + if (goldenCross) { + logger.info(` 🟢 GOLDEN CROSS DETECTED!`); + } + if (deathCross) { + logger.info(` 🔴 DEATH CROSS DETECTED!`); + } + } + + // Note: We removed the MIN_HOLDING_BARS check here to allow closing and opening on same bar + // The check is now done individually for new position entries + + if (goldenCross) { + logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`); + logger.info(` Current position: ${currentPosition} shares`); + + // For golden cross, we want to be long + if (currentPosition < 0) { + // Close short position first + 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), // Buy to close short + }, + }; + + this.lastTradeTime.set(symbol, currentBar); + this.totalSignals++; + logger.info(`👉 Total signals generated: ${this.totalSignals}`); + return signal; + } else if (currentPosition === 0) { + // No position, open long + logger.info(` No current position, opening long`); + logger.info( + ` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} > Slow MA: ${slowMA.toFixed(2)}` + ); + logger.info( + ` Prev Fast MA: ${prevFastMA.toFixed(2)} <= Prev Slow MA: ${prevSlowMA.toFixed(2)}` + ); + + // Calculate position size + const positionSize = this.calculateCrossoverPositionSize(currentPrice); + logger.info(` Opening long position: ${positionSize} shares`); + + const signal: Signal = { + type: 'buy', + symbol, + strength: 0.8, + reason: 'Golden cross - Fast MA crossed above Slow MA', + metadata: { + fastMA, + slowMA, + prevFastMA, + prevSlowMA, + crossoverType: 'golden', + price: currentPrice, + quantity: positionSize, + }, + }; + + this.lastTradeTime.set(symbol, currentBar); + this.totalSignals++; + logger.info(`👉 Total signals generated: ${this.totalSignals}`); + return signal; + } else { + logger.info(` ⚠️ Already long, skipping buy signal`); + } + } else if (deathCross) { + logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`); + logger.info(` Current position: ${currentPosition} shares`); + + // For death cross, we want to be flat or short + if (currentPosition > 0) { + // Close long position + logger.info(` Closing long position of ${currentPosition} shares`); + logger.info( + ` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} < Slow MA: ${slowMA.toFixed(2)}` + ); + logger.info( + ` Prev Fast MA: ${prevFastMA.toFixed(2)} >= Prev Slow MA: ${prevSlowMA.toFixed(2)}` + ); + + const signal: Signal = { + type: 'sell', + symbol, + strength: 0.8, + reason: 'Death cross - Fast MA crossed below Slow MA', + metadata: { + fastMA, + slowMA, + prevFastMA, + prevSlowMA, + crossoverType: 'death', + price: currentPrice, + quantity: currentPosition, + }, + }; + + this.lastTradeTime.set(symbol, currentBar); + this.totalSignals++; + logger.info(`👉 Total signals generated: ${this.totalSignals}`); + return signal; + } else if (currentPosition === 0) { + // Open short position for long/short strategy + logger.info(` No current position, opening short`); + + const positionSize = this.calculateCrossoverPositionSize(currentPrice); + logger.info(` Opening short position: ${positionSize} shares`); + + const signal: Signal = { + type: 'sell', + symbol, + strength: 0.8, + reason: 'Death cross - Opening short position', + metadata: { + fastMA, + slowMA, + prevFastMA, + prevSlowMA, + crossoverType: 'death', + price: currentPrice, + quantity: positionSize, + }, + }; + + this.lastTradeTime.set(symbol, currentBar); + this.totalSignals++; + logger.info(`👉 Total signals generated: ${this.totalSignals}`); + return signal; + } else { + logger.info(` ⚠️ Already short, skipping sell signal`); + } + } + + // Log near-crossover conditions + const fastApproachingSlow = Math.abs(fastMA - slowMA) / slowMA < 0.01; // Within 1% + if (fastApproachingSlow && history.length % 20 === 0) { + logger.debug( + `${symbol} - MAs converging: Fast MA ${fastMA.toFixed(2)} ~ Slow MA ${slowMA.toFixed(2)} (${((Math.abs(fastMA - slowMA) / slowMA) * 100).toFixed(2)}% diff)` + ); + } + + return null; + } + + private calculateSMA(prices: number[], period: number): number { + if (prices.length < period) { + logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`); + return 0; + } + + const slice = prices.slice(-period); + const sum = slice.reduce((a, b) => a + b, 0); + const sma = sum / period; + + // Sanity check + if (isNaN(sma) || !isFinite(sma)) { + logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`); + return 0; + } + + return sma; + } + + private calculateCrossoverPositionSize(price: number): number { + // Get account balance from trading engine + const tradingEngine = this.modeManager?.getTradingEngine(); + if (!tradingEngine) { + logger.warn('No trading engine available, using default position size'); + return 100; + } + + // Try to get account balance from trading engine + let accountBalance = 100000; // Default + try { + { + const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); + accountBalance = 100000 + realized + unrealized; // Assuming 100k initial + } + } catch (error) { + logger.warn('Could not get account balance', { error }); + } + + const positionValue = accountBalance * this.POSITION_SIZE; + const shares = Math.floor(positionValue / price); + + logger.debug( + `Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, 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}`); + + // Position tracking is handled by BaseStrategy.onOrderUpdate + // Just log the current position + const currentPosition = this.getPosition(symbol); + logger.info(`Position for ${symbol}: ${currentPosition} shares`); + } + + // Override to provide custom order generation + protected override async signalToOrder(signal: Signal): Promise { + logger.info(`🔄 Converting signal to order:`, signal); + + const _currentPosition = this.getPosition(signal.symbol); + + // Get position sizing from metadata + const quantity = typeof signal.metadata?.quantity === 'number' ? signal.metadata.quantity : 100; + + if (signal.type === 'buy') { + const order: OrderRequest = { + symbol: signal.symbol, + side: 'buy', + quantity, + orderType: 'market', + timeInForce: 'DAY', + }; + logger.info(`📈 Generated BUY order:`, order); + return order; + } else if (signal.type === 'sell') { + const order: OrderRequest = { + symbol: signal.symbol, + side: 'sell', + quantity, + orderType: 'market', + timeInForce: 'DAY', + }; + logger.info(`📉 Generated SELL order:`, order); + return order; + } + + return null; + } +} diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts index f68cd1ec..07f1f931 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts +++ b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts @@ -1,306 +1,320 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('SimpleMovingAverageCrossover'); - -export class SimpleMovingAverageCrossover extends BaseStrategy { - private priceHistory = new Map(); - private lastSignalBar = new Map(); - private barCount = new Map(); - private totalSignals = 0; - private lastCrossoverType = new Map(); - - // Strategy parameters - private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals - private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals - private readonly POSITION_SIZE = 0.1; // 10% of capital per position - private readonly MIN_HOLDING_BARS = 3; // Minimum bars to hold position - private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging - - constructor(config: any, modeManager?: any, executionService?: any) { - super(config, modeManager, executionService); - logger.info(`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`); - } - - 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 = 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.SLOW_PERIOD * 2) { - history.shift(); - } - - // Log when we have enough data to start trading - if (history.length === this.SLOW_PERIOD) { - 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.SLOW_PERIOD) { - return null; - } - - const currentPrice = data.data.close; - const timestamp = data.data.timestamp; - const currentBar = this.barCount.get(symbol) || 0; - - // Calculate moving averages - const fastMA = this.calculateSMA(history, this.FAST_PERIOD); - const slowMA = this.calculateSMA(history, this.SLOW_PERIOD); - - // Get previous MAs for crossover detection - const historyWithoutLast = history.slice(0, -1); - const prevFastMA = this.calculateSMA(historyWithoutLast, this.FAST_PERIOD); - const prevSlowMA = this.calculateSMA(historyWithoutLast, this.SLOW_PERIOD); - - // Detect crossovers - const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA; - const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA; - - // 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.FAST_PERIOD}): $${fastMA.toFixed(2)}`); - logger.info(` Slow MA (${this.SLOW_PERIOD}): $${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.MIN_HOLDING_BARS) { - // 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 = this.calculatePositionSize(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 = this.calculatePositionSize(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; - } - - private calculateSMA(prices: number[], period: number): number { - if (prices.length < period) { - logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`); - return 0; - } - - const slice = prices.slice(-period); - const sum = slice.reduce((a, b) => a + b, 0); - const sma = sum / period; - - // Sanity check - if (isNaN(sma) || !isFinite(sma)) { - logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`); - return 0; - } - - return sma; - } - - private calculatePositionSize(price: number): number { - // Get account balance from trading engine - const tradingEngine = this.modeManager?.getTradingEngine(); - if (!tradingEngine) { - logger.warn('No trading engine available, using default position size'); - return 100; - } - - // Try to get account balance from trading engine - // Use initial capital from config parameters if available - let accountBalance = this.config.parameters?.initialCapital || 100000; - try { - if (tradingEngine.getAccountBalance) { - accountBalance = tradingEngine.getAccountBalance(); - } else if (tradingEngine.getTotalPnl) { - const [realized, unrealized] = tradingEngine.getTotalPnl(); - accountBalance = (this.config.parameters?.initialCapital || 100000) + realized + unrealized; - } - } catch (error) { - logger.warn('Could not get account balance:', error); - } - - const positionValue = accountBalance * this.POSITION_SIZE; - const shares = Math.floor(positionValue / price); - - logger.debug(`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`); - - return Math.max(1, shares); // At least 1 share - } - - protected onOrderFilled(fill: any): 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`); - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import type { ModeManager } from '../../core/ModeManager'; +import type { ExecutionService, StrategyFill } from '../../services/ExecutionService'; +import type { StrategyConfig } from '../../types'; +import { type MarketData } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; + +const logger = getLogger('SimpleMovingAverageCrossover'); + +export class SimpleMovingAverageCrossover extends BaseStrategy { + private priceHistory = new Map(); + private lastSignalBar = new Map(); + private barCount = new Map(); + private totalSignals = 0; + private lastCrossoverType = new Map(); + + // Strategy parameters + private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals + private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals + private readonly POSITION_SIZE = 0.1; // 10% of capital per position + private readonly MIN_HOLDING_BARS = 3; // Minimum bars to hold position + private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging + + constructor( + config: StrategyConfig, + modeManager: ModeManager, + executionService: ExecutionService + ) { + super(config, modeManager, executionService); + logger.info( + `SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}` + ); + } + + 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.SLOW_PERIOD * 2) { + history.shift(); + } + + // Log when we have enough data to start trading + if (history.length === this.SLOW_PERIOD) { + 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.SLOW_PERIOD) { + return null; + } + + const currentPrice = data.data.close; + const timestamp = data.data.timestamp; + const currentBar = this.barCount.get(symbol) || 0; + + // Calculate moving averages + const fastMA = this.calculateSMA(history, this.FAST_PERIOD); + const slowMA = this.calculateSMA(history, this.SLOW_PERIOD); + + // Get previous MAs for crossover detection + const historyWithoutLast = history.slice(0, -1); + const prevFastMA = this.calculateSMA(historyWithoutLast, this.FAST_PERIOD); + const prevSlowMA = this.calculateSMA(historyWithoutLast, this.SLOW_PERIOD); + + // Detect crossovers + const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA; + const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA; + + // 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.FAST_PERIOD}): $${fastMA.toFixed(2)}`); + logger.info(` Slow MA (${this.SLOW_PERIOD}): $${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.MIN_HOLDING_BARS) { + // 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 = 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 = 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; + } + + private calculateSMA(prices: number[], period: number): number { + if (prices.length < period) { + logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`); + return 0; + } + + const slice = prices.slice(-period); + const sum = slice.reduce((a, b) => a + b, 0); + const sma = sum / period; + + // Sanity check + if (isNaN(sma) || !isFinite(sma)) { + logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`); + return 0; + } + + return sma; + } + + private calculateCrossoverPositionSize(price: number): number { + // Get account balance from trading engine + const tradingEngine = this.modeManager?.getTradingEngine(); + if (!tradingEngine) { + logger.warn('No trading engine available, using default position size'); + return 100; + } + + // Try to get account balance from trading engine + // Use initial capital from config parameters if available + let accountBalance = Number(this.config.parameters?.initialCapital ?? 100000); + try { + { + const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); + accountBalance = + Number(this.config.parameters?.initialCapital ?? 100000) + realized + unrealized; + } + } catch (error) { + logger.warn('Could not get account balance', { error }); + } + + const positionValue = accountBalance * this.POSITION_SIZE; + const shares = Math.floor(positionValue / price); + + logger.debug( + `Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, 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/examples/SimpleMovingAverageCrossoverV2.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts index e869f5fb..669d82bc 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts +++ b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts @@ -1,308 +1,333 @@ -import { BaseStrategy, Signal } from '../BaseStrategy'; -import { MarketData } from '../../types'; -import { IndicatorManager } from '../indicators/IndicatorManager'; -import { PositionManager, PositionSizingParams } from '../position/PositionManager'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('SimpleMovingAverageCrossoverV2'); - -export interface SMAStrategyConfig { - fastPeriod?: number; - slowPeriod?: number; - positionSizePct?: number; - riskPerTrade?: number; - useATRStops?: boolean; - minHoldingBars?: number; - debugInterval?: number; -} - -/** - * Refactored SMA Crossover Strategy using new TA library - */ -export class SimpleMovingAverageCrossoverV2 extends BaseStrategy { - private indicatorManager: IndicatorManager; - private positionManager: PositionManager; - - // Strategy parameters - private readonly config: Required; - private lastTradeBar = new Map(); - private barCount = new Map(); - private totalSignals = 0; - - constructor(strategyConfig: any, modeManager?: any, executionService?: any) { - super(strategyConfig, modeManager, executionService); - - // Initialize config with defaults - this.config = { - fastPeriod: 10, - slowPeriod: 20, - positionSizePct: 0.1, - riskPerTrade: 0.02, - useATRStops: true, - minHoldingBars: 1, - debugInterval: 20, - ...strategyConfig.params - }; - - this.indicatorManager = new IndicatorManager(); - this.positionManager = new PositionManager(strategyConfig.initialCapital || 100000); - - logger.info(`SimpleMovingAverageCrossoverV2 initialized:`, this.config); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') return; - - const { symbol, timestamp } = data.data; - const { open, high, low, close, volume } = data.data; - - // Update bar count - const currentBar = (this.barCount.get(symbol) || 0) + 1; - this.barCount.set(symbol, currentBar); - - // First time seeing this symbol - if (!this.indicatorManager.getHistoryLength(symbol)) { - logger.info(`📊 Starting to track ${symbol} @ ${close}`); - - // Setup incremental indicators for real-time updates - this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { - type: 'sma', - period: this.config.fastPeriod - }); - this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { - type: 'sma', - period: this.config.slowPeriod - }); - - if (this.config.useATRStops) { - this.indicatorManager.setupIncrementalIndicator(symbol, 'atr', { - type: 'sma', // Using SMA as proxy for now - period: 14 - }); - } - } - - // Update price history - this.indicatorManager.updatePrice({ - symbol, - timestamp, - open, - high, - low, - close, - volume - }); - - // Update position market prices - const currentPrices = new Map([[symbol, close]]); - this.positionManager.updateMarketPrices(currentPrices); - - // Log when we have enough data - const historyLength = this.indicatorManager.getHistoryLength(symbol); - if (historyLength === this.config.slowPeriod) { - logger.info(`✅ ${symbol} has enough history (${historyLength} bars) to start trading`); - } - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') return null; - - const { symbol, timestamp } = data.data; - const { close } = data.data; - const historyLength = this.indicatorManager.getHistoryLength(symbol); - - // Need enough data for slow MA - if (historyLength < this.config.slowPeriod) { - if (historyLength % 5 === 0) { - logger.debug(`${symbol} - Building history: ${historyLength}/${this.config.slowPeriod} bars`); - } - return null; - } - - // Calculate indicators - const fastMA = this.indicatorManager.getSMA(symbol, this.config.fastPeriod); - const slowMA = this.indicatorManager.getSMA(symbol, this.config.slowPeriod); - - if (!fastMA || !slowMA) return null; - - // Get current and previous values - const currentFast = this.indicatorManager.getLatest(fastMA); - const currentSlow = this.indicatorManager.getLatest(slowMA); - - if (currentFast === null || currentSlow === null) return null; - - // Check for crossovers - const goldenCross = this.indicatorManager.checkCrossover(fastMA, slowMA); - const deathCross = this.indicatorManager.checkCrossunder(fastMA, slowMA); - - // Get current position - const currentPosition = this.positionManager.getPositionQuantity(symbol); - const currentBar = this.barCount.get(symbol) || 0; - const lastTradeBar = this.lastTradeBar.get(symbol) || 0; - const barsSinceLastTrade = lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; - - // Enhanced debugging - const maDiff = currentFast - currentSlow; - const maDiffPct = (maDiff / currentSlow) * 100; - const shouldLog = historyLength % this.config.debugInterval === 0 || - Math.abs(maDiffPct) < 1.0 || - goldenCross || - deathCross; - - if (shouldLog) { - const dateStr = new Date(timestamp).toISOString().split('T')[0]; - logger.info(`${symbol} @ ${dateStr} [Bar ${currentBar}]:`); - logger.info(` Price: $${close.toFixed(2)}`); - logger.info(` Fast MA (${this.config.fastPeriod}): $${currentFast.toFixed(2)}`); - logger.info(` Slow MA (${this.config.slowPeriod}): $${currentSlow.toFixed(2)}`); - logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); - logger.info(` Position: ${currentPosition} shares`); - - // Show additional indicators if available - const rsi = this.indicatorManager.getRSI(symbol); - if (rsi) { - const currentRSI = this.indicatorManager.getLatest(rsi); - logger.info(` RSI: ${currentRSI?.toFixed(2)}`); - } - - if (goldenCross) logger.info(` 🟢 GOLDEN CROSS DETECTED!`); - if (deathCross) logger.info(` 🔴 DEATH CROSS DETECTED!`); - } - - // Check minimum holding period - if (barsSinceLastTrade < this.config.minHoldingBars && lastTradeBar > 0) { - return null; - } - - // Position sizing parameters - const sizingParams: PositionSizingParams = { - accountBalance: this.positionManager.getAccountBalance(), - riskPerTrade: this.config.riskPerTrade, - volatilityAdjustment: this.config.useATRStops - }; - - if (this.config.useATRStops) { - const atr = this.indicatorManager.getATR(symbol); - if (atr) { - sizingParams.atr = this.indicatorManager.getLatest(atr) || undefined; - } - } - - // Generate signals - if (goldenCross) { - logger.info(`🟢 Golden cross detected for ${symbol}`); - - if (currentPosition < 0) { - // Close short position - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - return { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Closing short position', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'golden', - price: close, - quantity: Math.abs(currentPosition) - } - }; - } else if (currentPosition === 0) { - // Calculate position size - const positionSize = this.positionManager.calculatePositionSize(sizingParams, close); - - logger.info(` Opening long position: ${positionSize} shares`); - logger.info(` Account balance: $${sizingParams.accountBalance.toFixed(2)}`); - - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - - return { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Fast MA crossed above Slow MA', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'golden', - price: close, - quantity: positionSize - } - }; - } - } else if (deathCross && currentPosition > 0) { - logger.info(`🔴 Death cross detected for ${symbol}`); - - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - - return { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Fast MA crossed below Slow MA', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'death', - price: close, - quantity: currentPosition - } - }; - } - - return null; - } - - protected async onOrderUpdate(update: any): Promise { - await super.onOrderUpdate(update); - - // Update position manager with fills - if (update.status === 'filled' && update.fills?.length > 0) { - for (const fill of update.fills) { - this.positionManager.updatePosition({ - symbol: update.symbol, - side: update.side, - quantity: fill.quantity, - price: fill.price, - commission: fill.commission || 0, - timestamp: new Date(fill.timestamp) - }); - } - - // Log performance metrics periodically - if (this.totalSignals % 5 === 0) { - const metrics = this.positionManager.getPerformanceMetrics(); - logger.info('📊 Strategy Performance:', { - trades: metrics.totalTrades, - winRate: `${metrics.winRate.toFixed(2)}%`, - totalPnL: `$${metrics.totalPnl.toFixed(2)}`, - returnPct: `${metrics.returnPct.toFixed(2)}%` - }); - } - } - } - - getPerformance(): any { - const metrics = this.positionManager.getPerformanceMetrics(); - return { - ...super.getPerformance(), - ...metrics, - totalSignals: this.totalSignals, - openPositions: this.positionManager.getOpenPositions() - }; - } - - // Optional: Get current state for debugging - getState() { - return { - config: this.config, - totalSignals: this.totalSignals, - performance: this.getPerformance(), - positions: Array.from(this.positions.entries()) - }; - } -} \ No newline at end of file +import { getLogger } from '@stock-bot/logger'; +import type { ModeManager } from '../../core/ModeManager'; +import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService'; +import type { StrategyConfig } from '../../types'; +import { type MarketData } from '../../types'; +import { BaseStrategy, type Signal } from '../BaseStrategy'; +import { IndicatorManager } from '../indicators/IndicatorManager'; +import { PositionManager, type PositionSizingParams } from '../position/PositionManager'; + +const logger = getLogger('SimpleMovingAverageCrossoverV2'); + +export interface SMAStrategyConfig { + fastPeriod?: number; + slowPeriod?: number; + positionSizePct?: number; + riskPerTrade?: number; + useATRStops?: boolean; + minHoldingBars?: number; + debugInterval?: number; +} + +/** + * Refactored SMA Crossover Strategy using new TA library + */ +export class SimpleMovingAverageCrossoverV2 extends BaseStrategy { + private indicatorManager: IndicatorManager; + private positionManager: PositionManager; + + // Strategy parameters + private readonly indicatorConfig: Required; + private lastTradeBar = new Map(); + private barCount = new Map(); + private totalSignals = 0; + + constructor( + strategyConfig: StrategyConfig, + modeManager: ModeManager, + executionService: ExecutionService + ) { + super(strategyConfig, modeManager, executionService); + + // Initialize config with defaults + this.indicatorConfig = { + fastPeriod: 10, + slowPeriod: 20, + positionSizePct: 0.1, + riskPerTrade: 0.02, + useATRStops: true, + minHoldingBars: 1, + debugInterval: 20, + ...strategyConfig.parameters, + }; + + this.indicatorManager = new IndicatorManager(); + this.positionManager = new PositionManager( + Number(strategyConfig.parameters.initialCapital ?? 100000) + ); + + logger.info(`SimpleMovingAverageCrossoverV2 initialized:`, this.indicatorConfig); + } + + protected updateIndicators(data: MarketData): void { + if (data.type !== 'bar') { + return; + } + + const { symbol, timestamp } = data.data; + const { open, high, low, close, volume } = data.data; + + // Update bar count + const currentBar = (this.barCount.get(symbol) || 0) + 1; + this.barCount.set(symbol, currentBar); + + // First time seeing this symbol + if (!this.indicatorManager.getHistoryLength(symbol)) { + logger.info(`📊 Starting to track ${symbol} @ ${close}`); + + // Setup incremental indicators for real-time updates + this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { + type: 'sma', + period: this.indicatorConfig.fastPeriod, + }); + this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { + type: 'sma', + period: this.indicatorConfig.slowPeriod, + }); + + if (this.indicatorConfig.useATRStops) { + this.indicatorManager.setupIncrementalIndicator(symbol, 'atr', { + type: 'sma', // Using SMA as proxy for now + period: 14, + }); + } + } + + // Update price history + this.indicatorManager.updatePrice({ + symbol, + timestamp, + open, + high, + low, + close, + volume, + }); + + // Update position market prices + const currentPrices = new Map([[symbol, close]]); + this.positionManager.updateMarketPrices(currentPrices); + + // Log when we have enough data + const historyLength = this.indicatorManager.getHistoryLength(symbol); + if (historyLength === this.indicatorConfig.slowPeriod) { + logger.info(`✅ ${symbol} has enough history (${historyLength} bars) to start trading`); + } + } + + protected async generateSignal(data: MarketData): Promise { + if (data.type !== 'bar') { + return null; + } + + const { symbol, timestamp } = data.data; + const { close } = data.data; + const historyLength = this.indicatorManager.getHistoryLength(symbol); + + // Need enough data for slow MA + if (historyLength < this.indicatorConfig.slowPeriod) { + if (historyLength % 5 === 0) { + logger.debug( + `${symbol} - Building history: ${historyLength}/${this.indicatorConfig.slowPeriod} bars` + ); + } + return null; + } + + // Calculate indicators + const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastPeriod); + const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowPeriod); + + if (!fastMA || !slowMA) { + return null; + } + + // Get current and previous values + const currentFast = this.indicatorManager.getLatest(fastMA); + const currentSlow = this.indicatorManager.getLatest(slowMA); + + if (currentFast === null || currentSlow === null) { + return null; + } + + // Check for crossovers + const goldenCross = this.indicatorManager.checkCrossover(fastMA, slowMA); + const deathCross = this.indicatorManager.checkCrossunder(fastMA, slowMA); + + // Get current position + const currentPosition = this.positionManager.getPositionQuantity(symbol); + const currentBar = this.barCount.get(symbol) || 0; + const lastTradeBar = this.lastTradeBar.get(symbol) || 0; + const barsSinceLastTrade = + lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; + + // Enhanced debugging + const maDiff = currentFast - currentSlow; + const maDiffPct = (maDiff / currentSlow) * 100; + const shouldLog = + historyLength % this.indicatorConfig.debugInterval === 0 || + Math.abs(maDiffPct) < 1.0 || + goldenCross || + deathCross; + + if (shouldLog) { + const dateStr = new Date(timestamp).toISOString().split('T')[0]; + logger.info(`${symbol} @ ${dateStr} [Bar ${currentBar}]:`); + logger.info(` Price: $${close.toFixed(2)}`); + logger.info(` Fast MA (${this.indicatorConfig.fastPeriod}): $${currentFast.toFixed(2)}`); + logger.info(` Slow MA (${this.indicatorConfig.slowPeriod}): $${currentSlow.toFixed(2)}`); + logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); + logger.info(` Position: ${currentPosition} shares`); + + // Show additional indicators if available + const rsi = this.indicatorManager.getRSI(symbol); + if (rsi) { + const currentRSI = this.indicatorManager.getLatest(rsi); + logger.info(` RSI: ${currentRSI?.toFixed(2)}`); + } + + if (goldenCross) { + logger.info(` 🟢 GOLDEN CROSS DETECTED!`); + } + if (deathCross) { + logger.info(` 🔴 DEATH CROSS DETECTED!`); + } + } + + // Check minimum holding period + if (barsSinceLastTrade < this.indicatorConfig.minHoldingBars && lastTradeBar > 0) { + return null; + } + + // Position sizing parameters + const sizingParams: PositionSizingParams = { + accountBalance: this.positionManager.getAccountBalance(), + riskPerTrade: this.indicatorConfig.riskPerTrade, + volatilityAdjustment: this.indicatorConfig.useATRStops, + }; + + if (this.indicatorConfig.useATRStops) { + const atr = this.indicatorManager.getATR(symbol); + if (atr) { + sizingParams.atr = this.indicatorManager.getLatest(atr) || undefined; + } + } + + // Generate signals + if (goldenCross) { + logger.info(`🟢 Golden cross detected for ${symbol}`); + + if (currentPosition < 0) { + // Close short position + this.lastTradeBar.set(symbol, currentBar); + this.totalSignals++; + return { + type: 'buy', + symbol, + strength: 0.8, + reason: 'Golden cross - Closing short position', + metadata: { + fastMA: currentFast, + slowMA: currentSlow, + crossoverType: 'golden', + price: close, + quantity: Math.abs(currentPosition), + }, + }; + } else if (currentPosition === 0) { + // Calculate position size + const positionSize = this.positionManager.calculatePositionSize(sizingParams, close); + + logger.info(` Opening long position: ${positionSize} shares`); + logger.info(` Account balance: $${sizingParams.accountBalance.toFixed(2)}`); + + this.lastTradeBar.set(symbol, currentBar); + this.totalSignals++; + + return { + type: 'buy', + symbol, + strength: 0.8, + reason: 'Golden cross - Fast MA crossed above Slow MA', + metadata: { + fastMA: currentFast, + slowMA: currentSlow, + crossoverType: 'golden', + price: close, + quantity: positionSize, + }, + }; + } + } else if (deathCross && currentPosition > 0) { + logger.info(`🔴 Death cross detected for ${symbol}`); + + this.lastTradeBar.set(symbol, currentBar); + this.totalSignals++; + + return { + type: 'sell', + symbol, + strength: 0.8, + reason: 'Death cross - Fast MA crossed below Slow MA', + metadata: { + fastMA: currentFast, + slowMA: currentSlow, + crossoverType: 'death', + price: close, + quantity: currentPosition, + }, + }; + } + + return null; + } + + override async onOrderUpdate(update: StrategyOrderUpdate): Promise { + await super.onOrderUpdate(update); + + // Update position manager with fills + if (update.status === 'filled' && update.fills?.length > 0) { + for (const fill of update.fills) { + this.positionManager.updatePosition({ + symbol: update.symbol, + side: update.side, + quantity: fill.quantity, + price: fill.price, + commission: fill.commission || 0, + timestamp: new Date(fill.timestamp), + }); + } + + // Log performance metrics periodically + if (this.totalSignals % 5 === 0) { + const metrics = this.positionManager.getPerformanceMetrics(); + logger.info('📊 Strategy Performance:', { + trades: metrics.totalTrades, + winRate: `${metrics.winRate.toFixed(2)}%`, + totalPnL: `$${metrics.totalPnl.toFixed(2)}`, + returnPct: `${metrics.returnPct.toFixed(2)}%`, + }); + } + } + } + + override getPerformance() { + const metrics = this.positionManager.getPerformanceMetrics(); + return { + ...super.getPerformance(), + ...metrics, + totalSignals: this.totalSignals, + openPositions: this.positionManager.getOpenPositions(), + }; + } + + // Optional: Get current state for debugging + getState() { + return { + config: this.indicatorConfig, + totalSignals: this.totalSignals, + performance: this.getPerformance(), + positions: Array.from(this.positions.entries()), + }; + } +} diff --git a/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts b/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts index fcad9c6a..ae392a60 100644 --- a/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts +++ b/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts @@ -1,315 +1,337 @@ -import { TechnicalAnalysis, IncrementalIndicators } from '../../indicators/TechnicalAnalysis'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('IndicatorManager'); - -export interface IndicatorConfig { - type: 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger' | 'stochastic' | 'atr'; - period?: number; - fastPeriod?: number; - slowPeriod?: number; - signalPeriod?: number; - stdDev?: number; - kPeriod?: number; - dPeriod?: number; - smoothK?: number; -} - -export interface PriceData { - symbol: string; - timestamp: number; - open: number; - high: number; - low: number; - close: number; - volume: number; -} - -/** - * Manages technical indicators for a strategy - * Handles both batch and incremental calculations - */ -export class IndicatorManager { - private ta: TechnicalAnalysis; - private incrementalIndicators: IncrementalIndicators; - private priceHistory: Map = new Map(); - - private indicatorCache: Map> = new Map(); - private maxHistoryLength: number; - - constructor(maxHistoryLength = 500) { - this.ta = new TechnicalAnalysis(); - this.incrementalIndicators = new IncrementalIndicators(); - this.maxHistoryLength = maxHistoryLength; - } - - /** - * Update price history with new data - */ - updatePrice(data: PriceData): void { - const { symbol, open, high, low, close, volume } = data; - - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, { - open: [], - high: [], - low: [], - close: [], - volume: [] - }); - } - - const history = this.priceHistory.get(symbol)!; - - // Add new data - history.open.push(open); - history.high.push(high); - history.low.push(low); - history.close.push(close); - history.volume.push(volume); - - // Trim to max length - if (history.close.length > this.maxHistoryLength) { - history.open.shift(); - history.high.shift(); - history.low.shift(); - history.close.shift(); - history.volume.shift(); - } - - // Clear cache for this symbol as data has changed - this.indicatorCache.delete(symbol); - - // Update incremental indicators - this.updateIncrementalIndicators(symbol, close); - } - - /** - * Get price history for a symbol - */ - getPriceHistory(symbol: string) { - return this.priceHistory.get(symbol); - } - - /** - * Get the number of price bars for a symbol - */ - getHistoryLength(symbol: string): number { - const history = this.priceHistory.get(symbol); - return history ? history.close.length : 0; - } - - /** - * Calculate SMA - */ - getSMA(symbol: string, period: number): number[] | null { - const cacheKey = `sma_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) return null; - return this.ta.sma(history.close, period); - }); - } - - /** - * Calculate EMA - */ - getEMA(symbol: string, period: number): number[] | null { - const cacheKey = `ema_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) return null; - return this.ta.ema(history.close, period); - }); - } - - /** - * Calculate RSI - */ - getRSI(symbol: string, period: number = 14): number[] | null { - const cacheKey = `rsi_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period + 1) return null; - return this.ta.rsi(history.close, period); - }); - } - - /** - * Calculate MACD - */ - getMACD(symbol: string, fastPeriod = 12, slowPeriod = 26, signalPeriod = 9) { - const cacheKey = `macd_${fastPeriod}_${slowPeriod}_${signalPeriod}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < slowPeriod + signalPeriod) return null; - return this.ta.macd(history.close, fastPeriod, slowPeriod, signalPeriod); - }); - } - - /** - * Calculate Bollinger Bands - */ - getBollingerBands(symbol: string, period = 20, stdDev = 2) { - const cacheKey = `bb_${period}_${stdDev}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) return null; - return this.ta.bollingerBands(history.close, period, stdDev); - }); - } - - /** - * Calculate Stochastic - */ - getStochastic(symbol: string, kPeriod = 14, dPeriod = 3, smoothK = 1) { - const cacheKey = `stoch_${kPeriod}_${dPeriod}_${smoothK}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < kPeriod) return null; - return this.ta.stochastic( - history.high, - history.low, - history.close, - kPeriod, - dPeriod, - smoothK - ); - }); - } - - /** - * Calculate ATR - */ - getATR(symbol: string, period = 14): number[] | null { - const cacheKey = `atr_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period + 1) return null; - return this.ta.atr(history.high, history.low, history.close, period); - }); - } - - /** - * Get latest value from an indicator - */ - getLatest(values: number[] | null): number | null { - if (!values || values.length === 0) return null; - return values[values.length - 1]; - } - - /** - * Check for crossover - */ - checkCrossover(series1: number[] | null, series2: number[] | null): boolean { - if (!series1 || !series2) return false; - return TechnicalAnalysis.crossover(series1, series2); - } - - /** - * Check for crossunder - */ - checkCrossunder(series1: number[] | null, series2: number[] | null): boolean { - if (!series1 || !series2) return false; - return TechnicalAnalysis.crossunder(series1, series2); - } - - /** - * Setup incremental indicators - */ - setupIncrementalIndicator(symbol: string, name: string, config: IndicatorConfig): void { - const key = `${symbol}_${name}`; - - switch (config.type) { - case 'sma': - this.incrementalIndicators.createSMA(key, config.period!); - break; - case 'ema': - this.incrementalIndicators.createEMA(key, config.period!); - break; - case 'rsi': - this.incrementalIndicators.createRSI(key, config.period!); - break; - default: - logger.warn(`Incremental indicator type ${config.type} not supported`); - } - } - - /** - * Get incremental indicator value - */ - getIncrementalValue(symbol: string, name: string): number | null { - const key = `${symbol}_${name}`; - return this.incrementalIndicators.current(key); - } - - /** - * Clear all data for a symbol - */ - clearSymbol(symbol: string): void { - this.priceHistory.delete(symbol); - this.indicatorCache.delete(symbol); - - // Reset incremental indicators for this symbol - const indicators = this.incrementalIndicators as any; - for (const [key, indicator] of indicators.indicators) { - if (key.startsWith(`${symbol}_`)) { - if ('reset' in indicator) { - indicator.reset(); - } - } - } - } - - /** - * Clear all data - */ - clearAll(): void { - this.priceHistory.clear(); - this.indicatorCache.clear(); - this.incrementalIndicators.resetAll(); - } - - private getCachedOrCalculate( - symbol: string, - cacheKey: string, - calculator: () => T | null - ): T | null { - if (!this.indicatorCache.has(symbol)) { - this.indicatorCache.set(symbol, new Map()); - } - - const symbolCache = this.indicatorCache.get(symbol)!; - - if (symbolCache.has(cacheKey)) { - return symbolCache.get(cacheKey); - } - - const result = calculator(); - if (result !== null) { - symbolCache.set(cacheKey, result); - } - - return result; - } - - private updateIncrementalIndicators(symbol: string, price: number): void { - // Update all incremental indicators for this symbol - const indicators = this.incrementalIndicators as any; - for (const [key] of indicators.indicators) { - if (key.startsWith(`${symbol}_`)) { - try { - this.incrementalIndicators.update(key, price); - } catch (error) { - logger.error(`Error updating incremental indicator ${key}:`, error); - } - } - } - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { IncrementalIndicators, TechnicalAnalysis } from '../../indicators/TechnicalAnalysis'; + +const logger = getLogger('IndicatorManager'); + +export interface IndicatorConfig { + type: 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger' | 'stochastic' | 'atr'; + period?: number; + fastPeriod?: number; + slowPeriod?: number; + signalPeriod?: number; + stdDev?: number; + kPeriod?: number; + dPeriod?: number; + smoothK?: number; +} + +export interface PriceData { + symbol: string; + timestamp: number; + open: number; + high: number; + low: number; + close: number; + volume: number; +} + +/** + * Manages technical indicators for a strategy + * Handles both batch and incremental calculations + */ +export class IndicatorManager { + private ta: TechnicalAnalysis; + private incrementalIndicators: IncrementalIndicators; + private priceHistory: Map< + string, + { + open: number[]; + high: number[]; + low: number[]; + close: number[]; + volume: number[]; + } + > = new Map(); + + private indicatorCache: Map> = new Map(); + private maxHistoryLength: number; + + constructor(maxHistoryLength = 500) { + this.ta = new TechnicalAnalysis(); + this.incrementalIndicators = new IncrementalIndicators(); + this.maxHistoryLength = maxHistoryLength; + } + + /** + * Update price history with new data + */ + updatePrice(data: PriceData): void { + const { symbol, open, high, low, close, volume } = data; + + if (!this.priceHistory.has(symbol)) { + this.priceHistory.set(symbol, { + open: [], + high: [], + low: [], + close: [], + volume: [], + }); + } + + const history = defined(this.priceHistory.get(symbol)); + + // Add new data + history.open.push(open); + history.high.push(high); + history.low.push(low); + history.close.push(close); + history.volume.push(volume); + + // Trim to max length + if (history.close.length > this.maxHistoryLength) { + history.open.shift(); + history.high.shift(); + history.low.shift(); + history.close.shift(); + history.volume.shift(); + } + + // Clear cache for this symbol as data has changed + this.indicatorCache.delete(symbol); + + // Update incremental indicators + this.updateIncrementalIndicators(symbol, close); + } + + /** + * Get price history for a symbol + */ + getPriceHistory(symbol: string) { + return this.priceHistory.get(symbol); + } + + /** + * Get the number of price bars for a symbol + */ + getHistoryLength(symbol: string): number { + const history = this.priceHistory.get(symbol); + return history ? history.close.length : 0; + } + + /** + * Calculate SMA + */ + getSMA(symbol: string, period: number): number[] | null { + const cacheKey = `sma_${period}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < period) { + return null; + } + return this.ta.sma(history.close, period); + }); + } + + /** + * Calculate EMA + */ + getEMA(symbol: string, period: number): number[] | null { + const cacheKey = `ema_${period}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < period) { + return null; + } + return this.ta.ema(history.close, period); + }); + } + + /** + * Calculate RSI + */ + getRSI(symbol: string, period: number = 14): number[] | null { + const cacheKey = `rsi_${period}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < period + 1) { + return null; + } + return this.ta.rsi(history.close, period); + }); + } + + /** + * Calculate MACD + */ + getMACD(symbol: string, fastPeriod = 12, slowPeriod = 26, signalPeriod = 9) { + const cacheKey = `macd_${fastPeriod}_${slowPeriod}_${signalPeriod}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < slowPeriod + signalPeriod) { + return null; + } + return this.ta.macd(history.close, fastPeriod, slowPeriod, signalPeriod); + }); + } + + /** + * Calculate Bollinger Bands + */ + getBollingerBands(symbol: string, period = 20, stdDev = 2) { + const cacheKey = `bb_${period}_${stdDev}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < period) { + return null; + } + return this.ta.bollingerBands(history.close, period, stdDev); + }); + } + + /** + * Calculate Stochastic + */ + getStochastic(symbol: string, kPeriod = 14, dPeriod = 3, smoothK = 1) { + const cacheKey = `stoch_${kPeriod}_${dPeriod}_${smoothK}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < kPeriod) { + return null; + } + return this.ta.stochastic( + history.high, + history.low, + history.close, + kPeriod, + dPeriod, + smoothK + ); + }); + } + + /** + * Calculate ATR + */ + getATR(symbol: string, period = 14): number[] | null { + const cacheKey = `atr_${period}`; + return this.getCachedOrCalculate(symbol, cacheKey, () => { + const history = this.priceHistory.get(symbol); + if (!history || history.close.length < period + 1) { + return null; + } + return this.ta.atr(history.high, history.low, history.close, period); + }); + } + + /** + * Get latest value from an indicator + */ + getLatest(values: number[] | null): number | null { + if (!values || values.length === 0) { + return null; + } + return values[values.length - 1] ?? null; + } + + /** + * Check for crossover + */ + checkCrossover(series1: number[] | null, series2: number[] | null): boolean { + if (!series1 || !series2) { + return false; + } + return TechnicalAnalysis.crossover(series1, series2); + } + + /** + * Check for crossunder + */ + checkCrossunder(series1: number[] | null, series2: number[] | null): boolean { + if (!series1 || !series2) { + return false; + } + return TechnicalAnalysis.crossunder(series1, series2); + } + + /** + * Setup incremental indicators + */ + setupIncrementalIndicator(symbol: string, name: string, config: IndicatorConfig): void { + const key = `${symbol}_${name}`; + + switch (config.type) { + case 'sma': + this.incrementalIndicators.createSMA(key, defined(config.period)); + break; + case 'ema': + this.incrementalIndicators.createEMA(key, defined(config.period)); + break; + case 'rsi': + this.incrementalIndicators.createRSI(key, defined(config.period)); + break; + default: + logger.warn(`Incremental indicator type ${config.type} not supported`); + } + } + + /** + * Get incremental indicator value + */ + getIncrementalValue(symbol: string, name: string): number | null { + const key = `${symbol}_${name}`; + return this.incrementalIndicators.current(key); + } + + /** + * Clear all data for a symbol + */ + clearSymbol(symbol: string): void { + this.priceHistory.delete(symbol); + this.indicatorCache.delete(symbol); + + // Reset incremental indicators for this symbol + for (const [key, indicator] of this.incrementalIndicators.entries()) { + if (key.startsWith(`${symbol}_`)) { + if ('reset' in indicator) { + indicator.reset(); + } + } + } + } + + /** + * Clear all data + */ + clearAll(): void { + this.priceHistory.clear(); + this.indicatorCache.clear(); + this.incrementalIndicators.resetAll(); + } + + private getCachedOrCalculate( + symbol: string, + cacheKey: string, + calculator: () => T | null + ): T | null { + if (!this.indicatorCache.has(symbol)) { + this.indicatorCache.set(symbol, new Map()); + } + + const symbolCache = defined(this.indicatorCache.get(symbol)); + + if (symbolCache.has(cacheKey)) { + return symbolCache.get(cacheKey) as T; + } + + const result = calculator(); + if (result !== null) { + symbolCache.set(cacheKey, result); + } + + return result; + } + + private updateIncrementalIndicators(symbol: string, price: number): void { + // Update all incremental indicators for this symbol + for (const [key] of this.incrementalIndicators.entries()) { + if (key.startsWith(`${symbol}_`)) { + try { + this.incrementalIndicators.update(key, price); + } catch (error) { + logger.error(`Error updating incremental indicator ${key}:`, error); + } + } + } + } +} diff --git a/apps/stock/orchestrator/src/strategies/position/PositionManager.ts b/apps/stock/orchestrator/src/strategies/position/PositionManager.ts index 90214d6a..4999ad03 100644 --- a/apps/stock/orchestrator/src/strategies/position/PositionManager.ts +++ b/apps/stock/orchestrator/src/strategies/position/PositionManager.ts @@ -1,290 +1,304 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('PositionManager'); - -export interface Position { - symbol: string; - quantity: number; - avgPrice: number; - currentPrice?: number; - unrealizedPnl?: number; - realizedPnl: number; - openTime: Date; - lastUpdateTime: Date; -} - -export interface Trade { - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - timestamp: Date; - pnl?: number; -} - -export interface PositionSizingParams { - accountBalance: number; - riskPerTrade: number; // As percentage (e.g., 0.02 for 2%) - stopLossDistance?: number; // Price distance for stop loss - maxPositionSize?: number; // Max % of account in one position - volatilityAdjustment?: boolean; - atr?: number; // For volatility-based sizing -} - -/** - * Manages positions and calculates position sizes - */ -export class PositionManager { - private positions: Map = new Map(); - private trades: Trade[] = []; - private accountBalance: number; - private initialBalance: number; - - constructor(initialBalance: number = 100000) { - this.initialBalance = initialBalance; - this.accountBalance = initialBalance; - } - - /** - * Update position with a new trade - */ - updatePosition(trade: Trade): Position { - const { symbol, side, quantity, price, commission } = trade; - let position = this.positions.get(symbol); - - if (!position) { - // New position - position = { - symbol, - quantity: side === 'buy' ? quantity : -quantity, - avgPrice: price, - realizedPnl: -commission, - openTime: trade.timestamp, - lastUpdateTime: trade.timestamp - }; - } else { - const oldQuantity = position.quantity; - const newQuantity = side === 'buy' - ? oldQuantity + quantity - : oldQuantity - quantity; - - if (Math.sign(oldQuantity) !== Math.sign(newQuantity) && oldQuantity !== 0) { - // Position flip or close - const closedQuantity = Math.min(Math.abs(oldQuantity), quantity); - const pnl = this.calculatePnl( - position.avgPrice, - price, - closedQuantity, - oldQuantity > 0 ? 'sell' : 'buy' - ); - - position.realizedPnl += pnl - commission; - trade.pnl = pnl - commission; - - // Update average price if position continues - if (Math.abs(newQuantity) > 0.0001) { - position.avgPrice = price; - } - } else if (Math.sign(oldQuantity) === Math.sign(newQuantity) || oldQuantity === 0) { - // Adding to position - const totalCost = Math.abs(oldQuantity) * position.avgPrice + quantity * price; - const totalQuantity = Math.abs(oldQuantity) + quantity; - position.avgPrice = totalCost / totalQuantity; - position.realizedPnl -= commission; - } - - position.quantity = newQuantity; - position.lastUpdateTime = trade.timestamp; - } - - // Store or remove position - if (Math.abs(position.quantity) < 0.0001) { - this.positions.delete(symbol); - logger.info(`Closed position for ${symbol}, realized P&L: $${position.realizedPnl.toFixed(2)}`); - } else { - this.positions.set(symbol, position); - } - - // Record trade - this.trades.push(trade); - - // Update account balance - if (trade.pnl !== undefined) { - this.accountBalance += trade.pnl; - } - - return position; - } - - /** - * Get current position for a symbol - */ - getPosition(symbol: string): Position | undefined { - return this.positions.get(symbol); - } - - /** - * Get position quantity - */ - getPositionQuantity(symbol: string): number { - const position = this.positions.get(symbol); - return position ? position.quantity : 0; - } - - /** - * Check if has position - */ - hasPosition(symbol: string): boolean { - const position = this.positions.get(symbol); - return position !== undefined && Math.abs(position.quantity) > 0.0001; - } - - /** - * Get all open positions - */ - getOpenPositions(): Position[] { - return Array.from(this.positions.values()); - } - - /** - * Update market prices for positions - */ - updateMarketPrices(prices: Map): void { - for (const [symbol, position] of this.positions) { - const currentPrice = prices.get(symbol); - if (currentPrice) { - position.currentPrice = currentPrice; - position.unrealizedPnl = this.calculatePnl( - position.avgPrice, - currentPrice, - Math.abs(position.quantity), - position.quantity > 0 ? 'sell' : 'buy' - ); - } - } - } - - /** - * Calculate position size based on risk parameters - */ - calculatePositionSize(params: PositionSizingParams, currentPrice: number): number { - const { - accountBalance, - riskPerTrade, - stopLossDistance, - maxPositionSize = 0.25, - volatilityAdjustment = false, - atr - } = params; - - let positionSize: number; - - if (stopLossDistance && stopLossDistance > 0) { - // Risk-based position sizing - const riskAmount = accountBalance * riskPerTrade; - positionSize = Math.floor(riskAmount / stopLossDistance); - } else if (volatilityAdjustment && atr) { - // Volatility-based position sizing - const riskAmount = accountBalance * riskPerTrade; - const stopDistance = atr * 2; // 2 ATR stop - positionSize = Math.floor(riskAmount / stopDistance); - } else { - // Fixed percentage position sizing - const positionValue = accountBalance * riskPerTrade * 10; // Simplified - positionSize = Math.floor(positionValue / currentPrice); - } - - // Apply max position size limit - const maxShares = Math.floor((accountBalance * maxPositionSize) / currentPrice); - positionSize = Math.min(positionSize, maxShares); - - // Ensure minimum position size - return Math.max(1, positionSize); - } - - /** - * Calculate Kelly Criterion position size - */ - calculateKellySize(winRate: number, avgWin: number, avgLoss: number, currentPrice: number): number { - if (avgLoss === 0) return 0; - - const b = avgWin / avgLoss; - const p = winRate; - const q = 1 - p; - const kelly = (p * b - q) / b; - - // Apply Kelly fraction (usually 0.25 to be conservative) - const kellyFraction = 0.25; - const percentageOfCapital = Math.max(0, Math.min(0.25, kelly * kellyFraction)); - - const positionValue = this.accountBalance * percentageOfCapital; - return Math.max(1, Math.floor(positionValue / currentPrice)); - } - - /** - * Get performance metrics - */ - getPerformanceMetrics() { - const totalTrades = this.trades.length; - const winningTrades = this.trades.filter(t => (t.pnl || 0) > 0); - const losingTrades = this.trades.filter(t => (t.pnl || 0) < 0); - - const totalPnl = this.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); - const unrealizedPnl = Array.from(this.positions.values()) - .reduce((sum, p) => sum + (p.unrealizedPnl || 0), 0); - - const winRate = totalTrades > 0 ? winningTrades.length / totalTrades : 0; - const avgWin = winningTrades.length > 0 - ? winningTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / winningTrades.length - : 0; - const avgLoss = losingTrades.length > 0 - ? Math.abs(losingTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / losingTrades.length) - : 0; - - const profitFactor = avgLoss > 0 ? (avgWin * winningTrades.length) / (avgLoss * losingTrades.length) : 0; - - return { - totalTrades, - winningTrades: winningTrades.length, - losingTrades: losingTrades.length, - winRate: winRate * 100, - totalPnl, - unrealizedPnl, - totalEquity: this.accountBalance + unrealizedPnl, - avgWin, - avgLoss, - profitFactor, - returnPct: ((this.accountBalance - this.initialBalance) / this.initialBalance) * 100 - }; - } - - /** - * Get account balance - */ - getAccountBalance(): number { - return this.accountBalance; - } - - /** - * Get total equity (balance + unrealized P&L) - */ - getTotalEquity(): number { - const unrealizedPnl = Array.from(this.positions.values()) - .reduce((sum, p) => sum + (p.unrealizedPnl || 0), 0); - return this.accountBalance + unrealizedPnl; - } - - private calculatePnl( - entryPrice: number, - exitPrice: number, - quantity: number, - side: 'buy' | 'sell' - ): number { - if (side === 'sell') { - return (exitPrice - entryPrice) * quantity; - } else { - return (entryPrice - exitPrice) * quantity; - } - } -} \ No newline at end of file +import { getLogger } from '@stock-bot/logger'; + +const logger = getLogger('PositionManager'); + +export interface Position { + symbol: string; + quantity: number; + avgPrice: number; + currentPrice?: number; + unrealizedPnl?: number; + realizedPnl: number; + openTime: Date; + lastUpdateTime: Date; +} + +export interface Trade { + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + price: number; + commission: number; + timestamp: Date; + pnl?: number; +} + +export interface PositionSizingParams { + accountBalance: number; + riskPerTrade: number; // As percentage (e.g., 0.02 for 2%) + stopLossDistance?: number; // Price distance for stop loss + maxPositionSize?: number; // Max % of account in one position + volatilityAdjustment?: boolean; + atr?: number; // For volatility-based sizing +} + +/** + * Manages positions and calculates position sizes + */ +export class PositionManager { + private positions: Map = new Map(); + private trades: Trade[] = []; + private accountBalance: number; + private initialBalance: number; + + constructor(initialBalance: number = 100000) { + this.initialBalance = initialBalance; + this.accountBalance = initialBalance; + } + + /** + * Update position with a new trade + */ + updatePosition(trade: Trade): Position { + const { symbol, side, quantity, price, commission } = trade; + let position = this.positions.get(symbol); + + if (!position) { + // New position + position = { + symbol, + quantity: side === 'buy' ? quantity : -quantity, + avgPrice: price, + realizedPnl: -commission, + openTime: trade.timestamp, + lastUpdateTime: trade.timestamp, + }; + } else { + const oldQuantity = position.quantity; + const newQuantity = side === 'buy' ? oldQuantity + quantity : oldQuantity - quantity; + + if (Math.sign(oldQuantity) !== Math.sign(newQuantity) && oldQuantity !== 0) { + // Position flip or close + const closedQuantity = Math.min(Math.abs(oldQuantity), quantity); + const pnl = this.calculatePnl( + position.avgPrice, + price, + closedQuantity, + oldQuantity > 0 ? 'sell' : 'buy' + ); + + position.realizedPnl += pnl - commission; + trade.pnl = pnl - commission; + + // Update average price if position continues + if (Math.abs(newQuantity) > 0.0001) { + position.avgPrice = price; + } + } else if (Math.sign(oldQuantity) === Math.sign(newQuantity) || oldQuantity === 0) { + // Adding to position + const totalCost = Math.abs(oldQuantity) * position.avgPrice + quantity * price; + const totalQuantity = Math.abs(oldQuantity) + quantity; + position.avgPrice = totalCost / totalQuantity; + position.realizedPnl -= commission; + } + + position.quantity = newQuantity; + position.lastUpdateTime = trade.timestamp; + } + + // Store or remove position + if (Math.abs(position.quantity) < 0.0001) { + this.positions.delete(symbol); + logger.info( + `Closed position for ${symbol}, realized P&L: $${position.realizedPnl.toFixed(2)}` + ); + } else { + this.positions.set(symbol, position); + } + + // Record trade + this.trades.push(trade); + + // Update account balance + if (trade.pnl !== undefined) { + this.accountBalance += trade.pnl; + } + + return position; + } + + /** + * Get current position for a symbol + */ + getPosition(symbol: string): Position | undefined { + return this.positions.get(symbol); + } + + /** + * Get position quantity + */ + getPositionQuantity(symbol: string): number { + const position = this.positions.get(symbol); + return position ? position.quantity : 0; + } + + /** + * Check if has position + */ + hasPosition(symbol: string): boolean { + const position = this.positions.get(symbol); + return position !== undefined && Math.abs(position.quantity) > 0.0001; + } + + /** + * Get all open positions + */ + getOpenPositions(): Position[] { + return Array.from(this.positions.values()); + } + + /** + * Update market prices for positions + */ + updateMarketPrices(prices: Map): void { + for (const [symbol, position] of this.positions) { + const currentPrice = prices.get(symbol); + if (currentPrice) { + position.currentPrice = currentPrice; + position.unrealizedPnl = this.calculatePnl( + position.avgPrice, + currentPrice, + Math.abs(position.quantity), + position.quantity > 0 ? 'sell' : 'buy' + ); + } + } + } + + /** + * Calculate position size based on risk parameters + */ + calculatePositionSize(params: PositionSizingParams, currentPrice: number): number { + const { + accountBalance, + riskPerTrade, + stopLossDistance, + maxPositionSize = 0.25, + volatilityAdjustment = false, + atr, + } = params; + + let positionSize: number; + + if (stopLossDistance && stopLossDistance > 0) { + // Risk-based position sizing + const riskAmount = accountBalance * riskPerTrade; + positionSize = Math.floor(riskAmount / stopLossDistance); + } else if (volatilityAdjustment && atr) { + // Volatility-based position sizing + const riskAmount = accountBalance * riskPerTrade; + const stopDistance = atr * 2; // 2 ATR stop + positionSize = Math.floor(riskAmount / stopDistance); + } else { + // Fixed percentage position sizing + const positionValue = accountBalance * riskPerTrade * 10; // Simplified + positionSize = Math.floor(positionValue / currentPrice); + } + + // Apply max position size limit + const maxShares = Math.floor((accountBalance * maxPositionSize) / currentPrice); + positionSize = Math.min(positionSize, maxShares); + + // Ensure minimum position size + return Math.max(1, positionSize); + } + + /** + * Calculate Kelly Criterion position size + */ + calculateKellySize( + winRate: number, + avgWin: number, + avgLoss: number, + currentPrice: number + ): number { + if (avgLoss === 0) { + return 0; + } + + const b = avgWin / avgLoss; + const p = winRate; + const q = 1 - p; + const kelly = (p * b - q) / b; + + // Apply Kelly fraction (usually 0.25 to be conservative) + const kellyFraction = 0.25; + const percentageOfCapital = Math.max(0, Math.min(0.25, kelly * kellyFraction)); + + const positionValue = this.accountBalance * percentageOfCapital; + return Math.max(1, Math.floor(positionValue / currentPrice)); + } + + /** + * Get performance metrics + */ + getPerformanceMetrics() { + const totalTrades = this.trades.length; + const winningTrades = this.trades.filter(t => (t.pnl || 0) > 0); + const losingTrades = this.trades.filter(t => (t.pnl || 0) < 0); + + const totalPnl = this.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); + const unrealizedPnl = Array.from(this.positions.values()).reduce( + (sum, p) => sum + (p.unrealizedPnl || 0), + 0 + ); + + const winRate = totalTrades > 0 ? winningTrades.length / totalTrades : 0; + const avgWin = + winningTrades.length > 0 + ? winningTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / winningTrades.length + : 0; + const avgLoss = + losingTrades.length > 0 + ? Math.abs(losingTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / losingTrades.length) + : 0; + + const profitFactor = + avgLoss > 0 ? (avgWin * winningTrades.length) / (avgLoss * losingTrades.length) : 0; + + return { + totalTrades, + winningTrades: winningTrades.length, + losingTrades: losingTrades.length, + winRate: winRate * 100, + totalPnl, + unrealizedPnl, + totalEquity: this.accountBalance + unrealizedPnl, + avgWin, + avgLoss, + profitFactor, + returnPct: ((this.accountBalance - this.initialBalance) / this.initialBalance) * 100, + }; + } + + /** + * Get account balance + */ + getAccountBalance(): number { + return this.accountBalance; + } + + /** + * Get total equity (balance + unrealized P&L) + */ + getTotalEquity(): number { + const unrealizedPnl = Array.from(this.positions.values()).reduce( + (sum, p) => sum + (p.unrealizedPnl || 0), + 0 + ); + return this.accountBalance + unrealizedPnl; + } + + private calculatePnl( + entryPrice: number, + exitPrice: number, + quantity: number, + side: 'buy' | 'sell' + ): number { + if (side === 'sell') { + return (exitPrice - entryPrice) * quantity; + } else { + return (entryPrice - exitPrice) * quantity; + } + } +} diff --git a/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts b/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts index eba69527..f4f4b2a1 100644 --- a/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts +++ b/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts @@ -1,262 +1,275 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('RiskManager'); - -export interface RiskLimits { - maxPositions?: number; - maxPositionSizePct?: number; // Max % of account per position - maxTotalExposurePct?: number; // Max % of account in all positions - maxDailyLossPct?: number; // Max daily loss as % of account - maxDrawdownPct?: number; // Max drawdown allowed - maxConsecutiveLosses?: number; - minWinRate?: number; // Minimum win rate to continue trading -} - -export interface RiskMetrics { - currentExposure: number; - currentExposurePct: number; - dailyPnl: number; - dailyPnlPct: number; - currentDrawdown: number; - currentDrawdownPct: number; - maxDrawdown: number; - maxDrawdownPct: number; - consecutiveLosses: number; - volatility: number; - sharpeRatio: number; - var95: number; // Value at Risk 95% -} - -export interface RiskCheckResult { - allowed: boolean; - reason?: string; - adjustedSize?: number; -} - -/** - * Manages risk limits and calculates risk metrics - */ -export class RiskManager { - private limits: Required; - private dailyPnl = 0; - private dailyStartBalance: number; - private peakBalance: number; - private consecutiveLosses = 0; - private dailyReturns: number[] = []; - private readonly lookbackDays = 30; - - constructor( - private accountBalance: number, - limits: RiskLimits = {} - ) { - this.limits = { - maxPositions: 10, - maxPositionSizePct: 0.1, - maxTotalExposurePct: 0.6, - maxDailyLossPct: 0.05, - maxDrawdownPct: 0.2, - maxConsecutiveLosses: 5, - minWinRate: 0.3, - ...limits - }; - - this.dailyStartBalance = accountBalance; - this.peakBalance = accountBalance; - } - - /** - * Check if a new position is allowed - */ - checkNewPosition( - symbol: string, - proposedSize: number, - price: number, - currentPositions: Map - ): RiskCheckResult { - const proposedValue = Math.abs(proposedSize * price); - const proposedPct = proposedValue / this.accountBalance; - - // Check max position size - if (proposedPct > this.limits.maxPositionSizePct) { - const maxValue = this.accountBalance * this.limits.maxPositionSizePct; - const adjustedSize = Math.floor(maxValue / price); - - return { - allowed: true, - reason: `Position size reduced from ${proposedSize} to ${adjustedSize} (max ${(this.limits.maxPositionSizePct * 100).toFixed(1)}% per position)`, - adjustedSize - }; - } - - // Check max positions - if (currentPositions.size >= this.limits.maxPositions && !currentPositions.has(symbol)) { - return { - allowed: false, - reason: `Maximum number of positions (${this.limits.maxPositions}) reached` - }; - } - - // Check total exposure - let totalExposure = proposedValue; - for (const [sym, pos] of currentPositions) { - if (sym !== symbol) { - totalExposure += Math.abs(pos.value); - } - } - - const totalExposurePct = totalExposure / this.accountBalance; - if (totalExposurePct > this.limits.maxTotalExposurePct) { - return { - allowed: false, - reason: `Total exposure would be ${(totalExposurePct * 100).toFixed(1)}% (max ${(this.limits.maxTotalExposurePct * 100).toFixed(1)}%)` - }; - } - - // Check daily loss limit - const dailyLossPct = Math.abs(this.dailyPnl) / this.dailyStartBalance; - if (this.dailyPnl < 0 && dailyLossPct >= this.limits.maxDailyLossPct) { - return { - allowed: false, - reason: `Daily loss limit reached (${(dailyLossPct * 100).toFixed(1)}%)` - }; - } - - // Check consecutive losses - if (this.consecutiveLosses >= this.limits.maxConsecutiveLosses) { - return { - allowed: false, - reason: `Maximum consecutive losses (${this.limits.maxConsecutiveLosses}) reached` - }; - } - - // Check drawdown - const currentDrawdownPct = (this.peakBalance - this.accountBalance) / this.peakBalance; - if (currentDrawdownPct >= this.limits.maxDrawdownPct) { - return { - allowed: false, - reason: `Maximum drawdown reached (${(currentDrawdownPct * 100).toFixed(1)}%)` - }; - } - - return { allowed: true }; - } - - /** - * Update metrics after a trade - */ - updateAfterTrade(pnl: number): void { - this.dailyPnl += pnl; - this.accountBalance += pnl; - - if (pnl < 0) { - this.consecutiveLosses++; - } else if (pnl > 0) { - this.consecutiveLosses = 0; - } - - if (this.accountBalance > this.peakBalance) { - this.peakBalance = this.accountBalance; - } - } - - /** - * Reset daily metrics - */ - resetDaily(): void { - // Record daily return - const dailyReturn = (this.accountBalance - this.dailyStartBalance) / this.dailyStartBalance; - this.dailyReturns.push(dailyReturn); - - // Keep only recent returns - if (this.dailyReturns.length > this.lookbackDays) { - this.dailyReturns.shift(); - } - - this.dailyPnl = 0; - this.dailyStartBalance = this.accountBalance; - - logger.info(`Daily reset - Balance: $${this.accountBalance.toFixed(2)}, Daily return: ${(dailyReturn * 100).toFixed(2)}%`); - } - - /** - * Calculate current risk metrics - */ - getMetrics(currentPositions: Map): RiskMetrics { - let currentExposure = 0; - for (const pos of currentPositions.values()) { - currentExposure += Math.abs(pos.value); - } - - const currentDrawdown = this.peakBalance - this.accountBalance; - const currentDrawdownPct = this.peakBalance > 0 ? currentDrawdown / this.peakBalance : 0; - - return { - currentExposure, - currentExposurePct: currentExposure / this.accountBalance, - dailyPnl: this.dailyPnl, - dailyPnlPct: this.dailyPnl / this.dailyStartBalance, - currentDrawdown, - currentDrawdownPct, - maxDrawdown: Math.max(currentDrawdown, 0), - maxDrawdownPct: Math.max(currentDrawdownPct, 0), - consecutiveLosses: this.consecutiveLosses, - volatility: this.calculateVolatility(), - sharpeRatio: this.calculateSharpeRatio(), - var95: this.calculateVaR(0.95) - }; - } - - /** - * Update risk limits - */ - updateLimits(newLimits: Partial): void { - this.limits = { ...this.limits, ...newLimits }; - logger.info('Risk limits updated:', this.limits); - } - - /** - * Get current limits - */ - getLimits(): Required { - return { ...this.limits }; - } - - /** - * Calculate portfolio volatility - */ - private calculateVolatility(): number { - if (this.dailyReturns.length < 2) return 0; - - const mean = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; - const variance = this.dailyReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (this.dailyReturns.length - 1); - - return Math.sqrt(variance) * Math.sqrt(252); // Annualized - } - - /** - * Calculate Sharpe ratio - */ - private calculateSharpeRatio(riskFreeRate = 0.02): number { - if (this.dailyReturns.length < 2) return 0; - - const avgReturn = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; - const annualizedReturn = avgReturn * 252; - const volatility = this.calculateVolatility(); - - if (volatility === 0) return 0; - - return (annualizedReturn - riskFreeRate) / volatility; - } - - /** - * Calculate Value at Risk - */ - private calculateVaR(confidence: number): number { - if (this.dailyReturns.length < 5) return 0; - - const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sortedReturns.length); - - return Math.abs(sortedReturns[index] * this.accountBalance); - } -} \ No newline at end of file +import { getLogger } from '@stock-bot/logger'; +import { at } from '@stock-bot/utils'; + +const logger = getLogger('RiskManager'); + +export interface RiskLimits { + maxPositions?: number; + maxPositionSizePct?: number; // Max % of account per position + maxTotalExposurePct?: number; // Max % of account in all positions + maxDailyLossPct?: number; // Max daily loss as % of account + maxDrawdownPct?: number; // Max drawdown allowed + maxConsecutiveLosses?: number; + minWinRate?: number; // Minimum win rate to continue trading +} + +export interface RiskMetrics { + currentExposure: number; + currentExposurePct: number; + dailyPnl: number; + dailyPnlPct: number; + currentDrawdown: number; + currentDrawdownPct: number; + maxDrawdown: number; + maxDrawdownPct: number; + consecutiveLosses: number; + volatility: number; + sharpeRatio: number; + var95: number; // Value at Risk 95% +} + +export interface RiskCheckResult { + allowed: boolean; + reason?: string; + adjustedSize?: number; +} + +/** + * Manages risk limits and calculates risk metrics + */ +export class RiskManager { + private limits: Required; + private dailyPnl = 0; + private dailyStartBalance: number; + private peakBalance: number; + private consecutiveLosses = 0; + private dailyReturns: number[] = []; + private readonly lookbackDays = 30; + + constructor( + private accountBalance: number, + limits: RiskLimits = {} + ) { + this.limits = { + maxPositions: 10, + maxPositionSizePct: 0.1, + maxTotalExposurePct: 0.6, + maxDailyLossPct: 0.05, + maxDrawdownPct: 0.2, + maxConsecutiveLosses: 5, + minWinRate: 0.3, + ...limits, + }; + + this.dailyStartBalance = accountBalance; + this.peakBalance = accountBalance; + } + + /** + * Check if a new position is allowed + */ + checkNewPosition( + symbol: string, + proposedSize: number, + price: number, + currentPositions: Map + ): RiskCheckResult { + const proposedValue = Math.abs(proposedSize * price); + const proposedPct = proposedValue / this.accountBalance; + + // Check max position size + if (proposedPct > this.limits.maxPositionSizePct) { + const maxValue = this.accountBalance * this.limits.maxPositionSizePct; + const adjustedSize = Math.floor(maxValue / price); + + return { + allowed: true, + reason: `Position size reduced from ${proposedSize} to ${adjustedSize} (max ${(this.limits.maxPositionSizePct * 100).toFixed(1)}% per position)`, + adjustedSize, + }; + } + + // Check max positions + if (currentPositions.size >= this.limits.maxPositions && !currentPositions.has(symbol)) { + return { + allowed: false, + reason: `Maximum number of positions (${this.limits.maxPositions}) reached`, + }; + } + + // Check total exposure + let totalExposure = proposedValue; + for (const [sym, pos] of currentPositions) { + if (sym !== symbol) { + totalExposure += Math.abs(pos.value); + } + } + + const totalExposurePct = totalExposure / this.accountBalance; + if (totalExposurePct > this.limits.maxTotalExposurePct) { + return { + allowed: false, + reason: `Total exposure would be ${(totalExposurePct * 100).toFixed(1)}% (max ${(this.limits.maxTotalExposurePct * 100).toFixed(1)}%)`, + }; + } + + // Check daily loss limit + const dailyLossPct = Math.abs(this.dailyPnl) / this.dailyStartBalance; + if (this.dailyPnl < 0 && dailyLossPct >= this.limits.maxDailyLossPct) { + return { + allowed: false, + reason: `Daily loss limit reached (${(dailyLossPct * 100).toFixed(1)}%)`, + }; + } + + // Check consecutive losses + if (this.consecutiveLosses >= this.limits.maxConsecutiveLosses) { + return { + allowed: false, + reason: `Maximum consecutive losses (${this.limits.maxConsecutiveLosses}) reached`, + }; + } + + // Check drawdown + const currentDrawdownPct = (this.peakBalance - this.accountBalance) / this.peakBalance; + if (currentDrawdownPct >= this.limits.maxDrawdownPct) { + return { + allowed: false, + reason: `Maximum drawdown reached (${(currentDrawdownPct * 100).toFixed(1)}%)`, + }; + } + + return { allowed: true }; + } + + /** + * Update metrics after a trade + */ + updateAfterTrade(pnl: number): void { + this.dailyPnl += pnl; + this.accountBalance += pnl; + + if (pnl < 0) { + this.consecutiveLosses++; + } else if (pnl > 0) { + this.consecutiveLosses = 0; + } + + if (this.accountBalance > this.peakBalance) { + this.peakBalance = this.accountBalance; + } + } + + /** + * Reset daily metrics + */ + resetDaily(): void { + // Record daily return + const dailyReturn = (this.accountBalance - this.dailyStartBalance) / this.dailyStartBalance; + this.dailyReturns.push(dailyReturn); + + // Keep only recent returns + if (this.dailyReturns.length > this.lookbackDays) { + this.dailyReturns.shift(); + } + + this.dailyPnl = 0; + this.dailyStartBalance = this.accountBalance; + + logger.info( + `Daily reset - Balance: $${this.accountBalance.toFixed(2)}, Daily return: ${(dailyReturn * 100).toFixed(2)}%` + ); + } + + /** + * Calculate current risk metrics + */ + getMetrics(currentPositions: Map): RiskMetrics { + let currentExposure = 0; + for (const pos of currentPositions.values()) { + currentExposure += Math.abs(pos.value); + } + + const currentDrawdown = this.peakBalance - this.accountBalance; + const currentDrawdownPct = this.peakBalance > 0 ? currentDrawdown / this.peakBalance : 0; + + return { + currentExposure, + currentExposurePct: currentExposure / this.accountBalance, + dailyPnl: this.dailyPnl, + dailyPnlPct: this.dailyPnl / this.dailyStartBalance, + currentDrawdown, + currentDrawdownPct, + maxDrawdown: Math.max(currentDrawdown, 0), + maxDrawdownPct: Math.max(currentDrawdownPct, 0), + consecutiveLosses: this.consecutiveLosses, + volatility: this.calculateVolatility(), + sharpeRatio: this.calculateSharpeRatio(), + var95: this.calculateVaR(0.95), + }; + } + + /** + * Update risk limits + */ + updateLimits(newLimits: Partial): void { + this.limits = { ...this.limits, ...newLimits }; + logger.info('Risk limits updated:', this.limits); + } + + /** + * Get current limits + */ + getLimits(): Required { + return { ...this.limits }; + } + + /** + * Calculate portfolio volatility + */ + private calculateVolatility(): number { + if (this.dailyReturns.length < 2) { + return 0; + } + + const mean = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; + const variance = + this.dailyReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / + (this.dailyReturns.length - 1); + + return Math.sqrt(variance) * Math.sqrt(252); // Annualized + } + + /** + * Calculate Sharpe ratio + */ + private calculateSharpeRatio(riskFreeRate = 0.02): number { + if (this.dailyReturns.length < 2) { + return 0; + } + + const avgReturn = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; + const annualizedReturn = avgReturn * 252; + const volatility = this.calculateVolatility(); + + if (volatility === 0) { + return 0; + } + + return (annualizedReturn - riskFreeRate) / volatility; + } + + /** + * Calculate Value at Risk + */ + private calculateVaR(confidence: number): number { + if (this.dailyReturns.length < 5) { + return 0; + } + + const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b); + const index = Math.floor((1 - confidence) * sortedReturns.length); + + return Math.abs(at(sortedReturns, index) * this.accountBalance); + } +} diff --git a/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts b/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts index e818f77e..841c1999 100644 --- a/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts +++ b/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts @@ -1,136 +1,139 @@ -import { RustStrategy, Signal } from '../RustStrategy'; -import { MarketData } from '../../types'; - -interface BarData { - open: number; - high: number; - low: number; - close: number; - volume: number; - timestamp: number; -} - -export class SimpleMovingAverageCrossoverRust extends RustStrategy { - private priceHistory: Map = new Map(); - private lastCrossover: Map = new Map(); - private barsSinceSignal: Map = new Map(); - - private fastPeriod: number; - private slowPeriod: number; - private minHoldingBars: number; - - constructor(parameters: { - fastPeriod?: number; - slowPeriod?: number; - minHoldingBars?: number; - } = {}) { - super('SimpleMovingAverageCrossover', `sma-crossover-${Date.now()}`, parameters); - - this.fastPeriod = parameters.fastPeriod || 5; - this.slowPeriod = parameters.slowPeriod || 15; - this.minHoldingBars = parameters.minHoldingBars || 3; - } - - protected onMarketData(data: MarketData): Signal[] { - const signals: Signal[] = []; - - // Only process bar data - if (data.data.type !== 'bar') { - return signals; - } - - const bar = data.data as BarData; - const symbol = data.symbol; - const price = bar.close; - - // Update price history - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, []); - this.barsSinceSignal.set(symbol, 0); - } - - const history = this.priceHistory.get(symbol)!; - history.push(price); - - // Keep only necessary history - if (history.length > this.slowPeriod) { - history.shift(); - } - - // Update bars since signal - const currentBar = this.barsSinceSignal.get(symbol) || 0; - this.barsSinceSignal.set(symbol, currentBar + 1); - - // Need enough data - if (history.length < this.slowPeriod) { - return signals; - } - - // Calculate moving averages - const fastMA = this.calculateSMA(history, this.fastPeriod); - const slowMA = this.calculateSMA(history, this.slowPeriod); - - // Calculate previous MAs - const prevHistory = history.slice(0, -1); - const prevFastMA = this.calculateSMA(prevHistory, this.fastPeriod); - const prevSlowMA = this.calculateSMA(prevHistory, this.slowPeriod); - - // Check for crossovers - const currentPosition = this.positions.get(symbol) || 0; - const lastCrossover = this.lastCrossover.get(symbol); - const barsSinceSignal = this.barsSinceSignal.get(symbol) || 0; - - // Golden cross - bullish signal - if (prevFastMA <= prevSlowMA && fastMA > slowMA) { - this.lastCrossover.set(symbol, 'golden'); - - if (currentPosition < 0) { - // Close short position - signals.push(this.closeSignal(symbol, 'Golden cross - Close short')); - } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - // Open long position - signals.push(this.buySignal(symbol, 0.8, 'Golden cross - Open long')); - this.barsSinceSignal.set(symbol, 0); - } - } - - // Death cross - bearish signal - else if (prevFastMA >= prevSlowMA && fastMA < slowMA) { - this.lastCrossover.set(symbol, 'death'); - - if (currentPosition > 0) { - // Close long position - signals.push(this.closeSignal(symbol, 'Death cross - Close long')); - } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - // Open short position - signals.push(this.sellSignal(symbol, 0.8, 'Death cross - Open short')); - this.barsSinceSignal.set(symbol, 0); - } - } - - // Trend following - enter on pullbacks - else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - if (lastCrossover === 'golden' && fastMA > slowMA) { - // Bullish trend continues - signals.push(this.buySignal(symbol, 0.8, 'Bullish trend - Open long')); - this.barsSinceSignal.set(symbol, 0); - } else if (lastCrossover === 'death' && fastMA < slowMA) { - // Bearish trend continues - signals.push(this.sellSignal(symbol, 0.8, 'Bearish trend - Open short')); - this.barsSinceSignal.set(symbol, 0); - } - } - - return signals; - } - - private calculateSMA(prices: number[], period: number): number { - if (prices.length < period) { - return 0; - } - - const relevantPrices = prices.slice(-period); - const sum = relevantPrices.reduce((a, b) => a + b, 0); - return sum / period; - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import { type MarketData } from '../../types'; +import { RustStrategy, type Signal } from '../RustStrategy'; + +interface BarData { + open: number; + high: number; + low: number; + close: number; + volume: number; + timestamp: number; +} + +export class SimpleMovingAverageCrossoverRust extends RustStrategy { + private priceHistory: Map = new Map(); + private lastCrossover: Map = new Map(); + private barsSinceSignal: Map = new Map(); + + private fastPeriod: number; + private slowPeriod: number; + private minHoldingBars: number; + + constructor( + parameters: { + fastPeriod?: number; + slowPeriod?: number; + minHoldingBars?: number; + } = {} + ) { + super('SimpleMovingAverageCrossover', `sma-crossover-${Date.now()}`, parameters); + + this.fastPeriod = parameters.fastPeriod || 5; + this.slowPeriod = parameters.slowPeriod || 15; + this.minHoldingBars = parameters.minHoldingBars || 3; + } + + protected onMarketData(data: MarketData): Signal[] { + const signals: Signal[] = []; + + // Only process bar data + if (data.type !== 'bar') { + return signals; + } + + const bar = data.data as BarData; + const symbol = data.data.symbol; + const price = bar.close; + + // Update price history + if (!this.priceHistory.has(symbol)) { + this.priceHistory.set(symbol, []); + this.barsSinceSignal.set(symbol, 0); + } + + const history = defined(this.priceHistory.get(symbol)); + history.push(price); + + // Keep only necessary history + if (history.length > this.slowPeriod) { + history.shift(); + } + + // Update bars since signal + const currentBar = this.barsSinceSignal.get(symbol) || 0; + this.barsSinceSignal.set(symbol, currentBar + 1); + + // Need enough data + if (history.length < this.slowPeriod) { + return signals; + } + + // Calculate moving averages + const fastMA = this.calculateSMA(history, this.fastPeriod); + const slowMA = this.calculateSMA(history, this.slowPeriod); + + // Calculate previous MAs + const prevHistory = history.slice(0, -1); + const prevFastMA = this.calculateSMA(prevHistory, this.fastPeriod); + const prevSlowMA = this.calculateSMA(prevHistory, this.slowPeriod); + + // Check for crossovers + const currentPosition = this.positions.get(symbol) || 0; + const lastCrossover = this.lastCrossover.get(symbol); + const barsSinceSignal = this.barsSinceSignal.get(symbol) || 0; + + // Golden cross - bullish signal + if (prevFastMA <= prevSlowMA && fastMA > slowMA) { + this.lastCrossover.set(symbol, 'golden'); + + if (currentPosition < 0) { + // Close short position + signals.push(this.closeSignal(symbol, 'Golden cross - Close short')); + } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { + // Open long position + signals.push(this.buySignal(symbol, 0.8, 'Golden cross - Open long')); + this.barsSinceSignal.set(symbol, 0); + } + } + + // Death cross - bearish signal + else if (prevFastMA >= prevSlowMA && fastMA < slowMA) { + this.lastCrossover.set(symbol, 'death'); + + if (currentPosition > 0) { + // Close long position + signals.push(this.closeSignal(symbol, 'Death cross - Close long')); + } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { + // Open short position + signals.push(this.sellSignal(symbol, 0.8, 'Death cross - Open short')); + this.barsSinceSignal.set(symbol, 0); + } + } + + // Trend following - enter on pullbacks + else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { + if (lastCrossover === 'golden' && fastMA > slowMA) { + // Bullish trend continues + signals.push(this.buySignal(symbol, 0.8, 'Bullish trend - Open long')); + this.barsSinceSignal.set(symbol, 0); + } else if (lastCrossover === 'death' && fastMA < slowMA) { + // Bearish trend continues + signals.push(this.sellSignal(symbol, 0.8, 'Bearish trend - Open short')); + this.barsSinceSignal.set(symbol, 0); + } + } + + return signals; + } + + private calculateSMA(prices: number[], period: number): number { + if (prices.length < period) { + return 0; + } + + const relevantPrices = prices.slice(-period); + const sum = relevantPrices.reduce((a, b) => a + b, 0); + return sum / period; + } +} diff --git a/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts b/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts index 190a8589..e8cc549d 100644 --- a/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts +++ b/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts @@ -1,469 +1,497 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('SignalManager'); - -export interface SignalRule { - name: string; - condition: (indicators: any) => boolean; - weight: number; - direction: 'buy' | 'sell' | 'both'; -} - -export interface SignalFilter { - name: string; - filter: (signal: TradingSignal, context: any) => boolean; -} - -export interface TradingSignal { - symbol: string; - timestamp: number; - direction: 'buy' | 'sell' | 'neutral'; - strength: number; // -1 to 1 (-1 = strong sell, 1 = strong buy) - confidence: number; // 0 to 1 - rules: string[]; // Rules that triggered - indicators: Record; - metadata?: any; -} - -export interface SignalAggregation { - method: 'weighted' | 'majority' | 'unanimous' | 'threshold'; - threshold?: number; // For threshold method -} - -/** - * Manages trading signals and rules - */ -export class SignalManager { - private rules: SignalRule[] = []; - private filters: SignalFilter[] = []; - private signalHistory: TradingSignal[] = []; - private maxHistorySize = 1000; - - constructor( - private aggregation: SignalAggregation = { method: 'weighted' } - ) {} - - /** - * Add a signal rule - */ - addRule(rule: SignalRule): void { - this.rules.push(rule); - logger.info(`Added signal rule: ${rule.name}`); - } - - /** - * Add multiple rules - */ - addRules(rules: SignalRule[]): void { - rules.forEach(rule => this.addRule(rule)); - } - - /** - * Add a signal filter - */ - addFilter(filter: SignalFilter): void { - this.filters.push(filter); - logger.info(`Added signal filter: ${filter.name}`); - } - - /** - * Remove a rule by name - */ - removeRule(name: string): void { - this.rules = this.rules.filter(r => r.name !== name); - } - - /** - * Generate signal based on indicators - */ - generateSignal( - symbol: string, - timestamp: number, - indicators: Record, - context: any = {} - ): TradingSignal | null { - const triggeredRules: { rule: SignalRule; triggered: boolean }[] = []; - - // Check each rule - for (const rule of this.rules) { - try { - const triggered = rule.condition(indicators); - if (triggered) { - triggeredRules.push({ rule, triggered: true }); - } - } catch (error) { - logger.error(`Error evaluating rule ${rule.name}:`, error); - } - } - - if (triggeredRules.length === 0) { - return null; - } - - // Aggregate signals based on method - const signal = this.aggregateSignals(symbol, timestamp, indicators, triggeredRules); - - if (!signal) return null; - - // Apply filters - for (const filter of this.filters) { - try { - if (!filter.filter(signal, context)) { - logger.debug(`Signal filtered by ${filter.name}`); - return null; - } - } catch (error) { - logger.error(`Error applying filter ${filter.name}:`, error); - } - } - - // Store in history - this.addToHistory(signal); - - return signal; - } - - /** - * Aggregate multiple rule triggers into a single signal - */ - private aggregateSignals( - symbol: string, - timestamp: number, - indicators: Record, - triggeredRules: { rule: SignalRule; triggered: boolean }[] - ): TradingSignal | null { - let buyWeight = 0; - let sellWeight = 0; - let totalWeight = 0; - const rules: string[] = []; - - for (const { rule } of triggeredRules) { - rules.push(rule.name); - totalWeight += Math.abs(rule.weight); - - if (rule.direction === 'buy' || rule.direction === 'both') { - buyWeight += rule.weight; - } - if (rule.direction === 'sell' || rule.direction === 'both') { - sellWeight += rule.weight; - } - } - - let direction: 'buy' | 'sell' | 'neutral' = 'neutral'; - let strength = 0; - let confidence = 0; - - switch (this.aggregation.method) { - case 'weighted': - const netWeight = buyWeight - sellWeight; - strength = totalWeight > 0 ? netWeight / totalWeight : 0; - confidence = Math.min(triggeredRules.length / this.rules.length, 1); - - if (Math.abs(strength) > 0.1) { - direction = strength > 0 ? 'buy' : 'sell'; - } - break; - - case 'majority': - const buyCount = triggeredRules.filter(t => - t.rule.direction === 'buy' || t.rule.direction === 'both' - ).length; - const sellCount = triggeredRules.filter(t => - t.rule.direction === 'sell' || t.rule.direction === 'both' - ).length; - - if (buyCount > sellCount) { - direction = 'buy'; - strength = buyCount / triggeredRules.length; - } else if (sellCount > buyCount) { - direction = 'sell'; - strength = -sellCount / triggeredRules.length; - } - confidence = triggeredRules.length / this.rules.length; - break; - - case 'unanimous': - const allBuy = triggeredRules.every(t => - t.rule.direction === 'buy' || t.rule.direction === 'both' - ); - const allSell = triggeredRules.every(t => - t.rule.direction === 'sell' || t.rule.direction === 'both' - ); - - if (allBuy && triggeredRules.length >= 2) { - direction = 'buy'; - strength = 1; - confidence = 1; - } else if (allSell && triggeredRules.length >= 2) { - direction = 'sell'; - strength = -1; - confidence = 1; - } - break; - - case 'threshold': - const threshold = this.aggregation.threshold || 0.7; - const avgWeight = totalWeight > 0 ? (buyWeight - sellWeight) / totalWeight : 0; - - if (avgWeight >= threshold) { - direction = 'buy'; - strength = avgWeight; - confidence = triggeredRules.length / this.rules.length; - } else if (avgWeight <= -threshold) { - direction = 'sell'; - strength = avgWeight; - confidence = triggeredRules.length / this.rules.length; - } - break; - } - - if (direction === 'neutral') { - return null; - } - - return { - symbol, - timestamp, - direction, - strength, - confidence, - rules, - indicators - }; - } - - /** - * Get recent signals for a symbol - */ - getRecentSignals(symbol: string, count = 10): TradingSignal[] { - return this.signalHistory - .filter(s => s.symbol === symbol) - .slice(-count); - } - - /** - * Get signal statistics - */ - getSignalStats(symbol?: string) { - const signals = symbol - ? this.signalHistory.filter(s => s.symbol === symbol) - : this.signalHistory; - - const buySignals = signals.filter(s => s.direction === 'buy'); - const sellSignals = signals.filter(s => s.direction === 'sell'); - - const avgBuyStrength = buySignals.length > 0 - ? buySignals.reduce((sum, s) => sum + s.strength, 0) / buySignals.length - : 0; - - const avgSellStrength = sellSignals.length > 0 - ? sellSignals.reduce((sum, s) => sum + Math.abs(s.strength), 0) / sellSignals.length - : 0; - - const avgConfidence = signals.length > 0 - ? signals.reduce((sum, s) => sum + s.confidence, 0) / signals.length - : 0; - - return { - totalSignals: signals.length, - buySignals: buySignals.length, - sellSignals: sellSignals.length, - avgBuyStrength, - avgSellStrength, - avgConfidence, - ruleHitRate: this.calculateRuleHitRate() - }; - } - - /** - * Clear signal history - */ - clearHistory(): void { - this.signalHistory = []; - } - - private addToHistory(signal: TradingSignal): void { - this.signalHistory.push(signal); - - if (this.signalHistory.length > this.maxHistorySize) { - this.signalHistory.shift(); - } - } - - private calculateRuleHitRate(): Record { - const ruleHits: Record = {}; - - for (const signal of this.signalHistory) { - for (const rule of signal.rules) { - ruleHits[rule] = (ruleHits[rule] || 0) + 1; - } - } - - const hitRate: Record = {}; - for (const [rule, hits] of Object.entries(ruleHits)) { - hitRate[rule] = this.signalHistory.length > 0 - ? hits / this.signalHistory.length - : 0; - } - - return hitRate; - } -} - -/** - * Common signal rules - */ -export const CommonRules = { - // Moving Average Rules - goldenCross: (fastMA: string, slowMA: string): SignalRule => ({ - name: `Golden Cross (${fastMA}/${slowMA})`, - condition: (indicators) => { - const fast = indicators[fastMA]; - const slow = indicators[slowMA]; - const prevFast = indicators[`${fastMA}_prev`]; - const prevSlow = indicators[`${slowMA}_prev`]; - return prevFast <= prevSlow && fast > slow; - }, - weight: 1, - direction: 'buy' - }), - - deathCross: (fastMA: string, slowMA: string): SignalRule => ({ - name: `Death Cross (${fastMA}/${slowMA})`, - condition: (indicators) => { - const fast = indicators[fastMA]; - const slow = indicators[slowMA]; - const prevFast = indicators[`${fastMA}_prev`]; - const prevSlow = indicators[`${slowMA}_prev`]; - return prevFast >= prevSlow && fast < slow; - }, - weight: 1, - direction: 'sell' - }), - - // RSI Rules - rsiOversold: (threshold = 30): SignalRule => ({ - name: `RSI Oversold (<${threshold})`, - condition: (indicators) => indicators.rsi < threshold, - weight: 0.5, - direction: 'buy' - }), - - rsiOverbought: (threshold = 70): SignalRule => ({ - name: `RSI Overbought (>${threshold})`, - condition: (indicators) => indicators.rsi > threshold, - weight: 0.5, - direction: 'sell' - }), - - // MACD Rules - macdBullishCross: (): SignalRule => ({ - name: 'MACD Bullish Cross', - condition: (indicators) => { - return indicators.macd_prev < indicators.macd_signal_prev && - indicators.macd > indicators.macd_signal; - }, - weight: 0.8, - direction: 'buy' - }), - - macdBearishCross: (): SignalRule => ({ - name: 'MACD Bearish Cross', - condition: (indicators) => { - return indicators.macd_prev > indicators.macd_signal_prev && - indicators.macd < indicators.macd_signal; - }, - weight: 0.8, - direction: 'sell' - }), - - // Bollinger Band Rules - bollingerSqueeze: (threshold = 0.02): SignalRule => ({ - name: `Bollinger Squeeze (<${threshold})`, - condition: (indicators) => { - const bandwidth = (indicators.bb_upper - indicators.bb_lower) / indicators.bb_middle; - return bandwidth < threshold; - }, - weight: 0.3, - direction: 'both' - }), - - priceAtLowerBand: (): SignalRule => ({ - name: 'Price at Lower Bollinger Band', - condition: (indicators) => { - const bbPercent = (indicators.price - indicators.bb_lower) / - (indicators.bb_upper - indicators.bb_lower); - return bbPercent < 0.05; - }, - weight: 0.6, - direction: 'buy' - }), - - priceAtUpperBand: (): SignalRule => ({ - name: 'Price at Upper Bollinger Band', - condition: (indicators) => { - const bbPercent = (indicators.price - indicators.bb_lower) / - (indicators.bb_upper - indicators.bb_lower); - return bbPercent > 0.95; - }, - weight: 0.6, - direction: 'sell' - }) -}; - -/** - * Common signal filters - */ -export const CommonFilters = { - // Minimum signal strength - minStrength: (threshold = 0.5): SignalFilter => ({ - name: `Min Strength (${threshold})`, - filter: (signal) => Math.abs(signal.strength) >= threshold - }), - - // Minimum confidence - minConfidence: (threshold = 0.3): SignalFilter => ({ - name: `Min Confidence (${threshold})`, - filter: (signal) => signal.confidence >= threshold - }), - - // Time of day filter - tradingHours: (startHour = 9.5, endHour = 16): SignalFilter => ({ - name: `Trading Hours (${startHour}-${endHour})`, - filter: (signal) => { - const date = new Date(signal.timestamp); - const hour = date.getUTCHours() + date.getUTCMinutes() / 60; - return hour >= startHour && hour < endHour; - } - }), - - // Trend alignment - trendAlignment: (trendIndicator = 'sma200'): SignalFilter => ({ - name: `Trend Alignment (${trendIndicator})`, - filter: (signal) => { - const trend = signal.indicators[trendIndicator]; - const price = signal.indicators.price; - if (!trend || !price) return true; - - // Buy signals only above trend, sell signals only below - if (signal.direction === 'buy') { - return price > trend; - } else if (signal.direction === 'sell') { - return price < trend; - } - return true; - } - }), - - // Volume confirmation - volumeConfirmation: (multiplier = 1.5): SignalFilter => ({ - name: `Volume Confirmation (${multiplier}x)`, - filter: (signal) => { - const volume = signal.indicators.volume; - const avgVolume = signal.indicators.avg_volume; - if (!volume || !avgVolume) return true; - - return volume >= avgVolume * multiplier; - } - }) -}; \ No newline at end of file +import { getLogger } from '@stock-bot/logger'; + +const logger = getLogger('SignalManager'); + +export interface SignalRule { + name: string; + condition: (indicators: Record) => boolean; + weight: number; + direction: 'buy' | 'sell' | 'both'; +} + +export interface SignalFilter { + name: string; + filter: (signal: TradingSignal, context: Record) => boolean; +} + +export interface TradingSignal { + symbol: string; + timestamp: number; + direction: 'buy' | 'sell' | 'neutral'; + strength: number; // -1 to 1 (-1 = strong sell, 1 = strong buy) + confidence: number; // 0 to 1 + rules: string[]; // Rules that triggered + indicators: Record; + metadata?: unknown; +} + +export interface SignalAggregation { + method: 'weighted' | 'majority' | 'unanimous' | 'threshold'; + threshold?: number; // For threshold method +} + +/** + * Manages trading signals and rules + */ +export class SignalManager { + private rules: SignalRule[] = []; + private filters: SignalFilter[] = []; + private signalHistory: TradingSignal[] = []; + private maxHistorySize = 1000; + + constructor(private aggregation: SignalAggregation = { method: 'weighted' }) {} + + /** + * Add a signal rule + */ + addRule(rule: SignalRule): void { + this.rules.push(rule); + logger.info(`Added signal rule: ${rule.name}`); + } + + /** + * Add multiple rules + */ + addRules(rules: SignalRule[]): void { + rules.forEach(rule => this.addRule(rule)); + } + + /** + * Add a signal filter + */ + addFilter(filter: SignalFilter): void { + this.filters.push(filter); + logger.info(`Added signal filter: ${filter.name}`); + } + + /** + * Remove a rule by name + */ + removeRule(name: string): void { + this.rules = this.rules.filter(r => r.name !== name); + } + + /** + * Generate signal based on indicators + */ + generateSignal( + symbol: string, + timestamp: number, + indicators: Record, + context: Record = {} + ): TradingSignal | null { + const triggeredRules: { rule: SignalRule; triggered: boolean }[] = []; + + // Check each rule + for (const rule of this.rules) { + try { + const triggered = rule.condition(indicators); + if (triggered) { + triggeredRules.push({ rule, triggered: true }); + } + } catch (error) { + logger.error(`Error evaluating rule ${rule.name}:`, error); + } + } + + if (triggeredRules.length === 0) { + return null; + } + + // Aggregate signals based on method + const signal = this.aggregateSignals(symbol, timestamp, indicators, triggeredRules); + + if (!signal) { + return null; + } + + // Apply filters + for (const filter of this.filters) { + try { + if (!filter.filter(signal, context)) { + logger.debug(`Signal filtered by ${filter.name}`); + return null; + } + } catch (error) { + logger.error(`Error applying filter ${filter.name}:`, error); + } + } + + // Store in history + this.addToHistory(signal); + + return signal; + } + + /** + * Aggregate multiple rule triggers into a single signal + */ + private aggregateSignals( + symbol: string, + timestamp: number, + indicators: Record, + triggeredRules: { rule: SignalRule; triggered: boolean }[] + ): TradingSignal | null { + let buyWeight = 0; + let sellWeight = 0; + let totalWeight = 0; + const rules: string[] = []; + + for (const { rule } of triggeredRules) { + rules.push(rule.name); + totalWeight += Math.abs(rule.weight); + + if (rule.direction === 'buy' || rule.direction === 'both') { + buyWeight += rule.weight; + } + if (rule.direction === 'sell' || rule.direction === 'both') { + sellWeight += rule.weight; + } + } + + let direction: 'buy' | 'sell' | 'neutral' = 'neutral'; + let strength = 0; + let confidence = 0; + + switch (this.aggregation.method) { + case 'weighted': { + const netWeight = buyWeight - sellWeight; + strength = totalWeight > 0 ? netWeight / totalWeight : 0; + confidence = Math.min(triggeredRules.length / this.rules.length, 1); + + if (Math.abs(strength) > 0.1) { + direction = strength > 0 ? 'buy' : 'sell'; + } + break; + } + + case 'majority': { + const buyCount = triggeredRules.filter( + t => t.rule.direction === 'buy' || t.rule.direction === 'both' + ).length; + const sellCount = triggeredRules.filter( + t => t.rule.direction === 'sell' || t.rule.direction === 'both' + ).length; + + if (buyCount > sellCount) { + direction = 'buy'; + strength = buyCount / triggeredRules.length; + } else if (sellCount > buyCount) { + direction = 'sell'; + strength = -sellCount / triggeredRules.length; + } + confidence = triggeredRules.length / this.rules.length; + break; + } + + case 'unanimous': { + const allBuy = triggeredRules.every( + t => t.rule.direction === 'buy' || t.rule.direction === 'both' + ); + const allSell = triggeredRules.every( + t => t.rule.direction === 'sell' || t.rule.direction === 'both' + ); + + if (allBuy && triggeredRules.length >= 2) { + direction = 'buy'; + strength = 1; + confidence = 1; + } else if (allSell && triggeredRules.length >= 2) { + direction = 'sell'; + strength = -1; + confidence = 1; + } + break; + } + + case 'threshold': { + const threshold = this.aggregation.threshold || 0.7; + const avgWeight = totalWeight > 0 ? (buyWeight - sellWeight) / totalWeight : 0; + + if (avgWeight >= threshold) { + direction = 'buy'; + strength = avgWeight; + confidence = triggeredRules.length / this.rules.length; + } else if (avgWeight <= -threshold) { + direction = 'sell'; + strength = avgWeight; + confidence = triggeredRules.length / this.rules.length; + } + break; + } + } + + if (direction === 'neutral') { + return null; + } + + return { + symbol, + timestamp, + direction, + strength, + confidence, + rules, + indicators, + }; + } + + /** + * Get recent signals for a symbol + */ + getRecentSignals(symbol: string, count = 10): TradingSignal[] { + return this.signalHistory.filter(s => s.symbol === symbol).slice(-count); + } + + /** + * Get signal statistics + */ + getSignalStats(symbol?: string) { + const signals = symbol + ? this.signalHistory.filter(s => s.symbol === symbol) + : this.signalHistory; + + const buySignals = signals.filter(s => s.direction === 'buy'); + const sellSignals = signals.filter(s => s.direction === 'sell'); + + const avgBuyStrength = + buySignals.length > 0 + ? buySignals.reduce((sum, s) => sum + s.strength, 0) / buySignals.length + : 0; + + const avgSellStrength = + sellSignals.length > 0 + ? sellSignals.reduce((sum, s) => sum + Math.abs(s.strength), 0) / sellSignals.length + : 0; + + const avgConfidence = + signals.length > 0 ? signals.reduce((sum, s) => sum + s.confidence, 0) / signals.length : 0; + + return { + totalSignals: signals.length, + buySignals: buySignals.length, + sellSignals: sellSignals.length, + avgBuyStrength, + avgSellStrength, + avgConfidence, + ruleHitRate: this.calculateRuleHitRate(), + }; + } + + /** + * Clear signal history + */ + clearHistory(): void { + this.signalHistory = []; + } + + private addToHistory(signal: TradingSignal): void { + this.signalHistory.push(signal); + + if (this.signalHistory.length > this.maxHistorySize) { + this.signalHistory.shift(); + } + } + + private calculateRuleHitRate(): Record { + const ruleHits: Record = {}; + + for (const signal of this.signalHistory) { + for (const rule of signal.rules) { + ruleHits[rule] = (ruleHits[rule] || 0) + 1; + } + } + + const hitRate: Record = {}; + for (const [rule, hits] of Object.entries(ruleHits)) { + hitRate[rule] = this.signalHistory.length > 0 ? hits / this.signalHistory.length : 0; + } + + return hitRate; + } +} + +/** + * Common signal rules + */ +export const CommonRules = { + // Moving Average Rules + goldenCross: (fastMA: string, slowMA: string): SignalRule => ({ + name: `Golden Cross (${fastMA}/${slowMA})`, + condition: indicators => { + const fast = indicators[fastMA]; + const slow = indicators[slowMA]; + const prevFast = indicators[`${fastMA}_prev`]; + const prevSlow = indicators[`${slowMA}_prev`]; + if ( + fast === undefined || + slow === undefined || + prevFast === undefined || + prevSlow === undefined + ) { + return false; + } + return prevFast <= prevSlow && fast > slow; + }, + weight: 1, + direction: 'buy', + }), + + deathCross: (fastMA: string, slowMA: string): SignalRule => ({ + name: `Death Cross (${fastMA}/${slowMA})`, + condition: indicators => { + const fast = indicators[fastMA]; + const slow = indicators[slowMA]; + const prevFast = indicators[`${fastMA}_prev`]; + const prevSlow = indicators[`${slowMA}_prev`]; + if ( + fast === undefined || + slow === undefined || + prevFast === undefined || + prevSlow === undefined + ) { + return false; + } + return prevFast >= prevSlow && fast < slow; + }, + weight: 1, + direction: 'sell', + }), + + // RSI Rules + rsiOversold: (threshold = 30): SignalRule => ({ + name: `RSI Oversold (<${threshold})`, + condition: indicators => Number(indicators.rsi) < threshold, + weight: 0.5, + direction: 'buy', + }), + + rsiOverbought: (threshold = 70): SignalRule => ({ + name: `RSI Overbought (>${threshold})`, + condition: indicators => Number(indicators.rsi) > threshold, + weight: 0.5, + direction: 'sell', + }), + + // MACD Rules + macdBullishCross: (): SignalRule => ({ + name: 'MACD Bullish Cross', + condition: indicators => { + return ( + Number(indicators.macd_prev) < Number(indicators.macd_signal_prev) && + Number(indicators.macd) > Number(indicators.macd_signal) + ); + }, + weight: 0.8, + direction: 'buy', + }), + + macdBearishCross: (): SignalRule => ({ + name: 'MACD Bearish Cross', + condition: indicators => { + return ( + Number(indicators.macd_prev) > Number(indicators.macd_signal_prev) && + Number(indicators.macd) < Number(indicators.macd_signal) + ); + }, + weight: 0.8, + direction: 'sell', + }), + + // Bollinger Band Rules + bollingerSqueeze: (threshold = 0.02): SignalRule => ({ + name: `Bollinger Squeeze (<${threshold})`, + condition: indicators => { + const bandwidth = + (Number(indicators.bb_upper) - Number(indicators.bb_lower)) / Number(indicators.bb_middle); + return bandwidth < threshold; + }, + weight: 0.3, + direction: 'both', + }), + + priceAtLowerBand: (): SignalRule => ({ + name: 'Price at Lower Bollinger Band', + condition: indicators => { + const bbPercent = + (Number(indicators.price) - Number(indicators.bb_lower)) / + (Number(indicators.bb_upper) - Number(indicators.bb_lower)); + return bbPercent < 0.05; + }, + weight: 0.6, + direction: 'buy', + }), + + priceAtUpperBand: (): SignalRule => ({ + name: 'Price at Upper Bollinger Band', + condition: indicators => { + const bbPercent = + (Number(indicators.price) - Number(indicators.bb_lower)) / + (Number(indicators.bb_upper) - Number(indicators.bb_lower)); + return bbPercent > 0.95; + }, + weight: 0.6, + direction: 'sell', + }), +}; + +/** + * Common signal filters + */ +export const CommonFilters = { + // Minimum signal strength + minStrength: (threshold = 0.5): SignalFilter => ({ + name: `Min Strength (${threshold})`, + filter: signal => Math.abs(signal.strength) >= threshold, + }), + + // Minimum confidence + minConfidence: (threshold = 0.3): SignalFilter => ({ + name: `Min Confidence (${threshold})`, + filter: signal => signal.confidence >= threshold, + }), + + // Time of day filter + tradingHours: (startHour = 9.5, endHour = 16): SignalFilter => ({ + name: `Trading Hours (${startHour}-${endHour})`, + filter: signal => { + const date = new Date(signal.timestamp); + const hour = date.getUTCHours() + date.getUTCMinutes() / 60; + return hour >= startHour && hour < endHour; + }, + }), + + // Trend alignment + trendAlignment: (trendIndicator = 'sma200'): SignalFilter => ({ + name: `Trend Alignment (${trendIndicator})`, + filter: signal => { + const trend = signal.indicators[trendIndicator]; + const price = signal.indicators.price; + if (!trend || !price) { + return true; + } + + // Buy signals only above trend, sell signals only below + if (signal.direction === 'buy') { + return price > trend; + } else if (signal.direction === 'sell') { + return price < trend; + } + return true; + }, + }), + + // Volume confirmation + volumeConfirmation: (multiplier = 1.5): SignalFilter => ({ + name: `Volume Confirmation (${multiplier}x)`, + filter: signal => { + const volume = signal.indicators.volume; + const avgVolume = signal.indicators.avg_volume; + if (!volume || !avgVolume) { + return true; + } + + return volume >= avgVolume * multiplier; + }, + }), +}; diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index 549040ba..2ff42672 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -1,173 +1,206 @@ -import { z } from 'zod'; - -// Trading modes -export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']); -export type TradingMode = z.infer; - -// Mode configurations -export const BacktestConfigSchema = z.object({ - mode: z.literal('backtest'), - startDate: z.string().datetime(), - endDate: z.string().datetime(), - symbols: z.array(z.string()), - initialCapital: z.number().positive(), - dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']), - strategy: z.string(), - strategies: z.array(z.object({ - name: z.string(), - enabled: z.boolean().default(true), - config: z.record(z.any()).optional() - })).optional(), - commission: z.number().optional(), - slippage: z.number().optional(), - fillModel: z.object({ - slippage: z.enum(['zero', 'conservative', 'realistic', 'aggressive']), - marketImpact: z.boolean(), - partialFills: z.boolean() - }).optional(), - speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max') -}); - -export const PaperConfigSchema = z.object({ - mode: z.literal('paper'), - startingCapital: z.number().positive(), - fillModel: z.object({ - useRealOrderBook: z.boolean().default(true), - addLatency: z.number().min(0).default(100) - }).optional() -}); - -export const LiveConfigSchema = z.object({ - mode: z.literal('live'), - broker: z.string(), - accountId: z.string(), - accountType: z.enum(['cash', 'margin']), - riskLimits: z.object({ - maxPositionSize: z.number().positive(), - maxDailyLoss: z.number().positive(), - maxOrderSize: z.number().positive(), - maxGrossExposure: z.number().positive(), - maxSymbolExposure: z.number().positive() - }) -}); - -export const ModeConfigSchema = z.discriminatedUnion('mode', [ - BacktestConfigSchema, - PaperConfigSchema, - LiveConfigSchema -]); - -export type ModeConfig = z.infer; - -// Market data types -export const QuoteSchema = z.object({ - symbol: z.string(), - bid: z.number(), - ask: z.number(), - bidSize: z.number(), - askSize: z.number(), - timestamp: z.number() -}); - -export const TradeSchema = z.object({ - symbol: z.string(), - price: z.number(), - size: z.number(), - side: z.enum(['buy', 'sell']), - timestamp: z.number() -}); - -export const BarSchema = z.object({ - symbol: z.string(), - open: z.number(), - high: z.number(), - low: z.number(), - close: z.number(), - volume: z.number(), - vwap: z.number().optional(), - timestamp: z.number() -}); - -export const MarketDataSchema = z.discriminatedUnion('type', [ - z.object({ type: z.literal('quote'), data: QuoteSchema }), - z.object({ type: z.literal('trade'), data: TradeSchema }), - z.object({ type: z.literal('bar'), data: BarSchema }) -]); - -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(), - side: OrderSideSchema, - quantity: z.number().positive(), - orderType: OrderTypeSchema, - limitPrice: z.number().positive().optional(), - stopPrice: z.number().positive().optional(), - timeInForce: TimeInForceSchema.default('DAY'), - clientOrderId: z.string().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.any()), - symbols: z.array(z.string()), - allocation: z.number().min(0).max(1) -}); - -export type StrategyConfig = z.infer; - -// Analytics types -export const PerformanceMetricsSchema = z.object({ - totalReturn: z.number(), - sharpeRatio: z.number(), - sortinoRatio: z.number(), - maxDrawdown: z.number(), - winRate: z.number(), - profitFactor: z.number(), - avgWin: z.number(), - avgLoss: z.number(), - totalTrades: z.number() -}); - -export type PerformanceMetrics = z.infer; - -// Risk types -export const RiskMetricsSchema = z.object({ - currentExposure: z.number(), - dailyPnl: z.number(), - positionCount: z.number(), - grossExposure: z.number(), - var95: z.number().optional(), - cvar95: z.number().optional() -}); - -export type RiskMetrics = z.infer; - -// Re-export specialized types -export type { MarketMicrostructure, PriceLevel, OrderBookSnapshot } from './types/MarketMicrostructure'; \ No newline at end of file +import { z } from 'zod'; + +// Trading modes +export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']); +export type TradingMode = z.infer; + +// Mode configurations +export const BacktestConfigSchema = z.object({ + mode: z.literal('backtest'), + name: z.string().optional(), + runId: z.string().optional(), + config: z.record(z.unknown()).optional(), + startDate: z.string().datetime(), + endDate: z.string().datetime(), + symbols: z.array(z.string()), + initialCapital: z.number().positive(), + dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']), + strategy: z.string(), + strategies: z + .array( + z.object({ + name: z.string(), + enabled: z.boolean().default(true), + config: z.record(z.unknown()).optional(), + }) + ) + .optional(), + commission: z.number().optional(), + slippage: z.number().optional(), + fillModel: z + .object({ + slippage: z.enum(['zero', 'conservative', 'realistic', 'aggressive']), + marketImpact: z.boolean(), + partialFills: z.boolean(), + }) + .optional(), + speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max'), +}); + +export const PaperConfigSchema = z.object({ + mode: z.literal('paper'), + startingCapital: z.number().positive(), + fillModel: z + .object({ + useRealOrderBook: z.boolean().default(true), + addLatency: z.number().min(0).default(100), + }) + .optional(), +}); + +export const LiveConfigSchema = z.object({ + mode: z.literal('live'), + broker: z.string(), + accountId: z.string(), + accountType: z.enum(['cash', 'margin']), + riskLimits: z.object({ + maxPositionSize: z.number().positive(), + maxDailyLoss: z.number().positive(), + maxOrderSize: z.number().positive(), + maxGrossExposure: z.number().positive(), + maxSymbolExposure: z.number().positive(), + }), +}); + +export const ModeConfigSchema = z.discriminatedUnion('mode', [ + BacktestConfigSchema, + PaperConfigSchema, + LiveConfigSchema, +]); + +export type BacktestConfig = z.infer; + +export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & { + custom?: Partial<{ + 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; + BacktestEngine: + | import('./backtest/BacktestEngine').BacktestEngine + | import('./backtest/RustBacktestAdapter').RustBacktestAdapter; + PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager; + ModeManager: import('./core/ModeManager').ModeManager; + }>; +}; +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(), + ask: z.number(), + bidSize: z.number(), + askSize: z.number(), + timestamp: z.number(), +}); + +export const TradeSchema = z.object({ + symbol: z.string(), + price: z.number(), + size: z.number(), + side: z.enum(['buy', 'sell']), + timestamp: z.number(), +}); + +export const BarSchema = z.object({ + symbol: z.string(), + open: z.number(), + high: z.number(), + low: z.number(), + close: z.number(), + volume: z.number(), + vwap: z.number().optional(), + timestamp: z.number(), +}); + +export const MarketDataSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('quote'), data: QuoteSchema }), + z.object({ type: z.literal('trade'), data: TradeSchema }), + z.object({ type: z.literal('bar'), data: BarSchema }), +]); + +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(), + side: OrderSideSchema, + quantity: z.number().positive(), + orderType: OrderTypeSchema, + limitPrice: z.number().positive().optional(), + stopPrice: z.number().positive().optional(), + timeInForce: TimeInForceSchema.default('DAY'), + clientOrderId: z.string().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; + +// Analytics types +export const PerformanceMetricsSchema = z.object({ + totalReturn: z.number(), + sharpeRatio: z.number(), + sortinoRatio: z.number(), + maxDrawdown: z.number(), + winRate: z.number(), + profitFactor: z.number(), + avgWin: z.number(), + avgLoss: z.number(), + totalTrades: z.number(), +}); + +export type PerformanceMetrics = z.infer; + +// Risk types +export const RiskMetricsSchema = z.object({ + currentExposure: z.number(), + dailyPnl: z.number(), + positionCount: z.number(), + grossExposure: z.number(), + var95: z.number().optional(), + cvar95: z.number().optional(), +}); + +export type RiskMetrics = z.infer; + +// Re-export specialized types +export type { + MarketMicrostructure, + PriceLevel, + OrderBookSnapshot, +} from './types/MarketMicrostructure'; diff --git a/apps/stock/orchestrator/tests/indicators.test.ts b/apps/stock/orchestrator/tests/indicators.test.ts index 4c07bced..9014a317 100644 --- a/apps/stock/orchestrator/tests/indicators.test.ts +++ b/apps/stock/orchestrator/tests/indicators.test.ts @@ -1,195 +1,199 @@ -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.10, 45.42, - 45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00, - 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.70, 48.72, 48.90, 48.87, 48.82, 49.05, 49.20, 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.50, 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); - }); - }); -}); \ No newline at end of file +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/orchestrator/tsconfig.json b/apps/stock/orchestrator/tsconfig.json index 877b067b..582b9bf5 100644 --- a/apps/stock/orchestrator/tsconfig.json +++ b/apps/stock/orchestrator/tsconfig.json @@ -30,5 +30,10 @@ "baseUrl": "." }, "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist"], + "references": [ + { + "path": "../../../libs/core/invariants" + } + ] } diff --git a/apps/stock/web-api/package.json b/apps/stock/web-api/package.json index a01aee7b..176e5a08 100644 --- a/apps/stock/web-api/package.json +++ b/apps/stock/web-api/package.json @@ -22,7 +22,8 @@ "@stock-bot/shutdown": "*", "@stock-bot/handlers": "*", "@stock-bot/di": "*", - "hono": "^4.0.0" + "hono": "^4.0.0", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "typescript": "^5.0.0" diff --git a/apps/stock/web-api/src/container-setup.ts b/apps/stock/web-api/src/container-setup.ts index 9e5ff9e4..0937aad6 100644 --- a/apps/stock/web-api/src/container-setup.ts +++ b/apps/stock/web-api/src/container-setup.ts @@ -3,7 +3,7 @@ * Configures dependency injection for the web API service */ -import type { AppConfig } from '@stock-bot/config'; +import type { UnifiedAppConfig } from '@stock-bot/config'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; @@ -13,7 +13,7 @@ const logger = getLogger('web-api-container'); * Configure the service container for web API workloads */ export function setupServiceContainer( - config: AppConfig, + config: UnifiedAppConfig, container: IServiceContainer ): IServiceContainer { logger.info('Configuring web API service container...'); diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 3271dde8..d2992936 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -1,70 +1,67 @@ -import { readFileSync, readdirSync } from 'fs'; -import { join } from 'path'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('migration-runner'); - -export async function runMigrations(container: IServiceContainer): Promise { - logger.info('Migration runner called'); - logger.info('Container type:', typeof container); - logger.info('Container postgres available:', !!container.postgres); - - if (!container.postgres) { - logger.warn('PostgreSQL not available, skipping migrations'); - logger.info('Container keys:', Object.keys(container)); - return; - } - - try { - // Create migrations table if it doesn't exist - await container.postgres.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 - const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init'); - logger.info('Looking for migrations in:', migrationsDir); - - const files = readdirSync(migrationsDir) - .filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now - .sort(); - - logger.info('Found migration files:', files); - - for (const file of files) { - // Check if migration has already been run - const result = await container.postgres.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 container.postgres.query(sql); - - // Record migration as executed - await container.postgres.query( - 'INSERT INTO migrations (filename) VALUES ($1)', - [file] - ); - - logger.info(`Migration completed: ${file}`); - } else { - logger.debug(`Migration already executed: ${file}`); - } - } - - logger.info('All migrations completed successfully'); - } catch (error) { - logger.error('Migration failed', { error }); - throw error; - } -} \ No newline at end of file +import { readdirSync, readFileSync } from 'fs'; +import { join } from 'path'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; + +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 { + // Create migrations table if it doesn't exist + await container.postgres.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 + const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init'); + logger.info('Looking for migrations', { directory: migrationsDir }); + + const files = readdirSync(migrationsDir) + .filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now + .sort(); + + logger.info('Found migration files:', files); + + for (const file of files) { + // Check if migration has already been run + const result = await container.postgres.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 container.postgres.query(sql); + + // Record migration as executed + await container.postgres.query('INSERT INTO migrations (filename) VALUES ($1)', [file]); + + logger.info(`Migration completed: ${file}`); + } else { + logger.debug(`Migration already executed: ${file}`); + } + } + + logger.info('All migrations completed successfully'); + } catch (error) { + logger.error('Migration failed', { error }); + throw error; + } +} diff --git a/apps/stock/web-api/src/routes/backtests-v2.router.ts b/apps/stock/web-api/src/routes/backtests-v2.router.ts deleted file mode 100644 index c511f1cc..00000000 --- a/apps/stock/web-api/src/routes/backtests-v2.router.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { Router } from 'express'; -import { BacktestServiceV2 } from '../services/backtest-v2.service'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('backtests-v2-router'); - -export function createBacktestsV2Router(container: IServiceContainer): Router { - const router = Router(); - const backtestService = new BacktestServiceV2(container); - - // Backtest endpoints - router.get('/backtests', async (req, res) => { - try { - const limit = parseInt(req.query.limit as string) || 50; - const offset = parseInt(req.query.offset as string) || 0; - - const backtests = await backtestService.listBacktests({ limit, offset }); - res.json(backtests); - } catch (error) { - logger.error('Failed to list backtests', error); - res.status(500).json({ error: 'Failed to list backtests' }); - } - }); - - router.get('/backtests/:id', async (req, res) => { - try { - const backtest = await backtestService.getBacktest(req.params.id); - if (!backtest) { - return res.status(404).json({ error: 'Backtest not found' }); - } - res.json(backtest); - } catch (error) { - logger.error('Failed to get backtest', error); - res.status(500).json({ error: 'Failed to get backtest' }); - } - }); - - router.post('/backtests', async (req, res) => { - try { - const backtest = await backtestService.createBacktest(req.body); - res.status(201).json(backtest); - } catch (error) { - logger.error('Failed to create backtest', error); - res.status(500).json({ error: 'Failed to create backtest' }); - } - }); - - router.put('/backtests/:id', async (req, res) => { - try { - const backtest = await backtestService.updateBacktest(req.params.id, req.body); - if (!backtest) { - return res.status(404).json({ error: 'Backtest not found' }); - } - res.json(backtest); - } catch (error) { - logger.error('Failed to update backtest', error); - res.status(500).json({ error: 'Failed to update backtest' }); - } - }); - - router.delete('/backtests/:id', async (req, res) => { - try { - await backtestService.deleteBacktest(req.params.id); - res.status(204).send(); - } catch (error) { - logger.error('Failed to delete backtest', error); - res.status(500).json({ error: 'Failed to delete backtest' }); - } - }); - - // Run endpoints - router.get('/backtests/:backtestId/runs', async (req, res) => { - try { - const runs = await backtestService.listRuns(req.params.backtestId); - res.json(runs); - } catch (error) { - logger.error('Failed to list runs', error); - res.status(500).json({ error: 'Failed to list runs' }); - } - }); - - router.post('/backtests/:backtestId/runs', async (req, res) => { - try { - const run = await backtestService.createRun({ - backtestId: req.params.backtestId, - speedMultiplier: req.body.speedMultiplier - }); - res.status(201).json(run); - } catch (error) { - logger.error('Failed to create run', error); - res.status(500).json({ error: 'Failed to create run' }); - } - }); - - router.get('/runs/:id', async (req, res) => { - try { - const run = await backtestService.getRun(req.params.id); - if (!run) { - return res.status(404).json({ error: 'Run not found' }); - } - res.json(run); - } catch (error) { - logger.error('Failed to get run', error); - res.status(500).json({ error: 'Failed to get run' }); - } - }); - - router.get('/runs/:id/results', async (req, res) => { - try { - const results = await backtestService.getRunResults(req.params.id); - if (!results) { - return res.status(404).json({ error: 'Results not found' }); - } - res.json(results); - } catch (error) { - logger.error('Failed to get run results', error); - res.status(500).json({ error: 'Failed to get run results' }); - } - }); - - router.post('/runs/:id/pause', async (req, res) => { - try { - await backtestService.pauseRun(req.params.id); - res.json({ message: 'Run paused' }); - } catch (error) { - logger.error('Failed to pause run', error); - res.status(500).json({ error: 'Failed to pause run' }); - } - }); - - router.post('/runs/:id/resume', async (req, res) => { - try { - await backtestService.resumeRun(req.params.id); - res.json({ message: 'Run resumed' }); - } catch (error) { - logger.error('Failed to resume run', error); - res.status(500).json({ error: 'Failed to resume run' }); - } - }); - - router.post('/runs/:id/cancel', async (req, res) => { - try { - await backtestService.cancelRun(req.params.id); - res.json({ message: 'Run cancelled' }); - } catch (error) { - logger.error('Failed to cancel run', error); - res.status(500).json({ error: 'Failed to cancel run' }); - } - }); - - router.put('/runs/:id/speed', async (req, res) => { - try { - await backtestService.updateRunSpeed(req.params.id, req.body.speedMultiplier); - res.json({ message: 'Speed updated' }); - } catch (error) { - logger.error('Failed to update run speed', error); - res.status(500).json({ error: 'Failed to update run speed' }); - } - }); - - // WebSocket endpoint for real-time run updates - router.ws('/runs/:id/stream', (ws, req) => { - const runId = req.params.id; - logger.info('WebSocket connection established for run', { runId }); - - // TODO: Implement real-time updates - ws.on('message', (msg) => { - logger.debug('Received WebSocket message', { runId, msg }); - }); - - ws.on('close', () => { - logger.info('WebSocket connection closed', { runId }); - }); - }); - - return router; -} \ No newline at end of file diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index 2f749963..03f21c8e 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -1,196 +1,197 @@ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { BacktestServiceV2 } from '../services/backtest-v2.service'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('backtests-v2-routes'); - -export function createBacktestV2Routes(container: IServiceContainer) { - const app = new Hono(); - const backtestService = new BacktestServiceV2(container); - - // Backtest endpoints - app.get('/api/v2/backtests', async (c) => { - try { - const limit = parseInt(c.req.query('limit') || '50'); - const offset = parseInt(c.req.query('offset') || '0'); - - const backtests = await backtestService.listBacktests({ limit, offset }); - return c.json(backtests); - } catch (error) { - logger.error('Failed to list backtests', error); - return c.json({ error: 'Failed to list backtests' }, 500); - } - }); - - app.get('/api/v2/backtests/:id', async (c) => { - try { - const backtest = await backtestService.getBacktest(c.req.param('id')); - if (!backtest) { - return c.json({ error: 'Backtest not found' }, 404); - } - return c.json(backtest); - } catch (error) { - logger.error('Failed to get backtest', error); - return c.json({ error: 'Failed to get backtest' }, 500); - } - }); - - app.post('/api/v2/backtests', async (c) => { - try { - const body = await c.req.json(); - const backtest = await backtestService.createBacktest(body); - return c.json(backtest, 201); - } catch (error) { - logger.error('Failed to create backtest', error); - return c.json({ error: 'Failed to create backtest' }, 500); - } - }); - - app.put('/api/v2/backtests/:id', async (c) => { - try { - const body = await c.req.json(); - const backtest = await backtestService.updateBacktest(c.req.param('id'), body); - if (!backtest) { - return c.json({ error: 'Backtest not found' }, 404); - } - return c.json(backtest); - } catch (error) { - logger.error('Failed to update backtest', error); - return c.json({ error: 'Failed to update backtest' }, 500); - } - }); - - app.delete('/api/v2/backtests/:id', async (c) => { - try { - await backtestService.deleteBacktest(c.req.param('id')); - return c.text('', 204); - } catch (error) { - logger.error('Failed to delete backtest', error); - return c.json({ error: 'Failed to delete backtest' }, 500); - } - }); - - // Run endpoints - app.get('/api/v2/backtests/:backtestId/runs', async (c) => { - try { - const runs = await backtestService.listRuns(c.req.param('backtestId')); - return c.json(runs); - } catch (error) { - logger.error('Failed to list runs', error); - return c.json({ error: 'Failed to list runs' }, 500); - } - }); - - app.post('/api/v2/backtests/:backtestId/runs', async (c) => { - try { - const body = await c.req.json(); - const run = await backtestService.createRun({ - backtestId: c.req.param('backtestId'), - speedMultiplier: body.speedMultiplier - }); - return c.json(run, 201); - } catch (error) { - logger.error('Failed to create run', error); - return c.json({ error: 'Failed to create run' }, 500); - } - }); - - app.get('/api/v2/runs/:id', async (c) => { - try { - const run = await backtestService.getRun(c.req.param('id')); - if (!run) { - return c.json({ error: 'Run not found' }, 404); - } - return c.json(run); - } catch (error) { - logger.error('Failed to get run', error); - return c.json({ error: 'Failed to get run' }, 500); - } - }); - - app.get('/api/v2/runs/:id/results', async (c) => { - try { - const results = await backtestService.getRunResults(c.req.param('id')); - if (!results) { - return c.json({ error: 'Results not found' }, 404); - } - return c.json(results); - } catch (error) { - logger.error('Failed to get run results', error); - return c.json({ error: 'Failed to get run results' }, 500); - } - }); - - app.post('/api/v2/runs/:id/pause', async (c) => { - try { - await backtestService.pauseRun(c.req.param('id')); - return c.json({ message: 'Run paused' }); - } catch (error) { - logger.error('Failed to pause run', error); - return c.json({ error: 'Failed to pause run' }, 500); - } - }); - - app.post('/api/v2/runs/:id/resume', async (c) => { - try { - await backtestService.resumeRun(c.req.param('id')); - return c.json({ message: 'Run resumed' }); - } catch (error) { - logger.error('Failed to resume run', error); - return c.json({ error: 'Failed to resume run' }, 500); - } - }); - - app.post('/api/v2/runs/:id/cancel', async (c) => { - try { - await backtestService.cancelRun(c.req.param('id')); - return c.json({ message: 'Run cancelled' }); - } catch (error) { - logger.error('Failed to cancel run', error); - return c.json({ error: 'Failed to cancel run' }, 500); - } - }); - - app.put('/api/v2/runs/:id/speed', async (c) => { - try { - const body = await c.req.json(); - await backtestService.updateRunSpeed(c.req.param('id'), body.speedMultiplier); - return c.json({ message: 'Speed updated' }); - } catch (error) { - logger.error('Failed to update run speed', error); - return c.json({ error: 'Failed to update run speed' }, 500); - } - }); - - // Progress update endpoint (called by orchestrator) - app.post('/api/runs/:id/progress', async (c) => { - try { - const runId = c.req.param('id'); - const body = await c.req.json(); - const { progress, currentDate } = body; - - // Update run progress in database - await backtestService.updateRunStatus(runId, 'running', { - progress, - currentDate - }); - - // Broadcast via WebSocket if handler is available - const wsHandler = (global as any).wsHandler; - if (wsHandler) { - wsHandler.sendProgressUpdate(runId, progress, currentDate); - } - - return c.json({ message: 'Progress updated' }); - } catch (error) { - logger.error('Failed to update run progress', error); - return c.json({ error: 'Failed to update run progress' }, 500); - } - }); - - // TODO: WebSocket endpoint for real-time run updates - // This needs additional setup with Hono WebSocket support - - return app; -} \ No newline at end of file +import { Hono } from 'hono'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; +import { BacktestServiceV2 } from '../services/backtest-v2.service'; +import { getWebSocketHandler } from '../websocket/run-updates'; + +const logger = getLogger('backtests-v2-routes'); + +export function createBacktestV2Routes(container: IServiceContainer) { + const app = new Hono(); + const backtestService = new BacktestServiceV2(container); + + // Backtest endpoints + app.get('/api/v2/backtests', async c => { + try { + const limit = parseInt(c.req.query('limit') || '50'); + const offset = parseInt(c.req.query('offset') || '0'); + + const backtests = await backtestService.listBacktests({ limit, offset }); + return c.json(backtests); + } catch (error) { + logger.error('Failed to list backtests', error); + return c.json({ error: 'Failed to list backtests' }, 500); + } + }); + + app.get('/api/v2/backtests/:id', async c => { + try { + const backtest = await backtestService.getBacktest(c.req.param('id')); + if (!backtest) { + return c.json({ error: 'Backtest not found' }, 404); + } + return c.json(backtest); + } catch (error) { + logger.error('Failed to get backtest', error); + return c.json({ error: 'Failed to get backtest' }, 500); + } + }); + + app.post('/api/v2/backtests', async c => { + try { + const body = await c.req.json(); + const backtest = await backtestService.createBacktest(body); + return c.json(backtest, 201); + } catch (error) { + logger.error('Failed to create backtest', error); + return c.json({ error: 'Failed to create backtest' }, 500); + } + }); + + app.put('/api/v2/backtests/:id', async c => { + try { + const body = await c.req.json(); + const backtest = await backtestService.updateBacktest(c.req.param('id'), body); + if (!backtest) { + return c.json({ error: 'Backtest not found' }, 404); + } + return c.json(backtest); + } catch (error) { + logger.error('Failed to update backtest', error); + return c.json({ error: 'Failed to update backtest' }, 500); + } + }); + + app.delete('/api/v2/backtests/:id', async c => { + try { + await backtestService.deleteBacktest(c.req.param('id')); + return c.body(null, 204); + } catch (error) { + logger.error('Failed to delete backtest', error); + return c.json({ error: 'Failed to delete backtest' }, 500); + } + }); + + // Run endpoints + app.get('/api/v2/backtests/:backtestId/runs', async c => { + try { + const runs = await backtestService.listRuns(c.req.param('backtestId')); + return c.json(runs); + } catch (error) { + logger.error('Failed to list runs', error); + return c.json({ error: 'Failed to list runs' }, 500); + } + }); + + app.post('/api/v2/backtests/:backtestId/runs', async c => { + try { + const body = await c.req.json(); + const run = await backtestService.createRun({ + backtestId: c.req.param('backtestId'), + speedMultiplier: body.speedMultiplier, + }); + return c.json(run, 201); + } catch (error) { + logger.error('Failed to create run', error); + return c.json({ error: 'Failed to create run' }, 500); + } + }); + + app.get('/api/v2/runs/:id', async c => { + try { + const run = await backtestService.getRun(c.req.param('id')); + if (!run) { + return c.json({ error: 'Run not found' }, 404); + } + return c.json(run); + } catch (error) { + logger.error('Failed to get run', error); + return c.json({ error: 'Failed to get run' }, 500); + } + }); + + app.get('/api/v2/runs/:id/results', async c => { + try { + const results = await backtestService.getRunResults(c.req.param('id')); + if (!results) { + return c.json({ error: 'Results not found' }, 404); + } + return c.json(results); + } catch (error) { + logger.error('Failed to get run results', error); + return c.json({ error: 'Failed to get run results' }, 500); + } + }); + + app.post('/api/v2/runs/:id/pause', async c => { + try { + await backtestService.pauseRun(c.req.param('id')); + return c.json({ message: 'Run paused' }); + } catch (error) { + logger.error('Failed to pause run', error); + return c.json({ error: 'Failed to pause run' }, 500); + } + }); + + app.post('/api/v2/runs/:id/resume', async c => { + try { + await backtestService.resumeRun(c.req.param('id')); + return c.json({ message: 'Run resumed' }); + } catch (error) { + logger.error('Failed to resume run', error); + return c.json({ error: 'Failed to resume run' }, 500); + } + }); + + app.post('/api/v2/runs/:id/cancel', async c => { + try { + await backtestService.cancelRun(c.req.param('id')); + return c.json({ message: 'Run cancelled' }); + } catch (error) { + logger.error('Failed to cancel run', error); + return c.json({ error: 'Failed to cancel run' }, 500); + } + }); + + app.put('/api/v2/runs/:id/speed', async c => { + try { + const body = await c.req.json(); + await backtestService.updateRunSpeed(c.req.param('id'), body.speedMultiplier); + return c.json({ message: 'Speed updated' }); + } catch (error) { + logger.error('Failed to update run speed', error); + return c.json({ error: 'Failed to update run speed' }, 500); + } + }); + + // Progress update endpoint (called by orchestrator) + app.post('/api/runs/:id/progress', async c => { + try { + const runId = c.req.param('id'); + const body = await c.req.json(); + const { progress, currentDate } = body; + + // Update run progress in database + await backtestService.updateRunStatus(runId, 'running', { + progress, + currentDate, + }); + + // Broadcast via WebSocket if handler is available + const wsHandler = getWebSocketHandler(); + if (wsHandler) { + wsHandler.sendProgressUpdate(runId, progress, currentDate); + } + + return c.json({ message: 'Progress updated' }); + } catch (error) { + logger.error('Failed to update run progress', error); + return c.json({ error: 'Failed to update run progress' }, 500); + } + }); + + // TODO: WebSocket endpoint for real-time run updates + // This needs additional setup with Hono WebSocket support + + return app; +} diff --git a/apps/stock/web-api/src/routes/monitoring.routes.ts b/apps/stock/web-api/src/routes/monitoring.routes.ts index 652bf437..5053675f 100644 --- a/apps/stock/web-api/src/routes/monitoring.routes.ts +++ b/apps/stock/web-api/src/routes/monitoring.routes.ts @@ -183,12 +183,11 @@ export function createMonitoringRoutes(container: IServiceContainer) { ); } - const info = await container.cache.info(); const stats = await monitoringService.getCacheStats(); return c.json({ parsed: stats, - raw: info, + raw: null, // Raw Redis commands are not part of the cache capability. }); } catch (error) { return c.json( @@ -288,12 +287,12 @@ export function createMonitoringRoutes(container: IServiceContainer) { queueName, counts, }); - } catch (error: any) { + } catch (error) { await queue.close(); return c.json( { queueName, - error: error.message, + error: error instanceof Error ? error.message : String(error), }, 500 ); diff --git a/apps/stock/web-api/src/routes/pipeline.routes.ts b/apps/stock/web-api/src/routes/pipeline.routes.ts index 202fb19b..d7e862fb 100644 --- a/apps/stock/web-api/src/routes/pipeline.routes.ts +++ b/apps/stock/web-api/src/routes/pipeline.routes.ts @@ -106,7 +106,7 @@ export function createPipelineRoutes(container: IServiceContainer) { pipeline.get('/stats/exchanges', async c => { try { const result = await pipelineService.getExchangeStats(); - if (result.success) { + if (result.success && result.data) { return c.json(result.data); } else { return c.json({ error: result.error }, 503); @@ -120,7 +120,7 @@ export function createPipelineRoutes(container: IServiceContainer) { pipeline.get('/stats/provider-mappings', async c => { try { const result = await pipelineService.getProviderMappingStats(); - if (result.success) { + if (result.success && result.data) { return c.json(result.data); } else { return c.json({ error: result.error }, 503); diff --git a/apps/stock/web-api/src/routes/websocket.routes.ts b/apps/stock/web-api/src/routes/websocket.routes.ts index 38366d57..65727013 100644 --- a/apps/stock/web-api/src/routes/websocket.routes.ts +++ b/apps/stock/web-api/src/routes/websocket.routes.ts @@ -1,47 +1,53 @@ -import type { IServiceContainer } from '@stock-bot/handlers'; -import { createWebSocketHandler } from '../websocket/run-updates'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('websocket-routes'); - -export function createWebSocketRoute(container: IServiceContainer) { - const wsHandler = createWebSocketHandler(container); - - // Make the handler available globally for other services - (global as any).wsHandler = wsHandler; - - return (request: Request, server: any) => { - const url = new URL(request.url); - const runId = url.searchParams.get('runId'); - - if (!runId) { - return new Response('Missing runId parameter', { status: 400 }); - } - - logger.info(`WebSocket upgrade request for run: ${runId}`); - - // Upgrade the connection to WebSocket - const success = server.upgrade(request, { - data: { runId } - }); - - if (success) { - logger.info(`WebSocket upgrade successful for run: ${runId}`); - // Return undefined to indicate successful upgrade - return; - } else { - logger.error(`WebSocket upgrade failed for run: ${runId}`); - return new Response('WebSocket upgrade failed', { status: 500 }); - } - }; -} - -// WebSocket connection handler for Bun -export function handleWebSocketConnection(ws: any) { - const { runId } = ws.data; - const wsHandler = (global as any).wsHandler; - - if (wsHandler && runId) { - wsHandler.handleConnection(ws, runId); - } -} \ No newline at end of file +import type { Server, ServerWebSocket } from 'bun'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; +import { + createWebSocketHandler, + getWebSocketHandler, + setWebSocketHandler, + type RunSocketData, +} from '../websocket/run-updates'; + +const logger = getLogger('websocket-routes'); + +export function createWebSocketRoute(container: IServiceContainer) { + const wsHandler = createWebSocketHandler(container); + + // Make the handler available globally for other services + setWebSocketHandler(wsHandler); + + return (request: Request, server: Pick) => { + const url = new URL(request.url); + const runId = url.searchParams.get('runId'); + + if (!runId) { + return new Response('Missing runId parameter', { status: 400 }); + } + + logger.info(`WebSocket upgrade request for run: ${runId}`); + + // Upgrade the connection to WebSocket + const success = server.upgrade(request, { + data: { runId }, + }); + + if (success) { + logger.info(`WebSocket upgrade successful for run: ${runId}`); + // Return undefined to indicate successful upgrade + return; + } else { + logger.error(`WebSocket upgrade failed for run: ${runId}`); + return new Response('WebSocket upgrade failed', { status: 500 }); + } + }; +} + +// WebSocket connection handler for Bun +export function handleWebSocketConnection(ws: ServerWebSocket) { + const { runId } = ws.data; + const wsHandler = getWebSocketHandler(); + + if (wsHandler && runId) { + wsHandler.handleConnection(ws, runId); + } +} diff --git a/apps/stock/web-api/src/server-with-websocket.ts b/apps/stock/web-api/src/server-with-websocket.ts index b2be9bbc..b53ffd23 100644 --- a/apps/stock/web-api/src/server-with-websocket.ts +++ b/apps/stock/web-api/src/server-with-websocket.ts @@ -1,131 +1,131 @@ -import { getLogger } from '@stock-bot/logger'; -import { initializeStockConfig } from '@stock-bot/stock-config'; -import { createRoutes } from './routes/create-routes'; -import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes'; -import type { IServiceContainer } from '@stock-bot/handlers'; - -// Initialize configuration with service-specific overrides -const config = initializeStockConfig('webApi'); - -// Override queue settings for web-api (no workers needed) -if (config.queue) { - config.queue.workers = 0; - config.queue.concurrency = 0; - config.queue.enableScheduledJobs = false; -} - -// Log the full configuration -const logger = getLogger('web-api'); -logger.info('Service configuration:', config); - -// Container factory function -async function createContainer(config: any) { - const { ServiceContainerBuilder } = await import('@stock-bot/di'); - - const container = await new ServiceContainerBuilder() - .withConfig(config) - .withOptions({ - enableQuestDB: false, - enableMongoDB: true, - enablePostgres: true, - enableCache: true, - enableQueue: true, - enableBrowser: false, - enableProxy: false, - }) - .build(); - - // Run database migrations - if (container.postgres) { - const { runMigrations } = await import('./migrations/migration-runner'); - await runMigrations(container); - } - - return container; -} - -// Custom server start function with WebSocket support -export async function startServerWithWebSocket() { - let container: IServiceContainer | null = null; - - try { - // Create container - const diContainer = await createContainer(config); - container = diContainer.resolve('serviceContainer'); - - // Create HTTP routes - const routes = createRoutes(container); - - // Create WebSocket route handler - const wsRoute = createWebSocketRoute(container); - - // Start server with WebSocket support - const port = config.service.port || 2003; - - logger.info(`Starting server on port ${port}...`); - - let server; - try { - server = Bun.serve({ - port, - - // Handle HTTP requests - async fetch(req, server) { - const url = new URL(req.url); - - // Check if this is a WebSocket upgrade request - if (url.pathname === '/ws' && req.headers.get('upgrade') === 'websocket') { - return wsRoute(req, server); - } - - // Otherwise handle as normal HTTP request - return routes.fetch(req); - }, - - // WebSocket handlers - websocket: { - open(ws) { - handleWebSocketConnection(ws); - }, - - message(ws, message) { - // Message handling is done in the WebSocket handler - // No need to echo messages back - }, - - close(ws, code, reason) { - logger.info('WebSocket closed', { code, reason }); - }, - - error(ws, error) { - logger.error('WebSocket error', error); - } - }, - - development: config.environment === 'development', - }); - } catch (error) { - if (error instanceof Error && error.message.includes('port')) { - logger.error(`Port ${port} is already in use. Please stop any other servers running on this port.`); - throw new Error(`Port ${port} is already in use`); - } - throw error; - } - - logger.info(`Web API service with WebSocket support started on port ${server.port}`); - logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`); - - // Handle shutdown - process.on('SIGINT', async () => { - logger.info('Shutting down server...'); - server.stop(); - process.exit(0); - }); - - } catch (error) { - logger.fatal('Failed to start web API service', { error }); - process.exit(1); - } -} - -// Export the function - don't start automatically \ No newline at end of file +import type { IServiceContainer } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; +import { initializeStockConfig } from '@stock-bot/stock-config'; +import { createRoutes } from './routes/create-routes'; +import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes'; +import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates'; + +// Initialize configuration with service-specific overrides +const config = initializeStockConfig('webApi'); + +// Override queue settings for web-api (no workers needed) +if (config.queue) { + config.queue.workers = 0; + config.queue.concurrency = 0; + config.queue.enableScheduledJobs = false; +} + +// Log the full configuration +const logger = getLogger('web-api'); +logger.info('Service configuration:', config); + +// Container factory function +async function createContainer(config: import('@stock-bot/config').UnifiedAppConfig) { + const { ServiceContainerBuilder } = await import('@stock-bot/di'); + + const container = await new ServiceContainerBuilder() + .withConfig(config) + .withOptions({ + enableQuestDB: false, + enableMongoDB: true, + enablePostgres: true, + enableCache: true, + enableQueue: true, + enableBrowser: false, + enableProxy: false, + }) + .build(); + + // Run database migrations + const services = container.resolve('serviceContainer'); + if (services.postgres) { + const { runMigrations } = await import('./migrations/migration-runner'); + await runMigrations(services); + } + + return container; +} + +// Custom server start function with WebSocket support +export async function startServerWithWebSocket() { + let container: IServiceContainer | null = null; + + try { + // Create container + const diContainer = await createContainer(config); + container = diContainer.resolve('serviceContainer'); + + // Create HTTP routes + const routes = createRoutes(container); + + // Create WebSocket route handler + const wsRoute = createWebSocketRoute(container); + + // Start server with WebSocket support + const port = config.service.port || 2003; + + logger.info(`Starting server on port ${port}...`); + + let server; + try { + server = Bun.serve({ + port, + + // Handle HTTP requests + async fetch(req, server) { + const url = new URL(req.url); + + // Check if this is a WebSocket upgrade request + if (url.pathname === '/ws' && req.headers.get('upgrade') === 'websocket') { + return wsRoute(req, server); + } + + // Otherwise handle as normal HTTP request + return routes.fetch(req); + }, + + // WebSocket handlers + websocket: { + open(ws) { + handleWebSocketConnection(ws); + }, + + message(ws, message) { + getWebSocketHandler()?.handleMessage(ws, message); + }, + + close(ws, code, reason) { + getWebSocketHandler()?.handleClose(ws); + logger.info('WebSocket closed', { code, reason }); + }, + }, + + development: config.environment === 'development', + }); + } catch (error) { + if (error instanceof Error && error.message.includes('port')) { + logger.error( + `Port ${port} is already in use. Please stop any other servers running on this port.` + ); + throw new Error(`Port ${port} is already in use`); + } + throw error; + } + + logger.info(`Web API service with WebSocket support started on port ${server.port}`); + logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`); + + // Handle shutdown + process.on('SIGINT', async () => { + logger.info('Shutting down server...'); + getWebSocketHandler()?.cleanup(); + await server.stop(true); + process.exit(0); + }); + } catch (error) { + logger.fatal('Failed to start web API service', { error }); + process.exit(1); + } +} + +// Export the function - don't start automatically diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index a5bd60fc..2ef8db7c 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -1,569 +1,571 @@ -import { v4 as uuidv4 } from 'uuid'; -import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import type { WebSocketHandler } from '../websocket/run-updates'; - -const logger = getLogger('backtest-v2-service'); - -// Use environment variable or default -const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; - -export interface BacktestRequest { - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config?: Record; -} - -export interface Backtest { - id: string; - name: string; - strategy: string; - symbols: string[]; - startDate: Date; - endDate: Date; - initialCapital: number; - config: Record; - createdAt: Date; - updatedAt: Date; -} - -export interface Run { - id: string; - backtestId: string; - runNumber: number; - status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; - speedMultiplier: number; - error?: string; - startedAt?: Date; - completedAt?: Date; - pausedAt?: Date; - progress: number; - currentDate?: Date; - createdAt: Date; - updatedAt: Date; -} - -export interface RunRequest { - backtestId: string; - speedMultiplier?: number | null; -} - -export class BacktestServiceV2 { - private container: IServiceContainer; - private activeRuns: Map = new Map(); // Track active WebSocket connections - private wsHandler: WebSocketHandler | null = null; - - constructor(container: IServiceContainer) { - this.container = container; - logger.info('BacktestServiceV2 initialized'); - } - - // Backtest CRUD operations - async createBacktest(request: BacktestRequest): Promise { - const backtestId = uuidv4(); - - const result = await this.container.postgres.query( - `INSERT INTO backtests - (id, name, strategy, symbols, start_date, end_date, initial_capital, config) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - RETURNING *`, - [ - backtestId, - request.name, - request.strategy, - JSON.stringify(request.symbols), - request.startDate, - request.endDate, - request.initialCapital, - JSON.stringify(request.config || {}) - ] - ); - - const backtest = this.mapBacktest(result.rows[0]); - - // Automatically create and start a run for the new backtest - try { - await this.createRun({ - backtestId: backtest.id, - speedMultiplier: null // Max speed (instant) - }); - } catch (error) { - logger.error('Failed to auto-create run for new backtest', { backtestId: backtest.id, error }); - // Don't fail the backtest creation if run creation fails - } - - return backtest; - } - - async getBacktest(id: string): Promise { - const result = await this.container.postgres.query( - 'SELECT * FROM backtests WHERE id = $1', - [id] - ); - - if (result.rows.length === 0) { - return null; - } - - return this.mapBacktest(result.rows[0]); - } - - async updateBacktest(id: string, request: Partial): Promise { - const updates: string[] = []; - const values: any[] = []; - let paramCount = 1; - - if (request.name !== undefined) { - updates.push(`name = $${paramCount++}`); - values.push(request.name); - } - if (request.strategy !== undefined) { - updates.push(`strategy = $${paramCount++}`); - values.push(request.strategy); - } - if (request.symbols !== undefined) { - updates.push(`symbols = $${paramCount++}`); - values.push(JSON.stringify(request.symbols)); - } - if (request.startDate !== undefined) { - updates.push(`start_date = $${paramCount++}`); - values.push(request.startDate); - } - if (request.endDate !== undefined) { - updates.push(`end_date = $${paramCount++}`); - values.push(request.endDate); - } - if (request.initialCapital !== undefined) { - updates.push(`initial_capital = $${paramCount++}`); - values.push(request.initialCapital); - } - if (request.config !== undefined) { - updates.push(`config = $${paramCount++}`); - values.push(JSON.stringify(request.config)); - } - - if (updates.length === 0) { - return this.getBacktest(id); - } - - values.push(id); - const result = await this.container.postgres.query( - `UPDATE backtests - SET ${updates.join(', ')}, updated_at = NOW() - WHERE id = $${paramCount} - RETURNING *`, - values - ); - - if (result.rows.length === 0) { - return null; - } - - return this.mapBacktest(result.rows[0]); - } - - async listBacktests(params: { limit: number; offset: number }): Promise { - const result = await this.container.postgres.query( - `SELECT * FROM backtests - ORDER BY created_at DESC - LIMIT $1 OFFSET $2`, - [params.limit, params.offset] - ); - - return result.rows.map(row => this.mapBacktest(row)); - } - - async deleteBacktest(id: string): Promise { - await this.container.postgres.query( - 'DELETE FROM backtests WHERE id = $1', - [id] - ); - } - - // Run operations - async createRun(request: RunRequest): Promise { - const runId = uuidv4(); - - // Get the next run number for this backtest - const runNumberResult = await this.container.postgres.query( - 'SELECT COALESCE(MAX(run_number), 0) + 1 as next_run_number FROM runs WHERE backtest_id = $1', - [request.backtestId] - ); - const runNumber = runNumberResult.rows[0].next_run_number; - - const result = await this.container.postgres.query( - `INSERT INTO runs - (id, backtest_id, run_number, speed_multiplier, status) - VALUES ($1, $2, $3, $4, 'pending') - RETURNING *`, - [ - runId, - request.backtestId, - runNumber, - request.speedMultiplier ?? 1.0 - ] - ); - - const run = this.mapRun(result.rows[0]); - - // Start the run immediately - this.startRun(run); - - return run; - } - - async getRun(id: string): Promise { - const result = await this.container.postgres.query( - 'SELECT * FROM runs WHERE id = $1', - [id] - ); - - if (result.rows.length === 0) { - return null; - } - - return this.mapRun(result.rows[0]); - } - - async listRuns(backtestId: string): Promise { - const result = await this.container.postgres.query( - `SELECT * FROM runs - WHERE backtest_id = $1 - ORDER BY run_number DESC`, - [backtestId] - ); - - return result.rows.map(row => this.mapRun(row)); - } - - async updateRunStatus( - id: string, - status: Run['status'], - updates?: { - error?: string; - progress?: number; - currentDate?: Date; - speedMultiplier?: number; - } - ): Promise { - const setClauses = ['status = $2', 'updated_at = NOW()']; - const values: any[] = [id, status]; - let paramCount = 3; - - if (status === 'running' && !updates?.currentDate) { - setClauses.push(`started_at = NOW()`); - } - if (status === 'completed' || status === 'failed' || status === 'cancelled') { - setClauses.push(`completed_at = NOW()`); - } - if (status === 'paused') { - setClauses.push(`paused_at = NOW()`); - } - - if (updates?.error !== undefined) { - setClauses.push(`error = $${paramCount++}`); - values.push(updates.error); - } - if (updates?.progress !== undefined) { - setClauses.push(`progress = $${paramCount++}`); - values.push(updates.progress); - } - if (updates?.currentDate !== undefined) { - setClauses.push(`current_simulation_date = $${paramCount++}`); - values.push(updates.currentDate); - } - if (updates?.speedMultiplier !== undefined) { - setClauses.push(`speed_multiplier = $${paramCount++}`); - values.push(updates.speedMultiplier); - } - - await this.container.postgres.query( - `UPDATE runs SET ${setClauses.join(', ')} WHERE id = $1`, - values - ); - - // Send WebSocket update if handler is available - if (this.getWebSocketHandler()) { - this.getWebSocketHandler().broadcastRunUpdate(id, { - type: 'run_update', - runId: id, - data: { - status, - ...updates, - timestamp: new Date().toISOString() - } - }); - } - } - - async pauseRun(id: string): Promise { - await this.updateRunStatus(id, 'paused'); - - // Send pause command to orchestrator - try { - const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/pause`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' } - }); - - if (!response.ok) { - logger.warn('Failed to pause backtest in orchestrator'); - } - } catch (error) { - logger.error('Error pausing backtest in orchestrator', error); - } - } - - async resumeRun(id: string): Promise { - const run = await this.getRun(id); - if (!run || run.status !== 'paused') { - throw new Error('Run is not paused'); - } - - await this.updateRunStatus(id, 'running'); - - // Send resume command to orchestrator - try { - const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/resume`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' } - }); - - if (!response.ok) { - logger.warn('Failed to resume backtest in orchestrator'); - } - } catch (error) { - logger.error('Error resuming backtest in orchestrator', error); - } - } - - async cancelRun(id: string): Promise { - await this.updateRunStatus(id, 'cancelled'); - // TODO: Send cancel command to orchestrator - } - - async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { - await this.updateRunStatus(id, 'running', { speedMultiplier }); - - // Send speed update to orchestrator - try { - const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/speed`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ speed: speedMultiplier }) - }); - - if (!response.ok) { - logger.warn('Failed to update backtest speed in orchestrator'); - } - } catch (error) { - logger.error('Error updating backtest speed in orchestrator', error); - } - } - - // Get run results - async getRunResults(runId: string): Promise { - const result = await this.container.postgres.query( - `SELECT - br.*, - r.backtest_id, - b.strategy, - b.symbols, - b.start_date, - b.end_date, - b.initial_capital, - b.config as backtest_config - FROM backtest_results br - JOIN runs r ON r.id = br.run_id - JOIN backtests b ON b.id = r.backtest_id - WHERE br.run_id = $1`, - [runId] - ); - - if (result.rows.length === 0) { - return null; - } - - const row = result.rows[0]; - - return { - runId: row.run_id, - backtestId: row.backtest_id, - status: 'completed', - completedAt: row.completed_at.toISOString(), - config: { - name: row.backtest_config?.name || 'Backtest', - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date.toISOString(), - endDate: row.end_date.toISOString(), - initialCapital: parseFloat(row.initial_capital), - commission: row.backtest_config?.commission ?? 0.001, - slippage: row.backtest_config?.slippage ?? 0.0001, - dataFrequency: row.backtest_config?.dataFrequency || '1d', - }, - metrics: row.metrics, - equity: row.equity_curve, - ohlcData: row.ohlc_data, - trades: row.trades, - positions: row.positions, - analytics: row.analytics, - executionTime: row.execution_time, - }; - } - - // Private methods - private async startRun(run: Run): Promise { - const backtest = await this.getBacktest(run.backtestId); - if (!backtest) { - throw new Error('Backtest not found'); - } - - await this.updateRunStatus(run.id, 'running', { progress: 0 }); - - // Send initial WebSocket update - if (this.getWebSocketHandler()) { - this.getWebSocketHandler().sendProgressUpdate(run.id, 0); - } - - try { - // Call orchestrator to run backtest - const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - runId: run.id, - mode: 'backtest', - startDate: new Date(backtest.startDate).toISOString(), - endDate: new Date(backtest.endDate).toISOString(), - symbols: backtest.symbols, - strategy: backtest.strategy, - initialCapital: backtest.initialCapital, - dataFrequency: backtest.config?.dataFrequency || '1d', - commission: backtest.config?.commission ?? 0.001, - slippage: backtest.config?.slippage ?? 0.0001, - speed: run.speedMultiplier === null ? 'max' : - run.speedMultiplier >= 10 ? '10x' : - run.speedMultiplier >= 5 ? '5x' : - run.speedMultiplier >= 2 ? '2x' : 'realtime', - fillModel: { - slippage: 'realistic', - marketImpact: true, - partialFills: true - } - }), - }); - - if (!response.ok) { - const errorText = await response.text(); - logger.error('Orchestrator request failed', { - status: response.status, - statusText: response.statusText, - error: errorText, - request: { - runId: run.id, - strategy: backtest.strategy, - symbols: backtest.symbols, - startDate: new Date(backtest.startDate).toISOString(), - endDate: new Date(backtest.endDate).toISOString(), - } - }); - throw new Error(`Orchestrator returned ${response.status}: ${errorText}`); - } - - const result = await response.json(); - - if (result.status === 'completed') { - await this.updateRunStatus(run.id, 'completed', { progress: 100 }); - await this.saveRunResults(run.id, result); - - // Send completion via WebSocket - if (this.getWebSocketHandler()) { - this.getWebSocketHandler().sendCompletion(run.id, result); - } - } - } catch (error) { - logger.error('Failed to start run', { runId: run.id, error }); - const errorMessage = error instanceof Error ? error.message : 'Unknown error'; - await this.updateRunStatus(run.id, 'failed', { - error: errorMessage - }); - - // Send error via WebSocket - if (this.getWebSocketHandler()) { - this.getWebSocketHandler().sendError(run.id, errorMessage); - } - } - } - - private async saveRunResults(runId: string, result: any): Promise { - try { - await this.container.postgres.query( - `INSERT INTO backtest_results - (run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [ - runId, - result.completedAt || new Date(), - JSON.stringify(result.metrics || {}), - JSON.stringify(result.equity || result.equityCurve || []), - JSON.stringify(result.ohlcData || {}), - JSON.stringify(result.trades || []), - JSON.stringify(result.positions || result.finalPositions || {}), - JSON.stringify(result.analytics || {}), - result.executionTime || 0 - ] - ); - } catch (error) { - logger.error('Failed to save run results', { runId, error }); - throw error; - } - } - - private mapBacktest(row: any): Backtest { - return { - id: row.id, - name: row.name, - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date, - endDate: row.end_date, - initialCapital: parseFloat(row.initial_capital), - config: row.config, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } - - private getWebSocketHandler(): WebSocketHandler | null { - // Try to get from global if not already set - if (!this.wsHandler && (global as any).wsHandler) { - this.wsHandler = (global as any).wsHandler; - } - return this.wsHandler; - } - - private mapRun(row: any): Run { - return { - id: row.id, - backtestId: row.backtest_id, - runNumber: row.run_number, - status: row.status, - speedMultiplier: parseFloat(row.speed_multiplier), - error: row.error, - startedAt: row.started_at, - completedAt: row.completed_at, - pausedAt: row.paused_at, - progress: parseFloat(row.progress), - currentDate: row.current_simulation_date, - createdAt: row.created_at, - updatedAt: row.updated_at, - }; - } -} \ No newline at end of file +import { randomUUID as uuidv4 } from 'node:crypto'; +import type { QueryResultRow } from 'pg'; +import { at } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { getWebSocketHandler } from '../websocket/run-updates'; +import type { WebSocketHandler } from '../websocket/run-updates'; + +const logger = getLogger('backtest-v2-service'); + +// Use environment variable or default +const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; + +export interface BacktestRequest { + name: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config?: Record; +} + +export interface Backtest { + id: string; + name: string; + strategy: string; + symbols: string[]; + startDate: Date; + endDate: Date; + initialCapital: number; + config: Record; + createdAt: Date; + updatedAt: Date; +} + +export interface Run { + id: string; + backtestId: string; + runNumber: number; + status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; + speedMultiplier: number; + error?: string; + startedAt?: Date; + completedAt?: Date; + pausedAt?: Date; + progress: number; + currentDate?: Date; + createdAt: Date; + updatedAt: Date; +} + +export interface RunRequest { + backtestId: string; + speedMultiplier?: number | null; +} + +export class BacktestServiceV2 { + private container: IServiceContainer & { postgres: NonNullable }; + private wsHandler: WebSocketHandler | null = null; + + constructor(container: IServiceContainer) { + this.container = requireServices(container, 'postgres'); + logger.info('BacktestServiceV2 initialized'); + } + + // Backtest CRUD operations + async createBacktest(request: BacktestRequest): Promise { + const backtestId = uuidv4(); + + const result = await this.container.postgres.query( + `INSERT INTO backtests + (id, name, strategy, symbols, start_date, end_date, initial_capital, config) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + RETURNING *`, + [ + backtestId, + request.name, + request.strategy, + JSON.stringify(request.symbols), + request.startDate, + request.endDate, + request.initialCapital, + JSON.stringify(request.config || {}), + ] + ); + + const backtest = this.mapBacktest(at(result.rows, 0)); + + // Automatically create and start a run for the new backtest + try { + await this.createRun({ + backtestId: backtest.id, + speedMultiplier: null, // Max speed (instant) + }); + } catch (error) { + logger.error('Failed to auto-create run for new backtest', { + backtestId: backtest.id, + error, + }); + // Don't fail the backtest creation if run creation fails + } + + return backtest; + } + + async getBacktest(id: string): Promise { + const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [ + id, + ]); + + if (result.rows.length === 0) { + return null; + } + + return this.mapBacktest(at(result.rows, 0)); + } + + async updateBacktest(id: string, request: Partial): Promise { + const updates: string[] = []; + const values: unknown[] = []; + let paramCount = 1; + + if (request.name !== undefined) { + updates.push(`name = $${paramCount++}`); + values.push(request.name); + } + if (request.strategy !== undefined) { + updates.push(`strategy = $${paramCount++}`); + values.push(request.strategy); + } + if (request.symbols !== undefined) { + updates.push(`symbols = $${paramCount++}`); + values.push(JSON.stringify(request.symbols)); + } + if (request.startDate !== undefined) { + updates.push(`start_date = $${paramCount++}`); + values.push(request.startDate); + } + if (request.endDate !== undefined) { + updates.push(`end_date = $${paramCount++}`); + values.push(request.endDate); + } + if (request.initialCapital !== undefined) { + updates.push(`initial_capital = $${paramCount++}`); + values.push(request.initialCapital); + } + if (request.config !== undefined) { + updates.push(`config = $${paramCount++}`); + values.push(JSON.stringify(request.config)); + } + + if (updates.length === 0) { + return this.getBacktest(id); + } + + values.push(id); + const result = await this.container.postgres.query( + `UPDATE backtests + SET ${updates.join(', ')}, updated_at = NOW() + WHERE id = $${paramCount} + RETURNING *`, + values + ); + + if (result.rows.length === 0) { + return null; + } + + return this.mapBacktest(at(result.rows, 0)); + } + + async listBacktests(params: { limit: number; offset: number }): Promise { + const result = await this.container.postgres.query( + `SELECT * FROM backtests + ORDER BY created_at DESC + LIMIT $1 OFFSET $2`, + [params.limit, params.offset] + ); + + return result.rows.map(row => this.mapBacktest(row)); + } + + async deleteBacktest(id: string): Promise { + await this.container.postgres.query('DELETE FROM backtests WHERE id = $1', [id]); + } + + // Run operations + async createRun(request: RunRequest): Promise { + const runId = uuidv4(); + + // Get the next run number for this backtest + const runNumberResult = await this.container.postgres.query( + 'SELECT COALESCE(MAX(run_number), 0) + 1 as next_run_number FROM runs WHERE backtest_id = $1', + [request.backtestId] + ); + const runNumber = at(runNumberResult.rows, 0).next_run_number; + + const result = await this.container.postgres.query( + `INSERT INTO runs + (id, backtest_id, run_number, speed_multiplier, status) + VALUES ($1, $2, $3, $4, 'pending') + RETURNING *`, + [runId, request.backtestId, runNumber, request.speedMultiplier ?? 1.0] + ); + + const run = this.mapRun(at(result.rows, 0)); + + // Start the run immediately + this.startRun(run); + + return run; + } + + async getRun(id: string): Promise { + const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]); + + if (result.rows.length === 0) { + return null; + } + + return this.mapRun(at(result.rows, 0)); + } + + async listRuns(backtestId: string): Promise { + const result = await this.container.postgres.query( + `SELECT * FROM runs + WHERE backtest_id = $1 + ORDER BY run_number DESC`, + [backtestId] + ); + + return result.rows.map(row => this.mapRun(row)); + } + + async updateRunStatus( + id: string, + status: Run['status'], + updates?: { + error?: string; + progress?: number; + currentDate?: Date; + speedMultiplier?: number | null; + } + ): Promise { + const setClauses = ['status = $2', 'updated_at = NOW()']; + const values: unknown[] = [id, status]; + let paramCount = 3; + + if (status === 'running' && !updates?.currentDate) { + setClauses.push(`started_at = NOW()`); + } + if (status === 'completed' || status === 'failed' || status === 'cancelled') { + setClauses.push(`completed_at = NOW()`); + } + if (status === 'paused') { + setClauses.push(`paused_at = NOW()`); + } + + if (updates?.error !== undefined) { + setClauses.push(`error = $${paramCount++}`); + values.push(updates.error); + } + if (updates?.progress !== undefined) { + setClauses.push(`progress = $${paramCount++}`); + values.push(updates.progress); + } + if (updates?.currentDate !== undefined) { + setClauses.push(`current_simulation_date = $${paramCount++}`); + values.push(updates.currentDate); + } + if (updates?.speedMultiplier !== undefined) { + setClauses.push(`speed_multiplier = $${paramCount++}`); + values.push(updates.speedMultiplier); + } + + await this.container.postgres.query( + `UPDATE runs SET ${setClauses.join(', ')} WHERE id = $1`, + values + ); + + // Send WebSocket update if handler is available + if (this.getWebSocketHandler()) { + this.getWebSocketHandler()?.broadcastRunUpdate(id, { + type: 'run_update', + runId: id, + data: { + status, + ...updates, + timestamp: new Date().toISOString(), + }, + }); + } + } + + async pauseRun(id: string): Promise { + await this.updateRunStatus(id, 'paused'); + + // Send pause command to orchestrator + try { + const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/pause`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + logger.warn('Failed to pause backtest in orchestrator'); + } + } catch (error) { + logger.error('Error pausing backtest in orchestrator', error); + } + } + + async resumeRun(id: string): Promise { + const run = await this.getRun(id); + if (!run || run.status !== 'paused') { + throw new Error('Run is not paused'); + } + + await this.updateRunStatus(id, 'running'); + + // Send resume command to orchestrator + try { + const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/resume`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + logger.warn('Failed to resume backtest in orchestrator'); + } + } catch (error) { + logger.error('Error resuming backtest in orchestrator', error); + } + } + + async cancelRun(id: string): Promise { + await this.updateRunStatus(id, 'cancelled'); + // TODO: Send cancel command to orchestrator + } + + async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { + await this.updateRunStatus(id, 'running', { speedMultiplier }); + + // Send speed update to orchestrator + try { + const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/speed`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ speed: speedMultiplier }), + }); + + if (!response.ok) { + logger.warn('Failed to update backtest speed in orchestrator'); + } + } catch (error) { + logger.error('Error updating backtest speed in orchestrator', error); + } + } + + // Get run results + async getRunResults(runId: string) { + const result = await this.container.postgres.query( + `SELECT + br.*, + r.backtest_id, + b.strategy, + b.symbols, + b.start_date, + b.end_date, + b.initial_capital, + b.config as backtest_config + FROM backtest_results br + JOIN runs r ON r.id = br.run_id + JOIN backtests b ON b.id = r.backtest_id + WHERE br.run_id = $1`, + [runId] + ); + + if (result.rows.length === 0) { + return null; + } + + const row = at(result.rows, 0); + + return { + runId: row.run_id, + backtestId: row.backtest_id, + status: 'completed', + completedAt: row.completed_at.toISOString(), + config: { + name: row.backtest_config?.name || 'Backtest', + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date.toISOString(), + endDate: row.end_date.toISOString(), + initialCapital: parseFloat(row.initial_capital), + commission: row.backtest_config?.commission ?? 0.001, + slippage: row.backtest_config?.slippage ?? 0.0001, + dataFrequency: row.backtest_config?.dataFrequency || '1d', + }, + metrics: row.metrics, + equity: row.equity_curve, + ohlcData: row.ohlc_data, + trades: row.trades, + positions: row.positions, + analytics: row.analytics, + executionTime: row.execution_time, + }; + } + + // Private methods + private async startRun(run: Run): Promise { + const backtest = await this.getBacktest(run.backtestId); + if (!backtest) { + throw new Error('Backtest not found'); + } + + await this.updateRunStatus(run.id, 'running', { progress: 0 }); + + // Send initial WebSocket update + if (this.getWebSocketHandler()) { + this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0); + } + + try { + // Call orchestrator to run backtest + const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + runId: run.id, + mode: 'backtest', + startDate: new Date(backtest.startDate).toISOString(), + endDate: new Date(backtest.endDate).toISOString(), + symbols: backtest.symbols, + strategy: backtest.strategy, + initialCapital: backtest.initialCapital, + dataFrequency: backtest.config?.dataFrequency || '1d', + commission: backtest.config?.commission ?? 0.001, + slippage: backtest.config?.slippage ?? 0.0001, + speed: + run.speedMultiplier === null + ? 'max' + : run.speedMultiplier >= 10 + ? '10x' + : run.speedMultiplier >= 5 + ? '5x' + : run.speedMultiplier >= 2 + ? '2x' + : 'realtime', + fillModel: { + slippage: 'realistic', + marketImpact: true, + partialFills: true, + }, + }), + }); + + if (!response.ok) { + const errorText = await response.text(); + logger.error('Orchestrator request failed', { + status: response.status, + statusText: response.statusText, + error: errorText, + request: { + runId: run.id, + strategy: backtest.strategy, + symbols: backtest.symbols, + startDate: new Date(backtest.startDate).toISOString(), + endDate: new Date(backtest.endDate).toISOString(), + }, + }); + throw new Error(`Orchestrator returned ${response.status}: ${errorText}`); + } + + const result = await response.json(); + + if (result.status === 'completed') { + await this.updateRunStatus(run.id, 'completed', { progress: 100 }); + await this.saveRunResults(run.id, result); + + // Send completion via WebSocket + if (this.getWebSocketHandler()) { + this.getWebSocketHandler()?.sendCompletion(run.id, result); + } + } + } catch (error) { + logger.error('Failed to start run', { runId: run.id, error }); + const errorMessage = + error instanceof Error + ? error instanceof Error + ? error.message + : String(error) + : 'Unknown error'; + await this.updateRunStatus(run.id, 'failed', { + error: errorMessage, + }); + + // Send error via WebSocket + if (this.getWebSocketHandler()) { + this.getWebSocketHandler()?.sendError(run.id, errorMessage); + } + } + } + + private async saveRunResults(runId: string, result: Record): Promise { + try { + await this.container.postgres.query( + `INSERT INTO backtest_results + (run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + runId, + result.completedAt || new Date(), + JSON.stringify(result.metrics || {}), + JSON.stringify(result.equity || result.equityCurve || []), + JSON.stringify(result.ohlcData || {}), + JSON.stringify(result.trades || []), + JSON.stringify(result.positions || result.finalPositions || {}), + JSON.stringify(result.analytics || {}), + result.executionTime || 0, + ] + ); + } catch (error) { + logger.error('Failed to save run results', { runId, error }); + throw error; + } + } + + private mapBacktest(row: QueryResultRow): Backtest { + return { + id: row.id, + name: row.name, + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date, + endDate: row.end_date, + initialCapital: parseFloat(row.initial_capital), + config: row.config, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; + } + + private getWebSocketHandler(): WebSocketHandler | null { + // Try to get from global if not already set + this.wsHandler ??= getWebSocketHandler(); + return this.wsHandler; + } + + private mapRun(row: QueryResultRow): Run { + return { + id: row.id, + backtestId: row.backtest_id, + runNumber: row.run_number, + status: row.status, + speedMultiplier: parseFloat(row.speed_multiplier), + error: row.error, + startedAt: row.started_at, + completedAt: row.completed_at, + pausedAt: row.paused_at, + progress: parseFloat(row.progress), + currentDate: row.current_simulation_date, + createdAt: row.created_at, + updatedAt: row.updated_at, + }; + } +} diff --git a/apps/stock/web-api/src/services/backtest.service.ts b/apps/stock/web-api/src/services/backtest.service.ts index 3f90b889..df7448ac 100644 --- a/apps/stock/web-api/src/services/backtest.service.ts +++ b/apps/stock/web-api/src/services/backtest.service.ts @@ -1,294 +1,301 @@ -import { v4 as uuidv4 } from 'uuid'; -import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/handlers'; - -const logger = getLogger('backtest-service'); - -// Use environment variable or default -const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; - -export interface BacktestRequest { - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config?: Record; -} - -export interface BacktestJob { - id: string; - status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; - strategy: string; - symbols: string[]; - startDate: Date; - endDate: Date; - initialCapital: number; - config: Record; - createdAt: Date; - updatedAt: Date; - error?: string; -} - -export class BacktestService { - private container: IServiceContainer; - - constructor(container: IServiceContainer) { - this.container = container; - logger.info('BacktestService initialized', { - hasPostgres: !!container.postgres, - containerKeys: Object.keys(container) - }); - } - async createBacktest(request: BacktestRequest): Promise { - const backtestId = uuidv4(); - - // Insert into PostgreSQL - const result = await this.container.postgres.query( - `INSERT INTO backtests - (id, name, strategy, symbols, start_date, end_date, initial_capital, config, status) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending') - RETURNING *`, - [ - backtestId, - request.config?.name || `Backtest ${new Date().toISOString()}`, - request.strategy, - JSON.stringify(request.symbols), - request.startDate, - request.endDate, - request.initialCapital, - JSON.stringify(request.config || {}) - ] - ); - - const backtest: BacktestJob = { - id: result.rows[0].id, - status: result.rows[0].status, - strategy: result.rows[0].strategy, - symbols: result.rows[0].symbols, - startDate: result.rows[0].start_date, - endDate: result.rows[0].end_date, - initialCapital: parseFloat(result.rows[0].initial_capital), - config: result.rows[0].config, - createdAt: result.rows[0].created_at, - updatedAt: result.rows[0].updated_at, - }; - - // Call orchestrator to run backtest - try { - const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - mode: 'backtest', - startDate: new Date(request.startDate).toISOString(), - endDate: new Date(request.endDate).toISOString(), - symbols: request.symbols, - strategy: request.strategy, - initialCapital: request.initialCapital, - dataFrequency: '1d', // Default to daily - commission: request.config?.commission, - slippage: request.config?.slippage, - speed: 'max', // Default speed - fillModel: { - slippage: 'realistic', - marketImpact: true, - partialFills: true - } - }), - }); - - if (!response.ok) { - throw new Error(`Orchestrator returned ${response.status}`); - } - - const result = await response.json(); - - // Store result directly without transformation - if (result.status === 'completed') { - // Update backtest status - await this.container.postgres.query( - 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', - ['completed', backtestId] - ); - - // Store results in backtest_results table - await this.saveBacktestResults(backtestId, result); - - logger.info('Backtest completed', { - backtestId, - trades: result.metrics?.totalTrades, - return: result.metrics?.totalReturn - }); - } else { - // Update status to running if not completed - await this.container.postgres.query( - 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', - ['running', backtestId] - ); - } - - logger.info('Backtest started in orchestrator', { backtestId, result }); - } catch (error) { - logger.error('Failed to start backtest in orchestrator', { backtestId, error }); - await this.container.postgres.query( - 'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3', - ['failed', error.message, backtestId] - ); - backtest.status = 'failed'; - backtest.error = error.message; - } - - return backtest; - } - - async getBacktest(id: string): Promise { - const result = await this.container.postgres.query( - 'SELECT * FROM backtests WHERE id = $1', - [id] - ); - - if (result.rows.length === 0) { - return null; - } - - const row = result.rows[0]; - return { - id: row.id, - status: row.status, - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date, - endDate: row.end_date, - initialCapital: parseFloat(row.initial_capital), - config: row.config, - createdAt: row.created_at, - updatedAt: row.updated_at, - error: row.error, - }; - } - - async getBacktestResults(id: string): Promise { - const result = await this.container.postgres.query( - `SELECT - br.*, - b.strategy, - b.symbols, - b.start_date, - b.end_date, - b.initial_capital, - b.config as backtest_config - FROM backtest_results br - JOIN backtests b ON b.id = br.backtest_id - WHERE br.backtest_id = $1`, - [id] - ); - - if (result.rows.length === 0) { - return null; - } - - const row = result.rows[0]; - - // Reconstruct the result format expected by frontend - return { - backtestId: row.backtest_id, - status: 'completed', - completedAt: row.completed_at.toISOString(), - config: { - name: row.backtest_config?.name || 'Backtest', - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date.toISOString(), - endDate: row.end_date.toISOString(), - initialCapital: parseFloat(row.initial_capital), - commission: row.backtest_config?.commission ?? 0.001, - slippage: row.backtest_config?.slippage ?? 0.0001, - dataFrequency: row.backtest_config?.dataFrequency || '1d', - }, - metrics: row.metrics, - equity: row.equity_curve, - ohlcData: row.ohlc_data, - trades: row.trades, - positions: row.positions, - analytics: row.analytics, - executionTime: row.execution_time, - }; - } - - async listBacktests(params: { limit: number; offset: number }): Promise { - const result = await this.container.postgres.query( - `SELECT * FROM backtests - ORDER BY created_at DESC - LIMIT $1 OFFSET $2`, - [params.limit, params.offset] - ); - - return result.rows.map(row => ({ - id: row.id, - status: row.status, - strategy: row.strategy, - symbols: row.symbols, - startDate: row.start_date, - endDate: row.end_date, - initialCapital: parseFloat(row.initial_capital), - config: row.config, - createdAt: row.created_at, - updatedAt: row.updated_at, - error: row.error, - })); - } - - async updateBacktestStatus(id: string, status: BacktestJob['status'], error?: string): Promise { - if (error) { - await this.container.postgres.query( - 'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3', - [status, error, id] - ); - } else { - await this.container.postgres.query( - 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', - [status, id] - ); - } - } - - async cancelBacktest(id: string): Promise { - await this.updateBacktestStatus(id, 'cancelled'); - - // Call orchestrator to stop backtest - try { - await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, { - method: 'POST', - }); - } catch (error) { - logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error }); - } - } - - private async saveBacktestResults(backtestId: string, result: any): Promise { - try { - await this.container.postgres.query( - `INSERT INTO backtest_results - (backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, - [ - backtestId, - result.completedAt || new Date(), - JSON.stringify(result.metrics || {}), - JSON.stringify(result.equity || result.equityCurve || []), - JSON.stringify(result.ohlcData || {}), - JSON.stringify(result.trades || []), - JSON.stringify(result.positions || result.finalPositions || {}), - JSON.stringify(result.analytics || {}), - result.executionTime || 0 - ] - ); - } catch (error) { - logger.error('Failed to save backtest results', { backtestId, error }); - throw error; - } - } -} \ No newline at end of file +import { randomUUID as uuidv4 } from 'node:crypto'; +import { at } from '@stock-bot/invariants'; +import { getLogger } from '@stock-bot/logger'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; + +const logger = getLogger('backtest-service'); + +// Use environment variable or default +const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; + +export interface BacktestRequest { + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config?: Record; +} + +export interface BacktestJob { + id: string; + status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; + strategy: string; + symbols: string[]; + startDate: Date; + endDate: Date; + initialCapital: number; + config: Record; + createdAt: Date; + updatedAt: Date; + error?: string; +} + +export class BacktestService { + private container: IServiceContainer & { postgres: NonNullable }; + + constructor(container: IServiceContainer) { + this.container = requireServices(container, 'postgres'); + logger.info('BacktestService initialized', { + hasPostgres: !!container.postgres, + containerKeys: Object.keys(container), + }); + } + async createBacktest(request: BacktestRequest): Promise { + const backtestId = uuidv4(); + + // Insert into PostgreSQL + const result = await this.container.postgres.query( + `INSERT INTO backtests + (id, name, strategy, symbols, start_date, end_date, initial_capital, config, status) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending') + RETURNING *`, + [ + backtestId, + request.config?.name || `Backtest ${new Date().toISOString()}`, + request.strategy, + JSON.stringify(request.symbols), + request.startDate, + request.endDate, + request.initialCapital, + JSON.stringify(request.config || {}), + ] + ); + + const backtest: BacktestJob = { + id: at(result.rows, 0).id, + status: at(result.rows, 0).status, + strategy: at(result.rows, 0).strategy, + symbols: at(result.rows, 0).symbols, + startDate: at(result.rows, 0).start_date, + endDate: at(result.rows, 0).end_date, + initialCapital: parseFloat(at(result.rows, 0).initial_capital), + config: at(result.rows, 0).config, + createdAt: at(result.rows, 0).created_at, + updatedAt: at(result.rows, 0).updated_at, + }; + + // Call orchestrator to run backtest + try { + const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + mode: 'backtest', + startDate: new Date(request.startDate).toISOString(), + endDate: new Date(request.endDate).toISOString(), + symbols: request.symbols, + strategy: request.strategy, + initialCapital: request.initialCapital, + dataFrequency: '1d', // Default to daily + commission: request.config?.commission, + slippage: request.config?.slippage, + speed: 'max', // Default speed + fillModel: { + slippage: 'realistic', + marketImpact: true, + partialFills: true, + }, + }), + }); + + if (!response.ok) { + throw new Error(`Orchestrator returned ${response.status}`); + } + + const result = await response.json(); + + // Store result directly without transformation + if (result.status === 'completed') { + // Update backtest status + await this.container.postgres.query( + 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', + ['completed', backtestId] + ); + + // Store results in backtest_results table + await this.saveBacktestResults(backtestId, result); + + logger.info('Backtest completed', { + backtestId, + trades: result.metrics?.totalTrades, + return: result.metrics?.totalReturn, + }); + } else { + // Update status to running if not completed + await this.container.postgres.query( + 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', + ['running', backtestId] + ); + } + + logger.info('Backtest started in orchestrator', { backtestId, result }); + } catch (error) { + logger.error('Failed to start backtest in orchestrator', { backtestId, error }); + await this.container.postgres.query( + 'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3', + ['failed', error instanceof Error ? error.message : String(error), backtestId] + ); + backtest.status = 'failed'; + backtest.error = error instanceof Error ? error.message : String(error); + } + + return backtest; + } + + async getBacktest(id: string): Promise { + const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [ + id, + ]); + + if (result.rows.length === 0) { + return null; + } + + const row = at(result.rows, 0); + return { + id: row.id, + status: row.status, + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date, + endDate: row.end_date, + initialCapital: parseFloat(row.initial_capital), + config: row.config, + createdAt: row.created_at, + updatedAt: row.updated_at, + error: row.error, + }; + } + + async getBacktestResults(id: string) { + const result = await this.container.postgres.query( + `SELECT + br.*, + b.strategy, + b.symbols, + b.start_date, + b.end_date, + b.initial_capital, + b.config as backtest_config + FROM backtest_results br + JOIN backtests b ON b.id = br.backtest_id + WHERE br.backtest_id = $1`, + [id] + ); + + if (result.rows.length === 0) { + return null; + } + + const row = at(result.rows, 0); + + // Reconstruct the result format expected by frontend + return { + backtestId: row.backtest_id, + status: 'completed', + completedAt: row.completed_at.toISOString(), + config: { + name: row.backtest_config?.name || 'Backtest', + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date.toISOString(), + endDate: row.end_date.toISOString(), + initialCapital: parseFloat(row.initial_capital), + commission: row.backtest_config?.commission ?? 0.001, + slippage: row.backtest_config?.slippage ?? 0.0001, + dataFrequency: row.backtest_config?.dataFrequency || '1d', + }, + metrics: row.metrics, + equity: row.equity_curve, + ohlcData: row.ohlc_data, + trades: row.trades, + positions: row.positions, + analytics: row.analytics, + executionTime: row.execution_time, + }; + } + + async listBacktests(params: { limit: number; offset: number }): Promise { + const result = await this.container.postgres.query( + `SELECT * FROM backtests + ORDER BY created_at DESC + LIMIT $1 OFFSET $2`, + [params.limit, params.offset] + ); + + return result.rows.map(row => ({ + id: row.id, + status: row.status, + strategy: row.strategy, + symbols: row.symbols, + startDate: row.start_date, + endDate: row.end_date, + initialCapital: parseFloat(row.initial_capital), + config: row.config, + createdAt: row.created_at, + updatedAt: row.updated_at, + error: row.error, + })); + } + + async updateBacktestStatus( + id: string, + status: BacktestJob['status'], + error?: string + ): Promise { + if (error) { + await this.container.postgres.query( + 'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3', + [status, error, id] + ); + } else { + await this.container.postgres.query( + 'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2', + [status, id] + ); + } + } + + async cancelBacktest(id: string): Promise { + await this.updateBacktestStatus(id, 'cancelled'); + + // Call orchestrator to stop backtest + try { + await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, { + method: 'POST', + }); + } catch (error) { + logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error }); + } + } + + private async saveBacktestResults( + backtestId: string, + result: Record + ): Promise { + try { + await this.container.postgres.query( + `INSERT INTO backtest_results + (backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + [ + backtestId, + result.completedAt || new Date(), + JSON.stringify(result.metrics || {}), + JSON.stringify(result.equity || result.equityCurve || []), + JSON.stringify(result.ohlcData || {}), + JSON.stringify(result.trades || []), + JSON.stringify(result.positions || result.finalPositions || {}), + JSON.stringify(result.analytics || {}), + result.executionTime || 0, + ] + ); + } catch (error) { + logger.error('Failed to save backtest results', { backtestId, error }); + throw error; + } + } +} diff --git a/apps/stock/web-api/src/services/exchange.service.ts b/apps/stock/web-api/src/services/exchange.service.ts index f1f570b6..29051f44 100644 --- a/apps/stock/web-api/src/services/exchange.service.ts +++ b/apps/stock/web-api/src/services/exchange.service.ts @@ -1,15 +1,16 @@ +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/services'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; import { - CreateExchangeRequest, - CreateProviderMappingRequest, - Exchange, - ExchangeStats, - ExchangeWithMappings, - ProviderExchange, - ProviderMapping, - UpdateExchangeRequest, - UpdateProviderMappingRequest, + type CreateExchangeRequest, + type CreateProviderMappingRequest, + type Exchange, + type ExchangeStats, + type ExchangeWithMappings, + type ProviderExchange, + type ProviderMapping, + type UpdateExchangeRequest, + type UpdateProviderMappingRequest, } from '../types/exchange.types'; const logger = getLogger('exchange-service'); @@ -18,11 +19,11 @@ export class ExchangeService { constructor(private container: IServiceContainer) {} private get postgresClient() { - return this.container.postgres; + return requireServices(this.container, 'postgres').postgres; } private get mongoClient() { - return this.container.mongodb; + return requireServices(this.container, 'mongodb').mongodb; } // Exchanges @@ -49,7 +50,7 @@ export class ExchangeService { ORDER BY e.code `; - const exchangesResult = await this.postgresClient.query(exchangesQuery); + const exchangesResult = await this.postgresClient.query(exchangesQuery); // Get all provider mappings const mappingsQuery = ` @@ -62,7 +63,7 @@ export class ExchangeService { WHERE e.visible = true ORDER BY pem.master_exchange_id, pem.provider, pem.provider_exchange_code `; - const mappingsResult = await this.postgresClient.query(mappingsQuery); + const mappingsResult = await this.postgresClient.query(mappingsQuery); // Group mappings by exchange ID const mappingsByExchange = mappingsResult.rows.reduce( @@ -88,7 +89,7 @@ export class ExchangeService { id: string ): Promise<{ exchange: Exchange; provider_mappings: ProviderMapping[] } | null> { const exchangeQuery = 'SELECT * FROM exchanges WHERE id = $1 AND visible = true'; - const exchangeResult = await this.postgresClient.query(exchangeQuery, [id]); + const exchangeResult = await this.postgresClient.query(exchangeQuery, [id]); if (exchangeResult.rows.length === 0) { return null; @@ -104,10 +105,10 @@ export class ExchangeService { WHERE pem.master_exchange_id = $1 ORDER BY pem.provider, pem.provider_exchange_code `; - const mappingsResult = await this.postgresClient.query(mappingsQuery, [id]); + const mappingsResult = await this.postgresClient.query(mappingsQuery, [id]); return { - exchange: exchangeResult.rows[0], + exchange: at(exchangeResult.rows, 0), provider_mappings: mappingsResult.rows, }; } @@ -119,7 +120,7 @@ export class ExchangeService { RETURNING * `; - const result = await this.postgresClient.query(query, [ + const result = await this.postgresClient.query(query, [ data.code, data.name, data.country, @@ -128,12 +129,12 @@ export class ExchangeService { ]); logger.info('Exchange created', { - exchangeId: result.rows[0].id, + exchangeId: at(result.rows, 0).id, code: data.code, name: data.name, }); - return result.rows[0]; + return at(result.rows, 0); } async updateExchange(id: string, updates: UpdateExchangeRequest): Promise { @@ -156,7 +157,7 @@ export class ExchangeService { RETURNING * `; - const result = await this.postgresClient.query(query, values); + const result = await this.postgresClient.query(query, values); if (result.rows.length === 0) { return null; @@ -169,7 +170,7 @@ export class ExchangeService { logger.info('Exchange updated', { exchangeId: id, updates }); - return result.rows[0]; + return result.rows[0] ?? null; } // Provider Mappings @@ -186,7 +187,7 @@ export class ExchangeService { ORDER BY pem.provider, pem.provider_exchange_code `; - const result = await this.postgresClient.query(query); + const result = await this.postgresClient.query(query); return result.rows; } @@ -203,7 +204,7 @@ export class ExchangeService { ORDER BY pem.provider_exchange_code `; - const result = await this.postgresClient.query(query, [provider]); + const result = await this.postgresClient.query(query, [provider]); return result.rows; } @@ -216,7 +217,7 @@ export class ExchangeService { RETURNING * `; - const result = await this.postgresClient.query(query, [ + const result = await this.postgresClient.query(query, [ data.provider, data.provider_exchange_code, data.provider_exchange_name, @@ -234,7 +235,7 @@ export class ExchangeService { master_exchange_id: data.master_exchange_id, }); - return result.rows[0]; + return at(result.rows, 0); } async updateProviderMapping( @@ -261,7 +262,7 @@ export class ExchangeService { RETURNING * `; - const result = await this.postgresClient.query(query, values); + const result = await this.postgresClient.query(query, values); if (result.rows.length === 0) { return null; @@ -269,7 +270,7 @@ export class ExchangeService { logger.info('Provider mapping updated', { mappingId: id, updates }); - return result.rows[0]; + return result.rows[0] ?? null; } async deleteProviderMappingsByExchangeId(exchangeId: string): Promise { @@ -309,8 +310,8 @@ export class ExchangeService { (SELECT COUNT(DISTINCT provider) FROM provider_exchange_mappings pem JOIN exchanges e ON pem.master_exchange_id = e.id WHERE e.visible = true) as providers `; - const result = await this.postgresClient.query(query); - return result.rows[0]; + const result = await this.postgresClient.query(query); + return at(result.rows, 0); } async getUnmappedProviderExchanges(provider: string): Promise { diff --git a/apps/stock/web-api/src/services/monitoring.service.ts b/apps/stock/web-api/src/services/monitoring.service.ts index e997e5f2..11dc8371 100644 --- a/apps/stock/web-api/src/services/monitoring.service.ts +++ b/apps/stock/web-api/src/services/monitoring.service.ts @@ -6,6 +6,7 @@ import * as os from 'os'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { getFullQueueName } from '@stock-bot/queue'; import type { CacheStats, DatabaseStats, @@ -73,269 +74,53 @@ export class MonitoringService { * Get queue statistics */ async getQueueStats(): Promise { - const stats: QueueStats[] = []; - - try { - if (!this.container.queueManager) { - this.logger.warn('No queue manager available'); - return stats; - } - - // Get all queue names from the QueueManager - const queueManager = this.container.queueManager as any; - this.logger.debug('Queue manager type:', { - type: queueManager.constructor.name, - hasGetAllQueues: typeof queueManager.getAllQueues === 'function', - hasQueues: !!queueManager.queues, - hasGetQueue: typeof queueManager.getQueue === 'function', - }); - - // Always use the known queue names since web-api doesn't create worker queues - const handlerMapping = { - qm: 'data-ingestion', - ib: 'data-ingestion', - ceo: 'data-ingestion', - webshare: 'data-ingestion', - exchanges: 'data-pipeline', - symbols: 'data-pipeline', - }; - - // Worker configuration per queue (from service configs) - const workerConfig: Record = { - qm: { count: 1, concurrency: 2 }, - ib: { count: 1, concurrency: 1 }, - ceo: { count: 1, concurrency: 2 }, - webshare: { count: 1, concurrency: 1 }, - exchanges: { count: 1, concurrency: 1 }, - symbols: { count: 1, concurrency: 2 }, - }; - - const queueNames = Object.keys(handlerMapping); - this.logger.debug('Using known queue names', { count: queueNames.length, names: queueNames }); - - // Create BullMQ queues directly with the correct format - for (const handlerName of queueNames) { - try { - // Import BullMQ directly to create queue instances - const { Queue: BullMQQueue } = await import('bullmq'); - const connection = { - host: 'localhost', - port: 6379, - db: 0, // All queues now in DB 0 - }; - - // Get the service that owns this handler - const serviceName = handlerMapping[handlerName as keyof typeof handlerMapping]; - - // Create BullMQ queue with the new naming format {service_handler} - const fullQueueName = `{${serviceName}_${handlerName}}`; - const bullQueue = new BullMQQueue(fullQueueName, { connection }); - - // Get stats directly from BullMQ - const queueStats = await this.getQueueStatsForBullQueue(bullQueue, handlerName); - - // Get actual worker count from BullMQ - const actualWorkerCount = await this.getActiveWorkerCountFromBullMQ(bullQueue); - const configuredWorkers = workerConfig[handlerName] || { count: 0, concurrency: 1 }; - - stats.push({ - name: handlerName, - service: serviceName, - queue: handlerName, - connected: true, - jobs: queueStats, - workers: { - count: actualWorkerCount, - concurrency: configuredWorkers.concurrency, - }, - }); - - // Close the queue connection after getting stats - await bullQueue.close(); - } catch (error) { - this.logger.warn(`Failed to get stats for queue ${handlerName}`, { error }); - stats.push({ - name: handlerName, - service: serviceName, - queue: handlerName, - connected: false, - jobs: { - waiting: 0, - active: 0, - completed: 0, - failed: 0, - delayed: 0, - paused: 0, - }, - }); - } - } - } catch (error) { - this.logger.error('Failed to get queue stats', { error }); + const manager = this.container.queueManager; + if (!manager) { + return []; } - - return stats; - } - - /** - * Get stats for a BullMQ queue directly - */ - private async getQueueStatsForBullQueue(bullQueue: any, queueName: string) { - try { - // BullMQ provides getJobCounts which returns all counts at once - const counts = await bullQueue.getJobCounts(); - - return { - waiting: counts.waiting || 0, - active: counts.active || 0, - completed: counts.completed || 0, - failed: counts.failed || 0, - delayed: counts.delayed || 0, - paused: counts.paused || 0, - prioritized: counts.prioritized || 0, - 'waiting-children': counts['waiting-children'] || 0, - }; - } catch (error) { - this.logger.error(`Failed to get stats for BullMQ queue ${queueName}`, { error }); - // Fallback to individual methods - try { - const [waiting, active, completed, failed, delayed, paused] = await Promise.all([ - bullQueue.getWaitingCount(), - bullQueue.getActiveCount(), - bullQueue.getCompletedCount(), - bullQueue.getFailedCount(), - bullQueue.getDelayedCount(), - bullQueue.getPausedCount ? bullQueue.getPausedCount() : 0, - ]); - - return { - waiting, - active, - completed, - failed, - delayed, - paused, - }; - } catch (fallbackError) { - this.logger.error(`Fallback also failed for queue ${queueName}`, { fallbackError }); - return this.getQueueStatsForQueue(bullQueue, queueName); - } - } - } - - /** - * Get stats for a specific queue - */ - private async getQueueStatsForQueue(queue: any, _queueName: string) { - // Check if it has the getStats method - if (queue.getStats && typeof queue.getStats === 'function') { - const stats = await queue.getStats(); - return { - waiting: stats.waiting || 0, - active: stats.active || 0, - completed: stats.completed || 0, - failed: stats.failed || 0, - delayed: stats.delayed || 0, - paused: stats.paused || 0, - }; - } - - // Try individual count methods - const [waiting, active, completed, failed, delayed] = await Promise.all([ - this.safeGetCount(queue, 'getWaitingCount', 'getWaiting'), - this.safeGetCount(queue, 'getActiveCount', 'getActive'), - this.safeGetCount(queue, 'getCompletedCount', 'getCompleted'), - this.safeGetCount(queue, 'getFailedCount', 'getFailed'), - this.safeGetCount(queue, 'getDelayedCount', 'getDelayed'), - ]); - - const paused = await this.safeGetPausedStatus(queue); - - return { - waiting, - active, - completed, - failed, - delayed, - paused, + const owners = { + qm: 'data-ingestion', + ib: 'data-ingestion', + ceo: 'data-ingestion', + webshare: 'data-ingestion', + exchanges: 'data-pipeline', + symbols: 'data-pipeline', }; - } - - /** - * Safely get count from queue - */ - private async safeGetCount(queue: any, ...methodNames: string[]): Promise { - for (const methodName of methodNames) { - if (queue[methodName] && typeof queue[methodName] === 'function') { + return Promise.all( + Object.entries(owners).map(async ([name, service]) => { try { - const result = await queue[methodName](); - return Array.isArray(result) ? result.length : result || 0; - } catch (_e) { - // Continue to next method + const queue = manager.getQueue(getFullQueueName(service, name)); + const snapshot = await queue.getStats(); + return { + name, + service, + queue: name, + connected: true, + jobs: { + waiting: snapshot.waiting, + active: snapshot.active, + completed: snapshot.completed, + failed: snapshot.failed, + delayed: snapshot.delayed, + paused: snapshot.paused ? 1 : 0, + }, + workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 }, + }; + } catch (error) { + this.logger.warn('Unable to inspect queue', { name, service, error }); + return { + name, + service, + queue: name, + connected: false, + jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 }, + }; } - } - } - return 0; + }) + ); } - /** - * Get paused status - */ - private async safeGetPausedStatus(queue: any): Promise { - try { - if (queue.isPaused && typeof queue.isPaused === 'function') { - const isPaused = await queue.isPaused(); - return isPaused ? 1 : 0; - } - if (queue.getPausedCount && typeof queue.getPausedCount === 'function') { - return await queue.getPausedCount(); - } - } catch (_e) { - // Ignore - } - return 0; - } - - /** - * Get worker info for a queue - */ - private getWorkerInfo(queue: any, queueManager: any, _queueName: string) { - try { - // Check queue itself for worker info - if (queue.workers && Array.isArray(queue.workers)) { - return { - count: queue.workers.length, - concurrency: queue.workers[0]?.concurrency || 1, - }; - } - - // Check queue manager for worker config - if (queueManager.config?.defaultQueueOptions) { - const options = queueManager.config.defaultQueueOptions; - return { - count: options.workers || 1, - concurrency: options.concurrency || 1, - }; - } - - // Check for getWorkerCount method - if (queue.getWorkerCount && typeof queue.getWorkerCount === 'function') { - const count = queue.getWorkerCount(); - return { - count, - concurrency: 1, - }; - } - } catch (_e) { - // Ignore - } - - return undefined; - } - - /** - * Get database statistics - */ + /** Database health uses the public adapter capabilities. */ async getDatabaseStats(): Promise { const stats: DatabaseStats[] = []; @@ -347,12 +132,13 @@ export class MonitoringService { const latency = Date.now() - startTime; // Get pool stats - const pool = (this.container.postgres as any).pool; + const pool = this.container.postgres.connectionPool; const poolStats = pool ? { size: pool.totalCount || 0, - active: pool.idleCount || 0, - idle: pool.waitingCount || 0, + active: pool.totalCount - pool.idleCount, + idle: pool.idleCount, + waiting: pool.waitingCount, max: pool.options?.max || 0, } : undefined; @@ -378,7 +164,7 @@ export class MonitoringService { if (this.container.mongodb) { try { const startTime = Date.now(); - const mongoClient = this.container.mongodb as any; // This is MongoDBClient + const mongoClient = this.container.mongodb; // This is MongoDBClient const db = mongoClient.getDatabase(); await db.admin().ping(); const latency = Date.now() - startTime; @@ -528,14 +314,14 @@ export class MonitoringService { */ private parseInfoValue(info: string, key: string): number { const match = info.match(new RegExp(`${key}:(\\d+)`)); - return match ? parseInt(match[1], 10) : 0; + return match?.[1] ? parseInt(match[1], 10) : 0; } /** * Parse Redis INFO into structured object */ - private parseRedisInfo(info: string): Record { - const result: Record = {}; + private parseRedisInfo(info: string): Record> { + const result: Record> = {}; const sections = info.split('\r\n\r\n'); for (const section of sections) { @@ -544,7 +330,7 @@ export class MonitoringService { result[sectionName] = {}; for (let i = 1; i < lines.length; i++) { - const [key, value] = lines[i].split(':'); + const [key, value] = (lines[i] ?? '').split(':'); if (key && value) { result[sectionName][key] = value; } @@ -656,7 +442,7 @@ export class MonitoringService { this.logger.debug('Attempting to fetch proxy data from cache'); const [cachedProxies, lastUpdateStr] = await Promise.all([ - cacheProvider.getRaw('cache:proxy:active'), + cacheProvider.getRaw<{ isWorking?: boolean }[]>('cache:proxy:active'), cacheProvider.getRaw('cache:proxy:last-update'), ]); @@ -668,8 +454,8 @@ export class MonitoringService { }); if (cachedProxies && Array.isArray(cachedProxies)) { - const workingCount = cachedProxies.filter((p: any) => p.isWorking !== false).length; - const failedCount = cachedProxies.filter((p: any) => p.isWorking === false).length; + const workingCount = cachedProxies.filter(p => p.isWorking !== false).length; + const failedCount = cachedProxies.filter(p => p.isWorking === false).length; return { enabled: true, @@ -811,23 +597,4 @@ export class MonitoringService { /** * Get active worker count using BullMQ's built-in tracking */ - private async getActiveWorkerCountFromBullMQ(bullQueue: any): Promise { - try { - // Use BullMQ's built-in getWorkers method - if (bullQueue.getWorkers && typeof bullQueue.getWorkers === 'function') { - const workers = await bullQueue.getWorkers(); - return workers.length; - } - - // Fallback to getWorkersCount if available - if (bullQueue.getWorkersCount && typeof bullQueue.getWorkersCount === 'function') { - return await bullQueue.getWorkersCount(); - } - - return 0; - } catch (error) { - this.logger.debug('Failed to get active worker count from BullMQ', { error }); - return 0; - } - } } diff --git a/apps/stock/web-api/src/services/pipeline.service.ts b/apps/stock/web-api/src/services/pipeline.service.ts index 81036f6f..38f0eb9b 100644 --- a/apps/stock/web-api/src/services/pipeline.service.ts +++ b/apps/stock/web-api/src/services/pipeline.service.ts @@ -14,12 +14,12 @@ export interface PipelineJobResult { jobId?: string; message?: string; error?: string; - data?: any; + data?: unknown; } export interface PipelineStatsResult { success: boolean; - data?: any; + data?: Record; error?: string; } @@ -294,7 +294,7 @@ export class PipelineService { }); // Wait for job to complete and return result - const result = await exchangesQueue.waitForJob(job); + const result = await exchangesQueue.waitForJob>(job); return { success: true, data: result }; } catch (error) { logger.error('Failed to get exchange stats', { error }); @@ -323,7 +323,7 @@ export class PipelineService { }); // Wait for job to complete and return result - const result = await exchangesQueue.waitForJob(job); + const result = await exchangesQueue.waitForJob>(job); return { success: true, data: result }; } catch (error) { logger.error('Failed to get provider mapping stats', { error }); diff --git a/apps/stock/web-api/src/types/monitoring.types.ts b/apps/stock/web-api/src/types/monitoring.types.ts index d04edd30..3ccb8d21 100644 --- a/apps/stock/web-api/src/types/monitoring.types.ts +++ b/apps/stock/web-api/src/types/monitoring.types.ts @@ -18,7 +18,7 @@ export interface CacheStats { evictedKeys?: number; expiredKeys?: number; }; - info?: Record; + info?: Record; } export interface QueueStats { @@ -59,7 +59,7 @@ export interface DatabaseStats { waiting?: number; max: number; }; - stats?: Record; + stats?: Record; } export interface SystemHealth { @@ -70,6 +70,7 @@ export interface SystemHealth { used: number; total: number; percentage: number; + heap?: { used: number; total: number }; }; cpu?: { usage: number; diff --git a/apps/stock/web-api/src/utils/error-handler.ts b/apps/stock/web-api/src/utils/error-handler.ts index eba907df..22deee2f 100644 --- a/apps/stock/web-api/src/utils/error-handler.ts +++ b/apps/stock/web-api/src/utils/error-handler.ts @@ -1,6 +1,6 @@ -import { Context } from 'hono'; +import type { Context } from 'hono'; import { getLogger } from '@stock-bot/logger'; -import { ApiResponse } from '../types/exchange.types'; +import type { ApiResponse } from '../types/exchange.types'; import { ValidationError } from './validation'; const logger = getLogger('error-handler'); diff --git a/apps/stock/web-api/src/utils/validation.ts b/apps/stock/web-api/src/utils/validation.ts index 59441ecd..57c95726 100644 --- a/apps/stock/web-api/src/utils/validation.ts +++ b/apps/stock/web-api/src/utils/validation.ts @@ -1,4 +1,4 @@ -import { CreateExchangeRequest, CreateProviderMappingRequest } from '../types/exchange.types'; +import type { CreateExchangeRequest, CreateProviderMappingRequest } from '../types/exchange.types'; export class ValidationError extends Error { constructor( @@ -85,14 +85,15 @@ export function validateCreateProviderMapping(data: unknown): CreateProviderMapp } // Validate currency is 3 characters or null - const cleanCurrency = currency && currency.length <= 3 ? currency : null; + const cleanCurrency = typeof currency === 'string' && currency.length <= 3 ? currency : undefined; return { provider: provider.trim(), provider_exchange_code: provider_exchange_code.trim(), - provider_exchange_name: provider_exchange_name?.trim(), + provider_exchange_name: + typeof provider_exchange_name === 'string' ? provider_exchange_name.trim() : undefined, master_exchange_id: master_exchange_id.trim(), - country_code: country_code?.trim() || null, + country_code: typeof country_code === 'string' ? country_code.trim() || undefined : undefined, currency: cleanCurrency, confidence: Number(confidence), active: Boolean(active), diff --git a/apps/stock/web-api/src/websocket/run-updates.ts b/apps/stock/web-api/src/websocket/run-updates.ts index c926de8c..2eb8cdb3 100644 --- a/apps/stock/web-api/src/websocket/run-updates.ts +++ b/apps/stock/web-api/src/websocket/run-updates.ts @@ -1,160 +1,118 @@ -import { getLogger } from '@stock-bot/logger'; -import type { IServiceContainer } from '@stock-bot/handlers'; - -const logger = getLogger('websocket-run-updates'); - -// Store active WebSocket connections per run -// Using 'any' type for Bun WebSocket compatibility -const runConnections = new Map>(); - -export interface RunUpdateMessage { - type: 'run_update' | 'progress' | 'error' | 'completed'; - runId: string; - data: any; -} - -export function createWebSocketHandler(container: IServiceContainer) { - return { - // Handle new WebSocket connection (ws is Bun's WebSocket type) - handleConnection(ws: any, runId: string) { - logger.info(`WebSocket connected for run: ${runId}`); - - // Add connection to the run's connection set - if (!runConnections.has(runId)) { - runConnections.set(runId, new Set()); - } - runConnections.get(runId)!.add(ws); - - // Send initial connection confirmation - ws.send(JSON.stringify({ - type: 'connected', - runId, - timestamp: new Date().toISOString() - })); - - // In Bun, WebSocket handlers are set directly as properties - ws.onmessage = (event: MessageEvent) => { - try { - const message = JSON.parse(event.data.toString()); - logger.debug('Received WebSocket message:', message); - - // Handle different message types - switch (message.type) { - case 'ping': - ws.send(JSON.stringify({ type: 'pong' })); - break; - case 'subscribe': - // Already subscribed to this run - break; - default: - logger.warn('Unknown message type:', message.type); - } - } catch (error) { - logger.error('Error handling WebSocket message:', error); - } - }; - - // Handle connection close - ws.onclose = (event: any) => { - logger.info(`WebSocket disconnected for run: ${runId}`, { code: event.code, reason: event.reason }); - const connections = runConnections.get(runId); - if (connections) { - connections.delete(ws); - if (connections.size === 0) { - runConnections.delete(runId); - } - } - }; - - // Handle errors - ws.onerror = (error: Event) => { - logger.error(`WebSocket error for run ${runId}:`, error); - }; - }, - - // Broadcast update to all connected clients for a run - broadcastRunUpdate(runId: string, update: Partial) { - const connections = runConnections.get(runId); - if (!connections || connections.size === 0) { - return; - } - - const message: RunUpdateMessage = { - type: 'run_update', - runId, - data: update.data || update, - ...update - }; - - const messageStr = JSON.stringify(message); - - connections.forEach(ws => { - try { - // Bun WebSocket - just try to send, it will throw if not open - ws.send(messageStr); - } catch (error) { - // Connection is closed, ignore - } - }); - }, - - // Send progress update - sendProgressUpdate(runId: string, progress: number, currentDate?: string) { - this.broadcastRunUpdate(runId, { - type: 'progress', - data: { - progress, - currentDate, - timestamp: new Date().toISOString() - } - }); - }, - - // Send error - sendError(runId: string, error: string) { - this.broadcastRunUpdate(runId, { - type: 'error', - data: { - error, - timestamp: new Date().toISOString() - } - }); - }, - - // Send completion - sendCompletion(runId: string, results?: any) { - this.broadcastRunUpdate(runId, { - type: 'completed', - data: { - results, - timestamp: new Date().toISOString() - } - }); - - // Clean up connections after completion - setTimeout(() => { - const connections = runConnections.get(runId); - if (connections) { - connections.forEach(ws => ws.close()); - runConnections.delete(runId); - } - }, 5000); - }, - - // Get active connections count - getConnectionsCount(runId: string): number { - return runConnections.get(runId)?.size || 0; - }, - - // Clean up all connections - cleanup() { - runConnections.forEach((connections, runId) => { - connections.forEach(ws => ws.close()); - }); - runConnections.clear(); - } - }; -} - -// Export the WebSocket handler type -export type WebSocketHandler = ReturnType; \ No newline at end of file +import type { ServerWebSocket } from 'bun'; +import { getLogger } from '@stock-bot/logger'; +import type { IServiceContainer } from '@stock-bot/services'; + +const logger = getLogger('websocket-run-updates'); +export interface RunSocketData { + runId: string; +} +type RunSocket = ServerWebSocket; +export interface RunUpdateMessage { + type: 'run_update' | 'progress' | 'error' | 'completed'; + runId: string; + data: unknown; +} + +export function createWebSocketHandler(_container: IServiceContainer) { + const connections = new Map>(); + const completionTimers = new Map>(); + return { + handleConnection(ws: RunSocket, runId: string) { + const clients = connections.get(runId) ?? new Set(); + clients.add(ws); + connections.set(runId, clients); + ws.send(JSON.stringify({ type: 'connected', runId, timestamp: new Date().toISOString() })); + }, + handleMessage(ws: RunSocket, payload: string | Buffer) { + try { + const message: unknown = JSON.parse(payload.toString()); + if ( + message && + typeof message === 'object' && + 'type' in message && + message.type === 'ping' + ) { + ws.send(JSON.stringify({ type: 'pong' })); + } + } catch (error) { + logger.warn('Invalid WebSocket message', { error }); + } + }, + handleClose(ws: RunSocket) { + const runId = ws.data.runId; + const clients = connections.get(runId); + clients?.delete(ws); + if (clients?.size === 0) { + connections.delete(runId); + } + }, + broadcastRunUpdate(runId: string, update: Partial) { + const message: RunUpdateMessage = { + type: 'run_update', + runId, + data: update.data ?? update, + ...update, + }; + for (const ws of connections.get(runId) ?? []) { + try { + ws.send(JSON.stringify(message)); + } catch { + this.handleClose(ws); + } + } + }, + sendProgressUpdate(runId: string, progress: number, currentDate?: string) { + this.broadcastRunUpdate(runId, { + type: 'progress', + data: { progress, currentDate, timestamp: new Date().toISOString() }, + }); + }, + sendError(runId: string, error: string) { + this.broadcastRunUpdate(runId, { + type: 'error', + data: { error, timestamp: new Date().toISOString() }, + }); + }, + sendCompletion(runId: string, results?: unknown) { + this.broadcastRunUpdate(runId, { + type: 'completed', + data: { results, timestamp: new Date().toISOString() }, + }); + clearTimeout(completionTimers.get(runId)); + completionTimers.set( + runId, + setTimeout(() => { + for (const ws of connections.get(runId) ?? []) { + ws.close(); + } + connections.delete(runId); + completionTimers.delete(runId); + }, 5000) + ); + }, + getConnectionsCount(runId: string): number { + return connections.get(runId)?.size ?? 0; + }, + cleanup() { + for (const timer of completionTimers.values()) { + clearTimeout(timer); + } + completionTimers.clear(); + for (const clients of connections.values()) { + for (const ws of clients) { + ws.close(); + } + } + connections.clear(); + }, + }; +} + +export type WebSocketHandler = ReturnType; +let sharedHandler: WebSocketHandler | null = null; +export function setWebSocketHandler(handler: WebSocketHandler): void { + sharedHandler = handler; +} +export function getWebSocketHandler(): WebSocketHandler | null { + return sharedHandler; +} diff --git a/apps/stock/web-app/package.json b/apps/stock/web-app/package.json index 57a237e6..fc88c2ed 100644 --- a/apps/stock/web-app/package.json +++ b/apps/stock/web-app/package.json @@ -24,7 +24,8 @@ "react-virtuoso": "^4.12.8", "recharts": "^2.10.4", "tailwind-merge": "^3.3.1", - "zod": "^3.22.4" + "zod": "^3.22.4", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/react": "^18.2.15", diff --git a/apps/stock/web-app/src/components/ErrorBoundary.tsx b/apps/stock/web-app/src/components/ErrorBoundary.tsx index fd7a921d..c90b0ff0 100644 --- a/apps/stock/web-app/src/components/ErrorBoundary.tsx +++ b/apps/stock/web-app/src/components/ErrorBoundary.tsx @@ -1,53 +1,52 @@ -import React, { Component, type ReactNode } from 'react'; - -interface Props { - children: ReactNode; - fallback?: ReactNode; -} - -interface State { - hasError: boolean; - error?: Error; -} - -export class ErrorBoundary extends Component { - constructor(props: Props) { - super(props); - this.state = { hasError: false }; - } - - static getDerivedStateFromError(error: Error): State { - return { hasError: true, error }; - } - - override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { - console.error('ErrorBoundary caught an error:', error, errorInfo); - } - - override render() { - if (this.state.hasError) { - return ( - this.props.fallback || ( -
-
-

- Something went wrong -

-

- {this.state.error?.message || 'An unexpected error occurred'} -

- -
-
- ) - ); - } - - return this.props.children; - } -} \ No newline at end of file +import React, { Component, type ReactNode } from 'react'; +import { browserLog } from '@/utils/browserLog'; + +interface Props { + children: ReactNode; + fallback?: ReactNode; +} + +interface State { + hasError: boolean; + error?: Error; +} + +export class ErrorBoundary extends Component { + constructor(props: Props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error: Error): State { + return { hasError: true, error }; + } + + override componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { + browserLog.error('ErrorBoundary caught an error:', error, errorInfo); + } + + override render() { + if (this.state.hasError) { + return ( + this.props.fallback || ( +
+
+

Something went wrong

+

+ {this.state.error?.message || 'An unexpected error occurred'} +

+ +
+
+ ) + ); + } + + return this.props.children; + } +} diff --git a/apps/stock/web-app/src/components/charts/Chart.tsx b/apps/stock/web-app/src/components/charts/Chart.tsx index 27a8edf5..eea3219e 100644 --- a/apps/stock/web-app/src/components/charts/Chart.tsx +++ b/apps/stock/web-app/src/components/charts/Chart.tsx @@ -1,415 +1,434 @@ -import * as LightweightCharts from 'lightweight-charts'; -import { useEffect, useRef, useCallback, useMemo } from 'react'; -import { useChartManager } from '@/hooks/useChartManager'; - -export interface ChartData { - time: number; - open?: number; - high?: number; - low?: number; - close?: number; - value?: number; - volume?: number; -} - -export interface TradeMarker { - time: number; - position: 'aboveBar' | 'belowBar'; - color: string; - shape: 'arrowUp' | 'arrowDown'; - text: string; - id?: string; - price?: number; -} - -export interface ChartProps { - data: ChartData[]; - height?: number | string; - type?: 'candlestick' | 'line' | 'area'; - showVolume?: boolean; - theme?: 'light' | 'dark'; - overlayData?: Array<{ - name: string; - data: Array<{ time: number; value: number }>; - color?: string; - lineWidth?: number; - }>; - tradeMarkers?: TradeMarker[]; - className?: string; - chartId?: string; -} - -export function Chart({ - data, - height = 400, - type = 'candlestick', - showVolume = true, - theme = 'dark', - overlayData = [], - tradeMarkers = [], - className = '', - chartId = 'default', -}: ChartProps) { - const chartContainerRef = useRef(null); - const { createChart, getChart, setMainSeries, setVolumeSeries, addOverlaySeries, disposeChart } = useChartManager(); - - // Use a stable unique ID that changes only when chartId prop changes - const uniqueChartId = useMemo(() => { - return `${chartId}-${Date.now()}`; - }, [chartId]) - const mountedRef = useRef(true); - - // Track component mount state - useEffect(() => { - mountedRef.current = true; - return () => { - mountedRef.current = false; - // Cleanup on unmount - disposeChart(uniqueChartId); - }; - }, [disposeChart]); - - // Reset zoom handler - const resetZoom = useCallback(() => { - const chartInstance = getChart(uniqueChartId); - if (chartInstance && !chartInstance.isDisposed && data.length > 0) { - // Get the validated data to ensure we're using the correct time values - const validateData = (rawData: any[]) => { - const seen = new Set(); - return rawData - .map(item => { - const timeInSeconds = item.time > 10000000000 - ? Math.floor(item.time / 1000) - : item.time; - return { ...item, time: timeInSeconds }; - }) - .filter(item => { - if (seen.has(item.time)) return false; - seen.add(item.time); - return true; - }) - .sort((a, b) => a.time - b.time); - }; - - const validatedData = validateData(data); - - if (validatedData.length > 0) { - const firstTime = validatedData[0].time; - const lastTime = validatedData[validatedData.length - 1].time; - - // Add some padding (5% on each side) - const timeRange = lastTime - firstTime; - const padding = timeRange * 0.05; - - try { - chartInstance.chart.timeScale().setVisibleRange({ - from: (firstTime - padding) as any, - to: (lastTime + padding) as any, - }); - - chartInstance.chart.timeScale().fitContent(); - } catch (error) { - console.error('Error resetting zoom:', error); - } - } - } - }, [data, getChart]); - - useEffect(() => { - if (!chartContainerRef.current || !data || !data.length) { - return; - } - - let handleResize: (() => void) | undefined; - let isCleanedUp = false; - - // Use requestAnimationFrame to ensure DOM is ready and avoid conflicts - const rafId = requestAnimationFrame(() => { - setTimeout(() => { - if (!chartContainerRef.current || isCleanedUp || !mountedRef.current) return; - - // Create chart using the chart manager - const chart = createChart(uniqueChartId, chartContainerRef.current, { - width: chartContainerRef.current.clientWidth, - height: typeof height === 'string' ? parseInt(height) : height, - layout: { - background: { - type: LightweightCharts.ColorType.Solid, - color: theme === 'dark' ? '#0f0f0f' : '#ffffff' - }, - textColor: theme === 'dark' ? '#d1d5db' : '#374151', - }, - grid: { - vertLines: { - color: theme === 'dark' ? '#1f2937' : '#e5e7eb', - visible: true, - }, - horzLines: { - color: theme === 'dark' ? '#1f2937' : '#e5e7eb', - visible: true, - }, - }, - crosshair: { - mode: LightweightCharts.CrosshairMode.Normal, - }, - rightPriceScale: { - borderColor: theme === 'dark' ? '#1f2937' : '#e5e7eb', - autoScale: true, - }, - timeScale: { - borderColor: theme === 'dark' ? '#1f2937' : '#e5e7eb', - timeVisible: true, - secondsVisible: false, - rightOffset: 12, - barSpacing: 3, - fixLeftEdge: true, - fixRightEdge: true, - }, - }); - - if (!chart) { - console.error('Failed to create chart'); - return; - } - - // Filter, validate and sort data - const validateAndFilterData = (rawData: any[]) => { - const seen = new Set(); - return rawData - .map(item => { - // Convert timestamp to seconds if it's in milliseconds - const timeInSeconds = item.time > 10000000000 - ? Math.floor(item.time / 1000) - : item.time; - - return { - ...item, - time: timeInSeconds as LightweightCharts.Time - }; - }) - .filter((item) => { - if (seen.has(item.time)) { - return false; - } - seen.add(item.time); - return true; - }) - .sort((a, b) => (a.time as number) - (b.time as number)); // Ensure ascending time order - }; - - // Create main series - let mainSeries: LightweightCharts.ISeriesApi | null = null; - - if (type === 'candlestick' && data[0]?.open !== undefined) { - mainSeries = chart.addCandlestickSeries({ - upColor: '#10b981', - downColor: '#ef4444', - borderUpColor: '#10b981', - borderDownColor: '#ef4444', - wickUpColor: '#10b981', - wickDownColor: '#ef4444', - }); - const validData = validateAndFilterData(data); - mainSeries.setData(validData as LightweightCharts.CandlestickData[]); - } else if (type === 'line' || (type === 'candlestick' && data[0]?.value !== undefined)) { - mainSeries = chart.addLineSeries({ - color: '#3b82f6', - lineWidth: 2, - }); - const lineData = data.map(d => ({ - time: d.time, - value: d.value ?? d.close ?? 0 - })); - const validData = validateAndFilterData(lineData); - mainSeries.setData(validData); - } else if (type === 'area') { - mainSeries = chart.addAreaSeries({ - lineColor: '#3b82f6', - topColor: '#3b82f6', - bottomColor: 'rgba(59, 130, 246, 0.1)', - lineWidth: 2, - }); - const areaData = data.map(d => ({ - time: d.time, - value: d.value ?? d.close ?? 0 - })); - const validData = validateAndFilterData(areaData); - mainSeries.setData(validData); - } - - if (mainSeries) { - setMainSeries(uniqueChartId, mainSeries); - } - - // Add volume if available - if (showVolume && data.some(d => d.volume)) { - const volumeSeries = chart.addHistogramSeries({ - color: '#3b82f680', - priceFormat: { - type: 'volume', - }, - priceScaleId: 'volume', - }); - - volumeSeries.priceScale().applyOptions({ - scaleMargins: { - top: 0.8, - bottom: 0, - }, - }); - - const volumeData = validateAndFilterData( - data - .filter(d => d.volume !== undefined) - .map(d => ({ - time: d.time, - value: d.volume!, - color: d.close && d.open ? - (d.close >= d.open ? '#10b98140' : '#ef444440') : - '#3b82f640', - })) - ); - volumeSeries.setData(volumeData); - setVolumeSeries(uniqueChartId, volumeSeries); - } - - // Add overlay series - overlayData.forEach((overlay, index) => { - const series = chart.addLineSeries({ - color: overlay.color || ['#ff9800', '#4caf50', '#9c27b0', '#f44336'][index % 4], - lineWidth: (overlay.lineWidth || 2) as LightweightCharts.LineWidth, - title: overlay.name, - priceScaleId: index === 0 ? '' : `overlay-${index}`, // First overlay uses main scale - }); - - if (index > 0) { - series.priceScale().applyOptions({ - scaleMargins: { - top: 0.1, - bottom: 0.1, - }, - }); - } - - // Use validateAndFilterData to ensure consistent time handling - const overlayDataWithTime = overlay.data.map(d => ({ - ...d, - time: d.time // Ensure time field exists - })); - const validatedData = validateAndFilterData(overlayDataWithTime); - series.setData(validatedData); - addOverlaySeries(uniqueChartId, overlay.name, series); - }); - - // Add trade markers - if (tradeMarkers.length > 0 && mainSeries) { - // Sort markers by time to ensure they're in ascending order - const sortedMarkers = [...tradeMarkers].sort((a, b) => a.time - b.time); - const markers: LightweightCharts.SeriesMarker[] = sortedMarkers.map(marker => ({ - time: marker.time as LightweightCharts.Time, - position: marker.position, - color: marker.color, - shape: marker.shape as LightweightCharts.SeriesMarkerShape, - text: marker.text, - id: marker.id, - size: 1 - })); - mainSeries.setMarkers(markers); - } - - // Fit content with a slight delay to ensure all series are loaded - setTimeout(() => { - // First fit content to calculate proper range - chart.timeScale().fitContent(); - - // Get the validated data to ensure we're using the correct time values - const validatedData = validateAndFilterData(data); - - // Set visible range with some padding - if (validatedData.length > 0) { - const firstTime = validatedData[0].time; - const lastTime = validatedData[validatedData.length - 1].time; - - // Add some padding (5% on each side) - const timeRange = (lastTime as number) - (firstTime as number); - const padding = timeRange * 0.05; - - chart.timeScale().setVisibleRange({ - from: ((firstTime as number) - padding) as any, - to: ((lastTime as number) + padding) as any, - }); - } - - // Ensure the chart fits the content properly - chart.timeScale().fitContent(); - }, 100); - - // Enable mouse wheel zoom and touch gestures - chart.applyOptions({ - handleScroll: { - mouseWheel: true, - pressedMouseMove: true, - horzTouchDrag: true, - vertTouchDrag: true, - }, - handleScale: { - mouseWheel: true, - pinch: true, - axisPressedMouseMove: true, - }, - }); - - // Handle resize - handleResize = () => { - if (chartContainerRef.current && !isCleanedUp) { - const chartInstance = getChart(uniqueChartId); - if (chartInstance && !chartInstance.isDisposed) { - try { - chartInstance.chart.applyOptions({ - width: chartContainerRef.current.clientWidth, - }); - } catch (error) { - // Ignore errors if the chart is being disposed - if (!(error instanceof Error) || !error.message?.includes('disposed')) { - console.error('Error resizing chart:', error); - } - } - } - } - }; - - window.addEventListener('resize', handleResize); - }, 0); // End of setTimeout - }); // End of requestAnimationFrame - - // Cleanup - return () => { - isCleanedUp = true; - cancelAnimationFrame(rafId); - if (handleResize) { - window.removeEventListener('resize', handleResize); - } - // Dispose immediately - the chart manager handles cleanup safely - disposeChart(uniqueChartId); - }; - }, [data, height, type, showVolume, theme, overlayData, tradeMarkers, createChart, getChart, setMainSeries, setVolumeSeries, addOverlaySeries, disposeChart]); - - return ( -
-
- -
- ); -} \ No newline at end of file +import * as LightweightCharts from 'lightweight-charts'; +import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { at, defined } from '@stock-bot/invariants'; +import { useChartManager } from '@/hooks/useChartManager'; +import { browserLog } from '@/utils/browserLog'; + +export interface ChartData { + time: number; + open?: number; + high?: number; + low?: number; + close?: number; + value?: number; + volume?: number; +} + +export interface TradeMarker { + time: number; + position: 'aboveBar' | 'belowBar'; + color: string; + shape: 'arrowUp' | 'arrowDown'; + text: string; + id?: string; + price?: number; +} + +export interface ChartProps { + data: ChartData[]; + height?: number | string; + type?: 'candlestick' | 'line' | 'area'; + showVolume?: boolean; + theme?: 'light' | 'dark'; + overlayData?: Array<{ + name: string; + data: Array<{ time: number; value: number }>; + color?: string; + lineWidth?: number; + }>; + tradeMarkers?: TradeMarker[]; + className?: string; + chartId?: string; +} + +export function Chart({ + data, + height = 400, + type = 'candlestick', + showVolume = true, + theme = 'dark', + overlayData = [], + tradeMarkers = [], + className = '', + chartId = 'default', +}: ChartProps) { + const chartContainerRef = useRef(null); + const { createChart, getChart, setMainSeries, setVolumeSeries, addOverlaySeries, disposeChart } = + useChartManager(); + + // Use a stable unique ID that changes only when chartId prop changes + const uniqueChartId = useMemo(() => { + return `${chartId}-${Date.now()}`; + }, [chartId]); + const mountedRef = useRef(true); + + // Track component mount state + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + // Cleanup on unmount + disposeChart(uniqueChartId); + }; + }, [disposeChart]); + + // Reset zoom handler + const resetZoom = useCallback(() => { + const chartInstance = getChart(uniqueChartId); + if (chartInstance && !chartInstance.isDisposed && data.length > 0) { + // Get the validated data to ensure we're using the correct time values + const validateData = (rawData: ChartData[]) => { + const seen = new Set(); + return rawData + .map(item => { + const timeInSeconds = + item.time > 10000000000 ? Math.floor(item.time / 1000) : item.time; + return { ...item, time: timeInSeconds }; + }) + .filter(item => { + if (seen.has(item.time)) { + return false; + } + seen.add(item.time); + return true; + }) + .sort((a, b) => a.time - b.time); + }; + + const validatedData = validateData(data); + + if (validatedData.length > 0) { + const firstTime = at(validatedData, 0).time; + const lastTime = at(validatedData, validatedData.length - 1).time; + + // Add some padding (5% on each side) + const timeRange = lastTime - firstTime; + const padding = timeRange * 0.05; + + try { + chartInstance.chart.timeScale().setVisibleRange({ + from: (firstTime - padding) as LightweightCharts.UTCTimestamp, + to: (lastTime + padding) as LightweightCharts.UTCTimestamp, + }); + + chartInstance.chart.timeScale().fitContent(); + } catch (error) { + browserLog.error('Error resetting zoom:', error); + } + } + } + }, [data, getChart]); + + useEffect(() => { + if (!chartContainerRef.current || !data || !data.length) { + return; + } + + let handleResize: (() => void) | undefined; + let isCleanedUp = false; + + // Use requestAnimationFrame to ensure DOM is ready and avoid conflicts + const rafId = requestAnimationFrame(() => { + setTimeout(() => { + if (!chartContainerRef.current || isCleanedUp || !mountedRef.current) { + return; + } + + // Create chart using the chart manager + const chart = createChart(uniqueChartId, chartContainerRef.current, { + width: chartContainerRef.current.clientWidth, + height: typeof height === 'string' ? parseInt(height) : height, + layout: { + background: { + type: LightweightCharts.ColorType.Solid, + color: theme === 'dark' ? '#0f0f0f' : '#ffffff', + }, + textColor: theme === 'dark' ? '#d1d5db' : '#374151', + }, + grid: { + vertLines: { + color: theme === 'dark' ? '#1f2937' : '#e5e7eb', + visible: true, + }, + horzLines: { + color: theme === 'dark' ? '#1f2937' : '#e5e7eb', + visible: true, + }, + }, + crosshair: { + mode: LightweightCharts.CrosshairMode.Normal, + }, + rightPriceScale: { + borderColor: theme === 'dark' ? '#1f2937' : '#e5e7eb', + autoScale: true, + }, + timeScale: { + borderColor: theme === 'dark' ? '#1f2937' : '#e5e7eb', + timeVisible: true, + secondsVisible: false, + rightOffset: 12, + barSpacing: 3, + fixLeftEdge: true, + fixRightEdge: true, + }, + }); + + if (!chart) { + browserLog.error('Failed to create chart'); + return; + } + + // Filter, validate and sort data + const validateAndFilterData = (rawData: ChartData[]) => { + const seen = new Set(); + return rawData + .map(item => { + // Convert timestamp to seconds if it's in milliseconds + const timeInSeconds = + item.time > 10000000000 ? Math.floor(item.time / 1000) : item.time; + + return { + ...item, + time: timeInSeconds as LightweightCharts.UTCTimestamp, + }; + }) + .filter(item => { + if (seen.has(item.time)) { + return false; + } + seen.add(item.time); + return true; + }) + .sort((a, b) => (a.time as number) - (b.time as number)); // Ensure ascending time order + }; + + // Create main series + let mainSeries: LightweightCharts.ISeriesApi | null = null; + + if (type === 'candlestick' && data[0]?.open !== undefined) { + mainSeries = chart.addCandlestickSeries({ + upColor: '#10b981', + downColor: '#ef4444', + borderUpColor: '#10b981', + borderDownColor: '#ef4444', + wickUpColor: '#10b981', + wickDownColor: '#ef4444', + }); + const validData = validateAndFilterData(data); + mainSeries.setData(validData as LightweightCharts.CandlestickData[]); + } else if (type === 'line' || (type === 'candlestick' && data[0]?.value !== undefined)) { + mainSeries = chart.addLineSeries({ + color: '#3b82f6', + lineWidth: 2, + }); + const lineData = data.map(d => ({ + time: d.time, + value: d.value ?? d.close ?? 0, + })); + const validData = validateAndFilterData(lineData); + mainSeries.setData(validData); + } else if (type === 'area') { + mainSeries = chart.addAreaSeries({ + lineColor: '#3b82f6', + topColor: '#3b82f6', + bottomColor: 'rgba(59, 130, 246, 0.1)', + lineWidth: 2, + }); + const areaData = data.map(d => ({ + time: d.time, + value: d.value ?? d.close ?? 0, + })); + const validData = validateAndFilterData(areaData); + mainSeries.setData(validData); + } + + if (mainSeries) { + setMainSeries(uniqueChartId, mainSeries); + } + + // Add volume if available + if (showVolume && data.some(d => d.volume)) { + const volumeSeries = chart.addHistogramSeries({ + color: '#3b82f680', + priceFormat: { + type: 'volume', + }, + priceScaleId: 'volume', + }); + + volumeSeries.priceScale().applyOptions({ + scaleMargins: { + top: 0.8, + bottom: 0, + }, + }); + + const volumeData = validateAndFilterData( + data + .filter(d => d.volume !== undefined) + .map(d => ({ + time: d.time, + value: defined(d.volume), + color: + d.close && d.open ? (d.close >= d.open ? '#10b98140' : '#ef444440') : '#3b82f640', + })) + ); + volumeSeries.setData(volumeData); + setVolumeSeries(uniqueChartId, volumeSeries); + } + + // Add overlay series + overlayData.forEach((overlay, index) => { + const series = chart.addLineSeries({ + color: overlay.color || ['#ff9800', '#4caf50', '#9c27b0', '#f44336'][index % 4], + lineWidth: (overlay.lineWidth || 2) as LightweightCharts.LineWidth, + title: overlay.name, + priceScaleId: index === 0 ? '' : `overlay-${index}`, // First overlay uses main scale + }); + + if (index > 0) { + series.priceScale().applyOptions({ + scaleMargins: { + top: 0.1, + bottom: 0.1, + }, + }); + } + + // Use validateAndFilterData to ensure consistent time handling + const overlayDataWithTime = overlay.data.map(d => ({ + ...d, + time: d.time, // Ensure time field exists + })); + const validatedData = validateAndFilterData(overlayDataWithTime); + series.setData(validatedData); + addOverlaySeries(uniqueChartId, overlay.name, series); + }); + + // Add trade markers + if (tradeMarkers.length > 0 && mainSeries) { + // Sort markers by time to ensure they're in ascending order + const sortedMarkers = [...tradeMarkers].sort((a, b) => a.time - b.time); + const markers: LightweightCharts.SeriesMarker[] = + sortedMarkers.map(marker => ({ + time: marker.time as LightweightCharts.Time, + position: marker.position, + color: marker.color, + shape: marker.shape as LightweightCharts.SeriesMarkerShape, + text: marker.text, + id: marker.id, + size: 1, + })); + mainSeries.setMarkers(markers); + } + + // Fit content with a slight delay to ensure all series are loaded + setTimeout(() => { + // First fit content to calculate proper range + chart.timeScale().fitContent(); + + // Get the validated data to ensure we're using the correct time values + const validatedData = validateAndFilterData(data); + + // Set visible range with some padding + if (validatedData.length > 0) { + const firstTime = at(validatedData, 0).time; + const lastTime = at(validatedData, validatedData.length - 1).time; + + // Add some padding (5% on each side) + const timeRange = (lastTime as number) - (firstTime as number); + const padding = timeRange * 0.05; + + chart.timeScale().setVisibleRange({ + from: ((firstTime as number) - padding) as LightweightCharts.UTCTimestamp, + to: ((lastTime as number) + padding) as LightweightCharts.UTCTimestamp, + }); + } + + // Ensure the chart fits the content properly + chart.timeScale().fitContent(); + }, 100); + + // Enable mouse wheel zoom and touch gestures + chart.applyOptions({ + handleScroll: { + mouseWheel: true, + pressedMouseMove: true, + horzTouchDrag: true, + vertTouchDrag: true, + }, + handleScale: { + mouseWheel: true, + pinch: true, + axisPressedMouseMove: true, + }, + }); + + // Handle resize + handleResize = () => { + if (chartContainerRef.current && !isCleanedUp) { + const chartInstance = getChart(uniqueChartId); + if (chartInstance && !chartInstance.isDisposed) { + try { + chartInstance.chart.applyOptions({ + width: chartContainerRef.current.clientWidth, + }); + } catch (error) { + // Ignore errors if the chart is being disposed + if (!(error instanceof Error) || !error.message?.includes('disposed')) { + browserLog.error('Error resizing chart:', error); + } + } + } + } + }; + + window.addEventListener('resize', handleResize); + }, 0); // End of setTimeout + }); // End of requestAnimationFrame + + // Cleanup + return () => { + isCleanedUp = true; + cancelAnimationFrame(rafId); + if (handleResize) { + window.removeEventListener('resize', handleResize); + } + // Dispose immediately - the chart manager handles cleanup safely + disposeChart(uniqueChartId); + }; + }, [ + data, + height, + type, + showVolume, + theme, + overlayData, + tradeMarkers, + createChart, + getChart, + setMainSeries, + setVolumeSeries, + addOverlaySeries, + disposeChart, + ]); + + return ( +
+
+ +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 23ef7279..0194b368 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -1,375 +1,387 @@ -import { useWebSocket } from '@/hooks/useWebSocket'; -import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; -import { useCallback, useEffect, useState } from 'react'; -import { useNavigate, useParams } from 'react-router-dom'; -import { BacktestConfiguration } from './components/BacktestConfiguration'; -import { BacktestPlayback } from './components/BacktestPlayback'; -import { BacktestTrades } from './components/BacktestTrades'; -import { RunControlsCompact } from './components/RunControlsCompact'; -import { RunsListWithMetrics } from './components/RunsListWithMetrics'; -import { useBacktestV2 } from './hooks/useBacktestV2'; -import type { BacktestConfig } from './types/backtest.types'; - -const baseTabs = [ - { id: 'runs', name: 'Runs' }, - { id: 'settings', name: 'Settings' }, -]; - -const runTabs = [ - { id: 'details', name: 'Details' }, - { id: 'trades', name: 'Trades' }, -]; - -export function BacktestDetailPageV2() { - const { id, runId } = useParams<{ id: string; runId?: string }>(); - const navigate = useNavigate(); - const [activeTab, setActiveTab] = useState('details'); - const [showNewRun, setShowNewRun] = useState(false); - - const { - backtest, - runs, - currentRun, - runResults, - isLoading, - error, - loadBacktest, - updateBacktest, - createRun, - pauseRun, - resumeRun, - updateRunSpeed, - selectRun, - } = useBacktestV2(); - - // WebSocket connection for real-time updates - useWebSocket({ - runId: currentRun?.id || null, - onProgress: (progress, currentDate) => { - // Update the run progress in the UI - if (currentRun) { - // This will trigger a re-render with updated progress - console.log('Progress update:', progress, currentDate); - } - }, - onError: (error) => { - console.error('Run error:', error); - // Reload runs to get updated status - if (id) { - loadBacktest(id); - } - }, - onCompleted: async () => { - // When run completes, reload to get the final results - if (currentRun?.id) { - try { - // Small delay to ensure the results are persisted - await new Promise(resolve => setTimeout(resolve, 500)); - // Force re-select the run to load its results - await selectRun(currentRun.id); - } catch (err) { - console.error('Failed to load completed run results:', err); - } - } - } - }); - - // Load backtest on mount - useEffect(() => { - if (id) { - loadBacktest(id); - } - }, [id, loadBacktest]); - - // Clear mismatched results immediately - useEffect(() => { - if (runResults && currentRun && runResults.runId !== currentRun.id) { - console.warn('Run results mismatch:', { - runResultsId: runResults.runId, - currentRunId: currentRun.id - }); - // Clear the mismatched results immediately to prevent rendering wrong data - // The selectRun effect will load the correct results - } - }, [runResults?.runId, currentRun?.id]); - - // We don't need this effect anymore - it's causing unnecessary re-renders - // The selectRun function already handles clearing mismatched results - - // Select run based on URL parameter with debounce - useEffect(() => { - const timeoutId = setTimeout(() => { - if (runId) { - // If the current run already matches, don't re-select - if (currentRun?.id === runId) { - return; - } - - // Always try to select the run - selectRun will fetch it if not found - selectRun(runId); - - // Show details tab by default when a run is selected - if (activeTab === 'runs') { - setActiveTab('details'); - } - } else if (!runId && currentRun) { - // Clear run selection when navigating away from run URL - selectRun(undefined); - setActiveTab('runs'); - } - }, 50); // Small debounce to prevent rapid switching - - return () => clearTimeout(timeoutId); - }, [runId, currentRun?.id, selectRun, activeTab]); - - // Handle configuration save - const handleConfigSubmit = useCallback(async (config: BacktestConfig) => { - if (!id) return; - - await updateBacktest(id, { - name: config.name, - strategy: config.strategy, - symbols: config.symbols, - startDate: config.startDate.toISOString().split('T')[0], - endDate: config.endDate.toISOString().split('T')[0], - initialCapital: config.initialCapital, - config: { - commission: config.commission, - slippage: config.slippage, - speedMultiplier: config.speedMultiplier, - }, - }); - }, [id, updateBacktest]); - - // Handle new run creation - const handleCreateRun = useCallback(async (speedMultiplier: number) => { - const newRun = await createRun(speedMultiplier); - setShowNewRun(false); - // Navigate to the new run - if (newRun && id) { - navigate(`/backtests/${id}/run/${newRun.id}`); - } - }, [createRun, navigate, id]); - - // Handle rerun - const handleRerun = useCallback(async (speedMultiplier: number | null) => { - // Pass null for max speed (no limit) - const newRun = await createRun(speedMultiplier ?? undefined); - - // Navigate to the new run's URL - if (newRun && id) { - navigate(`/backtests/${id}/run/${newRun.id}`); - } - }, [createRun, navigate, id]); - - // Convert backtest to config format for the form - const backtestConfig: BacktestConfig | undefined = backtest ? { - name: backtest.name, - startDate: new Date(backtest.startDate), - endDate: new Date(backtest.endDate), - initialCapital: backtest.initialCapital, - symbols: backtest.symbols, - strategy: backtest.strategy, - speedMultiplier: 1, - commission: backtest.config?.commission ?? 0.001, - slippage: backtest.config?.slippage ?? 0.0001, - } : undefined; - - const renderTabContent = () => { - // Show message if trying to view run-specific tabs without a run selected - if (!currentRun && ['details', 'trades'].includes(activeTab)) { - return ( -
-
-

Please select a run to view {activeTab}

- -
-
- ); - } - - switch (activeTab) { - case 'runs': - return ( -
-
-

Run History

- -
- - {showNewRun && ( -
-

Start New Run

-

- This will start a new backtest run with the current configuration. -

-
- - -
-
- )} - - -
- ); - case 'settings': - return ( -
- -
- ); - case 'details': - // Only render if we have matching results or no results yet - if (runResults && currentRun && runResults.runId !== currentRun.id) { - return ( -
-
Loading run data...
-
- ); - } - - return ( -
- -
- ); - case 'trades': - return ( -
- -
- ); - default: - return null; - } - }; - - if (!backtest && !isLoading) { - return ( -
-
-

Backtest not found

- -
-
- ); - } - - return ( -
- {/* Header with Tabs */} -
-
-
- -
-

- {backtest?.name || 'Loading...'} - {currentRun && ( - - - Run #{currentRun.runNumber} - - )} -

-

- {backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''} -

-
- - {/* Tabs */} - -
- - {/* Run Controls */} - {currentRun && ( -
- -
- )} -
-
- - {/* Tab Content */} -
- {error && ( -
-

{error}

-
- )} - {renderTabContent()} -
-
- ); -} \ No newline at end of file +import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline'; +import { useCallback, useEffect, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { useWebSocket } from '@/hooks/useWebSocket'; +import { browserLog } from '@/utils/browserLog'; +import { BacktestConfiguration } from './components/BacktestConfiguration'; +import { BacktestPlayback } from './components/BacktestPlayback'; +import { BacktestTrades } from './components/BacktestTrades'; +import { RunControlsCompact } from './components/RunControlsCompact'; +import { RunsListWithMetrics } from './components/RunsListWithMetrics'; +import { useBacktestV2 } from './hooks/useBacktestV2'; +import type { BacktestConfig } from './types/backtest.types'; + +const baseTabs = [ + { id: 'runs', name: 'Runs' }, + { id: 'settings', name: 'Settings' }, +]; + +const runTabs = [ + { id: 'details', name: 'Details' }, + { id: 'trades', name: 'Trades' }, +]; + +export function BacktestDetailPageV2() { + const { id, runId } = useParams<{ id: string; runId?: string }>(); + const navigate = useNavigate(); + const [activeTab, setActiveTab] = useState('details'); + const [showNewRun, setShowNewRun] = useState(false); + + const { + backtest, + runs, + currentRun, + runResults, + isLoading, + error, + loadBacktest, + updateBacktest, + createRun, + pauseRun, + resumeRun, + updateRunSpeed, + selectRun, + } = useBacktestV2(); + + // WebSocket connection for real-time updates + useWebSocket({ + runId: currentRun?.id || null, + onProgress: (progress, currentDate) => { + // Update the run progress in the UI + if (currentRun) { + // This will trigger a re-render with updated progress + browserLog.log('Progress update:', progress, currentDate); + } + }, + onError: error => { + browserLog.error('Run error:', error); + // Reload runs to get updated status + if (id) { + loadBacktest(id); + } + }, + onCompleted: async () => { + // When run completes, reload to get the final results + if (currentRun?.id) { + try { + // Small delay to ensure the results are persisted + await new Promise(resolve => setTimeout(resolve, 500)); + // Force re-select the run to load its results + await selectRun(currentRun.id); + } catch (err) { + browserLog.error('Failed to load completed run results:', err); + } + } + }, + }); + + // Load backtest on mount + useEffect(() => { + if (id) { + loadBacktest(id); + } + }, [id, loadBacktest]); + + // Clear mismatched results immediately + useEffect(() => { + if (runResults && currentRun && runResults.runId !== currentRun.id) { + browserLog.warn('Run results mismatch:', { + runResultsId: runResults.runId, + currentRunId: currentRun.id, + }); + // Clear the mismatched results immediately to prevent rendering wrong data + // The selectRun effect will load the correct results + } + }, [runResults?.runId, currentRun?.id]); + + // We don't need this effect anymore - it's causing unnecessary re-renders + // The selectRun function already handles clearing mismatched results + + // Select run based on URL parameter with debounce + useEffect(() => { + const timeoutId = setTimeout(() => { + if (runId) { + // If the current run already matches, don't re-select + if (currentRun?.id === runId) { + return; + } + + // Always try to select the run - selectRun will fetch it if not found + selectRun(runId); + + // Show details tab by default when a run is selected + if (activeTab === 'runs') { + setActiveTab('details'); + } + } else if (!runId && currentRun) { + // Clear run selection when navigating away from run URL + selectRun(undefined); + setActiveTab('runs'); + } + }, 50); // Small debounce to prevent rapid switching + + return () => clearTimeout(timeoutId); + }, [runId, currentRun?.id, selectRun, activeTab]); + + // Handle configuration save + const handleConfigSubmit = useCallback( + async (config: BacktestConfig) => { + if (!id) { + return; + } + + await updateBacktest(id, { + name: config.name, + strategy: config.strategy, + symbols: config.symbols, + startDate: config.startDate.toISOString().split('T')[0], + endDate: config.endDate.toISOString().split('T')[0], + initialCapital: config.initialCapital, + config: { + commission: config.commission, + slippage: config.slippage, + speedMultiplier: config.speedMultiplier, + }, + }); + }, + [id, updateBacktest] + ); + + // Handle new run creation + const handleCreateRun = useCallback( + async (speedMultiplier: number) => { + const newRun = await createRun(speedMultiplier); + setShowNewRun(false); + // Navigate to the new run + if (newRun && id) { + navigate(`/backtests/${id}/run/${newRun.id}`); + } + }, + [createRun, navigate, id] + ); + + // Handle rerun + const handleRerun = useCallback( + async (speedMultiplier: number | null) => { + // Pass null for max speed (no limit) + const newRun = await createRun(speedMultiplier ?? undefined); + + // Navigate to the new run's URL + if (newRun && id) { + navigate(`/backtests/${id}/run/${newRun.id}`); + } + }, + [createRun, navigate, id] + ); + + // Convert backtest to config format for the form + const backtestConfig: BacktestConfig | undefined = backtest + ? { + name: backtest.name, + startDate: new Date(backtest.startDate), + endDate: new Date(backtest.endDate), + initialCapital: backtest.initialCapital, + symbols: backtest.symbols, + strategy: backtest.strategy, + speedMultiplier: 1, + commission: Number(backtest.config?.commission ?? 0.001), + slippage: Number(backtest.config?.slippage ?? 0.0001), + } + : undefined; + + const renderTabContent = () => { + // Show message if trying to view run-specific tabs without a run selected + if (!currentRun && ['details', 'trades'].includes(activeTab)) { + return ( +
+
+

Please select a run to view {activeTab}

+ +
+
+ ); + } + + switch (activeTab) { + case 'runs': + return ( +
+
+

Run History

+ +
+ + {showNewRun && ( +
+

Start New Run

+

+ This will start a new backtest run with the current configuration. +

+
+ + +
+
+ )} + + +
+ ); + case 'settings': + return ( +
+ +
+ ); + case 'details': + // Only render if we have matching results or no results yet + if (runResults && currentRun && runResults.runId !== currentRun.id) { + return ( +
+
Loading run data...
+
+ ); + } + + return ( +
+ +
+ ); + case 'trades': + return ( +
+ +
+ ); + default: + return null; + } + }; + + if (!backtest && !isLoading) { + return ( +
+
+

Backtest not found

+ +
+
+ ); + } + + return ( +
+ {/* Header with Tabs */} +
+
+
+ +
+

+ {backtest?.name || 'Loading...'} + {currentRun && ( + + - Run #{currentRun.runNumber} + + )} +

+

+ {backtest?.strategy || ''} • {backtest?.symbols.join(', ') || ''} +

+
+ + {/* Tabs */} + +
+ + {/* Run Controls */} + {currentRun && ( +
+ +
+ )} +
+
+ + {/* Tab Content */} +
+ {error && ( +
+

{error}

+
+ )} + {renderTabContent()} +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx index 8cebad0d..c65c15dd 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx @@ -1,151 +1,143 @@ -import { useEffect, useState } from 'react'; -import { useNavigate } from 'react-router-dom'; -import { DataTable } from '@/components/ui/DataTable/DataTable'; -import type { ColumnDef } from '@tanstack/react-table'; -import { PlusIcon } from '@heroicons/react/24/solid'; -import { backtestApiV2, type Backtest } from './services/backtestApiV2'; -import { CreateBacktestDialog } from './components/CreateBacktestDialog'; - -export function BacktestListPageV2() { - const navigate = useNavigate(); - const [backtests, setBacktests] = useState([]); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - const [showCreateDialog, setShowCreateDialog] = useState(false); - - const loadBacktests = async () => { - setIsLoading(true); - setError(null); - try { - const data = await backtestApiV2.listBacktests(); - setBacktests(data); - } catch (err) { - setError('Failed to load backtests'); - console.error(err); - } finally { - setIsLoading(false); - } - }; - - useEffect(() => { - loadBacktests(); - }, []); - - const handleCreateBacktest = async (config: Omit) => { - try { - const newBacktest = await backtestApiV2.createBacktest(config); - await loadBacktests(); - setShowCreateDialog(false); - navigate(`/backtests/${newBacktest.id}`); - } catch (err) { - setError('Failed to create backtest'); - console.error(err); - } - }; - - const columns: ColumnDef[] = [ - { - accessorKey: 'name', - header: 'Name', - size: 200, - cell: ({ row }) => ( -
- {row.original.name} -
- ), - }, - { - accessorKey: 'strategy', - header: 'Strategy', - size: 150, - cell: ({ row }) => ( - - {row.original.strategy} - - ), - }, - { - accessorKey: 'symbols', - header: 'Symbols', - size: 200, - cell: ({ row }) => ( -
- {row.original.symbols.join(', ')} -
- ), - }, - { - accessorKey: 'dateRange', - header: 'Date Range', - size: 200, - cell: ({ row }) => ( -
- {new Date(row.original.startDate).toLocaleDateString()} - {new Date(row.original.endDate).toLocaleDateString()} -
- ), - }, - { - accessorKey: 'initialCapital', - header: 'Initial Capital', - size: 150, - cell: ({ row }) => ( -
- ${row.original.initialCapital.toLocaleString()} -
- ), - }, - { - accessorKey: 'createdAt', - header: 'Created', - size: 180, - cell: ({ row }) => ( -
- {new Date(row.original.createdAt).toLocaleString()} -
- ), - }, - ]; - - return ( -
-
-
-

Backtests

-

- Create and manage backtest configurations -

-
- -
- - {error && ( -
- {error} -
- )} - -
- navigate(`/backtests/${row.id}`)} - height={600} - /> -
- - {showCreateDialog && ( - setShowCreateDialog(false)} - onCreate={handleCreateBacktest} - /> - )} -
- ); -} \ No newline at end of file +import { PlusIcon } from '@heroicons/react/24/solid'; +import type { ColumnDef } from '@tanstack/react-table'; +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { DataTable } from '@/components/ui/DataTable/DataTable'; +import { browserLog } from '@/utils/browserLog'; +import { CreateBacktestDialog } from './components/CreateBacktestDialog'; +import { backtestApiV2, type Backtest } from './services/backtestApiV2'; + +export function BacktestListPageV2() { + const navigate = useNavigate(); + const [backtests, setBacktests] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + const [showCreateDialog, setShowCreateDialog] = useState(false); + + const loadBacktests = async () => { + setIsLoading(true); + setError(null); + try { + const data = await backtestApiV2.listBacktests(); + setBacktests(data); + } catch (err) { + setError('Failed to load backtests'); + browserLog.error(err); + } finally { + setIsLoading(false); + } + }; + + useEffect(() => { + loadBacktests(); + }, []); + + const handleCreateBacktest = async (config: Omit) => { + try { + const newBacktest = await backtestApiV2.createBacktest(config); + await loadBacktests(); + setShowCreateDialog(false); + navigate(`/backtests/${newBacktest.id}`); + } catch (err) { + setError('Failed to create backtest'); + browserLog.error(err); + } + }; + + const columns: ColumnDef[] = [ + { + accessorKey: 'name', + header: 'Name', + size: 200, + cell: ({ row }) =>
{row.original.name}
, + }, + { + accessorKey: 'strategy', + header: 'Strategy', + size: 150, + cell: ({ row }) => ( + {row.original.strategy} + ), + }, + { + accessorKey: 'symbols', + header: 'Symbols', + size: 200, + cell: ({ row }) => ( +
{row.original.symbols.join(', ')}
+ ), + }, + { + accessorKey: 'dateRange', + header: 'Date Range', + size: 200, + cell: ({ row }) => ( +
+ {new Date(row.original.startDate).toLocaleDateString()} -{' '} + {new Date(row.original.endDate).toLocaleDateString()} +
+ ), + }, + { + accessorKey: 'initialCapital', + header: 'Initial Capital', + size: 150, + cell: ({ row }) => ( +
+ ${row.original.initialCapital.toLocaleString()} +
+ ), + }, + { + accessorKey: 'createdAt', + header: 'Created', + size: 180, + cell: ({ row }) => ( +
+ {new Date(row.original.createdAt).toLocaleString()} +
+ ), + }, + ]; + + return ( +
+
+
+

Backtests

+

Create and manage backtest configurations

+
+ +
+ + {error && ( +
+ {error} +
+ )} + +
+ navigate(`/backtests/${row.id}`)} + height={600} + /> +
+ + {showCreateDialog && ( + setShowCreateDialog(false)} + onCreate={handleCreateBacktest} + /> + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestChart.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestChart.tsx index 6f420ea0..55071e7b 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestChart.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestChart.tsx @@ -1,188 +1,220 @@ -import type { BacktestResult } from '../types/backtest.types'; -import { useState, useMemo, memo } from 'react'; -import { Chart } from '../../../components/charts/Chart'; -import { ChartContainer } from './ChartContainer'; - -interface ExtendedBacktestResult extends BacktestResult { - equity?: Array<{ date: string; value: number }>; - ohlcData?: Record>; - runId?: string; -} - -interface ExtendedTrade { - id: string; - timestamp: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - pnl?: number; - positionAfter: number; - entryPrice?: number; - entryDate?: string; - date?: string; -} - -interface BacktestChartProps { - result: ExtendedBacktestResult | null; - isLoading: boolean; -} - -// Memoize the component to prevent unnecessary re-renders -export const BacktestChart = memo(function BacktestChart({ result, isLoading }: BacktestChartProps) { - const [selectedSymbol, setSelectedSymbol] = useState(''); - - const chartData = useMemo(() => { - if (!result || (!result.equity && !result.performanceData) || (!result.ohlcData && !result.trades)) return null; - - const symbols = result.ohlcData ? Object.keys(result.ohlcData) : (result.trades ? [...new Set(result.trades.map(t => t.symbol))] : []); - const symbol = selectedSymbol || symbols[0] || ''; - const ohlcData = result.ohlcData?.[symbol] || []; - - // Remove excessive logging in production - // Log only on significant changes - if (process.env.NODE_ENV === 'development' && ohlcData.length > 0) { - // Use a simple hash to detect actual data changes - const dataHash = `${symbols.length}-${result.equity?.length || result.performanceData?.length}-${ohlcData.length}`; - if ((window as any).__lastDataHash !== dataHash) { - (window as any).__lastDataHash = dataHash; - console.log('BacktestChart data updated:', { - symbols, - selectedSymbol, - symbol, - ohlcDataKeys: result.ohlcData ? Object.keys(result.ohlcData) : [], - equityLength: result.equity?.length || result.performanceData?.length, - tradesLength: result.trades?.length - }); - } - } - - const equityData = result.equity - ? result.equity - .filter(e => e && e.date && e.value != null) - .map(e => ({ - time: new Date(e.date).getTime() / 1000, - value: e.value - })) - : result.performanceData - ?.filter(p => p && p.timestamp && p.portfolioValue != null) - .map(p => ({ - time: new Date(p.timestamp).getTime() / 1000, - value: p.portfolioValue - })) || []; - - // Find trades for this symbol - const symbolTrades = result.trades?.filter(t => t.symbol === symbol) || []; - console.log('Symbol trades for', symbol, ':', symbolTrades); - - const tradeMarkers = symbolTrades - .filter(trade => { - // Check multiple possible field names - const extTrade = trade as ExtendedTrade; - const hasPrice = extTrade.price != null || extTrade.entryPrice != null; - const hasTime = extTrade.timestamp != null || extTrade.entryDate != null || extTrade.date != null; - return hasPrice && hasTime; - }) - .map(trade => { - // Use whatever field names are present - const extTrade = trade as ExtendedTrade; - const price = extTrade.price || extTrade.entryPrice || 0; - const timestamp = extTrade.timestamp || extTrade.entryDate || extTrade.date || ''; - const side = extTrade.side || (extTrade.quantity > 0 ? 'buy' : 'sell'); - - return { - time: new Date(timestamp).getTime() / 1000, - position: 'belowBar' as const, - color: side === 'buy' ? '#10b981' : '#ef4444', - shape: (side === 'buy' ? 'arrowUp' : 'arrowDown') as const, - text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`, - price: price - }; - }); - - console.log('Trade markers:', tradeMarkers); - - const processedOhlcData = ohlcData - .filter(d => d && d.timestamp != null && d.open != null && d.high != null && d.low != null && d.close != null) - .map(d => ({ - time: d.timestamp / 1000, // timestamp is already in milliseconds - open: d.open, - high: d.high, - low: d.low, - close: d.close, - volume: d.volume || 0 - })); - - return { - ohlcData: processedOhlcData, - equityData, - tradeMarkers, - symbols - }; - }, [result, selectedSymbol]); - - if (isLoading) { - return ( -
-
-
- ); - } - - if (!result || !chartData) { - return ( -
-

Run a backtest to see the equity curve and price chart.

-
- ); - } - - return ( -
- {chartData.symbols.length > 1 && ( -
- - -
- )} - -
- - {(height) => ( - - )} - -
-
- ); -}); \ No newline at end of file +import { memo, useMemo, useState } from 'react'; +import { browserLog } from '@/utils/browserLog'; +import { Chart } from '../../../components/charts/Chart'; +import type { PerformanceDataPoint } from '../types/backtest.types'; +import { ChartContainer } from './ChartContainer'; + +interface ExtendedBacktestResult + extends Pick { + performanceData?: PerformanceDataPoint[]; + runId?: string; + id?: string; +} + +interface ExtendedTrade { + id: string; + timestamp: string; + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + price: number; + commission: number; + pnl?: number; + positionAfter: number; + entryPrice?: number; + entryDate?: string; + date?: string; +} + +interface BacktestChartProps { + result: ExtendedBacktestResult | null; + isLoading: boolean; +} + +// Memoize the component to prevent unnecessary re-renders +export const BacktestChart = memo(function BacktestChart({ + result, + isLoading, +}: BacktestChartProps) { + const [selectedSymbol, setSelectedSymbol] = useState(''); + + const chartData = useMemo(() => { + if ( + !result || + (!result.equity && !result.performanceData) || + (!result.ohlcData && !result.trades) + ) { + return null; + } + + const symbols = result.ohlcData + ? Object.keys(result.ohlcData) + : result.trades + ? [...new Set(result.trades.map(t => t.symbol))] + : []; + const symbol = selectedSymbol || symbols[0] || ''; + const ohlcData = result.ohlcData?.[symbol] || []; + + // Remove excessive logging in production + // Log only on significant changes + if (process.env.NODE_ENV === 'development' && ohlcData.length > 0) { + // Use a simple hash to detect actual data changes + const dataHash = `${symbols.length}-${result.equity?.length || result.performanceData?.length}-${ohlcData.length}`; + if ((window as Window & { __lastDataHash?: string }).__lastDataHash !== dataHash) { + (window as Window & { __lastDataHash?: string }).__lastDataHash = dataHash; + browserLog.log('BacktestChart data updated:', { + symbols, + selectedSymbol, + symbol, + ohlcDataKeys: result.ohlcData ? Object.keys(result.ohlcData) : [], + equityLength: result.equity?.length || result.performanceData?.length, + tradesLength: result.trades?.length, + }); + } + } + + const equityData = result.equity + ? result.equity + .filter(e => e && e.date && e.value !== null && e.value !== undefined) + .map(e => ({ + time: new Date(e.date).getTime() / 1000, + value: e.value, + })) + : result.performanceData + ?.filter( + p => p && p.timestamp && p.portfolioValue !== null && p.portfolioValue !== undefined + ) + .map(p => ({ + time: new Date(p.timestamp).getTime() / 1000, + value: p.portfolioValue, + })) || []; + + // Find trades for this symbol + const symbolTrades = result.trades?.filter(t => t.symbol === symbol) || []; + browserLog.log('Symbol trades for', symbol, ':', symbolTrades); + + const tradeMarkers = symbolTrades + .filter(trade => { + // Check multiple possible field names + const extTrade = trade as ExtendedTrade; + const hasPrice = + (extTrade.price !== null && extTrade.price !== undefined) || + (extTrade.entryPrice !== null && extTrade.entryPrice !== undefined); + const hasTime = + (extTrade.timestamp !== null && extTrade.timestamp !== undefined) || + (extTrade.entryDate !== null && extTrade.entryDate !== undefined) || + (extTrade.date !== null && extTrade.date !== undefined); + return hasPrice && hasTime; + }) + .map(trade => { + // Use whatever field names are present + const extTrade = trade as ExtendedTrade; + const price = extTrade.price || extTrade.entryPrice || 0; + const timestamp = extTrade.timestamp || extTrade.entryDate || extTrade.date || ''; + const side = extTrade.side || (extTrade.quantity > 0 ? 'buy' : 'sell'); + + return { + time: new Date(timestamp).getTime() / 1000, + position: 'belowBar' as const, + color: side === 'buy' ? '#10b981' : '#ef4444', + shape: side === 'buy' ? ('arrowUp' as const) : ('arrowDown' as const), + text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`, + price: price, + }; + }); + + browserLog.log('Trade markers:', tradeMarkers); + + const processedOhlcData = ohlcData + .filter( + d => + d && + d.timestamp !== null && + d.timestamp !== undefined && + d.open !== null && + d.open !== undefined && + d.high !== null && + d.high !== undefined && + d.low !== null && + d.low !== undefined && + d.close !== null && + d.close !== undefined + ) + .map(d => ({ + time: d.timestamp / 1000, // timestamp is already in milliseconds + open: d.open, + high: d.high, + low: d.low, + close: d.close, + volume: d.volume || 0, + })); + + return { + ohlcData: processedOhlcData, + equityData, + tradeMarkers, + symbols, + }; + }, [result, selectedSymbol]); + + if (isLoading) { + return ( +
+
+
+ ); + } + + if (!result || !chartData) { + return ( +
+

+ Run a backtest to see the equity curve and price chart. +

+
+ ); + } + + return ( +
+ {chartData.symbols.length > 1 && ( +
+ + +
+ )} + +
+ + {height => ( + + )} + +
+
+ ); +}); diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx index 20fa1c86..2cf47f2a 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestPlayback.tsx @@ -1,228 +1,258 @@ -import { useState, memo } from 'react'; -import { BacktestChart } from './BacktestChart'; -import { ErrorBoundary } from '../../../components/ErrorBoundary'; -import { CompactPerformanceMetrics } from './CompactPerformanceMetrics'; -import { PositionsSummary } from './PositionsSummary'; - -interface BacktestPlaybackProps { - result: any | null; - isLoading: boolean; -} - -export const BacktestPlayback = memo(function BacktestPlayback({ result, isLoading }: BacktestPlaybackProps) { - const [showPositions, setShowPositions] = useState(false); - - if (isLoading) { - return ( -
-
Loading playback data...
-
- ); - } - - if (!result) { - return ( -
-
No data available
-
- ); - } - - // Get positions from the result - let openPositions: any[] = []; - let closedPositions: any[] = []; - - if (result.positions) { - if (Array.isArray(result.positions)) { - result.positions.forEach((p: any) => { - if (p.quantity !== 0) { - openPositions.push(p); - } else if (p.realizedPnl !== 0) { - closedPositions.push(p); - } - }); - } else if (typeof result.positions === 'object') { - // Convert positions object to array - Object.entries(result.positions).forEach(([symbol, position]: [string, any]) => { - const pos = { symbol, ...position }; - if (position.quantity !== 0) { - openPositions.push(pos); - } else if (position.realizedPnl !== 0) { - closedPositions.push(pos); - } - }); - } - } - - return ( -
- {/* Chart Section */} -
- -
-

Chart failed to load

- -
-
- } - > - - -
- - {/* Performance Metrics and Positions - Fixed height section */} -
- - setShowPositions(true)} - /> -
- - {/* Detailed Positions View - Optional expanded view */} - {showPositions && (openPositions.length > 0 || closedPositions.length > 0) && ( -
-
-
-

- All Positions -

- -
- -
- {openPositions.length > 0 && ( -
-

Open Positions ({openPositions.length})

-
-
-
Symbol
-
Side
-
Quantity
-
Entry Price
-
Current Price
-
P&L
-
- - {openPositions.map((position, index) => { - const quantity = position.quantity || 0; - const avgPrice = position.averagePrice || position.avgPrice || 0; - const currentPrice = position.currentPrice || position.lastPrice || avgPrice; - const side = quantity > 0 ? 'long' : 'short'; - const absQuantity = Math.abs(quantity); - const pnl = (currentPrice - avgPrice) * quantity; - const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0; - - return ( -
-
{position.symbol}
-
- {side.toUpperCase()} -
-
{absQuantity}
-
- ${avgPrice.toFixed(2)} -
-
- ${currentPrice.toFixed(2)} -
-
= 0 ? 'text-success' : 'text-error'}`}> - ${pnl.toFixed(2)} ({pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%) -
-
- ); - })} -
-
- )} - - {closedPositions.length > 0 && ( -
-

Closed Positions ({closedPositions.length})

-
- {closedPositions.map((position, index) => ( -
-
- {position.symbol} - Closed -
-
-
= 0 ? 'text-success' : 'text-error'}`}> - Realized P&L: ${position.realizedPnl.toFixed(2)} -
-
-
- ))} -
-
- )} - -
-
-
Unrealized P&L
-
{ - const quantity = p.quantity || 0; - const avgPrice = p.averagePrice || p.avgPrice || 0; - const currentPrice = p.currentPrice || p.lastPrice || avgPrice; - return sum + ((currentPrice - avgPrice) * quantity); - }, 0) >= 0 ? 'text-success' : 'text-error' - }`}> - ${openPositions.reduce((sum, p) => { - const quantity = p.quantity || 0; - const avgPrice = p.averagePrice || p.avgPrice || 0; - const currentPrice = p.currentPrice || p.lastPrice || avgPrice; - return sum + ((currentPrice - avgPrice) * quantity); - }, 0).toFixed(2)} -
-
-
-
Realized P&L
-
sum + (p.realizedPnl || 0), 0) >= 0 ? 'text-success' : 'text-error' - }`}> - ${closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0).toFixed(2)} -
-
-
-
Total P&L
-
{ - const quantity = p.quantity || 0; - const avgPrice = p.averagePrice || p.avgPrice || 0; - const currentPrice = p.currentPrice || p.lastPrice || avgPrice; - return sum + ((currentPrice - avgPrice) * quantity); - }, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)) >= 0 ? 'text-success' : 'text-error' - }`}> - ${(openPositions.reduce((sum, p) => { - const quantity = p.quantity || 0; - const avgPrice = p.averagePrice || p.avgPrice || 0; - const currentPrice = p.currentPrice || p.lastPrice || avgPrice; - return sum + ((currentPrice - avgPrice) * quantity); - }, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)).toFixed(2)} -
-
-
-
-
-
- )} -
- ); -}); \ No newline at end of file +import { memo, useState } from 'react'; +import { ErrorBoundary } from '../../../components/ErrorBoundary'; +import type { RunResult } from '../services/backtestApiV2'; +import type { Position } from '../types/backtest.types'; +import { BacktestChart } from './BacktestChart'; +import { CompactPerformanceMetrics } from './CompactPerformanceMetrics'; +import { PositionsSummary } from './PositionsSummary'; + +interface BacktestPlaybackProps { + result: RunResult | null; + isLoading: boolean; +} + +export const BacktestPlayback = memo(function BacktestPlayback({ + result, + isLoading, +}: BacktestPlaybackProps) { + const [showPositions, setShowPositions] = useState(false); + + if (isLoading) { + return ( +
+
Loading playback data...
+
+ ); + } + + if (!result) { + return ( +
+
No data available
+
+ ); + } + + // Get positions from the result + const openPositions: Position[] = []; + const closedPositions: Position[] = []; + + if (result.positions) { + if (Array.isArray(result.positions)) { + result.positions.forEach(p => { + if (p.quantity !== 0) { + openPositions.push(p); + } else if (p.realizedPnl !== 0) { + closedPositions.push(p); + } + }); + } else if (typeof result.positions === 'object') { + // Convert positions object to array + Object.entries(result.positions).forEach(([symbol, position]) => { + const pos = { symbol, ...position }; + if (position.quantity !== 0) { + openPositions.push(pos); + } else if (position.realizedPnl !== 0) { + closedPositions.push(pos); + } + }); + } + } + + return ( +
+ {/* Chart Section */} +
+ +
+

Chart failed to load

+ +
+
+ } + > + + +
+ + {/* Performance Metrics and Positions - Fixed height section */} +
+ + setShowPositions(true)} + /> +
+ + {/* Detailed Positions View - Optional expanded view */} + {showPositions && (openPositions.length > 0 || closedPositions.length > 0) && ( +
+
+
+

All Positions

+ +
+ +
+ {openPositions.length > 0 && ( +
+

+ Open Positions ({openPositions.length}) +

+
+
+
Symbol
+
Side
+
Quantity
+
Entry Price
+
Current Price
+
P&L
+
+ + {openPositions.map((position, index) => { + const quantity = position.quantity || 0; + const avgPrice = position.averagePrice || position.avgPrice || 0; + const currentPrice = position.currentPrice || position.lastPrice || avgPrice; + const side = quantity > 0 ? 'long' : 'short'; + const absQuantity = Math.abs(quantity); + const pnl = (currentPrice - avgPrice) * quantity; + const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0; + + return ( +
+
{position.symbol}
+
+ {side.toUpperCase()} +
+
{absQuantity}
+
${avgPrice.toFixed(2)}
+
+ ${currentPrice.toFixed(2)} +
+
= 0 ? 'text-success' : 'text-error'}`} + > + ${pnl.toFixed(2)} ({pnlPercent >= 0 ? '+' : ''} + {pnlPercent.toFixed(2)}%) +
+
+ ); + })} +
+
+ )} + + {closedPositions.length > 0 && ( +
+

+ Closed Positions ({closedPositions.length}) +

+
+ {closedPositions.map((position, index) => ( +
+
+ {position.symbol} + Closed +
+
+
= 0 ? 'text-success' : 'text-error'}`} + > + Realized P&L: ${position.realizedPnl.toFixed(2)} +
+
+
+ ))} +
+
+ )} + +
+
+
Unrealized P&L
+
{ + const quantity = p.quantity || 0; + const avgPrice = p.averagePrice || p.avgPrice || 0; + const currentPrice = p.currentPrice || p.lastPrice || avgPrice; + return sum + (currentPrice - avgPrice) * quantity; + }, 0) >= 0 + ? 'text-success' + : 'text-error' + }`} + > + $ + {openPositions + .reduce((sum, p) => { + const quantity = p.quantity || 0; + const avgPrice = p.averagePrice || p.avgPrice || 0; + const currentPrice = p.currentPrice || p.lastPrice || avgPrice; + return sum + (currentPrice - avgPrice) * quantity; + }, 0) + .toFixed(2)} +
+
+
+
Realized P&L
+
sum + (p.realizedPnl || 0), 0) >= 0 + ? 'text-success' + : 'text-error' + }`} + > + ${closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0).toFixed(2)} +
+
+
+
Total P&L
+
{ + const quantity = p.quantity || 0; + const avgPrice = p.averagePrice || p.avgPrice || 0; + const currentPrice = p.currentPrice || p.lastPrice || avgPrice; + return sum + (currentPrice - avgPrice) * quantity; + }, 0) + + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) >= + 0 + ? 'text-success' + : 'text-error' + }`} + > + $ + {( + openPositions.reduce((sum, p) => { + const quantity = p.quantity || 0; + const avgPrice = p.averagePrice || p.avgPrice || 0; + const currentPrice = p.currentPrice || p.lastPrice || avgPrice; + return sum + (currentPrice - avgPrice) * quantity; + }, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) + ).toFixed(2)} +
+
+
+
+
+
+ )} +
+ ); +}); diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestTrades.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestTrades.tsx index f6e47cc8..b5eb91dc 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestTrades.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestTrades.tsx @@ -1,246 +1,251 @@ -import type { BacktestResult } from '../types/backtest.types'; -import { DataTable } from '@/components/ui/DataTable'; -import type { ColumnDef } from '@tanstack/react-table'; - -interface BacktestTradesProps { - result: any | null; - isLoading: boolean; -} - -export function BacktestTrades({ result, isLoading }: BacktestTradesProps) { - if (isLoading) { - return ( -
-
- {[...Array(5)].map((_, i) => ( -
- ))} -
-
- ); - } - - if (!result || !result.trades || result.trades.length === 0) { - return ( -
-

No trades executed in this backtest.

-
- ); - } - - // Add debug logging - console.log('Trades data:', result.trades); - - const columns: ColumnDef[] = [ - { - accessorKey: 'symbol', - header: 'Symbol', - size: 100, - cell: ({ getValue }) => ( - {getValue() as string} - ), - }, - { - id: 'side', - header: 'Side', - size: 80, - cell: ({ row }) => { - const trade = row.original; - const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell'); - return ( - - {side.toUpperCase()} - - ); - }, - }, - { - id: 'date', - header: 'Date', - size: 180, - cell: ({ row }) => { - const trade = row.original; - const date = trade.timestamp || trade.entryDate || trade.date; - return ( - - {date ? new Date(date).toLocaleString() : '-'} - - ); - }, - }, - { - id: 'price', - header: 'Price', - size: 100, - cell: ({ row }) => { - const trade = row.original; - const price = trade.price || trade.entryPrice; - return ( - - ${price != null ? price.toFixed(2) : '0.00'} - - ); - }, - }, - { - accessorKey: 'quantity', - header: 'Quantity', - size: 80, - cell: ({ getValue }) => { - const qty = Math.abs(getValue() as number || 0); - return {qty}; - }, - }, - { - accessorKey: 'commission', - header: 'Commission', - size: 100, - cell: ({ getValue }) => { - const commission = getValue() as number || 0; - return ( - - ${commission.toFixed(2)} - - ); - }, - }, - { - id: 'pnl', - header: 'P&L', - size: 100, - cell: ({ row }) => { - const trade = row.original; - const pnl = trade.pnl || trade.realizedPnl || 0; - return ( - = 0 ? 'text-success' : 'text-error' - }`}> - ${pnl.toFixed(2)} - - ); - }, - }, - ]; - - // Calculate trade statistics - const tradeStats = result.trades.reduce((stats: any, trade: any) => { - const pnl = trade.pnl || trade.realizedPnl || 0; - if (pnl > 0) { - stats.wins++; - stats.totalWin += pnl; - } else if (pnl < 0) { - stats.losses++; - stats.totalLoss += Math.abs(pnl); - } - stats.totalPnL += pnl; - return stats; - }, { wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 }); - - const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0; - - return ( -
-
-
-

Total Trades

-

{result.trades.length}

-
-
-

Win Rate

-

{winRate.toFixed(1)}%

-
-
-

Wins

-

{tradeStats.wins}

-
-
-

Losses

-

{tradeStats.losses}

-
-
-

Total P&L

-

= 0 ? 'text-success' : 'text-error'}`}> - ${tradeStats.totalPnL.toFixed(2)} -

-
-
- - - - {result.positions && Object.keys(result.positions).length > 0 && (() => { - const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({ - symbol, - ...position - })); - - const positionColumns: ColumnDef[] = [ - { - accessorKey: 'symbol', - header: 'Symbol', - size: 100, - cell: ({ getValue }) => ( - {getValue() as string} - ), - }, - { - accessorKey: 'quantity', - header: 'Quantity', - size: 100, - cell: ({ getValue }) => ( - {getValue() as number || 0} - ), - }, - { - accessorKey: 'averagePrice', - header: 'Avg Price', - size: 120, - cell: ({ getValue }) => { - const price = getValue() as number; - return ( - - ${price != null ? price.toFixed(2) : '0.00'} - - ); - }, - }, - { - accessorKey: 'unrealizedPnl', - header: 'Unrealized P&L', - size: 150, - cell: ({ getValue }) => { - const pnl = getValue() as number || 0; - return ( - = 0 ? 'text-success' : 'text-error' - }`}> - ${pnl != null ? pnl.toFixed(2) : '0.00'} - - ); - }, - }, - ]; - - return ( -
-

Open Positions

- -
- ); - })()} -
- ); -} \ No newline at end of file +import type { ColumnDef } from '@tanstack/react-table'; +import { DataTable } from '@/components/ui/DataTable'; +import { browserLog } from '@/utils/browserLog'; +import type { RunResult } from '../services/backtestApiV2'; +import type { Trade } from '../types/backtest.types'; + +interface BacktestTradesProps { + result: RunResult | null; + isLoading: boolean; +} + +export function BacktestTrades({ result, isLoading }: BacktestTradesProps) { + if (isLoading) { + return ( +
+
+ {[...Array(5)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + if (!result || !result.trades || result.trades.length === 0) { + return ( +
+

No trades executed in this backtest.

+
+ ); + } + + // Add debug logging + browserLog.log('Trades data:', result.trades); + + const columns: ColumnDef[] = [ + { + accessorKey: 'symbol', + header: 'Symbol', + size: 100, + cell: ({ getValue }) => ( + {getValue() as string} + ), + }, + { + id: 'side', + header: 'Side', + size: 80, + cell: ({ row }) => { + const trade = row.original; + const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell'); + return ( + + {side.toUpperCase()} + + ); + }, + }, + { + id: 'date', + header: 'Date', + size: 180, + cell: ({ row }) => { + const trade = row.original; + const date = trade.timestamp || trade.entryDate || trade.date; + return ( + + {date ? new Date(date).toLocaleString() : '-'} + + ); + }, + }, + { + id: 'price', + header: 'Price', + size: 100, + cell: ({ row }) => { + const trade = row.original; + const price = trade.price || trade.entryPrice; + return ( + + ${price !== null && price !== undefined ? price.toFixed(2) : '0.00'} + + ); + }, + }, + { + accessorKey: 'quantity', + header: 'Quantity', + size: 80, + cell: ({ getValue }) => { + const qty = Math.abs((getValue() as number) || 0); + return {qty}; + }, + }, + { + accessorKey: 'commission', + header: 'Commission', + size: 100, + cell: ({ getValue }) => { + const commission = (getValue() as number) || 0; + return ${commission.toFixed(2)}; + }, + }, + { + id: 'pnl', + header: 'P&L', + size: 100, + cell: ({ row }) => { + const trade = row.original; + const pnl = trade.pnl || trade.realizedPnl || 0; + return ( + = 0 ? 'text-success' : 'text-error'}`}> + ${pnl.toFixed(2)} + + ); + }, + }, + ]; + + // Calculate trade statistics + const tradeStats = result.trades.reduce( + (stats, trade) => { + const pnl = trade.pnl || trade.realizedPnl || 0; + if (pnl > 0) { + stats.wins++; + stats.totalWin += pnl; + } else if (pnl < 0) { + stats.losses++; + stats.totalLoss += Math.abs(pnl); + } + stats.totalPnL += pnl; + return stats; + }, + { wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 } + ); + + const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0; + + return ( +
+
+
+

Total Trades

+

{result.trades.length}

+
+
+

Win Rate

+

{winRate.toFixed(1)}%

+
+
+

Wins

+

{tradeStats.wins}

+
+
+

Losses

+

{tradeStats.losses}

+
+
+

Total P&L

+

= 0 ? 'text-success' : 'text-error'}`} + > + ${tradeStats.totalPnL.toFixed(2)} +

+
+
+ + + + {result.positions && + Object.keys(result.positions).length > 0 && + (() => { + const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({ + symbol, + ...position, + })); + + const positionColumns: ColumnDef<(typeof positionsArray)[0]>[] = [ + { + accessorKey: 'symbol', + header: 'Symbol', + size: 100, + cell: ({ getValue }) => ( + + {getValue() as string} + + ), + }, + { + accessorKey: 'quantity', + header: 'Quantity', + size: 100, + cell: ({ getValue }) => ( + {(getValue() as number) || 0} + ), + }, + { + accessorKey: 'averagePrice', + header: 'Avg Price', + size: 120, + cell: ({ getValue }) => { + const price = getValue() as number; + return ( + + ${price !== null && price !== undefined ? price.toFixed(2) : '0.00'} + + ); + }, + }, + { + accessorKey: 'unrealizedPnl', + header: 'Unrealized P&L', + size: 150, + cell: ({ getValue }) => { + const pnl = (getValue() as number) || 0; + return ( + = 0 ? 'text-success' : 'text-error'}`} + > + ${pnl !== null && pnl !== undefined ? pnl.toFixed(2) : '0.00'} + + ); + }, + }, + ]; + + return ( +
+

Open Positions

+ +
+ ); + })()} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/ChartContainer.tsx b/apps/stock/web-app/src/features/backtest/components/ChartContainer.tsx index bf8afd44..347f3614 100644 --- a/apps/stock/web-app/src/features/backtest/components/ChartContainer.tsx +++ b/apps/stock/web-app/src/features/backtest/components/ChartContainer.tsx @@ -1,42 +1,44 @@ -import { useRef, useEffect, useState, ReactNode } from 'react'; - -interface ChartContainerProps { - children: (height: number) => ReactNode; - className?: string; -} - -export function ChartContainer({ children, className = '' }: ChartContainerProps) { - const containerRef = useRef(null); - const [height, setHeight] = useState(500); // Default height - - useEffect(() => { - if (!containerRef.current) return; - - const resizeObserver = new ResizeObserver((entries) => { - for (const entry of entries) { - const { height } = entry.contentRect; - if (height > 0) { - setHeight(Math.floor(height)); - } - } - }); - - resizeObserver.observe(containerRef.current); - - // Initial measurement - const initialHeight = containerRef.current.clientHeight; - if (initialHeight > 0) { - setHeight(initialHeight); - } - - return () => { - resizeObserver.disconnect(); - }; - }, []); - - return ( -
- {children(height)} -
- ); -} \ No newline at end of file +import { useEffect, useRef, useState, type ReactNode } from 'react'; + +interface ChartContainerProps { + children: (height: number) => ReactNode; + className?: string; +} + +export function ChartContainer({ children, className = '' }: ChartContainerProps) { + const containerRef = useRef(null); + const [height, setHeight] = useState(500); // Default height + + useEffect(() => { + if (!containerRef.current) { + return; + } + + const resizeObserver = new ResizeObserver(entries => { + for (const entry of entries) { + const { height } = entry.contentRect; + if (height > 0) { + setHeight(Math.floor(height)); + } + } + }); + + resizeObserver.observe(containerRef.current); + + // Initial measurement + const initialHeight = containerRef.current.clientHeight; + if (initialHeight > 0) { + setHeight(initialHeight); + } + + return () => { + resizeObserver.disconnect(); + }; + }, []); + + return ( +
+ {children(height)} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx b/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx index 63617eec..c9828696 100644 --- a/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics.tsx @@ -1,297 +1,350 @@ -import type { BacktestResult } from '../types/backtest.types'; - -interface ExtendedMetrics { - // Core metrics - totalReturn?: number; - sharpeRatio?: number; - maxDrawdown?: number; - winRate?: number; - totalProfit?: number; - profitFactor?: number; - totalTrades?: number; - avgWin?: number; - avgLoss?: number; - expectancy?: number; - sortinoRatio?: number; - calmarRatio?: number; - profitableTrades?: number; - - // Extended metrics from orchestrator - annualizedReturn?: number; - volatility?: number; - avgHoldingPeriod?: number; - maxConsecutiveLosses?: number; - maxConsecutiveWins?: number; - payoffRatio?: number; - largestWin?: number; - largestLoss?: number; - avgWinLoss?: number; - skewness?: number; - kurtosis?: number; - tailRatio?: number; - kellyFraction?: number; - informationRatio?: number; - avgTradesPerDay?: number; -} - -interface CompactPerformanceMetricsProps { - result: any | null; - isLoading: boolean; -} - -export function CompactPerformanceMetrics({ result, isLoading }: CompactPerformanceMetricsProps) { - if (isLoading || !result) { - return null; - } - - const metrics = result.metrics as ExtendedMetrics; - const analytics = result.analytics || {}; - - // Merge metrics from both sources - const allMetrics = { - ...metrics, - ...analytics, - // Override with metrics values if they exist - ...metrics - }; - - // Calculate totalProfit if not provided - const totalProfit = allMetrics.totalProfit ?? - (allMetrics.totalReturn && result.config?.initialCapital ? - allMetrics.totalReturn * result.config.initialCapital : - undefined); - - const formatValue = (value: number | undefined, format: 'percent' | 'number' | 'currency', decimals = 2) => { - if (value === undefined || value === null) return '-'; - - switch (format) { - case 'percent': - return `${(value * 100).toFixed(decimals)}%`; - case 'currency': - const prefix = value < 0 ? '-$' : '$'; - return `${prefix}${Math.abs(value).toFixed(decimals)}`; - case 'number': - return value.toFixed(decimals); - } - }; - - const getColorClass = (value: number | undefined, thresholds: { good: number; warning?: number }) => { - if (value === undefined || value === null) return 'text-text-secondary'; - - if (thresholds.warning !== undefined) { - if (value >= thresholds.good) return 'text-success'; - if (value >= thresholds.warning) return 'text-warning'; - return 'text-error'; - } - - return value >= thresholds.good ? 'text-success' : 'text-error'; - }; - - return ( -
-

Performance Analytics

- -
- {/* Column 1 - Return Metrics */} -
-
- Total Return - - {formatValue(allMetrics.totalReturn, 'percent')} - -
- -
- Sharpe Ratio - - {formatValue(allMetrics.sharpeRatio, 'number')} - -
- -
- Max Drawdown - - {formatValue(allMetrics.maxDrawdown, 'percent')} - -
- -
- Win Rate - - {formatValue(allMetrics.winRate, 'percent', 1)} - -
- -
- Total Profit - - {formatValue(totalProfit, 'currency')} - -
-
- - {/* Column 2 - Risk Metrics */} -
-
- Profit Factor - - {formatValue(allMetrics.profitFactor, 'number')} - -
- -
- Total Trades - - {allMetrics.totalTrades ?? '-'} - -
- -
- Avg Win/Loss - - {formatValue(allMetrics.avgWin, 'currency')} - / - {formatValue(allMetrics.avgLoss, 'currency')} - -
- -
- Expectancy - - {formatValue(allMetrics.expectancy, 'currency')} - -
- -
- Sortino Ratio - - {formatValue(allMetrics.sortinoRatio, 'number')} - -
-
- - {/* Column 3 - Additional Metrics */} -
-
- Annual Return - - {formatValue(allMetrics.annualizedReturn, 'percent')} - -
- -
- Volatility - - {formatValue(allMetrics.volatility ? allMetrics.volatility / 100 : undefined, 'percent', 1)} - -
- -
- Avg Holding - - {allMetrics.avgHoldingPeriod ? `${(allMetrics.avgHoldingPeriod / 60).toFixed(1)}h` : '-'} - -
- -
- Max Consec Loss - 5 ? 'text-error' : 'text-text-primary'}`}> - {allMetrics.maxConsecutiveLosses ?? '-'} - -
- -
- Payoff Ratio - - {formatValue(allMetrics.payoffRatio, 'number')} - -
-
-
- - {/* Advanced Metrics - Show only if available */} - {(allMetrics.skewness !== undefined || allMetrics.kurtosis !== undefined || - allMetrics.informationRatio !== undefined || allMetrics.kellyFraction !== undefined) && ( -
-
- {allMetrics.informationRatio !== undefined && ( -
- Info Ratio -
- {formatValue(allMetrics.informationRatio, 'number')} -
-
- )} - - {allMetrics.skewness !== undefined && ( -
- Skewness -
- {formatValue(allMetrics.skewness, 'number')} -
-
- )} - - {allMetrics.kurtosis !== undefined && ( -
- Kurtosis -
- {formatValue(allMetrics.kurtosis, 'number')} -
-
- )} - - {allMetrics.kellyFraction !== undefined && ( -
- Kelly % -
- {formatValue(allMetrics.kellyFraction, 'percent')} -
-
- )} -
-
- )} - - {/* Additional Metrics Row */} -
-
-
- Calmar -
- {formatValue(allMetrics.calmarRatio, 'number')} -
-
- -
- Profitable -
- {allMetrics.profitableTrades ?? '-'}/{allMetrics.totalTrades ?? '-'} -
-
- -
- Exposure -
- {result.analytics?.exposureTime ? formatValue(result.analytics.exposureTime, 'percent', 1) : '-'} -
-
- -
- Largest Win -
- {formatValue(allMetrics.largestWin, 'currency')} -
-
- -
- Largest Loss -
- {formatValue(allMetrics.largestLoss, 'currency')} -
-
-
-
-
- ); -} \ No newline at end of file +import type { RunResult } from '../services/backtestApiV2'; + +interface ExtendedMetrics { + // Core metrics + totalReturn?: number; + sharpeRatio?: number; + maxDrawdown?: number; + winRate?: number; + totalProfit?: number; + profitFactor?: number; + totalTrades?: number; + avgWin?: number; + avgLoss?: number; + expectancy?: number; + sortinoRatio?: number; + calmarRatio?: number; + profitableTrades?: number; + + // Extended metrics from orchestrator + annualizedReturn?: number; + volatility?: number; + avgHoldingPeriod?: number; + maxConsecutiveLosses?: number; + maxConsecutiveWins?: number; + payoffRatio?: number; + largestWin?: number; + largestLoss?: number; + avgWinLoss?: number; + skewness?: number; + kurtosis?: number; + tailRatio?: number; + kellyFraction?: number; + informationRatio?: number; + avgTradesPerDay?: number; +} + +interface CompactPerformanceMetricsProps { + result: RunResult | null; + isLoading: boolean; +} + +export function CompactPerformanceMetrics({ result, isLoading }: CompactPerformanceMetricsProps) { + if (isLoading || !result) { + return null; + } + + const metrics = result.metrics as ExtendedMetrics; + const analytics = result.analytics || {}; + + // Merge metrics from both sources + const allMetrics = { + ...metrics, + ...analytics, + // Override with metrics values if they exist + ...metrics, + }; + + // Calculate totalProfit if not provided + const totalProfit = + allMetrics.totalProfit ?? + (allMetrics.totalReturn && result.config?.initialCapital + ? allMetrics.totalReturn * result.config.initialCapital + : undefined); + + const formatValue = ( + value: number | undefined, + format: 'percent' | 'number' | 'currency', + decimals = 2 + ) => { + if (value === undefined || value === null) { + return '-'; + } + + switch (format) { + case 'percent': + return `${(value * 100).toFixed(decimals)}%`; + case 'currency': { + const prefix = value < 0 ? '-$' : '$'; + return `${prefix}${Math.abs(value).toFixed(decimals)}`; + } + case 'number': + return value.toFixed(decimals); + } + }; + + const getColorClass = ( + value: number | undefined, + thresholds: { good: number; warning?: number } + ) => { + if (value === undefined || value === null) { + return 'text-text-secondary'; + } + + if (thresholds.warning !== undefined) { + if (value >= thresholds.good) { + return 'text-success'; + } + if (value >= thresholds.warning) { + return 'text-warning'; + } + return 'text-error'; + } + + return value >= thresholds.good ? 'text-success' : 'text-error'; + }; + + return ( +
+

Performance Analytics

+ +
+ {/* Column 1 - Return Metrics */} +
+
+ Total Return + + {formatValue(allMetrics.totalReturn, 'percent')} + +
+ +
+ Sharpe Ratio + + {formatValue(allMetrics.sharpeRatio, 'number')} + +
+ +
+ Max Drawdown + + {formatValue(allMetrics.maxDrawdown, 'percent')} + +
+ +
+ Win Rate + + {formatValue(allMetrics.winRate, 'percent', 1)} + +
+ +
+ Total Profit + + {formatValue(totalProfit, 'currency')} + +
+
+ + {/* Column 2 - Risk Metrics */} +
+
+ Profit Factor + + {formatValue(allMetrics.profitFactor, 'number')} + +
+ +
+ Total Trades + + {allMetrics.totalTrades ?? '-'} + +
+ +
+ Avg Win/Loss + + {formatValue(allMetrics.avgWin, 'currency')} + / + {formatValue(allMetrics.avgLoss, 'currency')} + +
+ +
+ Expectancy + + {formatValue(allMetrics.expectancy, 'currency')} + +
+ +
+ Sortino Ratio + + {formatValue(allMetrics.sortinoRatio, 'number')} + +
+
+ + {/* Column 3 - Additional Metrics */} +
+
+ Annual Return + + {formatValue(allMetrics.annualizedReturn, 'percent')} + +
+ +
+ Volatility + + {formatValue( + allMetrics.volatility ? allMetrics.volatility / 100 : undefined, + 'percent', + 1 + )} + +
+ +
+ Avg Holding + + {allMetrics.avgHoldingPeriod + ? `${(allMetrics.avgHoldingPeriod / 60).toFixed(1)}h` + : '-'} + +
+ +
+ Max Consec Loss + 5 ? 'text-error' : 'text-text-primary'}`} + > + {allMetrics.maxConsecutiveLosses ?? '-'} + +
+ +
+ Payoff Ratio + + {formatValue(allMetrics.payoffRatio, 'number')} + +
+
+
+ + {/* Advanced Metrics - Show only if available */} + {(allMetrics.skewness !== undefined || + allMetrics.kurtosis !== undefined || + allMetrics.informationRatio !== undefined || + allMetrics.kellyFraction !== undefined) && ( +
+
+ {allMetrics.informationRatio !== undefined && ( +
+ Info Ratio +
+ {formatValue(allMetrics.informationRatio, 'number')} +
+
+ )} + + {allMetrics.skewness !== undefined && ( +
+ Skewness +
+ {formatValue(allMetrics.skewness, 'number')} +
+
+ )} + + {allMetrics.kurtosis !== undefined && ( +
+ Kurtosis +
+ {formatValue(allMetrics.kurtosis, 'number')} +
+
+ )} + + {allMetrics.kellyFraction !== undefined && ( +
+ Kelly % +
+ {formatValue(allMetrics.kellyFraction, 'percent')} +
+
+ )} +
+
+ )} + + {/* Additional Metrics Row */} +
+
+
+ Calmar +
+ {formatValue(allMetrics.calmarRatio, 'number')} +
+
+ +
+ Profitable +
+ {allMetrics.profitableTrades ?? '-'}/{allMetrics.totalTrades ?? '-'} +
+
+ +
+ Exposure +
+ {result.analytics?.exposureTime + ? formatValue(result.analytics.exposureTime, 'percent', 1) + : '-'} +
+
+ +
+ Largest Win +
+ {formatValue(allMetrics.largestWin, 'currency')} +
+
+ +
+ Largest Loss +
+ {formatValue(allMetrics.largestLoss, 'currency')} +
+
+
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx index bb6dffdb..d26c2754 100644 --- a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx @@ -1,228 +1,228 @@ -import { useState } from 'react'; -import { XMarkIcon } from '@heroicons/react/24/solid'; -import type { Backtest } from '../services/backtestApiV2'; - -interface CreateBacktestDialogProps { - onClose: () => void; - onCreate: (config: Omit) => void; -} - -export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) { - const [formData, setFormData] = useState({ - name: '', - strategy: 'moving-average', - symbols: ['AAPL'], - startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], - endDate: new Date().toISOString().split('T')[0], - initialCapital: 100000, - commission: 0, - slippage: 0, - }); - - const [symbolInput, setSymbolInput] = useState(''); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - - if (!formData.name.trim()) { - alert('Please enter a backtest name'); - return; - } - - onCreate({ - ...formData, - metadata: {}, - }); - }; - - const addSymbol = () => { - const symbol = symbolInput.trim().toUpperCase(); - if (symbol && !formData.symbols.includes(symbol)) { - setFormData({ ...formData, symbols: [...formData.symbols, symbol] }); - setSymbolInput(''); - } - }; - - const removeSymbol = (symbol: string) => { - setFormData({ - ...formData, - symbols: formData.symbols.filter(s => s !== symbol), - }); - }; - - return ( -
-
-
-

Create New Backtest

- -
- -
-
- - setFormData({ ...formData, name: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="My Strategy Backtest" - required - /> -
- -
- - -
- -
- -
- setSymbolInput(e.target.value)} - onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addSymbol())} - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="Enter symbol (e.g., AAPL)" - /> - -
-
- {formData.symbols.map(symbol => ( - - {symbol} - - - ))} -
-
- -
-
- - setFormData({ ...formData, startDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> -
-
- - setFormData({ ...formData, endDate: e.target.value })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - required - /> -
-
- -
- - setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - min="0" - step="1000" - required - /> -
- -
-
- - setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - min="0" - step="0.01" - /> -
-
- - setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 })} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - min="0" - step="0.01" - /> -
-
- -
- - -
-
-
-
- ); -} \ No newline at end of file +import { XMarkIcon } from '@heroicons/react/24/solid'; +import { useState } from 'react'; +import type { Backtest } from '../services/backtestApiV2'; + +interface CreateBacktestDialogProps { + onClose: () => void; + onCreate: (config: Omit) => void; +} + +export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) { + const [formData, setFormData] = useState({ + name: '', + strategy: 'moving-average', + symbols: ['AAPL'], + startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10), + endDate: new Date().toISOString().slice(0, 10), + initialCapital: 100000, + commission: 0, + slippage: 0, + }); + + const [symbolInput, setSymbolInput] = useState(''); + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + + if (!formData.name.trim()) { + alert('Please enter a backtest name'); + return; + } + + onCreate({ + ...formData, + config: { commission: formData.commission, slippage: formData.slippage }, + }); + }; + + const addSymbol = () => { + const symbol = symbolInput.trim().toUpperCase(); + if (symbol && !formData.symbols.includes(symbol)) { + setFormData({ ...formData, symbols: [...formData.symbols, symbol] }); + setSymbolInput(''); + } + }; + + const removeSymbol = (symbol: string) => { + setFormData({ + ...formData, + symbols: formData.symbols.filter(s => s !== symbol), + }); + }; + + return ( +
+
+
+

Create New Backtest

+ +
+ +
+
+ + setFormData({ ...formData, name: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + placeholder="My Strategy Backtest" + required + /> +
+ +
+ + +
+ +
+ +
+ setSymbolInput(e.target.value)} + onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())} + className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + placeholder="Enter symbol (e.g., AAPL)" + /> + +
+
+ {formData.symbols.map(symbol => ( + + {symbol} + + + ))} +
+
+ +
+
+ + setFormData({ ...formData, startDate: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + required + /> +
+
+ + setFormData({ ...formData, endDate: e.target.value })} + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + required + /> +
+
+ +
+ + + setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 }) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + min="0" + step="1000" + required + /> +
+ +
+
+ + + setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 }) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + min="0" + step="0.01" + /> +
+
+ + + setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 }) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + min="0" + step="0.01" + /> +
+
+ +
+ + +
+
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/PositionsSummary.tsx b/apps/stock/web-app/src/features/backtest/components/PositionsSummary.tsx index b427daa4..242c577a 100644 --- a/apps/stock/web-app/src/features/backtest/components/PositionsSummary.tsx +++ b/apps/stock/web-app/src/features/backtest/components/PositionsSummary.tsx @@ -1,134 +1,157 @@ -interface Position { - symbol: string; - quantity: number; - averagePrice?: number; - avgPrice?: number; - currentPrice?: number; - lastPrice?: number; - realizedPnl?: number; - unrealizedPnl?: number; -} - -interface PositionsSummaryProps { - openPositions: Position[]; - closedPositions: Position[]; - onExpand?: () => void; -} - -export function PositionsSummary({ openPositions, closedPositions, onExpand }: PositionsSummaryProps) { - const totalRealizedPnL = closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0); - const totalUnrealizedPnL = openPositions.reduce((sum, p) => { - const quantity = p.quantity || 0; - const avgPrice = p.averagePrice || p.avgPrice || 0; - const currentPrice = p.currentPrice || p.lastPrice || avgPrice; - return sum + ((currentPrice - avgPrice) * quantity); - }, 0); - const totalPnL = totalRealizedPnL + totalUnrealizedPnL; - - return ( -
-

Positions Summary

- -
- {openPositions.length > 0 && ( -
-

Open Positions ({openPositions.length})

-
- {openPositions.slice(0, 3).map((position, index) => { - const quantity = position.quantity || 0; - const avgPrice = position.averagePrice || position.avgPrice || 0; - const currentPrice = position.currentPrice || position.lastPrice || avgPrice; - const side = quantity > 0 ? 'long' : 'short'; - const absQuantity = Math.abs(quantity); - const pnl = (currentPrice - avgPrice) * quantity; - const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0; - - return ( -
-
- {position.symbol} - - {side.toUpperCase()} - - - {absQuantity} @ ${avgPrice.toFixed(2)} - -
-
- - ${currentPrice.toFixed(2)} - - = 0 ? 'text-success' : 'text-error'}`}> - {pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(1)}% - -
-
- ); - })} -
-
- )} - - {closedPositions.length > 0 && openPositions.length === 0 && ( -
-

- Closed Positions ({closedPositions.length}) -

-
- {closedPositions.slice(0, 3).map((position, index) => ( -
- {position.symbol} - = 0 ? 'text-success' : 'text-error'}`}> - ${position.realizedPnl.toFixed(2)} - -
- ))} -
-
- )} - - {openPositions.length === 0 && closedPositions.length === 0 && ( -

No positions to display

- )} -
- - {/* Summary metrics at bottom - similar to performance metrics */} -
-
-
- Unrealized -
= 0 ? 'text-success' : 'text-error'}`}> - ${totalUnrealizedPnL.toFixed(2)} -
-
- -
- Realized -
= 0 ? 'text-success' : 'text-error'}`}> - ${totalRealizedPnL.toFixed(2)} -
-
- -
- Total P&L -
= 0 ? 'text-success' : 'text-error'}`}> - ${totalPnL.toFixed(2)} -
-
-
- - {((openPositions.length > 3) || - (closedPositions.length > 3 && openPositions.length === 0)) && onExpand && ( - - )} -
-
- ); -} \ No newline at end of file +interface Position { + symbol: string; + quantity: number; + averagePrice?: number; + avgPrice?: number; + currentPrice?: number; + lastPrice?: number; + realizedPnl?: number; + unrealizedPnl?: number; +} + +interface PositionsSummaryProps { + openPositions: Position[]; + closedPositions: Position[]; + onExpand?: () => void; +} + +export function PositionsSummary({ + openPositions, + closedPositions, + onExpand, +}: PositionsSummaryProps) { + const totalRealizedPnL = closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0); + const totalUnrealizedPnL = openPositions.reduce((sum, p) => { + const quantity = p.quantity || 0; + const avgPrice = p.averagePrice || p.avgPrice || 0; + const currentPrice = p.currentPrice || p.lastPrice || avgPrice; + return sum + (currentPrice - avgPrice) * quantity; + }, 0); + const totalPnL = totalRealizedPnL + totalUnrealizedPnL; + + return ( +
+

Positions Summary

+ +
+ {openPositions.length > 0 && ( +
+

+ Open Positions ({openPositions.length}) +

+
+ {openPositions.slice(0, 3).map((position, index) => { + const quantity = position.quantity || 0; + const avgPrice = position.averagePrice || position.avgPrice || 0; + const currentPrice = position.currentPrice || position.lastPrice || avgPrice; + const side = quantity > 0 ? 'long' : 'short'; + const absQuantity = Math.abs(quantity); + const pnl = (currentPrice - avgPrice) * quantity; + const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0; + + return ( +
+
+ + {position.symbol} + + + {side.toUpperCase()} + + + {absQuantity} @ ${avgPrice.toFixed(2)} + +
+
+ + ${currentPrice.toFixed(2)} + + = 0 ? 'text-success' : 'text-error'}`} + > + {pnlPercent >= 0 ? '+' : ''} + {pnlPercent.toFixed(1)}% + +
+
+ ); + })} +
+
+ )} + + {closedPositions.length > 0 && openPositions.length === 0 && ( +
+

+ Closed Positions ({closedPositions.length}) +

+
+ {closedPositions.slice(0, 3).map((position, index) => ( +
+ {position.symbol} + = 0 ? 'text-success' : 'text-error'}`} + > + ${(position.realizedPnl ?? 0).toFixed(2)} + +
+ ))} +
+
+ )} + + {openPositions.length === 0 && closedPositions.length === 0 && ( +

No positions to display

+ )} +
+ + {/* Summary metrics at bottom - similar to performance metrics */} +
+
+
+ Unrealized +
= 0 ? 'text-success' : 'text-error'}`} + > + ${totalUnrealizedPnL.toFixed(2)} +
+
+ +
+ Realized +
= 0 ? 'text-success' : 'text-error'}`}> + ${totalRealizedPnL.toFixed(2)} +
+
+ +
+ Total P&L +
= 0 ? 'text-success' : 'text-error'}`}> + ${totalPnL.toFixed(2)} +
+
+
+ + {(openPositions.length > 3 || (closedPositions.length > 3 && openPositions.length === 0)) && + onExpand && ( + + )} +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunControls.tsx b/apps/stock/web-app/src/features/backtest/components/RunControls.tsx index dc174e68..e01a611e 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunControls.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunControls.tsx @@ -1,201 +1,196 @@ -import { useState } from 'react'; -import type { Run } from '../services/backtestApiV2'; -import { - PlayIcon, - PauseIcon, - StopIcon, - ForwardIcon, - BackwardIcon, -} from '@heroicons/react/24/solid'; - -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); - - 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.currentSimulationDate && ( -
- Current Date: - - {formatDate(run.currentSimulationDate)} - -
- )} - {run.error && ( -
- Error: - - {run.error} - -
- )} -
-
-
- ); -} \ No newline at end of file +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.currentSimulationDate && ( +
+ Current Date: + + {formatDate(run.currentSimulationDate)} + +
+ )} + {run.error && ( +
+ Error: + {run.error} +
+ )} +
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx index a5b74eba..cc86b289 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunControlsCompact.tsx @@ -1,100 +1,102 @@ -import type { Run } from '../services/backtestApiV2'; -import { - ArrowPathIcon, -} from '@heroicons/react/24/solid'; - -interface RunControlsCompactProps { - run: Run; - onPause: () => void; - onResume: () => void; - onRerun: (speed: number | null) => void; - onNext?: () => void; - onSpeedChange: (speed: number | null) => void; -} - -export function RunControlsCompact({ - run, - onPause, - onResume, - onRerun, - onNext, -}: RunControlsCompactProps) { - - const isRunning = run.status === 'running'; - const isPaused = run.status === 'paused'; - const isCompleted = run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled'; - - return ( -
- {/* Progress */} -
- Progress: -
-
-
-
-
- {run.progress.toFixed(0)}% -
- - - {/* Control Buttons */} -
- {isRunning ? ( - - ) : isPaused ? ( - - ) : null} - - {onNext && ( - - )} - - -
- - {/* Status Indicator */} - {run.status !== 'running' && run.status !== 'paused' && ( - <> -
- - {run.status.charAt(0).toUpperCase() + run.status.slice(1)} - - - )} -
- ); -} \ No newline at end of file +import { ArrowPathIcon, ForwardIcon, PauseIcon, PlayIcon } from '@heroicons/react/24/solid'; +import type { Run } from '../services/backtestApiV2'; + +interface RunControlsCompactProps { + run: Run; + onPause: () => void; + onResume: () => void; + onRerun: (speed: number | null) => void; + onNext?: () => void; + onSpeedChange: (speed: number | null) => void; +} + +export function RunControlsCompact({ + run, + onPause, + onResume, + onRerun, + onNext, +}: RunControlsCompactProps) { + const isRunning = run.status === 'running'; + const isPaused = run.status === 'paused'; + const _isCompleted = + run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled'; + + return ( +
+ {/* Progress */} +
+ Progress: +
+
+
+
+
+ {run.progress.toFixed(0)}% +
+ + {/* Control Buttons */} +
+ {isRunning ? ( + + ) : isPaused ? ( + + ) : null} + + {onNext && ( + + )} + + +
+ + {/* Status Indicator */} + {run.status !== 'running' && run.status !== 'paused' && ( + <> +
+ + {run.status.charAt(0).toUpperCase() + run.status.slice(1)} + + + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx b/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx index c31082e6..e1413555 100644 --- a/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx +++ b/apps/stock/web-app/src/features/backtest/components/RunsListWithMetrics.tsx @@ -1,290 +1,336 @@ -import { DataTable } from '@/components/ui/DataTable'; -import type { ColumnDef } from '@tanstack/react-table'; -import type { Run, RunResult } from '../services/backtestApiV2'; -import { useNavigate, useParams } from 'react-router-dom'; -import { useEffect, useState } from 'react'; -import { backtestApiV2 } from '../services/backtestApiV2'; -import { - CheckCircleIcon, - XCircleIcon, - PauseIcon, - PlayIcon, - ClockIcon, -} from '@heroicons/react/24/outline'; - -interface RunsListProps { - runs: Run[]; - currentRunId?: string; - onSelectRun: (runId: string) => void; -} - -interface RunWithMetrics extends Run { - metrics?: RunResult['metrics']; - initialCapital?: number; -} - -export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) { - const navigate = useNavigate(); - const { id: backtestId } = useParams<{ id: string }>(); - const [runsWithMetrics, setRunsWithMetrics] = useState([]); - const [loadingMetrics, setLoadingMetrics] = useState(false); - - // Fetch metrics for completed runs - useEffect(() => { - const fetchMetrics = async () => { - setLoadingMetrics(true); - const updatedRuns: RunWithMetrics[] = await Promise.all( - runs.map(async (run) => { - if (run.status === 'completed') { - try { - const results = await backtestApiV2.getRunResults(run.id); - return { - ...run, - metrics: results.metrics, - initialCapital: results.config?.initialCapital - }; - } catch (error) { - console.error(`Failed to fetch metrics for run ${run.id}:`, error); - return run; - } - } - return run; - }) - ); - setRunsWithMetrics(updatedRuns); - setLoadingMetrics(false); - }; - - if (runs.length > 0) { - fetchMetrics(); - } - }, [runs]); - - const getStatusIcon = (status: Run['status']) => { - switch (status) { - case 'completed': - return ; - case 'failed': - return ; - case 'cancelled': - return ; - case 'running': - return ; - case 'paused': - return ; - case 'pending': - return ; - } - }; - - const getStatusLabel = (status: Run['status']) => { - return status.charAt(0).toUpperCase() + status.slice(1); - }; - - const formatPercentage = (value: number | undefined, decimals = 2) => { - if (value === undefined || value === null) return '-'; - return `${(value * 100).toFixed(decimals)}%`; - }; - - const formatNumber = (value: number | undefined, decimals = 2) => { - if (value === undefined || value === null) return '-'; - return value.toFixed(decimals); - }; - - const formatCurrency = (value: number | undefined) => { - if (value === undefined || value === null) return '-'; - const prefix = value < 0 ? '-$' : '$'; - return `${prefix}${Math.abs(value).toFixed(2)}`; - }; - - const columns: ColumnDef[] = [ - { - accessorKey: 'runNumber', - header: 'Run #', - size: 60, - cell: ({ getValue, row }) => ( - - #{getValue() as number} - - ), - }, - { - accessorKey: 'status', - header: 'Status', - size: 100, - cell: ({ getValue }) => { - const status = getValue() as Run['status']; - return ( -
- {getStatusIcon(status)} - {getStatusLabel(status)} -
- ); - }, - }, - { - accessorKey: 'progress', - header: 'Progress', - size: 120, - cell: ({ row }) => { - const progress = row.original.progress; - const status = row.original.status; - - if (status === 'pending') return -; - if (status === 'completed') return Complete; - - return ( -
-
-
-
- {progress.toFixed(0)}% -
- ); - }, - }, - { - id: 'totalReturn', - header: 'Return', - size: 80, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.totalReturn; - return ( - = 0 ? 'text-success' : 'text-error' - }`}> - {formatPercentage(value)} - - ); - }, - }, - { - id: 'sharpeRatio', - header: 'Sharpe', - size: 80, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.sharpeRatio; - return ( - 1 ? 'text-success' : - value > 0 ? 'text-warning' : 'text-error' - }`}> - {formatNumber(value)} - - ); - }, - }, - { - id: 'maxDrawdown', - header: 'Max DD', - size: 80, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.maxDrawdown; - return ( - -0.1 ? 'text-success' : - value > -0.2 ? 'text-warning' : 'text-error' - }`}> - {formatPercentage(value)} - - ); - }, - }, - { - id: 'winRate', - header: 'Win Rate', - size: 80, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.winRate; - return ( - 0.5 ? 'text-success' : 'text-warning' - }`}> - {formatPercentage(value, 1)} - - ); - }, - }, - { - id: 'profitFactor', - header: 'Profit Factor', - size: 100, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.profitFactor; - return ( - 1.5 ? 'text-success' : - value > 1 ? 'text-warning' : 'text-error' - }`}> - {formatNumber(value)} - - ); - }, - }, - { - id: 'totalProfit', - header: 'Total Profit', - size: 100, - cell: ({ row }) => { - const metrics = row.original.metrics; - const value = metrics?.totalProfit; - return ( - = 0 ? 'text-success' : 'text-error' - }`}> - {formatCurrency(value)} - - ); - }, - }, - { - accessorKey: 'startedAt', - header: 'Started', - size: 160, - cell: ({ getValue }) => { - const date = getValue() as string | undefined; - return ( - - {date ? new Date(date).toLocaleString() : '-'} - - ); - }, - }, - ]; - - if (runs.length === 0) { - return ( -
-

No runs yet. Create a new run to get started.

-
- ); - } - - return ( - { - navigate(`/backtests/${backtestId}/run/${run.id}`); - onSelectRun(run.id); - }} - className="bg-surface-secondary rounded-lg border border-border" - height={400} - loading={loadingMetrics} - /> - ); -} \ No newline at end of file +import { + CheckCircleIcon, + ClockIcon, + PauseIcon, + PlayIcon, + XCircleIcon, +} from '@heroicons/react/24/outline'; +import type { ColumnDef } from '@tanstack/react-table'; +import { useEffect, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { DataTable } from '@/components/ui/DataTable'; +import { browserLog } from '@/utils/browserLog'; +import type { Run, RunResult } from '../services/backtestApiV2'; +import { backtestApiV2 } from '../services/backtestApiV2'; + +interface RunsListProps { + runs: Run[]; + currentRunId?: string; + onSelectRun: (runId: string) => void; +} + +interface RunWithMetrics extends Run { + metrics?: RunResult['metrics']; + initialCapital?: number; +} + +export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) { + const navigate = useNavigate(); + const { id: backtestId } = useParams<{ id: string }>(); + const [runsWithMetrics, setRunsWithMetrics] = useState([]); + const [loadingMetrics, setLoadingMetrics] = useState(false); + + // Fetch metrics for completed runs + useEffect(() => { + const fetchMetrics = async () => { + setLoadingMetrics(true); + const updatedRuns: RunWithMetrics[] = await Promise.all( + runs.map(async run => { + if (run.status === 'completed') { + try { + const results = await backtestApiV2.getRunResults(run.id); + return { + ...run, + metrics: results.metrics, + initialCapital: results.config?.initialCapital, + }; + } catch (error) { + browserLog.error(`Failed to fetch metrics for run ${run.id}:`, error); + return run; + } + } + return run; + }) + ); + setRunsWithMetrics(updatedRuns); + setLoadingMetrics(false); + }; + + if (runs.length > 0) { + fetchMetrics(); + } + }, [runs]); + + const getStatusIcon = (status: Run['status']) => { + switch (status) { + case 'completed': + return ; + case 'failed': + return ; + case 'cancelled': + return ; + case 'running': + return ; + case 'paused': + return ; + case 'pending': + return ; + } + }; + + const getStatusLabel = (status: Run['status']) => { + return status.charAt(0).toUpperCase() + status.slice(1); + }; + + const formatPercentage = (value: number | undefined, decimals = 2) => { + if (value === undefined || value === null) { + return '-'; + } + return `${(value * 100).toFixed(decimals)}%`; + }; + + const formatNumber = (value: number | undefined, decimals = 2) => { + if (value === undefined || value === null) { + return '-'; + } + return value.toFixed(decimals); + }; + + const formatCurrency = (value: number | undefined) => { + if (value === undefined || value === null) { + return '-'; + } + const prefix = value < 0 ? '-$' : '$'; + return `${prefix}${Math.abs(value).toFixed(2)}`; + }; + + const columns: ColumnDef[] = [ + { + accessorKey: 'runNumber', + header: 'Run #', + size: 60, + cell: ({ getValue, row }) => ( + + #{getValue() as number} + + ), + }, + { + accessorKey: 'status', + header: 'Status', + size: 100, + cell: ({ getValue }) => { + const status = getValue() as Run['status']; + return ( +
+ {getStatusIcon(status)} + {getStatusLabel(status)} +
+ ); + }, + }, + { + accessorKey: 'progress', + header: 'Progress', + size: 120, + cell: ({ row }) => { + const progress = row.original.progress; + const status = row.original.status; + + if (status === 'pending') { + return -; + } + if (status === 'completed') { + return Complete; + } + + return ( +
+
+
+
+ {progress.toFixed(0)}% +
+ ); + }, + }, + { + id: 'totalReturn', + header: 'Return', + size: 80, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.totalReturn; + return ( + = 0 + ? 'text-success' + : 'text-error' + }`} + > + {formatPercentage(value)} + + ); + }, + }, + { + id: 'sharpeRatio', + header: 'Sharpe', + size: 80, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.sharpeRatio; + return ( + 1 + ? 'text-success' + : value > 0 + ? 'text-warning' + : 'text-error' + }`} + > + {formatNumber(value)} + + ); + }, + }, + { + id: 'maxDrawdown', + header: 'Max DD', + size: 80, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.maxDrawdown; + return ( + -0.1 + ? 'text-success' + : value > -0.2 + ? 'text-warning' + : 'text-error' + }`} + > + {formatPercentage(value)} + + ); + }, + }, + { + id: 'winRate', + header: 'Win Rate', + size: 80, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.winRate; + return ( + 0.5 + ? 'text-success' + : 'text-warning' + }`} + > + {formatPercentage(value, 1)} + + ); + }, + }, + { + id: 'profitFactor', + header: 'Profit Factor', + size: 100, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.profitFactor; + return ( + 1.5 + ? 'text-success' + : value > 1 + ? 'text-warning' + : 'text-error' + }`} + > + {formatNumber(value)} + + ); + }, + }, + { + id: 'totalProfit', + header: 'Total Profit', + size: 100, + cell: ({ row }) => { + const metrics = row.original.metrics; + const value = metrics?.totalProfit; + return ( + = 0 + ? 'text-success' + : 'text-error' + }`} + > + {formatCurrency(value)} + + ); + }, + }, + { + accessorKey: 'startedAt', + header: 'Started', + size: 160, + cell: ({ getValue }) => { + const date = getValue() as string | undefined; + return ( + + {date ? new Date(date).toLocaleString() : '-'} + + ); + }, + }, + ]; + + if (runs.length === 0) { + return ( +
+

No runs yet. Create a new run to get started.

+
+ ); + } + + return ( + { + navigate(`/backtests/${backtestId}/run/${run.id}`); + onSelectRun(run.id); + }} + className="bg-surface-secondary rounded-lg border border-border" + height={400} + loading={loadingMetrics} + /> + ); +} diff --git a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts index 5b549533..074665d2 100644 --- a/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts +++ b/apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts @@ -1,389 +1,411 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; -import { backtestApiV2 } from '../services/backtestApiV2'; -import type { Backtest, Run, RunResult, CreateBacktestRequest } from '../services/backtestApiV2'; - -interface UseBacktestV2Return { - // State - backtest: Backtest | null; - runs: Run[]; - currentRun: Run | null; - runResults: RunResult | null; - isLoading: boolean; - error: string | null; - - // Actions - loadBacktest: (id: string) => Promise; - createBacktest: (request: CreateBacktestRequest) => Promise; - updateBacktest: (id: string, updates: Partial) => Promise; - deleteBacktest: (id: string) => Promise; - - createRun: (speedMultiplier?: number | null) => Promise; - pauseRun: () => Promise; - resumeRun: () => Promise; - cancelRun: () => Promise; - updateRunSpeed: (speedMultiplier: number | null) => Promise; - selectRun: (runId: string | undefined) => Promise; -} - -export function useBacktestV2(): UseBacktestV2Return { - const [backtest, setBacktest] = useState(null); - const [runs, setRuns] = useState([]); - const [currentRun, setCurrentRun] = useState(null); - const [runResults, setRunResults] = useState(null); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - - const pollingIntervalRef = useRef(null); - - // Load a specific backtest and its runs - const loadBacktest = useCallback(async (id: string) => { - setIsLoading(true); - setError(null); - - try { - const [loadedBacktest, loadedRuns] = await Promise.all([ - backtestApiV2.getBacktest(id), - backtestApiV2.listRuns(id) - ]); - - setBacktest(loadedBacktest); - setRuns(loadedRuns); - - // Don't auto-select runs here - let the URL parameter drive the selection - } catch (err) { - console.error('Failed to load backtest:', err); - setError(err instanceof Error ? err.message : 'Failed to load backtest'); - } finally { - setIsLoading(false); - } - }, []); - - // Create a new backtest - const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise => { - setIsLoading(true); - setError(null); - - try { - const newBacktest = await backtestApiV2.createBacktest(request); - setBacktest(newBacktest); - setRuns([]); - setCurrentRun(null); - setRunResults(null); - return newBacktest; - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to create backtest'); - throw err; - } finally { - setIsLoading(false); - } - }, []); - - // Update backtest configuration - const updateBacktest = useCallback(async (id: string, updates: Partial) => { - setIsLoading(true); - setError(null); - - try { - const updatedBacktest = await backtestApiV2.updateBacktest(id, updates); - setBacktest(updatedBacktest); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to update backtest'); - throw err; - } finally { - setIsLoading(false); - } - }, []); - - // Delete backtest - const deleteBacktest = useCallback(async (id: string) => { - setIsLoading(true); - setError(null); - - try { - await backtestApiV2.deleteBacktest(id); - setBacktest(null); - setRuns([]); - setCurrentRun(null); - setRunResults(null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to delete backtest'); - throw err; - } finally { - setIsLoading(false); - } - }, []); - - // Create a new run - const createRun = useCallback(async (speedMultiplier?: number | null) => { - if (!backtest) return; - - setIsLoading(true); - setError(null); - setRunResults(null); - - try { - // Pass speedMultiplier as-is, null means max speed - const newRun = await backtestApiV2.createRun(backtest.id, { - speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier - }); - - // Add to runs array first - setRuns(prevRuns => [newRun, ...prevRuns]); - - // Clear previous results immediately - setRunResults(null); - - // Set as current run - setCurrentRun(newRun); - - // Small delay to ensure the run is properly created in the database - await new Promise(resolve => setTimeout(resolve, 100)); - - // Check if the run is completed (it might complete instantly) - let finalRun = newRun; - - // If status is pending, check again after a short delay - if (newRun.status === 'pending') { - await new Promise(resolve => setTimeout(resolve, 500)); - try { - finalRun = await backtestApiV2.getRun(newRun.id); - // Update the current run with the latest status - setCurrentRun(finalRun); - setRuns(prevRuns => - prevRuns.map(r => r.id === finalRun.id ? finalRun : r) - ); - } catch (err) { - console.error('Failed to re-check run status:', err); - } - } - - // If the run is completed, load results - if (finalRun.status === 'completed') { - try { - const results = await backtestApiV2.getRunResults(finalRun.id); - setRunResults(results); - } catch (err) { - console.error('Failed to load new run results:', err); - } - } else { - // Start monitoring the run - startMonitoringRun(finalRun.id); - } - - return newRun; // Return the created run - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to create run'); - throw err; // Re-throw so caller knows it failed - } finally { - setIsLoading(false); - } - }, [backtest]); - - // Run control actions - const pauseRun = useCallback(async () => { - if (!currentRun || currentRun.status !== 'running') return; - - try { - await backtestApiV2.pauseRun(currentRun.id); - setCurrentRun(prev => prev ? { ...prev, status: 'paused' } : null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to pause run'); - } - }, [currentRun]); - - const resumeRun = useCallback(async () => { - if (!currentRun || currentRun.status !== 'paused') return; - - try { - await backtestApiV2.resumeRun(currentRun.id); - setCurrentRun(prev => prev ? { ...prev, status: 'running' } : null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to resume run'); - } - }, [currentRun]); - - const cancelRun = useCallback(async () => { - if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) return; - - try { - await backtestApiV2.cancelRun(currentRun.id); - setCurrentRun(prev => prev ? { ...prev, status: 'cancelled' } : null); - stopMonitoringRun(); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to cancel run'); - } - }, [currentRun]); - - const updateRunSpeed = useCallback(async (speedMultiplier: number | null) => { - if (!currentRun) return; - - try { - // Keep null as null for max speed (no limit) - const apiSpeed = speedMultiplier; - - // Only call API if run is active - if (currentRun.status === 'running' || currentRun.status === 'paused') { - await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed); - } - - // Always update local state so UI reflects the selection - setCurrentRun(prev => prev ? { ...prev, speedMultiplier: apiSpeed } : null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to update run speed'); - } - }, [currentRun]); - - // Select a specific run - const selectRun = useCallback(async (runId: string | undefined) => { - if (!runId) { - setCurrentRun(null); - setRunResults(null); - stopMonitoringRun(); - return; - } - - let run = runs.find(r => r.id === runId); - - // If run not found in list, try to fetch it directly - if (!run) { - let attempts = 0; - const maxAttempts = 3; - - while (attempts < maxAttempts) { - try { - run = await backtestApiV2.getRun(runId); - - // Add to runs list if not present - setRuns(prevRuns => { - const exists = prevRuns.some(r => r.id === run!.id); - if (!exists) { - return [run!, ...prevRuns]; - } - return prevRuns; - }); - - break; // Success, exit loop - } catch (err) { - attempts++; - if (attempts >= maxAttempts) { - console.error('Failed to fetch run after all attempts:', runId, err); - setError(`Failed to load run ${runId}`); - return; - } - // Wait before retrying - await new Promise(resolve => setTimeout(resolve, 1000)); - } - } - } - - setCurrentRun(run); - setRunResults(null); - - if (run.status === 'completed') { - try { - const results = await backtestApiV2.getRunResults(run.id); - setRunResults(results); - } catch (err) { - console.error('Failed to load run results:', err); - setError(err instanceof Error ? err.message : 'Failed to load run results'); - } - } else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') { - startMonitoringRun(run.id); - } else { - console.warn('Run has unexpected status:', run.status); - } - }, [runs]); - - // Monitor run progress - const startMonitoringRun = useCallback((runId: string) => { - // Stop any existing monitoring - stopMonitoringRun(); - - // For pending runs, we need to poll until they start or complete - // We'll check the run status by fetching it - pollingIntervalRef.current = setInterval(async () => { - try { - const updatedRun = await backtestApiV2.getRun(runId); - // Update the run in state - setCurrentRun(updatedRun); - setRuns(prevRuns => - prevRuns.map(r => r.id === updatedRun.id ? updatedRun : r) - ); - - // If run is no longer pending, handle the new status - if (updatedRun.status === 'completed') { - stopMonitoringRun(); - try { - const results = await backtestApiV2.getRunResults(runId); - setRunResults(results); - } catch (err) { - console.error('Failed to load completed run results:', err); - } - } else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') { - stopMonitoringRun(); - } - } catch (err) { - console.error('Failed to poll run status:', err); - } - }, 1000); // Poll every second - }, []); - - const startPollingRun = (runId: string) => { - pollingIntervalRef.current = setInterval(async () => { - try { - const updatedRun = await backtestApiV2.getRun(runId); - handleRunUpdate(updatedRun); - - if (updatedRun.status === 'completed') { - const results = await backtestApiV2.getRunResults(runId); - setRunResults(results); - stopMonitoringRun(); - } else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') { - stopMonitoringRun(); - } - } catch (err) { - console.error('Failed to poll run status:', err); - } - }, 1000); // Poll every second - }; - - const stopMonitoringRun = () => { - if (pollingIntervalRef.current) { - clearInterval(pollingIntervalRef.current); - pollingIntervalRef.current = null; - } - }; - - const handleRunUpdate = (update: Run) => { - setCurrentRun(update); - setRuns(prevRuns => - prevRuns.map(run => run.id === update.id ? update : run) - ); - }; - - // Cleanup on unmount - useEffect(() => { - return () => { - stopMonitoringRun(); - }; - }, []); - - return { - backtest, - runs, - currentRun, - runResults, - isLoading, - error, - loadBacktest, - createBacktest, - updateBacktest, - deleteBacktest, - createRun, - pauseRun, - resumeRun, - cancelRun, - updateRunSpeed, - selectRun, - }; -} \ No newline at end of file +import { useCallback, useEffect, useRef, useState } from 'react'; +import { defined } from '@stock-bot/invariants'; +import { browserLog } from '@/utils/browserLog'; +import { backtestApiV2 } from '../services/backtestApiV2'; +import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2'; + +interface UseBacktestV2Return { + // State + backtest: Backtest | null; + runs: Run[]; + currentRun: Run | null; + runResults: RunResult | null; + isLoading: boolean; + error: string | null; + + // Actions + loadBacktest: (id: string) => Promise; + createBacktest: (request: CreateBacktestRequest) => Promise; + updateBacktest: (id: string, updates: Partial) => Promise; + deleteBacktest: (id: string) => Promise; + + createRun: (speedMultiplier?: number | null) => Promise; + pauseRun: () => Promise; + resumeRun: () => Promise; + cancelRun: () => Promise; + updateRunSpeed: (speedMultiplier: number | null) => Promise; + selectRun: (runId: string | undefined) => Promise; +} + +export function useBacktestV2(): UseBacktestV2Return { + const [backtest, setBacktest] = useState(null); + const [runs, setRuns] = useState([]); + const [currentRun, setCurrentRun] = useState(null); + const [runResults, setRunResults] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const pollingIntervalRef = useRef(null); + + // Load a specific backtest and its runs + const loadBacktest = useCallback(async (id: string) => { + setIsLoading(true); + setError(null); + + try { + const [loadedBacktest, loadedRuns] = await Promise.all([ + backtestApiV2.getBacktest(id), + backtestApiV2.listRuns(id), + ]); + + setBacktest(loadedBacktest); + setRuns(loadedRuns); + + // Don't auto-select runs here - let the URL parameter drive the selection + } catch (err) { + browserLog.error('Failed to load backtest:', err); + setError(err instanceof Error ? err.message : 'Failed to load backtest'); + } finally { + setIsLoading(false); + } + }, []); + + // Create a new backtest + const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise => { + setIsLoading(true); + setError(null); + + try { + const newBacktest = await backtestApiV2.createBacktest(request); + setBacktest(newBacktest); + setRuns([]); + setCurrentRun(null); + setRunResults(null); + return newBacktest; + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to create backtest'); + throw err; + } finally { + setIsLoading(false); + } + }, []); + + // Update backtest configuration + const updateBacktest = useCallback( + async (id: string, updates: Partial) => { + setIsLoading(true); + setError(null); + + try { + const updatedBacktest = await backtestApiV2.updateBacktest(id, updates); + setBacktest(updatedBacktest); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to update backtest'); + throw err; + } finally { + setIsLoading(false); + } + }, + [] + ); + + // Delete backtest + const deleteBacktest = useCallback(async (id: string) => { + setIsLoading(true); + setError(null); + + try { + await backtestApiV2.deleteBacktest(id); + setBacktest(null); + setRuns([]); + setCurrentRun(null); + setRunResults(null); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to delete backtest'); + throw err; + } finally { + setIsLoading(false); + } + }, []); + + // Create a new run + const createRun = useCallback( + async (speedMultiplier?: number | null) => { + if (!backtest) { + return; + } + + setIsLoading(true); + setError(null); + setRunResults(null); + + try { + // Pass speedMultiplier as-is, null means max speed + const newRun = await backtestApiV2.createRun(backtest.id, { + speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier, + }); + + // Add to runs array first + setRuns(prevRuns => [newRun, ...prevRuns]); + + // Clear previous results immediately + setRunResults(null); + + // Set as current run + setCurrentRun(newRun); + + // Small delay to ensure the run is properly created in the database + await new Promise(resolve => setTimeout(resolve, 100)); + + // Check if the run is completed (it might complete instantly) + let finalRun = newRun; + + // If status is pending, check again after a short delay + if (newRun.status === 'pending') { + await new Promise(resolve => setTimeout(resolve, 500)); + try { + finalRun = await backtestApiV2.getRun(newRun.id); + // Update the current run with the latest status + setCurrentRun(finalRun); + setRuns(prevRuns => prevRuns.map(r => (r.id === finalRun.id ? finalRun : r))); + } catch (err) { + browserLog.error('Failed to re-check run status:', err); + } + } + + // If the run is completed, load results + if (finalRun.status === 'completed') { + try { + const results = await backtestApiV2.getRunResults(finalRun.id); + setRunResults(results); + } catch (err) { + browserLog.error('Failed to load new run results:', err); + } + } else { + // Start monitoring the run + startMonitoringRun(finalRun.id); + } + + return newRun; // Return the created run + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to create run'); + throw err; // Re-throw so caller knows it failed + } finally { + setIsLoading(false); + } + }, + [backtest] + ); + + // Run control actions + const pauseRun = useCallback(async () => { + if (!currentRun || currentRun.status !== 'running') { + return; + } + + try { + await backtestApiV2.pauseRun(currentRun.id); + setCurrentRun(prev => (prev ? { ...prev, status: 'paused' } : null)); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to pause run'); + } + }, [currentRun]); + + const resumeRun = useCallback(async () => { + if (!currentRun || currentRun.status !== 'paused') { + return; + } + + try { + await backtestApiV2.resumeRun(currentRun.id); + setCurrentRun(prev => (prev ? { ...prev, status: 'running' } : null)); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to resume run'); + } + }, [currentRun]); + + const cancelRun = useCallback(async () => { + if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) { + return; + } + + try { + await backtestApiV2.cancelRun(currentRun.id); + setCurrentRun(prev => (prev ? { ...prev, status: 'cancelled' } : null)); + stopMonitoringRun(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to cancel run'); + } + }, [currentRun]); + + const updateRunSpeed = useCallback( + async (speedMultiplier: number | null) => { + if (!currentRun) { + return; + } + + try { + // Keep null as null for max speed (no limit) + const apiSpeed = speedMultiplier; + + // Only call API if run is active + if (currentRun.status === 'running' || currentRun.status === 'paused') { + await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed); + } + + // Always update local state so UI reflects the selection + setCurrentRun(prev => (prev ? { ...prev, speedMultiplier: apiSpeed } : null)); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to update run speed'); + } + }, + [currentRun] + ); + + // Select a specific run + const selectRun = useCallback( + async (runId: string | undefined) => { + if (!runId) { + setCurrentRun(null); + setRunResults(null); + stopMonitoringRun(); + return; + } + + let run = runs.find(r => r.id === runId); + + // If run not found in list, try to fetch it directly + if (!run) { + let attempts = 0; + const maxAttempts = 3; + + while (attempts < maxAttempts) { + try { + run = await backtestApiV2.getRun(runId); + + // Add to runs list if not present + setRuns(prevRuns => { + const exists = prevRuns.some(r => r.id === defined(run).id); + if (!exists) { + return [defined(run), ...prevRuns]; + } + return prevRuns; + }); + + break; // Success, exit loop + } catch (err) { + attempts++; + if (attempts >= maxAttempts) { + browserLog.error('Failed to fetch run after all attempts:', runId, err); + setError(`Failed to load run ${runId}`); + return; + } + // Wait before retrying + await new Promise(resolve => setTimeout(resolve, 1000)); + } + } + } + + if (!run) { + setError(`Run ${runId} not found`); + return; + } + setCurrentRun(run); + setRunResults(null); + + if (run.status === 'completed') { + try { + const results = await backtestApiV2.getRunResults(run.id); + setRunResults(results); + } catch (err) { + browserLog.error('Failed to load run results:', err); + setError(err instanceof Error ? err.message : 'Failed to load run results'); + } + } else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') { + startMonitoringRun(run.id); + } else { + browserLog.warn('Run has unexpected status:', run.status); + } + }, + [runs] + ); + + // Monitor run progress + const startMonitoringRun = useCallback((runId: string) => { + // Stop any existing monitoring + stopMonitoringRun(); + + // For pending runs, we need to poll until they start or complete + // We'll check the run status by fetching it + pollingIntervalRef.current = setInterval(async () => { + try { + const updatedRun = await backtestApiV2.getRun(runId); + // Update the run in state + setCurrentRun(updatedRun); + setRuns(prevRuns => prevRuns.map(r => (r.id === updatedRun.id ? updatedRun : r))); + + // If run is no longer pending, handle the new status + if (updatedRun.status === 'completed') { + stopMonitoringRun(); + try { + const results = await backtestApiV2.getRunResults(runId); + setRunResults(results); + } catch (err) { + browserLog.error('Failed to load completed run results:', err); + } + } else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') { + stopMonitoringRun(); + } + } catch (err) { + browserLog.error('Failed to poll run status:', err); + } + }, 1000); // Poll every second + }, []); + + const _startPollingRun = (runId: string) => { + pollingIntervalRef.current = setInterval(async () => { + try { + const updatedRun = await backtestApiV2.getRun(runId); + handleRunUpdate(updatedRun); + + if (updatedRun.status === 'completed') { + const results = await backtestApiV2.getRunResults(runId); + setRunResults(results); + stopMonitoringRun(); + } else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') { + stopMonitoringRun(); + } + } catch (err) { + browserLog.error('Failed to poll run status:', err); + } + }, 1000); // Poll every second + }; + + const stopMonitoringRun = () => { + if (pollingIntervalRef.current) { + clearInterval(pollingIntervalRef.current); + pollingIntervalRef.current = null; + } + }; + + const handleRunUpdate = (update: Run) => { + setCurrentRun(update); + setRuns(prevRuns => prevRuns.map(run => (run.id === update.id ? update : run))); + }; + + // Cleanup on unmount + useEffect(() => { + return () => { + stopMonitoringRun(); + }; + }, []); + + return { + backtest, + runs, + currentRun, + runResults, + isLoading, + error, + loadBacktest, + createBacktest, + updateBacktest, + deleteBacktest, + createRun, + pauseRun, + resumeRun, + cancelRun, + updateRunSpeed, + selectRun, + }; +} diff --git a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts index 84fe987c..e35c28ec 100644 --- a/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts +++ b/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts @@ -1,232 +1,244 @@ -const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003'; - -export interface Backtest { - id: string; - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config: Record; - createdAt: string; - updatedAt: string; -} - -export interface Run { - id: string; - backtestId: string; - runNumber: number; - status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; - speedMultiplier: number; - error?: string; - startedAt?: string; - completedAt?: string; - pausedAt?: string; - progress: number; - currentSimulationDate?: string; - createdAt: string; - updatedAt: string; -} - -export interface CreateBacktestRequest { - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - config?: Record; -} - -export interface CreateRunRequest { - speedMultiplier?: number | null; -} - -export interface RunResult { - runId: string; - backtestId: string; - status: 'completed'; - completedAt: string; - config: { - name: string; - strategy: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - commission: number; - slippage: number; - dataFrequency: string; - }; - metrics: any; - equity: any[]; - ohlcData: Record; - trades: any[]; - positions: any; - analytics: any; - executionTime: number; -} - -export const backtestApiV2 = { - // Backtest operations - async createBacktest(request: CreateBacktestRequest): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request), - }); - - if (!response.ok) { - throw new Error(`Failed to create backtest: ${response.statusText}`); - } - - return response.json(); - }, - - async getBacktest(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`); - - if (!response.ok) { - throw new Error(`Failed to get backtest: ${response.statusText}`); - } - - return response.json(); - }, - - async listBacktests(limit = 50, offset = 0): Promise { - const response = await fetch( - `${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}` - ); - - if (!response.ok) { - throw new Error(`Failed to list backtests: ${response.statusText}`); - } - - return response.json(); - }, - - async updateBacktest(id: string, updates: Partial): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(updates), - }); - - if (!response.ok) { - throw new Error(`Failed to update backtest: ${response.statusText}`); - } - - return response.json(); - }, - - async deleteBacktest(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, { - method: 'DELETE', - }); - - if (!response.ok) { - throw new Error(`Failed to delete backtest: ${response.statusText}`); - } - }, - - // Run operations - async createRun(backtestId: string, request?: CreateRunRequest): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request || {}), - }); - - if (!response.ok) { - const errorText = await response.text(); - console.error(`Failed to create run:`, response.status, errorText); - throw new Error(`Failed to create run: ${response.statusText}`); - } - - return response.json(); - }, - - async listRuns(backtestId: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`); - - if (!response.ok) { - throw new Error(`Failed to list runs: ${response.statusText}`); - } - - return response.json(); - }, - - async getRun(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`); - - if (!response.ok) { - throw new Error(`Failed to get run: ${response.statusText}`); - } - - return response.json(); - }, - - async getRunResults(runId: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`); - - if (!response.ok) { - throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`); - } - - return response.json(); - }, - - async pauseRun(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, { - method: 'POST', - }); - - if (!response.ok) { - throw new Error(`Failed to pause run: ${response.statusText}`); - } - }, - - async resumeRun(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, { - method: 'POST', - }); - - if (!response.ok) { - throw new Error(`Failed to resume run: ${response.statusText}`); - } - }, - - async cancelRun(id: string): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, { - method: 'POST', - }); - - if (!response.ok) { - throw new Error(`Failed to cancel run: ${response.statusText}`); - } - }, - - async updateRunSpeed(id: string, speedMultiplier: number): Promise { - const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ speedMultiplier }), - }); - - if (!response.ok) { - throw new Error(`Failed to update run speed: ${response.statusText}`); - } - }, - - // Note: WebSocket connections are handled by the useWebSocket hook - // which connects to ws://localhost:2003/ws?runId={runId} -}; \ No newline at end of file +import { browserLog } from '@/utils/browserLog'; +import type { BacktestMetrics, Position, Trade } from '../types/backtest.types'; + +const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003'; + +export interface Backtest { + id: string; + name: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config: Record; + createdAt: string; + updatedAt: string; +} + +export interface Run { + id: string; + backtestId: string; + runNumber: number; + status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused'; + speedMultiplier: number | null; + error?: string; + startedAt?: string; + completedAt?: string; + pausedAt?: string; + progress: number; + currentSimulationDate?: string; + createdAt: string; + updatedAt: string; +} + +export interface CreateBacktestRequest { + name: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + config?: Record; +} + +export interface CreateRunRequest { + speedMultiplier?: number | null; +} + +export interface RunResult { + runId: string; + backtestId: string; + status: 'completed'; + completedAt: string; + config: { + name: string; + strategy: string; + symbols: string[]; + startDate: string; + endDate: string; + initialCapital: number; + commission: number; + slippage: number; + dataFrequency: string; + }; + metrics: BacktestMetrics; + equity: { date: string; value: number }[]; + ohlcData: Record< + string, + { timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[] + >; + trades: Trade[]; + positions: Position[] | Record>; + analytics: { + exposureTime?: number; + drawdownSeries?: { timestamp: number; value: number }[]; + dailyReturns?: number[]; + monthlyReturns?: Record; + riskMetrics?: Record; + }; + executionTime: number; +} + +export const backtestApiV2 = { + // Backtest operations + async createBacktest(request: CreateBacktestRequest): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(request), + }); + + if (!response.ok) { + throw new Error(`Failed to create backtest: ${response.statusText}`); + } + + return response.json(); + }, + + async getBacktest(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`); + + if (!response.ok) { + throw new Error(`Failed to get backtest: ${response.statusText}`); + } + + return response.json(); + }, + + async listBacktests(limit = 50, offset = 0): Promise { + const response = await fetch( + `${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}` + ); + + if (!response.ok) { + throw new Error(`Failed to list backtests: ${response.statusText}`); + } + + return response.json(); + }, + + async updateBacktest(id: string, updates: Partial): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(updates), + }); + + if (!response.ok) { + throw new Error(`Failed to update backtest: ${response.statusText}`); + } + + return response.json(); + }, + + async deleteBacktest(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, { + method: 'DELETE', + }); + + if (!response.ok) { + throw new Error(`Failed to delete backtest: ${response.statusText}`); + } + }, + + // Run operations + async createRun(backtestId: string, request?: CreateRunRequest): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(request || {}), + }); + + if (!response.ok) { + const errorText = await response.text(); + browserLog.error(`Failed to create run:`, response.status, errorText); + throw new Error(`Failed to create run: ${response.statusText}`); + } + + return response.json(); + }, + + async listRuns(backtestId: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`); + + if (!response.ok) { + throw new Error(`Failed to list runs: ${response.statusText}`); + } + + return response.json(); + }, + + async getRun(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`); + + if (!response.ok) { + throw new Error(`Failed to get run: ${response.statusText}`); + } + + return response.json(); + }, + + async getRunResults(runId: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`); + + if (!response.ok) { + throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`); + } + + return response.json(); + }, + + async pauseRun(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, { + method: 'POST', + }); + + if (!response.ok) { + throw new Error(`Failed to pause run: ${response.statusText}`); + } + }, + + async resumeRun(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, { + method: 'POST', + }); + + if (!response.ok) { + throw new Error(`Failed to resume run: ${response.statusText}`); + } + }, + + async cancelRun(id: string): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, { + method: 'POST', + }); + + if (!response.ok) { + throw new Error(`Failed to cancel run: ${response.statusText}`); + } + }, + + async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { + const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ speedMultiplier }), + }); + + if (!response.ok) { + throw new Error(`Failed to update run speed: ${response.statusText}`); + } + }, + + // Note: WebSocket connections are handled by the useWebSocket hook + // which connects to ws://localhost:2003/ws?runId={runId} +}; diff --git a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts index 16c42538..3b533473 100644 --- a/apps/stock/web-app/src/features/backtest/types/backtest.types.ts +++ b/apps/stock/web-app/src/features/backtest/types/backtest.types.ts @@ -1,89 +1,103 @@ -export type BacktestStatus = - | 'idle' - | 'configured' - | 'running' - | 'paused' - | 'stopped' - | 'completed' - | 'error'; - -export interface BacktestConfig { - name: string; - startDate: Date; - endDate: Date; - initialCapital: number; - symbols: string[]; - strategy: string; - speedMultiplier: number; - commission: number; - slippage: number; -} - -export interface BacktestMetrics { - totalReturn: number; - sharpeRatio: number; - maxDrawdown: number; - winRate: number; - totalTrades: number; - profitableTrades: number; -} - -export interface Position { - symbol: string; - quantity: number; - averagePrice: number; - currentPrice: number; - realizedPnl: number; - unrealizedPnl: number; - lastUpdate: string; -} - -export interface Trade { - id: string; - timestamp: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - pnl?: number; - positionAfter: number; // Position size after this trade -} - -export interface PerformanceDataPoint { - timestamp: string; - portfolioValue: number; - pnl: number; - drawdown: number; -} - -export interface BacktestResult { - id: string; - config: BacktestConfig; - metrics: BacktestMetrics; - positions: Position[]; - trades: Trade[]; - performanceData: PerformanceDataPoint[]; -} - -export interface OrderBookLevel { - price: number; - size: number; - orderCount?: number; -} - -export interface OrderBookSnapshot { - symbol: string; - timestamp: string; - bids: OrderBookLevel[]; - asks: OrderBookLevel[]; -} - -export interface RiskMetrics { - currentExposure: number; - dailyPnl: number; - positionCount: number; - grossExposure: number; - maxPositionSize: number; - utilizationPct: number; -} \ No newline at end of file +export type BacktestStatus = + | 'idle' + | 'configured' + | 'running' + | 'paused' + | 'stopped' + | 'completed' + | 'error'; + +export interface BacktestConfig { + name: string; + startDate: Date; + endDate: Date; + initialCapital: number; + symbols: string[]; + strategy: string; + speedMultiplier: number; + commission: number; + slippage: number; +} + +export interface BacktestMetrics { + totalReturn: number; + sharpeRatio: number; + maxDrawdown: number; + winRate: number; + totalTrades: number; + profitableTrades: number; + profitFactor?: number; + totalProfit?: number; + avgWin?: number; + avgLoss?: number; + expectancy?: number; + calmarRatio?: number; + sortinoRatio?: number; +} + +export interface Position { + symbol: string; + quantity: number; + averagePrice: number; + currentPrice: number; + realizedPnl: number; + unrealizedPnl: number; + lastUpdate?: string; + avgPrice?: number; + lastPrice?: number; +} + +export interface Trade { + id: string; + timestamp: string; + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + price: number; + commission: number; + pnl?: number; + entryDate?: string; + entryPrice?: number; + date?: string; + realizedPnl?: number; + positionAfter: number; // Position size after this trade +} + +export interface PerformanceDataPoint { + timestamp: string; + portfolioValue: number; + pnl: number; + drawdown: number; +} + +export interface BacktestResult { + id: string; + config: BacktestConfig; + metrics: BacktestMetrics; + positions: Position[]; + trades: Trade[]; + performanceData: PerformanceDataPoint[]; + analytics?: { exposureTime?: number }; +} + +export interface OrderBookLevel { + price: number; + size: number; + orderCount?: number; +} + +export interface OrderBookSnapshot { + symbol: string; + timestamp: string; + bids: OrderBookLevel[]; + asks: OrderBookLevel[]; +} + +export interface RiskMetrics { + currentExposure: number; + dailyPnl: number; + positionCount: number; + grossExposure: number; + maxPositionSize: number; + utilizationPct: number; +} diff --git a/apps/stock/web-app/src/features/charts/ChartPage.tsx b/apps/stock/web-app/src/features/charts/ChartPage.tsx index a9851db7..fcc27fb4 100644 --- a/apps/stock/web-app/src/features/charts/ChartPage.tsx +++ b/apps/stock/web-app/src/features/charts/ChartPage.tsx @@ -1,286 +1,292 @@ -import { useState, useEffect } from 'react'; -import { SymbolChart } from './components/SymbolChart'; -import { ChartToolbar } from './components/ChartToolbar'; -import { IndicatorList } from './components/IndicatorList'; -import { IndicatorSelector } from './components/IndicatorSelector'; -import { IndicatorSettings, type IndicatorConfig } from './components/IndicatorSettings'; -import type { ChartConfig, CandlestickData, MarketData } from './types'; - -// Mock data generator for demonstration -function generateMockData(days: number = 365): CandlestickData[] { - const data: CandlestickData[] = []; - const now = new Date(); - let price = 100; - - for (let i = days; i >= 0; i--) { - const date = new Date(now); - date.setDate(date.getDate() - i); - - // Generate realistic price movement - const volatility = 0.02; - const trend = Math.random() > 0.5 ? 1 : -1; - const change = (Math.random() * volatility * 2 - volatility) * price; - - const open = price; - const close = price + change * trend; - const high = Math.max(open, close) + Math.random() * volatility * price; - const low = Math.min(open, close) - Math.random() * volatility * price; - const volume = Math.floor(1000000 + Math.random() * 9000000); - - data.push({ - time: Math.floor(date.getTime() / 1000), // Convert to Unix timestamp (seconds) - open: parseFloat(open.toFixed(2)), - high: parseFloat(high.toFixed(2)), - low: parseFloat(low.toFixed(2)), - close: parseFloat(close.toFixed(2)), - volume, - }); - - price = close; - } - - return data; -} - -interface ChartPageProps { - symbol?: string; - showHeader?: boolean; -} - -export function ChartPage({ symbol = 'AAPL', showHeader = true }: ChartPageProps = {}) { - const [config, setConfig] = useState({ - symbol, - interval: '1d', - chartType: 'candlestick', - showVolume: true, - indicators: [], - theme: 'dark', - }); - - const [chartData, setChartData] = useState([]); - const [marketData, setMarketData] = useState(null); - const [isLoading, setIsLoading] = useState(true); - const [showIndicatorSelector, setShowIndicatorSelector] = useState(false); - const [showIndicatorSettings, setShowIndicatorSettings] = useState(false); - const [selectedIndicator, setSelectedIndicator] = useState(null); - const [activeIndicators, setActiveIndicators] = useState([ - { - id: 'VOLUME', - name: 'Volume', - type: 'overlay', - visible: true, - parameters: {}, - style: { - color: '#3b82f6', - lineWidth: 1, - lineStyle: 'solid', - }, - } - ]); - const [showSidebar, setShowSidebar] = useState(false); - - // Keyboard shortcuts - useEffect(() => { - const handleKeyPress = (e: KeyboardEvent) => { - if (e.key === '/') { - e.preventDefault(); - setShowIndicatorSelector(true); - } - }; - - window.addEventListener('keydown', handleKeyPress); - return () => window.removeEventListener('keydown', handleKeyPress); - }, []); - - // Load chart data - useEffect(() => { - setIsLoading(true); - - // Simulate API call delay - setTimeout(() => { - const data = generateMockData(); - setChartData(data); - - // Set market data from latest candle - if (data.length > 0) { - const latest = data[data.length - 1]; - const previous = data[data.length - 2]; - const change = latest.close - previous.close; - const changePercent = (change / previous.close) * 100; - - setMarketData({ - symbol: config.symbol, - name: 'Apple Inc.', - price: latest.close, - change, - changePercent, - volume: latest.volume || 0, - high: latest.high, - low: latest.low, - open: latest.open, - previousClose: previous.close, - timestamp: new Date().toISOString(), - }); - } - - setIsLoading(false); - }, 1000); - }, [config.symbol, config.interval]); - - const handleConfigChange = (updates: Partial) => { - setConfig(prev => ({ ...prev, ...updates })); - }; - - const handleAddIndicators = (indicatorIds: string[]) => { - // Filter out indicators that already exist - const newIndicatorIds = indicatorIds.filter(id => !activeIndicators.find(i => i.id === id)); - - const newIndicators = newIndicatorIds.map(id => { - const colors: Record = { - SMA20: '#ff9800', - SMA50: '#2196f3', - EMA20: '#4caf50', - BB: '#ff5252', - VWAP: '#9c27b0', - RSI: '#00bcd4', - MACD: '#795548', - }; - - return { - id, - name: id.replace(/(\d+)/, ' $1'), - type: ['RSI', 'MACD'].includes(id) ? 'panel' : 'overlay', - visible: true, - parameters: {}, - style: { - color: colors[id] || '#9e9e9e', - lineWidth: 2, - lineStyle: 'solid' as const, - }, - } as IndicatorConfig; - }); - - const updatedIndicators = [...activeIndicators, ...newIndicators]; - setActiveIndicators(updatedIndicators); - setConfig(prev => ({ ...prev, indicators: updatedIndicators.filter(i => i.id !== 'VOLUME').map(i => i.id) })); - }; - - const handleRemoveIndicator = (id: string) => { - // Don't allow removing Volume indicator - if (id === 'VOLUME') return; - - setActiveIndicators(prev => prev.filter(i => i.id !== id)); - setConfig(prev => ({ ...prev, indicators: prev.indicators.filter(i => i !== id) })); - }; - - const handleToggleIndicatorVisibility = (id: string) => { - setActiveIndicators(prev => { - const updated = prev.map(i => - i.id === id ? { ...i, visible: !i.visible } : i - ); - // Force chart update by also updating config - if (id === 'VOLUME') { - const volumeIndicator = updated.find(i => i.id === 'VOLUME'); - setConfig(prevConfig => ({ - ...prevConfig, - showVolume: volumeIndicator?.visible ?? true - })); - } - return updated; - }); - }; - - const handleIndicatorSettings = (id: string) => { - const indicator = activeIndicators.find(i => i.id === id); - if (indicator) { - setSelectedIndicator(indicator); - setShowIndicatorSettings(true); - } - }; - - const handleSaveIndicatorSettings = (updatedConfig: IndicatorConfig) => { - setActiveIndicators(prev => prev.map(i => - i.id === updatedConfig.id ? updatedConfig : i - )); - }; - - return ( -
- {showHeader && ( -
-

Market Charts

-

- Real-time market data and advanced charting powered by TradingView. -

-
- )} - -
- {/* Left Sidebar - Indicator List */} - {showSidebar && ( - ({ - id: i.id, - name: i.name, - type: i.type, - visible: i.visible, - color: i.style.color, - }))} - onRemove={handleRemoveIndicator} - onToggleVisibility={handleToggleIndicatorVisibility} - onSettings={handleIndicatorSettings} - onAddIndicator={() => setShowIndicatorSelector(true)} - /> - )} - - {/* Main Chart Area */} -
- - -
- {isLoading ? ( -
-
-
-

Loading chart data...

-
-
- ) : ( - i.visible && i.id !== 'VOLUME').map(i => i.id), - showVolume: activeIndicators.find(i => i.id === 'VOLUME')?.visible ?? true, - }} - activeIndicators={activeIndicators} - onIndicatorSettings={handleIndicatorSettings} - onIndicatorRemove={handleRemoveIndicator} - onIndicatorToggle={handleToggleIndicatorVisibility} - onAddIndicator={() => setShowIndicatorSelector(true)} - className="h-full" - /> - )} -
-
-
- - {/* Indicator Selector Modal */} - setShowIndicatorSelector(false)} - selectedIndicators={activeIndicators.map(i => i.id)} - onIndicatorsChange={handleAddIndicators} - /> - - {/* Indicator Settings Modal */} - setShowIndicatorSettings(false)} - indicator={selectedIndicator} - onSave={handleSaveIndicatorSettings} - /> -
- ); -} \ No newline at end of file +import { useEffect, useState } from 'react'; +import { at } from '@stock-bot/invariants'; +import { ChartToolbar } from './components/ChartToolbar'; +import { IndicatorList } from './components/IndicatorList'; +import { IndicatorSelector } from './components/IndicatorSelector'; +import { IndicatorSettings, type IndicatorConfig } from './components/IndicatorSettings'; +import { SymbolChart } from './components/SymbolChart'; +import type { CandlestickData, ChartConfig, MarketData } from './types'; + +// Mock data generator for demonstration +function generateMockData(days: number = 365): CandlestickData[] { + const data: CandlestickData[] = []; + const now = new Date(); + let price = 100; + + for (let i = days; i >= 0; i--) { + const date = new Date(now); + date.setDate(date.getDate() - i); + + // Generate realistic price movement + const volatility = 0.02; + const trend = Math.random() > 0.5 ? 1 : -1; + const change = (Math.random() * volatility * 2 - volatility) * price; + + const open = price; + const close = price + change * trend; + const high = Math.max(open, close) + Math.random() * volatility * price; + const low = Math.min(open, close) - Math.random() * volatility * price; + const volume = Math.floor(1000000 + Math.random() * 9000000); + + data.push({ + time: Math.floor(date.getTime() / 1000), // Convert to Unix timestamp (seconds) + open: parseFloat(open.toFixed(2)), + high: parseFloat(high.toFixed(2)), + low: parseFloat(low.toFixed(2)), + close: parseFloat(close.toFixed(2)), + volume, + }); + + price = close; + } + + return data; +} + +interface ChartPageProps { + symbol?: string; + showHeader?: boolean; +} + +export function ChartPage({ symbol = 'AAPL', showHeader = true }: ChartPageProps = {}) { + const [config, setConfig] = useState({ + symbol, + interval: '1d', + chartType: 'candlestick', + showVolume: true, + indicators: [], + theme: 'dark', + }); + + const [chartData, setChartData] = useState([]); + const [_marketData, setMarketData] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [showIndicatorSelector, setShowIndicatorSelector] = useState(false); + const [showIndicatorSettings, setShowIndicatorSettings] = useState(false); + const [selectedIndicator, setSelectedIndicator] = useState(null); + const [activeIndicators, setActiveIndicators] = useState([ + { + id: 'VOLUME', + name: 'Volume', + type: 'overlay', + visible: true, + parameters: {}, + style: { + color: '#3b82f6', + lineWidth: 1, + lineStyle: 'solid', + }, + }, + ]); + const [showSidebar, _setShowSidebar] = useState(false); + + // Keyboard shortcuts + useEffect(() => { + const handleKeyPress = (e: KeyboardEvent) => { + if (e.key === '/') { + e.preventDefault(); + setShowIndicatorSelector(true); + } + }; + + window.addEventListener('keydown', handleKeyPress); + return () => window.removeEventListener('keydown', handleKeyPress); + }, []); + + // Load chart data + useEffect(() => { + setIsLoading(true); + + // Simulate API call delay + setTimeout(() => { + const data = generateMockData(); + setChartData(data); + + // Set market data from latest candle + if (data.length > 0) { + const latest = at(data, data.length - 1); + const previous = at(data, data.length - 2); + const change = latest.close - previous.close; + const changePercent = (change / previous.close) * 100; + + setMarketData({ + symbol: config.symbol, + name: 'Apple Inc.', + price: latest.close, + change, + changePercent, + volume: latest.volume || 0, + high: latest.high, + low: latest.low, + open: latest.open, + previousClose: previous.close, + timestamp: new Date().toISOString(), + }); + } + + setIsLoading(false); + }, 1000); + }, [config.symbol, config.interval]); + + const handleConfigChange = (updates: Partial) => { + setConfig(prev => ({ ...prev, ...updates })); + }; + + const handleAddIndicators = (indicatorIds: string[]) => { + // Filter out indicators that already exist + const newIndicatorIds = indicatorIds.filter(id => !activeIndicators.find(i => i.id === id)); + + const newIndicators = newIndicatorIds.map(id => { + const colors: Record = { + SMA20: '#ff9800', + SMA50: '#2196f3', + EMA20: '#4caf50', + BB: '#ff5252', + VWAP: '#9c27b0', + RSI: '#00bcd4', + MACD: '#795548', + }; + + return { + id, + name: id.replace(/(\d+)/, ' $1'), + type: ['RSI', 'MACD'].includes(id) ? 'panel' : 'overlay', + visible: true, + parameters: {}, + style: { + color: colors[id] || '#9e9e9e', + lineWidth: 2, + lineStyle: 'solid' as const, + }, + } as IndicatorConfig; + }); + + const updatedIndicators = [...activeIndicators, ...newIndicators]; + setActiveIndicators(updatedIndicators); + setConfig(prev => ({ + ...prev, + indicators: updatedIndicators.filter(i => i.id !== 'VOLUME').map(i => i.id), + })); + }; + + const handleRemoveIndicator = (id: string) => { + // Don't allow removing Volume indicator + if (id === 'VOLUME') { + return; + } + + setActiveIndicators(prev => prev.filter(i => i.id !== id)); + setConfig(prev => ({ ...prev, indicators: prev.indicators.filter(i => i !== id) })); + }; + + const handleToggleIndicatorVisibility = (id: string) => { + setActiveIndicators(prev => { + const updated = prev.map(i => (i.id === id ? { ...i, visible: !i.visible } : i)); + // Force chart update by also updating config + if (id === 'VOLUME') { + const volumeIndicator = updated.find(i => i.id === 'VOLUME'); + setConfig(prevConfig => ({ + ...prevConfig, + showVolume: volumeIndicator?.visible ?? true, + })); + } + return updated; + }); + }; + + const handleIndicatorSettings = (id: string) => { + const indicator = activeIndicators.find(i => i.id === id); + if (indicator) { + setSelectedIndicator(indicator); + setShowIndicatorSettings(true); + } + }; + + const handleSaveIndicatorSettings = (updatedConfig: IndicatorConfig) => { + setActiveIndicators(prev => prev.map(i => (i.id === updatedConfig.id ? updatedConfig : i))); + }; + + return ( +
+ {showHeader && ( +
+

Market Charts

+

+ Real-time market data and advanced charting powered by TradingView. +

+
+ )} + +
+ {/* Left Sidebar - Indicator List */} + {showSidebar && ( + ({ + id: i.id, + name: i.name, + type: i.type, + visible: i.visible, + color: i.style.color, + }))} + onRemove={handleRemoveIndicator} + onToggleVisibility={handleToggleIndicatorVisibility} + onSettings={handleIndicatorSettings} + onAddIndicator={() => setShowIndicatorSelector(true)} + /> + )} + + {/* Main Chart Area */} +
+ + +
+ {isLoading ? ( +
+
+
+

Loading chart data...

+
+
+ ) : ( + i.visible && i.id !== 'VOLUME') + .map(i => i.id), + showVolume: activeIndicators.find(i => i.id === 'VOLUME')?.visible ?? true, + }} + activeIndicators={activeIndicators} + onIndicatorSettings={handleIndicatorSettings} + onIndicatorRemove={handleRemoveIndicator} + onIndicatorToggle={handleToggleIndicatorVisibility} + onAddIndicator={() => setShowIndicatorSelector(true)} + className="h-full" + /> + )} +
+
+
+ + {/* Indicator Selector Modal */} + setShowIndicatorSelector(false)} + selectedIndicators={activeIndicators.map(i => i.id)} + onIndicatorsChange={handleAddIndicators} + /> + + {/* Indicator Settings Modal */} + setShowIndicatorSettings(false)} + indicator={selectedIndicator} + onSave={handleSaveIndicatorSettings} + /> +
+ ); +} diff --git a/apps/stock/web-app/src/features/charts/components/ChartOverlay.tsx b/apps/stock/web-app/src/features/charts/components/ChartOverlay.tsx index 4a5ffb56..6cc84fa8 100644 --- a/apps/stock/web-app/src/features/charts/components/ChartOverlay.tsx +++ b/apps/stock/web-app/src/features/charts/components/ChartOverlay.tsx @@ -1,141 +1,149 @@ -import { Cog6ToothIcon, XMarkIcon, EyeIcon, EyeSlashIcon, ChevronUpIcon, ChevronDownIcon, PlusIcon } from '@heroicons/react/24/outline'; -import { useState } from 'react'; - -interface IndicatorInfo { - id: string; - name: string; - value?: number; - color: string; - visible?: boolean; -} - -interface ChartOverlayProps { - symbol: string; - price?: number; - change?: number; - changePercent?: number; - indicators: IndicatorInfo[]; - onIndicatorSettings: (id: string) => void; - onIndicatorRemove: (id: string) => void; - onIndicatorToggle?: (id: string) => void; - onAddIndicator?: () => void; -} - -export function ChartOverlay({ - symbol, - price, - change, - changePercent, - indicators, - onIndicatorSettings, - onIndicatorRemove, - onIndicatorToggle, - onAddIndicator, -}: ChartOverlayProps) { - const [showIndicators, setShowIndicators] = useState(true); - - return ( -
- {/* Indicators */} - {(indicators.length > 0 || true) && ( -
- {/* Indicators Header with Toggle */} -
- Indicators - -
- - {/* Indicator List */} - {showIndicators && ( -
- {indicators.map((indicator) => ( -
- {/* Eye icon on the left */} - {onIndicatorToggle && ( - - )} - - {/* Color dot */} -
- - {/* Name and value */} -
- - {indicator.name} - - {indicator.value !== undefined && indicator.visible !== false && ( - - {indicator.value.toFixed(2)} - - )} -
- - {/* Spacer to push buttons to the right */} -
- - {/* Settings and Remove on the right */} -
- - {indicator.id !== 'VOLUME' && ( - - )} -
-
- ))} - - {/* Add Indicator Button */} - {onAddIndicator && ( - - )} -
- )} -
- )} -
- ); -} \ No newline at end of file +import { + ChevronDownIcon, + ChevronUpIcon, + Cog6ToothIcon, + EyeIcon, + EyeSlashIcon, + PlusIcon, + XMarkIcon, +} from '@heroicons/react/24/outline'; +import { useState } from 'react'; + +interface IndicatorInfo { + id: string; + name: string; + value?: number; + color: string; + visible?: boolean; +} + +interface ChartOverlayProps { + symbol: string; + price?: number; + change?: number; + changePercent?: number; + indicators: IndicatorInfo[]; + onIndicatorSettings: (id: string) => void; + onIndicatorRemove: (id: string) => void; + onIndicatorToggle?: (id: string) => void; + onAddIndicator?: () => void; +} + +export function ChartOverlay({ + symbol: _symbol, + price: _price, + change: _change, + changePercent: _changePercent, + indicators, + onIndicatorSettings, + onIndicatorRemove, + onIndicatorToggle, + onAddIndicator, +}: ChartOverlayProps) { + const [showIndicators, setShowIndicators] = useState(true); + + return ( +
+ {/* Indicators */} + { +
+ {/* Indicators Header with Toggle */} +
+ Indicators + +
+ + {/* Indicator List */} + {showIndicators && ( +
+ {indicators.map(indicator => ( +
+ {/* Eye icon on the left */} + {onIndicatorToggle && ( + + )} + + {/* Color dot */} +
+ + {/* Name and value */} +
+ + {indicator.name} + + {indicator.value !== undefined && indicator.visible !== false && ( + + {indicator.value.toFixed(2)} + + )} +
+ + {/* Spacer to push buttons to the right */} +
+ + {/* Settings and Remove on the right */} +
+ + {indicator.id !== 'VOLUME' && ( + + )} +
+
+ ))} + + {/* Add Indicator Button */} + {onAddIndicator && ( + + )} +
+ )} +
+ } +
+ ); +} diff --git a/apps/stock/web-app/src/features/charts/components/IndicatorSettings.tsx b/apps/stock/web-app/src/features/charts/components/IndicatorSettings.tsx index 20bc8948..199fff8f 100644 --- a/apps/stock/web-app/src/features/charts/components/IndicatorSettings.tsx +++ b/apps/stock/web-app/src/features/charts/components/IndicatorSettings.tsx @@ -1,261 +1,291 @@ -import { Fragment, useState, useEffect } from 'react'; -import { Dialog, Transition } from '@headlessui/react'; -import { XMarkIcon } from '@heroicons/react/24/outline'; - -export interface IndicatorConfig { - id: string; - name: string; - type: 'overlay' | 'panel'; - parameters: Record; - style: { - color?: string; - lineWidth?: number; - lineStyle?: 'solid' | 'dashed' | 'dotted'; - }; -} - -interface IndicatorSettingsProps { - isOpen: boolean; - onClose: () => void; - indicator: IndicatorConfig | null; - onSave: (config: IndicatorConfig) => void; -} - -const indicatorParameters: Record> = { - SMA20: [ - { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }, - ], - SMA50: [ - { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }, - ], - EMA20: [ - { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }, - ], - BB: [ - { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }, - { key: 'stdDev', label: 'Standard Deviation', type: 'number', min: 0.1, max: 5 }, - ], - RSI: [ - { key: 'period', label: 'Period', type: 'number', min: 1, max: 100 }, - { key: 'overbought', label: 'Overbought Level', type: 'number', min: 50, max: 100 }, - { key: 'oversold', label: 'Oversold Level', type: 'number', min: 0, max: 50 }, - ], - MACD: [ - { key: 'fastPeriod', label: 'Fast Period', type: 'number', min: 1, max: 200 }, - { key: 'slowPeriod', label: 'Slow Period', type: 'number', min: 1, max: 200 }, - { key: 'signalPeriod', label: 'Signal Period', type: 'number', min: 1, max: 200 }, - ], -}; - -const defaultParameters: Record> = { - SMA20: { period: 20 }, - SMA50: { period: 50 }, - EMA20: { period: 20 }, - BB: { period: 20, stdDev: 2 }, - RSI: { period: 14, overbought: 70, oversold: 30 }, - MACD: { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }, - VWAP: {}, -}; - -const lineStyles = [ - { value: 'solid', label: 'Solid' }, - { value: 'dashed', label: 'Dashed' }, - { value: 'dotted', label: 'Dotted' }, -]; - -export function IndicatorSettings({ isOpen, onClose, indicator, onSave }: IndicatorSettingsProps) { - const [config, setConfig] = useState(null); - - useEffect(() => { - if (indicator) { - setConfig({ - ...indicator, - parameters: { ...defaultParameters[indicator.id], ...indicator.parameters }, - }); - } - }, [indicator]); - - if (!config || !indicator) return null; - - const handleParameterChange = (key: string, value: any) => { - setConfig({ - ...config, - parameters: { - ...config.parameters, - [key]: value, - }, - }); - }; - - const handleStyleChange = (key: string, value: any) => { - setConfig({ - ...config, - style: { - ...config.style, - [key]: value, - }, - }); - }; - - const handleSave = () => { - onSave(config); - onClose(); - }; - - const parameters = indicatorParameters[indicator.id] || []; - - return ( - - - -
- - -
-
- - -
-
- - {config.name} Settings - - -
- -
- {/* Parameters */} - {parameters.length > 0 && ( -
-

Parameters

-
- {parameters.map(param => ( -
- - {param.type === 'number' ? ( - handleParameterChange(param.key, parseFloat(e.target.value))} - className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - /> - ) : ( - - )} -
- ))} -
-
- )} - - {/* Style */} -
-

Style

-
-
- -
- handleStyleChange('color', e.target.value)} - className="w-10 h-10 rounded border border-border cursor-pointer" - /> - handleStyleChange('color', e.target.value)} - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - /> -
-
- -
- - handleStyleChange('lineWidth', parseInt(e.target.value))} - className="w-full" - /> -
- {config.style.lineWidth || 2}px -
-
- -
- - -
-
-
-
-
- -
- - -
-
-
-
-
-
-
- ); -} \ No newline at end of file +import { Dialog, Transition } from '@headlessui/react'; +import { XMarkIcon } from '@heroicons/react/24/outline'; +import { Fragment, useEffect, useState } from 'react'; + +export interface IndicatorConfig { + id: string; + name: string; + visible: boolean; + type: 'overlay' | 'panel'; + parameters: Record; + style: { + color?: string; + lineWidth?: import('lightweight-charts').LineWidth; + lineStyle?: 'solid' | 'dashed' | 'dotted'; + }; +} + +interface IndicatorSettingsProps { + isOpen: boolean; + onClose: () => void; + indicator: IndicatorConfig | null; + onSave: (config: IndicatorConfig) => void; +} + +const indicatorParameters: Record< + string, + Array<{ + key: string; + label: string; + type: 'number' | 'select'; + min?: number; + max?: number; + options?: string[]; + }> +> = { + SMA20: [{ key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }], + SMA50: [{ key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }], + EMA20: [{ key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }], + BB: [ + { key: 'period', label: 'Period', type: 'number', min: 1, max: 200 }, + { key: 'stdDev', label: 'Standard Deviation', type: 'number', min: 0.1, max: 5 }, + ], + RSI: [ + { key: 'period', label: 'Period', type: 'number', min: 1, max: 100 }, + { key: 'overbought', label: 'Overbought Level', type: 'number', min: 50, max: 100 }, + { key: 'oversold', label: 'Oversold Level', type: 'number', min: 0, max: 50 }, + ], + MACD: [ + { key: 'fastPeriod', label: 'Fast Period', type: 'number', min: 1, max: 200 }, + { key: 'slowPeriod', label: 'Slow Period', type: 'number', min: 1, max: 200 }, + { key: 'signalPeriod', label: 'Signal Period', type: 'number', min: 1, max: 200 }, + ], +}; + +const defaultParameters: Record> = { + SMA20: { period: 20 }, + SMA50: { period: 50 }, + EMA20: { period: 20 }, + BB: { period: 20, stdDev: 2 }, + RSI: { period: 14, overbought: 70, oversold: 30 }, + MACD: { fastPeriod: 12, slowPeriod: 26, signalPeriod: 9 }, + VWAP: {}, +}; + +const lineStyles = [ + { value: 'solid', label: 'Solid' }, + { value: 'dashed', label: 'Dashed' }, + { value: 'dotted', label: 'Dotted' }, +]; + +export function IndicatorSettings({ isOpen, onClose, indicator, onSave }: IndicatorSettingsProps) { + const [config, setConfig] = useState(null); + + useEffect(() => { + if (indicator) { + setConfig({ + ...indicator, + parameters: { ...defaultParameters[indicator.id], ...indicator.parameters }, + }); + } + }, [indicator]); + + if (!config || !indicator) { + return null; + } + + const handleParameterChange = (key: string, value: number | string) => { + setConfig({ + ...config, + parameters: { + ...config.parameters, + [key]: value, + }, + }); + }; + + const handleStyleChange = ( + key: K, + value: IndicatorConfig['style'][K] + ) => { + setConfig({ + ...config, + style: { + ...config.style, + [key]: value, + }, + }); + }; + + const handleSave = () => { + onSave(config); + onClose(); + }; + + const parameters = indicatorParameters[indicator.id] || []; + + return ( + + + +
+ + +
+
+ + +
+
+ + {config.name} Settings + + +
+ +
+ {/* Parameters */} + {parameters.length > 0 && ( +
+

Parameters

+
+ {parameters.map(param => ( +
+ + {param.type === 'number' ? ( + + handleParameterChange(param.key, parseFloat(e.target.value)) + } + className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + /> + ) : ( + + )} +
+ ))} +
+
+ )} + + {/* Style */} +
+

Style

+
+
+ +
+ handleStyleChange('color', e.target.value)} + className="w-10 h-10 rounded border border-border cursor-pointer" + /> + handleStyleChange('color', e.target.value)} + className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + /> +
+
+ +
+ + + handleStyleChange( + 'lineWidth', + parseInt(e.target.value) as import('lightweight-charts').LineWidth + ) + } + className="w-full" + /> +
+ {config.style.lineWidth || 2}px +
+
+ +
+ + +
+
+
+
+
+ +
+ + +
+
+
+
+
+
+
+ ); +} diff --git a/apps/stock/web-app/src/features/charts/components/SymbolChart.tsx b/apps/stock/web-app/src/features/charts/components/SymbolChart.tsx index 36137f88..77f8f1e2 100644 --- a/apps/stock/web-app/src/features/charts/components/SymbolChart.tsx +++ b/apps/stock/web-app/src/features/charts/components/SymbolChart.tsx @@ -1,425 +1,506 @@ -import * as LightweightCharts from 'lightweight-charts'; -import { useEffect, useRef, useState } from 'react'; -import type { CandlestickData, ChartConfig, ChartOptions } from '../types'; -import { calculateBollingerBands, calculateEMA, calculateSMA, calculateVWAP } from '../utils/indicators'; -import { ChartOverlay } from './ChartOverlay'; - -interface SymbolChartProps { - symbol: string; - data: CandlestickData[]; - config?: Partial; - options?: ChartOptions; - className?: string; - onIndicatorSettings?: (id: string) => void; - onIndicatorRemove?: (id: string) => void; - onIndicatorToggle?: (id: string) => void; - onAddIndicator?: () => void; - activeIndicators?: Array<{ - id: string; - name: string; - color: string; - visible: boolean; - }>; -} - -export function SymbolChart({ - symbol, - data, - config = {}, - options = {}, - className = '', - onIndicatorSettings, - onIndicatorRemove, - onIndicatorToggle, - onAddIndicator, - activeIndicators = [], -}: SymbolChartProps) { - const chartContainerRef = useRef(null); - const chartRef = useRef(null); - const seriesRef = useRef | null>(null); - const volumeSeriesRef = useRef | null>(null); - const indicatorSeriesRef = useRef>>(new Map()); - const [chartInitialized, setChartInitialized] = useState(false); - const [isLoading, setIsLoading] = useState(true); - const [currentPrice, setCurrentPrice] = useState<{ price: number; change: number; changePercent: number } | null>(null); - const [indicatorValues, setIndicatorValues] = useState>(new Map()); - - // Default configuration - const chartConfig: ChartConfig = { - symbol, - interval: '1d', - chartType: 'candlestick', - showVolume: true, - indicators: [], - theme: 'dark', - ...config, - }; - - // Set initial price from last candle - useEffect(() => { - if (data.length > 0 && !currentPrice) { - const latest = data[data.length - 1]; - const previous = data.length > 1 ? data[data.length - 2] : latest; - const change = latest.close - previous.close; - const changePercent = (change / previous.close) * 100; - setCurrentPrice({ price: latest.close, change, changePercent }); - } - }, [data, currentPrice]); - - useEffect(() => { - if (!chartContainerRef.current) return; - - // Create chart - const chart = LightweightCharts.createChart(chartContainerRef.current, { - width: chartContainerRef.current.clientWidth, - height: chartContainerRef.current.clientHeight || 500, - layout: { - background: { type: LightweightCharts.ColorType.Solid, color: chartConfig.theme === 'dark' ? '#0f0f0f' : '#ffffff' }, - textColor: chartConfig.theme === 'dark' ? '#d1d5db' : '#374151', - }, - grid: { - vertLines: { - color: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', - visible: true, - }, - horzLines: { - color: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', - visible: true, - }, - }, - crosshair: { - mode: LightweightCharts.CrosshairMode.Normal, - }, - rightPriceScale: { - borderColor: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', - }, - timeScale: { - borderColor: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', - timeVisible: true, - secondsVisible: false, - }, - }); - - chartRef.current = chart; - - // Create a new map for this chart instance - indicatorSeriesRef.current = new Map(); - - // Create main series based on chart type - if (chartConfig.chartType === 'candlestick') { - seriesRef.current = chart.addCandlestickSeries({ - upColor: '#10b981', - downColor: '#ef4444', - borderUpColor: '#10b981', - borderDownColor: '#ef4444', - wickUpColor: '#10b981', - wickDownColor: '#ef4444', - }); - } else if (chartConfig.chartType === 'line') { - seriesRef.current = chart.addLineSeries({ - color: '#3b82f6', - lineWidth: 2, - }); - } else if (chartConfig.chartType === 'area') { - seriesRef.current = chart.addAreaSeries({ - lineColor: '#3b82f6', - topColor: '#3b82f6', - bottomColor: 'rgba(59, 130, 246, 0.1)', - lineWidth: 2, - }); - } else if (chartConfig.chartType === 'bar') { - seriesRef.current = chart.addBarSeries({ - upColor: '#10b981', - downColor: '#ef4444', - }); - } - - // Create volume series if data has volume - if (data.some(d => d.volume)) { - const volumeIndicator = activeIndicators.find(i => i.id === 'VOLUME'); - const volumeVisible = volumeIndicator ? volumeIndicator.visible : chartConfig.showVolume; - - volumeSeriesRef.current = chart.addHistogramSeries({ - color: '#3b82f680', - priceFormat: { - type: 'volume', - }, - priceScaleId: 'volume', - visible: volumeVisible, - }); - volumeSeriesRef.current.priceScale().applyOptions({ - scaleMargins: { - top: 0.9, // highest point of the series will be 70% away from the top - bottom: 0, - }, - }); - } - - // Set data - if (seriesRef.current && data.length > 0) { - if (chartConfig.chartType === 'candlestick' || chartConfig.chartType === 'bar') { - seriesRef.current.setData(data); - } else if (chartConfig.chartType === 'line' || chartConfig.chartType === 'area') { - // Convert candlestick data to line/area data (using close price) - const lineData = data.map(d => ({ time: d.time, value: d.close })); - seriesRef.current.setData(lineData); - } - - // Set volume data if available - if (volumeSeriesRef.current) { - const volumeData = data - .filter(d => d.volume) - .map(d => ({ - time: d.time, - value: d.volume!, - color: d.close >= d.open ? '#10b98180' : '#ef444480', - })); - volumeSeriesRef.current.setData(volumeData); - } - - // Add indicators - include all indicators from activeIndicators, not just visible ones - if (activeIndicators && activeIndicators.length > 0) { - activeIndicators.filter(ind => ind.id !== 'VOLUME').forEach(indicator => { - const indicatorId = indicator.id; - if (indicatorId === 'SMA20') { - const sma20 = calculateSMA(data, 20); - const sma20Series = chart.addLineSeries({ - color: indicator.style?.color || '#ff9800', - lineWidth: indicator.style?.lineWidth || 2, - title: 'SMA 20', - visible: indicator.visible, - }); - sma20Series.setData(sma20); - indicatorSeriesRef.current.set('SMA20', sma20Series); - } - - if (indicatorId === 'SMA50') { - const sma50 = calculateSMA(data, 50); - const sma50Series = chart.addLineSeries({ - color: indicator.style?.color || '#2196f3', - lineWidth: indicator.style?.lineWidth || 2, - title: 'SMA 50', - visible: indicator.visible, - }); - sma50Series.setData(sma50); - indicatorSeriesRef.current.set('SMA50', sma50Series); - } - - if (indicatorId === 'EMA20') { - const ema20 = calculateEMA(data, 20); - const ema20Series = chart.addLineSeries({ - color: indicator.style?.color || '#4caf50', - lineWidth: indicator.style?.lineWidth || 2, - title: 'EMA 20', - visible: indicator.visible, - }); - ema20Series.setData(ema20); - indicatorSeriesRef.current.set('EMA20', ema20Series); - } - - if (indicatorId === 'BB') { - const bb = calculateBollingerBands(data, 20, 2); - - const bbUpperSeries = chart.addLineSeries({ - color: indicator.style?.color || '#ff5252', - lineWidth: 1, - lineStyle: LightweightCharts.LineStyle.Dashed, - title: 'BB Upper', - visible: indicator.visible, - }); - bbUpperSeries.setData(bb.upper); - indicatorSeriesRef.current.set('BB_upper', bbUpperSeries); - - const bbMiddleSeries = chart.addLineSeries({ - color: '#9e9e9e', - lineWidth: 1, - title: 'BB Middle', - visible: indicator.visible, - }); - bbMiddleSeries.setData(bb.middle); - indicatorSeriesRef.current.set('BB_middle', bbMiddleSeries); - - const bbLowerSeries = chart.addLineSeries({ - color: '#4caf50', - lineWidth: 1, - lineStyle: LightweightCharts.LineStyle.Dashed, - title: 'BB Lower', - visible: indicator.visible, - }); - bbLowerSeries.setData(bb.lower); - indicatorSeriesRef.current.set('BB_lower', bbLowerSeries); - } - - if (indicatorId === 'VWAP') { - const vwap = calculateVWAP(data); - const vwapSeries = chart.addLineSeries({ - color: indicator.style?.color || '#9c27b0', - lineWidth: indicator.style?.lineWidth || 2, - title: 'VWAP', - visible: indicator.visible, - }); - vwapSeries.setData(vwap); - indicatorSeriesRef.current.set('VWAP', vwapSeries); - } - }); - } - - // Subscribe to crosshair move for tracking values - chart.subscribeCrosshairMove((param) => { - if (!param || !param.time || !param.seriesData) return; - - // Update price info - const mainSeriesData = param.seriesData.get(seriesRef.current!); - if (mainSeriesData) { - const currentData = mainSeriesData as any; - const price = currentData.close || currentData.value || 0; - - // Find previous close - const currentIndex = data.findIndex(d => d.time === param.time); - const previousClose = currentIndex > 0 ? data[currentIndex - 1].close : price; - const change = price - previousClose; - const changePercent = (change / previousClose) * 100; - - setCurrentPrice({ price, change, changePercent }); - } - - // Update indicator values - const newIndicatorValues = new Map(); - indicatorSeriesRef.current.forEach((series, indicatorId) => { - const indicatorData = param.seriesData.get(series); - if (indicatorData && 'value' in indicatorData) { - newIndicatorValues.set(indicatorId, indicatorData.value); - } - }); - setIndicatorValues(newIndicatorValues); - }); - - // Fit content only on initial load - chart.timeScale().fitContent(); - setIsLoading(false); - setChartInitialized(true); - } - - // Handle resize - const handleResize = () => { - if (chartContainerRef.current && chart) { - chart.applyOptions({ - width: chartContainerRef.current.clientWidth, - height: chartContainerRef.current.clientHeight, - }); - } - }; - - window.addEventListener('resize', handleResize); - - // Cleanup - return () => { - window.removeEventListener('resize', handleResize); - setChartInitialized(false); - if (chart) { - chart.remove(); - } - }; - }, [data.length, chartConfig.theme, chartConfig.chartType, activeIndicators.length]); // Include activeIndicators.length to recreate when indicators are added/removed - - // Update data when it changes - useEffect(() => { - if (!seriesRef.current || !data.length) return; - - if (chartConfig.chartType === 'candlestick' || chartConfig.chartType === 'bar') { - seriesRef.current.setData(data); - } else if (chartConfig.chartType === 'line' || chartConfig.chartType === 'area') { - const lineData = data.map(d => ({ time: d.time, value: d.close })); - seriesRef.current.setData(lineData); - } - - if (volumeSeriesRef.current) { - const volumeData = data - .filter(d => d.volume) - .map(d => ({ - time: d.time, - value: d.volume!, - color: d.close >= d.open ? '#10b98180' : '#ef444480', - })); - volumeSeriesRef.current.setData(volumeData); - } - - // Don't fit content on data updates to preserve user's zoom/pan - // chartRef.current?.timeScale().fitContent(); - }, [data, chartConfig.chartType]); - - // Create a dependency string that captures visibility changes - const visibilityKey = activeIndicators.map(i => `${i.id}:${i.visible}`).join(','); - - // Handle indicator visibility changes without recreating chart - useEffect(() => { - if (!chartRef.current || !chartInitialized) return; - - // Update volume visibility - if (volumeSeriesRef.current) { - const volumeIndicator = activeIndicators.find(i => i.id === 'VOLUME'); - const volumeVisible = volumeIndicator ? volumeIndicator.visible : chartConfig.showVolume; - volumeSeriesRef.current.applyOptions({ - visible: volumeVisible, - }); - } - - // Update indicator visibility - activeIndicators.forEach(indicator => { - if (indicator.id === 'VOLUME') return; // Skip volume, handled above - - // For indicators with multiple series (like Bollinger Bands) - if (indicator.id === 'BB') { - ['BB_upper', 'BB_middle', 'BB_lower'].forEach(seriesId => { - const series = indicatorSeriesRef.current.get(seriesId); - if (series) { - series.applyOptions({ visible: indicator.visible }); - } - }); - } else { - // For single series indicators - const series = indicatorSeriesRef.current.get(indicator.id); - if (series) { - series.applyOptions({ visible: indicator.visible }); - } - } - }); - }, [chartConfig.showVolume, visibilityKey, chartInitialized]); - - // Prepare indicator info for overlay - include all indicators - const indicatorInfo = activeIndicators.map(indicator => ({ - id: indicator.id, - name: indicator.name, - value: indicator.visible ? indicatorValues.get(indicator.id) : undefined, - color: indicator.color, - visible: indicator.visible, - })); - - return ( -
- {isLoading && ( -
-
-
- )} - - {/* Chart container */} -
- - {/* Chart Overlay with indicators */} - {!isLoading && onIndicatorSettings && onIndicatorRemove && ( - - )} -
- ); -} \ No newline at end of file +import * as LightweightCharts from 'lightweight-charts'; +import { useEffect, useRef, useState } from 'react'; +import { at, defined } from '@stock-bot/invariants'; +import type { CandlestickData, ChartConfig, ChartOptions } from '../types'; +import { + calculateBollingerBands, + calculateEMA, + calculateSMA, + calculateVWAP, +} from '../utils/indicators'; +import { ChartOverlay } from './ChartOverlay'; +import type { IndicatorConfig } from './IndicatorSettings'; + +interface SymbolChartProps { + symbol: string; + data: CandlestickData[]; + config?: Partial; + options?: ChartOptions; + className?: string; + onIndicatorSettings?: (id: string) => void; + onIndicatorRemove?: (id: string) => void; + onIndicatorToggle?: (id: string) => void; + onAddIndicator?: () => void; + activeIndicators?: IndicatorConfig[]; +} + +export function SymbolChart({ + symbol, + data, + config = {}, + options: _options = {}, + className = '', + onIndicatorSettings, + onIndicatorRemove, + onIndicatorToggle, + onAddIndicator, + activeIndicators = [], +}: SymbolChartProps) { + const chartContainerRef = useRef(null); + const chartRef = useRef(null); + const seriesRef = useRef | null>(null); + const volumeSeriesRef = useRef | null>( + null + ); + const indicatorSeriesRef = useRef< + Map> + >(new Map()); + const [chartInitialized, setChartInitialized] = useState(false); + const [isLoading, setIsLoading] = useState(true); + const [currentPrice, setCurrentPrice] = useState<{ + price: number; + change: number; + changePercent: number; + } | null>(null); + const [indicatorValues, setIndicatorValues] = useState>(new Map()); + + // Default configuration + const chartConfig: ChartConfig = { + symbol, + interval: '1d', + chartType: 'candlestick', + showVolume: true, + indicators: [], + theme: 'dark', + ...config, + }; + + // Set initial price from last candle + useEffect(() => { + if (data.length > 0 && !currentPrice) { + const latest = at(data, data.length - 1); + const previous = data.length > 1 ? at(data, data.length - 2) : latest; + const change = latest.close - previous.close; + const changePercent = (change / previous.close) * 100; + setCurrentPrice({ price: latest.close, change, changePercent }); + } + }, [data, currentPrice]); + + useEffect(() => { + if (!chartContainerRef.current) { + return; + } + + // Create chart + const chart = LightweightCharts.createChart(chartContainerRef.current, { + width: chartContainerRef.current.clientWidth, + height: chartContainerRef.current.clientHeight || 500, + layout: { + background: { + type: LightweightCharts.ColorType.Solid, + color: chartConfig.theme === 'dark' ? '#0f0f0f' : '#ffffff', + }, + textColor: chartConfig.theme === 'dark' ? '#d1d5db' : '#374151', + }, + grid: { + vertLines: { + color: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', + visible: true, + }, + horzLines: { + color: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', + visible: true, + }, + }, + crosshair: { + mode: LightweightCharts.CrosshairMode.Normal, + }, + rightPriceScale: { + borderColor: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', + }, + timeScale: { + borderColor: chartConfig.theme === 'dark' ? '#1f2937' : '#e5e7eb', + timeVisible: true, + secondsVisible: false, + }, + }); + + chartRef.current = chart; + + // Create a new map for this chart instance + indicatorSeriesRef.current = new Map(); + + // Create main series based on chart type + if (chartConfig.chartType === 'candlestick') { + seriesRef.current = chart.addCandlestickSeries({ + upColor: '#10b981', + downColor: '#ef4444', + borderUpColor: '#10b981', + borderDownColor: '#ef4444', + wickUpColor: '#10b981', + wickDownColor: '#ef4444', + }); + } else if (chartConfig.chartType === 'line') { + seriesRef.current = chart.addLineSeries({ + color: '#3b82f6', + lineWidth: 2, + }); + } else if (chartConfig.chartType === 'area') { + seriesRef.current = chart.addAreaSeries({ + lineColor: '#3b82f6', + topColor: '#3b82f6', + bottomColor: 'rgba(59, 130, 246, 0.1)', + lineWidth: 2, + }); + } else if (chartConfig.chartType === 'bar') { + seriesRef.current = chart.addBarSeries({ + upColor: '#10b981', + downColor: '#ef4444', + }); + } + + // Create volume series if data has volume + if (data.some(d => d.volume)) { + const volumeIndicator = activeIndicators.find(i => i.id === 'VOLUME'); + const volumeVisible = volumeIndicator ? volumeIndicator.visible : chartConfig.showVolume; + + volumeSeriesRef.current = chart.addHistogramSeries({ + color: '#3b82f680', + priceFormat: { + type: 'volume', + }, + priceScaleId: 'volume', + visible: volumeVisible, + }); + volumeSeriesRef.current.priceScale().applyOptions({ + scaleMargins: { + top: 0.9, // highest point of the series will be 70% away from the top + bottom: 0, + }, + }); + } + + // Set data + if (seriesRef.current && data.length > 0) { + if (chartConfig.chartType === 'candlestick' || chartConfig.chartType === 'bar') { + seriesRef.current.setData( + data.map(point => ({ ...point, time: point.time as LightweightCharts.UTCTimestamp })) + ); + } else if (chartConfig.chartType === 'line' || chartConfig.chartType === 'area') { + // Convert candlestick data to line/area data (using close price) + const lineData = data.map(d => ({ + time: d.time as LightweightCharts.UTCTimestamp, + value: d.close, + })); + seriesRef.current.setData(lineData); + } + + // Set volume data if available + if (volumeSeriesRef.current) { + const volumeData = data + .filter(d => d.volume) + .map(d => ({ + time: d.time as LightweightCharts.UTCTimestamp, + value: defined(d.volume), + color: d.close >= d.open ? '#10b98180' : '#ef444480', + })); + volumeSeriesRef.current.setData( + volumeData.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + } + + // Add indicators - include all indicators from activeIndicators, not just visible ones + if (activeIndicators && activeIndicators.length > 0) { + activeIndicators + .filter(ind => ind.id !== 'VOLUME') + .forEach(indicator => { + const indicatorId = indicator.id; + if (indicatorId === 'SMA20') { + const sma20 = calculateSMA(data, 20); + const sma20Series = chart.addLineSeries({ + color: indicator.style?.color || '#ff9800', + lineWidth: indicator.style?.lineWidth || 2, + title: 'SMA 20', + visible: indicator.visible, + }); + sma20Series.setData( + sma20.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('SMA20', sma20Series); + } + + if (indicatorId === 'SMA50') { + const sma50 = calculateSMA(data, 50); + const sma50Series = chart.addLineSeries({ + color: indicator.style?.color || '#2196f3', + lineWidth: indicator.style?.lineWidth || 2, + title: 'SMA 50', + visible: indicator.visible, + }); + sma50Series.setData( + sma50.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('SMA50', sma50Series); + } + + if (indicatorId === 'EMA20') { + const ema20 = calculateEMA(data, 20); + const ema20Series = chart.addLineSeries({ + color: indicator.style?.color || '#4caf50', + lineWidth: indicator.style?.lineWidth || 2, + title: 'EMA 20', + visible: indicator.visible, + }); + ema20Series.setData( + ema20.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('EMA20', ema20Series); + } + + if (indicatorId === 'BB') { + const bb = calculateBollingerBands(data, 20, 2); + + const bbUpperSeries = chart.addLineSeries({ + color: indicator.style?.color || '#ff5252', + lineWidth: 1, + lineStyle: LightweightCharts.LineStyle.Dashed, + title: 'BB Upper', + visible: indicator.visible, + }); + bbUpperSeries.setData( + bb.upper.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('BB_upper', bbUpperSeries); + + const bbMiddleSeries = chart.addLineSeries({ + color: '#9e9e9e', + lineWidth: 1, + title: 'BB Middle', + visible: indicator.visible, + }); + bbMiddleSeries.setData( + bb.middle.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('BB_middle', bbMiddleSeries); + + const bbLowerSeries = chart.addLineSeries({ + color: '#4caf50', + lineWidth: 1, + lineStyle: LightweightCharts.LineStyle.Dashed, + title: 'BB Lower', + visible: indicator.visible, + }); + bbLowerSeries.setData( + bb.lower.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('BB_lower', bbLowerSeries); + } + + if (indicatorId === 'VWAP') { + const vwap = calculateVWAP(data); + const vwapSeries = chart.addLineSeries({ + color: indicator.style?.color || '#9c27b0', + lineWidth: indicator.style?.lineWidth || 2, + title: 'VWAP', + visible: indicator.visible, + }); + vwapSeries.setData( + vwap.map(point => ({ + ...point, + time: point.time as LightweightCharts.UTCTimestamp, + })) + ); + indicatorSeriesRef.current.set('VWAP', vwapSeries); + } + }); + } + + // Subscribe to crosshair move for tracking values + chart.subscribeCrosshairMove(param => { + if (!param || !param.time || !param.seriesData) { + return; + } + + // Update price info + const mainSeriesData = param.seriesData.get(defined(seriesRef.current)); + if (mainSeriesData) { + const price = + 'close' in mainSeriesData + ? mainSeriesData.close + : 'value' in mainSeriesData + ? mainSeriesData.value + : 0; + + // Find previous close + const currentIndex = data.findIndex(d => d.time === param.time); + const previousClose = currentIndex > 0 ? at(data, currentIndex - 1).close : price; + const change = price - previousClose; + const changePercent = (change / previousClose) * 100; + + setCurrentPrice({ price, change, changePercent }); + } + + // Update indicator values + const newIndicatorValues = new Map(); + indicatorSeriesRef.current.forEach((series, indicatorId) => { + const indicatorData = param.seriesData.get(series); + if (indicatorData && 'value' in indicatorData) { + newIndicatorValues.set(indicatorId, indicatorData.value); + } + }); + setIndicatorValues(newIndicatorValues); + }); + + // Fit content only on initial load + chart.timeScale().fitContent(); + setIsLoading(false); + setChartInitialized(true); + } + + // Handle resize + const handleResize = () => { + if (chartContainerRef.current && chart) { + chart.applyOptions({ + width: chartContainerRef.current.clientWidth, + height: chartContainerRef.current.clientHeight, + }); + } + }; + + window.addEventListener('resize', handleResize); + + // Cleanup + return () => { + window.removeEventListener('resize', handleResize); + setChartInitialized(false); + if (chart) { + chart.remove(); + } + }; + }, [data.length, chartConfig.theme, chartConfig.chartType, activeIndicators.length]); // Include activeIndicators.length to recreate when indicators are added/removed + + // Update data when it changes + useEffect(() => { + if (!seriesRef.current || !data.length) { + return; + } + + if (chartConfig.chartType === 'candlestick' || chartConfig.chartType === 'bar') { + seriesRef.current.setData( + data.map(point => ({ ...point, time: point.time as LightweightCharts.UTCTimestamp })) + ); + } else if (chartConfig.chartType === 'line' || chartConfig.chartType === 'area') { + const lineData = data.map(d => ({ + time: d.time as LightweightCharts.UTCTimestamp, + value: d.close, + })); + seriesRef.current.setData(lineData); + } + + if (volumeSeriesRef.current) { + const volumeData = data + .filter(d => d.volume) + .map(d => ({ + time: d.time as LightweightCharts.UTCTimestamp, + value: defined(d.volume), + color: d.close >= d.open ? '#10b98180' : '#ef444480', + })); + volumeSeriesRef.current.setData( + volumeData.map(point => ({ ...point, time: point.time as LightweightCharts.UTCTimestamp })) + ); + } + + // Don't fit content on data updates to preserve user's zoom/pan + // chartRef.current?.timeScale().fitContent(); + }, [data, chartConfig.chartType]); + + // Create a dependency string that captures visibility changes + const visibilityKey = activeIndicators.map(i => `${i.id}:${i.visible}`).join(','); + + // Handle indicator visibility changes without recreating chart + useEffect(() => { + if (!chartRef.current || !chartInitialized) { + return; + } + + // Update volume visibility + if (volumeSeriesRef.current) { + const volumeIndicator = activeIndicators.find(i => i.id === 'VOLUME'); + const volumeVisible = volumeIndicator ? volumeIndicator.visible : chartConfig.showVolume; + volumeSeriesRef.current.applyOptions({ + visible: volumeVisible, + }); + } + + // Update indicator visibility + activeIndicators.forEach(indicator => { + if (indicator.id === 'VOLUME') { + return; + } // Skip volume, handled above + + // For indicators with multiple series (like Bollinger Bands) + if (indicator.id === 'BB') { + ['BB_upper', 'BB_middle', 'BB_lower'].forEach(seriesId => { + const series = indicatorSeriesRef.current.get(seriesId); + if (series) { + series.applyOptions({ visible: indicator.visible }); + } + }); + } else { + // For single series indicators + const series = indicatorSeriesRef.current.get(indicator.id); + if (series) { + series.applyOptions({ visible: indicator.visible }); + } + } + }); + }, [chartConfig.showVolume, visibilityKey, chartInitialized]); + + // Prepare indicator info for overlay - include all indicators + const indicatorInfo = activeIndicators.map(indicator => ({ + id: indicator.id, + name: indicator.name, + value: indicator.visible ? indicatorValues.get(indicator.id) : undefined, + color: indicator.style.color ?? '#2962FF', + visible: indicator.visible, + })); + + return ( +
+ {isLoading && ( +
+
+
+ )} + + {/* Chart container */} +
+ + {/* Chart Overlay with indicators */} + {!isLoading && onIndicatorSettings && onIndicatorRemove && ( + + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/charts/hooks/useChartData.ts b/apps/stock/web-app/src/features/charts/hooks/useChartData.ts index 68dcf1ee..129f402d 100644 --- a/apps/stock/web-app/src/features/charts/hooks/useChartData.ts +++ b/apps/stock/web-app/src/features/charts/hooks/useChartData.ts @@ -1,145 +1,150 @@ -import { useState, useEffect, useRef } from 'react'; -import { ChartDataService } from '../services/chartDataService'; -import type { CandlestickData, MarketData, ChartInterval } 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) => { - console.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, - }; -} \ No newline at end of file +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/services/chartDataService.ts b/apps/stock/web-app/src/features/charts/services/chartDataService.ts index 48f80a2b..894a80ab 100644 --- a/apps/stock/web-app/src/features/charts/services/chartDataService.ts +++ b/apps/stock/web-app/src/features/charts/services/chartDataService.ts @@ -1,209 +1,240 @@ -import type { CandlestickData, MarketData, ChartInterval } from '../types'; - -const API_BASE = '/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 = await response.json(); - - // Transform data to match lightweight-charts format - const candlestickData = data.map((candle: any) => { - // 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 - time = Math.floor(Date.now() / 1000); - } - - return { - time, - open: candle.open, - high: candle.high, - low: candle.low, - close: candle.close, - volume: candle.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 }; - } -} \ No newline at end of file +import type { CandlestickData, ChartInterval, MarketData } from '../types'; + +const API_BASE = '/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/charts/utils/indicators.ts b/apps/stock/web-app/src/features/charts/utils/indicators.ts index 71f60ea0..00d0be8b 100644 --- a/apps/stock/web-app/src/features/charts/utils/indicators.ts +++ b/apps/stock/web-app/src/features/charts/utils/indicators.ts @@ -1,295 +1,321 @@ -import type { CandlestickData, LineData } from '../types'; - -// Simple Moving Average -export function calculateSMA(data: CandlestickData[], period: number): LineData[] { - const result: LineData[] = []; - - for (let i = period - 1; i < data.length; i++) { - let sum = 0; - for (let j = 0; j < period; j++) { - const item = data[i - j]; - if (item) sum += item.close; - } - const current = data[i]; - if (current) { - result.push({ - time: current.time, - value: parseFloat((sum / period).toFixed(2)), - }); - } - } - - return result; -} - -// Exponential Moving Average -export function calculateEMA(data: CandlestickData[], period: number): LineData[] { - const result: LineData[] = []; - const multiplier = 2 / (period + 1); - - // Start with SMA for the first period - let sum = 0; - for (let i = 0; i < period; i++) { - const item = data[i]; - if (item) sum += item.close; - } - let ema = sum / period; - - const firstItem = data[period - 1]; - if (firstItem) { - result.push({ - time: firstItem.time, - value: parseFloat(ema.toFixed(2)), - }); - } - - // Calculate EMA for the rest - for (let i = period; i < data.length; i++) { - const current = data[i]; - if (current) { - ema = (current.close - ema) * multiplier + ema; - result.push({ - time: current.time, - value: parseFloat(ema.toFixed(2)), - }); - } - } - - return result; -} - -// Bollinger Bands -export function calculateBollingerBands(data: CandlestickData[], period: number = 20, stdDev: number = 2) { - const sma = calculateSMA(data, period); - const upper: LineData[] = []; - const lower: LineData[] = []; - - for (let i = period - 1; i < data.length; i++) { - let sumSquaredDiff = 0; - const smaItem = sma[i - (period - 1)]; - if (!smaItem) continue; - const smaValue = smaItem.value; - - for (let j = 0; j < period; j++) { - const item = data[i - j]; - if (item) { - const diff = item.close - smaValue; - sumSquaredDiff += diff * diff; - } - } - - const standardDeviation = Math.sqrt(sumSquaredDiff / period); - const upperBand = smaValue + (standardDeviation * stdDev); - const lowerBand = smaValue - (standardDeviation * stdDev); - - const current = data[i]; - if (current) { - upper.push({ - time: current.time, - value: parseFloat(upperBand.toFixed(2)), - }); - - lower.push({ - time: current.time, - value: parseFloat(lowerBand.toFixed(2)), - }); - } - } - - return { upper, middle: sma, lower }; -} - -// Relative Strength Index (RSI) -export function calculateRSI(data: CandlestickData[], period: number = 14): LineData[] { - const result: LineData[] = []; - - if (data.length < period + 1) return result; - - // Calculate initial average gain/loss - let avgGain = 0; - let avgLoss = 0; - - for (let i = 1; i <= period; i++) { - const current = data[i]; - const prev = data[i - 1]; - if (current && prev) { - const change = current.close - prev.close; - if (change > 0) { - avgGain += change; - } else { - avgLoss += Math.abs(change); - } - } - } - - avgGain /= period; - avgLoss /= period; - - // Calculate RSI for each period - for (let i = period; i < data.length; i++) { - const current = data[i]; - const prev = data[i - 1]; - if (!current || !prev) continue; - const change = current.close - prev.close; - const gain = change > 0 ? change : 0; - const loss = change < 0 ? Math.abs(change) : 0; - - avgGain = (avgGain * (period - 1) + gain) / period; - avgLoss = (avgLoss * (period - 1) + loss) / period; - - const rs = avgLoss === 0 ? 100 : avgGain / avgLoss; - const rsi = 100 - (100 / (1 + rs)); - - result.push({ - time: current.time, - value: parseFloat(rsi.toFixed(2)), - }); - } - - return result; -} - -// MACD (Moving Average Convergence Divergence) -export function calculateMACD( - data: CandlestickData[], - fastPeriod: number = 12, - slowPeriod: number = 26, - signalPeriod: number = 9 -) { - const emaFast = calculateEMA(data, fastPeriod); - const emaSlow = calculateEMA(data, slowPeriod); - - const macdLine: LineData[] = []; - const macdData: number[] = []; - - // Calculate MACD line - for (let i = 0; i < Math.min(emaFast.length, emaSlow.length); i++) { - const fastIdx = emaFast.findIndex(d => d.time === emaSlow[i].time); - if (fastIdx !== -1) { - const macdValue = emaFast[fastIdx].value - emaSlow[i].value; - macdLine.push({ - time: emaSlow[i].time, - value: parseFloat(macdValue.toFixed(2)), - }); - macdData.push(macdValue); - } - } - - // Calculate signal line (EMA of MACD) - const signalLine: LineData[] = []; - if (macdData.length >= signalPeriod) { - const multiplier = 2 / (signalPeriod + 1); - let ema = macdData.slice(0, signalPeriod).reduce((a, b) => a + b, 0) / signalPeriod; - - const firstMacd = macdLine[signalPeriod - 1]; - if (firstMacd) { - signalLine.push({ - time: firstMacd.time, - value: parseFloat(ema.toFixed(2)), - }); - } - - for (let i = signalPeriod; i < macdData.length; i++) { - ema = (macdData[i] - ema) * multiplier + ema; - const macdItem = macdLine[i]; - if (macdItem) { - signalLine.push({ - time: macdItem.time, - value: parseFloat(ema.toFixed(2)), - }); - } - } - } - - // Calculate histogram - const histogram: LineData[] = []; - for (let i = 0; i < signalLine.length; i++) { - const macdIdx = macdLine.findIndex(d => d.time === signalLine[i].time); - if (macdIdx !== -1) { - histogram.push({ - time: signalLine[i].time, - value: parseFloat((macdLine[macdIdx].value - signalLine[i].value).toFixed(2)), - }); - } - } - - return { macdLine, signalLine, histogram }; -} - -// Volume Weighted Average Price (VWAP) -export function calculateVWAP(data: CandlestickData[]): LineData[] { - const result: LineData[] = []; - let cumulativeTPV = 0; // Cumulative Typical Price × Volume - let cumulativeVolume = 0; - - for (let i = 0; i < data.length; i++) { - const current = data[i]; - if (!current) continue; - const typicalPrice = (current.high + current.low + current.close) / 3; - const volume = current.volume || 0; - - cumulativeTPV += typicalPrice * volume; - cumulativeVolume += volume; - - if (cumulativeVolume > 0) { - result.push({ - time: current.time, - value: parseFloat((cumulativeTPV / cumulativeVolume).toFixed(2)), - }); - } - } - - return result; -} - -// Stochastic Oscillator -export function calculateStochastic(data: CandlestickData[], period: number = 14, smoothK: number = 3, smoothD: number = 3) { - const kValues: LineData[] = []; - - // Calculate %K - for (let i = period - 1; i < data.length; i++) { - const current = data[i]; - if (!current) continue; - let lowestLow = current.low; - let highestHigh = current.high; - - for (let j = 1; j < period; j++) { - const prev = data[i - j]; - if (!prev) continue; - lowestLow = Math.min(lowestLow, prev.low); - highestHigh = Math.max(highestHigh, prev.high); - } - - const k = ((current.close - lowestLow) / (highestHigh - lowestLow)) * 100; - kValues.push({ - time: current.time, - value: parseFloat(k.toFixed(2)), - }); - } - - // Smooth %K if needed - const smoothedK = smoothK > 1 ? calculateSMAFromLineData(kValues, smoothK) : kValues; - - // Calculate %D (SMA of %K) - const smoothedD = calculateSMAFromLineData(smoothedK, smoothD); - - return { k: smoothedK, d: smoothedD }; -} - -// Helper function to calculate SMA from LineData -function calculateSMAFromLineData(data: LineData[], period: number): LineData[] { - const result: LineData[] = []; - - for (let i = period - 1; i < data.length; i++) { - let sum = 0; - for (let j = 0; j < period; j++) { - sum += data[i - j].value; - } - result.push({ - time: data[i].time, - value: parseFloat((sum / period).toFixed(2)), - }); - } - - return result; -} \ No newline at end of file +import { at } from '@stock-bot/invariants'; +import type { CandlestickData, LineData } from '../types'; + +// Simple Moving Average +export function calculateSMA(data: CandlestickData[], period: number): LineData[] { + const result: LineData[] = []; + + for (let i = period - 1; i < data.length; i++) { + let sum = 0; + for (let j = 0; j < period; j++) { + const item = data[i - j]; + if (item) { + sum += item.close; + } + } + const current = data[i]; + if (current) { + result.push({ + time: current.time, + value: parseFloat((sum / period).toFixed(2)), + }); + } + } + + return result; +} + +// Exponential Moving Average +export function calculateEMA(data: CandlestickData[], period: number): LineData[] { + const result: LineData[] = []; + const multiplier = 2 / (period + 1); + + // Start with SMA for the first period + let sum = 0; + for (let i = 0; i < period; i++) { + const item = data[i]; + if (item) { + sum += item.close; + } + } + let ema = sum / period; + + const firstItem = data[period - 1]; + if (firstItem) { + result.push({ + time: firstItem.time, + value: parseFloat(ema.toFixed(2)), + }); + } + + // Calculate EMA for the rest + for (let i = period; i < data.length; i++) { + const current = data[i]; + if (current) { + ema = (current.close - ema) * multiplier + ema; + result.push({ + time: current.time, + value: parseFloat(ema.toFixed(2)), + }); + } + } + + return result; +} + +// Bollinger Bands +export function calculateBollingerBands( + data: CandlestickData[], + period: number = 20, + stdDev: number = 2 +) { + const sma = calculateSMA(data, period); + const upper: LineData[] = []; + const lower: LineData[] = []; + + for (let i = period - 1; i < data.length; i++) { + let sumSquaredDiff = 0; + const smaItem = sma[i - (period - 1)]; + if (!smaItem) { + continue; + } + const smaValue = smaItem.value; + + for (let j = 0; j < period; j++) { + const item = data[i - j]; + if (item) { + const diff = item.close - smaValue; + sumSquaredDiff += diff * diff; + } + } + + const standardDeviation = Math.sqrt(sumSquaredDiff / period); + const upperBand = smaValue + standardDeviation * stdDev; + const lowerBand = smaValue - standardDeviation * stdDev; + + const current = data[i]; + if (current) { + upper.push({ + time: current.time, + value: parseFloat(upperBand.toFixed(2)), + }); + + lower.push({ + time: current.time, + value: parseFloat(lowerBand.toFixed(2)), + }); + } + } + + return { upper, middle: sma, lower }; +} + +// Relative Strength Index (RSI) +export function calculateRSI(data: CandlestickData[], period: number = 14): LineData[] { + const result: LineData[] = []; + + if (data.length < period + 1) { + return result; + } + + // Calculate initial average gain/loss + let avgGain = 0; + let avgLoss = 0; + + for (let i = 1; i <= period; i++) { + const current = data[i]; + const prev = data[i - 1]; + if (current && prev) { + const change = current.close - prev.close; + if (change > 0) { + avgGain += change; + } else { + avgLoss += Math.abs(change); + } + } + } + + avgGain /= period; + avgLoss /= period; + + // Calculate RSI for each period + for (let i = period; i < data.length; i++) { + const current = data[i]; + const prev = data[i - 1]; + if (!current || !prev) { + continue; + } + const change = current.close - prev.close; + const gain = change > 0 ? change : 0; + const loss = change < 0 ? Math.abs(change) : 0; + + avgGain = (avgGain * (period - 1) + gain) / period; + avgLoss = (avgLoss * (period - 1) + loss) / period; + + const rs = avgLoss === 0 ? 100 : avgGain / avgLoss; + const rsi = 100 - 100 / (1 + rs); + + result.push({ + time: current.time, + value: parseFloat(rsi.toFixed(2)), + }); + } + + return result; +} + +// MACD (Moving Average Convergence Divergence) +export function calculateMACD( + data: CandlestickData[], + fastPeriod: number = 12, + slowPeriod: number = 26, + signalPeriod: number = 9 +) { + const emaFast = calculateEMA(data, fastPeriod); + const emaSlow = calculateEMA(data, slowPeriod); + + const macdLine: LineData[] = []; + const macdData: number[] = []; + + // Calculate MACD line + for (let i = 0; i < Math.min(emaFast.length, emaSlow.length); i++) { + const fastIdx = emaFast.findIndex(d => d.time === at(emaSlow, i).time); + if (fastIdx !== -1) { + const macdValue = at(emaFast, fastIdx).value - at(emaSlow, i).value; + macdLine.push({ + time: at(emaSlow, i).time, + value: parseFloat(macdValue.toFixed(2)), + }); + macdData.push(macdValue); + } + } + + // Calculate signal line (EMA of MACD) + const signalLine: LineData[] = []; + if (macdData.length >= signalPeriod) { + const multiplier = 2 / (signalPeriod + 1); + let ema = macdData.slice(0, signalPeriod).reduce((a, b) => a + b, 0) / signalPeriod; + + const firstMacd = macdLine[signalPeriod - 1]; + if (firstMacd) { + signalLine.push({ + time: firstMacd.time, + value: parseFloat(ema.toFixed(2)), + }); + } + + for (let i = signalPeriod; i < macdData.length; i++) { + ema = (at(macdData, i) - ema) * multiplier + ema; + const macdItem = macdLine[i]; + if (macdItem) { + signalLine.push({ + time: macdItem.time, + value: parseFloat(ema.toFixed(2)), + }); + } + } + } + + // Calculate histogram + const histogram: LineData[] = []; + for (let i = 0; i < signalLine.length; i++) { + const macdIdx = macdLine.findIndex(d => d.time === at(signalLine, i).time); + if (macdIdx !== -1) { + histogram.push({ + time: at(signalLine, i).time, + value: parseFloat((at(macdLine, macdIdx).value - at(signalLine, i).value).toFixed(2)), + }); + } + } + + return { macdLine, signalLine, histogram }; +} + +// Volume Weighted Average Price (VWAP) +export function calculateVWAP(data: CandlestickData[]): LineData[] { + const result: LineData[] = []; + let cumulativeTPV = 0; // Cumulative Typical Price × Volume + let cumulativeVolume = 0; + + for (let i = 0; i < data.length; i++) { + const current = data[i]; + if (!current) { + continue; + } + const typicalPrice = (current.high + current.low + current.close) / 3; + const volume = current.volume || 0; + + cumulativeTPV += typicalPrice * volume; + cumulativeVolume += volume; + + if (cumulativeVolume > 0) { + result.push({ + time: current.time, + value: parseFloat((cumulativeTPV / cumulativeVolume).toFixed(2)), + }); + } + } + + return result; +} + +// Stochastic Oscillator +export function calculateStochastic( + data: CandlestickData[], + period: number = 14, + smoothK: number = 3, + smoothD: number = 3 +) { + const kValues: LineData[] = []; + + // Calculate %K + for (let i = period - 1; i < data.length; i++) { + const current = data[i]; + if (!current) { + continue; + } + let lowestLow = current.low; + let highestHigh = current.high; + + for (let j = 1; j < period; j++) { + const prev = data[i - j]; + if (!prev) { + continue; + } + lowestLow = Math.min(lowestLow, prev.low); + highestHigh = Math.max(highestHigh, prev.high); + } + + const k = ((current.close - lowestLow) / (highestHigh - lowestLow)) * 100; + kValues.push({ + time: current.time, + value: parseFloat(k.toFixed(2)), + }); + } + + // Smooth %K if needed + const smoothedK = smoothK > 1 ? calculateSMAFromLineData(kValues, smoothK) : kValues; + + // Calculate %D (SMA of %K) + const smoothedD = calculateSMAFromLineData(smoothedK, smoothD); + + return { k: smoothedK, d: smoothedD }; +} + +// Helper function to calculate SMA from LineData +function calculateSMAFromLineData(data: LineData[], period: number): LineData[] { + const result: LineData[] = []; + + for (let i = period - 1; i < data.length; i++) { + let sum = 0; + for (let j = 0; j < period; j++) { + sum += at(data, i - j).value; + } + result.push({ + time: at(data, i).time, + value: parseFloat((sum / period).toFixed(2)), + }); + } + + return result; +} diff --git a/apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx b/apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx index 17b56cd1..df5613ba 100644 --- a/apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx +++ b/apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx @@ -1,7 +1,7 @@ -import { Dialog, DialogContent, DialogHeader, DialogTitle, Button } from '@/components/ui'; import { useCallback, useEffect, useState } from 'react'; +import { Button, Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui'; import { useExchanges } from '../hooks/useExchanges'; -import type { CreateProviderMappingRequest } from '../types/index'; +import type { CreateProviderMappingRequest, ProviderExchange } from '../types/index'; interface AddProviderMappingDialogProps { isOpen: boolean; @@ -11,13 +11,7 @@ interface AddProviderMappingDialogProps { onCreateMapping: (request: CreateProviderMappingRequest) => Promise; } -interface UnmappedExchange { - provider_exchange_code: string; - provider_exchange_name: string; - country_code?: string; - currency?: string; - symbol_count?: number; -} +type UnmappedExchange = ProviderExchange; export function AddProviderMappingDialog({ isOpen, @@ -102,8 +96,8 @@ export function AddProviderMappingDialog({ provider_exchange_code: selectedExchange.provider_exchange_code, provider_exchange_name: selectedExchange.provider_exchange_name, master_exchange_id: exchangeId, - country_code: selectedExchange.country_code, - currency: selectedExchange.currency, + country_code: selectedExchange.country_code ?? undefined, + currency: selectedExchange.currency ?? undefined, confidence: 1.0, active: false, verified: false, @@ -181,13 +175,16 @@ export function AddProviderMappingDialog({ {!selectedProvider ? 'Select a provider first' : exchangesLoading - ? 'Loading exchanges...' - : unmappedExchanges.length === 0 - ? 'No unmapped exchanges available' - : 'Select an exchange'} + ? 'Loading exchanges...' + : unmappedExchanges.length === 0 + ? 'No unmapped exchanges available' + : 'Select an exchange'} {unmappedExchanges.map(exchange => ( - @@ -208,7 +205,9 @@ export function AddProviderMappingDialog({ const exchange = unmappedExchanges.find( ex => ex.provider_exchange_code === selectedProviderExchange ); - if (!exchange) {return null;} + if (!exchange) { + return null; + } return (
@@ -217,7 +216,8 @@ export function AddProviderMappingDialog({ {exchange.provider_exchange_code}
- Name: {exchange.provider_exchange_name} + Name:{' '} + {exchange.provider_exchange_name}
{exchange.country_code && (
@@ -256,4 +256,4 @@ export function AddProviderMappingDialog({ ); -} \ No newline at end of file +} diff --git a/apps/stock/web-app/src/features/monitoring/hooks/useMonitoring.ts b/apps/stock/web-app/src/features/monitoring/hooks/useMonitoring.ts index 0da703f0..7a68ef4b 100644 --- a/apps/stock/web-app/src/features/monitoring/hooks/useMonitoring.ts +++ b/apps/stock/web-app/src/features/monitoring/hooks/useMonitoring.ts @@ -38,6 +38,7 @@ export function useSystemHealth(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -67,6 +68,7 @@ export function useCacheStats(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -96,6 +98,7 @@ export function useQueueStats(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -125,6 +128,7 @@ export function useDatabaseStats(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -154,6 +158,7 @@ export function useServiceStatus(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -183,6 +188,7 @@ export function useProxyStats(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; @@ -212,6 +218,7 @@ export function useSystemOverview(refreshInterval: number = 5000) { const interval = setInterval(fetchData, refreshInterval); return () => clearInterval(interval); } + return undefined; }, [fetchData, refreshInterval]); return { data, loading, error, refetch: fetchData }; diff --git a/apps/stock/web-app/src/features/monitoring/types/index.ts b/apps/stock/web-app/src/features/monitoring/types/index.ts index 456e3260..4b4e1da6 100644 --- a/apps/stock/web-app/src/features/monitoring/types/index.ts +++ b/apps/stock/web-app/src/features/monitoring/types/index.ts @@ -59,7 +59,11 @@ export interface DatabaseStats { waiting?: number; max: number; }; - stats?: Record; + stats?: { + version?: string; + connections?: { current: number; available: number }; + [key: string]: unknown; + }; } export interface SystemHealth { diff --git a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx index bb980c06..0fbf61d7 100644 --- a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx +++ b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx @@ -1,13 +1,18 @@ -import { useState, useEffect, useCallback } from 'react'; -import { - ArrowPathIcon, +import { + ArrowPathIcon, + CheckCircleIcon, CircleStackIcon, CloudArrowDownIcon, ExclamationTriangleIcon, - CheckCircleIcon, } from '@heroicons/react/24/outline'; +import { useCallback, useEffect, useState } from 'react'; import { usePipeline } from './hooks/usePipeline'; -import type { PipelineOperation, ExchangeStats, ProviderMappingStats, DataClearType } from './types'; +import type { + DataClearType, + ExchangeStats, + PipelineOperation, + ProviderMappingStats, +} from './types'; const operations: PipelineOperation[] = [ // Symbol operations @@ -92,13 +97,13 @@ export function PipelinePage() { const [selectedProvider, setSelectedProvider] = useState('yahoo'); const [clearFirst, setClearFirst] = useState(false); - const [clearDataType, setClearDataType] = useState<'all' | 'exchanges' | 'provider_mappings'>('all'); - const [stats, setStats] = useState<{ exchanges?: ExchangeStats; providerMappings?: ProviderMappingStats }>({}); - - // Load stats on mount - useEffect(() => { - loadStats(); - }, [loadStats]); + const [clearDataType, setClearDataType] = useState<'all' | 'exchanges' | 'provider_mappings'>( + 'all' + ); + const [stats, setStats] = useState<{ + exchanges?: ExchangeStats; + providerMappings?: ProviderMappingStats; + }>({}); const loadStats = useCallback(async () => { const [exchangeStats, mappingStats] = await Promise.all([ @@ -106,11 +111,15 @@ export function PipelinePage() { getProviderMappingStats(), ]); setStats({ - exchanges: exchangeStats, - providerMappings: mappingStats, + exchanges: exchangeStats ?? undefined, + providerMappings: mappingStats ?? undefined, }); }, [getExchangeStats, getProviderMappingStats]); + useEffect(() => { + void loadStats(); + }, [loadStats]); + const handleOperation = async (op: PipelineOperation) => { switch (op.id) { case 'sync-qm-symbols': @@ -132,7 +141,11 @@ export function PipelinePage() { await syncIBExchanges(); break; case 'clear-postgresql': - if (confirm(`Are you sure you want to clear ${clearDataType} data? This action cannot be undone.`)) { + if ( + confirm( + `Are you sure you want to clear ${clearDataType} data? This action cannot be undone.` + ) + ) { await clearPostgreSQLData(clearDataType); } break; @@ -177,23 +190,33 @@ export function PipelinePage() {
{stats.exchanges && (
-

Exchange Statistics

+

+ Exchange Statistics +

Total Exchanges: - {stats.exchanges.totalExchanges} + + {stats.exchanges.totalExchanges} +
Active Exchanges: - {stats.exchanges.activeExchanges} + + {stats.exchanges.activeExchanges} +
Total Provider Mappings: - {stats.exchanges.totalProviderMappings} + + {stats.exchanges.totalProviderMappings} +
Active Mappings: - {stats.exchanges.activeProviderMappings} + + {stats.exchanges.activeProviderMappings} +
@@ -201,7 +224,9 @@ export function PipelinePage() { {stats.providerMappings && (
-

Provider Mapping Statistics

+

+ Provider Mapping Statistics +

Coverage: @@ -211,21 +236,27 @@ export function PipelinePage() {
Verified Mappings: - {stats.providerMappings.verifiedMappings} + + {stats.providerMappings.verifiedMappings} +
Auto-mapped: - {stats.providerMappings.autoMappedCount} + + {stats.providerMappings.autoMappedCount} +
{stats.providerMappings.mappingsByProvider && (
By Provider:
- {Object.entries(stats.providerMappings.mappingsByProvider).map(([provider, count]) => ( - - {provider}: {String(count)} - - ))} + {Object.entries(stats.providerMappings.mappingsByProvider).map( + ([provider, count]) => ( + + {provider}: {String(count)} + + ) + )}
)} @@ -246,11 +277,13 @@ export function PipelinePage() { )} {lastJobResult && ( -
+
{lastJobResult.success ? ( @@ -261,9 +294,7 @@ export function PipelinePage() { {lastJobResult.message || lastJobResult.error} {lastJobResult.jobId && ( - - Job ID: {lastJobResult.jobId} - + Job ID: {lastJobResult.jobId} )}
@@ -278,68 +309,70 @@ export function PipelinePage() { Sync Operations
- {operations.filter(op => op.category === 'sync').map(op => ( -
-
-

{op.name}

-
- {getCategoryIcon(op.category)} -
-
-

{op.description}

- - {/* Special inputs for specific operations */} - {op.id === 'sync-provider-symbols' && ( -
- - -
- )} - - {op.id === 'sync-all-exchanges' && ( -
- -
- )} - - -
- ))} + + {op.id === 'sync-all-exchanges' && ( +
+ +
+ )} + + +
+ ))}
@@ -350,56 +383,58 @@ export function PipelinePage() { Maintenance Operations
- {operations.filter(op => op.category === 'maintenance').map(op => ( -
-
-

{op.name}

-
- {getCategoryIcon(op.category)} -
-
-

{op.description}

- - {op.id === 'clear-postgresql' && ( -
- - -
- )} - - -
- ))} + + +
+ ))}
); -} \ No newline at end of file +} diff --git a/apps/stock/web-app/src/features/symbols/SymbolsPage.tsx b/apps/stock/web-app/src/features/symbols/SymbolsPage.tsx index b2abfe76..8299f68e 100644 --- a/apps/stock/web-app/src/features/symbols/SymbolsPage.tsx +++ b/apps/stock/web-app/src/features/symbols/SymbolsPage.tsx @@ -1,101 +1,293 @@ -import { useEffect, useState } from 'react'; -import { SymbolsFilter } from './components/SymbolsFilter'; -import { SymbolsTable } from './components/SymbolsTable'; -import type { Exchange, Symbol, SymbolFilter } from './types'; - -// Mock data for demonstration -const mockExchanges: Exchange[] = [ - { code: 'TSX', name: 'Toronto Stock Exchange', country: 'CA' }, - { code: 'TSXV', name: 'TSX Venture Exchange', country: 'CA' }, - { code: 'NYSE', name: 'New York Stock Exchange', country: 'US' }, - { code: 'NASDAQ', name: 'NASDAQ', country: 'US' }, - { code: 'AMEX', name: 'NYSE American', country: 'US' }, -]; - -const mockSymbols: Symbol[] = [ - { symbol: 'AAPL', name: 'Apple Inc.', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 3.48e12, sector: 'Technology', industry: 'Consumer Electronics' }, - { symbol: 'MSFT', name: 'Microsoft Corporation', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 3.18e12, sector: 'Technology', industry: 'Software' }, - { symbol: 'GOOGL', name: 'Alphabet Inc. Class A', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 2.23e12, sector: 'Technology', industry: 'Internet Services' }, - { symbol: 'AMZN', name: 'Amazon.com Inc.', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 2.16e12, sector: 'Consumer Cyclical', industry: 'E-Commerce' }, - { symbol: 'TSLA', name: 'Tesla Inc.', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 1.25e12, sector: 'Consumer Cyclical', industry: 'Auto Manufacturers' }, - { symbol: 'META', name: 'Meta Platforms Inc.', exchange: 'NASDAQ', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 1.52e12, sector: 'Technology', industry: 'Social Media' }, - { symbol: 'JPM', name: 'JPMorgan Chase & Co.', exchange: 'NYSE', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 650e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'BAC', name: 'Bank of America Corp.', exchange: 'NYSE', country: 'US', type: 'Common Stock', currency: 'USD', marketCap: 370e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'TD', name: 'Toronto-Dominion Bank', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 150e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'RY', name: 'Royal Bank of Canada', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 200e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'SHOP', name: 'Shopify Inc.', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 135e9, sector: 'Technology', industry: 'E-Commerce Software' }, - { symbol: 'CP', name: 'Canadian Pacific Kansas City', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 110e9, sector: 'Industrials', industry: 'Railroads' }, - { symbol: 'CNR', name: 'Canadian National Railway', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 105e9, sector: 'Industrials', industry: 'Railroads' }, - { symbol: 'BMO', name: 'Bank of Montreal', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 125e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'BNS', name: 'Bank of Nova Scotia', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 95e9, sector: 'Financial', industry: 'Banks' }, - { symbol: 'ENB', name: 'Enbridge Inc.', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 110e9, sector: 'Energy', industry: 'Oil & Gas Pipelines' }, - { symbol: 'SU', name: 'Suncor Energy Inc.', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 65e9, sector: 'Energy', industry: 'Oil & Gas' }, - { symbol: 'TRP', name: 'TC Energy Corporation', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 60e9, sector: 'Energy', industry: 'Oil & Gas Pipelines' }, - { symbol: 'MFC', name: 'Manulife Financial Corp.', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 55e9, sector: 'Financial', industry: 'Insurance' }, - { symbol: 'BAM', name: 'Brookfield Asset Management', exchange: 'TSX', country: 'CA', type: 'Common Stock', currency: 'CAD', marketCap: 85e9, sector: 'Financial', industry: 'Asset Management' }, -]; - -export function SymbolsPage() { - const [filters, setFilters] = useState({ - country: ['CA', 'US'], - }); - const [filteredSymbols, setFilteredSymbols] = useState([]); - const [isLoading, setIsLoading] = useState(true); - - useEffect(() => { - // Simulate API call - setIsLoading(true); - setTimeout(() => { - let symbols = [...mockSymbols]; - - // Apply filters - if (filters.exchange) { - symbols = symbols.filter(s => s.exchange === filters.exchange); - } - - if (filters.searchText) { - const search = filters.searchText.toLowerCase(); - symbols = symbols.filter(s => - s.symbol.toLowerCase().includes(search) || - s.name.toLowerCase().includes(search) - ); - } - - if (filters.country && filters.country.length > 0) { - symbols = symbols.filter(s => filters.country!.includes(s.country)); - } - - // Sort by market cap (descending) - symbols.sort((a, b) => (b.marketCap || 0) - (a.marketCap || 0)); - - setFilteredSymbols(symbols); - setIsLoading(false); - }, 500); - }, [filters]); - - return ( -
-
-
-

Symbols

- -
- {isLoading ? ( - 'Loading...' - ) : ( - `${filteredSymbols.length} found` - )} -
-
-
- -
- -
-
- ); -} \ No newline at end of file +import { useEffect, useState } from 'react'; +import { defined } from '@stock-bot/invariants'; +import { SymbolsFilter } from './components/SymbolsFilter'; +import { SymbolsTable } from './components/SymbolsTable'; +import type { Exchange, Symbol, SymbolFilter } from './types'; + +// Mock data for demonstration +const mockExchanges: Exchange[] = [ + { code: 'TSX', name: 'Toronto Stock Exchange', country: 'CA' }, + { code: 'TSXV', name: 'TSX Venture Exchange', country: 'CA' }, + { code: 'NYSE', name: 'New York Stock Exchange', country: 'US' }, + { code: 'NASDAQ', name: 'NASDAQ', country: 'US' }, + { code: 'AMEX', name: 'NYSE American', country: 'US' }, +]; + +const mockSymbols: Symbol[] = [ + { + symbol: 'AAPL', + name: 'Apple Inc.', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 3.48e12, + sector: 'Technology', + industry: 'Consumer Electronics', + }, + { + symbol: 'MSFT', + name: 'Microsoft Corporation', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 3.18e12, + sector: 'Technology', + industry: 'Software', + }, + { + symbol: 'GOOGL', + name: 'Alphabet Inc. Class A', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 2.23e12, + sector: 'Technology', + industry: 'Internet Services', + }, + { + symbol: 'AMZN', + name: 'Amazon.com Inc.', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 2.16e12, + sector: 'Consumer Cyclical', + industry: 'E-Commerce', + }, + { + symbol: 'TSLA', + name: 'Tesla Inc.', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 1.25e12, + sector: 'Consumer Cyclical', + industry: 'Auto Manufacturers', + }, + { + symbol: 'META', + name: 'Meta Platforms Inc.', + exchange: 'NASDAQ', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 1.52e12, + sector: 'Technology', + industry: 'Social Media', + }, + { + symbol: 'JPM', + name: 'JPMorgan Chase & Co.', + exchange: 'NYSE', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 650e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'BAC', + name: 'Bank of America Corp.', + exchange: 'NYSE', + country: 'US', + type: 'Common Stock', + currency: 'USD', + marketCap: 370e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'TD', + name: 'Toronto-Dominion Bank', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 150e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'RY', + name: 'Royal Bank of Canada', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 200e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'SHOP', + name: 'Shopify Inc.', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 135e9, + sector: 'Technology', + industry: 'E-Commerce Software', + }, + { + symbol: 'CP', + name: 'Canadian Pacific Kansas City', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 110e9, + sector: 'Industrials', + industry: 'Railroads', + }, + { + symbol: 'CNR', + name: 'Canadian National Railway', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 105e9, + sector: 'Industrials', + industry: 'Railroads', + }, + { + symbol: 'BMO', + name: 'Bank of Montreal', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 125e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'BNS', + name: 'Bank of Nova Scotia', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 95e9, + sector: 'Financial', + industry: 'Banks', + }, + { + symbol: 'ENB', + name: 'Enbridge Inc.', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 110e9, + sector: 'Energy', + industry: 'Oil & Gas Pipelines', + }, + { + symbol: 'SU', + name: 'Suncor Energy Inc.', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 65e9, + sector: 'Energy', + industry: 'Oil & Gas', + }, + { + symbol: 'TRP', + name: 'TC Energy Corporation', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 60e9, + sector: 'Energy', + industry: 'Oil & Gas Pipelines', + }, + { + symbol: 'MFC', + name: 'Manulife Financial Corp.', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 55e9, + sector: 'Financial', + industry: 'Insurance', + }, + { + symbol: 'BAM', + name: 'Brookfield Asset Management', + exchange: 'TSX', + country: 'CA', + type: 'Common Stock', + currency: 'CAD', + marketCap: 85e9, + sector: 'Financial', + industry: 'Asset Management', + }, +]; + +export function SymbolsPage() { + const [filters, setFilters] = useState({ + country: ['CA', 'US'], + }); + const [filteredSymbols, setFilteredSymbols] = useState([]); + const [isLoading, setIsLoading] = useState(true); + + useEffect(() => { + // Simulate API call + setIsLoading(true); + setTimeout(() => { + let symbols = [...mockSymbols]; + + // Apply filters + if (filters.exchange) { + symbols = symbols.filter(s => s.exchange === filters.exchange); + } + + if (filters.searchText) { + const search = filters.searchText.toLowerCase(); + symbols = symbols.filter( + s => s.symbol.toLowerCase().includes(search) || s.name.toLowerCase().includes(search) + ); + } + + if (filters.country && filters.country.length > 0) { + symbols = symbols.filter(s => defined(filters.country).includes(s.country)); + } + + // Sort by market cap (descending) + symbols.sort((a, b) => (b.marketCap || 0) - (a.marketCap || 0)); + + setFilteredSymbols(symbols); + setIsLoading(false); + }, 500); + }, [filters]); + + return ( +
+
+
+

Symbols

+ +
+ {isLoading ? 'Loading...' : `${filteredSymbols.length} found`} +
+
+
+ +
+ +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/symbols/components/SymbolsTable.tsx b/apps/stock/web-app/src/features/symbols/components/SymbolsTable.tsx index 3511b882..e3c21f6e 100644 --- a/apps/stock/web-app/src/features/symbols/components/SymbolsTable.tsx +++ b/apps/stock/web-app/src/features/symbols/components/SymbolsTable.tsx @@ -1,103 +1,111 @@ -import { useNavigate } from 'react-router-dom'; -import type { Symbol } from '../types'; -import { DataTable } from '@/components/ui/DataTable'; -import type { ColumnDef } from '@tanstack/react-table'; - -interface SymbolsTableProps { - symbols: Symbol[]; - isLoading?: boolean; -} - -export function SymbolsTable({ symbols, isLoading }: SymbolsTableProps) { - const navigate = useNavigate(); - - const formatMarketCap = (value?: number) => { - if (!value) return '-'; - if (value >= 1e12) return `$${(value / 1e12).toFixed(2)}T`; - if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`; - if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`; - return `$${value.toLocaleString()}`; - }; - - const columns: ColumnDef[] = [ - { - accessorKey: 'symbol', - header: 'Symbol', - size: 120, - cell: ({ row }) => ( -
-
{row.original.symbol}
-
{row.original.currency}
-
- ), - }, - { - accessorKey: 'name', - header: 'Name', - size: 250, - cell: ({ getValue }) => ( -
{getValue() as string}
- ), - }, - { - accessorKey: 'exchange', - header: 'Exchange', - size: 150, - cell: ({ row }) => ( -
-
{row.original.exchange}
-
{row.original.country}
-
- ), - }, - { - accessorKey: 'type', - header: 'Type', - size: 120, - cell: ({ getValue }) => ( - - {getValue() as string} - - ), - }, - { - accessorKey: 'marketCap', - header: 'Market Cap', - size: 120, - cell: ({ getValue }) => ( - {formatMarketCap(getValue() as number)} - ), - }, - { - accessorKey: 'sector', - header: 'Sector', - size: 200, - cell: ({ row }) => ( -
-
{row.original.sector || '-'}
-
{row.original.industry || '-'}
-
- ), - }, - ]; - - if (symbols.length === 0 && !isLoading) { - return ( -
-
- No symbols found matching your criteria -
-
- ); - } - - return ( - navigate(`/symbols/${symbol.symbol}`)} - className="border-0 rounded-none border-t h-full" - /> - ); -} \ No newline at end of file +import type { ColumnDef } from '@tanstack/react-table'; +import { useNavigate } from 'react-router-dom'; +import { DataTable } from '@/components/ui/DataTable'; +import type { Symbol } from '../types'; + +interface SymbolsTableProps { + symbols: Symbol[]; + isLoading?: boolean; +} + +export function SymbolsTable({ symbols, isLoading }: SymbolsTableProps) { + const navigate = useNavigate(); + + const formatMarketCap = (value?: number) => { + if (!value) { + return '-'; + } + if (value >= 1e12) { + return `$${(value / 1e12).toFixed(2)}T`; + } + if (value >= 1e9) { + return `$${(value / 1e9).toFixed(2)}B`; + } + if (value >= 1e6) { + return `$${(value / 1e6).toFixed(2)}M`; + } + return `$${value.toLocaleString()}`; + }; + + const columns: ColumnDef[] = [ + { + accessorKey: 'symbol', + header: 'Symbol', + size: 120, + cell: ({ row }) => ( +
+
{row.original.symbol}
+
{row.original.currency}
+
+ ), + }, + { + accessorKey: 'name', + header: 'Name', + size: 250, + cell: ({ getValue }) => ( +
{getValue() as string}
+ ), + }, + { + accessorKey: 'exchange', + header: 'Exchange', + size: 150, + cell: ({ row }) => ( +
+
{row.original.exchange}
+
{row.original.country}
+
+ ), + }, + { + accessorKey: 'type', + header: 'Type', + size: 120, + cell: ({ getValue }) => ( + + {getValue() as string} + + ), + }, + { + accessorKey: 'marketCap', + header: 'Market Cap', + size: 120, + cell: ({ getValue }) => ( + {formatMarketCap(getValue() as number)} + ), + }, + { + accessorKey: 'sector', + header: 'Sector', + size: 200, + cell: ({ row }) => ( +
+
{row.original.sector || '-'}
+
{row.original.industry || '-'}
+
+ ), + }, + ]; + + if (symbols.length === 0 && !isLoading) { + return ( +
+
+ No symbols found matching your criteria +
+
+ ); + } + + return ( + navigate(`/symbols/${symbol.symbol}`)} + className="border-0 rounded-none border-t h-full" + /> + ); +} diff --git a/apps/stock/web-app/src/hooks/useChartManager.ts b/apps/stock/web-app/src/hooks/useChartManager.ts index cf52c320..f833c233 100644 --- a/apps/stock/web-app/src/hooks/useChartManager.ts +++ b/apps/stock/web-app/src/hooks/useChartManager.ts @@ -1,159 +1,156 @@ -import { useRef, useCallback, useEffect } from 'react'; -import * as LightweightCharts from 'lightweight-charts'; - -interface ChartInstance { - chart: LightweightCharts.IChartApi; - mainSeries: LightweightCharts.ISeriesApi | null; - volumeSeries: LightweightCharts.ISeriesApi | null; - overlaySeries: Map>; - isDisposed: boolean; -} - -export function useChartManager() { - const instancesRef = useRef>(new Map()); - - const disposeChart = useCallback((id: string) => { - const instance = instancesRef.current.get(id); - if (!instance || instance.isDisposed) { - return; - } - - // Mark as disposed first to prevent any further operations - instance.isDisposed = true; - - try { - // Disable all chart updates before removal - const chart = instance.chart; - - // Stop all animations and pending operations - if (chart.timeScale) { - try { - chart.timeScale().unsubscribeVisibleLogicalRangeChange(); - } catch (e) { - // Ignore - } - } - - // Clear all series references - instance.mainSeries = null; - instance.volumeSeries = null; - instance.overlaySeries.clear(); - - // Remove the chart - chart.remove(); - } catch (error) { - // Only log if it's not a disposed error - if (!error?.message?.includes('disposed')) { - console.error('Error disposing chart:', error); - } - } finally { - // Remove from instances map - instancesRef.current.delete(id); - } - }, []); - - const createChart = useCallback(( - id: string, - container: HTMLElement, - options: LightweightCharts.DeepPartial - ): LightweightCharts.IChartApi | null => { - // Dispose any existing chart with this ID first - disposeChart(id); - - try { - const chart = LightweightCharts.createChart(container, options); - const instance: ChartInstance = { - chart, - mainSeries: null, - volumeSeries: null, - overlaySeries: new Map(), - isDisposed: false, - }; - - // Wrap chart methods to check disposal state - const originalApplyOptions = chart.applyOptions.bind(chart); - chart.applyOptions = (options: any) => { - if (!instance.isDisposed) { - originalApplyOptions(options); - } - }; - - const originalTimeScale = chart.timeScale.bind(chart); - chart.timeScale = () => { - if (instance.isDisposed) { - // Return a mock object that does nothing - return { - fitContent: () => {}, - setVisibleRange: () => {}, - getVisibleRange: () => null, - scrollToPosition: () => {}, - applyOptions: () => {}, - options: () => ({}), - subscribeVisibleTimeRangeChange: () => {}, - unsubscribeVisibleTimeRangeChange: () => {}, - subscribeVisibleLogicalRangeChange: () => {}, - unsubscribeVisibleLogicalRangeChange: () => {}, - } as any; - } - return originalTimeScale(); - }; - - instancesRef.current.set(id, instance); - return chart; - } catch (error) { - console.error('Failed to create chart:', error); - return null; - } - }, [disposeChart]); - - const getChart = useCallback((id: string): ChartInstance | null => { - const instance = instancesRef.current.get(id); - if (!instance || instance.isDisposed) { - return null; - } - return instance; - }, []); - - const setMainSeries = useCallback((id: string, series: LightweightCharts.ISeriesApi | null) => { - const instance = getChart(id); - if (instance) { - instance.mainSeries = series; - } - }, [getChart]); - - const setVolumeSeries = useCallback((id: string, series: LightweightCharts.ISeriesApi | null) => { - const instance = getChart(id); - if (instance) { - instance.volumeSeries = series; - } - }, [getChart]); - - const addOverlaySeries = useCallback((id: string, name: string, series: LightweightCharts.ISeriesApi) => { - const instance = getChart(id); - if (instance) { - instance.overlaySeries.set(name, series); - } - }, [getChart]); - - const disposeAllCharts = useCallback(() => { - const ids = Array.from(instancesRef.current.keys()); - ids.forEach(id => disposeChart(id)); - }, [disposeChart]); - - // Cleanup on unmount - useEffect(() => { - return () => { - disposeAllCharts(); - }; - }, [disposeAllCharts]); - - return { - createChart, - getChart, - setMainSeries, - setVolumeSeries, - addOverlaySeries, - disposeChart, - disposeAllCharts, - }; -} \ No newline at end of file +import * as LightweightCharts from 'lightweight-charts'; +import { useCallback, useEffect, useRef } from 'react'; +import { browserLog } from '@/utils/browserLog'; + +interface ChartInstance { + chart: LightweightCharts.IChartApi; + mainSeries: LightweightCharts.ISeriesApi | null; + volumeSeries: LightweightCharts.ISeriesApi | null; + overlaySeries: Map>; + isDisposed: boolean; +} + +export function useChartManager() { + const instancesRef = useRef>(new Map()); + + const disposeChart = useCallback((id: string) => { + const instance = instancesRef.current.get(id); + if (!instance || instance.isDisposed) { + return; + } + + // Mark as disposed first to prevent any further operations + instance.isDisposed = true; + + try { + // Disable all chart updates before removal + const chart = instance.chart; + + // Removing the chart releases its subscriptions. + // Clear all series references + instance.mainSeries = null; + instance.volumeSeries = null; + instance.overlaySeries.clear(); + + // Remove the chart + chart.remove(); + } catch (error) { + // Only log if it's not a disposed error + if (!(error instanceof Error && error.message.includes('disposed'))) { + browserLog.error('Error disposing chart:', error); + } + } finally { + // Remove from instances map + instancesRef.current.delete(id); + } + }, []); + + const createChart = useCallback( + ( + id: string, + container: HTMLElement, + options: LightweightCharts.DeepPartial + ): LightweightCharts.IChartApi | null => { + // Dispose any existing chart with this ID first + disposeChart(id); + + try { + const chart = LightweightCharts.createChart(container, options); + const instance: ChartInstance = { + chart, + mainSeries: null, + volumeSeries: null, + overlaySeries: new Map(), + isDisposed: false, + }; + + // Wrap chart methods to check disposal state + const originalApplyOptions = chart.applyOptions.bind(chart); + chart.applyOptions = options => { + if (!instance.isDisposed) { + originalApplyOptions(options); + } + }; + + const originalTimeScale = chart.timeScale.bind(chart); + chart.timeScale = () => { + if (instance.isDisposed) { + throw new Error('Chart has been disposed'); + } + return originalTimeScale(); + }; + + instancesRef.current.set(id, instance); + return chart; + } catch (error) { + browserLog.error('Failed to create chart:', error); + return null; + } + }, + [disposeChart] + ); + + const getChart = useCallback((id: string): ChartInstance | null => { + const instance = instancesRef.current.get(id); + if (!instance || instance.isDisposed) { + return null; + } + return instance; + }, []); + + const setMainSeries = useCallback( + (id: string, series: LightweightCharts.ISeriesApi | null) => { + const instance = getChart(id); + if (instance) { + instance.mainSeries = series; + } + }, + [getChart] + ); + + const setVolumeSeries = useCallback( + (id: string, series: LightweightCharts.ISeriesApi | null) => { + const instance = getChart(id); + if (instance) { + instance.volumeSeries = series; + } + }, + [getChart] + ); + + const addOverlaySeries = useCallback( + ( + id: string, + name: string, + series: LightweightCharts.ISeriesApi + ) => { + const instance = getChart(id); + if (instance) { + instance.overlaySeries.set(name, series); + } + }, + [getChart] + ); + + const disposeAllCharts = useCallback(() => { + const ids = Array.from(instancesRef.current.keys()); + ids.forEach(id => disposeChart(id)); + }, [disposeChart]); + + // Cleanup on unmount + useEffect(() => { + return () => { + disposeAllCharts(); + }; + }, [disposeAllCharts]); + + return { + createChart, + getChart, + setMainSeries, + setVolumeSeries, + addOverlaySeries, + disposeChart, + disposeAllCharts, + }; +} diff --git a/apps/stock/web-app/src/hooks/useWebSocket.ts b/apps/stock/web-app/src/hooks/useWebSocket.ts index 7f9854c5..415ed923 100644 --- a/apps/stock/web-app/src/hooks/useWebSocket.ts +++ b/apps/stock/web-app/src/hooks/useWebSocket.ts @@ -1,195 +1,200 @@ -import { useEffect, useRef, useState, useCallback } from 'react'; - -export interface WebSocketMessage { - type: 'connected' | 'run_update' | 'progress' | 'error' | 'completed' | 'pong'; - runId?: string; - data?: any; - timestamp?: string; -} - -interface UseWebSocketOptions { - runId: string | null; - onMessage?: (message: WebSocketMessage) => void; - onProgress?: (progress: number, currentDate?: string) => void; - onError?: (error: string) => void; - onCompleted?: (results?: any) => void; -} - -export function useWebSocket({ - runId, - onMessage, - onProgress, - onError, - onCompleted -}: UseWebSocketOptions) { - const [isConnected, setIsConnected] = useState(false); - const [lastMessage, setLastMessage] = useState(null); - const wsRef = useRef(null); - const reconnectTimeoutRef = useRef(null); - const pingIntervalRef = useRef(null); - const isIntentionalDisconnect = useRef(false); - - const connect = useCallback(() => { - if (!runId) { - console.log('useWebSocket: No runId provided, skipping connection'); - return; - } - - // Check if already connected or connecting - if (wsRef.current && (wsRef.current.readyState === WebSocket.OPEN || wsRef.current.readyState === WebSocket.CONNECTING)) { - console.log('useWebSocket: Already connected or connecting to runId:', runId); - return; - } - - // Reset intentional disconnect flag - isIntentionalDisconnect.current = false; - - // Clear any pending reconnect timeout - if (reconnectTimeoutRef.current) { - clearTimeout(reconnectTimeoutRef.current); - reconnectTimeoutRef.current = null; - } - - const wsUrl = `ws://localhost:2003/ws?runId=${runId}`; - console.log('Connecting to WebSocket:', wsUrl); - - try { - const ws = new WebSocket(wsUrl); - wsRef.current = ws; - - ws.onopen = () => { - console.log('WebSocket connected'); - setIsConnected(true); - - // Start ping interval - pingIntervalRef.current = setInterval(() => { - if (ws.readyState === WebSocket.OPEN) { - ws.send(JSON.stringify({ type: 'ping' })); - } - }, 30000); // Ping every 30 seconds - }; - - ws.onmessage = (event) => { - try { - const message: WebSocketMessage = JSON.parse(event.data); - console.log('WebSocket message:', message); - setLastMessage(message); - - // Call appropriate callbacks - if (onMessage) { - onMessage(message); - } - - switch (message.type) { - case 'progress': - if (onProgress && message.data) { - onProgress(message.data.progress, message.data.currentDate); - } - break; - case 'error': - if (onError && message.data?.error) { - onError(message.data.error); - console.error('Run Error:', message.data.error); - } - break; - case 'completed': - if (onCompleted) { - onCompleted(message.data?.results); - } - console.log('Run Completed: The backtest run has completed successfully.'); - break; - } - } catch (error) { - console.error('Error parsing WebSocket message:', error); - } - }; - - ws.onerror = (error) => { - console.error('WebSocket error:', error); - setIsConnected(false); - }; - - ws.onclose = () => { - console.log('WebSocket disconnected'); - setIsConnected(false); - wsRef.current = null; - - // Clear ping interval - if (pingIntervalRef.current) { - clearInterval(pingIntervalRef.current); - pingIntervalRef.current = null; - } - - // Attempt to reconnect after 3 seconds - // Only reconnect if not intentionally disconnected and still the same WebSocket - if (runId && wsRef.current === ws && !isIntentionalDisconnect.current) { - reconnectTimeoutRef.current = setTimeout(() => { - console.log('Attempting to reconnect...'); - connect(); - }, 3000); - } - }; - } catch (error) { - console.error('Error creating WebSocket:', error); - setIsConnected(false); - } - }, [runId, onMessage, onProgress, onError, onCompleted]); - - const disconnect = useCallback(() => { - console.log('Disconnecting WebSocket...'); - - // Set flag to prevent automatic reconnection - isIntentionalDisconnect.current = true; - - if (reconnectTimeoutRef.current) { - clearTimeout(reconnectTimeoutRef.current); - reconnectTimeoutRef.current = null; - } - - if (pingIntervalRef.current) { - clearInterval(pingIntervalRef.current); - pingIntervalRef.current = null; - } - - if (wsRef.current) { - // Set a flag to prevent reconnection - const ws = wsRef.current; - wsRef.current = null; - ws.close(); - } - - setIsConnected(false); - }, []); - - const sendMessage = useCallback((message: any) => { - if (wsRef.current?.readyState === WebSocket.OPEN) { - wsRef.current.send(JSON.stringify(message)); - } else { - console.warn('WebSocket is not connected'); - } - }, []); - - useEffect(() => { - // Small delay to prevent rapid reconnections during React's render cycles - const timeoutId = setTimeout(() => { - if (runId) { - connect(); - } else { - disconnect(); - } - }, 100); - - return () => { - clearTimeout(timeoutId); - disconnect(); - }; - }, [runId]); // Only depend on runId, not the functions - - return { - isConnected, - lastMessage, - sendMessage, - disconnect, - connect - }; -} \ No newline at end of file +import { useCallback, useEffect, useRef, useState } from 'react'; +import { browserLog } from '@/utils/browserLog'; + +export interface WebSocketMessage { + type: 'connected' | 'run_update' | 'progress' | 'error' | 'completed' | 'pong'; + runId?: string; + data?: { progress?: number; currentDate?: string; error?: string; results?: unknown }; + timestamp?: string; +} + +interface UseWebSocketOptions { + runId: string | null; + onMessage?: (message: WebSocketMessage) => void; + onProgress?: (progress: number, currentDate?: string) => void; + onError?: (error: string) => void; + onCompleted?: (results?: unknown) => void; +} + +export function useWebSocket({ + runId, + onMessage, + onProgress, + onError, + onCompleted, +}: UseWebSocketOptions) { + const [isConnected, setIsConnected] = useState(false); + const [lastMessage, setLastMessage] = useState(null); + const wsRef = useRef(null); + const reconnectTimeoutRef = useRef(null); + const pingIntervalRef = useRef(null); + const isIntentionalDisconnect = useRef(false); + + const connect = useCallback(() => { + if (!runId) { + browserLog.log('useWebSocket: No runId provided, skipping connection'); + return; + } + + // Check if already connected or connecting + if ( + wsRef.current && + (wsRef.current.readyState === WebSocket.OPEN || + wsRef.current.readyState === WebSocket.CONNECTING) + ) { + browserLog.log('useWebSocket: Already connected or connecting to runId:', runId); + return; + } + + // Reset intentional disconnect flag + isIntentionalDisconnect.current = false; + + // Clear any pending reconnect timeout + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + reconnectTimeoutRef.current = null; + } + + const wsUrl = `ws://localhost:2003/ws?runId=${runId}`; + browserLog.log('Connecting to WebSocket:', wsUrl); + + try { + const ws = new WebSocket(wsUrl); + wsRef.current = ws; + + ws.onopen = () => { + browserLog.log('WebSocket connected'); + setIsConnected(true); + + // Start ping interval + pingIntervalRef.current = setInterval(() => { + if (ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ type: 'ping' })); + } + }, 30000); // Ping every 30 seconds + }; + + ws.onmessage = event => { + try { + const message: WebSocketMessage = JSON.parse(event.data); + browserLog.log('WebSocket message:', message); + setLastMessage(message); + + // Call appropriate callbacks + if (onMessage) { + onMessage(message); + } + + switch (message.type) { + case 'progress': + if (onProgress && message.data) { + onProgress(message.data.progress ?? 0, message.data.currentDate); + } + break; + case 'error': + if (onError && message.data?.error) { + onError(message.data.error); + browserLog.error('Run Error:', message.data.error); + } + break; + case 'completed': + if (onCompleted) { + onCompleted(message.data?.results); + } + browserLog.log('Run Completed: The backtest run has completed successfully.'); + break; + } + } catch (error) { + browserLog.error('Error parsing WebSocket message:', error); + } + }; + + ws.onerror = error => { + browserLog.error('WebSocket error:', error); + setIsConnected(false); + }; + + ws.onclose = () => { + browserLog.log('WebSocket disconnected'); + setIsConnected(false); + wsRef.current = null; + + // Clear ping interval + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } + + // Attempt to reconnect after 3 seconds + // Only reconnect if not intentionally disconnected and still the same WebSocket + if (runId && wsRef.current === ws && !isIntentionalDisconnect.current) { + reconnectTimeoutRef.current = setTimeout(() => { + browserLog.log('Attempting to reconnect...'); + connect(); + }, 3000); + } + }; + } catch (error) { + browserLog.error('Error creating WebSocket:', error); + setIsConnected(false); + } + }, [runId, onMessage, onProgress, onError, onCompleted]); + + const disconnect = useCallback(() => { + browserLog.log('Disconnecting WebSocket...'); + + // Set flag to prevent automatic reconnection + isIntentionalDisconnect.current = true; + + if (reconnectTimeoutRef.current) { + clearTimeout(reconnectTimeoutRef.current); + reconnectTimeoutRef.current = null; + } + + if (pingIntervalRef.current) { + clearInterval(pingIntervalRef.current); + pingIntervalRef.current = null; + } + + if (wsRef.current) { + // Set a flag to prevent reconnection + const ws = wsRef.current; + wsRef.current = null; + ws.close(); + } + + setIsConnected(false); + }, []); + + const sendMessage = useCallback((message: unknown) => { + if (wsRef.current?.readyState === WebSocket.OPEN) { + wsRef.current.send(JSON.stringify(message)); + } else { + browserLog.warn('WebSocket is not connected'); + } + }, []); + + useEffect(() => { + // Small delay to prevent rapid reconnections during React's render cycles + const timeoutId = setTimeout(() => { + if (runId) { + connect(); + } else { + disconnect(); + } + }, 100); + + return () => { + clearTimeout(timeoutId); + disconnect(); + }; + }, [runId]); // Only depend on runId, not the functions + + return { + isConnected, + lastMessage, + sendMessage, + disconnect, + connect, + }; +} diff --git a/apps/stock/web-app/src/utils/browserLog.ts b/apps/stock/web-app/src/utils/browserLog.ts new file mode 100644 index 00000000..d63d058f --- /dev/null +++ b/apps/stock/web-app/src/utils/browserLog.ts @@ -0,0 +1,24 @@ +/** Browser logging boundary: keep debug traces out of production. */ +export const browserLog = { + log(...values: unknown[]) { + if (import.meta.env.DEV) { + console.debug(...values); + } + }, + info(...values: unknown[]) { + if (import.meta.env.DEV) { + console.info(...values); + } + }, + debug(...values: unknown[]) { + if (import.meta.env.DEV) { + console.debug(...values); + } + }, + warn(...values: unknown[]) { + console.warn(...values); + }, + error(...values: unknown[]) { + console.error(...values); + }, +}; diff --git a/apps/stock/web-app/src/utils/chartErrorHandler.ts b/apps/stock/web-app/src/utils/chartErrorHandler.ts index 82ff837b..9d4e672d 100644 --- a/apps/stock/web-app/src/utils/chartErrorHandler.ts +++ b/apps/stock/web-app/src/utils/chartErrorHandler.ts @@ -1,47 +1,51 @@ -// Global error handler for chart disposal errors -export function setupChartErrorHandler() { - // Only suppress chart disposal errors during page unload - let isUnloading = false; - - window.addEventListener('beforeunload', () => { - isUnloading = true; - }); - - window.addEventListener('unload', () => { - isUnloading = true; - }); - - // Intercept console errors for chart disposal - const originalError = console.error; - console.error = (...args) => { - // Check if this is a chart disposal error during unload - if (isUnloading) { - const errorStr = args.join(' '); - if (errorStr.includes('Object is disposed') || - errorStr.includes('Cannot read properties of null') || - errorStr.includes('lightweight-charts')) { - // Suppress the error during unload - return; - } - } - - // Otherwise, log normally - originalError.apply(console, args); - }; - - // Also catch unhandled errors - window.addEventListener('error', (event) => { - if (isUnloading && event.error?.message?.includes('Object is disposed')) { - event.preventDefault(); - return; - } - }); - - // Catch unhandled promise rejections - window.addEventListener('unhandledrejection', (event) => { - if (isUnloading && event.reason?.message?.includes('Object is disposed')) { - event.preventDefault(); - return; - } - }); -} \ No newline at end of file +import { browserLog } from '@/utils/browserLog'; + +// Global error handler for chart disposal errors +export function setupChartErrorHandler() { + // Only suppress chart disposal errors during page unload + let isUnloading = false; + + window.addEventListener('beforeunload', () => { + isUnloading = true; + }); + + window.addEventListener('unload', () => { + isUnloading = true; + }); + + // Intercept console errors for chart disposal + const originalError = browserLog.error; + browserLog.error = (...args) => { + // Check if this is a chart disposal error during unload + if (isUnloading) { + const errorStr = args.join(' '); + if ( + errorStr.includes('Object is disposed') || + errorStr.includes('Cannot read properties of null') || + errorStr.includes('lightweight-charts') + ) { + // Suppress the error during unload + return; + } + } + + // Otherwise, log normally + originalError.apply(console, args); + }; + + // Also catch unhandled errors + window.addEventListener('error', event => { + if (isUnloading && event.error?.message?.includes('Object is disposed')) { + event.preventDefault(); + return; + } + }); + + // Catch unhandled promise rejections + window.addEventListener('unhandledrejection', event => { + if (isUnloading && event.reason?.message?.includes('Object is disposed')) { + event.preventDefault(); + return; + } + }); +} diff --git a/bun.lock b/bun.lock index e829db09..7f9b81aa 100644 --- a/bun.lock +++ b/bun.lock @@ -70,6 +70,7 @@ "@stock-bot/config": "*", "@stock-bot/di": "*", "@stock-bot/handlers": "*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/mongodb": "*", "@stock-bot/postgres": "*", @@ -96,6 +97,7 @@ "@stock-bot/config": "*", "@stock-bot/di": "*", "@stock-bot/handlers": "*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/mongodb": "*", "@stock-bot/postgres": "*", @@ -126,9 +128,13 @@ "@stock-bot/config": "*", "@stock-bot/di": "*", "@stock-bot/engine": "*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", + "@stock-bot/mongodb": "workspace:*", + "@stock-bot/postgres": "workspace:*", "@stock-bot/questdb": "*", "@stock-bot/queue": "*", + "@stock-bot/services": "workspace:*", "@stock-bot/shutdown": "*", "@stock-bot/stock-config": "*", "@stock-bot/utils": "*", @@ -141,6 +147,7 @@ "zod": "^3.22.0", }, "devDependencies": { + "@tensorflow/tfjs-node": "^4.0.0", "@types/node": "^20.0.0", "typescript": "^5.0.0", }, @@ -158,6 +165,7 @@ "@stock-bot/config": "*", "@stock-bot/di": "*", "@stock-bot/handlers": "*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/mongodb": "*", "@stock-bot/postgres": "*", @@ -178,6 +186,7 @@ "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@hookform/resolvers": "^3.3.4", + "@stock-bot/invariants": "workspace:*", "@tanstack/react-table": "^8.21.3", "clsx": "^2.1.1", "date-fns": "^3.3.1", @@ -228,6 +237,7 @@ "config-cli": "./dist/cli.js", }, "dependencies": { + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "workspace:*", "zod": "^3.22.4", }, @@ -246,6 +256,7 @@ "@stock-bot/config": "workspace:*", "@stock-bot/handler-registry": "workspace:*", "@stock-bot/handlers": "workspace:*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/mongodb": "workspace:*", "@stock-bot/postgres": "workspace:*", @@ -268,6 +279,7 @@ "name": "@stock-bot/event-bus", "version": "1.0.0", "dependencies": { + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "eventemitter3": "^5.0.1", "ioredis": "^5.3.2", @@ -308,6 +320,10 @@ "typescript": "^5.3.0", }, }, + "libs/core/invariants": { + "name": "@stock-bot/invariants", + "version": "1.0.0", + }, "libs/core/logger": { "name": "@stock-bot/logger", "version": "1.0.0", @@ -329,6 +345,7 @@ "dependencies": { "@stock-bot/cache": "*", "@stock-bot/handler-registry": "*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/types": "*", "bullmq": "^5.0.0", @@ -398,6 +415,7 @@ "name": "@stock-bot/postgres", "version": "1.0.0", "dependencies": { + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/types": "*", "pg": "^8.11.3", @@ -416,6 +434,7 @@ "name": "@stock-bot/questdb", "version": "1.0.0", "dependencies": { + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "*", "@stock-bot/types": "*", "pg": "^8.11.3", @@ -460,6 +479,7 @@ "dependencies": { "@stock-bot/cache": "workspace:*", "@stock-bot/config": "workspace:*", + "@stock-bot/invariants": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/types": "workspace:*", }, @@ -476,6 +496,8 @@ "stock-bot-coverage": "./dist/index.js", }, "dependencies": { + "@stock-bot/invariants": "workspace:*", + "@stock-bot/utils": "workspace:*", "chalk": "^5.3.0", "commander": "^11.1.0", "glob": "^10.3.10", @@ -725,6 +747,8 @@ "@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="], + "@mapbox/node-pre-gyp": ["@mapbox/node-pre-gyp@1.0.9", "", { "dependencies": { "detect-libc": "^2.0.0", "https-proxy-agent": "^5.0.0", "make-dir": "^3.1.0", "node-fetch": "^2.6.7", "nopt": "^5.0.0", "npmlog": "^5.0.1", "rimraf": "^3.0.2", "semver": "^7.3.5", "tar": "^6.1.11" }, "bin": { "node-pre-gyp": "bin/node-pre-gyp" } }, "sha512-aDF3S3rK9Q2gey/WAttUlISduDItz5BU3306M9Eyv6/oS40aMprnopshtlKTykxRNIBEZuRMaZAnbrQ4QtKGyw=="], + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.0.1", "", { "dependencies": { "content-type": "^1.0.5", "raw-body": "^3.0.0", "zod": "^3.23.8" } }, "sha512-slLdFaxQJ9AlRg+hw28iiTtGvShAOgOKXcD0F91nUcRYiOMuS9ZBYjcdNZRXW9G5JQ511GRTdUy1zQVZDpJ+4w=="], "@modelcontextprotocol/server-postgres": ["@modelcontextprotocol/server-postgres@0.6.2", "", { "dependencies": { "@modelcontextprotocol/sdk": "1.0.1", "pg": "^8.13.0" }, "bin": { "mcp-server-postgres": "dist/index.js" } }, "sha512-ukbVmVxLAsdZ5pTVWbhf9fc7lqkSf7XqizNH8XAotI21GnRPtkqO+WLWpeBFU+/2Fyv63uXS7/9NnR8Y8wOP1Q=="], @@ -941,6 +965,8 @@ "@stock-bot/handlers": ["@stock-bot/handlers@workspace:libs/core/handlers"], + "@stock-bot/invariants": ["@stock-bot/invariants@workspace:libs/core/invariants"], + "@stock-bot/logger": ["@stock-bot/logger@workspace:libs/core/logger"], "@stock-bot/mongodb": ["@stock-bot/mongodb@workspace:libs/data/mongodb"], @@ -981,6 +1007,22 @@ "@tanstack/virtual-core": ["@tanstack/virtual-core@3.13.12", "", {}, "sha512-1YBOJfRHV4sXUmWsFSf5rQor4Ss82G8dQWLRbnk3GA4jeP8hQt1hxXh0tmflpC0dz3VgEv/1+qwPyLeWkQuPFA=="], + "@tensorflow/tfjs": ["@tensorflow/tfjs@4.22.0", "", { "dependencies": { "@tensorflow/tfjs-backend-cpu": "4.22.0", "@tensorflow/tfjs-backend-webgl": "4.22.0", "@tensorflow/tfjs-converter": "4.22.0", "@tensorflow/tfjs-core": "4.22.0", "@tensorflow/tfjs-data": "4.22.0", "@tensorflow/tfjs-layers": "4.22.0", "argparse": "^1.0.10", "chalk": "^4.1.0", "core-js": "3.29.1", "regenerator-runtime": "^0.13.5", "yargs": "^16.0.3" }, "bin": { "tfjs-custom-module": "dist/tools/custom_module/cli.js" } }, "sha512-0TrIrXs6/b7FLhLVNmfh8Sah6JgjBPH4mZ8JGb7NU6WW+cx00qK5BcAZxw7NCzxj6N8MRAIfHq+oNbPUNG5VAg=="], + + "@tensorflow/tfjs-backend-cpu": ["@tensorflow/tfjs-backend-cpu@4.22.0", "", { "dependencies": { "@types/seedrandom": "^2.4.28", "seedrandom": "^3.0.5" }, "peerDependencies": { "@tensorflow/tfjs-core": "4.22.0" } }, "sha512-1u0FmuLGuRAi8D2c3cocHTASGXOmHc/4OvoVDENJayjYkS119fcTcQf4iHrtLthWyDIPy3JiPhRrZQC9EwnhLw=="], + + "@tensorflow/tfjs-backend-webgl": ["@tensorflow/tfjs-backend-webgl@4.22.0", "", { "dependencies": { "@tensorflow/tfjs-backend-cpu": "4.22.0", "@types/offscreencanvas": "~2019.3.0", "@types/seedrandom": "^2.4.28", "seedrandom": "^3.0.5" }, "peerDependencies": { "@tensorflow/tfjs-core": "4.22.0" } }, "sha512-H535XtZWnWgNwSzv538czjVlbJebDl5QTMOth4RXr2p/kJ1qSIXE0vZvEtO+5EC9b00SvhplECny2yDewQb/Yg=="], + + "@tensorflow/tfjs-converter": ["@tensorflow/tfjs-converter@4.22.0", "", { "peerDependencies": { "@tensorflow/tfjs-core": "4.22.0" } }, "sha512-PT43MGlnzIo+YfbsjM79Lxk9lOq6uUwZuCc8rrp0hfpLjF6Jv8jS84u2jFb+WpUeuF4K33ZDNx8CjiYrGQ2trQ=="], + + "@tensorflow/tfjs-core": ["@tensorflow/tfjs-core@4.22.0", "", { "dependencies": { "@types/long": "^4.0.1", "@types/offscreencanvas": "~2019.7.0", "@types/seedrandom": "^2.4.28", "@webgpu/types": "0.1.38", "long": "4.0.0", "node-fetch": "~2.6.1", "seedrandom": "^3.0.5" } }, "sha512-LEkOyzbknKFoWUwfkr59vSB68DMJ4cjwwHgicXN0DUi3a0Vh1Er3JQqCI1Hl86GGZQvY8ezVrtDIvqR1ZFW55A=="], + + "@tensorflow/tfjs-data": ["@tensorflow/tfjs-data@4.22.0", "", { "dependencies": { "@types/node-fetch": "^2.1.2", "node-fetch": "~2.6.1", "string_decoder": "^1.3.0" }, "peerDependencies": { "@tensorflow/tfjs-core": "4.22.0", "seedrandom": "^3.0.5" } }, "sha512-dYmF3LihQIGvtgJrt382hSRH4S0QuAp2w1hXJI2+kOaEqo5HnUPG0k5KA6va+S1yUhx7UBToUKCBHeLHFQRV4w=="], + + "@tensorflow/tfjs-layers": ["@tensorflow/tfjs-layers@4.22.0", "", { "peerDependencies": { "@tensorflow/tfjs-core": "4.22.0" } }, "sha512-lybPj4ZNj9iIAPUj7a8ZW1hg8KQGfqWLlCZDi9eM/oNKCCAgchiyzx8OrYoWmRrB+AM6VNEeIT+2gZKg5ReihA=="], + + "@tensorflow/tfjs-node": ["@tensorflow/tfjs-node@4.22.0", "", { "dependencies": { "@mapbox/node-pre-gyp": "1.0.9", "@tensorflow/tfjs": "4.22.0", "adm-zip": "^0.5.2", "google-protobuf": "^3.9.2", "https-proxy-agent": "^2.2.1", "progress": "^2.0.0", "rimraf": "^2.6.2", "tar": "^6.2.1" } }, "sha512-uHrXeUlfgkMxTZqHkESSV7zSdKdV0LlsBeblqkuKU9nnfxB1pC6DtoyYVaLxznzZy7WQSegjcohxxCjAf6Dc7w=="], + "@testcontainers/mongodb": ["@testcontainers/mongodb@10.28.0", "", { "dependencies": { "testcontainers": "^10.28.0" } }, "sha512-78h6n2jnFOQ8IfPjgL1+vsHuEeA0itclEOpx9kkQR+FOWnwJN9AeeX6+rMmZCtRgTsr5wT0BvfFoDssMkDqWaQ=="], "@testcontainers/postgresql": ["@testcontainers/postgresql@10.28.0", "", { "dependencies": { "testcontainers": "^10.28.0" } }, "sha512-NN25rruG5D4Q7pCNIJuHwB+G85OSeJ3xHZ2fWx0O6sPoPEfCYwvpj8mq99cyn68nxFkFYZeyrZJtSFO+FnydiA=="], @@ -1037,6 +1079,8 @@ "@types/lcov-parse": ["@types/lcov-parse@1.0.2", "", {}, "sha512-tdoxiYm04XdDEdR7UMwkWj78UAVo9U2IOcxI6tmX2/s9TK/ue/9T8gbpS/07yeWyVkVO0UumFQ5EUIBQbVejzQ=="], + "@types/long": ["@types/long@4.0.2", "", {}, "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA=="], + "@types/methods": ["@types/methods@1.1.4", "", {}, "sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ=="], "@types/minimatch": ["@types/minimatch@5.1.2", "", {}, "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA=="], @@ -1045,6 +1089,10 @@ "@types/node": ["@types/node@20.19.4", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-OP+We5WV8Xnbuvw0zC2m4qfB/BJvjyCwtNjhHdJxV1639SGSKrLmJkc3fMnp2Qy8nJyHp8RO6umxELN/dS1/EA=="], + "@types/node-fetch": ["@types/node-fetch@2.6.13", "", { "dependencies": { "@types/node": "*", "form-data": "^4.0.4" } }, "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw=="], + + "@types/offscreencanvas": ["@types/offscreencanvas@2019.3.0", "", {}, "sha512-esIJx9bQg+QYF0ra8GnvfianIY8qWB0GBx54PK5Eps6m+xTj86KLavHv6qDhzKcu5UUOgNfJ2pWaIIV7TRUd9Q=="], + "@types/pako": ["@types/pako@2.0.4", "", {}, "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw=="], "@types/pg": ["@types/pg@8.15.4", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-I6UNVBAoYbvuWkkU3oosC8yxqH21f4/Jc4DK71JLG3dT2mdlGe1z+ep/LQGXaKaOgcvUrsQoPRqfgtMcvZiJhg=="], @@ -1055,6 +1103,8 @@ "@types/react-dom": ["@types/react-dom@18.3.7", "", { "peerDependencies": { "@types/react": "^18.0.0" } }, "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ=="], + "@types/seedrandom": ["@types/seedrandom@2.4.34", "", {}, "sha512-ytDiArvrn/3Xk6/vtylys5tlY6eo7Ane0hvcx++TKo6RxQXuVfW0AF/oeWqAj9dN29SyhtawuXstgmPlwNcv/A=="], + "@types/semver": ["@types/semver@7.7.0", "", {}, "sha512-k107IF4+Xr7UHjwDc7Cfd6PRQfbdkiRabXGRjo07b4WyPahFBZCZ1sE+BNxYIJPPg73UkfOsVOLwqVc/6ETrIA=="], "@types/ssh2": ["@types/ssh2@0.5.52", "", { "dependencies": { "@types/node": "*", "@types/ssh2-streams": "*" } }, "sha512-lbLLlXxdCZOSJMCInKH2+9V/77ET2J6NPQHpFI0kda61Dd1KglJs+fPQBchizmzYSOJBgdTajhPqBO1xxLywvg=="], @@ -1095,6 +1145,10 @@ "@vitejs/plugin-react": ["@vitejs/plugin-react@4.6.0", "", { "dependencies": { "@babel/core": "^7.27.4", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.19", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0-beta.0" } }, "sha512-5Kgff+m8e2PB+9j51eGHEpn5kUzRKH2Ry0qGoe8ItJg7pqnkPrYPkDQZGgGmTa0EGarHrkjLvOdU3b1fzI8otQ=="], + "@webgpu/types": ["@webgpu/types@0.1.38", "", {}, "sha512-7LrhVKz2PRh+DD7+S+PVaFd5HxaWQvoMqBbsV9fNJO1pjUs1P8bM2vQVNfk+3URTqbuTI7gkXi0rfsN0IadoBA=="], + + "abbrev": ["abbrev@1.1.1", "", {}, "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q=="], + "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="], @@ -1103,7 +1157,9 @@ "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], - "agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + "adm-zip": ["adm-zip@0.5.18", "", {}, "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng=="], + + "agent-base": ["agent-base@4.3.0", "", { "dependencies": { "es6-promisify": "^5.0.0" } }, "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg=="], "ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="], @@ -1115,10 +1171,14 @@ "anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="], + "aproba": ["aproba@2.1.0", "", {}, "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew=="], + "archiver": ["archiver@7.0.1", "", { "dependencies": { "archiver-utils": "^5.0.2", "async": "^3.2.4", "buffer-crc32": "^1.0.0", "readable-stream": "^4.0.0", "readdir-glob": "^1.1.2", "tar-stream": "^3.0.0", "zip-stream": "^6.0.1" } }, "sha512-ZcbTaIqJOfCc03QwD468Unz/5Ir8ATtvAHsK+FdXbDIbGfihqh9mrvdcYunQzqn4HrvWWaFyaxJhGZagaJJpPQ=="], "archiver-utils": ["archiver-utils@5.0.2", "", { "dependencies": { "glob": "^10.0.0", "graceful-fs": "^4.2.0", "is-stream": "^2.0.1", "lazystream": "^1.0.0", "lodash": "^4.17.15", "normalize-path": "^3.0.0", "readable-stream": "^4.0.0" } }, "sha512-wuLJMmIBQYCsGZgYLTy5FIB2pF6Lfb6cXMSF8Qywwk3t20zWnAi7zLcQFdKQmIB8wyZpY5ER38x08GbwtR2cLA=="], + "are-we-there-yet": ["are-we-there-yet@2.0.0", "", { "dependencies": { "delegates": "^1.0.0", "readable-stream": "^3.6.0" } }, "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw=="], + "arg": ["arg@5.0.2", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="], "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], @@ -1265,7 +1325,7 @@ "chokidar": ["chokidar@3.6.0", "", { "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw=="], - "chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], + "chownr": ["chownr@2.0.0", "", {}, "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ=="], "cli-table": ["cli-table@0.3.11", "", { "dependencies": { "colors": "1.0.3" } }, "sha512-IqLQi4lO0nIB4tcdTpN4LCB9FI3uqrJZK7RC515EnhZ6qBaglkIgICb1wjeAqpdoOabm1+SuQtkXIPdYC93jhQ=="], @@ -1281,6 +1341,8 @@ "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + "color-support": ["color-support@1.1.3", "", { "bin": { "color-support": "bin.js" } }, "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg=="], + "colorette": ["colorette@2.0.20", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="], "colors": ["colors@1.0.3", "", {}, "sha512-pFGrxThWcWQ2MsAz6RtgeWe4NK2kUE1WfsrvvlctdII745EW9I0yflqhe7++M5LEc7bV2c/9/5zc8sFcpL0Drw=="], @@ -1297,6 +1359,8 @@ "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], + "console-control-strings": ["console-control-strings@1.1.0", "", {}, "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="], + "content-disposition": ["content-disposition@1.0.0", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg=="], "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], @@ -1309,6 +1373,8 @@ "cookiejar": ["cookiejar@2.1.4", "", {}, "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw=="], + "core-js": ["core-js@3.29.1", "", {}, "sha512-+jwgnhg6cQxKYIIjGtAHq2nwUOolo9eoFZ4sHfUH09BLXBgxnH4gA0zEd+t+BO2cNB8idaBtZFcFTRjQJRJmAw=="], + "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], "cors": ["cors@2.8.5", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g=="], @@ -1391,6 +1457,8 @@ "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], + "delegates": ["delegates@1.0.0", "", {}, "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="], + "denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="], "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], @@ -1467,6 +1535,10 @@ "es-to-primitive": ["es-to-primitive@1.3.0", "", { "dependencies": { "is-callable": "^1.2.7", "is-date-object": "^1.0.5", "is-symbol": "^1.0.4" } }, "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g=="], + "es6-promise": ["es6-promise@4.2.8", "", {}, "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w=="], + + "es6-promisify": ["es6-promisify@5.0.0", "", { "dependencies": { "es6-promise": "^4.0.3" } }, "sha512-C+d6UdsYDk0lMebHNR4S2NybQMMngAOnOwYBQjTOiv0MkoJMP0Myw2mgpDLBcpfCmRLxyFqYhS/CfOENq4SJhQ=="], + "esbuild": ["esbuild@0.25.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.5", "@esbuild/android-arm": "0.25.5", "@esbuild/android-arm64": "0.25.5", "@esbuild/android-x64": "0.25.5", "@esbuild/darwin-arm64": "0.25.5", "@esbuild/darwin-x64": "0.25.5", "@esbuild/freebsd-arm64": "0.25.5", "@esbuild/freebsd-x64": "0.25.5", "@esbuild/linux-arm": "0.25.5", "@esbuild/linux-arm64": "0.25.5", "@esbuild/linux-ia32": "0.25.5", "@esbuild/linux-loong64": "0.25.5", "@esbuild/linux-mips64el": "0.25.5", "@esbuild/linux-ppc64": "0.25.5", "@esbuild/linux-riscv64": "0.25.5", "@esbuild/linux-s390x": "0.25.5", "@esbuild/linux-x64": "0.25.5", "@esbuild/netbsd-arm64": "0.25.5", "@esbuild/netbsd-x64": "0.25.5", "@esbuild/openbsd-arm64": "0.25.5", "@esbuild/openbsd-x64": "0.25.5", "@esbuild/sunos-x64": "0.25.5", "@esbuild/win32-arm64": "0.25.5", "@esbuild/win32-ia32": "0.25.5", "@esbuild/win32-x64": "0.25.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ=="], "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], @@ -1605,6 +1677,8 @@ "fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="], + "fs-minipass": ["fs-minipass@2.1.0", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg=="], + "fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -1617,6 +1691,8 @@ "functions-have-names": ["functions-have-names@1.2.3", "", {}, "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ=="], + "gauge": ["gauge@3.0.2", "", { "dependencies": { "aproba": "^1.0.3 || ^2.0.0", "color-support": "^1.1.2", "console-control-strings": "^1.0.0", "has-unicode": "^2.0.1", "object-assign": "^4.1.1", "signal-exit": "^3.0.0", "string-width": "^4.2.3", "strip-ansi": "^6.0.1", "wide-align": "^1.1.2" } }, "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q=="], + "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], @@ -1647,6 +1723,8 @@ "globby": ["globby@11.1.0", "", { "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", "fast-glob": "^3.2.9", "ignore": "^5.2.0", "merge2": "^1.4.1", "slash": "^3.0.0" } }, "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g=="], + "google-protobuf": ["google-protobuf@3.21.4", "", {}, "sha512-MnG7N936zcKTco4Jd2PX2U96Kf9PxygAPKBug+74LHzmHXmceN16MmRcdgZv+DGef/S9YvQAfRsNCn4cjf9yyQ=="], + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], "got": ["got@14.4.7", "", { "dependencies": { "@sindresorhus/is": "^7.0.1", "@szmarczak/http-timer": "^5.0.1", "cacheable-lookup": "^7.0.0", "cacheable-request": "^12.0.1", "decompress-response": "^6.0.0", "form-data-encoder": "^4.0.2", "http2-wrapper": "^2.2.1", "lowercase-keys": "^3.0.0", "p-cancelable": "^4.0.1", "responselike": "^3.0.0", "type-fest": "^4.26.1" } }, "sha512-DI8zV1231tqiGzOiOzQWDhsBmncFW7oQDH6Zgy6pDPrqJuVZMtoSgPLLsBZQj8Jg4JFfwoOsDA8NGtLQLnIx2g=="], @@ -1669,6 +1747,8 @@ "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], + "has-unicode": ["has-unicode@2.0.1", "", {}, "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="], + "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], "heap-js": ["heap-js@2.6.0", "", {}, "sha512-trFMIq3PATiFRiQmNNeHtsrkwYRByIXUbYNbotiY9RLVfMkdwZdd2eQ38mGt7BRiCKBaj1DyBAIHmm7mmXPuuw=="], @@ -1687,7 +1767,7 @@ "http2-wrapper": ["http2-wrapper@2.2.1", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.2.0" } }, "sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ=="], - "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "https-proxy-agent": ["https-proxy-agent@2.2.4", "", { "dependencies": { "agent-base": "^4.3.0", "debug": "^3.1.0" } }, "sha512-OmvfoQ53WLjtA9HeYP9RNrWMJzzAz1JGaSFr1nijg0PVR1JaD/xbJq1mdEIIlxGpXp9eSe/O2LgU9DJmTPd0Eg=="], "human-signals": ["human-signals@4.3.1", "", {}, "sha512-nZXjEF2nbo7lIw3mgYjItAfgQXog3OjJogSbKa2CQIIvSGWcKgeJnQlNXip6NglNzYH45nSRiEVimMvYL8DDqQ=="], @@ -1859,7 +1939,7 @@ "lodash.truncate": ["lodash.truncate@4.4.2", "", {}, "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw=="], - "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "long": ["long@4.0.0", "", {}, "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="], "loose-envify": ["loose-envify@1.4.0", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="], @@ -1907,6 +1987,8 @@ "minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="], + "minizlib": ["minizlib@2.1.2", "", { "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" } }, "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg=="], + "mkdirp": ["mkdirp@1.0.4", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="], "mkdirp-classic": ["mkdirp-classic@0.5.3", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="], @@ -1973,7 +2055,7 @@ "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], - "node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], + "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], "node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="], @@ -1981,6 +2063,8 @@ "node-releases": ["node-releases@2.0.19", "", {}, "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw=="], + "nopt": ["nopt@5.0.0", "", { "dependencies": { "abbrev": "1" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ=="], + "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], "normalize-range": ["normalize-range@0.1.2", "", {}, "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA=="], @@ -1989,6 +2073,8 @@ "npm-run-path": ["npm-run-path@5.3.0", "", { "dependencies": { "path-key": "^4.0.0" } }, "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ=="], + "npmlog": ["npmlog@5.0.1", "", { "dependencies": { "are-we-there-yet": "^2.0.0", "console-control-strings": "^1.1.0", "gauge": "^3.0.0", "set-blocking": "^2.0.0" } }, "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw=="], + "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], "numeral": ["numeral@2.0.6", "", {}, "sha512-qaKRmtYPZ5qdw4jWJD6bxEf1FJEqllJrwxCLIm0sQU/A7v2/czigzOb+C2uSiFsa9lBUzeH7M1oK+Q+OLxL3kA=="], @@ -2243,6 +2329,8 @@ "reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="], + "regenerator-runtime": ["regenerator-runtime@0.13.11", "", {}, "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="], + "regexp.prototype.flags": ["regexp.prototype.flags@1.5.4", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", "get-proto": "^1.0.1", "gopd": "^1.2.0", "set-function-name": "^2.0.2" } }, "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA=="], "regexpp": ["regexpp@3.2.0", "", {}, "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg=="], @@ -2271,7 +2359,7 @@ "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - "rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + "rimraf": ["rimraf@2.7.1", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "./bin.js" } }, "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w=="], "rollup": ["rollup@3.29.5", "", { "optionalDependencies": { "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-GVsDdsbJzzy4S/v3dqWPJ7EfvZJfCHiDqe80IyrF59LYuP+e6U1LJoUqeuqRbwAWoMNoXivMNeNAOf5E22VA1w=="], @@ -2297,12 +2385,16 @@ "secure-json-parse": ["secure-json-parse@2.7.0", "", {}, "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw=="], + "seedrandom": ["seedrandom@3.0.5", "", {}, "sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg=="], + "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], "send": ["send@1.2.0", "", { "dependencies": { "debug": "^4.3.5", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.0", "mime-types": "^3.0.1", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.1" } }, "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw=="], "serve-static": ["serve-static@2.2.0", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ=="], + "set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="], + "set-cookie-parser": ["set-cookie-parser@2.7.1", "", {}, "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ=="], "set-function-length": ["set-function-length@1.2.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="], @@ -2429,6 +2521,8 @@ "tailwindcss": ["tailwindcss@3.4.17", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", "chokidar": "^3.6.0", "didyoumean": "^1.2.2", "dlv": "^1.1.3", "fast-glob": "^3.3.2", "glob-parent": "^6.0.2", "is-glob": "^4.0.3", "jiti": "^1.21.6", "lilconfig": "^3.1.3", "micromatch": "^4.0.8", "normalize-path": "^3.0.0", "object-hash": "^3.0.0", "picocolors": "^1.1.1", "postcss": "^8.4.47", "postcss-import": "^15.1.0", "postcss-js": "^4.0.1", "postcss-load-config": "^4.0.2", "postcss-nested": "^6.2.0", "postcss-selector-parser": "^6.1.2", "resolve": "^1.22.8", "sucrase": "^3.35.0" }, "bin": { "tailwind": "lib/cli.js", "tailwindcss": "lib/cli.js" } }, "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og=="], + "tar": ["tar@6.2.1", "", { "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" } }, "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A=="], + "tar-fs": ["tar-fs@3.1.0", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-5Mty5y/sOF1YWj1J6GiBodjlDc05CUR8PKXrsnFAiSG0xA+GHeWLovaZPYUDXkH/1iKRf2+M5+OrRgzC7O9b7w=="], "tar-stream": ["tar-stream@3.1.7", "", { "dependencies": { "b4a": "^1.6.4", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ=="], @@ -2557,6 +2651,8 @@ "which-typed-array": ["which-typed-array@1.1.19", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.8", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw=="], + "wide-align": ["wide-align@1.1.5", "", { "dependencies": { "string-width": "^1.0.2 || 2 || 3 || 4" } }, "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg=="], + "win-export-certificate-and-key": ["win-export-certificate-and-key@2.1.0", "", { "dependencies": { "bindings": "^1.5.0", "node-addon-api": "^3.1.0" }, "os": "win32" }, "sha512-WeMLa/2uNZcS/HWGKU2G1Gzeh3vHpV/UFvwLhJLKxPHYFAbubxxVcJbqmPXaqySWK1Ymymh16zKK5WYIJ3zgzA=="], "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], @@ -2621,6 +2717,8 @@ "@eslint/plugin-kit/@eslint/core": ["@eslint/core@0.15.1", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-bkOp+iumZCCbt1K1CmWf0R9pM5yKpDv+ZXtvSyQpudrI9kuFLp+bM2WOPXImuD/ceQuaa8f5pj93Y7zyECIGNA=="], + "@grpc/proto-loader/long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "@hapi/topo/@hapi/hoek": ["@hapi/hoek@9.3.0", "", {}, "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ=="], "@humanfs/node/@humanwhocodes/retry": ["@humanwhocodes/retry@0.3.1", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="], @@ -2629,6 +2727,16 @@ "@isaacs/cliui/strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="], + "@mapbox/node-pre-gyp/https-proxy-agent": ["https-proxy-agent@5.0.1", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="], + + "@mapbox/node-pre-gyp/rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + + "@mongodb-js/devtools-proxy-support/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + + "@mongodb-js/devtools-proxy-support/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + + "@mongodb-js/devtools-proxy-support/node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], + "@mongodb-js/oidc-plugin/express": ["express@4.21.2", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "1.20.3", "content-disposition": "0.5.4", "content-type": "~1.0.4", "cookie": "0.7.1", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "1.3.1", "fresh": "0.5.2", "http-errors": "2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "0.1.12", "proxy-addr": "~2.0.7", "qs": "6.13.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "0.19.0", "serve-static": "1.16.2", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA=="], "@sideway/address/@hapi/hoek": ["@hapi/hoek@9.3.0", "", {}, "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ=="], @@ -2657,12 +2765,28 @@ "@stock-bot/web-app/eslint": ["eslint@8.57.1", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.4", "@eslint/js": "8.57.1", "@humanwhocodes/config-array": "^0.13.0", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", "eslint-scope": "^7.2.2", "eslint-visitor-keys": "^3.4.3", "espree": "^9.6.1", "esquery": "^1.4.2", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^6.0.1", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "globals": "^13.19.0", "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "is-path-inside": "^3.0.3", "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3", "strip-ansi": "^6.0.1", "text-table": "^0.2.0" }, "bin": { "eslint": "bin/eslint.js" } }, "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA=="], + "@tensorflow/tfjs/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], + + "@tensorflow/tfjs/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "@tensorflow/tfjs/yargs": ["yargs@16.2.2", "", { "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.0", "y18n": "^5.0.5", "yargs-parser": "^20.2.2" } }, "sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w=="], + + "@tensorflow/tfjs-core/@types/offscreencanvas": ["@types/offscreencanvas@2019.7.3", "", {}, "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A=="], + + "@tensorflow/tfjs-core/node-fetch": ["node-fetch@2.6.13", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-StxNAxh15zr77QvvkmveSQ8uCQ4+v5FkvNTj0OESmiHu+VRi/gXArXtkWMElOsOUNLtUEvI4yS+rdtOHZTwlQA=="], + + "@tensorflow/tfjs-data/node-fetch": ["node-fetch@2.6.13", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-StxNAxh15zr77QvvkmveSQ8uCQ4+v5FkvNTj0OESmiHu+VRi/gXArXtkWMElOsOUNLtUEvI4yS+rdtOHZTwlQA=="], + + "@types/node-fetch/form-data": ["form-data@4.0.6", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.4", "mime-types": "^2.1.35" } }, "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ=="], + "@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], "anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], "archiver-utils/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], + "are-we-there-yet/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], + "bl/buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], "bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], @@ -2719,6 +2843,10 @@ "fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], + "fs-minipass/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + + "gauge/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], + "get-uri/data-uri-to-buffer": ["data-uri-to-buffer@6.0.2", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="], "glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="], @@ -2731,6 +2859,10 @@ "htmlparser2/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], + "http-proxy-agent/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + + "https-proxy-agent/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "^2.1.1" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="], + "is-wsl/is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], "joi/@hapi/hoek": ["@hapi/hoek@9.3.0", "", {}, "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ=="], @@ -2743,22 +2875,32 @@ "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], + "minizlib/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], + "mongodb-client-encryption/node-addon-api": ["node-addon-api@4.3.0", "", {}, "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="], "mongodb-client-encryption/prebuild-install": ["prebuild-install@7.1.3", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="], "mongodb-mcp-server/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.15.0", "", { "dependencies": { "ajv": "^6.12.6", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-67hnl/ROKdb03Vuu0YOr+baKTvf1/5YBHBm9KnZdjdAh8hjt4FRCPD5ucwxGB237sBpzlqQsLy1PFu7z/ekZ9Q=="], + "mongodb-memory-server-core/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "mongodb-memory-server-core/mongodb": ["mongodb@5.9.2", "", { "dependencies": { "bson": "^5.5.0", "mongodb-connection-string-url": "^2.6.0", "socks": "^2.7.1" }, "optionalDependencies": { "@mongodb-js/saslprep": "^1.1.0" }, "peerDependencies": { "@aws-sdk/credential-providers": "^3.188.0", "@mongodb-js/zstd": "^1.0.0", "kerberos": "^1.0.0 || ^2.0.0", "mongodb-client-encryption": ">=2.3.0 <3", "snappy": "^7.2.2" }, "optionalPeers": ["@aws-sdk/credential-providers", "@mongodb-js/zstd", "kerberos", "mongodb-client-encryption", "snappy"] }, "sha512-H60HecKO4Bc+7dhOv4sJlgvenK4fQNqqUIlXxZYQNbfEWSALGAwGoyJd/0Qwk4TttFXUOHJ2ZJQe/52ScaUwtQ=="], "nearley/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="], + "node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], "openid-client/lru-cache": ["lru-cache@6.0.0", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA=="], "os-dns-native/node-addon-api": ["node-addon-api@4.3.0", "", {}, "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="], + "pac-proxy-agent/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + + "pac-proxy-agent/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "parse5/entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], "path-scurry/lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], @@ -2777,6 +2919,8 @@ "proper-lockfile/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], + "protobufjs/long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "rc/strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="], "react-router/cookie": ["cookie@1.0.2", "", {}, "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA=="], @@ -2801,6 +2945,8 @@ "socket.io-parser/debug": ["debug@4.3.7", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ=="], + "socks-proxy-agent/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + "sucrase/commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], "table/ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], @@ -2809,6 +2955,8 @@ "tailwindcss/object-hash": ["object-hash@3.0.0", "", {}, "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw=="], + "tar/minipass": ["minipass@5.0.0", "", {}, "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ=="], + "testcontainers/undici": ["undici@5.29.0", "", { "dependencies": { "@fastify/busboy": "^2.0.0" } }, "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg=="], "ts-unused-exports/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], @@ -2839,6 +2987,10 @@ "@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="], + "@mapbox/node-pre-gyp/https-proxy-agent/agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], + + "@mapbox/node-pre-gyp/rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "@mongodb-js/oidc-plugin/express/body-parser": ["body-parser@1.20.3", "", { "dependencies": { "bytes": "3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "http-errors": "2.0.0", "iconv-lite": "0.4.24", "on-finished": "2.4.1", "qs": "6.13.0", "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" } }, "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g=="], "@mongodb-js/oidc-plugin/express/content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="], @@ -3017,8 +3169,22 @@ "@stock-bot/web-app/eslint/ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + "@tensorflow/tfjs-core/node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + + "@tensorflow/tfjs-data/node-fetch/whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + + "@tensorflow/tfjs/argparse/sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], + + "@tensorflow/tfjs/yargs/cliui": ["cliui@7.0.4", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^7.0.0" } }, "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ=="], + + "@tensorflow/tfjs/yargs/yargs-parser": ["yargs-parser@20.2.9", "", {}, "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w=="], + + "@types/node-fetch/form-data/hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "dockerode/tar-fs/chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], + "dockerode/tar-fs/tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="], "express/accepts/negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], @@ -3037,12 +3203,20 @@ "mongodb-client-encryption/prebuild-install/tar-fs": ["tar-fs@2.1.3", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg=="], + "mongodb-memory-server-core/https-proxy-agent/agent-base": ["agent-base@7.1.3", "", {}, "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw=="], + "mongodb-memory-server-core/mongodb/bson": ["bson@5.5.1", "", {}, "sha512-ix0EwukN2EpC0SRWIj/7B5+A6uQMQy6KMREI9qQqvgpkV2frH63T0UDVd1SYedL6dNCmDBYB3QtXi4ISk9YT+g=="], "mongodb-memory-server-core/mongodb/mongodb-connection-string-url": ["mongodb-connection-string-url@2.6.0", "", { "dependencies": { "@types/whatwg-url": "^8.2.1", "whatwg-url": "^11.0.0" } }, "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ=="], + "node-fetch/whatwg-url/tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + + "node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + "pkg-dir/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], + "prebuild-install/tar-fs/chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], + "prebuild-install/tar-fs/tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="], "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], @@ -3219,8 +3393,20 @@ "@stock-bot/web-app/eslint/file-entry-cache/flat-cache": ["flat-cache@3.2.0", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.3", "rimraf": "^3.0.2" } }, "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw=="], + "@tensorflow/tfjs-core/node-fetch/whatwg-url/tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + + "@tensorflow/tfjs-core/node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + + "@tensorflow/tfjs-data/node-fetch/whatwg-url/tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + + "@tensorflow/tfjs-data/node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + + "@tensorflow/tfjs/yargs/cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + "dockerode/tar-fs/tar-stream/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], + "mongodb-client-encryption/prebuild-install/tar-fs/chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], + "mongodb-client-encryption/prebuild-install/tar-fs/tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="], "mongodb-memory-server-core/mongodb/mongodb-connection-string-url/@types/whatwg-url": ["@types/whatwg-url@8.2.2", "", { "dependencies": { "@types/node": "*", "@types/webidl-conversions": "*" } }, "sha512-FtQu10RWgn3D9U4aazdwIE2yzphmTJREDqNdODHrbrZmmMqI0vMheC/6NE/J1Yveaj8H+ela+YwWTjq5PGmuhA=="], @@ -3241,6 +3427,8 @@ "@stock-bot/mongodb/@typescript-eslint/parser/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/mongodb/eslint/file-entry-cache/flat-cache/rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + "@stock-bot/postgres/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/@typescript-eslint/types": ["@typescript-eslint/types@6.21.0", "", {}, "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg=="], "@stock-bot/postgres/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.3", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg=="], @@ -3249,6 +3437,8 @@ "@stock-bot/postgres/@typescript-eslint/parser/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/postgres/eslint/file-entry-cache/flat-cache/rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + "@stock-bot/questdb/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/@typescript-eslint/types": ["@typescript-eslint/types@6.21.0", "", {}, "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg=="], "@stock-bot/questdb/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.3", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg=="], @@ -3257,6 +3447,8 @@ "@stock-bot/questdb/@typescript-eslint/parser/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/questdb/eslint/file-entry-cache/flat-cache/rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + "@stock-bot/web-app/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/@typescript-eslint/types": ["@typescript-eslint/types@6.21.0", "", {}, "sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg=="], "@stock-bot/web-app/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.3", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg=="], @@ -3265,6 +3457,8 @@ "@stock-bot/web-app/@typescript-eslint/parser/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/web-app/eslint/file-entry-cache/flat-cache/rimraf": ["rimraf@3.0.2", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA=="], + "mongodb-client-encryption/prebuild-install/tar-fs/tar-stream/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], "mongodb-memory-server-core/mongodb/mongodb-connection-string-url/whatwg-url/tr46": ["tr46@3.0.0", "", { "dependencies": { "punycode": "^2.1.1" } }, "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA=="], @@ -3275,16 +3469,24 @@ "@stock-bot/mongodb/@typescript-eslint/eslint-plugin/@typescript-eslint/utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/mongodb/eslint/file-entry-cache/flat-cache/rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "@stock-bot/postgres/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], "@stock-bot/postgres/@typescript-eslint/eslint-plugin/@typescript-eslint/utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/postgres/eslint/file-entry-cache/flat-cache/rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "@stock-bot/questdb/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], "@stock-bot/questdb/@typescript-eslint/eslint-plugin/@typescript-eslint/utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + "@stock-bot/questdb/eslint/file-entry-cache/flat-cache/rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], + "@stock-bot/web-app/@typescript-eslint/eslint-plugin/@typescript-eslint/type-utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], "@stock-bot/web-app/@typescript-eslint/eslint-plugin/@typescript-eslint/utils/@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="], + + "@stock-bot/web-app/eslint/file-entry-cache/flat-cache/rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="], } } diff --git a/eslint.config.js b/eslint.config.js index 1abda3ce..f257fd13 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -9,6 +9,11 @@ export default [ 'dist/**', 'build/**', 'node_modules/**', + '**/dist/**', + '**/build/**', + '**/node_modules/**', + '**/.turbo/**', + '**/coverage/**', '**/*.js', '**/*.mjs', '**/*.d.ts', @@ -25,6 +30,13 @@ export default [ // Base JavaScript configuration js.configs.recommended, + { + files: ['**/*.cjs'], + languageOptions: { + globals: { __dirname: 'readonly', require: 'readonly', module: 'readonly' }, + }, + }, + // TypeScript configuration { files: ['**/*.{ts,tsx}'], @@ -91,4 +103,14 @@ export default [ 'no-console': 'off', }, }, + // Console output is the interface of CLIs, examples, and the browser log sink. + { + files: [ + '**/examples/**', + '**/scripts/**', + 'tools/coverage-cli/**', + '**/web-app/src/utils/browserLog.ts', + ], + rules: { 'no-console': 'off' }, + }, ]; diff --git a/libs/core/cache/src/redis-cache.ts b/libs/core/cache/src/redis-cache.ts index a08d6373..f84e17f5 100644 --- a/libs/core/cache/src/redis-cache.ts +++ b/libs/core/cache/src/redis-cache.ts @@ -8,18 +8,10 @@ import type { CacheOptions, CacheProvider, CacheStats } from './types'; */ export class RedisCache implements CacheProvider { private redis: Redis; - private logger: { info?: (...args: unknown[]) => void; error?: (...args: unknown[]) => void } = - console; + private logger: NonNullable; private defaultTTL: number; private keyPrefix: string; - private stats: CacheStats = { - hits: 0, - misses: 0, - errors: 0, - hitRate: 0, - total: 0, - uptime: 0, - }; + private stats: CacheStats = { hits: 0, misses: 0, errors: 0, hitRate: 0, total: 0, uptime: 0 }; private startTime = Date.now(); constructor(options: CacheOptions) { diff --git a/libs/core/cache/src/types.ts b/libs/core/cache/src/types.ts index a691fdcb..46d3e767 100644 --- a/libs/core/cache/src/types.ts +++ b/libs/core/cache/src/types.ts @@ -1,3 +1,5 @@ +import type { LoggerLike } from '@stock-bot/logger'; + export interface RedisConfig { host: string; port: number; @@ -113,12 +115,7 @@ export interface CacheOptions { name?: string; // Name for connection identification shared?: boolean; // Whether to use shared connection redisConfig: RedisConfig; - logger?: { - info?: (...args: unknown[]) => void; - error?: (...args: unknown[]) => void; - warn?: (...args: unknown[]) => void; - debug?: (...args: unknown[]) => void; - }; + logger?: Partial; } export interface CacheStats { diff --git a/libs/core/config/package.json b/libs/core/config/package.json index d8a10091..9d90e534 100644 --- a/libs/core/config/package.json +++ b/libs/core/config/package.json @@ -24,7 +24,8 @@ }, "dependencies": { "@stock-bot/logger": "workspace:*", - "zod": "^3.22.4" + "zod": "^3.22.4", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/bun": "^1.0.0", diff --git a/libs/core/config/src/schemas/unified-app.schema.ts b/libs/core/config/src/schemas/unified-app.schema.ts index 3fbfb452..adf94eda 100644 --- a/libs/core/config/src/schemas/unified-app.schema.ts +++ b/libs/core/config/src/schemas/unified-app.schema.ts @@ -52,10 +52,10 @@ export const unifiedAppSchema = baseAppSchema } if (data.database.questdb && !data.questdb) { // Handle the ilpPort -> influxPort mapping for DI system - const questdbConfig = { ...data.database.questdb }; - if ('ilpPort' in questdbConfig && !('influxPort' in questdbConfig)) { - (questdbConfig as any).influxPort = questdbConfig.ilpPort; - } + const questdbConfig = { + ...data.database.questdb, + influxPort: data.database.questdb.ilpPort, + }; data.questdb = questdbConfig; } } @@ -68,7 +68,7 @@ export type UnifiedAppConfig = z.infer; /** * Helper to convert StockBotAppConfig to UnifiedAppConfig */ -export function toUnifiedConfig(config: any): UnifiedAppConfig { +export function toUnifiedConfig(config: unknown): UnifiedAppConfig { return unifiedAppSchema.parse(config); } diff --git a/libs/core/config/src/utils/secrets.ts b/libs/core/config/src/utils/secrets.ts index d12fc86a..29febf93 100644 --- a/libs/core/config/src/utils/secrets.ts +++ b/libs/core/config/src/utils/secrets.ts @@ -83,21 +83,21 @@ export function isSecret(value: unknown): value is SecretValue { /** * Redact secrets from an object */ -export function redactSecrets>( +export function redactSecrets>( obj: T, secretPaths: string[] = [] ): T { - const result = { ...obj }; + const result = redactSecretValues(obj) as T; // Redact known secret paths for (const path of secretPaths) { const keys = path.split('.'); - let current: any = result; + 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]; + current = current[key] as Record; } else { break; } @@ -110,7 +110,7 @@ export function redactSecrets>( } // Recursively redact SecretValue instances - function redactSecretValues(obj: any): any { + function redactSecretValues(obj: unknown): unknown { if (obj === null || obj === undefined) { return obj; } @@ -124,7 +124,7 @@ export function redactSecrets>( } if (typeof obj === 'object') { - const result: any = {}; + const result: Record = {}; for (const [key, value] of Object.entries(obj)) { result[key] = redactSecretValues(value); } @@ -134,7 +134,7 @@ export function redactSecrets>( return obj; } - return redactSecretValues(result); + return result; } /** diff --git a/libs/core/config/src/utils/validation.ts b/libs/core/config/src/utils/validation.ts index ae361957..169cc149 100644 --- a/libs/core/config/src/utils/validation.ts +++ b/libs/core/config/src/utils/validation.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { defined } from '@stock-bot/invariants'; export interface ValidationResult { valid: boolean; @@ -62,19 +63,19 @@ export function checkRequiredEnvVars(required: string[]): ValidationResult { * Validate configuration completeness */ export function validateCompleteness( - config: Record, + config: Record, required: string[] ): ValidationResult { const errors: ValidationResult['errors'] = []; for (const path of required) { const keys = path.split('.'); - let current: any = config; + let current: unknown = config; let found = true; for (const key of keys) { if (current && typeof current === 'object' && key in current) { - current = current[key]; + current = (current as Record)[key]; } else { found = false; break; @@ -144,11 +145,11 @@ export function mergeSchemas( throw new Error('At least two schemas required for merge'); } - let result = schemas[0]!.and(schemas[1]!); + let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1])); for (let i = 2; i < schemas.length; i++) { - result = result.and(schemas[i]!) as any; + result = result.and(defined(schemas[i])); } - return result as any; + return result as z.ZodIntersection; } diff --git a/libs/core/config/test/env.loader.test.ts b/libs/core/config/test/env.loader.test.ts index 3f2a2381..cd8bfe57 100644 --- a/libs/core/config/test/env.loader.test.ts +++ b/libs/core/config/test/env.loader.test.ts @@ -579,7 +579,7 @@ KEY_WITHOUT_VALUE= it('should handle all .env file paths exhausted', () => { const readFileSpy = readFileSync as any; - readFileSpy.mockImplementation((path: string) => { + readFileSpy.mockImplementation((_path: string) => { const error: any = new Error('Not found'); error.code = 'ENOENT'; throw error; diff --git a/libs/core/config/test/file.loader.test.ts b/libs/core/config/test/file.loader.test.ts index 798db182..27da55fd 100644 --- a/libs/core/config/test/file.loader.test.ts +++ b/libs/core/config/test/file.loader.test.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'fs'; -import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { FileLoader } from '../src/loaders/file.loader'; diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index fed0753a..4b4d861f 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -690,7 +690,9 @@ describe('Config Schemas', () => { retries: 5, }; const config = baseProviderConfigSchema.parse(input); - expect(config).toEqual(input); + // Rate limiting is owned by handlers/queues, not the base provider schema. + const { rateLimit: _rateLimit, ...supported } = input; + expect(config).toEqual(supported); }); }); diff --git a/libs/core/config/test/utils.test.ts b/libs/core/config/test/utils.test.ts index 5cd8c56f..65d1b013 100644 --- a/libs/core/config/test/utils.test.ts +++ b/libs/core/config/test/utils.test.ts @@ -202,9 +202,10 @@ describe('Config Utils', () => { }); it('should not modify original object', () => { - const obj = { password: 'secret' }; - const original = { ...obj }; - redactSecrets(obj, ['password']); + 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); }); }); diff --git a/libs/core/config/tsconfig.json b/libs/core/config/tsconfig.json index 94055333..1da23d35 100644 --- a/libs/core/config/tsconfig.json +++ b/libs/core/config/tsconfig.json @@ -6,5 +6,9 @@ "composite": true }, "include": ["src/**/*"], - "references": [] + "references": [ + { + "path": "../../../libs/core/invariants" + } + ] } diff --git a/libs/core/di/package.json b/libs/core/di/package.json index 58f19380..3f8d63bc 100644 --- a/libs/core/di/package.json +++ b/libs/core/di/package.json @@ -26,7 +26,8 @@ "glob": "^10.0.0", "zod": "^3.23.8", "hono": "^4.0.0", - "awilix": "^12.0.5" + "awilix": "^12.0.5", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/pg": "^8.10.7" diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 87b9b0f5..5a555e8b 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -14,6 +14,10 @@ import { HandlerScanner } from '../scanner'; import { ServiceLifecycleManager } from '../utils/lifecycle'; import type { ContainerBuildOptions, ServiceDefinitions } from './types'; +function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number { + return config.influxPort ?? config.ilpPort ?? 9009; +} + export class ServiceContainerBuilder { private config: Partial = {}; private unifiedConfig: UnifiedAppConfig | null = null; @@ -86,7 +90,7 @@ export class ServiceContainerBuilder { const questdbConfig = config.questdb ? { ...config.questdb, - influxPort: (config.questdb as any).influxPort || (config.questdb as any).ilpPort || 9009, + influxPort: getInfluxPort(config.questdb), } : { enabled: true, @@ -200,7 +204,7 @@ export class ServiceContainerBuilder { host: config.questdb.host || 'localhost', httpPort: config.questdb.httpPort || 9000, pgPort: config.questdb.pgPort || 8812, - influxPort: (config.questdb as any).influxPort || (config.questdb as any).ilpPort || 9009, + influxPort: getInfluxPort(config.questdb), database: config.questdb.database || 'questdb', } : undefined; diff --git a/libs/core/di/src/index.ts b/libs/core/di/src/index.ts index 30de3048..254466ae 100644 --- a/libs/core/di/src/index.ts +++ b/libs/core/di/src/index.ts @@ -16,6 +16,9 @@ export { questdbConfigSchema, proxyConfigSchema, browserConfigSchema, - queueConfigSchema + queueConfigSchema, } 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 index 6aba8820..b2013417 100644 --- a/libs/core/di/src/operation-context.ts +++ b/libs/core/di/src/operation-context.ts @@ -14,14 +14,14 @@ export interface OperationContextOptions { operationName: string; parentLogger?: Logger; container?: ServiceResolver; - metadata?: Record; + metadata?: Record; traceId?: string; } export class OperationContext { public readonly logger: Logger; public readonly traceId: string; - public readonly metadata: Record; + public readonly metadata: Record; private readonly container?: ServiceResolver; private readonly startTime: Date; @@ -48,7 +48,7 @@ export class OperationContext { options: { container?: ServiceResolver; parentLogger?: Logger; - metadata?: Record; + metadata?: Record; traceId?: string; } = {} ): OperationContext { @@ -82,7 +82,7 @@ export class OperationContext { /** * Add metadata to the context */ - addMetadata(key: string, value: any): void { + addMetadata(key: string, value: unknown): void { this.metadata[key] = value; } @@ -124,7 +124,7 @@ export class OperationContext { /** * Create child context */ - createChild(operationName: string, metadata?: Record): OperationContext { + createChild(operationName: string, metadata?: Record): OperationContext { return new OperationContext({ handlerName: 'child', operationName, diff --git a/libs/core/di/src/registrations/database.registration.ts b/libs/core/di/src/registrations/database.registration.ts index 7370831b..97bfe759 100644 --- a/libs/core/di/src/registrations/database.registration.ts +++ b/libs/core/di/src/registrations/database.registration.ts @@ -1,4 +1,5 @@ import { asFunction, asValue, type AwilixContainer } from 'awilix'; +import { defined } from '@stock-bot/invariants'; import { MongoDBClient } from '@stock-bot/mongodb'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { QuestDBClient } from '@stock-bot/questdb'; @@ -66,11 +67,11 @@ export function registerDatabaseServices( questdbClient: asFunction(({ logger }) => { return new QuestDBClient( { - host: config.questdb!.host, - httpPort: config.questdb!.httpPort, - pgPort: config.questdb!.pgPort, - influxPort: config.questdb!.influxPort, - database: config.questdb!.database, + host: defined(config.questdb).host, + httpPort: defined(config.questdb).httpPort, + pgPort: defined(config.questdb).pgPort, + influxPort: defined(config.questdb).influxPort, + database: defined(config.questdb).database, }, logger ); diff --git a/libs/core/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index 0801371a..5e461896 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -1,5 +1,6 @@ import { asClass, asFunction, asValue, type AwilixContainer } from 'awilix'; import { Browser } from '@stock-bot/browser'; +import { defined } from '@stock-bot/invariants'; import { ProxyManager } from '@stock-bot/proxy'; import type { AppConfig } from '../config/schemas'; import type { ServiceDefinitions } from '../container/types'; @@ -15,14 +16,14 @@ export function registerApplicationServices( .singleton() .inject(() => ({ options: { - headless: config.browser!.headless, - timeout: config.browser!.timeout, + headless: defined(config.browser).headless, + timeout: defined(config.browser).timeout, }, })), }); } else { container.register({ - browser: asValue(null as any), // Required field + browser: asValue(null), // Required field }); } @@ -62,7 +63,7 @@ export function registerApplicationServices( container.register({ queueManager: asFunction(({ logger, handlerRegistry }) => { const { QueueManager } = require('@stock-bot/queue'); - + const queueConfig = { serviceName: config.service?.serviceName || config.service?.name || 'unknown', redis: { @@ -72,14 +73,14 @@ export function registerApplicationServices( db: config.redis.db, }, defaultQueueOptions: { - workers: config.queue!.workers || 1, - concurrency: config.queue!.concurrency || 1, - defaultJobOptions: config.queue!.defaultJobOptions, + workers: defined(config.queue).workers || 1, + concurrency: defined(config.queue).concurrency || 1, + defaultJobOptions: defined(config.queue).defaultJobOptions, }, - enableScheduledJobs: config.queue!.enableScheduledJobs ?? true, + enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? true, autoDiscoverHandlers: true, }; - + return new QueueManager(queueConfig, handlerRegistry, logger); }).singleton(), }); diff --git a/libs/core/di/src/scanner/handler-scanner.ts b/libs/core/di/src/scanner/handler-scanner.ts index ce97f4cf..e1cdc9ec 100644 --- a/libs/core/di/src/scanner/handler-scanner.ts +++ b/libs/core/di/src/scanner/handler-scanner.ts @@ -11,7 +11,12 @@ import type { HandlerRegistry, } from '@stock-bot/handler-registry'; import { getLogger } from '@stock-bot/logger'; -import type { ExecutionContext, IHandler } from '@stock-bot/types'; +import type { + DecoratedHandlerClass, + ExecutionContext, + IHandler, + JobHandler, +} from '@stock-bot/types'; export interface HandlerScannerOptions { serviceName?: string; @@ -21,7 +26,7 @@ export interface HandlerScannerOptions { export class HandlerScanner { private logger = getLogger('handler-scanner'); - private discoveredHandlers = new Map(); + private discoveredHandlers = new Map(); constructor( private registry: HandlerRegistry, @@ -69,7 +74,7 @@ export class HandlerScanner { /** * Register handlers found in a module */ - private registerHandlersFromModule(module: any, filePath: string): void { + private registerHandlersFromModule(module: Record, filePath: string): void { for (const [exportName, exported] of Object.entries(module)) { if (this.isHandler(exported)) { this.registerHandler(exported, exportName, filePath); @@ -80,14 +85,14 @@ export class HandlerScanner { /** * Check if an exported value is a handler */ - private isHandler(exported: any): boolean { + private isHandler(exported: unknown): exported is DecoratedHandlerClass { if (typeof exported !== 'function') { return false; } // Check for handler metadata added by decorators - const hasHandlerName = !!(exported as any).__handlerName; - const hasOperations = Array.isArray((exported as any).__operations); + const hasHandlerName = !!(exported as DecoratedHandlerClass).__handlerName; + const hasOperations = Array.isArray((exported as DecoratedHandlerClass).__operations); return hasHandlerName && hasOperations; } @@ -95,8 +100,15 @@ export class HandlerScanner { /** * Register a handler with the registry and DI container */ - private registerHandler(HandlerClass: any, exportName: string, filePath: string): void { + private registerHandler( + HandlerClass: DecoratedHandlerClass, + exportName: string, + filePath: string + ): void { const handlerName = HandlerClass.__handlerName; + if (!handlerName) { + throw new Error('Handler name is missing'); + } const operations = HandlerClass.__operations || []; const schedules = HandlerClass.__schedules || []; const isDisabled = HandlerClass.__disabled || false; @@ -110,24 +122,24 @@ export class HandlerScanner { } // Filter out disabled operations - const enabledOperations = operations.filter((op: any) => { + const enabledOperations = operations.filter(op => { const isDisabled = disabledOperations.includes(op.method); if (isDisabled) { - this.logger.debug('Skipping disabled operation', { - handlerName, + this.logger.debug('Skipping disabled operation', { + handlerName, operation: op.name, - method: op.method + method: op.method, }); } return !isDisabled; }); - const enabledSchedules = schedules.filter((schedule: any) => { + const enabledSchedules = schedules.filter(schedule => { const isDisabled = disabledOperations.includes(schedule.operation); if (isDisabled) { - this.logger.debug('Skipping disabled scheduled operation', { - handlerName, - operation: schedule.operation + this.logger.debug('Skipping disabled scheduled operation', { + handlerName, + operation: schedule.operation, }); } return !isDisabled; @@ -137,12 +149,12 @@ export class HandlerScanner { const metadata: HandlerMetadata = { name: handlerName, service: this.options.serviceName, - operations: enabledOperations.map((op: any) => ({ + operations: enabledOperations.map(op => ({ name: op.name, method: op.method, rateLimit: operationRateLimits[op.method] || null, })), - schedules: enabledSchedules.map((schedule: any) => ({ + schedules: enabledSchedules.map(schedule => ({ operation: schedule.operation, cronPattern: schedule.cronPattern, priority: schedule.priority, @@ -155,9 +167,9 @@ export class HandlerScanner { }; // Build configuration with operation handlers - const operationHandlers: Record = {}; + const operationHandlers: Record = {}; for (const op of enabledOperations) { - operationHandlers[op.name] = async (payload: any) => { + operationHandlers[op.name] = async (payload: unknown) => { const handler = this.container.resolve(handlerName); const context: ExecutionContext = { type: 'queue', @@ -170,8 +182,8 @@ export class HandlerScanner { const configuration: HandlerConfiguration = { name: handlerName, operations: operationHandlers, - scheduledJobs: enabledSchedules.map((schedule: any) => { - const operation = enabledOperations.find((op: any) => op.method === schedule.operation); + scheduledJobs: enabledSchedules.map(schedule => { + const operation = enabledOperations.find(op => op.method === schedule.operation); return { type: `${handlerName}-${schedule.operation}`, operation: operation?.name || schedule.operation, @@ -192,7 +204,7 @@ export class HandlerScanner { if (this.options.autoRegister !== false) { this.container.register({ [handlerName]: asFunction(({ serviceContainer }) => { - return new HandlerClass(serviceContainer); + return Reflect.construct(HandlerClass, [serviceContainer]) as IHandler; }).singleton(), }); } @@ -214,14 +226,17 @@ export class HandlerScanner { /** * Get all discovered handlers */ - getDiscoveredHandlers(): Map { + getDiscoveredHandlers(): Map { return new Map(this.discoveredHandlers); } /** * Manually register a handler class */ - registerHandlerClass(HandlerClass: any, options: { serviceName?: string } = {}): void { + registerHandlerClass( + HandlerClass: DecoratedHandlerClass, + options: { serviceName?: string } = {} + ): void { const serviceName = options.serviceName || this.options.serviceName; const originalServiceName = this.options.serviceName; diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index 373afc2f..58e6d4bb 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -1,3 +1,6 @@ +import type { AwilixContainer } from 'awilix'; +import { Hono } from 'hono'; +import { cors } from 'hono/cors'; /** * ServiceApplication - Common service initialization and lifecycle management * Encapsulates common patterns for Hono-based microservices @@ -6,13 +9,12 @@ import type { BaseAppConfig, UnifiedAppConfig } from '@stock-bot/config'; import { toUnifiedConfig } from '@stock-bot/config'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; +import { defined } from '@stock-bot/invariants'; import { getLogger, setLoggerConfig, shutdownLoggers, type Logger } from '@stock-bot/logger'; -import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown'; import type { IServiceContainer } from '@stock-bot/services'; -import type { AwilixContainer } from 'awilix'; -import { Hono } from 'hono'; -import { cors } from 'hono/cors'; +import { Shutdown, SHUTDOWN_DEFAULTS } from '@stock-bot/shutdown'; import type { ServiceDefinitions } from './container/types'; +import type { HandlerScanner } from './scanner'; /** * Configuration for ServiceApplication @@ -47,6 +49,11 @@ export interface ServiceApplicationConfig { /** * Lifecycle hooks for service customization */ +export interface HandlerInitializationContext { + handlerScanner: HandlerScanner; + handlerRegistry: HandlerRegistry; +} + export interface ServiceLifecycleHooks { /** Called after container is created but before routes */ onContainerReady?: (container: IServiceContainer) => Promise | void; @@ -167,7 +174,7 @@ export class ServiceApplication { this.logger.info('Registering shutdown handlers', { service: this.serviceConfig.serviceName, scheduledJobs: this.serviceConfig.enableScheduledJobs, - timeout: this.serviceConfig.shutdownTimeout + timeout: this.serviceConfig.shutdownTimeout, }); // Priority 1: Queue system (highest priority) @@ -222,7 +229,7 @@ export class ServiceApplication { this.shutdown.onShutdown( async () => { try { - await this.hooks.onBeforeShutdown!(); + await defined(this.hooks.onBeforeShutdown)(); } catch (error) { this.logger.error('Error in custom shutdown hook', { error }); } @@ -239,7 +246,7 @@ export class ServiceApplication { const startTime = Date.now(); const disposed: string[] = []; const failed: string[] = []; - + try { if (this.container) { // Disconnect database clients @@ -280,11 +287,11 @@ export class ServiceApplication { } const duration = Date.now() - startTime; - this.logger.info('Service disposal completed', { - duration, - disposed, + this.logger.info('Service disposal completed', { + duration, + disposed, failed, - success: failed.length === 0 + success: failed.length === 0, }); } else { this.logger.warn('No container available for service disposal'); @@ -309,16 +316,19 @@ export class ServiceApplication { // console.log(`[${new Date().toISOString()}] Loggers shut down successfully (${Date.now() - startTime}ms)`); } catch (error) { // Use console.error since logger might be partially shut down - console.error(`[${new Date().toISOString()}] Error shutting down loggers:`, error); + process.stderr.write(`Error shutting down loggers: ${String(error)}\n`); } }, SHUTDOWN_DEFAULTS.LOW_PRIORITY, 'Loggers' ); - + this.logger.info('All shutdown handlers registered', { service: this.serviceConfig.serviceName, - handlerCount: 3 + (this.serviceConfig.enableScheduledJobs ? 1 : 0) + (this.hooks.onBeforeShutdown ? 1 : 0) + handlerCount: + 3 + + (this.serviceConfig.enableScheduledJobs ? 1 : 0) + + (this.hooks.onBeforeShutdown ? 1 : 0), }); } @@ -328,7 +338,10 @@ export class ServiceApplication { async start( containerFactory: (config: UnifiedAppConfig) => Promise>, routeFactory: (container: IServiceContainer) => Hono, - handlerInitializer?: (container: IServiceContainer) => Promise + handlerInitializer?: ( + container: IServiceContainer, + context: HandlerInitializationContext + ) => Promise ): Promise { this.logger.info(`Initializing ${this.serviceConfig.serviceName} service...`); @@ -337,7 +350,7 @@ export class ServiceApplication { this.logger.debug('Creating DI container...'); // Config already has service name from constructor this.container = await containerFactory(this.config); - this.serviceContainer = this.container!.resolve('serviceContainer'); + this.serviceContainer = defined(this.container).resolve('serviceContainer'); this.logger.info('DI container created and initialized'); // Call container ready hook @@ -356,31 +369,30 @@ export class ServiceApplication { // Initialize handlers if enabled if (this.serviceConfig.enableHandlers && handlerInitializer) { this.logger.debug('Initializing handlers...'); - // Pass the service container with the DI container attached - const containerWithDI = Object.assign({}, this.serviceContainer, { - _diContainer: this.container, + await handlerInitializer(this.serviceContainer, { + handlerScanner: this.container.resolve('handlerScanner'), + handlerRegistry: this.container.resolve('handlerRegistry'), }); - await handlerInitializer(containerWithDI); 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'); - + if (queueManager && handlerRegistry) { const rateLimitRules = []; const allMetadata = handlerRegistry.getAllMetadata(); - + for (const [handlerName, metadata] of allMetadata) { // Handler-level rate limit if (metadata.rateLimit) { rateLimitRules.push({ level: 'handler' as const, handler: handlerName, - config: metadata.rateLimit as any, // Type mismatch between packages + config: metadata.rateLimit, // Type mismatch between packages }); } - + // Operation-level rate limits for (const operation of metadata.operations) { if (operation.rateLimit) { @@ -388,12 +400,12 @@ export class ServiceApplication { level: 'operation' as const, handler: handlerName, operation: operation.name, - config: operation.rateLimit as any, // Type mismatch between packages + config: operation.rateLimit, // Type mismatch between packages }); } } } - + if (rateLimitRules.length > 0) { await queueManager.addRateLimitRules(rateLimitRules); this.logger.info('Rate limit rules added to QueueManager', { diff --git a/libs/core/di/src/types.ts b/libs/core/di/src/types.ts index 2cf2b0f6..5de26740 100644 --- a/libs/core/di/src/types.ts +++ b/libs/core/di/src/types.ts @@ -1,6 +1,6 @@ // Generic types to avoid circular dependencies export interface GenericClientConfig { - [key: string]: any; + [key: string]: unknown; } export interface ConnectionPoolConfig { @@ -58,14 +58,14 @@ export interface PoolMetrics { } export interface ConnectionFactory { - createMongoDB(config: MongoDBPoolConfig): Promise>; - createPostgreSQL(config: PostgreSQLPoolConfig): Promise>; - createCache(config: CachePoolConfig): Promise>; - createQueue(config: QueuePoolConfig): Promise>; + 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; + ): ConnectionPool | undefined; listPools(): Array<{ type: string; name: string; metrics: PoolMetrics }>; disposeAll(): Promise; } diff --git a/libs/core/di/test/handler-scanner.test.ts b/libs/core/di/test/handler-scanner.test.ts index 06a5a20a..19444402 100644 --- a/libs/core/di/test/handler-scanner.test.ts +++ b/libs/core/di/test/handler-scanner.test.ts @@ -26,7 +26,7 @@ class MockHandler implements IHandler { constructor(private serviceContainer: any) {} - async execute(operation: string, payload: any, context: ExecutionContext): Promise { + async execute(operation: string, payload: any, _context: ExecutionContext): Promise { switch (operation) { case 'processData': return { processed: true, data: payload }; diff --git a/libs/core/di/test/registration.test.ts b/libs/core/di/test/registration.test.ts index 2114dcc1..719b6046 100644 --- a/libs/core/di/test/registration.test.ts +++ b/libs/core/di/test/registration.test.ts @@ -1,4 +1,4 @@ -import { asClass, asFunction, asValue, createContainer } from 'awilix'; +import { asFunction, asValue, createContainer } from 'awilix'; import { describe, expect, it, mock } from 'bun:test'; import { registerApplicationServices, diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index b15c7108..5d99a761 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, describe, expect, it, mock } from 'bun:test'; import type { BaseAppConfig } from '@stock-bot/config'; import { ServiceApplication } from '../src/service-application'; import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application'; @@ -31,7 +31,7 @@ const mockShutdownInstance = { }; const mockShutdown = { - getInstance: mock(() => mockShutdownInstance) + getInstance: mock(() => mockShutdownInstance), }; mock.module('@stock-bot/shutdown', () => ({ @@ -45,7 +45,7 @@ const mockServer = { hostname: '0.0.0.0', }; -const originalBunServe = Bun.serve; +const _originalBunServe = Bun.serve; Bun.serve = mock(() => mockServer); const mockConfig: BaseAppConfig = { diff --git a/libs/core/di/test/types.test.ts b/libs/core/di/test/types.test.ts index 8eff3784..b1818702 100644 --- a/libs/core/di/test/types.test.ts +++ b/libs/core/di/test/types.test.ts @@ -253,7 +253,7 @@ describe('DI Types', () => { health: async () => true, dispose: async () => {}, }), - getPool: (type, name) => undefined, + getPool: (_type, _name) => undefined, listPools: () => [], disposeAll: async () => {}, }; diff --git a/libs/core/di/tsconfig.json b/libs/core/di/tsconfig.json index 2c18f1ec..20659216 100644 --- a/libs/core/di/tsconfig.json +++ b/libs/core/di/tsconfig.json @@ -11,9 +11,20 @@ "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist", "test"], "references": [ - { "path": "../services" }, - { "path": "../config" }, - { "path": "../logger" }, - { "path": "../queue" } + { + "path": "../services" + }, + { + "path": "../config" + }, + { + "path": "../logger" + }, + { + "path": "../queue" + }, + { + "path": "../../../libs/core/invariants" + } ] } diff --git a/libs/core/event-bus/package.json b/libs/core/event-bus/package.json index 4438893d..2a5243c6 100644 --- a/libs/core/event-bus/package.json +++ b/libs/core/event-bus/package.json @@ -13,7 +13,8 @@ "dependencies": { "@stock-bot/logger": "*", "ioredis": "^5.3.2", - "eventemitter3": "^5.0.1" + "eventemitter3": "^5.0.1", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/node": "^20.11.0", diff --git a/libs/core/event-bus/src/event-bus.ts b/libs/core/event-bus/src/event-bus.ts index 2a40b3a0..06951e5f 100644 --- a/libs/core/event-bus/src/event-bus.ts +++ b/libs/core/event-bus/src/event-bus.ts @@ -98,7 +98,11 @@ export class EventBus extends EventEmitter { /** * Publish an event */ - async publish(type: string, data: T, metadata?: Record): Promise { + async publish( + type: string, + data: T, + metadata?: Record + ): Promise { const message: EventBusMessage = { id: this.generateId(), type, @@ -129,9 +133,12 @@ export class EventBus extends EventEmitter { /** * Subscribe to an event */ - async subscribe(eventType: string, handler: EventHandler): Promise { + async subscribe(eventType: string, handler: EventHandler): Promise { // Register handler - this.subscriptions.set(eventType, { channel: `events:${eventType}`, handler }); + this.subscriptions.set(eventType, { + channel: `events:${eventType}`, + handler: message => handler(message as EventBusMessage), + }); // Add local listener this.on(eventType, handler); diff --git a/libs/core/event-bus/src/simple-event-bus.ts b/libs/core/event-bus/src/simple-event-bus.ts index 00e36300..b4d453d7 100644 --- a/libs/core/event-bus/src/simple-event-bus.ts +++ b/libs/core/event-bus/src/simple-event-bus.ts @@ -1,3 +1,4 @@ +import { defined } from '@stock-bot/invariants'; import type { EventBusMessage, EventHandler, EventSubscription } from './types'; /** @@ -18,7 +19,7 @@ export class SimpleEventBus { if (!this.subscriptions.has(channel)) { this.subscriptions.set(channel, new Set()); } - this.subscriptions.get(channel)!.add(subscription); + defined(this.subscriptions.get(channel)).add(subscription); this.subscriptionById.set(id, { id, channel, handler }); return { channel, handler }; @@ -66,7 +67,7 @@ export class SimpleEventBus { } } - async publish(event: string, data: any): Promise { + async publish(event: string, data: unknown): Promise { const message: EventBusMessage = { id: `msg-${this.nextId++}`, type: event, @@ -93,14 +94,14 @@ export class SimpleEventBus { // Execute all handlers await Promise.all( handlers.map(handler => - Promise.resolve(handler(message)).catch(err => { + Promise.resolve(handler(message)).catch(_err => { // Silently catch errors }) ) ); } - publishSync(event: string, data: any): void { + publishSync(event: string, data: unknown): void { const message: EventBusMessage = { id: `msg-${this.nextId++}`, type: event, @@ -188,7 +189,7 @@ export class SimpleEventBus { } hasSubscribers(event: string): boolean { - return this.subscriptions.has(event) && this.subscriptions.get(event)!.size > 0; + return this.subscriptions.has(event) && defined(this.subscriptions.get(event)).size > 0; } clear(): void { diff --git a/libs/core/event-bus/src/types.ts b/libs/core/event-bus/src/types.ts index 07b8f530..bb2032dd 100644 --- a/libs/core/event-bus/src/types.ts +++ b/libs/core/event-bus/src/types.ts @@ -1,4 +1,4 @@ -export interface EventBusMessage { +export interface EventBusMessage { id: string; type: string; source: string; @@ -7,7 +7,7 @@ export interface EventBusMessage { metadata?: Record; } -export interface EventHandler { +export interface EventHandler { (message: EventBusMessage): Promise | void; } diff --git a/libs/core/event-bus/tsconfig.json b/libs/core/event-bus/tsconfig.json index 55c59a82..0b1bc98a 100644 --- a/libs/core/event-bus/tsconfig.json +++ b/libs/core/event-bus/tsconfig.json @@ -6,5 +6,12 @@ "composite": true }, "include": ["src/**/*"], - "references": [{ "path": "../../core/logger" }] + "references": [ + { + "path": "../../core/logger" + }, + { + "path": "../../../libs/core/invariants" + } + ] } diff --git a/libs/core/handler-registry/src/types.ts b/libs/core/handler-registry/src/types.ts index a1be9990..e51b91cc 100644 --- a/libs/core/handler-registry/src/types.ts +++ b/libs/core/handler-registry/src/types.ts @@ -3,16 +3,18 @@ * Pure types for handler metadata and registration */ -import type { JobHandler, ScheduledJob } from '@stock-bot/types'; +import type { + DecoratedHandlerClass, + HandlerRateLimitConfig, + JobHandler, + RateLimitWindow, + ScheduledJob, +} from '@stock-bot/types'; /** * Rate limit configuration */ -export interface RateLimitConfig { - points: number; - duration: number; - blockDuration?: number; -} +export type RateLimitConfig = HandlerRateLimitConfig & Partial; /** * Metadata for a single operation within a handler @@ -72,6 +74,6 @@ export interface RegistryStats { */ export interface HandlerDiscoveryResult { handler: HandlerMetadata; - constructor: any; + constructor: DecoratedHandlerClass; filePath?: string; } diff --git a/libs/core/handler-registry/test/registry-edge-cases.test.ts b/libs/core/handler-registry/test/registry-edge-cases.test.ts index 5282da54..2ccd9e73 100644 --- a/libs/core/handler-registry/test/registry-edge-cases.test.ts +++ b/libs/core/handler-registry/test/registry-edge-cases.test.ts @@ -1,12 +1,7 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; import type { JobHandler, ScheduledJob } from '@stock-bot/types'; import { HandlerRegistry } from '../src/registry'; -import type { - HandlerConfiguration, - HandlerMetadata, - OperationMetadata, - ScheduleMetadata, -} from '../src/types'; +import type { HandlerConfiguration, HandlerMetadata } from '../src/types'; describe('HandlerRegistry Edge Cases', () => { let registry: HandlerRegistry; diff --git a/libs/core/handlers/src/base/BaseHandler.ts b/libs/core/handlers/src/base/BaseHandler.ts index a9248f20..a5e26239 100644 --- a/libs/core/handlers/src/base/BaseHandler.ts +++ b/libs/core/handlers/src/base/BaseHandler.ts @@ -1,15 +1,17 @@ +import type { Collection, Document } from 'mongodb'; import { createNamespacedCache } from '@stock-bot/cache'; import { getLogger } from '@stock-bot/logger'; +import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; import type { + DecoratedHandlerClass, ExecutionContext, HandlerConfigWithSchedule, HandlerMetadata, IHandler, JobHandler, } from '@stock-bot/types'; -import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; +import type { FetchOptions } from '@stock-bot/utils'; import { fetch } from '@stock-bot/utils'; -import type { Collection, Document } from 'mongodb'; // Handler registry is now injected, not imported import { createJobHandler } from '../utils/create-job-handler'; @@ -40,7 +42,9 @@ export interface JobScheduleOptions { * Abstract base class for all handlers with improved DI * Provides common functionality and structure for queue/event operations */ -export abstract class BaseHandler implements IHandler { +export abstract class BaseHandler + implements IHandler +{ // Direct service properties - flattened for cleaner access with proper types readonly logger: TServices['logger']; readonly cache: TServices['cache']; @@ -57,7 +61,7 @@ export abstract class BaseHandler constructor(services: TServices, handlerName?: string) { // Read handler name from decorator first, then fallback to parameter or class name - const constructor = this.constructor as any; + const constructor = this.constructor as DecoratedHandlerClass; this.handlerName = constructor.__handlerName || handlerName || this.constructor.name.toLowerCase(); @@ -83,28 +87,28 @@ export abstract class BaseHandler * Works with queue (events commented for future) */ async execute(operation: string, input: unknown, context: ExecutionContext): Promise { - const constructor = this.constructor as any; + const constructor = this.constructor as DecoratedHandlerClass; const operations = constructor.__operations || []; // Debug logging this.logger.debug('Handler execute called', { handler: this.handlerName, operation, - availableOperations: operations.map((op: any) => ({ name: op.name, method: op.method })), + availableOperations: operations.map(op => ({ name: op.name, method: op.method })), }); // Find the operation metadata - const operationMeta = operations.find((op: any) => op.name === operation); + const operationMeta = operations.find(op => op.name === operation); if (!operationMeta) { this.logger.error('Operation not found', { requestedOperation: operation, - availableOperations: operations.map((op: any) => op.name), + availableOperations: operations.map(op => op.name), }); throw new Error(`Unknown operation: ${operation}`); } // Get the method from the instance and call it - const method = (this as any)[operationMeta.method]; + const method: unknown = Reflect.get(this, operationMeta.method); if (typeof method !== 'function') { throw new Error(`Operation method '${operationMeta.method}' not found on handler`); } @@ -125,7 +129,7 @@ export abstract class BaseHandler if (!this.queue) { throw new Error('Queue service is not available for this handler'); } - + const jobData = { handler: this.handlerName, operation, @@ -140,7 +144,7 @@ export abstract class BaseHandler */ protected createExecutionContext( type: 'http' | 'queue' | 'scheduled', - metadata: Record = {} + metadata: Record = {} ): ExecutionContext { return { type, @@ -177,18 +181,18 @@ export abstract class BaseHandler /** * Set cache with handler-prefixed key */ - protected async cacheSet(key: string, value: any, ttl?: number): Promise { + protected async cacheSet(key: string, value: unknown, ttl?: number): Promise { if (!this.cache) { return; } // Don't add 'cache:' prefix since the cache already has its own prefix - return this.cache.set(`${this.handlerName}:${key}`, value, ttl); + await this.cache.set(`${this.handlerName}:${key}`, value, ttl); } /** * Get cache with handler-prefixed key */ - protected async cacheGet(key: string): Promise { + protected async cacheGet(key: string): Promise { if (!this.cache) { return null; } @@ -210,17 +214,17 @@ export abstract class BaseHandler /** * Set global cache with key */ - protected async globalCacheSet(key: string, value: any, ttl?: number): Promise { + protected async globalCacheSet(key: string, value: unknown, ttl?: number): Promise { if (!this.globalCache) { return; } - return this.globalCache.set(key, value, ttl); + await this.globalCache.set(key, value, ttl); } /** * Get global cache with key */ - protected async globalCacheGet(key: string): Promise { + protected async globalCacheGet(key: string): Promise { if (!this.globalCache) { return null; } @@ -254,7 +258,7 @@ export abstract class BaseHandler /** * Log with handler context */ - protected log(level: 'info' | 'warn' | 'error' | 'debug', message: string, meta?: any): void { + protected log(level: 'info' | 'warn' | 'error' | 'debug', message: string, meta?: object): void { this.logger[level](message, { handler: this.handlerName, ...meta }); } @@ -263,9 +267,9 @@ export abstract class BaseHandler */ protected get http() { return { - get: (url: string, options?: any) => + get: (url: string, options?: FetchOptions) => fetch(url, { ...options, method: 'GET', logger: this.logger }), - post: (url: string, data?: any, options?: any) => + post: (url: string, data?: unknown, options?: FetchOptions) => fetch(url, { ...options, method: 'POST', @@ -273,7 +277,7 @@ export abstract class BaseHandler headers: { 'Content-Type': 'application/json', ...options?.headers }, logger: this.logger, }), - put: (url: string, data?: any, options?: any) => + put: (url: string, data?: unknown, options?: FetchOptions) => fetch(url, { ...options, method: 'PUT', @@ -281,7 +285,7 @@ export abstract class BaseHandler headers: { 'Content-Type': 'application/json', ...options?.headers }, logger: this.logger, }), - delete: (url: string, options?: any) => + delete: (url: string, options?: FetchOptions) => fetch(url, { ...options, method: 'DELETE', logger: this.logger }), }; } @@ -314,7 +318,7 @@ export abstract class BaseHandler const operationHandlers: Record = {}; for (const opName of metadata.operations) { - operationHandlers[opName] = createJobHandler(async (payload: any) => { + operationHandlers[opName] = createJobHandler(async (payload: unknown) => { const context: ExecutionContext = { type: 'queue', metadata: { source: 'queue', timestamp: Date.now() }, @@ -335,7 +339,7 @@ export abstract class BaseHandler * This returns metadata only - actual handler instances are created by the scanner */ static extractMetadata(): HandlerMetadata | null { - const constructor = this as any; + const constructor = this as DecoratedHandlerClass; const handlerName = constructor.__handlerName; if (!handlerName) { return null; @@ -345,9 +349,9 @@ export abstract class BaseHandler const schedules = constructor.__schedules || []; // Create scheduled jobs from decorator metadata - const scheduledJobs = schedules.map((schedule: any) => { + const scheduledJobs = schedules.map(schedule => { // Find the operation name from the method name - const operation = operations.find((op: any) => op.method === schedule.operation); + const operation = operations.find(op => op.method === schedule.operation); return { type: `${handlerName}-${schedule.operation}`, operation: operation?.name || schedule.operation, @@ -362,7 +366,7 @@ export abstract class BaseHandler return { name: handlerName, - operations: operations.map((op: any) => op.name), + operations: operations.map(op => op.name), scheduledJobs, description: constructor.__description, }; @@ -373,7 +377,7 @@ export abstract class BaseHandler * @param operation The operation name that needs a payload * @returns The payload for the scheduled job, or undefined */ - protected getScheduledJobPayload?(operation: string): any; + protected getScheduledJobPayload?(operation: string): unknown; /** * Lifecycle hooks - can be overridden by subclasses diff --git a/libs/core/handlers/src/decorators/decorators.ts b/libs/core/handlers/src/decorators/decorators.ts index 42f25b91..1c807b93 100644 --- a/libs/core/handlers/src/decorators/decorators.ts +++ b/libs/core/handlers/src/decorators/decorators.ts @@ -1,14 +1,20 @@ -// Bun-compatible decorators (hybrid approach) +import type { + ClassMemberMetadataDecorator, + DecoratedHandlerClass, + MemberMetadataDecorator, +} from '@stock-bot/types'; + +// Bun-compatible legacy decorators. /** * Handler decorator - marks a class as a handler * @param name Handler name for registration */ export function Handler(name: string) { - return function (target: T, _context?: any) { + return function (target: T, _context?: unknown) { // Store handler name on the constructor - (target as any).__handlerName = name; - (target as any).__needsAutoRegistration = true; + (target as DecoratedHandlerClass).__handlerName = name; + (target as DecoratedHandlerClass).__needsAutoRegistration = true; return target; }; @@ -30,17 +36,17 @@ export function Operation( direct?: boolean; }; } -): any { - return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any { +): MemberMetadataDecorator { + return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) { // Store metadata directly on the class constructor - const constructor = target.constructor; + const constructor = target.constructor as DecoratedHandlerClass; if (!constructor.__operations) { constructor.__operations = []; } constructor.__operations.push({ name, - method: methodName, + method: String(methodName), batch: options?.batch, }); @@ -59,7 +65,7 @@ export function QueueSchedule( priority?: number; immediately?: boolean; description?: string; - payload?: any; + payload?: unknown; batch?: { enabled?: boolean; size?: number; @@ -68,16 +74,16 @@ export function QueueSchedule( direct?: boolean; }; } -): any { - return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any { +): MemberMetadataDecorator { + return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) { // Store metadata directly on the class constructor - const constructor = target.constructor; + const constructor = target.constructor as DecoratedHandlerClass; if (!constructor.__schedules) { constructor.__schedules = []; } constructor.__schedules.push({ - operation: methodName, + operation: String(methodName), cronPattern, ...options, }); @@ -92,22 +98,27 @@ export function QueueSchedule( * - Classes: Entire handler will be skipped during auto-registration * - Methods: Individual operations will be skipped during registration */ -export function Disabled() { - return function (target: any, propertyKey?: string, descriptor?: PropertyDescriptor): any { - if (propertyKey) { +export function Disabled(): ClassMemberMetadataDecorator { + const decorator = function ( + target: object, + propertyKey?: unknown, + descriptor?: PropertyDescriptor + ) { + if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') { // Method decorator - mark specific operation as disabled - const constructor = target.constructor; + const constructor = target.constructor as DecoratedHandlerClass; if (!constructor.__disabledOperations) { constructor.__disabledOperations = []; } - constructor.__disabledOperations.push(propertyKey); + constructor.__disabledOperations.push(String(propertyKey)); return descriptor; } else { // Class decorator - mark entire handler as disabled - (target as any).__disabled = true; + (target as DecoratedHandlerClass).__disabled = true; return target; } }; + return decorator as ClassMemberMetadataDecorator; } /** @@ -124,7 +135,7 @@ export function ScheduledOperation( priority?: number; immediately?: boolean; description?: string; - payload?: any; + payload?: unknown; batch?: { enabled?: boolean; size?: number; @@ -133,8 +144,8 @@ export function ScheduledOperation( direct?: boolean; }; } -): any { - return function (target: any, methodName: string, descriptor?: PropertyDescriptor): any { +): MemberMetadataDecorator { + return function (target: object, methodName: string | symbol, descriptor?: PropertyDescriptor) { // Apply both decorators with batch configuration Operation(name, { batch: options?.batch })(target, methodName, descriptor); QueueSchedule(cronPattern, options)(target, methodName, descriptor); @@ -144,7 +155,7 @@ export function ScheduledOperation( // Future event decorators - commented for now // export function EventListener(eventName: string) { -// return function (target: any, propertyName: string, descriptor: PropertyDescriptor) { +// return function (target: object, propertyName: string, descriptor: PropertyDescriptor) { // if (!target.constructor.__eventListeners) { // target.constructor.__eventListeners = []; // } @@ -157,7 +168,7 @@ export function ScheduledOperation( // } // export function EventPublisher(eventName: string) { -// return function (target: any, propertyName: string, descriptor: PropertyDescriptor) { +// return function (target: object, propertyName: string, descriptor: PropertyDescriptor) { // if (!target.constructor.__eventPublishers) { // target.constructor.__eventPublishers = []; // } diff --git a/libs/core/handlers/src/decorators/rate-limit.ts b/libs/core/handlers/src/decorators/rate-limit.ts index 3fc1da9a..ae231d1e 100644 --- a/libs/core/handlers/src/decorators/rate-limit.ts +++ b/libs/core/handlers/src/decorators/rate-limit.ts @@ -1,110 +1,110 @@ -/** - * Individual rate limit window configuration - */ -export interface RateLimitWindow { - points: number; // Number of allowed points in the time window - duration: number; // Time window in seconds - blockDuration?: number; // How long to block after limit is hit (seconds) -} - -/** - * Rate limit configuration for handlers and operations - */ -export interface RateLimitConfig { - limits?: RateLimitWindow[]; // Array of rate limit windows - cost?: number; // How many points this operation costs (default: 1) -} - -/** - * Flexible rate limit configuration - * Can be: - * - A full config object with limits and cost - * - Just a cost number (for operations inheriting handler limits) - * - An array of limit windows (legacy support) - * - A single limit window (legacy support) - */ -export type RateLimitOptions = RateLimitConfig | number | RateLimitWindow[] | RateLimitWindow; - -/** - * RateLimit decorator - configures rate limiting for handlers or operations - * - * Can be applied to: - * - Classes: Sets default rate limit for all operations in the handler - * - Methods: Sets specific rate limit for individual operations (overrides handler-level) - * - * @param options Rate limit configuration - flexible format - * - * @example - * // Handler-level rate limit with multiple windows - * @Handler('myHandler') - * @RateLimit({ - * limits: [ - * { points: 100, duration: 1 }, // 100 points/second - * { points: 10000, duration: 3600 } // 10k points/hour - * ], - * cost: 1 // Default cost for all operations - * }) - * class MyHandler extends BaseHandler { - * // All operations inherit these limits - * } - * - * @example - * // Operation-specific cost only (inherits handler limits) - * @Operation('fetch-simple') - * @RateLimit(1) // Costs 1 point - * async fetchSimple() {} - * - * @Operation('fetch-complex') - * @RateLimit({ cost: 10 }) // Costs 10 points - * async fetchComplex() {} - * - * @example - * // Operation with custom limits and cost - * @Operation('special-operation') - * @RateLimit({ - * limits: [ - * { points: 10, duration: 60 } // More restrictive: 10/minute - * ], - * cost: 5 - * }) - * async specialOperation() {} - */ -export function RateLimit(options: RateLimitOptions) { - return function (target: any, propertyKey?: string, descriptor?: PropertyDescriptor): any { - // Normalize options to RateLimitConfig format - let config: RateLimitConfig; - - if (typeof options === 'number') { - // Just a cost number - config = { cost: options }; - } else if (Array.isArray(options)) { - // Array of limit windows (legacy support) - config = { limits: options }; - } else if ('points' in options && 'duration' in options) { - // Single limit window (legacy support) - config = { limits: [options as RateLimitWindow] }; - } else { - // Already a RateLimitConfig - config = options as RateLimitConfig; - } - - if (propertyKey) { - // Method decorator - operation-specific rate limit - const constructor = target.constructor; - - // Initialize rate limits array if not exists - if (!constructor.__rateLimits) { - constructor.__rateLimits = {}; - } - - // Store rate limit config for this operation - constructor.__rateLimits[propertyKey] = config; - - return descriptor; - } else { - // Class decorator - handler-level rate limit - (target as any).__handlerRateLimit = config; - return target; - } - }; -} \ No newline at end of file +import type { ClassMemberMetadataDecorator, DecoratedHandlerClass } from '@stock-bot/types'; + +/** + * Individual rate limit window configuration + */ +export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow; + +/** + * Rate limit configuration for handlers and operations + */ +export type RateLimitConfig = import('@stock-bot/types').HandlerRateLimitConfig; + +/** + * Flexible rate limit configuration + * Can be: + * - A full config object with limits and cost + * - Just a cost number (for operations inheriting handler limits) + * - An array of limit windows (legacy support) + * - A single limit window (legacy support) + */ +export type RateLimitOptions = RateLimitConfig | number | RateLimitWindow[] | RateLimitWindow; + +/** + * RateLimit decorator - configures rate limiting for handlers or operations + * + * Can be applied to: + * - Classes: Sets default rate limit for all operations in the handler + * - Methods: Sets specific rate limit for individual operations (overrides handler-level) + * + * @param options Rate limit configuration - flexible format + * + * @example + * // Handler-level rate limit with multiple windows + * @Handler('myHandler') + * @RateLimit({ + * limits: [ + * { points: 100, duration: 1 }, // 100 points/second + * { points: 10000, duration: 3600 } // 10k points/hour + * ], + * cost: 1 // Default cost for all operations + * }) + * class MyHandler extends BaseHandler { + * // All operations inherit these limits + * } + * + * @example + * // Operation-specific cost only (inherits handler limits) + * @Operation('fetch-simple') + * @RateLimit(1) // Costs 1 point + * async fetchSimple() {} + * + * @Operation('fetch-complex') + * @RateLimit({ cost: 10 }) // Costs 10 points + * async fetchComplex() {} + * + * @example + * // Operation with custom limits and cost + * @Operation('special-operation') + * @RateLimit({ + * limits: [ + * { points: 10, duration: 60 } // More restrictive: 10/minute + * ], + * cost: 5 + * }) + * async specialOperation() {} + */ +export function RateLimit(options: RateLimitOptions): ClassMemberMetadataDecorator { + const decorator = function ( + target: object, + propertyKey?: unknown, + descriptor?: PropertyDescriptor + ) { + // Normalize options to RateLimitConfig format + let config: RateLimitConfig; + + if (typeof options === 'number') { + // Just a cost number + config = { cost: options }; + } else if (Array.isArray(options)) { + // Array of limit windows (legacy support) + config = { limits: options }; + } else if ('points' in options && 'duration' in options) { + // Single limit window (legacy support) + config = { limits: [options as RateLimitWindow] }; + } else { + // Already a RateLimitConfig + config = options as RateLimitConfig; + } + + if (typeof propertyKey === 'string' || typeof propertyKey === 'symbol') { + // Method decorator - operation-specific rate limit + const constructor = target.constructor as DecoratedHandlerClass; + + // Initialize rate limits array if not exists + if (!constructor.__rateLimits) { + constructor.__rateLimits = {}; + } + + // Store rate limit config for this operation + constructor.__rateLimits[String(propertyKey)] = config; + + return descriptor; + } else { + // Class decorator - handler-level rate limit + (target as DecoratedHandlerClass).__handlerRateLimit = config; + return target; + } + }; + return decorator as ClassMemberMetadataDecorator; +} diff --git a/libs/core/handlers/test/base-handler-config.test.ts b/libs/core/handlers/test/base-handler-config.test.ts index c78cf5d1..212ac797 100644 --- a/libs/core/handlers/test/base-handler-config.test.ts +++ b/libs/core/handlers/test/base-handler-config.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import type { ExecutionContext } from '@stock-bot/types'; import type { IServiceContainer } from '@stock-bot/services'; +import type { ExecutionContext } from '@stock-bot/types'; import { BaseHandler } from '../src/base/BaseHandler'; // Test handler with metadata @@ -23,11 +23,11 @@ class ConfigTestHandler extends BaseHandler { ]; static __description = 'Test handler for configuration'; - async processData(input: any, context: ExecutionContext) { + async processData(input: any, _context: ExecutionContext) { return { processed: true, input }; } - async validateData(input: any, context: ExecutionContext) { + async validateData(input: any, _context: ExecutionContext) { return { valid: true, input }; } } diff --git a/libs/core/handlers/test/base-handler-http.test.ts b/libs/core/handlers/test/base-handler-http.test.ts index ffdf6026..4785c704 100644 --- a/libs/core/handlers/test/base-handler-http.test.ts +++ b/libs/core/handlers/test/base-handler-http.test.ts @@ -1,5 +1,4 @@ import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; -import type { ExecutionContext } from '@stock-bot/types'; import type { IServiceContainer } from '@stock-bot/services'; import * as utils from '@stock-bot/utils'; import { BaseHandler } from '../src/base/BaseHandler'; diff --git a/libs/core/handlers/test/base-handler.test.ts b/libs/core/handlers/test/base-handler.test.ts index 87b1c914..8f069e10 100644 --- a/libs/core/handlers/test/base-handler.test.ts +++ b/libs/core/handlers/test/base-handler.test.ts @@ -1,13 +1,8 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test'; -import type { Collection, Db, MongoClient } from 'mongodb'; -import type { Pool, QueryResult } from 'pg'; -import type { SimpleBrowser } from '@stock-bot/browser'; -import type { CacheProvider } from '@stock-bot/cache'; +import type { QueryResult } from 'pg'; import type { Logger } from '@stock-bot/logger'; -import type { SimpleProxyManager } from '@stock-bot/proxy'; -import type { Queue, QueueManager } from '@stock-bot/queue'; -import type { ExecutionContext } from '@stock-bot/types'; import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; +import type { ExecutionContext } from '@stock-bot/types'; import { BaseHandler, ScheduledHandler } from '../src/base/BaseHandler'; import { Handler, Operation } from '../src/decorators/decorators'; @@ -68,7 +63,7 @@ type MockMongoDB = { describe('BaseHandler', () => { let mockServices: IServiceContainer; - let mockContext: ExecutionContext; + let _mockContext: ExecutionContext; let mockQueue: MockQueue; let mockQueueManager: MockQueueManager; let mockCache: MockCache; @@ -139,7 +134,7 @@ describe('BaseHandler', () => { queue: mockQueue as unknown as ServiceTypes['queue'], }; - mockContext = { + _mockContext = { logger: mockLogger as unknown as Logger, traceId: 'trace-123', handlerName: 'TestHandler', diff --git a/libs/core/handlers/test/create-job-handler.test.ts b/libs/core/handlers/test/create-job-handler.test.ts index 48783bd5..b97e681d 100644 --- a/libs/core/handlers/test/create-job-handler.test.ts +++ b/libs/core/handlers/test/create-job-handler.test.ts @@ -17,7 +17,7 @@ describe('createJobHandler', () => { it('should create a type-safe job handler function', () => { const handler = createJobHandler(async job => { // Job should have correct payload type - const { userId, action, data } = job.data; + const { userId, action: _action, data: _data } = job.data; return { success: true, @@ -166,8 +166,8 @@ describe('createJobHandler', () => { // Type-safe access to nested properties const userId = job.data.user.id; - const requestType = job.data.request.type; - const version = job.data.metadata.version; + const _requestType = job.data.request.type; + const _version = job.data.metadata.version; return { status: 'success', diff --git a/libs/core/handlers/test/decorators-edge-cases.test.ts b/libs/core/handlers/test/decorators-edge-cases.test.ts index 964f5929..23a0db16 100644 --- a/libs/core/handlers/test/decorators-edge-cases.test.ts +++ b/libs/core/handlers/test/decorators-edge-cases.test.ts @@ -376,7 +376,7 @@ describe('Decorators Edge Cases', () => { @Operation('hasOwnProperty-op') hasOwnProperty(v: string | symbol): boolean { - return super.hasOwnProperty(v); + return Object.prototype.hasOwnProperty.call(this, v); } } diff --git a/libs/core/handlers/test/handlers.test.ts b/libs/core/handlers/test/handlers.test.ts index 130c55c1..6721add9 100644 --- a/libs/core/handlers/test/handlers.test.ts +++ b/libs/core/handlers/test/handlers.test.ts @@ -1,9 +1,6 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test'; -import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/logger'; -import type { Queue, QueueManager } from '@stock-bot/queue'; -import type { ExecutionContext } from '@stock-bot/types'; import type { IServiceContainer, ServiceTypes } from '@stock-bot/services'; +import type { ExecutionContext } from '@stock-bot/types'; import { BaseHandler } from '../src/base/BaseHandler'; import { Handler, diff --git a/libs/core/handlers/test/index.test.ts b/libs/core/handlers/test/index.test.ts index e4dfaee1..ea7f86fe 100644 --- a/libs/core/handlers/test/index.test.ts +++ b/libs/core/handlers/test/index.test.ts @@ -28,20 +28,13 @@ describe('Handlers Package Exports', () => { expect(typeof handlersExports.Disabled).toBe('function'); }); - it('should export types', () => { // Type tests - compile-time checks type TestJobScheduleOptions = handlersExports.JobScheduleOptions; type TestExecutionContext = handlersExports.ExecutionContext; - type TestIHandler = handlersExports.IHandler; - type TestJobHandler = handlersExports.JobHandler; - type TestScheduledJob = handlersExports.ScheduledJob; - type TestHandlerConfig = handlersExports.HandlerConfig; - type TestHandlerConfigWithSchedule = handlersExports.HandlerConfigWithSchedule; - type TestTypedJobHandler = handlersExports.TypedJobHandler; + type TestHandlerMetadata = handlersExports.HandlerMetadata; type TestOperationMetadata = handlersExports.OperationMetadata; - type TestIServiceContainer = handlersExports.IServiceContainer; // Runtime type usage tests const scheduleOptions: TestJobScheduleOptions = { @@ -74,5 +67,4 @@ describe('Handlers Package Exports', () => { expect(handlerMetadata).toBeDefined(); expect(operationMetadata).toBeDefined(); }); - }); diff --git a/libs/core/invariants/package.json b/libs/core/invariants/package.json new file mode 100644 index 00000000..3ea83fae --- /dev/null +++ b/libs/core/invariants/package.json @@ -0,0 +1,18 @@ +{ + "name": "@stock-bot/invariants", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc", + "clean": "rm -rf dist" + } +} diff --git a/libs/core/invariants/src/index.ts b/libs/core/invariants/src/index.ts new file mode 100644 index 00000000..5caddf61 --- /dev/null +++ b/libs/core/invariants/src/index.ts @@ -0,0 +1,15 @@ +/** Assert required input without turning missing data into NaN or a later TypeError. */ +export function defined(value: T | null | undefined, message = 'Required value is missing'): T { + if (value === undefined || value === null) { + throw new Error(message); + } + return value; +} + +export function at(values: ArrayLike, index: number): T { + const value = values[index]; + if (value === undefined) { + throw new RangeError(`Missing array element at index ${index} (length ${values.length})`); + } + return value; +} diff --git a/libs/core/invariants/tsconfig.json b/libs/core/invariants/tsconfig.json new file mode 100644 index 00000000..59c98286 --- /dev/null +++ b/libs/core/invariants/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../../tsconfig.lib.json", + "compilerOptions": { "rootDir": "src", "outDir": "dist", "composite": true }, + "include": ["src/**/*.ts"] +} diff --git a/libs/core/logger/src/logger.ts b/libs/core/logger/src/logger.ts index 58b8c7b3..59a43743 100644 --- a/libs/core/logger/src/logger.ts +++ b/libs/core/logger/src/logger.ts @@ -183,12 +183,12 @@ export class Logger { } if (typeof message === 'string') { - (this.pino as any)[level](data, message); + this.pino[level](data, message); } else { if (globalConfig.hideObject && level !== 'error' && level !== 'fatal') { - (this.pino as any)[level]({}, `Object logged (hidden)`); + this.pino[level]({}, `Object logged (hidden)`); } else { - (this.pino as any)[level]({ ...data, data: message }, 'Object logged'); + this.pino[level]({ ...data, data: message }, 'Object logged'); } } } @@ -210,8 +210,8 @@ export class Logger { this.log('warn', message, metadata); } - error(message: string | object, metadata?: (LogMetadata & { error?: any }) | unknown): void { - let data: any = {}; + error(message: string | object, metadata?: unknown): void { + let data: Record = {}; // Handle metadata parameter normalization if (metadata instanceof Error) { @@ -242,8 +242,8 @@ export class Logger { this.log('error', message, data); } - fatal(message: string | object, metadata?: (LogMetadata & { error?: any }) | unknown): void { - let data: any = {}; + fatal(message: string | object, metadata?: unknown): void { + let data: Record = {}; // Handle metadata parameter normalization (same as error) if (metadata instanceof Error) { @@ -273,7 +273,7 @@ export class Logger { /** * Normalize any error type to a structured format */ - private normalizeError(error: any): any { + private normalizeError(error: unknown): LogMetadata { if (error instanceof Error) { return { name: error.name, @@ -283,13 +283,14 @@ export class Logger { } if (error && typeof error === 'object') { + const errorObject = error as Record; // Handle error-like objects return { - name: error.name || 'UnknownError', - message: error.message || error.toString(), - ...(error.stack && { stack: error.stack }), - ...(error.code && { code: error.code }), - ...(error.status && { status: error.status }), + name: errorObject.name || 'UnknownError', + message: errorObject.message || String(error), + ...(errorObject.stack ? { stack: errorObject.stack } : {}), + ...(errorObject.code ? { code: errorObject.code } : {}), + ...(errorObject.status ? { status: errorObject.status } : {}), }; } diff --git a/libs/core/logger/src/types.ts b/libs/core/logger/src/types.ts index f0c91222..197e7f6a 100644 --- a/libs/core/logger/src/types.ts +++ b/libs/core/logger/src/types.ts @@ -12,13 +12,11 @@ export type LoggerLike = Pick> & // Context that persists across log calls export interface LogContext { - [key: string]: any; + [key: string]: unknown; } // Metadata for individual log entries -export interface LogMetadata { - [key: string]: any; -} +export type LogMetadata = object; // Logger configuration export interface LoggerConfig { diff --git a/libs/core/queue/package.json b/libs/core/queue/package.json index 02bacd4c..402e09a9 100644 --- a/libs/core/queue/package.json +++ b/libs/core/queue/package.json @@ -17,7 +17,8 @@ "@stock-bot/cache": "*", "@stock-bot/handler-registry": "*", "@stock-bot/logger": "*", - "@stock-bot/types": "*" + "@stock-bot/types": "*", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "typescript": "^5.3.0", diff --git a/libs/core/queue/src/batch-processor.ts b/libs/core/queue/src/batch-processor.ts index c44f9588..0016ca1d 100644 --- a/libs/core/queue/src/batch-processor.ts +++ b/libs/core/queue/src/batch-processor.ts @@ -1,4 +1,4 @@ -import { QueueManager } from './queue-manager'; +import type { QueueManager } from './queue-manager'; import type { BatchJobData, BatchResult, JobData, ProcessOptions } from './types'; /** @@ -9,7 +9,7 @@ export async function processItems( items: T[], queueName: string, options: ProcessOptions, - queueManager: QueueManager + queueManager: Pick ): Promise { const queue = queueManager.getQueue(queueName); const logger = queue.createChildLogger('batch-processor', { @@ -61,7 +61,7 @@ async function processDirect( items: T[], queueName: string, options: ProcessOptions, - queueManager: QueueManager + queueManager: Pick ): Promise> { const queue = queueManager.getQueue(queueName); const logger = queue.createChildLogger('batch-direct', { @@ -109,7 +109,7 @@ async function processBatched( items: T[], queueName: string, options: ProcessOptions, - queueManager: QueueManager + queueManager: Pick ): Promise> { const queue = queueManager.getQueue(queueName); const logger = queue.createChildLogger('batch-batched', { @@ -174,7 +174,7 @@ async function processBatched( export async function processBatchJob( jobData: BatchJobData, queueName: string, - queueManager: QueueManager + queueManager: Pick ): Promise { const queue = queueManager.getQueue(queueName); const logger = queue.createChildLogger('batch-job', { @@ -258,7 +258,7 @@ async function storeItems( items: T[], queueName: string, options: ProcessOptions, - queueManager: QueueManager + queueManager: Pick ): Promise { const cache = queueManager.getCache(queueName); const payloadKey = `payload:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`; @@ -284,7 +284,7 @@ async function storeItems( async function loadPayload( key: string, queueName: string, - queueManager: QueueManager + queueManager: Pick ): Promise<{ items: T[]; options: { @@ -311,7 +311,7 @@ async function loadPayload( async function cleanupPayload( key: string, queueName: string, - queueManager: QueueManager + queueManager: Pick ): Promise { const cache = queueManager.getCache(queueName); await cache.del(key); @@ -320,7 +320,7 @@ async function cleanupPayload( async function addJobsInChunks( queueName: string, jobs: Array<{ name: string; data: JobData; opts?: Record }>, - queueManager: QueueManager, + queueManager: Pick, chunkSize = 100 ): Promise { const queue = queueManager.getQueue(queueName); diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index dcb00c5c..449790d8 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -1,10 +1,11 @@ import { Queue as BullQueue, type Job } from 'bullmq'; +import Redis from 'ioredis'; import type { CacheProvider } from '@stock-bot/cache'; import { createCache } from '@stock-bot/cache'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; +import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { LoggerLike as Logger } from '@stock-bot/logger'; -import Redis from 'ioredis'; import { Queue, type QueueWorkerConfig } from './queue'; import { QueueRateLimiter } from './rate-limiter'; import { getFullQueueName, parseQueueName } from './service-utils'; @@ -58,7 +59,7 @@ export class QueueManager { this.handlerRegistry = handlerRegistry; this.logger = logger || getLogger('QueueManager'); this.redisConnection = getRedisConnection(config.redis); - + // Create ioredis connection for rate limiter this.ioredisConnection = new Redis({ host: config.redis.host, @@ -311,8 +312,8 @@ export class QueueManager { } this.rateLimiter = new QueueRateLimiter(this.ioredisConnection, this.logger); } - await Promise.all(rules.map(rule => this.rateLimiter!.addRule(rule))); - + await Promise.all(rules.map(rule => defined(this.rateLimiter).addRule(rule))); + this.logger.info('Added rate limit rules to QueueManager', { ruleCount: rules.length, rules, @@ -339,10 +340,10 @@ export class QueueManager { // Support both 2-parameter and 3-parameter calls let handler: string; let operation: string | undefined; - + if (operationIfThreeParams !== undefined) { // 3-parameter call: checkRateLimit(queueName, handler, operation) - handler = operationOrHandler!; + handler = defined(operationOrHandler); operation = operationIfThreeParams; } else { // 2-parameter call: checkRateLimit(handler, operation) @@ -375,7 +376,7 @@ export class QueueManager { const status = await this.rateLimiter.getStatus(handler, operation); return { queueName, - ...status + ...status, }; } @@ -478,8 +479,8 @@ export class QueueManager { try { // Add timeout to queue.close() to prevent hanging const closePromise = queue.close(); - const timeoutPromise = new Promise((_, reject) => - setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue + const timeoutPromise = new Promise( + (_, reject) => setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue ); await Promise.race([closePromise, timeoutPromise]); @@ -501,7 +502,7 @@ export class QueueManager { }); await Promise.all(cacheShutdownPromises); - + // Close ioredis connection if (this.ioredisConnection) { try { @@ -699,7 +700,7 @@ export class QueueManager { }); this.producerQueues.set(queueName, queue); } - return this.producerQueues.get(queueName)!; + return defined(this.producerQueues.get(queueName)); } /** @@ -724,7 +725,7 @@ export class QueueManager { service: ownerService, handler: handlerName, db: 0, // All queues in DB 0 - operations: metadata.operations.map((op: any) => op.name), + operations: metadata.operations.map(op => op.name), }); this.logger.trace('Discovered queue route', { diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index e2a35f9f..b10a0357 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -1,7 +1,8 @@ import { Queue as BullQueue, QueueEvents, Worker, type Job } from 'bullmq'; -import type { LoggerLike as Logger } from '@stock-bot/logger'; // Handler registry will be injected import type { HandlerRegistry } from '@stock-bot/handler-registry'; +import type { LoggerLike as Logger } from '@stock-bot/logger'; +import type { QueueManager } from './queue-manager'; import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types'; import { getRedisConnection } from './utils'; @@ -11,7 +12,7 @@ export interface QueueWorkerConfig { startWorker?: boolean; handlerRegistry?: HandlerRegistry; serviceName?: string; - queueManager?: any; // Reference to queue manager for rate limiting + queueManager?: Pick; // Reference to queue manager for rate limiting } /** @@ -27,7 +28,7 @@ export class Queue { private readonly logger: Logger; private readonly handlerRegistry?: HandlerRegistry; private serviceName?: string; - private queueManager?: any; + private queueManager?: Pick; constructor( queueName: string, @@ -274,26 +275,26 @@ export class Queue { const workerClosePromises = this.workers.map(async (worker, idx) => { try { const closePromise = worker.close(); - const timeoutPromise = new Promise((resolve) => { + const timeoutPromise = new Promise(resolve => { setTimeout(() => { - this.logger.warn('Worker close timeout, forcing closure', { - queueName: this.queueName, - workerId: idx + this.logger.warn('Worker close timeout, forcing closure', { + queueName: this.queueName, + workerId: idx, }); resolve(); }, 2000); // 2 second timeout per worker }); - + await Promise.race([closePromise, timeoutPromise]); } catch (error) { - this.logger.warn('Error closing worker', { - queueName: this.queueName, - workerId: idx, - error + this.logger.warn('Error closing worker', { + queueName: this.queueName, + workerId: idx, + error, }); } }); - + await Promise.all(workerClosePromises); this.workers = []; this.logger.debug('Workers closed', { queueName: this.queueName }); @@ -337,19 +338,23 @@ export class Queue { const connection = getRedisConnection(this.redisConfig); for (let i = 0; i < workerCount; i++) { - const worker: Worker = new Worker(this.queueName, async (job: Job) => this.processJob(job, worker), { - connection, - concurrency, - maxStalledCount: 3, - stalledInterval: 30000, - // Add a name to identify the worker - name: `${this.serviceName || 'unknown'}_worker_${i}`, - // Enable manual rate limiting - limiter: { - max: 100, - duration: 1, - }, - }); + const worker: Worker = new Worker( + this.queueName, + async (job: Job) => this.processJob(job, worker), + { + connection, + concurrency, + maxStalledCount: 3, + stalledInterval: 30000, + // Add a name to identify the worker + name: `${this.serviceName || 'unknown'}_worker_${i}`, + // Enable manual rate limiting + limiter: { + max: 100, + duration: 1, + }, + } + ); this.logger.info(`Starting worker ${i + 1}/${workerCount} for queue`, { queueName: this.queueName, @@ -414,7 +419,7 @@ export class Queue { jobName: job.name, queueName: this.queueName, hasQueueManager: !!this.queueManager, - jobData: job.data + jobData: job.data, }); const { handler, operation, payload }: JobData = job.data; @@ -436,19 +441,16 @@ export class Queue { this.logger.debug('Checking rate limits', { handler, operation, - queueManager: this.queueManager.constructor.name + queueManager: this.queueManager.constructor.name, }); - - const rateLimitCheck = await this.queueManager.checkRateLimit( - handler, - operation - ); - + + const rateLimitCheck = await this.queueManager.checkRateLimit(handler, operation); + this.logger.debug('Rate limit check result', { allowed: rateLimitCheck.allowed, retryDelayMs: rateLimitCheck.retryDelayMs, handler, - operation + operation, }); if (!rateLimitCheck.allowed) { @@ -456,7 +458,7 @@ export class Queue { id: job.id, handler, operation, - retryDelayMs: rateLimitCheck.retryDelayMs + retryDelayMs: rateLimitCheck.retryDelayMs, }); // Use BullMQ's manual rate limiting @@ -493,10 +495,13 @@ export class Queue { return result; } catch (error) { // Re-throw RateLimitError without logging as error - if (error === Worker.RateLimitError() || (error as any).name === 'RateLimitError') { + if ( + error === Worker.RateLimitError() || + (error instanceof Error ? error.name : undefined) === 'RateLimitError' + ) { throw error; } - + this.logger.error('Job processing failed', { id: job.id, handler, @@ -544,7 +549,7 @@ export class Queue { * Get active workers from BullMQ * This uses BullMQ's built-in worker tracking */ - async getActiveWorkers(): Promise { + async getActiveWorkers(): ReturnType { try { const workers = await this.bullQueue.getWorkers(); return workers; diff --git a/libs/core/queue/src/rate-limiter.ts b/libs/core/queue/src/rate-limiter.ts index 96912761..bfd1bd9a 100644 --- a/libs/core/queue/src/rate-limiter.ts +++ b/libs/core/queue/src/rate-limiter.ts @@ -1,380 +1,403 @@ -import type Redis from 'ioredis'; -import { RateLimiterRedis, type IRateLimiterRedisOptions } from 'rate-limiter-flexible'; -import type { RateLimitRule, RateLimitWindow } from './types'; - -// 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; - trace(message: string, meta?: Record): void; -} - -interface RateLimiterEntry { - windows: Array<{ - limiter: RateLimiterRedis; - window: RateLimitWindow; - }>; - cost: number; -} - -export interface RateLimitResult { - allowed: boolean; - retryDelayMs?: number; - remainingPoints?: number; - cost?: number; -} - -/** - * Enhanced rate limiter that supports: - * - Multiple time windows per rule - * - Variable costs per operation - * - Hierarchical rules (operation > handler > queue > global) - */ -export class QueueRateLimiter { - private limiters = new Map(); - private readonly logger: Logger; - - constructor( - private redisClient: Redis, - logger?: Logger - ) { - this.logger = logger || console; - this.logger.debug('QueueRateLimiter initialized', { - redisClientType: typeof this.redisClient, - redisClientKeys: this.redisClient ? Object.keys(this.redisClient).slice(0, 10) : [], - hasClient: !!this.redisClient, - isIoRedis: this.redisClient && this.redisClient.constructor.name === 'Redis' - }); - } - - /** - * Add a rate limit rule - */ - async addRule(rule: RateLimitRule): Promise { - const key = this.getRuleKey(rule); - - // Create array of limiters for each window - const windows: RateLimiterEntry['windows'] = []; - const limits = rule.config.limits || []; - - this.logger.debug('Adding rate limit rule', { - key, - rule, - windowCount: limits.length, - cost: rule.config.cost - }); - - for (const window of limits) { - const limiterOptions: IRateLimiterRedisOptions = { - storeClient: this.redisClient as any, - keyPrefix: `rate_limit:${key}:${window.duration}s`, - points: window.points, - duration: window.duration, - blockDuration: window.blockDuration || 0, - }; - - this.logger.debug('Creating RateLimiterRedis', { - keyPrefix: limiterOptions.keyPrefix, - points: limiterOptions.points, - duration: limiterOptions.duration, - hasRedisClient: !!this.redisClient, - redisClientType: typeof this.redisClient - }); - - try { - const limiter = new RateLimiterRedis(limiterOptions); - windows.push({ limiter, window }); - } catch (error) { - this.logger.error('Failed to create RateLimiterRedis', { error, limiterOptions }); - throw error; - } - } - - // Default cost: handler defines the pool (no default cost), operations default to 1 - const defaultCost = rule.level === 'operation' ? 1 : 0; - - this.limiters.set(key, { - windows, - cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost - }); - - this.logger.debug('Rate limit rule added', { - key, - level: rule.level, - handler: rule.handler, - operation: rule.operation, - windows: windows.length, - cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost - }); - } - - /** - * Check if an operation is allowed based on rate limits - */ - async checkLimit(handler: string, operation?: string): Promise { - // Build keys to check from most specific to least specific - const keysToCheck: string[] = []; - - if (operation) { - keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)); - } - keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); - keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule)); - keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule)); - - this.logger.debug('Checking rate limits', { - handler, - operation, - keysToCheck, - availableKeys: Array.from(this.limiters.keys()) - }); - - // First, find the cost from the most specific rule - let cost = 1; // Default cost - for (const key of keysToCheck) { - const entry = this.limiters.get(key); - if (entry && entry.cost !== undefined) { - cost = entry.cost; - this.logger.debug(`[RateLimiter] Using cost ${cost} from rule: ${key}`); - this.logger.debug('Using cost from rule', { - key, - cost, - handler, - operation - }); - break; - } - } - - // Then find the rate limit windows from the first matching rule that has windows - let windowEntry: RateLimiterEntry | undefined; - let appliedKey: string | undefined; - - for (const key of keysToCheck) { - const entry = this.limiters.get(key); - if (entry && entry.windows.length > 0) { - windowEntry = entry; - appliedKey = key; - break; - } - } - - if (!windowEntry) { - this.logger.debug('No rate limit rules found', { - handler, - operation - }); - return { allowed: true }; - } - - this.logger.debug(`[RateLimiter] Applying rate limit rule: ${appliedKey}`, { - appliedKey, - windowCount: windowEntry.windows.length, - cost, - handler, - operation - }); - - // Check all windows with the determined cost - let maxRetryDelayMs = 0; - - this.logger.debug('Checking rate limit windows', { - handler, - operation, - cost, - windowCount: windowEntry.windows.length - }); - - // Special handling for 0-cost operations - they should always pass - if (cost === 0) { - this.logger.debug(`[RateLimiter] Zero-cost operation ${handler}:${operation || 'N/A'} - allowing without consuming points`); - return { - allowed: true, - cost: 0 - }; - } - - for (const { limiter, window } of windowEntry.windows) { - // For handler-level rate limits, all operations share the same pool - // Use the applied key to determine the consumer key - const consumerKey = appliedKey?.startsWith('handler:') ? handler : - (operation ? `${handler}:${operation}` : handler); - - try { - // First check current state without consuming - const currentState = await limiter.get(consumerKey); - const now = Date.now(); - this.logger.debug(`[RateLimiter] Current state before consume:`, { - handler, - operation, - consumerKey, - cost, - window: `${window.points}pts/${window.duration}s`, - consumedPoints: currentState?.consumedPoints || 0, - remainingPoints: currentState?.remainingPoints ?? window.points, - msBeforeNext: currentState?.msBeforeNext || 0, - currentTime: new Date(now).toISOString(), - resetTime: currentState?.msBeforeNext ? new Date(now + currentState.msBeforeNext).toISOString() : 'N/A', - hasState: !!currentState, - stateDetails: currentState ? JSON.stringify(currentState) : 'no state' - }); - - // Try to consume points - this.logger.debug(`[RateLimiter] Attempting to consume ${cost} points for ${consumerKey}`); - const result = await limiter.consume(consumerKey, cost); - this.logger.debug(`[RateLimiter] Successfully consumed ${cost} points, ${result.remainingPoints} remaining`); - this.logger.debug('Consumed points successfully', { - handler, - operation, - consumerKey, - window: `${window.points}pts/${window.duration}s`, - cost, - remainingPoints: result.remainingPoints, - msBeforeNext: result.msBeforeNext - }); - this.logger.trace('Rate limit window passed', { - handler, - operation, - window: `${window.points}pts/${window.duration}s`, - cost - }); - } catch (rejRes: any) { - // Rate limit exceeded for this window - const retryDelayMs = rejRes.msBeforeNext || window.blockDuration || 1000; - maxRetryDelayMs = Math.max(maxRetryDelayMs, retryDelayMs); - - this.logger.debug(`[RateLimiter] RATE LIMIT HIT: ${consumerKey} - ${cost} points rejected, retry in ${retryDelayMs}ms`, { - consumedPoints: rejRes.consumedPoints || 0, - remainingPoints: rejRes.remainingPoints || 0, - totalPoints: rejRes.totalPoints || window.points, - isFirstInDuration: rejRes.isFirstInDuration || false, - msBeforeNext: rejRes.msBeforeNext || 0, - retryDelayMs - }); - this.logger.trace('Rate limit exceeded', { - handler, - operation, - consumerKey, - window: `${window.points}pts/${window.duration}s`, - cost, - remainingPoints: rejRes.remainingPoints || 0, - retryDelayMs: maxRetryDelayMs - }); - - return { - allowed: false, - retryDelayMs: maxRetryDelayMs, - remainingPoints: rejRes.remainingPoints || 0, - cost - }; - } - } - - // All windows passed - return { - allowed: true, - cost - }; - } - - /** - * Get rule key for storing rate limiter - */ - private getRuleKey(rule: RateLimitRule): string { - switch (rule.level) { - case 'global': - return 'global'; - case 'queue': - return `queue:${rule.queueName || 'default'}`; - case 'handler': - return `handler:${rule.handler}`; - case 'operation': - return `operation:${rule.handler}:${rule.operation}`; - default: - return rule.level; - } - } - - /** - * Get current rate limit status - */ - async getStatus(handler: string, operation?: string): Promise { - // Build keys to check from most specific to least specific - const keysToCheck: string[] = []; - - if (operation) { - keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)); - } - keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); - keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule)); - keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule)); - - // Find the first matching rule - let entry: RateLimiterEntry | undefined; - let appliedKey: string | undefined; - - for (const key of keysToCheck) { - entry = this.limiters.get(key); - if (entry) { - appliedKey = key; - break; - } - } - - if (!entry) { - return { - handler, - operation, - hasRule: false - }; - } - - // Get status for all windows - const consumerKey = operation ? `${handler}:${operation}` : handler; - const windows = await Promise.all( - entry.windows.map(async ({ limiter, window }) => { - const result = await limiter.get(consumerKey); - return { - points: window.points, - duration: window.duration, - remaining: result?.remainingPoints ?? window.points, - resetIn: result?.msBeforeNext ?? 0, - }; - }) - ); - - return { - handler, - operation, - hasRule: true, - appliedKey, - cost: entry.cost, - windows - }; - } - - /** - * Reset rate limits for a specific handler/operation - */ - async reset(handler: string, operation?: string): Promise { - const keysToCheck: string[] = []; - - if (operation) { - keysToCheck.push(this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule)); - } - keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); - - for (const key of keysToCheck) { - const entry = this.limiters.get(key); - if (entry) { - await Promise.all( - entry.windows.map(({ limiter }) => limiter.delete(handler)) - ); - } - } - - this.logger.debug('Rate limits reset', { handler, operation }); - } -} \ No newline at end of file +import type Redis from 'ioredis'; +import { + RateLimiterRedis, + RateLimiterRes, + type IRateLimiterRedisOptions, +} from 'rate-limiter-flexible'; +import type { RateLimitRule, RateLimitWindow } from './types'; + +// 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; + trace(message: string, meta?: Record): void; +} + +interface RateLimiterEntry { + windows: Array<{ + limiter: RateLimiterRedis; + window: RateLimitWindow; + }>; + cost: number; +} + +export interface RateLimitResult { + allowed: boolean; + retryDelayMs?: number; + remainingPoints?: number; + cost?: number; +} + +/** + * Enhanced rate limiter that supports: + * - Multiple time windows per rule + * - Variable costs per operation + * - Hierarchical rules (operation > handler > queue > global) + */ +export class QueueRateLimiter { + private limiters = new Map(); + private readonly logger: Logger; + + constructor( + private redisClient: Redis, + logger?: Logger + ) { + this.logger = logger || console; + this.logger.debug('QueueRateLimiter initialized', { + redisClientType: typeof this.redisClient, + redisClientKeys: this.redisClient ? Object.keys(this.redisClient).slice(0, 10) : [], + hasClient: !!this.redisClient, + isIoRedis: this.redisClient && this.redisClient.constructor.name === 'Redis', + }); + } + + /** + * Add a rate limit rule + */ + async addRule(rule: RateLimitRule): Promise { + const key = this.getRuleKey(rule); + + // Create array of limiters for each window + const windows: RateLimiterEntry['windows'] = []; + const limits = rule.config.limits || []; + + this.logger.debug('Adding rate limit rule', { + key, + rule, + windowCount: limits.length, + cost: rule.config.cost, + }); + + for (const window of limits) { + const limiterOptions: IRateLimiterRedisOptions = { + storeClient: this.redisClient, + keyPrefix: `rate_limit:${key}:${window.duration}s`, + points: window.points, + duration: window.duration, + blockDuration: window.blockDuration || 0, + }; + + this.logger.debug('Creating RateLimiterRedis', { + keyPrefix: limiterOptions.keyPrefix, + points: limiterOptions.points, + duration: limiterOptions.duration, + hasRedisClient: !!this.redisClient, + redisClientType: typeof this.redisClient, + }); + + try { + const limiter = new RateLimiterRedis(limiterOptions); + windows.push({ limiter, window }); + } catch (error) { + this.logger.error('Failed to create RateLimiterRedis', { error, limiterOptions }); + throw error; + } + } + + // Default cost: handler defines the pool (no default cost), operations default to 1 + const defaultCost = rule.level === 'operation' ? 1 : 0; + + this.limiters.set(key, { + windows, + cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost, + }); + + this.logger.debug('Rate limit rule added', { + key, + level: rule.level, + handler: rule.handler, + operation: rule.operation, + windows: windows.length, + cost: rule.config.cost !== undefined ? rule.config.cost : defaultCost, + }); + } + + /** + * Check if an operation is allowed based on rate limits + */ + async checkLimit(handler: string, operation?: string): Promise { + // Build keys to check from most specific to least specific + const keysToCheck: string[] = []; + + if (operation) { + keysToCheck.push( + this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule) + ); + } + keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); + keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule)); + keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule)); + + this.logger.debug('Checking rate limits', { + handler, + operation, + keysToCheck, + availableKeys: Array.from(this.limiters.keys()), + }); + + // First, find the cost from the most specific rule + let cost = 1; // Default cost + for (const key of keysToCheck) { + const entry = this.limiters.get(key); + if (entry && entry.cost !== undefined) { + cost = entry.cost; + this.logger.debug(`[RateLimiter] Using cost ${cost} from rule: ${key}`); + this.logger.debug('Using cost from rule', { + key, + cost, + handler, + operation, + }); + break; + } + } + + // Then find the rate limit windows from the first matching rule that has windows + let windowEntry: RateLimiterEntry | undefined; + let appliedKey: string | undefined; + + for (const key of keysToCheck) { + const entry = this.limiters.get(key); + if (entry && entry.windows.length > 0) { + windowEntry = entry; + appliedKey = key; + break; + } + } + + if (!windowEntry) { + this.logger.debug('No rate limit rules found', { + handler, + operation, + }); + return { allowed: true }; + } + + this.logger.debug(`[RateLimiter] Applying rate limit rule: ${appliedKey}`, { + appliedKey, + windowCount: windowEntry.windows.length, + cost, + handler, + operation, + }); + + // Check all windows with the determined cost + let maxRetryDelayMs = 0; + + this.logger.debug('Checking rate limit windows', { + handler, + operation, + cost, + windowCount: windowEntry.windows.length, + }); + + // Special handling for 0-cost operations - they should always pass + if (cost === 0) { + this.logger.debug( + `[RateLimiter] Zero-cost operation ${handler}:${operation || 'N/A'} - allowing without consuming points` + ); + return { + allowed: true, + cost: 0, + }; + } + + for (const { limiter, window } of windowEntry.windows) { + // For handler-level rate limits, all operations share the same pool + // Use the applied key to determine the consumer key + const consumerKey = appliedKey?.startsWith('handler:') + ? handler + : operation + ? `${handler}:${operation}` + : handler; + + try { + // First check current state without consuming + const currentState = await limiter.get(consumerKey); + const now = Date.now(); + this.logger.debug(`[RateLimiter] Current state before consume:`, { + handler, + operation, + consumerKey, + cost, + window: `${window.points}pts/${window.duration}s`, + consumedPoints: currentState?.consumedPoints || 0, + remainingPoints: currentState?.remainingPoints ?? window.points, + msBeforeNext: currentState?.msBeforeNext || 0, + currentTime: new Date(now).toISOString(), + resetTime: currentState?.msBeforeNext + ? new Date(now + currentState.msBeforeNext).toISOString() + : 'N/A', + hasState: !!currentState, + stateDetails: currentState ? JSON.stringify(currentState) : 'no state', + }); + + // Try to consume points + this.logger.debug(`[RateLimiter] Attempting to consume ${cost} points for ${consumerKey}`); + const result = await limiter.consume(consumerKey, cost); + this.logger.debug( + `[RateLimiter] Successfully consumed ${cost} points, ${result.remainingPoints} remaining` + ); + this.logger.debug('Consumed points successfully', { + handler, + operation, + consumerKey, + window: `${window.points}pts/${window.duration}s`, + cost, + remainingPoints: result.remainingPoints, + msBeforeNext: result.msBeforeNext, + }); + this.logger.trace('Rate limit window passed', { + handler, + operation, + window: `${window.points}pts/${window.duration}s`, + cost, + }); + } catch (rejRes) { + if (!(rejRes instanceof RateLimiterRes)) { + throw rejRes; + } + // Rate limit exceeded for this window + const retryDelayMs = rejRes.msBeforeNext || window.blockDuration || 1000; + maxRetryDelayMs = Math.max(maxRetryDelayMs, retryDelayMs); + + this.logger.debug( + `[RateLimiter] RATE LIMIT HIT: ${consumerKey} - ${cost} points rejected, retry in ${retryDelayMs}ms`, + { + consumedPoints: rejRes.consumedPoints || 0, + remainingPoints: rejRes.remainingPoints || 0, + totalPoints: window.points, + isFirstInDuration: rejRes.isFirstInDuration || false, + msBeforeNext: rejRes.msBeforeNext || 0, + retryDelayMs, + } + ); + this.logger.trace('Rate limit exceeded', { + handler, + operation, + consumerKey, + window: `${window.points}pts/${window.duration}s`, + cost, + remainingPoints: rejRes.remainingPoints || 0, + retryDelayMs: maxRetryDelayMs, + }); + + return { + allowed: false, + retryDelayMs: maxRetryDelayMs, + remainingPoints: rejRes.remainingPoints || 0, + cost, + }; + } + } + + // All windows passed + return { + allowed: true, + cost, + }; + } + + /** + * Get rule key for storing rate limiter + */ + private getRuleKey(rule: RateLimitRule): string { + switch (rule.level) { + case 'global': + return 'global'; + case 'queue': + return `queue:${rule.queueName || 'default'}`; + case 'handler': + return `handler:${rule.handler}`; + case 'operation': + return `operation:${rule.handler}:${rule.operation}`; + default: + return rule.level; + } + } + + /** + * Get current rate limit status + */ + async getStatus(handler: string, operation?: string) { + // Build keys to check from most specific to least specific + const keysToCheck: string[] = []; + + if (operation) { + keysToCheck.push( + this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule) + ); + } + keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); + keysToCheck.push(this.getRuleKey({ level: 'queue', config: {} } as RateLimitRule)); + keysToCheck.push(this.getRuleKey({ level: 'global', config: {} } as RateLimitRule)); + + // Find the first matching rule + let entry: RateLimiterEntry | undefined; + let appliedKey: string | undefined; + + for (const key of keysToCheck) { + entry = this.limiters.get(key); + if (entry) { + appliedKey = key; + break; + } + } + + if (!entry) { + return { + handler, + operation, + hasRule: false, + }; + } + + // Get status for all windows + const consumerKey = operation ? `${handler}:${operation}` : handler; + const windows = await Promise.all( + entry.windows.map(async ({ limiter, window }) => { + const result = await limiter.get(consumerKey); + return { + points: window.points, + duration: window.duration, + remaining: result?.remainingPoints ?? window.points, + resetIn: result?.msBeforeNext ?? 0, + }; + }) + ); + + return { + handler, + operation, + hasRule: true, + appliedKey, + cost: entry.cost, + windows, + }; + } + + /** + * Reset rate limits for a specific handler/operation + */ + async reset(handler: string, operation?: string): Promise { + const keysToCheck: string[] = []; + + if (operation) { + keysToCheck.push( + this.getRuleKey({ level: 'operation', handler, operation, config: {} } as RateLimitRule) + ); + } + keysToCheck.push(this.getRuleKey({ level: 'handler', handler, config: {} } as RateLimitRule)); + + for (const key of keysToCheck) { + const entry = this.limiters.get(key); + if (entry) { + await Promise.all(entry.windows.map(({ limiter }) => limiter.delete(handler))); + } + } + + this.logger.debug('Rate limits reset', { handler, operation }); + } +} diff --git a/libs/core/queue/src/service-cache.ts b/libs/core/queue/src/service-cache.ts index 980ef454..11c0726a 100644 --- a/libs/core/queue/src/service-cache.ts +++ b/libs/core/queue/src/service-cache.ts @@ -1,4 +1,5 @@ import { createCache, type CacheProvider, type CacheStats } from '@stock-bot/cache'; +import type { LoggerLike } from '@stock-bot/logger'; import { generateCachePrefix } from './service-utils'; import type { RedisConfig } from './types'; @@ -14,7 +15,7 @@ export class ServiceCache implements CacheProvider { serviceName: string, redisConfig: RedisConfig, isGlobalCache: boolean = false, - logger?: any + logger?: LoggerLike ) { // Determine Redis DB and prefix let db: number; @@ -45,11 +46,11 @@ export class ServiceCache implements CacheProvider { } // Implement CacheProvider interface - async get(key: string): Promise { + async get(key: string): Promise { return this.cache.get(key); } - async set( + async set( key: string, value: T, options?: @@ -98,7 +99,7 @@ export class ServiceCache implements CacheProvider { } // Enhanced cache methods (delegate to underlying cache if available) - async update(key: string, value: T): Promise { + async update(key: string, value: T): Promise { if (this.cache.update) { return this.cache.update(key, value); } @@ -106,7 +107,7 @@ export class ServiceCache implements CacheProvider { return this.cache.set(key, value, { preserveTTL: true }); } - async setIfExists(key: string, value: T, ttl?: number): Promise { + async setIfExists(key: string, value: T, ttl?: number): Promise { if (this.cache.setIfExists) { return this.cache.setIfExists(key, value, ttl); } @@ -115,7 +116,7 @@ export class ServiceCache implements CacheProvider { return result !== null; } - async setIfNotExists(key: string, value: T, ttl?: number): Promise { + async setIfNotExists(key: string, value: T, ttl?: number): Promise { if (this.cache.setIfNotExists) { return this.cache.setIfNotExists(key, value, ttl); } @@ -124,7 +125,7 @@ export class ServiceCache implements CacheProvider { return result !== null; } - async replace(key: string, value: T, ttl?: number): Promise { + async replace(key: string, value: T, ttl?: number): Promise { if (this.cache.replace) { return this.cache.replace(key, value, ttl); } @@ -132,7 +133,7 @@ export class ServiceCache implements CacheProvider { return this.cache.set(key, value, ttl); } - async updateField( + async updateField( key: string, updater: (current: T | null) => T, ttl?: number @@ -172,7 +173,7 @@ export class ServiceCache implements CacheProvider { export function createServiceCache( serviceName: string, redisConfig: RedisConfig, - options: { global?: boolean; logger?: any } = {} + options: { global?: boolean; logger?: LoggerLike } = {} ): ServiceCache { return new ServiceCache(serviceName, redisConfig, options.global, options.logger); } diff --git a/libs/core/queue/src/types.ts b/libs/core/queue/src/types.ts index 9abdbdd4..9960e2db 100644 --- a/libs/core/queue/src/types.ts +++ b/libs/core/queue/src/types.ts @@ -1,3 +1,4 @@ +import type { HandlerRegistry } from '@stock-bot/handler-registry'; // Import types we need to extend import type { JobOptions, QueueStats } from '@stock-bot/types'; @@ -61,7 +62,7 @@ export interface QueueOptions { concurrency?: number; enableMetrics?: boolean; enableDLQ?: boolean; - handlerRegistry?: any; // HandlerRegistry from @stock-bot/handler-registry + handlerRegistry?: HandlerRegistry; // HandlerRegistry from @stock-bot/handler-registry } export interface QueueManagerConfig { @@ -104,16 +105,9 @@ export interface HandlerInitializer { } // Rate limiting types -export interface RateLimitWindow { - points: number; - duration: number; - blockDuration?: number; -} +export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow; -export interface RateLimitConfig { - limits?: RateLimitWindow[]; - cost?: number; -} +export type RateLimitConfig = import('@stock-bot/types').HandlerRateLimitConfig; export interface RateLimitRule { level: 'global' | 'queue' | 'handler' | 'operation'; @@ -154,7 +148,7 @@ export interface SmartQueueConfig extends QueueManagerConfig { /** Whether to auto-discover handlers from registry */ autoDiscoverHandlers?: boolean; /** Custom service registry (defaults to built-in) */ - serviceRegistry?: Record; + serviceRegistry?: Record; } export interface QueueRoute { diff --git a/libs/core/queue/test/batch-processor.test.ts b/libs/core/queue/test/batch-processor.test.ts index fb1e9b09..bd69086b 100644 --- a/libs/core/queue/test/batch-processor.test.ts +++ b/libs/core/queue/test/batch-processor.test.ts @@ -1,7 +1,6 @@ import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test'; -import type { Logger } from '@stock-bot/logger'; import { processBatchJob, processItems } from '../src/batch-processor'; -import type { BatchJobData, ProcessOptions, Queue, QueueManager } from '../src/types'; +import type { BatchJobData, ProcessOptions, QueueManager } from '../src/types'; describe('Batch Processor', () => { type MockLogger = { @@ -122,7 +121,7 @@ describe('Batch Processor', () => { }); // processBatchJob should still complete even if addBulk fails - const result = await processBatchJob( + const _result = await processBatchJob( batchData, 'test-queue', mockQueueManager as unknown as QueueManager diff --git a/libs/core/queue/test/queue-class.test.ts b/libs/core/queue/test/queue-class.test.ts index c06513b3..a8d1cd3a 100644 --- a/libs/core/queue/test/queue-class.test.ts +++ b/libs/core/queue/test/queue-class.test.ts @@ -1,6 +1,6 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { describe, expect, it, mock } from 'bun:test'; import { Queue } from '../src/queue'; -import type { JobData, QueueWorkerConfig, RedisConfig } from '../src/types'; +import type { QueueWorkerConfig, RedisConfig } from '../src/types'; describe('Queue Class', () => { const mockRedisConfig: RedisConfig = { diff --git a/libs/core/queue/test/queue-manager.test.ts b/libs/core/queue/test/queue-manager.test.ts index f63ef5c6..3dc6bb8e 100644 --- a/libs/core/queue/test/queue-manager.test.ts +++ b/libs/core/queue/test/queue-manager.test.ts @@ -210,7 +210,7 @@ describe.skip('QueueManager', () => { mockLogger ); - const queue = manager.createQueue('test-queue'); + const _queue = manager.createQueue('test-queue'); const stats = await manager.getQueueStats('test-queue'); expect(stats).toBeDefined(); diff --git a/libs/core/queue/test/queue.test.ts b/libs/core/queue/test/queue.test.ts index c9537b95..bd9d6f77 100644 --- a/libs/core/queue/test/queue.test.ts +++ b/libs/core/queue/test/queue.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import { describe, expect, it } from 'bun:test'; import { createServiceCache, ServiceCache } from '../src/service-cache'; import { generateCachePrefix, diff --git a/libs/core/queue/tsconfig.json b/libs/core/queue/tsconfig.json index d9e93a7a..b1b55db2 100644 --- a/libs/core/queue/tsconfig.json +++ b/libs/core/queue/tsconfig.json @@ -7,9 +7,20 @@ }, "include": ["src/**/*"], "references": [ - { "path": "../cache" }, - { "path": "../handler-registry" }, - { "path": "../logger" }, - { "path": "../types" } + { + "path": "../cache" + }, + { + "path": "../handler-registry" + }, + { + "path": "../logger" + }, + { + "path": "../types" + }, + { + "path": "../../../libs/core/invariants" + } ] } diff --git a/libs/core/services/src/index.ts b/libs/core/services/src/index.ts index 953fd227..81650072 100644 --- a/libs/core/services/src/index.ts +++ b/libs/core/services/src/index.ts @@ -40,5 +40,18 @@ export interface ServiceTypes { } export interface IServiceContainer extends ServiceTypes { - readonly custom?: Record; + readonly custom?: Record; +} + +/** Validate required capabilities at the boundary before starting any work. */ +export function requireServices( + services: T, + ...keys: K[] +): T & { [P in K]-?: NonNullable } { + for (const key of keys) { + if (services[key] === null || services[key] === undefined) { + throw new Error(`Required service '${key}' is unavailable`); + } + } + return services as T & { [P in K]-?: NonNullable }; } diff --git a/libs/core/shutdown/src/shutdown.ts b/libs/core/shutdown/src/shutdown.ts index 66ce1e96..fbf8c6d9 100644 --- a/libs/core/shutdown/src/shutdown.ts +++ b/libs/core/shutdown/src/shutdown.ts @@ -40,7 +40,7 @@ export class Shutdown { return { isShuttingDown: this.isShuttingDown, signal: this.triggerSignal, - callbackCount: this.callbacks.length + callbackCount: this.callbacks.length, }; } @@ -64,9 +64,9 @@ export class Shutdown { async shutdown(signal?: string): Promise { // If already shutting down, return the existing promise if (this.shutdownPromise) { - this.logger.warn('Shutdown already in progress, ignoring additional request', { + this.logger.warn('Shutdown already in progress, ignoring additional request', { originalSignal: this.triggerSignal, - newSignal: signal + newSignal: signal, }); return this.shutdownPromise; } @@ -77,16 +77,16 @@ export class Shutdown { this.isShuttingDown = true; this.triggerSignal = signal || 'manual'; - - this.logger.info('Starting graceful shutdown', { + + this.logger.info('Starting graceful shutdown', { signal: this.triggerSignal, timeout: this.shutdownTimeout, - callbackCount: this.callbacks.length + callbackCount: this.callbacks.length, }); // Create and store the shutdown promise this.shutdownPromise = this.performShutdown(); - + try { await this.shutdownPromise; this.logger.info('Graceful shutdown completed successfully'); @@ -97,23 +97,23 @@ export class Shutdown { } private async performShutdown(): Promise { - const timeout = new Promise((_, reject) => - setTimeout(() => reject(new Error('Shutdown timeout')), this.shutdownTimeout) - ); - + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Shutdown timeout')), this.shutdownTimeout); + }); try { await Promise.race([this.executeCallbacks(), timeout]); - } catch (error) { - throw error; + } finally { + clearTimeout(timer); } } private async executeCallbacks(): Promise { const sorted = [...this.callbacks].sort((a, b) => a.priority - b.priority); - - this.logger.debug('Executing shutdown callbacks', { + + this.logger.debug('Executing shutdown callbacks', { count: sorted.length, - callbacks: sorted.map(c => ({ name: c.name || 'unnamed', priority: c.priority })) + callbacks: sorted.map(c => ({ name: c.name || 'unnamed', priority: c.priority })), }); let completed = 0; @@ -124,9 +124,9 @@ export class Shutdown { try { this.logger.debug(`Starting shutdown callback: ${callbackName}`, { priority }); const startTime = Date.now(); - + await callback(); - + const duration = Date.now() - startTime; completed++; this.logger.debug(`Completed shutdown callback: ${callbackName}`, { duration, priority }); @@ -136,10 +136,10 @@ export class Shutdown { } } - this.logger.info('Shutdown callbacks execution completed', { + this.logger.info('Shutdown callbacks execution completed', { total: sorted.length, completed, - failed + failed, }); } @@ -155,7 +155,7 @@ export class Shutdown { // Use process.on instead of process.once to handle multiple signals process.on(signal, async () => { this.logger.info(`Received ${signal} signal`); - + // If already shutting down, ignore the signal if (this.isShuttingDown || this.shutdownPromise) { this.logger.info(`Already shutting down, ignoring ${signal}`); @@ -164,22 +164,22 @@ export class Shutdown { try { await this.shutdown(signal); - + // Add small delay to ensure logs are flushed await new Promise(resolve => setTimeout(resolve, 100)); - + this.logger.info('Exiting process with code 0'); process.exit(0); } catch (error) { this.logger.error('Shutdown error, exiting with code 1', { error }); - + // Add small delay to ensure error logs are flushed await new Promise(resolve => setTimeout(resolve, 100)); - + process.exit(1); } }); - + this.logger.debug(`Registered handler for ${signal}`); }); diff --git a/libs/core/shutdown/test/shutdown-comprehensive.test.ts b/libs/core/shutdown/test/shutdown-comprehensive.test.ts index e587b54d..e0d434f7 100644 --- a/libs/core/shutdown/test/shutdown-comprehensive.test.ts +++ b/libs/core/shutdown/test/shutdown-comprehensive.test.ts @@ -1,10 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; -import { - onShutdown, - Shutdown, - SHUTDOWN_DEFAULTS, -} from '../src'; -import type { ShutdownOptions } from '../src/types'; +import { onShutdown, Shutdown } from '../src'; describe('Shutdown Comprehensive Tests', () => { let shutdownInstance: Shutdown; @@ -15,7 +10,7 @@ describe('Shutdown Comprehensive Tests', () => { // Create a fresh instance for each test shutdownInstance = new Shutdown({ autoRegister: false }); }); - + afterEach(() => { // Clean up singleton (Shutdown as any).instance = null; @@ -24,9 +19,9 @@ describe('Shutdown Comprehensive Tests', () => { describe('Basic Functionality', () => { it('should register callbacks', () => { const callback = mock(async () => {}); - + shutdownInstance.onShutdown(callback, 50, 'test-callback'); - + // We can't directly check callback count, but we can verify it executes expect(callback).toBeDefined(); }); @@ -34,19 +29,19 @@ describe('Shutdown Comprehensive Tests', () => { it('should execute callbacks on shutdown', async () => { const callback1 = mock(async () => {}); const callback2 = mock(async () => {}); - + shutdownInstance.onShutdown(callback1, 10, 'callback-1'); shutdownInstance.onShutdown(callback2, 20, 'callback-2'); - + await shutdownInstance.shutdown(); - + expect(callback1).toHaveBeenCalledTimes(1); expect(callback2).toHaveBeenCalledTimes(1); }); it('should execute callbacks in priority order', async () => { const order: string[] = []; - + const highPriority = mock(async () => { order.push('high'); }); @@ -56,14 +51,14 @@ describe('Shutdown Comprehensive Tests', () => { const lowPriority = mock(async () => { order.push('low'); }); - + // Lower number = higher priority shutdownInstance.onShutdown(lowPriority, 30, 'low'); shutdownInstance.onShutdown(highPriority, 10, 'high'); shutdownInstance.onShutdown(mediumPriority, 20, 'medium'); - + await shutdownInstance.shutdown(); - + expect(order).toEqual(['high', 'medium', 'low']); }); @@ -72,13 +67,13 @@ describe('Shutdown Comprehensive Tests', () => { const errorCallback = mock(async () => { throw new Error('Callback error'); }); - + shutdownInstance.onShutdown(successCallback, 10, 'success'); shutdownInstance.onShutdown(errorCallback, 20, 'error'); - + // Should not throw even if callbacks fail await expect(shutdownInstance.shutdown()).resolves.toBeUndefined(); - + expect(successCallback).toHaveBeenCalledTimes(1); expect(errorCallback).toHaveBeenCalledTimes(1); }); @@ -86,11 +81,11 @@ describe('Shutdown Comprehensive Tests', () => { it('should only shutdown once', async () => { const callback = mock(async () => {}); shutdownInstance.onShutdown(callback); - + await shutdownInstance.shutdown(); await shutdownInstance.shutdown(); await shutdownInstance.shutdown(); - + expect(callback).toHaveBeenCalledTimes(1); }); @@ -101,47 +96,47 @@ describe('Shutdown Comprehensive Tests', () => { throw new Error('Should not execute'); }); }); - + shutdownInstance.onShutdown(firstCallback); - + await shutdownInstance.shutdown(); - + expect(firstCallback).toHaveBeenCalledTimes(1); }); }); describe('Timeout Handling', () => { it('should timeout if callbacks take too long', async () => { - const slowShutdown = new Shutdown({ + const slowShutdown = new Shutdown({ timeout: 100, - autoRegister: false + autoRegister: false, }); - + const slowCallback = mock(async () => { await new Promise(resolve => setTimeout(resolve, 200)); }); - + slowShutdown.onShutdown(slowCallback, 10, 'slow'); - + const startTime = Date.now(); await expect(slowShutdown.shutdown()).rejects.toThrow('Shutdown timeout'); const duration = Date.now() - startTime; - + expect(duration).toBeLessThan(150); }); it('should complete if callbacks finish before timeout', async () => { - const quickShutdown = new Shutdown({ + const quickShutdown = new Shutdown({ timeout: 1000, - autoRegister: false + autoRegister: false, }); - + const quickCallback = mock(async () => { await new Promise(resolve => setTimeout(resolve, 10)); }); - + quickShutdown.onShutdown(quickCallback); - + await expect(quickShutdown.shutdown()).resolves.toBeUndefined(); expect(quickCallback).toHaveBeenCalledTimes(1); }); @@ -151,19 +146,19 @@ describe('Shutdown Comprehensive Tests', () => { it('should return same instance via getInstance', () => { const instance1 = Shutdown.getInstance(); const instance2 = Shutdown.getInstance(); - + expect(instance1).toBe(instance2); }); it('should maintain state across getInstance calls', async () => { const instance = Shutdown.getInstance(); const callback = mock(async () => {}); - + instance.onShutdown(callback); - + const sameInstance = Shutdown.getInstance(); await sameInstance.shutdown(); - + expect(callback).toHaveBeenCalledTimes(1); }); }); @@ -171,29 +166,29 @@ describe('Shutdown Comprehensive Tests', () => { describe('Global onShutdown Function', () => { it('should use singleton instance', async () => { const callback = mock(async () => {}); - + // Use global function onShutdown(callback, 50, 'global-callback'); - + // Get instance and shutdown const instance = Shutdown.getInstance(); await instance.shutdown(); - + expect(callback).toHaveBeenCalledTimes(1); }); it('should handle different parameter orders', () => { const callback = mock(async () => {}); - + // Test with all parameters onShutdown(callback, 10, 'with-all-params'); - + // Test with default priority onShutdown(callback); - + // Test with priority but no name onShutdown(callback, 20); - + expect(callback).toBeDefined(); }); }); @@ -203,11 +198,11 @@ describe('Shutdown Comprehensive Tests', () => { const syncCallback = mock(() => { // Synchronous callback }); - + shutdownInstance.onShutdown(syncCallback as any, 10, 'sync'); - + await shutdownInstance.shutdown(); - + expect(syncCallback).toHaveBeenCalledTimes(1); }); @@ -215,9 +210,9 @@ describe('Shutdown Comprehensive Tests', () => { const throwingCallback = mock(async () => { throw 'string error'; }); - + shutdownInstance.onShutdown(throwingCallback); - + // Should not throw await expect(shutdownInstance.shutdown()).resolves.toBeUndefined(); expect(throwingCallback).toHaveBeenCalledTimes(1); @@ -229,16 +224,14 @@ describe('Shutdown Comprehensive Tests', () => { }); it('should handle many callbacks', async () => { - const callbacks = Array.from({ length: 50 }, (_, i) => - mock(async () => {}) - ); - + const callbacks = Array.from({ length: 50 }, (_, _i) => mock(async () => {})); + callbacks.forEach((cb, i) => { shutdownInstance.onShutdown(cb, i, `callback-${i}`); }); - + await shutdownInstance.shutdown(); - + callbacks.forEach(cb => { expect(cb).toHaveBeenCalledTimes(1); }); @@ -248,19 +241,19 @@ describe('Shutdown Comprehensive Tests', () => { describe('Default Values', () => { it('should use default priority', async () => { const callback = mock(async () => {}); - + // No priority specified shutdownInstance.onShutdown(callback); - + await shutdownInstance.shutdown(); expect(callback).toHaveBeenCalledTimes(1); }); it('should use default timeout', () => { - const defaultShutdown = new Shutdown(); - + const _defaultShutdown = new Shutdown(); + // Can't directly test timeout value, but we can verify it doesn't throw expect(() => new Shutdown()).not.toThrow(); }); }); -}); \ No newline at end of file +}); diff --git a/libs/core/shutdown/test/shutdown-signals.test.ts b/libs/core/shutdown/test/shutdown-signals.test.ts index e5326a7c..709b44a9 100644 --- a/libs/core/shutdown/test/shutdown-signals.test.ts +++ b/libs/core/shutdown/test/shutdown-signals.test.ts @@ -24,7 +24,7 @@ describe('Shutdown Signal Handlers', () => { process.once = processOnceSpy as any; // Mock process.exit - processExitSpy = mock((code?: number) => { + processExitSpy = mock((_code?: number) => { // Just record the call, don't actually exit return undefined as never; }); @@ -79,7 +79,7 @@ describe('Shutdown Signal Handlers', () => { const listeners = (global as any).__testListeners; const sigtermHandler = listeners['SIGTERM']?.[0]; - + expect(sigtermHandler).toBeDefined(); // Mock the shutdown method to track it was called @@ -101,7 +101,7 @@ describe('Shutdown Signal Handlers', () => { const listeners = (global as any).__testListeners; const sigintHandler = listeners['SIGINT']?.[0]; - + expect(sigintHandler).toBeDefined(); // Mock the shutdown method @@ -162,17 +162,17 @@ describe('Shutdown Signal Handlers', () => { const instance2 = Shutdown.getInstance(); expect(instance1).toBe(instance2); - + // Only one set of signal handlers should be registered expect(processOnceSpy).toHaveBeenCalledTimes(2); // SIGTERM and SIGINT }); it('should handle callbacks registered before signal', async () => { shutdown = new Shutdown({ autoRegister: true }); - + const callback1 = mock(async () => {}); const callback2 = mock(async () => {}); - + shutdown.onShutdown(callback1, 10); shutdown.onShutdown(callback2, 20); @@ -200,7 +200,7 @@ describe('Shutdown Signal Handlers', () => { shutdown = new Shutdown({ autoRegister: true }); const listeners = (global as any).__testListeners; - + // Verify handlers exist expect(listeners['SIGTERM']).toBeDefined(); expect(listeners['SIGINT']).toBeDefined(); @@ -216,4 +216,4 @@ describe('Shutdown Signal Handlers', () => { expect(processOnceSpy).toHaveBeenCalled(); }); }); -}); \ No newline at end of file +}); diff --git a/libs/core/types/src/decorators.ts b/libs/core/types/src/decorators.ts index d73db353..76bac395 100644 --- a/libs/core/types/src/decorators.ts +++ b/libs/core/types/src/decorators.ts @@ -29,13 +29,61 @@ export interface DecoratorMetadata { /** * Type for decorator factories */ -export type DecoratorFactory = (target: T, context?: any) => T | void; +export type DecoratorFactory = (target: T, context?: unknown) => T | void; /** * Type for method decorators */ export type MethodDecoratorFactory = ( - target: any, + target: object, propertyKey: string, descriptor?: PropertyDescriptor -) => any; +) => void | PropertyDescriptor; + +/** Metadata shared by decorators, discovery, and handler dispatch. */ +export interface RateLimitWindow { + points: number; + duration: number; + blockDuration?: number; +} +export interface HandlerRateLimitConfig { + limits?: RateLimitWindow[]; + cost?: number; +} +export interface HandlerOperationDefinition { + name: string; + method: string; + batch?: import('./handlers').ScheduledJob['batch']; +} +export interface HandlerScheduleDefinition { + operation: string; + cronPattern: string; + priority?: number; + immediately?: boolean; + description?: string; + payload?: unknown; + batch?: import('./handlers').ScheduledJob['batch']; +} +export interface DecoratedHandlerMetadata { + __handlerName?: string; + __description?: string; + __needsAutoRegistration?: boolean; + __operations?: HandlerOperationDefinition[]; + __schedules?: HandlerScheduleDefinition[]; + __disabled?: boolean; + __disabledOperations?: string[]; + __handlerRateLimit?: HandlerRateLimitConfig; + __rateLimits?: Record; +} +export type DecoratedHandlerClass = Function & DecoratedHandlerMetadata; +export interface MemberMetadataDecorator { + (target: object, propertyKey: string | symbol): void; + ( + target: object, + propertyKey: string | symbol, + descriptor: PropertyDescriptor | undefined + ): PropertyDescriptor | void; +} +export interface ClassMemberMetadataDecorator extends MemberMetadataDecorator { + (target: T): T; +} diff --git a/libs/core/types/src/index.ts b/libs/core/types/src/index.ts index 0cd7e5bf..bbf6f65e 100644 --- a/libs/core/types/src/index.ts +++ b/libs/core/types/src/index.ts @@ -71,3 +71,14 @@ export type { // Export queue types export type { JobData, JobOptions, QueueStats, BatchJobData, QueueWorkerConfig } from './queue'; + +export type { + DecoratedHandlerClass, + DecoratedHandlerMetadata, + HandlerOperationDefinition, + HandlerScheduleDefinition, + HandlerRateLimitConfig, + RateLimitWindow, + MemberMetadataDecorator, + ClassMemberMetadataDecorator, +} from './decorators'; diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index 88fa2233..235d2e42 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -1,6 +1,20 @@ -import type { Logger } from '@stock-bot/logger'; -import type { Document, OptionalUnlessRequiredId } from 'mongodb'; +import type { + AggregateOptions, + BulkWriteOptions, + CountDocumentsOptions, + CreateCollectionOptions, + CreateIndexesOptions, + DeleteOptions, + Document, + DropIndexesOptions, + Filter, + FindOptions, + IndexSpecification, + OptionalUnlessRequiredId, + UpdateOptions, +} from 'mongodb'; import { Collection, Db, MongoClient } from 'mongodb'; +import type { Logger } from '@stock-bot/logger'; import type { ConnectionEvents, DocumentBase, @@ -312,15 +326,18 @@ export class MongoDBClient { } } - 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, - }); + 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 }; } @@ -366,22 +383,25 @@ export class MongoDBClient { /** * Insert multiple documents */ - async insertMany( + async insertMany( collectionName: string, documents: T[], - options?: any, + options?: BulkWriteOptions, dbName?: string - ): Promise { + ) { const collection = this.getCollection(collectionName, dbName); const now = new Date(); const docsWithTimestamps = documents.map(doc => ({ ...doc, - created_at: (doc as any).created_at || now, + created_at: doc.created_at || now, updated_at: now, })); - const result = await collection.insertMany(docsWithTimestamps as any, options); + const result = await collection.insertMany( + docsWithTimestamps as OptionalUnlessRequiredId[], + options + ); return { insertedCount: result.insertedCount, insertedIds: result.insertedIds, @@ -391,13 +411,13 @@ export class MongoDBClient { /** * Find multiple documents */ - async find( + async find( collectionName: string, - filter: any = {}, - options?: any, + filter: Filter = {}, + options?: FindOptions, dbName?: string ): Promise { - const collection = this.getCollection(collectionName, dbName); + const collection = this.getCollection(collectionName, dbName); const cursor = collection.find(filter, options); return (await cursor.toArray()) as T[]; } @@ -405,13 +425,13 @@ export class MongoDBClient { /** * Find a single document */ - async findOne( + async findOne( collectionName: string, - filter: any, - options?: any, + filter: Filter, + options?: FindOptions, dbName?: string ): Promise { - const collection = this.getCollection(collectionName, dbName); + const collection = this.getCollection(collectionName, dbName); const result = await collection.findOne(filter, options); return result as T | null; } @@ -421,11 +441,11 @@ export class MongoDBClient { */ async updateOne( collectionName: string, - filter: any, - update: any, - options?: any, + filter: Filter, + update: Document, + options?: UpdateOptions, dbName?: string - ): Promise { + ) { const collection = this.getCollection(collectionName, dbName); // Add updated_at timestamp @@ -449,11 +469,11 @@ export class MongoDBClient { */ async updateMany( collectionName: string, - filter: any, - update: any, - options?: any, + filter: Filter, + update: Document, + options?: UpdateOptions, dbName?: string - ): Promise { + ) { const collection = this.getCollection(collectionName, dbName); // Add updated_at timestamp @@ -477,10 +497,10 @@ export class MongoDBClient { */ async deleteOne( collectionName: string, - filter: any, - options?: any, + filter: Filter, + options?: DeleteOptions, dbName?: string - ): Promise { + ) { const collection = this.getCollection(collectionName, dbName); const result = await collection.deleteOne(filter, options); return { @@ -493,10 +513,10 @@ export class MongoDBClient { */ async deleteMany( collectionName: string, - filter: any, - options?: any, + filter: Filter, + options?: DeleteOptions, dbName?: string - ): Promise { + ) { const collection = this.getCollection(collectionName, dbName); const result = await collection.deleteMany(filter, options); return { @@ -509,8 +529,8 @@ export class MongoDBClient { */ async countDocuments( collectionName: string, - filter: any = {}, - options?: any, + filter: Filter = {}, + options?: CountDocumentsOptions, dbName?: string ): Promise { const collection = this.getCollection(collectionName, dbName); @@ -520,10 +540,10 @@ export class MongoDBClient { /** * Perform aggregation operations */ - async aggregate( + async aggregate( collectionName: string, - pipeline: any[], - options?: any, + pipeline: Document[], + options?: AggregateOptions, dbName?: string ): Promise { const collection = this.getCollection(collectionName, dbName); @@ -536,8 +556,8 @@ export class MongoDBClient { */ async createIndex( collectionName: string, - indexSpec: any, - options?: any, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions, dbName?: string ): Promise { const collection = this.getCollection(collectionName, dbName); @@ -550,7 +570,7 @@ export class MongoDBClient { async dropIndex( collectionName: string, indexName: string, - options?: any, + options?: DropIndexesOptions, dbName?: string ): Promise { const collection = this.getCollection(collectionName, dbName); @@ -560,7 +580,7 @@ export class MongoDBClient { /** * List all indexes on a collection */ - async listIndexes(collectionName: string, dbName?: string): Promise { + async listIndexes(collectionName: string, dbName?: string): Promise { const collection = this.getCollection(collectionName, dbName); const cursor = collection.listIndexes(); return await cursor.toArray(); @@ -576,7 +596,11 @@ export class MongoDBClient { /** * Create a new collection */ - async createCollection(collectionName: string, options?: any, dbName?: string): Promise { + async createCollection( + collectionName: string, + options?: CreateCollectionOptions, + dbName?: string + ): Promise { const db = this.getDatabase(dbName); await db.createCollection(collectionName, options); } @@ -592,7 +616,7 @@ export class MongoDBClient { /** * List all collections in a database */ - async listCollections(filter: any = {}, dbName?: string): Promise { + async listCollections(filter: Filter = {}, dbName?: string): Promise { const db = this.getDatabase(dbName); const collections = await db.listCollections(filter).toArray(); return collections; diff --git a/libs/data/mongodb/test/mongodb.test.ts b/libs/data/mongodb/test/mongodb.test.ts index b9810683..341da5b2 100644 --- a/libs/data/mongodb/test/mongodb.test.ts +++ b/libs/data/mongodb/test/mongodb.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it } from 'bun:test'; -import { SimpleMongoDBClient } from '../src/simple-mongodb'; +import { SimpleMongoDBClient } from './support/simple-mongodb'; describe('MongoDBClient', () => { let client: SimpleMongoDBClient; diff --git a/libs/data/mongodb/src/simple-mongodb.ts b/libs/data/mongodb/test/support/simple-mongodb.ts similarity index 96% rename from libs/data/mongodb/src/simple-mongodb.ts rename to libs/data/mongodb/test/support/simple-mongodb.ts index 27051bce..c78430fa 100644 --- a/libs/data/mongodb/src/simple-mongodb.ts +++ b/libs/data/mongodb/test/support/simple-mongodb.ts @@ -1,5 +1,5 @@ /** - * Simple MongoDB client implementation for testing + * Test-only in-memory MongoDB double. Never used by production adapters. */ export class SimpleMongoDBClient { private collections = new Map(); @@ -144,7 +144,7 @@ export class SimpleMongoDBClient { return docs.length; } - async createIndex(collection: string, index: any, options?: any): Promise { + async createIndex(_collection: string, _index: any, _options?: any): Promise { // No-op for simple implementation } diff --git a/libs/data/postgres/package.json b/libs/data/postgres/package.json index 2e6e5312..361e2231 100644 --- a/libs/data/postgres/package.json +++ b/libs/data/postgres/package.json @@ -15,7 +15,8 @@ "dependencies": { "@stock-bot/logger": "*", "@stock-bot/types": "*", - "pg": "^8.11.3" + "pg": "^8.11.3", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/node": "^20.11.0", diff --git a/libs/data/postgres/src/client.ts b/libs/data/postgres/src/client.ts index f202b17b..500cfd5a 100644 --- a/libs/data/postgres/src/client.ts +++ b/libs/data/postgres/src/client.ts @@ -1,5 +1,7 @@ +import type { PoolConfig, QueryResultRow } from 'pg'; import { Pool } from 'pg'; -import type { QueryResultRow } 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'; @@ -23,7 +25,7 @@ export class PostgreSQLClient { private pool: Pool | null = null; private readonly config: PostgreSQLClientConfig; private readonly options: PostgreSQLConnectionOptions; - private readonly logger: any; + private readonly logger: LoggerLike; private readonly healthMonitor: PostgreSQLHealthMonitor; private readonly transactionManager: PostgreSQLTransactionManager; private isConnected = false; @@ -34,7 +36,7 @@ export class PostgreSQLClient { constructor( config: PostgreSQLClientConfig, - logger?: any, + logger?: LoggerLike, options?: PostgreSQLConnectionOptions, events?: ConnectionEvents ) { @@ -183,9 +185,9 @@ export class PostgreSQLClient { /** * Execute a query */ - async query( + async query( text: string, - params?: any[] + params?: unknown[] ): Promise> { if (!this.pool) { throw new Error('PostgreSQL client not connected'); @@ -262,9 +264,9 @@ export class PostgreSQLClient { /** * Execute a stored procedure or function */ - async callFunction( + async callFunction( functionName: string, - params?: any[] + params?: unknown[] ): Promise> { const placeholders = params ? params.map((_, i) => `$${i + 1}`).join(', ') : ''; const query = `SELECT * FROM ${functionName}(${placeholders})`; @@ -375,13 +377,16 @@ export class PostgreSQLClient { )`, [schemaName, tableName] ); - return result.rows[0].exists; + return at(result.rows, 0).exists; } /** * Get table schema information */ - async getTableSchema(tableName: string, schemaName: string = 'public'): Promise { + async getTableSchema( + tableName: string, + schemaName: string = 'public' + ): Promise { const result = await this.query( `SELECT column_name, @@ -400,16 +405,16 @@ export class PostgreSQLClient { /** * Execute EXPLAIN for query analysis */ - async explain(query: string, params?: any[]): Promise { + async explain(query: string, params?: unknown[]): Promise { const explainQuery = `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`; const result = await this.query(explainQuery, params); - return result.rows[0]['QUERY PLAN']; + return at(result.rows, 0)['QUERY PLAN']; } /** * Get database statistics */ - async getStats(): Promise { + async getStats(): Promise { const result = await this.query(` SELECT (SELECT count(*) FROM pg_stat_activity WHERE state = 'active') as active_connections, @@ -417,7 +422,7 @@ export class PostgreSQLClient { (SELECT setting FROM pg_settings WHERE name = 'max_connections') as max_connections, pg_size_pretty(pg_database_size(current_database())) as database_size `); - return result.rows[0]; + return result.rows[0] ?? {}; } /** @@ -434,7 +439,7 @@ export class PostgreSQLClient { return this.pool; } - private buildPoolConfig(): any { + private buildPoolConfig(): PoolConfig { this.logger.debug('Building PostgreSQL pool config:', { host: this.config.host, port: this.config.port, diff --git a/libs/data/postgres/src/query-builder.ts b/libs/data/postgres/src/query-builder.ts index ddf64e3a..2983925c 100644 --- a/libs/data/postgres/src/query-builder.ts +++ b/libs/data/postgres/src/query-builder.ts @@ -18,8 +18,8 @@ export class PostgreSQLQueryBuilder { private orderByConditions: OrderByCondition[] = []; private limitCount: number | null = null; private offsetCount: number | null = null; - private insertValues: Record = {}; - private updateValues: Record = {}; + private insertValues: Record = {}; + private updateValues: Record = {}; private readonly client: PostgreSQLClient; @@ -55,8 +55,8 @@ export class PostgreSQLQueryBuilder { /** * WHERE clause */ - where(column: string, operator: string, value?: any): this { - this.whereConditions.push({ column, operator: operator as any, value }); + where(column: string, operator: WhereCondition['operator'], value?: unknown): this { + this.whereConditions.push({ column, operator, value }); return this; } @@ -104,7 +104,7 @@ export class PostgreSQLQueryBuilder { /** * VALUES for INSERT */ - values(data: Record): this { + values(data: Record): this { this.insertValues = data; return this; } @@ -121,7 +121,7 @@ export class PostgreSQLQueryBuilder { /** * SET for UPDATE */ - set(data: Record): this { + set(data: Record): this { this.updateValues = data; return this; } @@ -138,7 +138,7 @@ export class PostgreSQLQueryBuilder { /** * Build and execute the query */ - async execute(): Promise> { + async execute(): Promise> { const { sql, params } = this.build(); return await this.client.query(sql, params); } @@ -146,8 +146,8 @@ export class PostgreSQLQueryBuilder { /** * Build the SQL query */ - build(): { sql: string; params: any[] } { - const params: any[] = []; + build(): { sql: string; params: unknown[] } { + const params: unknown[] = []; let sql = ''; switch (this.queryType) { @@ -170,7 +170,7 @@ export class PostgreSQLQueryBuilder { return { sql, params }; } - private buildSelectQuery(params: any[]): string { + private buildSelectQuery(params: unknown[]): string { let sql = `SELECT ${this.selectColumns.join(', ')}`; if (this.fromTable) { @@ -220,7 +220,7 @@ export class PostgreSQLQueryBuilder { return sql; } - private buildInsertQuery(params: any[]): string { + private buildInsertQuery(params: unknown[]): string { const columns = Object.keys(this.insertValues); const placeholders = columns.map((_, i) => `$${params.length + i + 1}`); @@ -229,7 +229,7 @@ export class PostgreSQLQueryBuilder { return `INSERT INTO ${this.fromTable} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`; } - private buildUpdateQuery(params: any[]): string { + private buildUpdateQuery(params: unknown[]): string { const sets = Object.keys(this.updateValues).map((key, i) => { return `${key} = $${params.length + i + 1}`; }); @@ -245,7 +245,7 @@ export class PostgreSQLQueryBuilder { return sql; } - private buildDeleteQuery(params: any[]): string { + private buildDeleteQuery(params: unknown[]): string { let sql = `DELETE FROM ${this.fromTable}`; if (this.whereConditions.length > 0) { @@ -255,7 +255,7 @@ export class PostgreSQLQueryBuilder { return sql; } - private buildWhereClause(conditions: WhereCondition[], params: any[]): string { + private buildWhereClause(conditions: WhereCondition[], params: unknown[]): string { return conditions .map(condition => { if (condition.operator === 'IS NULL' || condition.operator === 'IS NOT NULL') { diff --git a/libs/data/postgres/src/types.ts b/libs/data/postgres/src/types.ts index 7a129f2d..78e9b55c 100644 --- a/libs/data/postgres/src/types.ts +++ b/libs/data/postgres/src/types.ts @@ -94,7 +94,7 @@ export interface PostgreSQLMetrics { /** * Query Result Types */ -export interface QueryResult extends PgQueryResult { +export interface QueryResult extends PgQueryResult { executionTime?: number; } @@ -182,7 +182,7 @@ export interface Strategy { id: string; name: string; description: string; - parameters: Record; + parameters: Record; status: 'active' | 'inactive' | 'paused'; performance_metrics: Record; portfolio_id: string; @@ -207,8 +207,8 @@ export interface AuditLog { action: string; entity_type: string; entity_id: string; - old_values?: Record; - new_values?: Record; + old_values?: Record; + new_values?: Record; user_id?: string; ip_address?: string; user_agent?: string; @@ -233,7 +233,7 @@ export interface WhereCondition { | 'ILIKE' | 'IS NULL' | 'IS NOT NULL'; - value?: any; + value?: unknown; } export interface JoinCondition { diff --git a/libs/data/postgres/test/postgres.test.ts b/libs/data/postgres/test/postgres.test.ts index 6d628c5f..7408622d 100644 --- a/libs/data/postgres/test/postgres.test.ts +++ b/libs/data/postgres/test/postgres.test.ts @@ -3,7 +3,7 @@ import { SimplePostgresClient, SimpleQueryBuilder, SimpleTransactionManager, -} from '../src/simple-postgres'; +} from './support/simple-postgres'; describe('PostgresClient', () => { let client: SimplePostgresClient; @@ -195,7 +195,7 @@ describe('TransactionManager', () => { it('should rollback on error', async () => { await expect( - manager.transaction(async client => { + manager.transaction(async _client => { throw new Error('Transaction failed'); }) ).rejects.toThrow('Transaction failed'); diff --git a/libs/data/postgres/src/simple-postgres.ts b/libs/data/postgres/test/support/simple-postgres.ts similarity index 95% rename from libs/data/postgres/src/simple-postgres.ts rename to libs/data/postgres/test/support/simple-postgres.ts index 750d50d6..e39d32e8 100644 --- a/libs/data/postgres/src/simple-postgres.ts +++ b/libs/data/postgres/test/support/simple-postgres.ts @@ -1,5 +1,5 @@ /** - * Simple PostgreSQL client for testing + * Test-only in-memory PostgreSQL double. Never used by production adapters. */ export class SimplePostgresClient { private tables = new Map(); @@ -7,7 +7,7 @@ export class SimplePostgresClient { constructor(private config: any) {} - async query(sql: string, params?: any[]): Promise<{ rows: any[]; rowCount: number }> { + async query(_sql: string, _params?: any[]): Promise<{ rows: any[]; rowCount: number }> { // Simple mock implementation return { rows: [], rowCount: 0 }; } @@ -119,7 +119,7 @@ export class SimpleQueryBuilder { where(conditions: any): SimpleQueryBuilder { const whereClause = Object.entries(conditions) - .map(([key], i) => { + .map(([key], _i) => { this.params.push(conditions[key]); return `${key} = $${this.params.length}`; }) @@ -196,7 +196,7 @@ export class SimpleTransactionManager { async transaction(fn: (client: any) => Promise): Promise { const mockClient = { - query: async (sql?: string) => ({ rows: [], rowCount: 0 }), + query: async (_sql?: string) => ({ rows: [], rowCount: 0 }), release: () => {}, }; diff --git a/libs/data/postgres/tsconfig.json b/libs/data/postgres/tsconfig.json index 75d59290..a8dcfbf4 100644 --- a/libs/data/postgres/tsconfig.json +++ b/libs/data/postgres/tsconfig.json @@ -6,5 +6,15 @@ "composite": true }, "include": ["src/**/*"], - "references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }] + "references": [ + { + "path": "../../core/logger" + }, + { + "path": "../../core/types" + }, + { + "path": "../../../libs/core/invariants" + } + ] } diff --git a/libs/data/questdb/package.json b/libs/data/questdb/package.json index d173cdd6..1b0e02e4 100644 --- a/libs/data/questdb/package.json +++ b/libs/data/questdb/package.json @@ -15,7 +15,8 @@ "dependencies": { "@stock-bot/logger": "*", "@stock-bot/types": "*", - "pg": "^8.11.3" + "pg": "^8.11.3", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/node": "^20.11.0", diff --git a/libs/data/questdb/src/client.ts b/libs/data/questdb/src/client.ts index efd9f49d..d4cba976 100644 --- a/libs/data/questdb/src/client.ts +++ b/libs/data/questdb/src/client.ts @@ -1,4 +1,6 @@ +import type { PoolConfig, QueryResultRow } from 'pg'; import { Pool } from 'pg'; +import type { LoggerLike } from '@stock-bot/logger'; import { QuestDBHealthMonitor } from './health'; import { QuestDBInfluxWriter } from './influx-writer'; import { QuestDBQueryBuilder } from './query-builder'; @@ -20,13 +22,17 @@ export class QuestDBClient { private pgPool: Pool | null = null; private readonly config: QuestDBClientConfig; private readonly options: QuestDBConnectionOptions; - private readonly logger: any; + private readonly logger: LoggerLike; private readonly healthMonitor: QuestDBHealthMonitor; private readonly influxWriter: QuestDBInfluxWriter; private readonly schemaManager: QuestDBSchemaManager; private isConnected = false; - constructor(config: QuestDBClientConfig, logger?: any, options?: QuestDBConnectionOptions) { + constructor( + config: QuestDBClientConfig, + logger?: LoggerLike, + options?: QuestDBConnectionOptions + ) { this.config = config; this.logger = logger || console; this.options = { @@ -128,7 +134,7 @@ export class QuestDBClient { /** * Execute a SQL query */ - async query(sql: string, params?: any[]): Promise> { + async query(sql: string, params?: unknown[]): Promise> { if (!this.pgPool) { throw new Error('QuestDB client not connected'); } @@ -150,7 +156,7 @@ export class QuestDBClient { executionTime, metadata: { columns: - result.fields?.map((field: any) => ({ + result.fields?.map(field => ({ name: field.name, type: this.mapDataType(field.dataTypeID), })) || [], @@ -227,13 +233,13 @@ export class QuestDBClient { /** * Execute a time-series specific query with SAMPLE BY */ - async sampleBy( + async sampleBy( table: TableNames, columns: string[], interval: string, _timeColumn: string = 'timestamp', where?: string, - params?: any[] + params?: unknown[] ): Promise> { const columnsStr = columns.join(', '); const whereClause = where ? `WHERE ${where}` : ''; @@ -252,7 +258,7 @@ export class QuestDBClient { /** * Get latest values by symbol using LATEST BY */ - async latestBy( + async latestBy( table: TableNames, columns: string | string[] = '*', keyColumns: string | string[] = 'symbol' @@ -272,13 +278,13 @@ export class QuestDBClient { /** * Execute ASOF JOIN for time-series correlation */ - async asofJoin( + async asofJoin( leftTable: TableNames, rightTable: TableNames, joinCondition: string, columns?: string[], where?: string, - params?: any[] + params?: unknown[] ): Promise> { const columnsStr = columns ? columns.join(', ') : '*'; const whereClause = where ? `WHERE ${where}` : ''; @@ -296,7 +302,7 @@ export class QuestDBClient { /** * Get database statistics */ - async getStats(): Promise { + async getStats(): Promise { const result = await this.query(` SELECT table_name, @@ -313,7 +319,7 @@ export class QuestDBClient { /** * Get table information */ - async getTableInfo(tableName: string): Promise { + async getTableInfo(tableName: string): Promise { const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [ tableName, ]); @@ -412,8 +418,8 @@ export class QuestDBClient { return { ...this.config }; } - private buildPgPoolConfig(): any { - const config: any = { + private buildPgPoolConfig(): PoolConfig { + const config: PoolConfig = { host: this.config.host, port: this.config.pgPort, database: this.config.database, @@ -430,7 +436,7 @@ export class QuestDBClient { // Only add user/password if they are provided if (this.config.user) { - this.logger.debug('Adding user to QuestDB pool config:', this.config.user); + this.logger.debug('Adding user to QuestDB pool config', { user: this.config.user }); config.user = this.config.user; } else { this.logger.debug('No user provided for QuestDB connection'); diff --git a/libs/data/questdb/src/health.ts b/libs/data/questdb/src/health.ts index 3722e7d2..a2ca5b76 100644 --- a/libs/data/questdb/src/health.ts +++ b/libs/data/questdb/src/health.ts @@ -1,9 +1,10 @@ +import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; import type { HealthStatus, PerformanceMetrics, QueryResult } from './types'; // Interface to avoid circular dependency interface QuestDBClientInterface { - query(sql: string, params?: any[]): Promise>; + query(sql: string, params?: unknown[]): Promise>; isPgPoolHealthy(): boolean; } diff --git a/libs/data/questdb/src/query-builder.ts b/libs/data/questdb/src/query-builder.ts index 7770ac08..7ebb56f1 100644 --- a/libs/data/questdb/src/query-builder.ts +++ b/libs/data/questdb/src/query-builder.ts @@ -1,9 +1,10 @@ +import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; import type { QueryResult, TableNames, TimeRange } from './types'; // Interface to avoid circular dependency interface QuestDBClientInterface { - query(sql: string, params?: any[]): Promise>; + query(sql: string, params?: unknown[]): Promise>; } /** @@ -190,7 +191,7 @@ export class QuestDBQueryBuilder { /** * Build and execute the query */ - public async execute(): Promise> { + public async execute(): Promise> { const sql = this.build(); this.logger.debug('Executing query', { sql }); diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index be91b3e4..27a8d5fc 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -1,9 +1,11 @@ +import type { QueryResultRow } from 'pg'; +import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { QueryResult, TableSchema } from './types'; // Interface to avoid circular dependency interface QuestDBClientInterface { - query(sql: string, params?: any[]): Promise>; + query(sql: string, params?: unknown[]): Promise>; } /** @@ -215,7 +217,7 @@ export class QuestDBSchemaManager { WHERE table_name = '${tableName}' `); - return result.rows.length > 0 && result.rows[0].count > 0; + return result.rows.length > 0 && at(result.rows, 0).count > 0; } catch (error) { this.logger.error(`Error checking if table exists: ${tableName}`, error); return false; @@ -266,7 +268,7 @@ export class QuestDBSchemaManager { /** * Get table statistics */ - public async getTableStats(tableName: string): Promise { + public async getTableStats(tableName: string): Promise { try { const result = await this.client.query(` SELECT diff --git a/libs/data/questdb/src/types.ts b/libs/data/questdb/src/types.ts index d219abc8..5aec03c7 100644 --- a/libs/data/questdb/src/types.ts +++ b/libs/data/questdb/src/types.ts @@ -1,3 +1,5 @@ +import type { QueryResultRow } from 'pg'; + /** * QuestDB Client Configuration and Types */ @@ -101,7 +103,7 @@ export interface QuoteData extends BaseTimeSeriesData { export interface IndicatorData extends BaseTimeSeriesData { indicator_name: string; value: number; - parameters?: Record; + parameters?: Record; timeframe: string; } @@ -127,7 +129,7 @@ export interface RiskMetrics extends BaseTimeSeriesData { /** * Query Result Types */ -export interface QueryResult { +export interface QueryResult { rows: T[]; rowCount: number; executionTime: number; diff --git a/libs/data/questdb/tsconfig.json b/libs/data/questdb/tsconfig.json index 75d59290..a8dcfbf4 100644 --- a/libs/data/questdb/tsconfig.json +++ b/libs/data/questdb/tsconfig.json @@ -6,5 +6,15 @@ "composite": true }, "include": ["src/**/*"], - "references": [{ "path": "../../core/logger" }, { "path": "../../core/types" }] + "references": [ + { + "path": "../../core/logger" + }, + { + "path": "../../core/types" + }, + { + "path": "../../../libs/core/invariants" + } + ] } diff --git a/libs/services/browser/src/browser.ts b/libs/services/browser/src/browser.ts index 7295048f..d79791de 100644 --- a/libs/services/browser/src/browser.ts +++ b/libs/services/browser/src/browser.ts @@ -1,15 +1,16 @@ import { chromium } from 'playwright'; import type { BrowserContext, Page, Browser as PlaywrightBrowser } from 'playwright'; +import type { LoggerLike } from '@stock-bot/logger'; import type { BrowserOptions, NetworkEvent, NetworkEventHandler } from './types'; export class Browser { private browser?: PlaywrightBrowser; private contexts: Map = new Map(); - private logger: any; + private logger: LoggerLike; private options: BrowserOptions; private initialized = false; - constructor(logger?: any, defaultOptions?: BrowserOptions) { + constructor(logger?: LoggerLike, defaultOptions?: BrowserOptions) { this.logger = logger || console; this.options = { headless: true, diff --git a/libs/services/browser/test/browser.test.ts b/libs/services/browser/test/browser.test.ts index 5536372c..c10a5791 100644 --- a/libs/services/browser/test/browser.test.ts +++ b/libs/services/browser/test/browser.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import { SimpleBrowser } from '../src/simple-browser'; +import { SimpleBrowser } from './support/simple-browser'; describe('Browser', () => { let browser: SimpleBrowser; diff --git a/libs/services/browser/src/simple-browser.ts b/libs/services/browser/test/support/simple-browser.ts similarity index 98% rename from libs/services/browser/src/simple-browser.ts rename to libs/services/browser/test/support/simple-browser.ts index e51756e6..697080b6 100644 --- a/libs/services/browser/src/simple-browser.ts +++ b/libs/services/browser/test/support/simple-browser.ts @@ -1,5 +1,5 @@ import type { Page } from 'playwright'; -import type { BrowserOptions, ScrapingResult } from './types'; +import type { BrowserOptions, ScrapingResult } from '../../src/types'; /** * Simple browser implementation for testing diff --git a/libs/services/proxy/src/proxy-manager.ts b/libs/services/proxy/src/proxy-manager.ts index 09047249..18f0d105 100644 --- a/libs/services/proxy/src/proxy-manager.ts +++ b/libs/services/proxy/src/proxy-manager.ts @@ -2,6 +2,7 @@ * Centralized Proxy Manager - Handles proxy storage, retrieval, and caching */ import type { CacheProvider } from '@stock-bot/cache'; +import type { LoggerLike } from '@stock-bot/logger'; import type { ProxyInfo, ProxyManagerConfig, ProxyStats } from './types'; export class ProxyManager { @@ -11,10 +12,10 @@ export class ProxyManager { private lastUpdate: Date | null = null; private lastFetchTime: Date | null = null; private isInitialized = false; - private logger: any; + private logger: LoggerLike; private config: ProxyManagerConfig; - constructor(cache: CacheProvider, config: ProxyManagerConfig = {}, logger?: any) { + constructor(cache: CacheProvider, config: ProxyManagerConfig = {}, logger?: LoggerLike) { this.cache = cache; this.config = config; this.logger = logger || console; @@ -85,7 +86,7 @@ export class ProxyManager { // Note: We don't increment the index here since getProxy() already does that const currentIndex = this.proxyIndex > 0 ? this.proxyIndex - 1 : this.proxies.length - 1; const proxyInfo = this.proxies[currentIndex]; - + return proxyInfo || null; } diff --git a/libs/utils/package.json b/libs/utils/package.json index e11b5066..49d16036 100644 --- a/libs/utils/package.json +++ b/libs/utils/package.json @@ -13,11 +13,16 @@ "@stock-bot/config": "workspace:*", "@stock-bot/logger": "workspace:*", "@stock-bot/cache": "workspace:*", - "@stock-bot/types": "workspace:*" + "@stock-bot/types": "workspace:*", + "@stock-bot/invariants": "workspace:*" }, "devDependencies": { "@types/node": "^20.11.0", "typescript": "^5.3.0", "bun-types": "^1.2.15" + }, + "exports": { + ".": "./src/index.ts", + "./assertions": "./src/assertions.ts" } } diff --git a/libs/utils/src/assertions.ts b/libs/utils/src/assertions.ts new file mode 100644 index 00000000..9b8b7105 --- /dev/null +++ b/libs/utils/src/assertions.ts @@ -0,0 +1 @@ +export { at, defined } from '@stock-bot/invariants'; diff --git a/libs/utils/src/calculations/index.ts b/libs/utils/src/calculations/index.ts index f45845b7..7ee646a0 100644 --- a/libs/utils/src/calculations/index.ts +++ b/libs/utils/src/calculations/index.ts @@ -92,8 +92,8 @@ export function analyzePortfolio( _benchmarkReturns?: number[], _riskFreeRate: number = 0.02 ): { - performance: any; - risk: any; + performance: Record; + risk: Record; } { // Note: Implementation depends on performance-metrics and risk-metrics // This is a placeholder for the full implementation diff --git a/libs/utils/src/calculations/technical-indicators.ts b/libs/utils/src/calculations/technical-indicators.ts index 7f787766..7d4d2f31 100644 --- a/libs/utils/src/calculations/technical-indicators.ts +++ b/libs/utils/src/calculations/technical-indicators.ts @@ -1,3 +1,4 @@ +import { defined } from '@stock-bot/invariants'; /** * Technical Indicators * Comprehensive set of technical analysis indicators @@ -807,7 +808,7 @@ export function ichimoku( } // Chikou Span (Lagging Span) - chikouSpan.push(ohlcv[i]!.close); + chikouSpan.push(defined(ohlcv[i]).close); } return { @@ -837,13 +838,13 @@ export function ultimateOscillator( // Calculate BP and TR for (let i = 0; i < ohlcv.length; i++) { - const current = ohlcv[i]!; + const current = defined(ohlcv[i]); if (i === 0) { bp.push(current.close - current.low); tr.push(current.high - current.low); } else { - const previous = ohlcv[i - 1]!; + const previous = defined(ohlcv[i - 1]); bp.push(current.close - Math.min(current.low, previous.close)); tr.push( Math.max( @@ -886,8 +887,8 @@ export function easeOfMovement(ohlcv: OHLCV[], period: number = 14): number[] { const emv: number[] = []; for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]!; - const previous = ohlcv[i - 1]!; + 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; @@ -1030,8 +1031,8 @@ export function klingerVolumeOscillator( const volumeForce: number[] = []; for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]!; - const previous = ohlcv[i - 1]!; + 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; @@ -1164,7 +1165,7 @@ export function stochasticRSI( const slice = rsiValues.slice(i - stochPeriod + 1, i + 1); const highest = Math.max(...slice); const lowest = Math.min(...slice); - const currentRSI = rsiValues[i]!; + const currentRSI = defined(rsiValues[i]); if (highest === lowest) { stochRSI.push(0); @@ -1196,8 +1197,8 @@ export function vortexIndicator( const tr: number[] = []; for (let i = 1; i < ohlcv.length; i++) { - const current = ohlcv[i]!; - const previous = ohlcv[i - 1]!; + const current = defined(ohlcv[i]); + const previous = defined(ohlcv[i - 1]); // Vortex Movement vm_plus.push(Math.abs(current.high - previous.low)); diff --git a/libs/utils/src/fetch.ts b/libs/utils/src/fetch.ts index f446c588..cc5147a3 100644 --- a/libs/utils/src/fetch.ts +++ b/libs/utils/src/fetch.ts @@ -1,3 +1,5 @@ +import type { LoggerLike } from '@stock-bot/logger'; + /** * Enhanced fetch wrapper with proxy support and automatic debug logging * Drop-in replacement for native fetch with additional features @@ -8,7 +10,7 @@ export interface BunRequestInit extends RequestInit { } export interface FetchOptions extends RequestInit { - logger?: any; + logger?: LoggerLike; proxy?: string | null; timeout?: number; } @@ -61,7 +63,7 @@ export async function fetch(input: RequestInfo | URL, options?: FetchOptions): P async function performFetch( input: RequestInfo | URL, requestOptions: RequestInit, - logger: any, + logger: LoggerLike, url: string ): Promise { logger.debug('HTTP request', { diff --git a/libs/utils/src/generic-functions.ts b/libs/utils/src/generic-functions.ts index 3e4a25d3..e5ab3820 100644 --- a/libs/utils/src/generic-functions.ts +++ b/libs/utils/src/generic-functions.ts @@ -1,3 +1,4 @@ +import { defined } from '@stock-bot/invariants'; /** * Generic utility functions that work with standardized types * These functions demonstrate how to use generic types with OHLCV data @@ -69,10 +70,10 @@ export function calculateTrueRange(data: T[]): number[] { for (let i = 0; i < data.length; i++) { if (i === 0) { - result.push(data[i]!.high - data[i]!.low); + result.push(defined(data[i]).high - defined(data[i]).low); } else { - const current = data[i]!; - const previous = data[i - 1]!; + const current = defined(data[i]); + const previous = defined(data[i - 1]); const tr = Math.max( current.high - current.low, Math.abs(current.high - previous.close), @@ -93,8 +94,8 @@ export function calculateReturns(data: T[]): number[] { const returns: number[] = []; for (let i = 1; i < closes.length; i++) { - const current = closes[i]!; - const previous = closes[i - 1]!; + const current = defined(closes[i]); + const previous = defined(closes[i - 1]); if (previous > 0) { returns.push((current - previous) / previous); } else { @@ -113,8 +114,8 @@ export function calculateLogReturns(data: T[]): number[] { const logReturns: number[] = []; for (let i = 1; i < closes.length; i++) { - const current = closes[i]!; - const previous = closes[i - 1]!; + const current = defined(closes[i]); + const previous = defined(closes[i - 1]); if (previous > 0 && current > 0) { logReturns.push(Math.log(current / previous)); } else { @@ -172,7 +173,7 @@ export function groupBySymbol(data: OHLCV[]): Record { if (!grouped[item.symbol]) { grouped[item.symbol] = []; } - grouped[item.symbol]!.push(item); + defined(grouped[item.symbol]).push(item); } return grouped; diff --git a/libs/utils/src/index.ts b/libs/utils/src/index.ts index 5329f6db..67758170 100644 --- a/libs/utils/src/index.ts +++ b/libs/utils/src/index.ts @@ -1,4 +1,5 @@ export * from './calculations/index'; +export * from './assertions'; export * from './common'; export * from './dateUtils'; export * from './generic-functions'; diff --git a/libs/utils/src/user-agent.ts b/libs/utils/src/user-agent.ts index ac76234b..f28f2ea0 100644 --- a/libs/utils/src/user-agent.ts +++ b/libs/utils/src/user-agent.ts @@ -1,3 +1,5 @@ +import { defined } from '@stock-bot/invariants'; + /** * User Agent utility for generating random user agents */ @@ -26,5 +28,5 @@ const USER_AGENTS = [ export function getRandomUserAgent(): string { const index = Math.floor(Math.random() * USER_AGENTS.length); - return USER_AGENTS[index]!; + return defined(USER_AGENTS[index]); } diff --git a/libs/utils/tsconfig.json b/libs/utils/tsconfig.json index 7a56502a..8e4792ca 100644 --- a/libs/utils/tsconfig.json +++ b/libs/utils/tsconfig.json @@ -10,9 +10,20 @@ "include": ["src/**/*"], "exclude": ["node_modules", "dist"], "references": [ - { "path": "../core/types" }, - { "path": "../core/cache" }, - { "path": "../core/config" }, - { "path": "../core/logger" } + { + "path": "../core/types" + }, + { + "path": "../core/cache" + }, + { + "path": "../core/config" + }, + { + "path": "../core/logger" + }, + { + "path": "../../libs/core/invariants" + } ] } diff --git a/package.json b/package.json index d6f6c2e3..a1df7ef0 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "coverage:html": "bun run tools/coverage-cli/src/index.ts --reporters html", "coverage:ci": "bun run tools/coverage-cli/src/index.ts --reporters markdown json --fail-under", "test:unit": "bun test test/unit", - "test:integration": "bun test test/integration", + "test:integration": "bun test test/integration/", "test:e2e": "bun test test/e2e", "test:libs": "turbo run test --filter='./libs/**'", "test:apps": "turbo run test --filter=./apps/*/*", diff --git a/scripts/check.ts b/scripts/check.ts index cba18659..6da706db 100644 --- a/scripts/check.ts +++ b/scripts/check.ts @@ -6,6 +6,7 @@ export const checks = [ 'typecheck', 'test:contracts', 'test:tooling', + 'test:integration', 'lint:check', ] as const; diff --git a/scripts/test/backend-boundaries.test.ts b/scripts/test/backend-boundaries.test.ts new file mode 100644 index 00000000..0bf702c2 --- /dev/null +++ b/scripts/test/backend-boundaries.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from 'bun:test'; +import type { ServerWebSocket } from 'bun'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { getLogger } from '@stock-bot/logger'; +import { createWebSocketHandler, type RunSocketData } from '../../apps/stock/web-api/src/websocket/run-updates'; +import { MonitoringService } from '../../apps/stock/web-api/src/services/monitoring.service'; +import { defined, at } from '@stock-bot/invariants'; + +const logger = getLogger('boundary-tests'); + +test('required services reject missing capabilities before work starts', () => { + expect(() => requireServices({ logger }, 'mongodb')).toThrow("'mongodb' is unavailable"); + expect(() => requireServices({ logger, postgres: null }, 'postgres')).toThrow("'postgres' is unavailable"); + expect(requireServices({ logger }, 'logger').logger).toBe(logger); + expect(() => defined(undefined)).toThrow(); + expect(() => at([], 0)).toThrow(RangeError); + expect(defined(0)).toBe(0); +}); + +test('Bun socket lifecycle dispatches messages and removes closed connections', () => { + const sent: string[] = []; + const socket = { data: { runId: 'run-1' }, send: (message: string) => sent.push(message), close() {} } as unknown as ServerWebSocket; + const handler = createWebSocketHandler({ logger }); + handler.handleConnection(socket, 'run-1'); + handler.handleMessage(socket, '{"type":"ping"}'); + expect(JSON.parse(sent[0]!)).toMatchObject({ type: 'connected', runId: 'run-1' }); + expect(JSON.parse(sent[1]!)).toEqual({ type: 'pong' }); + handler.sendProgressUpdate('run-1', 25); + expect(JSON.parse(sent[2]!)).toMatchObject({ type: 'progress', data: { progress: 25 } }); + handler.handleClose(socket); + expect(handler.getConnectionsCount('run-1')).toBe(0); + handler.cleanup(); +}); + +test('monitoring uses manager-owned queues and public counters', async () => { + const names: string[] = []; + const queueManager = { getQueue(name: string) { + names.push(name); + return { async getStats() { return { waiting: 2, active: 1, completed: 4, failed: 0, delayed: 0, paused: false, workers: 3 }; }, getWorkerCount() { return 3; } }; + } } as unknown as NonNullable; + const stats = await new MonitoringService({ logger, queueManager }).getQueueStats(); + expect(names).toContain('{data-pipeline_symbols}'); + expect(names).toContain('{data-ingestion_qm}'); + expect(stats.every(snapshot => snapshot.connected && snapshot.workers?.count === 3)).toBe(true); + expect(await new MonitoringService({ logger }).getQueueStats()).toEqual([]); +}); diff --git a/scripts/test/coverage-integrity.test.ts b/scripts/test/coverage-integrity.test.ts new file mode 100644 index 00000000..eddafe34 --- /dev/null +++ b/scripts/test/coverage-integrity.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from 'bun:test'; +import { loadConfig } from '../../tools/coverage-cli/src/config'; +import { CoverageProcessor } from '../../tools/coverage-cli/src/processor'; +import { CoverageRunner } from '../../tools/coverage-cli/src/runner'; + +test('missing coverage cannot become a passing synthetic percentage', () => { + const config = loadConfig({ threshold: 80 }); + const processor = new CoverageProcessor(config); + const report = processor.process({ files: [] }, []); + expect(report.overall.lines.percentage).toBe(0); + expect(processor.checkThresholds(report).passed).toBe(false); +}); + +test('requesting no existing packages is a failed coverage run', async () => { + const config = loadConfig({ packages: ['__missing_coverage_fixture__'] }); + const result = await new CoverageRunner(config).run(); + expect(result.success).toBe(false); + expect(result.coverage.files).toEqual([]); +}); + +test('coverage configuration does not mutate defaults and rejects unknown reporters', () => { + expect(loadConfig({ thresholdLines: 17 }).thresholds.lines).toBe(17); + expect(loadConfig({}).thresholds.lines).toBe(80); + expect(() => loadConfig({ reporters: ['not-a-reporter'] })).toThrow('Unknown coverage reporter'); +}); diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index a6d05786..088f1730 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -1,6 +1,6 @@ import { createRequire } from 'node:module'; import { describe, expect, it } from 'bun:test'; -import { IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine'; +import { BacktestEngine, IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine'; describe('generated native bindings', () => { it('ESM loads the generated artifact and exposes the documented constructor aliases', () => { @@ -15,4 +15,27 @@ describe('generated native bindings', () => { expect(binding.TechnicalIndicators).toBe(TechnicalIndicators); expect(binding.IncrementalSMA).toBe(IncrementalSMA); }); + + it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => { + const indicators = new TechnicalIndicators(); + const prices = Array.from({ length: 80 }, (_, index) => 100 + index); + const result = JSON.parse(indicators.calculateMacd(prices, 12, 26, 9)) as { + macd: number[]; signal: number[]; histogram: number[]; + }; + const fast = indicators.calculateEma(prices, 12); + const slow = indicators.calculateEma(prices, 26); + expect(result.macd).toHaveLength(prices.length); + expect(result.signal).toHaveLength(prices.length); + for (let index = 0; index < prices.length; index++) { + expect(result.macd[index]).toBeCloseTo(fast[index]! - slow[index]!, 10); + expect(result.histogram[index]).toBeCloseTo(result.macd[index]! - result.signal[index]!, 10); + } + }); + + it('invalid SMA periods throw before entering the native event loop', () => { + const engine = new BacktestEngine({ name: 'validation', symbols: ['TEST'], startDate: '2023-01-01T00:00:00Z', endDate: '2023-02-01T00:00:00Z', initialCapital: 100000, commission: 0, slippage: 0, dataFrequency: '1d' }); + expect(() => engine.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}')).toThrow('TypeScript strategy callbacks are not supported'); + expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 0, slowPeriod: 20 })).toThrow('SMA periods must satisfy'); + expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 20, slowPeriod: 10 })).toThrow('SMA periods must satisfy'); + }); }); diff --git a/scripts/test/orchestrator-container.test.ts b/scripts/test/orchestrator-container.test.ts new file mode 100644 index 00000000..939aa19c --- /dev/null +++ b/scripts/test/orchestrator-container.test.ts @@ -0,0 +1,12 @@ +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/test/integration/ingestion-backtest.test.ts b/test/integration/ingestion-backtest.test.ts new file mode 100644 index 00000000..921fa3a4 --- /dev/null +++ b/test/integration/ingestion-backtest.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, test } from 'bun:test'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import type { MongoDBClient } from '@stock-bot/services'; +import { + persistEodPrices, + type EodPrice, +} from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage'; +import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('replay-test'); +const identity = { symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' }; +const start = new Date('2024-01-01T00:00:00.000Z'); +const end = new Date('2024-03-15T00:00:00.000Z'); +const fixture: EodPrice[] = Array.from({ length: 70 }, (_, i) => { + const close = 100 + Math.sin((i * Math.PI) / 6) * 8 + i * 0.02; + return { + date: new Date(start.getTime() + i * 86400000).toISOString().slice(0, 10), + open: close - 0.1, + high: close + 1, + low: close - 1, + close, + volume: 1_000_000, + }; +}); + +/** Only the database transport is replaced; normalization, storage reads, and engine are real. */ +function memoryStore() { + const documents: Array = []; + const transport = { + async batchUpsert(collection: string, rows: typeof documents) { + expect(collection).toBe('eodPrices'); + for (const row of rows) { + const index = documents.findIndex( + old => old.date === row.date && old.eodSearchCode === row.eodSearchCode + ); + if (index >= 0) documents[index] = row; + else documents.push(row); + } + return { + insertedCount: rows.length, + modifiedCount: 0, + matchedCount: 0, + upsertedCount: rows.length, + }; + }, + async find( + collection: string, + filter: { symbol: string; date: { $gte: string; $lt: string } } + ) { + expect(collection).toBe('eodPrices'); + return documents + .filter( + row => + row.symbol === filter.symbol && + row.date >= filter.date.$gte && + row.date < filter.date.$lt + ) + .sort((a, b) => a.date.localeCompare(b.date)); + }, + }; + return { documents, mongodb: transport as unknown as MongoDBClient }; +} + +describe('deterministic ingestion → storage → native backtest', () => { + test('replays stored provider fixtures and produces identical trades and metrics', async () => { + const { documents, mongodb } = memoryStore(); + await persistEodPrices(mongodb, identity, fixture); + await persistEodPrices(mongodb, identity, fixture); + expect(documents).toHaveLength(fixture.length); + expect(documents.every(row => row.source === 'eod')).toBe(true); + const services = { logger, mongodb }; + const storage = new StorageService(services, mongodb, null, null); + const config = BacktestConfigSchema.parse({ + mode: 'backtest', + name: 'Fixed replay', + symbols: ['FIXTURE'], + strategy: 'sma-crossover', + startDate: start.toISOString(), + endDate: end.toISOString(), + initialCapital: 100000, + dataFrequency: '1d', + commission: 0, + slippage: 0, + config: { fastPeriod: 3, slowPeriod: 7 }, + }); + const engine = new RustBacktestAdapter({ ...services, custom: { StorageService: storage } }); + const first = await engine.runBacktest(config); + const second = await engine.runBacktest(config); + expect(first.status).toBe('completed'); + expect(first.trades.length).toBeGreaterThan(0); + expect(first.trades).toEqual(second.trades); + expect(first.metrics).toEqual(second.metrics); + expect(first.equity).toEqual(second.equity); + expect(first.metrics.totalReturn).toBeFinite(); + expect(engine.getStatus().isRunning).toBe(false); + }); + + test('rejects malformed provider records before writing anything', async () => { + const { documents, mongodb } = memoryStore(); + await expect( + persistEodPrices(mongodb, identity, [{ ...fixture[0]!, low: -1 }]) + ).rejects.toThrow('Invalid OHLCV'); + expect(documents).toHaveLength(0); + }); + + test('missing storage never silently produces synthetic prices', async () => { + const storage = new StorageService({ logger }, null, null, null); + await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow( + 'explicit opt-in' + ); + }); + + test('explicit synthetic fixtures use a stable seed', async () => { + const storage = new StorageService({ logger }, null, null, null, { + allowSyntheticData: true, + syntheticSeed: 7, + }); + expect(await storage.getHistoricalBars('FIXTURE', start, end, '1d')).toEqual( + await storage.getHistoricalBars('FIXTURE', start, end, '1d') + ); + }); + + test('empty storage and unknown strategies fail without leaving the engine running', async () => { + const { mongodb } = memoryStore(); + const engine = new RustBacktestAdapter({ logger, mongodb }); + const config = BacktestConfigSchema.parse({ + mode: 'backtest', + symbols: ['FIXTURE'], + strategy: 'sma-crossover', + startDate: start.toISOString(), + endDate: end.toISOString(), + initialCapital: 100000, + dataFrequency: '1d', + }); + await expect(engine.runBacktest(config)).rejects.toThrow('No historical data'); + await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow( + 'Unknown native strategy' + ); + expect(engine.getStatus().isRunning).toBe(false); + }); +}); diff --git a/tools/coverage-cli/package.json b/tools/coverage-cli/package.json index 948a9a9e..4a054f27 100644 --- a/tools/coverage-cli/package.json +++ b/tools/coverage-cli/package.json @@ -1,37 +1,39 @@ -{ - "name": "@stock-bot/coverage-cli", - "version": "1.0.0", - "description": "Custom coverage tool for Stock Bot with advanced reporting and exclusion capabilities", - "type": "module", - "bin": { - "stock-bot-coverage": "./dist/index.js" - }, - "scripts": { - "build": "bun build ./src/index.ts --outdir ./dist --target node", - "dev": "bun run src/index.ts", - "test": "bun test" - }, - "dependencies": { - "chalk": "^5.3.0", - "commander": "^11.1.0", - "glob": "^10.3.10", - "handlebars": "^4.7.8", - "lcov-parse": "^1.0.0", - "table": "^6.8.1" - }, - "devDependencies": { - "@types/glob": "^8.1.0", - "@types/lcov-parse": "^1.0.0", - "@types/node": "^20.10.5", - "bun-types": "^1.0.18" - }, - "keywords": [ - "coverage", - "test", - "cli", - "bun", - "reporting" - ], - "author": "Stock Bot Team", - "license": "MIT" -} \ No newline at end of file +{ + "name": "@stock-bot/coverage-cli", + "version": "1.0.0", + "description": "Custom coverage tool for Stock Bot with advanced reporting and exclusion capabilities", + "type": "module", + "bin": { + "stock-bot-coverage": "./dist/index.js" + }, + "scripts": { + "build": "bun build ./src/index.ts --outdir ./dist --target node", + "dev": "bun run src/index.ts", + "test": "bun test" + }, + "dependencies": { + "chalk": "^5.3.0", + "commander": "^11.1.0", + "glob": "^10.3.10", + "handlebars": "^4.7.8", + "lcov-parse": "^1.0.0", + "table": "^6.8.1", + "@stock-bot/utils": "workspace:*", + "@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" + }, + "keywords": [ + "coverage", + "test", + "cli", + "bun", + "reporting" + ], + "author": "Stock Bot Team", + "license": "MIT" +} diff --git a/tools/coverage-cli/src/config.ts b/tools/coverage-cli/src/config.ts index a5beb5c9..c078f43e 100644 --- a/tools/coverage-cli/src/config.ts +++ b/tools/coverage-cli/src/config.ts @@ -1,153 +1,168 @@ -import { readFileSync, existsSync } from 'fs'; -import { resolve, join } from 'path'; -import type { CoverageConfig, CLIOptions } from './types'; - -const DEFAULT_CONFIG: CoverageConfig = { - exclude: [ - '**/node_modules/**', - '**/dist/**', - '**/build/**', - '**/coverage/**', - '**/*.test.ts', - '**/*.test.js', - '**/*.spec.ts', - '**/*.spec.js', - '**/test/**', - '**/tests/**', - '**/__tests__/**', - '**/__mocks__/**', - '**/setup.ts', - '**/setup.js', - ], - reporters: ['terminal'], - thresholds: { - lines: 80, - functions: 80, - branches: 80, - statements: 80, - }, - outputDir: 'coverage', -}; - -export function loadConfig(options: CLIOptions): CoverageConfig { - let config = { ...DEFAULT_CONFIG }; - - // Load from config file - const configPath = options.config || findConfigFile(); - if (configPath && existsSync(configPath)) { - try { - const fileConfig = JSON.parse(readFileSync(configPath, 'utf-8')); - config = mergeConfig(config, fileConfig); - } catch (error) { - console.warn(`Warning: Failed to load config from ${configPath}:`, error); - } - } - - // Override with CLI options - if (options.exclude && options.exclude.length > 0) { - config.exclude = options.exclude; - } - - if (options.include && options.include.length > 0) { - config.include = options.include; - } - - if (options.reporters && options.reporters.length > 0) { - config.reporters = options.reporters as any[]; - } - - if (options.outputDir) { - config.outputDir = options.outputDir; - } - - // Handle thresholds - if (options.threshold !== undefined) { - config.thresholds = { - lines: options.threshold, - functions: options.threshold, - branches: options.threshold, - statements: options.threshold, - }; - } - - if (options.thresholdLines !== undefined) { - config.thresholds.lines = options.thresholdLines; - } - if (options.thresholdFunctions !== undefined) { - config.thresholds.functions = options.thresholdFunctions; - } - if (options.thresholdBranches !== undefined) { - config.thresholds.branches = options.thresholdBranches; - } - if (options.thresholdStatements !== undefined) { - config.thresholds.statements = options.thresholdStatements; - } - - if (options.packages) { - config.packages = options.packages; - } - - // Find workspace root - config.workspaceRoot = findWorkspaceRoot(); - - return config; -} - -function findConfigFile(): string | null { - const configNames = ['.coveragerc.json', '.coveragerc', 'coverage.config.json']; - const searchDirs = [process.cwd(), ...getParentDirs(process.cwd())]; - - for (const dir of searchDirs) { - for (const name of configNames) { - const path = join(dir, name); - if (existsSync(path)) { - return path; - } - } - } - - return null; -} - -function findWorkspaceRoot(): string { - const searchDirs = [process.cwd(), ...getParentDirs(process.cwd())]; - - for (const dir of searchDirs) { - // Check for common workspace indicators - if ( - existsSync(join(dir, 'package.json')) && - (existsSync(join(dir, 'packages')) || - existsSync(join(dir, 'apps')) || - existsSync(join(dir, 'libs'))) - ) { - return dir; - } - } - - return process.cwd(); -} - -function getParentDirs(dir: string): string[] { - const parents: string[] = []; - let current = resolve(dir); - let parent = resolve(current, '..'); - - while (parent !== current) { - parents.push(parent); - current = parent; - parent = resolve(current, '..'); - } - - return parents; -} - -function mergeConfig(base: CoverageConfig, override: Partial): CoverageConfig { - return { - ...base, - ...override, - thresholds: { - ...base.thresholds, - ...(override.thresholds || {}), - }, - }; -} \ No newline at end of file +import { existsSync, readFileSync } from 'fs'; +import { join, resolve } from 'path'; +import type { CLIOptions, CoverageConfig, ReporterType } from './types'; + +const DEFAULT_CONFIG: CoverageConfig = { + exclude: [ + '**/node_modules/**', + '**/dist/**', + '**/build/**', + '**/coverage/**', + '**/*.test.ts', + '**/*.test.js', + '**/*.spec.ts', + '**/*.spec.js', + '**/test/**', + '**/tests/**', + '**/__tests__/**', + '**/__mocks__/**', + '**/setup.ts', + '**/setup.js', + ], + reporters: ['terminal'], + thresholds: { + lines: 80, + functions: 80, + branches: 80, + statements: 80, + }, + outputDir: 'coverage', +}; + +export function loadConfig(options: CLIOptions): CoverageConfig { + let config = { ...DEFAULT_CONFIG, thresholds: { ...DEFAULT_CONFIG.thresholds } }; + + // Load from config file + const configPath = options.config || findConfigFile(); + if (configPath && existsSync(configPath)) { + try { + const fileConfig = JSON.parse(readFileSync(configPath, 'utf-8')); + config = mergeConfig(config, fileConfig); + } catch (error) { + console.warn(`Warning: Failed to load config from ${configPath}:`, error); + } + } + + // Override with CLI options + if (options.exclude && options.exclude.length > 0) { + config.exclude = options.exclude; + } + + if (options.include && options.include.length > 0) { + config.include = options.include; + } + + if (options.reporters && options.reporters.length > 0) { + const valid: ReporterType[] = [ + 'terminal', + 'html', + 'html-full', + 'markdown', + 'json', + 'text', + 'lcov', + ]; + config.reporters = options.reporters.map(reporter => { + const match = valid.find(candidate => candidate === reporter); + if (!match) { + throw new Error(`Unknown coverage reporter: ${reporter}`); + } + return match; + }); + } + + if (options.outputDir) { + config.outputDir = options.outputDir; + } + + // Handle thresholds + if (options.threshold !== undefined) { + config.thresholds = { + lines: options.threshold, + functions: options.threshold, + branches: options.threshold, + statements: options.threshold, + }; + } + + if (options.thresholdLines !== undefined) { + config.thresholds.lines = options.thresholdLines; + } + if (options.thresholdFunctions !== undefined) { + config.thresholds.functions = options.thresholdFunctions; + } + if (options.thresholdBranches !== undefined) { + config.thresholds.branches = options.thresholdBranches; + } + if (options.thresholdStatements !== undefined) { + config.thresholds.statements = options.thresholdStatements; + } + + if (options.packages) { + config.packages = options.packages; + } + + // Find workspace root + config.workspaceRoot = findWorkspaceRoot(); + + return config; +} + +function findConfigFile(): string | null { + const configNames = ['.coveragerc.json', '.coveragerc', 'coverage.config.json']; + const searchDirs = [process.cwd(), ...getParentDirs(process.cwd())]; + + for (const dir of searchDirs) { + for (const name of configNames) { + const path = join(dir, name); + if (existsSync(path)) { + return path; + } + } + } + + return null; +} + +function findWorkspaceRoot(): string { + const searchDirs = [process.cwd(), ...getParentDirs(process.cwd())]; + + for (const dir of searchDirs) { + // Check for common workspace indicators + if ( + existsSync(join(dir, 'package.json')) && + (existsSync(join(dir, 'packages')) || + existsSync(join(dir, 'apps')) || + existsSync(join(dir, 'libs'))) + ) { + return dir; + } + } + + return process.cwd(); +} + +function getParentDirs(dir: string): string[] { + const parents: string[] = []; + let current = resolve(dir); + let parent = resolve(current, '..'); + + while (parent !== current) { + parents.push(parent); + current = parent; + parent = resolve(current, '..'); + } + + return parents; +} + +function mergeConfig(base: CoverageConfig, override: Partial): CoverageConfig { + return { + ...base, + ...override, + thresholds: { + ...base.thresholds, + ...(override.thresholds || {}), + }, + }; +} diff --git a/tools/coverage-cli/src/index.ts b/tools/coverage-cli/src/index.ts index a70841f0..ca5a0fa3 100644 --- a/tools/coverage-cli/src/index.ts +++ b/tools/coverage-cli/src/index.ts @@ -1,127 +1,127 @@ -#!/usr/bin/env bun -import { Command } from 'commander'; -import { existsSync } from 'fs'; -import { resolve } from 'path'; -import chalk from 'chalk'; -import { loadConfig } from './config'; -import { CoverageRunner } from './runner'; -import { CoverageProcessor } from './processor'; -import { ReporterManager } from './reporters'; -import type { CLIOptions } from './types'; - -const program = new Command(); - -program - .name('stock-bot-coverage') - .description('Advanced coverage tool for Stock Bot with exclusion support and beautiful reporting') - .version('1.0.0') - .option('-p, --packages ', 'Run coverage for specific packages') - .option('-e, --exclude ', 'Glob patterns to exclude from coverage') - .option('-i, --include ', 'Glob patterns to include in coverage') - .option('-r, --reporters ', 'Coverage reporters (terminal, html, json, markdown, text)') - .option('-t, --threshold ', 'Set coverage threshold for all metrics', parseFloat) - .option('--threshold-lines ', 'Set line coverage threshold', parseFloat) - .option('--threshold-functions ', 'Set function coverage threshold', parseFloat) - .option('--threshold-branches ', 'Set branch coverage threshold', parseFloat) - .option('--threshold-statements ', 'Set statement coverage threshold', parseFloat) - .option('-o, --output-dir ', 'Output directory for reports') - .option('-c, --config ', 'Path to coverage config file') - .option('--fail-under', 'Exit with non-zero code if coverage is below threshold') - .action(async (options: CLIOptions) => { - try { - console.log(chalk.bold.blue('\n🚀 Stock Bot Coverage Tool\n')); - - // Load configuration - const config = loadConfig(options); - console.log(chalk.gray('Configuration loaded')); - console.log(chalk.gray(`Workspace root: ${config.workspaceRoot}`)); - console.log(chalk.gray(`Excluded patterns: ${config.exclude.length}`)); - console.log(chalk.gray(`Reporters: ${config.reporters.join(', ')}\n`)); - - // Run coverage - const runner = new CoverageRunner(config); - console.log(chalk.yellow('Running tests with coverage...\n')); - - const result = await runner.run(); - - if (!result.success) { - console.error(chalk.red('\n❌ Some tests failed')); - if (options.failUnder) { - process.exit(1); - } - } - - // Process coverage data - const processor = new CoverageProcessor(config); - const report = processor.process(result.coverage, result.testResults); - - // Generate reports - console.log(chalk.yellow('\nGenerating reports...\n')); - const reporterManager = new ReporterManager(); - await reporterManager.report(report, config.reporters, config.outputDir); - - // Check thresholds - if (options.failUnder) { - const thresholdResult = processor.checkThresholds(report); - if (!thresholdResult.passed) { - console.error(chalk.red('\n❌ Coverage thresholds not met')); - for (const failure of thresholdResult.failures) { - console.error( - chalk.red( - ` ${failure.metric}: ${failure.actual.toFixed(1)}% < ${failure.expected}%` - ) - ); - } - process.exit(1); - } - } - - console.log(chalk.green('\n✅ Coverage analysis complete!\n')); - } catch (error) { - console.error(chalk.red('\n❌ Error running coverage:'), error); - process.exit(1); - } - }); - -// Add init command to create default config -program - .command('init') - .description('Create a default .coveragerc.json configuration file') - .action(() => { - const configPath = resolve(process.cwd(), '.coveragerc.json'); - - if (existsSync(configPath)) { - console.error(chalk.red('Configuration file already exists')); - process.exit(1); - } - - const defaultConfig = { - exclude: [ - '**/node_modules/**', - '**/dist/**', - '**/build/**', - '**/coverage/**', - '**/*.test.ts', - '**/*.test.js', - '**/*.spec.ts', - '**/*.spec.js', - '**/test/**', - '**/tests/**', - '**/__tests__/**', - '**/__mocks__/**', - ], - reporters: ['terminal', 'html'], - thresholds: { - lines: 80, - functions: 80, - branches: 80, - statements: 80, - }, - outputDir: 'coverage', - }; - - require('fs').writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2)); - console.log(chalk.green(`✅ Created ${configPath}`)); - }); - -program.parse(); \ No newline at end of file +#!/usr/bin/env bun +import { existsSync } from 'fs'; +import { resolve } from 'path'; +import chalk from 'chalk'; +import { Command } from 'commander'; +import { loadConfig } from './config'; +import { CoverageProcessor } from './processor'; +import { ReporterManager } from './reporters'; +import { CoverageRunner } from './runner'; +import type { CLIOptions } from './types'; + +const program = new Command(); + +program + .name('stock-bot-coverage') + .description( + 'Advanced coverage tool for Stock Bot with exclusion support and beautiful reporting' + ) + .version('1.0.0') + .option('-p, --packages ', 'Run coverage for specific packages') + .option('-e, --exclude ', 'Glob patterns to exclude from coverage') + .option('-i, --include ', 'Glob patterns to include in coverage') + .option( + '-r, --reporters ', + 'Coverage reporters (terminal, html, json, markdown, text)' + ) + .option('-t, --threshold ', 'Set coverage threshold for all metrics', parseFloat) + .option('--threshold-lines ', 'Set line coverage threshold', parseFloat) + .option('--threshold-functions ', 'Set function coverage threshold', parseFloat) + .option('--threshold-branches ', 'Set branch coverage threshold', parseFloat) + .option('--threshold-statements ', 'Set statement coverage threshold', parseFloat) + .option('-o, --output-dir ', 'Output directory for reports') + .option('-c, --config ', 'Path to coverage config file') + .option('--fail-under', 'Exit with non-zero code if coverage is below threshold') + .action(async (options: CLIOptions) => { + try { + console.log(chalk.bold.blue('\n🚀 Stock Bot Coverage Tool\n')); + + // Load configuration + const config = loadConfig(options); + console.log(chalk.gray('Configuration loaded')); + console.log(chalk.gray(`Workspace root: ${config.workspaceRoot}`)); + console.log(chalk.gray(`Excluded patterns: ${config.exclude.length}`)); + console.log(chalk.gray(`Reporters: ${config.reporters.join(', ')}\n`)); + + // Run coverage + const runner = new CoverageRunner(config); + console.log(chalk.yellow('Running tests with coverage...\n')); + + const result = await runner.run(); + + if (!result.success) { + throw new Error(result.error || 'Tests failed or measured coverage is missing'); + } + + // Process coverage data + const processor = new CoverageProcessor(config); + const report = processor.process(result.coverage, result.testResults); + + // Generate reports + console.log(chalk.yellow('\nGenerating reports...\n')); + const reporterManager = new ReporterManager(); + await reporterManager.report(report, config.reporters, config.outputDir); + + // Check thresholds + if (options.failUnder) { + const thresholdResult = processor.checkThresholds(report); + if (!thresholdResult.passed) { + console.error(chalk.red('\n❌ Coverage thresholds not met')); + for (const failure of thresholdResult.failures) { + console.error( + chalk.red(` ${failure.metric}: ${failure.actual.toFixed(1)}% < ${failure.expected}%`) + ); + } + process.exit(1); + } + } + + console.log(chalk.green('\n✅ Coverage analysis complete!\n')); + } catch (error) { + console.error(chalk.red('\n❌ Error running coverage:'), error); + process.exit(1); + } + }); + +// Add init command to create default config +program + .command('init') + .description('Create a default .coveragerc.json configuration file') + .action(() => { + const configPath = resolve(process.cwd(), '.coveragerc.json'); + + if (existsSync(configPath)) { + console.error(chalk.red('Configuration file already exists')); + process.exit(1); + } + + const defaultConfig = { + exclude: [ + '**/node_modules/**', + '**/dist/**', + '**/build/**', + '**/coverage/**', + '**/*.test.ts', + '**/*.test.js', + '**/*.spec.ts', + '**/*.spec.js', + '**/test/**', + '**/tests/**', + '**/__tests__/**', + '**/__mocks__/**', + ], + reporters: ['terminal', 'html'], + thresholds: { + lines: 80, + functions: 80, + branches: 80, + statements: 80, + }, + outputDir: 'coverage', + }; + + require('fs').writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2)); + console.log(chalk.green(`✅ Created ${configPath}`)); + }); + +program.parse(); diff --git a/tools/coverage-cli/src/processor.ts b/tools/coverage-cli/src/processor.ts index 8f261174..404dae79 100644 --- a/tools/coverage-cli/src/processor.ts +++ b/tools/coverage-cli/src/processor.ts @@ -1,288 +1,312 @@ -import type { - CoverageConfig, - CoverageReport, - PackageCoverage, - CoverageMetric, - FileCoverage -} from './types'; - -export class CoverageProcessor { - constructor(private config: CoverageConfig) {} - - process(rawCoverage: any, testResults: any[]): CoverageReport { - // Use the package information from raw coverage if available - const packages = rawCoverage.packages - ? this.processPackagesCoverage(rawCoverage.packages) - : this.groupByPackage(rawCoverage.files, testResults); - - const overall = this.calculateOverallCoverage(packages); - - return { - timestamp: new Date().toISOString(), - packages, - overall, - config: this.config, - }; - } - - private processPackagesCoverage(packagesData: any): PackageCoverage[] { - const packages: PackageCoverage[] = []; - - for (const [packageName, packageData] of Object.entries(packagesData)) { - if (!packageData || typeof packageData !== 'object') continue; - - const pkg: PackageCoverage = { - name: packageName, - path: '', // Will be set from files if available - lines: this.createMetricFromRaw(packageData.lines), - functions: this.createMetricFromRaw(packageData.functions), - branches: this.createMetricFromRaw(packageData.branches), - statements: this.createMetricFromRaw(packageData.lines), // Often same as lines - files: [], - }; - - // Process files if available - if (packageData.files && Array.isArray(packageData.files)) { - for (const file of packageData.files) { - const fileCoverage = this.processFile(file); - pkg.files.push(fileCoverage); - - // Set package path from first file if not set - if (!pkg.path && file.path) { - pkg.path = this.getPackagePath(file.path); - } - } - } - - // Only include packages that have files with coverage data - if (pkg.files.length > 0) { - packages.push(pkg); - } - } - - return packages; - } - - private createMetricFromRaw(rawMetric: any): CoverageMetric { - if (!rawMetric || typeof rawMetric !== 'object') { - return this.createEmptyMetric(); - } - - const total = rawMetric.found || 0; - const covered = rawMetric.hit || 0; - - return { - total, - covered, - skipped: 0, - percentage: total > 0 ? (covered / total) * 100 : 100, - }; - } - - private groupByPackage(files: any[], testResults: any[]): PackageCoverage[] { - const packageMap = new Map(); - - // Group files by package - for (const file of files) { - const packageName = this.getPackageFromPath(file.path); - - if (!packageMap.has(packageName)) { - packageMap.set(packageName, { - name: packageName, - path: this.getPackagePath(file.path), - lines: this.createEmptyMetric(), - functions: this.createEmptyMetric(), - branches: this.createEmptyMetric(), - statements: this.createEmptyMetric(), - files: [], - }); - } - - const pkg = packageMap.get(packageName)!; - const fileCoverage = this.processFile(file); - - pkg.files.push(fileCoverage); - this.addMetrics(pkg.lines, fileCoverage.lines); - this.addMetrics(pkg.functions, fileCoverage.functions); - this.addMetrics(pkg.branches, fileCoverage.branches); - this.addMetrics(pkg.statements, fileCoverage.statements); - } - - // Calculate percentages for each package - const packages = Array.from(packageMap.values()); - for (const pkg of packages) { - this.calculatePercentage(pkg.lines); - this.calculatePercentage(pkg.functions); - this.calculatePercentage(pkg.branches); - this.calculatePercentage(pkg.statements); - } - - return packages; - } - - private processFile(file: any): FileCoverage { - const lines = this.createMetric(file.lines.found, file.lines.hit); - const functions = this.createMetric(file.functions.found, file.functions.hit); - const branches = this.createMetric(file.branches.found, file.branches.hit); - // Statements often equal lines in simple coverage tools - const statements = this.createMetric(file.lines.found, file.lines.hit); - - return { - path: file.path, - lines, - functions, - branches, - statements, - }; - } - - private createEmptyMetric(): CoverageMetric { - return { - total: 0, - covered: 0, - skipped: 0, - percentage: 0, - }; - } - - private createMetric(total: number, covered: number): CoverageMetric { - return { - total, - covered, - skipped: 0, - percentage: total > 0 ? (covered / total) * 100 : 100, - }; - } - - private addMetrics(target: CoverageMetric, source: CoverageMetric): void { - target.total += source.total; - target.covered += source.covered; - target.skipped += source.skipped; - } - - private calculatePercentage(metric: CoverageMetric): void { - metric.percentage = metric.total > 0 ? (metric.covered / metric.total) * 100 : 100; - } - - private calculateOverallCoverage(packages: PackageCoverage[]): CoverageReport['overall'] { - const overall = { - lines: this.createEmptyMetric(), - functions: this.createEmptyMetric(), - branches: this.createEmptyMetric(), - statements: this.createEmptyMetric(), - }; - - for (const pkg of packages) { - this.addMetrics(overall.lines, pkg.lines); - this.addMetrics(overall.functions, pkg.functions); - this.addMetrics(overall.branches, pkg.branches); - this.addMetrics(overall.statements, pkg.statements); - } - - this.calculatePercentage(overall.lines); - this.calculatePercentage(overall.functions); - this.calculatePercentage(overall.branches); - this.calculatePercentage(overall.statements); - - return overall; - } - - private getPackageFromPath(filePath: string): string { - const normalizedPath = filePath.replace(/\\/g, '/'); - - // Try to extract package name from path - const patterns = [ - /packages\/([^/]+)\//, - /apps\/stock\/([^/]+)\//, - /apps\/([^/]+)\//, - /libs\/core\/([^/]+)\//, - /libs\/data\/([^/]+)\//, - /libs\/services\/([^/]+)\//, - /libs\/([^/]+)\//, - /tools\/([^/]+)\//, - /@stock-bot\/([^/]+)\//, - ]; - - for (const pattern of patterns) { - const match = normalizedPath.match(pattern); - if (match) { - return `@stock-bot/${match[1]}`; - } - } - - // Default to root - return 'root'; - } - - private getPackagePath(filePath: string): string { - const normalizedPath = filePath.replace(/\\/g, '/'); - - // Extract package root path - const patterns = [ - /(.*\/packages\/[^/]+)\//, - /(.*\/apps\/stock\/[^/]+)\//, - /(.*\/apps\/[^/]+)\//, - /(.*\/libs\/core\/[^/]+)\//, - /(.*\/libs\/data\/[^/]+)\//, - /(.*\/libs\/services\/[^/]+)\//, - /(.*\/libs\/[^/]+)\//, - /(.*\/tools\/[^/]+)\//, - ]; - - for (const pattern of patterns) { - const match = normalizedPath.match(pattern); - if (match) { - return match[1]; - } - } - - // Default to workspace root - return this.config.workspaceRoot || process.cwd(); - } - - checkThresholds(report: CoverageReport): { - passed: boolean; - failures: Array<{ metric: string; expected: number; actual: number }>; - } { - const failures: Array<{ metric: string; expected: number; actual: number }> = []; - const { thresholds } = this.config; - const { overall } = report; - - if (thresholds.lines !== undefined && overall.lines.percentage < thresholds.lines) { - failures.push({ - metric: 'lines', - expected: thresholds.lines, - actual: overall.lines.percentage, - }); - } - - if (thresholds.functions !== undefined && overall.functions.percentage < thresholds.functions) { - failures.push({ - metric: 'functions', - expected: thresholds.functions, - actual: overall.functions.percentage, - }); - } - - if (thresholds.branches !== undefined && overall.branches.percentage < thresholds.branches) { - failures.push({ - metric: 'branches', - expected: thresholds.branches, - actual: overall.branches.percentage, - }); - } - - if (thresholds.statements !== undefined && overall.statements.percentage < thresholds.statements) { - failures.push({ - metric: 'statements', - expected: thresholds.statements, - actual: overall.statements.percentage, - }); - } - - return { - passed: failures.length === 0, - failures, - }; - } -} \ No newline at end of file +import { defined } from '@stock-bot/invariants'; +import type { + CoverageConfig, + CoverageMetric, + CoverageReport, + FileCoverage, + PackageCoverage, + RawCoverage, + RawFileCoverage, + RawMetric, +} from './types'; + +export class CoverageProcessor { + constructor(private config: CoverageConfig) {} + + process(rawCoverage: RawCoverage, testResults: unknown): CoverageReport { + // Use the package information from raw coverage if available + const packages = rawCoverage.packages + ? this.processPackagesCoverage(rawCoverage.packages) + : this.groupByPackage(rawCoverage.files, testResults); + + const overall = this.calculateOverallCoverage(packages); + + return { + timestamp: new Date().toISOString(), + packages, + overall, + config: this.config, + }; + } + + private processPackagesCoverage( + packagesData: Record< + string, + { + lines?: { found: number; hit: number }; + functions?: { found: number; hit: number }; + branches?: { found: number; hit: number }; + files?: Array<{ + path: string; + lines: { found: number; hit: number }; + functions: { found: number; hit: number }; + branches: { found: number; hit: number }; + }>; + } + > + ): PackageCoverage[] { + const packages: PackageCoverage[] = []; + + for (const [packageName, packageData] of Object.entries(packagesData)) { + if (!packageData || typeof packageData !== 'object') { + continue; + } + + const pkg: PackageCoverage = { + name: packageName, + path: '', // Will be set from files if available + lines: this.createMetricFromRaw(packageData.lines), + functions: this.createMetricFromRaw(packageData.functions), + branches: this.createMetricFromRaw(packageData.branches), + statements: this.createMetricFromRaw(packageData.lines), // Often same as lines + files: [], + }; + + // Process files if available + if (packageData.files && Array.isArray(packageData.files)) { + for (const file of packageData.files) { + const fileCoverage = this.processFile(file); + pkg.files.push(fileCoverage); + + // Set package path from first file if not set + if (!pkg.path && file.path) { + pkg.path = this.getPackagePath(file.path); + } + } + } + + // Only include packages that have files with coverage data + if (pkg.files.length > 0) { + packages.push(pkg); + } + } + + return packages; + } + + private createMetricFromRaw(rawMetric: RawMetric | undefined): CoverageMetric { + if (!rawMetric || typeof rawMetric !== 'object') { + return this.createEmptyMetric(); + } + + const total = rawMetric.found || 0; + const covered = rawMetric.hit || 0; + + return { + total, + covered, + skipped: 0, + percentage: total > 0 ? (covered / total) * 100 : 0, + }; + } + + private groupByPackage(files: RawFileCoverage[], _testResults: unknown): PackageCoverage[] { + const packageMap = new Map(); + + // Group files by package + for (const file of files) { + const packageName = this.getPackageFromPath(file.path); + + if (!packageMap.has(packageName)) { + packageMap.set(packageName, { + name: packageName, + path: this.getPackagePath(file.path), + lines: this.createEmptyMetric(), + functions: this.createEmptyMetric(), + branches: this.createEmptyMetric(), + statements: this.createEmptyMetric(), + files: [], + }); + } + + const pkg = defined(packageMap.get(packageName)); + const fileCoverage = this.processFile(file); + + pkg.files.push(fileCoverage); + this.addMetrics(pkg.lines, fileCoverage.lines); + this.addMetrics(pkg.functions, fileCoverage.functions); + this.addMetrics(pkg.branches, fileCoverage.branches); + this.addMetrics(pkg.statements, fileCoverage.statements); + } + + // Calculate percentages for each package + const packages = Array.from(packageMap.values()); + for (const pkg of packages) { + this.calculatePercentage(pkg.lines); + this.calculatePercentage(pkg.functions); + this.calculatePercentage(pkg.branches); + this.calculatePercentage(pkg.statements); + } + + return packages; + } + + private processFile(file: RawFileCoverage): FileCoverage { + const lines = this.createMetric(file.lines.found, file.lines.hit); + const functions = this.createMetric(file.functions.found, file.functions.hit); + const branches = this.createMetric(file.branches.found, file.branches.hit); + // Statements often equal lines in simple coverage tools + const statements = this.createMetric(file.lines.found, file.lines.hit); + + return { + path: file.path, + lines, + functions, + branches, + statements, + }; + } + + private createEmptyMetric(): CoverageMetric { + return { + total: 0, + covered: 0, + skipped: 0, + percentage: 0, + }; + } + + private createMetric(total: number, covered: number): CoverageMetric { + return { + total, + covered, + skipped: 0, + percentage: total > 0 ? (covered / total) * 100 : 0, + }; + } + + private addMetrics(target: CoverageMetric, source: CoverageMetric): void { + target.total += source.total; + target.covered += source.covered; + target.skipped += source.skipped; + } + + private calculatePercentage(metric: CoverageMetric): void { + metric.percentage = metric.total > 0 ? (metric.covered / metric.total) * 100 : 0; + } + + private calculateOverallCoverage(packages: PackageCoverage[]): CoverageReport['overall'] { + const overall = { + lines: this.createEmptyMetric(), + functions: this.createEmptyMetric(), + branches: this.createEmptyMetric(), + statements: this.createEmptyMetric(), + }; + + for (const pkg of packages) { + this.addMetrics(overall.lines, pkg.lines); + this.addMetrics(overall.functions, pkg.functions); + this.addMetrics(overall.branches, pkg.branches); + this.addMetrics(overall.statements, pkg.statements); + } + + this.calculatePercentage(overall.lines); + this.calculatePercentage(overall.functions); + this.calculatePercentage(overall.branches); + this.calculatePercentage(overall.statements); + + return overall; + } + + private getPackageFromPath(filePath: string): string { + const normalizedPath = filePath.replace(/\\/g, '/'); + + // Try to extract package name from path + const patterns = [ + /packages\/([^/]+)\//, + /apps\/stock\/([^/]+)\//, + /apps\/([^/]+)\//, + /libs\/core\/([^/]+)\//, + /libs\/data\/([^/]+)\//, + /libs\/services\/([^/]+)\//, + /libs\/([^/]+)\//, + /tools\/([^/]+)\//, + /@stock-bot\/([^/]+)\//, + ]; + + for (const pattern of patterns) { + const match = normalizedPath.match(pattern); + if (match) { + return `@stock-bot/${match[1]}`; + } + } + + // Default to root + return 'root'; + } + + private getPackagePath(filePath: string): string { + const normalizedPath = filePath.replace(/\\/g, '/'); + + // Extract package root path + const patterns = [ + /(.*\/packages\/[^/]+)\//, + /(.*\/apps\/stock\/[^/]+)\//, + /(.*\/apps\/[^/]+)\//, + /(.*\/libs\/core\/[^/]+)\//, + /(.*\/libs\/data\/[^/]+)\//, + /(.*\/libs\/services\/[^/]+)\//, + /(.*\/libs\/[^/]+)\//, + /(.*\/tools\/[^/]+)\//, + ]; + + for (const pattern of patterns) { + const match = normalizedPath.match(pattern); + if (match) { + return match[1] ?? this.config.workspaceRoot ?? process.cwd(); + } + } + + // Default to workspace root + return this.config.workspaceRoot || process.cwd(); + } + + checkThresholds(report: CoverageReport): { + passed: boolean; + failures: Array<{ metric: string; expected: number; actual: number }>; + } { + const failures: Array<{ metric: string; expected: number; actual: number }> = []; + const { thresholds } = this.config; + const { overall } = report; + + if (thresholds.lines !== undefined && overall.lines.percentage < thresholds.lines) { + failures.push({ + metric: 'lines', + expected: thresholds.lines, + actual: overall.lines.percentage, + }); + } + + if (thresholds.functions !== undefined && overall.functions.percentage < thresholds.functions) { + failures.push({ + metric: 'functions', + expected: thresholds.functions, + actual: overall.functions.percentage, + }); + } + + if (thresholds.branches !== undefined && overall.branches.percentage < thresholds.branches) { + failures.push({ + metric: 'branches', + expected: thresholds.branches, + actual: overall.branches.percentage, + }); + } + + if ( + thresholds.statements !== undefined && + overall.statements.percentage < thresholds.statements + ) { + failures.push({ + metric: 'statements', + expected: thresholds.statements, + actual: overall.statements.percentage, + }); + } + + return { + passed: failures.length === 0, + failures, + }; + } +} diff --git a/tools/coverage-cli/src/reporters/html-compact.ts b/tools/coverage-cli/src/reporters/html-compact.ts index dbd9768c..be0c724c 100644 --- a/tools/coverage-cli/src/reporters/html-compact.ts +++ b/tools/coverage-cli/src/reporters/html-compact.ts @@ -1,363 +1,377 @@ -import { writeFileSync, mkdirSync } from 'fs'; -import { join } from 'path'; -import type { CoverageReport, PackageCoverage } from '../types'; - -export class HtmlCompactReporter { - report(coverage: CoverageReport, outputDir: string): void { - const htmlDir = join(outputDir, 'html'); - mkdirSync(htmlDir, { recursive: true }); - - const html = this.generateHTML(coverage); - writeFileSync(join(htmlDir, 'index.html'), html); - - this.writeStyles(htmlDir); - - console.log(`HTML coverage report written to: ${join(htmlDir, 'index.html')}`); - } - - private generateHTML(report: CoverageReport): string { - const timestamp = new Date(report.timestamp).toLocaleString(); - const { overall, packages } = report; - - // Sort packages by line coverage descending - const sortedPackages = [...packages].sort((a, b) => b.lines.percentage - a.lines.percentage); - - // Filter packages with 0% coverage separately - const coveredPackages = sortedPackages.filter(p => p.lines.percentage > 0); - const uncoveredPackages = sortedPackages.filter(p => p.lines.percentage === 0); - - return ` - - - - - Coverage Report - - - -
-
-
Coverage Report
-
- Overall: - ${this.formatMetric('L', overall.lines)} - ${this.formatMetric('F', overall.functions)} - ${this.formatMetric('B', overall.branches)} - ${this.formatMetric('S', overall.statements)} -
-
${timestamp}
-
- - - - - - - - - - - - - - ${coveredPackages.map(pkg => this.generatePackageRow(pkg, report.config.thresholds)).join('\n')} - ${uncoveredPackages.length > 0 ? ` - - - - ${uncoveredPackages.map(pkg => this.generateUncoveredRow(pkg)).join('\n')} - ` : ''} - -
PackageLFBSDetails
Uncovered Packages (${uncoveredPackages.length})
-
- - -`; - } - - private formatMetric(label: string, metric: any): string { - const percentage = metric.percentage.toFixed(1); - const threshold = this.getThreshold(label); - const cssClass = this.getCoverageClass(metric.percentage, threshold); - return `${label}: ${percentage}%`; - } - - private getThreshold(label: string): number { - const map: Record = { L: 80, F: 80, B: 80, S: 80 }; - return map[label] || 80; - } - - private getCoverageClass(percentage: number, threshold: number = 80): string { - if (percentage >= threshold) return 'good'; - if (percentage >= threshold * 0.9) return 'warn'; - return 'bad'; - } - - private generatePackageRow(pkg: PackageCoverage, thresholds: any): string { - const id = pkg.name.replace(/[@/]/g, '-'); - const hasFiles = pkg.files && pkg.files.length > 0; - - return ` - - ${pkg.name} - ${pkg.lines.percentage.toFixed(1)} - ${pkg.functions.percentage.toFixed(1)} - ${pkg.branches.percentage.toFixed(1)} - ${pkg.statements.percentage.toFixed(1)} - - ${hasFiles ? `` : ''} - - - ${hasFiles ? ` - - -
- - - - - - - - - - - - ${pkg.files.map(f => this.generateFileRow(f)).join('\n')} - -
FileLFBS
-
- - ` : ''}`; - } - - private generateUncoveredRow(pkg: PackageCoverage): string { - return ` - - ${pkg.name} - 0.0 - - `; - } - - private generateFileRow(file: any): string { - const shortPath = this.shortenPath(file.path); - return ` - - ${shortPath} - ${file.lines.percentage.toFixed(1)} - ${file.functions.percentage.toFixed(1)} - ${file.branches.percentage.toFixed(1)} - ${file.statements.percentage.toFixed(1)} - `; - } - - private shortenPath(path: string): string { - const parts = path.split('/'); - const relevantParts = []; - let foundSrc = false; - - for (let i = parts.length - 1; i >= 0; i--) { - relevantParts.unshift(parts[i]); - if (parts[i] === 'src' || parts[i] === 'test') { - foundSrc = true; - if (i > 0) relevantParts.unshift(parts[i - 1]); - break; - } - } - - return foundSrc ? relevantParts.join('/') : parts.slice(-3).join('/'); - } - - private writeStyles(htmlDir: string): void { - const css = ` -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -body { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, monospace; - font-size: 13px; - line-height: 1.4; - color: #333; - background: #f5f5f5; -} - -.container-compact { - max-width: 1000px; - margin: 20px auto; - background: white; - border-radius: 8px; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); - overflow: hidden; -} - -.header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px 16px; - background: #2d3748; - color: white; -} - -.title { - font-size: 16px; - font-weight: 600; -} - -.overall { - display: flex; - gap: 12px; - align-items: center; -} - -.overall .label { - opacity: 0.8; -} - -.metric { - padding: 2px 8px; - border-radius: 3px; - font-weight: 500; - font-size: 12px; -} - -.metric.good { background: #48bb78; color: white; } -.metric.warn { background: #ed8936; color: white; } -.metric.bad { background: #f56565; color: white; } - -.timestamp { - font-size: 11px; - opacity: 0.7; -} - -.coverage-table { - width: 100%; - border-collapse: collapse; -} - -.coverage-table th { - background: #f7fafc; - padding: 8px 12px; - text-align: left; - font-weight: 600; - font-size: 12px; - border-bottom: 1px solid #e2e8f0; - color: #4a5568; -} - -.coverage-table td { - padding: 6px 12px; - border-bottom: 1px solid #f0f0f0; -} - -.coverage-table tbody tr:hover { - background: #f9f9f9; -} - -.pkg-name { - font-weight: 500; - color: #2d3748; -} - -.good { color: #22863a; font-weight: 600; } -.warn { color: #b08800; font-weight: 600; } -.bad { color: #dc3545; font-weight: 600; } -.zero { color: #999; text-align: center; } - -.details-btn button { - width: 20px; - height: 20px; - border: 1px solid #cbd5e0; - background: white; - border-radius: 3px; - cursor: pointer; - font-size: 14px; - line-height: 1; - color: #4a5568; -} - -.details-btn button:hover { - background: #e2e8f0; -} - -.separator td { - background: #f7fafc; - font-weight: 600; - color: #718096; - padding: 4px 12px; - font-size: 11px; -} - -.uncovered { - opacity: 0.6; -} - -.details-row td { - padding: 0; - background: #f9f9f9; -} - -.file-details { - padding: 12px 24px; -} - -.files-table { - width: 100%; - font-size: 12px; -} - -.files-table th { - background: #edf2f7; - padding: 4px 8px; - font-weight: 500; -} - -.files-table td { - padding: 3px 8px; - border-bottom: 1px solid #e2e8f0; -} - -.file-path { - font-family: 'Courier New', monospace; - font-size: 11px; - color: #4a5568; -} - -/* Compact mode for smaller screens */ -@media (max-width: 768px) { - .header { - flex-direction: column; - gap: 8px; - align-items: flex-start; - } - - .coverage-table { - font-size: 12px; - } - - .coverage-table th, - .coverage-table td { - padding: 4px 8px; - } -} -`; - - writeFileSync(join(htmlDir, 'styles.css'), css); - } -} \ No newline at end of file +import { mkdirSync, writeFileSync } from 'fs'; +import { join } from 'path'; +import type { CoverageReport, CoverageThresholds, FileCoverage, PackageCoverage } from '../types'; + +export class HtmlCompactReporter { + report(coverage: CoverageReport, outputDir: string): void { + const htmlDir = join(outputDir, 'html'); + mkdirSync(htmlDir, { recursive: true }); + + const html = this.generateHTML(coverage); + writeFileSync(join(htmlDir, 'index.html'), html); + + this.writeStyles(htmlDir); + + console.log(`HTML coverage report written to: ${join(htmlDir, 'index.html')}`); + } + + private generateHTML(report: CoverageReport): string { + const timestamp = new Date(report.timestamp).toLocaleString(); + const { overall, packages } = report; + + // Sort packages by line coverage descending + const sortedPackages = [...packages].sort((a, b) => b.lines.percentage - a.lines.percentage); + + // Filter packages with 0% coverage separately + const coveredPackages = sortedPackages.filter(p => p.lines.percentage > 0); + const uncoveredPackages = sortedPackages.filter(p => p.lines.percentage === 0); + + return ` + + + + + Coverage Report + + + +
+
+
Coverage Report
+
+ Overall: + ${this.formatMetric('L', overall.lines)} + ${this.formatMetric('F', overall.functions)} + ${this.formatMetric('B', overall.branches)} + ${this.formatMetric('S', overall.statements)} +
+
${timestamp}
+
+ + + + + + + + + + + + + + ${coveredPackages.map(pkg => this.generatePackageRow(pkg, report.config.thresholds)).join('\n')} + ${ + uncoveredPackages.length > 0 + ? ` + + + + ${uncoveredPackages.map(pkg => this.generateUncoveredRow(pkg)).join('\n')} + ` + : '' + } + +
PackageLFBSDetails
Uncovered Packages (${uncoveredPackages.length})
+
+ + +`; + } + + private formatMetric(label: string, metric: import('../types').CoverageMetric): string { + const percentage = metric.percentage.toFixed(1); + const threshold = this.getThreshold(label); + const cssClass = this.getCoverageClass(metric.percentage, threshold); + return `${label}: ${percentage}%`; + } + + private getThreshold(label: string): number { + const map: Record = { L: 80, F: 80, B: 80, S: 80 }; + return map[label] || 80; + } + + private getCoverageClass(percentage: number, threshold: number = 80): string { + if (percentage >= threshold) { + return 'good'; + } + if (percentage >= threshold * 0.9) { + return 'warn'; + } + return 'bad'; + } + + private generatePackageRow(pkg: PackageCoverage, thresholds: CoverageThresholds): string { + const id = pkg.name.replace(/[@/]/g, '-'); + const hasFiles = pkg.files && pkg.files.length > 0; + + return ` + + ${pkg.name} + ${pkg.lines.percentage.toFixed(1)} + ${pkg.functions.percentage.toFixed(1)} + ${pkg.branches.percentage.toFixed(1)} + ${pkg.statements.percentage.toFixed(1)} + + ${hasFiles ? `` : ''} + + + ${ + hasFiles + ? ` + + +
+ + + + + + + + + + + + ${pkg.files.map(f => this.generateFileRow(f)).join('\n')} + +
FileLFBS
+
+ + ` + : '' + }`; + } + + private generateUncoveredRow(pkg: PackageCoverage): string { + return ` + + ${pkg.name} + 0.0 + + `; + } + + private generateFileRow(file: FileCoverage): string { + const shortPath = this.shortenPath(file.path); + return ` + + ${shortPath} + ${file.lines.percentage.toFixed(1)} + ${file.functions.percentage.toFixed(1)} + ${file.branches.percentage.toFixed(1)} + ${file.statements.percentage.toFixed(1)} + `; + } + + private shortenPath(path: string): string { + const parts = path.split('/'); + const relevantParts = []; + let foundSrc = false; + + for (let i = parts.length - 1; i >= 0; i--) { + relevantParts.unshift(parts[i]); + if (parts[i] === 'src' || parts[i] === 'test') { + foundSrc = true; + if (i > 0) { + relevantParts.unshift(parts[i - 1]); + } + break; + } + } + + return foundSrc ? relevantParts.join('/') : parts.slice(-3).join('/'); + } + + private writeStyles(htmlDir: string): void { + const css = ` +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, monospace; + font-size: 13px; + line-height: 1.4; + color: #333; + background: #f5f5f5; +} + +.container-compact { + max-width: 1000px; + margin: 20px auto; + background: white; + border-radius: 8px; + box-shadow: 0 2px 4px rgba(0,0,0,0.1); + overflow: hidden; +} + +.header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + background: #2d3748; + color: white; +} + +.title { + font-size: 16px; + font-weight: 600; +} + +.overall { + display: flex; + gap: 12px; + align-items: center; +} + +.overall .label { + opacity: 0.8; +} + +.metric { + padding: 2px 8px; + border-radius: 3px; + font-weight: 500; + font-size: 12px; +} + +.metric.good { background: #48bb78; color: white; } +.metric.warn { background: #ed8936; color: white; } +.metric.bad { background: #f56565; color: white; } + +.timestamp { + font-size: 11px; + opacity: 0.7; +} + +.coverage-table { + width: 100%; + border-collapse: collapse; +} + +.coverage-table th { + background: #f7fafc; + padding: 8px 12px; + text-align: left; + font-weight: 600; + font-size: 12px; + border-bottom: 1px solid #e2e8f0; + color: #4a5568; +} + +.coverage-table td { + padding: 6px 12px; + border-bottom: 1px solid #f0f0f0; +} + +.coverage-table tbody tr:hover { + background: #f9f9f9; +} + +.pkg-name { + font-weight: 500; + color: #2d3748; +} + +.good { color: #22863a; font-weight: 600; } +.warn { color: #b08800; font-weight: 600; } +.bad { color: #dc3545; font-weight: 600; } +.zero { color: #999; text-align: center; } + +.details-btn button { + width: 20px; + height: 20px; + border: 1px solid #cbd5e0; + background: white; + border-radius: 3px; + cursor: pointer; + font-size: 14px; + line-height: 1; + color: #4a5568; +} + +.details-btn button:hover { + background: #e2e8f0; +} + +.separator td { + background: #f7fafc; + font-weight: 600; + color: #718096; + padding: 4px 12px; + font-size: 11px; +} + +.uncovered { + opacity: 0.6; +} + +.details-row td { + padding: 0; + background: #f9f9f9; +} + +.file-details { + padding: 12px 24px; +} + +.files-table { + width: 100%; + font-size: 12px; +} + +.files-table th { + background: #edf2f7; + padding: 4px 8px; + font-weight: 500; +} + +.files-table td { + padding: 3px 8px; + border-bottom: 1px solid #e2e8f0; +} + +.file-path { + font-family: 'Courier New', monospace; + font-size: 11px; + color: #4a5568; +} + +/* Compact mode for smaller screens */ +@media (max-width: 768px) { + .header { + flex-direction: column; + gap: 8px; + align-items: flex-start; + } + + .coverage-table { + font-size: 12px; + } + + .coverage-table th, + .coverage-table td { + padding: 4px 8px; + } +} +`; + + writeFileSync(join(htmlDir, 'styles.css'), css); + } +} diff --git a/tools/coverage-cli/src/reporters/html.ts b/tools/coverage-cli/src/reporters/html.ts index f0e58a1e..9959933b 100644 --- a/tools/coverage-cli/src/reporters/html.ts +++ b/tools/coverage-cli/src/reporters/html.ts @@ -1,404 +1,416 @@ -import { writeFileSync, mkdirSync, copyFileSync } from 'fs'; -import { join, dirname } from 'path'; -import Handlebars from 'handlebars'; -import type { CoverageReport } from '../types'; - -export class HtmlReporter { - private template: HandlebarsTemplateDelegate; - - constructor() { - this.registerHelpers(); - this.template = this.compileTemplate(); - } - - report(coverage: CoverageReport, outputDir: string): void { - const htmlDir = join(outputDir, 'html'); - mkdirSync(htmlDir, { recursive: true }); - - // Generate main report - const html = this.template({ - coverage, - timestamp: new Date(coverage.timestamp).toLocaleString(), - thresholds: coverage.config.thresholds, - }); - - writeFileSync(join(htmlDir, 'index.html'), html); - - // Write CSS - this.writeStyles(htmlDir); - - console.log(`HTML coverage report written to: ${join(htmlDir, 'index.html')}`); - } - - private registerHelpers(): void { - Handlebars.registerHelper('percentage', (value: number) => value.toFixed(1)); - - Handlebars.registerHelper('coverageClass', (percentage: number, threshold?: number) => { - if (!threshold) return 'neutral'; - if (percentage >= threshold) return 'good'; - if (percentage >= threshold * 0.9) return 'warning'; - return 'bad'; - }); - - Handlebars.registerHelper('coverageIcon', (percentage: number, threshold?: number) => { - if (!threshold) return ''; - if (percentage >= threshold) return '✓'; - if (percentage >= threshold * 0.9) return '⚠'; - return '✗'; - }); - - Handlebars.registerHelper('shortenPath', (path: string) => { - const parts = path.split('/'); - if (parts.length > 4) { - return '.../' + parts.slice(-3).join('/'); - } - return path; - }); - } - - private compileTemplate(): HandlebarsTemplateDelegate { - const template = ` - - - - - - Stock Bot Coverage Report - - - -
-
-

Stock Bot Coverage Report

-

Generated: {{timestamp}}

-
- -
-

Overall Coverage

-
-
-
Lines
-
- {{percentage coverage.overall.lines.percentage}}% - {{coverageIcon coverage.overall.lines.percentage thresholds.lines}} -
-
- {{coverage.overall.lines.covered}} / {{coverage.overall.lines.total}} -
-
- -
-
Functions
-
- {{percentage coverage.overall.functions.percentage}}% - {{coverageIcon coverage.overall.functions.percentage thresholds.functions}} -
-
- {{coverage.overall.functions.covered}} / {{coverage.overall.functions.total}} -
-
- -
-
Branches
-
- {{percentage coverage.overall.branches.percentage}}% - {{coverageIcon coverage.overall.branches.percentage thresholds.branches}} -
-
- {{coverage.overall.branches.covered}} / {{coverage.overall.branches.total}} -
-
- -
-
Statements
-
- {{percentage coverage.overall.statements.percentage}}% - {{coverageIcon coverage.overall.statements.percentage thresholds.statements}} -
-
- {{coverage.overall.statements.covered}} / {{coverage.overall.statements.total}} -
-
-
-
- -
-

Package Coverage

- - - - - - - - - - - - {{#each coverage.packages}} - - - - - - - - {{/each}} - -
PackageLinesFunctionsBranchesStatements
{{name}} - {{percentage lines.percentage}}% - - {{percentage functions.percentage}}% - - {{percentage branches.percentage}}% - - {{percentage statements.percentage}}% -
-
- - {{#each coverage.packages}} -
-

{{name}}

-
- - - - - - - - - - - - {{#each files}} - - - - - - - - {{/each}} - -
FileLinesFunctionsBranchesStatements
{{shortenPath path}} - {{percentage lines.percentage}}% - - {{percentage functions.percentage}}% - - {{percentage branches.percentage}}% - - {{percentage statements.percentage}}% -
-
-
- {{/each}} -
- - - `; - - return Handlebars.compile(template); - } - - private writeStyles(htmlDir: string): void { - const css = ` -:root { - --color-good: #4caf50; - --color-warning: #ff9800; - --color-bad: #f44336; - --color-neutral: #9e9e9e; - --bg-primary: #f5f5f5; - --bg-secondary: #ffffff; - --text-primary: #212121; - --text-secondary: #757575; - --border-color: #e0e0e0; -} - -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -body { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; - background-color: var(--bg-primary); - color: var(--text-primary); - line-height: 1.6; -} - -.container { - max-width: 1200px; - margin: 0 auto; - padding: 2rem; -} - -header { - text-align: center; - margin-bottom: 3rem; -} - -h1 { - font-size: 2.5rem; - margin-bottom: 0.5rem; -} - -.timestamp { - color: var(--text-secondary); -} - -.summary { - background: var(--bg-secondary); - border-radius: 8px; - padding: 2rem; - margin-bottom: 2rem; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); -} - -.metrics { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 1.5rem; - margin-top: 1.5rem; -} - -.metric { - text-align: center; - padding: 1.5rem; - border-radius: 8px; - background: var(--bg-primary); -} - -.metric.good { - border: 2px solid var(--color-good); -} - -.metric.warning { - border: 2px solid var(--color-warning); -} - -.metric.bad { - border: 2px solid var(--color-bad); -} - -.metric.neutral { - border: 2px solid var(--color-neutral); -} - -.metric-name { - font-size: 0.875rem; - color: var(--text-secondary); - text-transform: uppercase; - letter-spacing: 0.05em; -} - -.metric-value { - font-size: 2rem; - font-weight: bold; - margin: 0.5rem 0; -} - -.metric-detail { - font-size: 0.875rem; - color: var(--text-secondary); -} - -.icon { - margin-left: 0.5rem; -} - -.packages { - background: var(--bg-secondary); - border-radius: 8px; - padding: 2rem; - margin-bottom: 2rem; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); -} - -table { - width: 100%; - border-collapse: collapse; - margin-top: 1rem; -} - -th, td { - padding: 0.75rem; - text-align: left; - border-bottom: 1px solid var(--border-color); -} - -th { - font-weight: 600; - color: var(--text-secondary); - text-transform: uppercase; - font-size: 0.875rem; -} - -.package-name { - font-weight: 500; -} - -.good { - color: var(--color-good); - font-weight: 500; -} - -.warning { - color: var(--color-warning); - font-weight: 500; -} - -.bad { - color: var(--color-bad); - font-weight: 500; -} - -.neutral { - color: var(--color-neutral); -} - -.package-details { - background: var(--bg-secondary); - border-radius: 8px; - padding: 2rem; - margin-bottom: 2rem; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); -} - -.package-details h3 { - margin-bottom: 1rem; -} - -.file-path { - font-family: 'Courier New', Courier, monospace; - font-size: 0.875rem; -} - -.file-list { - max-height: 400px; - overflow-y: auto; -} - -@media (max-width: 768px) { - .container { - padding: 1rem; - } - - .metrics { - grid-template-columns: 1fr; - } - - table { - font-size: 0.875rem; - } - - th, td { - padding: 0.5rem; - } -} - `; - - writeFileSync(join(htmlDir, 'styles.css'), css); - } -} \ No newline at end of file +import { mkdirSync, writeFileSync } from 'fs'; +import { join } from 'path'; +import Handlebars from 'handlebars'; +import type { CoverageReport } from '../types'; + +export class HtmlReporter { + private template: HandlebarsTemplateDelegate; + + constructor() { + this.registerHelpers(); + this.template = this.compileTemplate(); + } + + report(coverage: CoverageReport, outputDir: string): void { + const htmlDir = join(outputDir, 'html'); + mkdirSync(htmlDir, { recursive: true }); + + // Generate main report + const html = this.template({ + coverage, + timestamp: new Date(coverage.timestamp).toLocaleString(), + thresholds: coverage.config.thresholds, + }); + + writeFileSync(join(htmlDir, 'index.html'), html); + + // Write CSS + this.writeStyles(htmlDir); + + console.log(`HTML coverage report written to: ${join(htmlDir, 'index.html')}`); + } + + private registerHelpers(): void { + Handlebars.registerHelper('percentage', (value: number) => value.toFixed(1)); + + Handlebars.registerHelper('coverageClass', (percentage: number, threshold?: number) => { + if (!threshold) { + return 'neutral'; + } + if (percentage >= threshold) { + return 'good'; + } + if (percentage >= threshold * 0.9) { + return 'warning'; + } + return 'bad'; + }); + + Handlebars.registerHelper('coverageIcon', (percentage: number, threshold?: number) => { + if (!threshold) { + return ''; + } + if (percentage >= threshold) { + return '✓'; + } + if (percentage >= threshold * 0.9) { + return '⚠'; + } + return '✗'; + }); + + Handlebars.registerHelper('shortenPath', (path: string) => { + const parts = path.split('/'); + if (parts.length > 4) { + return '.../' + parts.slice(-3).join('/'); + } + return path; + }); + } + + private compileTemplate(): HandlebarsTemplateDelegate { + const template = ` + + + + + + Stock Bot Coverage Report + + + +
+
+

Stock Bot Coverage Report

+

Generated: {{timestamp}}

+
+ +
+

Overall Coverage

+
+
+
Lines
+
+ {{percentage coverage.overall.lines.percentage}}% + {{coverageIcon coverage.overall.lines.percentage thresholds.lines}} +
+
+ {{coverage.overall.lines.covered}} / {{coverage.overall.lines.total}} +
+
+ +
+
Functions
+
+ {{percentage coverage.overall.functions.percentage}}% + {{coverageIcon coverage.overall.functions.percentage thresholds.functions}} +
+
+ {{coverage.overall.functions.covered}} / {{coverage.overall.functions.total}} +
+
+ +
+
Branches
+
+ {{percentage coverage.overall.branches.percentage}}% + {{coverageIcon coverage.overall.branches.percentage thresholds.branches}} +
+
+ {{coverage.overall.branches.covered}} / {{coverage.overall.branches.total}} +
+
+ +
+
Statements
+
+ {{percentage coverage.overall.statements.percentage}}% + {{coverageIcon coverage.overall.statements.percentage thresholds.statements}} +
+
+ {{coverage.overall.statements.covered}} / {{coverage.overall.statements.total}} +
+
+
+
+ +
+

Package Coverage

+ + + + + + + + + + + + {{#each coverage.packages}} + + + + + + + + {{/each}} + +
PackageLinesFunctionsBranchesStatements
{{name}} + {{percentage lines.percentage}}% + + {{percentage functions.percentage}}% + + {{percentage branches.percentage}}% + + {{percentage statements.percentage}}% +
+
+ + {{#each coverage.packages}} +
+

{{name}}

+
+ + + + + + + + + + + + {{#each files}} + + + + + + + + {{/each}} + +
FileLinesFunctionsBranchesStatements
{{shortenPath path}} + {{percentage lines.percentage}}% + + {{percentage functions.percentage}}% + + {{percentage branches.percentage}}% + + {{percentage statements.percentage}}% +
+
+
+ {{/each}} +
+ + + `; + + return Handlebars.compile(template); + } + + private writeStyles(htmlDir: string): void { + const css = ` +:root { + --color-good: #4caf50; + --color-warning: #ff9800; + --color-bad: #f44336; + --color-neutral: #9e9e9e; + --bg-primary: #f5f5f5; + --bg-secondary: #ffffff; + --text-primary: #212121; + --text-secondary: #757575; + --border-color: #e0e0e0; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; + background-color: var(--bg-primary); + color: var(--text-primary); + line-height: 1.6; +} + +.container { + max-width: 1200px; + margin: 0 auto; + padding: 2rem; +} + +header { + text-align: center; + margin-bottom: 3rem; +} + +h1 { + font-size: 2.5rem; + margin-bottom: 0.5rem; +} + +.timestamp { + color: var(--text-secondary); +} + +.summary { + background: var(--bg-secondary); + border-radius: 8px; + padding: 2rem; + margin-bottom: 2rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +.metrics { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 1.5rem; + margin-top: 1.5rem; +} + +.metric { + text-align: center; + padding: 1.5rem; + border-radius: 8px; + background: var(--bg-primary); +} + +.metric.good { + border: 2px solid var(--color-good); +} + +.metric.warning { + border: 2px solid var(--color-warning); +} + +.metric.bad { + border: 2px solid var(--color-bad); +} + +.metric.neutral { + border: 2px solid var(--color-neutral); +} + +.metric-name { + font-size: 0.875rem; + color: var(--text-secondary); + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.metric-value { + font-size: 2rem; + font-weight: bold; + margin: 0.5rem 0; +} + +.metric-detail { + font-size: 0.875rem; + color: var(--text-secondary); +} + +.icon { + margin-left: 0.5rem; +} + +.packages { + background: var(--bg-secondary); + border-radius: 8px; + padding: 2rem; + margin-bottom: 2rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +table { + width: 100%; + border-collapse: collapse; + margin-top: 1rem; +} + +th, td { + padding: 0.75rem; + text-align: left; + border-bottom: 1px solid var(--border-color); +} + +th { + font-weight: 600; + color: var(--text-secondary); + text-transform: uppercase; + font-size: 0.875rem; +} + +.package-name { + font-weight: 500; +} + +.good { + color: var(--color-good); + font-weight: 500; +} + +.warning { + color: var(--color-warning); + font-weight: 500; +} + +.bad { + color: var(--color-bad); + font-weight: 500; +} + +.neutral { + color: var(--color-neutral); +} + +.package-details { + background: var(--bg-secondary); + border-radius: 8px; + padding: 2rem; + margin-bottom: 2rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +.package-details h3 { + margin-bottom: 1rem; +} + +.file-path { + font-family: 'Courier New', Courier, monospace; + font-size: 0.875rem; +} + +.file-list { + max-height: 400px; + overflow-y: auto; +} + +@media (max-width: 768px) { + .container { + padding: 1rem; + } + + .metrics { + grid-template-columns: 1fr; + } + + table { + font-size: 0.875rem; + } + + th, td { + padding: 0.5rem; + } +} + `; + + writeFileSync(join(htmlDir, 'styles.css'), css); + } +} diff --git a/tools/coverage-cli/src/reporters/index.ts b/tools/coverage-cli/src/reporters/index.ts index e4105c8a..b45b9840 100644 --- a/tools/coverage-cli/src/reporters/index.ts +++ b/tools/coverage-cli/src/reporters/index.ts @@ -1,38 +1,44 @@ -import { TerminalReporter } from './terminal'; -import { JsonReporter } from './json'; -import { MarkdownReporter } from './markdown'; -import { HtmlReporter } from './html'; -import { HtmlCompactReporter } from './html-compact'; -import { TextReporter } from './text'; -import type { CoverageReport, ReporterType } from '../types'; - -export class ReporterManager { - private reporters = { - terminal: new TerminalReporter(), - json: new JsonReporter(), - markdown: new MarkdownReporter(), - html: new HtmlCompactReporter(), // Use compact HTML by default - 'html-full': new HtmlReporter(), // Keep full HTML as option - text: new TextReporter(), - }; - - async report(coverage: CoverageReport, reporters: ReporterType[], outputDir: string): Promise { - for (const reporterType of reporters) { - try { - const reporter = this.reporters[reporterType]; - if (!reporter) { - console.warn(`Unknown reporter type: ${reporterType}`); - continue; - } - - if (reporterType === 'terminal') { - reporter.report(coverage); - } else { - reporter.report(coverage, outputDir); - } - } catch (error) { - console.error(`Error running ${reporterType} reporter:`, error); - } - } - } -} \ No newline at end of file +import type { CoverageReport, ReporterType } from '../types'; +import { HtmlReporter } from './html'; +import { HtmlCompactReporter } from './html-compact'; +import { JsonReporter } from './json'; +import { MarkdownReporter } from './markdown'; +import { TerminalReporter } from './terminal'; +import { TextReporter } from './text'; + +export class ReporterManager { + private reporters: Partial< + Record + > = { + terminal: new TerminalReporter(), + json: new JsonReporter(), + markdown: new MarkdownReporter(), + html: new HtmlCompactReporter(), // Use compact HTML by default + 'html-full': new HtmlReporter(), // Keep full HTML as option + text: new TextReporter(), + }; + + async report( + coverage: CoverageReport, + reporters: ReporterType[], + outputDir: string + ): Promise { + for (const reporterType of reporters) { + try { + const reporter = this.reporters[reporterType]; + if (!reporter) { + console.warn(`Unknown reporter type: ${reporterType}`); + continue; + } + + if (reporterType === 'terminal') { + reporter.report(coverage); + } else { + reporter.report(coverage, outputDir); + } + } catch (error) { + console.error(`Error running ${reporterType} reporter:`, error); + } + } + } +} diff --git a/tools/coverage-cli/src/reporters/markdown.ts b/tools/coverage-cli/src/reporters/markdown.ts index 03e40923..31ab1f66 100644 --- a/tools/coverage-cli/src/reporters/markdown.ts +++ b/tools/coverage-cli/src/reporters/markdown.ts @@ -1,165 +1,190 @@ -import { writeFileSync } from 'fs'; -import { join } from 'path'; -import type { CoverageReport, PackageCoverage, CoverageMetric } from '../types'; - -export class MarkdownReporter { - report(coverage: CoverageReport, outputDir: string): void { - const outputPath = join(outputDir, 'coverage.md'); - const content = this.generateMarkdown(coverage); - - writeFileSync(outputPath, content); - console.log(`Markdown coverage report written to: ${outputPath}`); - } - - private generateMarkdown(coverage: CoverageReport): string { - const lines: string[] = []; - - // Header - lines.push('# Coverage Report'); - lines.push(''); - lines.push(`Generated: ${new Date(coverage.timestamp).toLocaleString()}`); - lines.push(''); - - // Overall Summary - lines.push('## Overall Coverage'); - lines.push(''); - lines.push(this.generateSummaryTable(coverage.overall, coverage.config.thresholds)); - lines.push(''); - - // Package Details - if (coverage.packages.length > 0) { - lines.push('## Package Coverage'); - lines.push(''); - lines.push(this.generatePackageTable(coverage)); - lines.push(''); - - // Detailed package breakdowns - lines.push('## Package Details'); - lines.push(''); - - for (const pkg of coverage.packages) { - lines.push(`### ${pkg.name}`); - lines.push(''); - lines.push(this.generatePackageDetails(pkg)); - lines.push(''); - } - } - - // Thresholds - lines.push('## Coverage Thresholds'); - lines.push(''); - lines.push('| Metric | Threshold | Actual | Status |'); - lines.push('|--------|-----------|---------|---------|'); - - const metrics = ['lines', 'functions', 'branches', 'statements'] as const; - for (const metric of metrics) { - const threshold = coverage.config.thresholds[metric]; - const actual = coverage.overall[metric].percentage; - const status = this.getStatus(actual, threshold); - - lines.push(`| ${this.capitalize(metric)} | ${threshold || 'N/A'}% | ${actual.toFixed(1)}% | ${status} |`); - } - - return lines.join('\n'); - } - - private generateSummaryTable(overall: CoverageReport['overall'], thresholds: any): string { - const lines: string[] = []; - - lines.push('| Metric | Coverage | Total | Covered |'); - lines.push('|--------|----------|--------|----------|'); - - const metrics = ['lines', 'functions', 'branches', 'statements'] as const; - for (const metric of metrics) { - const data = overall[metric]; - const icon = this.getIcon(data.percentage, thresholds[metric]); - - lines.push( - `| ${this.capitalize(metric)} | ${data.percentage.toFixed(1)}% ${icon} | ${data.total} | ${data.covered} |` - ); - } - - return lines.join('\n'); - } - - private generatePackageTable(coverage: CoverageReport): string { - const lines: string[] = []; - - lines.push('| Package | Lines | Functions | Branches | Statements |'); - lines.push('|---------|--------|-----------|----------|------------|'); - - for (const pkg of coverage.packages) { - lines.push( - `| ${pkg.name} | ${this.formatMetric(pkg.lines)} | ${this.formatMetric(pkg.functions)} | ${this.formatMetric(pkg.branches)} | ${this.formatMetric(pkg.statements)} |` - ); - } - - lines.push(`| **Overall** | **${this.formatMetric(coverage.overall.lines)}** | **${this.formatMetric(coverage.overall.functions)}** | **${this.formatMetric(coverage.overall.branches)}** | **${this.formatMetric(coverage.overall.statements)}** |`); - - return lines.join('\n'); - } - - private generatePackageDetails(pkg: PackageCoverage): string { - const lines: string[] = []; - - // Summary - lines.push(`**Coverage Summary:**`); - lines.push(`- Lines: ${pkg.lines.percentage.toFixed(1)}% (${pkg.lines.covered}/${pkg.lines.total})`); - lines.push(`- Functions: ${pkg.functions.percentage.toFixed(1)}% (${pkg.functions.covered}/${pkg.functions.total})`); - lines.push(`- Branches: ${pkg.branches.percentage.toFixed(1)}% (${pkg.branches.covered}/${pkg.branches.total})`); - lines.push(`- Statements: ${pkg.statements.percentage.toFixed(1)}% (${pkg.statements.covered}/${pkg.statements.total})`); - lines.push(''); - - // File breakdown (top 10 least covered) - const sortedFiles = [...pkg.files] - .sort((a, b) => a.lines.percentage - b.lines.percentage) - .slice(0, 10); - - if (sortedFiles.length > 0) { - lines.push('**Least Covered Files:**'); - lines.push(''); - lines.push('| File | Lines | Functions | Branches |'); - lines.push('|------|--------|-----------|----------|'); - - for (const file of sortedFiles) { - const shortPath = this.shortenPath(file.path); - lines.push( - `| ${shortPath} | ${file.lines.percentage.toFixed(1)}% | ${file.functions.percentage.toFixed(1)}% | ${file.branches.percentage.toFixed(1)}% |` - ); - } - } - - return lines.join('\n'); - } - - private formatMetric(metric: CoverageMetric): string { - return `${metric.percentage.toFixed(1)}%`; - } - - private getIcon(percentage: number, threshold?: number): string { - if (!threshold) return ''; - - if (percentage >= threshold) return '✅'; - if (percentage >= threshold * 0.9) return '⚠️'; - return '❌'; - } - - private getStatus(percentage: number, threshold?: number): string { - if (!threshold) return '➖'; - - if (percentage >= threshold) return '✅ Pass'; - return '❌ Fail'; - } - - private capitalize(str: string): string { - return str.charAt(0).toUpperCase() + str.slice(1); - } - - private shortenPath(path: string): string { - const parts = path.split('/'); - if (parts.length > 4) { - return '.../' + parts.slice(-3).join('/'); - } - return path; - } -} \ No newline at end of file +import { writeFileSync } from 'fs'; +import { join } from 'path'; +import type { CoverageMetric, CoverageReport, CoverageThresholds, PackageCoverage } from '../types'; + +export class MarkdownReporter { + report(coverage: CoverageReport, outputDir: string): void { + const outputPath = join(outputDir, 'coverage.md'); + const content = this.generateMarkdown(coverage); + + writeFileSync(outputPath, content); + console.log(`Markdown coverage report written to: ${outputPath}`); + } + + private generateMarkdown(coverage: CoverageReport): string { + const lines: string[] = []; + + // Header + lines.push('# Coverage Report'); + lines.push(''); + lines.push(`Generated: ${new Date(coverage.timestamp).toLocaleString()}`); + lines.push(''); + + // Overall Summary + lines.push('## Overall Coverage'); + lines.push(''); + lines.push(this.generateSummaryTable(coverage.overall, coverage.config.thresholds)); + lines.push(''); + + // Package Details + if (coverage.packages.length > 0) { + lines.push('## Package Coverage'); + lines.push(''); + lines.push(this.generatePackageTable(coverage)); + lines.push(''); + + // Detailed package breakdowns + lines.push('## Package Details'); + lines.push(''); + + for (const pkg of coverage.packages) { + lines.push(`### ${pkg.name}`); + lines.push(''); + lines.push(this.generatePackageDetails(pkg)); + lines.push(''); + } + } + + // Thresholds + lines.push('## Coverage Thresholds'); + lines.push(''); + lines.push('| Metric | Threshold | Actual | Status |'); + lines.push('|--------|-----------|---------|---------|'); + + const metrics = ['lines', 'functions', 'branches', 'statements'] as const; + for (const metric of metrics) { + const threshold = coverage.config.thresholds[metric]; + const actual = coverage.overall[metric].percentage; + const status = this.getStatus(actual, threshold); + + lines.push( + `| ${this.capitalize(metric)} | ${threshold || 'N/A'}% | ${actual.toFixed(1)}% | ${status} |` + ); + } + + return lines.join('\n'); + } + + private generateSummaryTable( + overall: CoverageReport['overall'], + thresholds: CoverageThresholds + ): string { + const lines: string[] = []; + + lines.push('| Metric | Coverage | Total | Covered |'); + lines.push('|--------|----------|--------|----------|'); + + const metrics = ['lines', 'functions', 'branches', 'statements'] as const; + for (const metric of metrics) { + const data = overall[metric]; + const icon = this.getIcon(data.percentage, thresholds[metric]); + + lines.push( + `| ${this.capitalize(metric)} | ${data.percentage.toFixed(1)}% ${icon} | ${data.total} | ${data.covered} |` + ); + } + + return lines.join('\n'); + } + + private generatePackageTable(coverage: CoverageReport): string { + const lines: string[] = []; + + lines.push('| Package | Lines | Functions | Branches | Statements |'); + lines.push('|---------|--------|-----------|----------|------------|'); + + for (const pkg of coverage.packages) { + lines.push( + `| ${pkg.name} | ${this.formatMetric(pkg.lines)} | ${this.formatMetric(pkg.functions)} | ${this.formatMetric(pkg.branches)} | ${this.formatMetric(pkg.statements)} |` + ); + } + + lines.push( + `| **Overall** | **${this.formatMetric(coverage.overall.lines)}** | **${this.formatMetric(coverage.overall.functions)}** | **${this.formatMetric(coverage.overall.branches)}** | **${this.formatMetric(coverage.overall.statements)}** |` + ); + + return lines.join('\n'); + } + + private generatePackageDetails(pkg: PackageCoverage): string { + const lines: string[] = []; + + // Summary + lines.push(`**Coverage Summary:**`); + lines.push( + `- Lines: ${pkg.lines.percentage.toFixed(1)}% (${pkg.lines.covered}/${pkg.lines.total})` + ); + lines.push( + `- Functions: ${pkg.functions.percentage.toFixed(1)}% (${pkg.functions.covered}/${pkg.functions.total})` + ); + lines.push( + `- Branches: ${pkg.branches.percentage.toFixed(1)}% (${pkg.branches.covered}/${pkg.branches.total})` + ); + lines.push( + `- Statements: ${pkg.statements.percentage.toFixed(1)}% (${pkg.statements.covered}/${pkg.statements.total})` + ); + lines.push(''); + + // File breakdown (top 10 least covered) + const sortedFiles = [...pkg.files] + .sort((a, b) => a.lines.percentage - b.lines.percentage) + .slice(0, 10); + + if (sortedFiles.length > 0) { + lines.push('**Least Covered Files:**'); + lines.push(''); + lines.push('| File | Lines | Functions | Branches |'); + lines.push('|------|--------|-----------|----------|'); + + for (const file of sortedFiles) { + const shortPath = this.shortenPath(file.path); + lines.push( + `| ${shortPath} | ${file.lines.percentage.toFixed(1)}% | ${file.functions.percentage.toFixed(1)}% | ${file.branches.percentage.toFixed(1)}% |` + ); + } + } + + return lines.join('\n'); + } + + private formatMetric(metric: CoverageMetric): string { + return `${metric.percentage.toFixed(1)}%`; + } + + private getIcon(percentage: number, threshold?: number): string { + if (!threshold) { + return ''; + } + + if (percentage >= threshold) { + return '✅'; + } + if (percentage >= threshold * 0.9) { + return '⚠️'; + } + return '❌'; + } + + private getStatus(percentage: number, threshold?: number): string { + if (!threshold) { + return '➖'; + } + + if (percentage >= threshold) { + return '✅ Pass'; + } + return '❌ Fail'; + } + + private capitalize(str: string): string { + return str.charAt(0).toUpperCase() + str.slice(1); + } + + private shortenPath(path: string): string { + const parts = path.split('/'); + if (parts.length > 4) { + return '.../' + parts.slice(-3).join('/'); + } + return path; + } +} diff --git a/tools/coverage-cli/src/reporters/terminal.ts b/tools/coverage-cli/src/reporters/terminal.ts index 4e9d5dca..419b8e3f 100644 --- a/tools/coverage-cli/src/reporters/terminal.ts +++ b/tools/coverage-cli/src/reporters/terminal.ts @@ -1,176 +1,200 @@ -import chalk from 'chalk'; -import { table } from 'table'; -import type { CoverageReport, PackageCoverage, CoverageMetric } from '../types'; - -export class TerminalReporter { - report(coverage: CoverageReport): void { - console.log('\n' + chalk.bold.cyan('═'.repeat(60))); - console.log(chalk.bold.cyan(' Stock Bot Coverage Report')); - console.log(chalk.bold.cyan('═'.repeat(60)) + '\n'); - - // Package-level coverage - if (coverage.packages.length > 0) { - this.printPackageTable(coverage); - } - - // Overall summary - this.printOverallSummary(coverage); - - // Threshold warnings - this.printThresholdWarnings(coverage); - } - - private printPackageTable(coverage: CoverageReport): void { - const data: any[][] = [ - [ - chalk.bold('Package'), - chalk.bold('Lines'), - chalk.bold('Functions'), - chalk.bold('Branches'), - chalk.bold('Statements'), - ], - ]; - - for (const pkg of coverage.packages) { - data.push([ - chalk.cyan(pkg.name), - this.formatMetric(pkg.lines, coverage.config.thresholds.lines), - this.formatMetric(pkg.functions, coverage.config.thresholds.functions), - this.formatMetric(pkg.branches, coverage.config.thresholds.branches), - this.formatMetric(pkg.statements, coverage.config.thresholds.statements), - ]); - } - - // Add separator - data.push([ - chalk.gray('─'.repeat(20)), - chalk.gray('─'.repeat(10)), - chalk.gray('─'.repeat(10)), - chalk.gray('─'.repeat(10)), - chalk.gray('─'.repeat(10)), - ]); - - // Add overall - data.push([ - chalk.bold('Overall'), - this.formatMetric(coverage.overall.lines, coverage.config.thresholds.lines), - this.formatMetric(coverage.overall.functions, coverage.config.thresholds.functions), - this.formatMetric(coverage.overall.branches, coverage.config.thresholds.branches), - this.formatMetric(coverage.overall.statements, coverage.config.thresholds.statements), - ]); - - const config = { - border: { - topBody: '─', - topJoin: '┬', - topLeft: '┌', - topRight: '┐', - bottomBody: '─', - bottomJoin: '┴', - bottomLeft: '└', - bottomRight: '┘', - bodyLeft: '│', - bodyRight: '│', - bodyJoin: '│', - joinBody: '─', - joinLeft: '├', - joinRight: '┤', - joinJoin: '┼', - }, - }; - - console.log(table(data, config)); - } - - private formatMetric(metric: CoverageMetric, threshold?: number): string { - const percentage = metric.percentage.toFixed(1); - const icon = this.getIcon(metric.percentage, threshold); - const color = this.getColor(metric.percentage, threshold); - - return color(`${percentage}% ${icon}`); - } - - private getIcon(percentage: number, threshold?: number): string { - if (!threshold) return ''; - - if (percentage >= threshold) return '✓'; - if (percentage >= threshold * 0.9) return '⚠'; - return '✗'; - } - - private getColor(percentage: number, threshold?: number): (text: string) => string { - if (!threshold) return chalk.white; - - if (percentage >= threshold) return chalk.green; - if (percentage >= threshold * 0.9) return chalk.yellow; - return chalk.red; - } - - private printOverallSummary(coverage: CoverageReport): void { - const { packages, config } = coverage; - const passingPackages = packages.filter(pkg => - this.packageMeetsThresholds(pkg, config.thresholds) - ).length; - - const warningPackages = packages.filter(pkg => { - const meetsThresholds = this.packageMeetsThresholds(pkg, config.thresholds); - const almostMeets = this.packageAlmostMeetsThresholds(pkg, config.thresholds); - return !meetsThresholds && almostMeets; - }).length; - - const failingPackages = packages.length - passingPackages - warningPackages; - - console.log(chalk.green(`✓ ${passingPackages} packages meet coverage thresholds`)); - - if (warningPackages > 0) { - console.log(chalk.yellow(`⚠ ${warningPackages} packages below threshold`)); - } - - if (failingPackages > 0) { - console.log(chalk.red(`✗ ${failingPackages} packages critically low`)); - } - } - - private packageMeetsThresholds(pkg: PackageCoverage, thresholds: any): boolean { - return ( - (!thresholds.lines || pkg.lines.percentage >= thresholds.lines) && - (!thresholds.functions || pkg.functions.percentage >= thresholds.functions) && - (!thresholds.branches || pkg.branches.percentage >= thresholds.branches) && - (!thresholds.statements || pkg.statements.percentage >= thresholds.statements) - ); - } - - private packageAlmostMeetsThresholds(pkg: PackageCoverage, thresholds: any): boolean { - return ( - (!thresholds.lines || pkg.lines.percentage >= thresholds.lines * 0.9) && - (!thresholds.functions || pkg.functions.percentage >= thresholds.functions * 0.9) && - (!thresholds.branches || pkg.branches.percentage >= thresholds.branches * 0.9) && - (!thresholds.statements || pkg.statements.percentage >= thresholds.statements * 0.9) - ); - } - - private printThresholdWarnings(coverage: CoverageReport): void { - const { overall, config } = coverage; - const failures: string[] = []; - - if (config.thresholds.lines && overall.lines.percentage < config.thresholds.lines) { - failures.push(`Lines: ${overall.lines.percentage.toFixed(1)}% < ${config.thresholds.lines}%`); - } - if (config.thresholds.functions && overall.functions.percentage < config.thresholds.functions) { - failures.push(`Functions: ${overall.functions.percentage.toFixed(1)}% < ${config.thresholds.functions}%`); - } - if (config.thresholds.branches && overall.branches.percentage < config.thresholds.branches) { - failures.push(`Branches: ${overall.branches.percentage.toFixed(1)}% < ${config.thresholds.branches}%`); - } - if (config.thresholds.statements && overall.statements.percentage < config.thresholds.statements) { - failures.push(`Statements: ${overall.statements.percentage.toFixed(1)}% < ${config.thresholds.statements}%`); - } - - if (failures.length > 0) { - console.log('\n' + chalk.red.bold('Coverage thresholds not met:')); - failures.forEach(failure => console.log(chalk.red(` • ${failure}`))); - } - - console.log('\n' + chalk.gray(`Run 'stock-bot-coverage --reporter html' for detailed report`)); - } -} \ No newline at end of file +import chalk from 'chalk'; +import { table } from 'table'; +import type { CoverageMetric, CoverageReport, CoverageThresholds, PackageCoverage } from '../types'; + +export class TerminalReporter { + report(coverage: CoverageReport): void { + console.log('\n' + chalk.bold.cyan('═'.repeat(60))); + console.log(chalk.bold.cyan(' Stock Bot Coverage Report')); + console.log(chalk.bold.cyan('═'.repeat(60)) + '\n'); + + // Package-level coverage + if (coverage.packages.length > 0) { + this.printPackageTable(coverage); + } + + // Overall summary + this.printOverallSummary(coverage); + + // Threshold warnings + this.printThresholdWarnings(coverage); + } + + private printPackageTable(coverage: CoverageReport): void { + const data: string[][] = [ + [ + chalk.bold('Package'), + chalk.bold('Lines'), + chalk.bold('Functions'), + chalk.bold('Branches'), + chalk.bold('Statements'), + ], + ]; + + for (const pkg of coverage.packages) { + data.push([ + chalk.cyan(pkg.name), + this.formatMetric(pkg.lines, coverage.config.thresholds.lines), + this.formatMetric(pkg.functions, coverage.config.thresholds.functions), + this.formatMetric(pkg.branches, coverage.config.thresholds.branches), + this.formatMetric(pkg.statements, coverage.config.thresholds.statements), + ]); + } + + // Add separator + data.push([ + chalk.gray('─'.repeat(20)), + chalk.gray('─'.repeat(10)), + chalk.gray('─'.repeat(10)), + chalk.gray('─'.repeat(10)), + chalk.gray('─'.repeat(10)), + ]); + + // Add overall + data.push([ + chalk.bold('Overall'), + this.formatMetric(coverage.overall.lines, coverage.config.thresholds.lines), + this.formatMetric(coverage.overall.functions, coverage.config.thresholds.functions), + this.formatMetric(coverage.overall.branches, coverage.config.thresholds.branches), + this.formatMetric(coverage.overall.statements, coverage.config.thresholds.statements), + ]); + + const config = { + border: { + topBody: '─', + topJoin: '┬', + topLeft: '┌', + topRight: '┐', + bottomBody: '─', + bottomJoin: '┴', + bottomLeft: '└', + bottomRight: '┘', + bodyLeft: '│', + bodyRight: '│', + bodyJoin: '│', + joinBody: '─', + joinLeft: '├', + joinRight: '┤', + joinJoin: '┼', + }, + }; + + console.log(table(data, config)); + } + + private formatMetric(metric: CoverageMetric, threshold?: number): string { + const percentage = metric.percentage.toFixed(1); + const icon = this.getIcon(metric.percentage, threshold); + const color = this.getColor(metric.percentage, threshold); + + return color(`${percentage}% ${icon}`); + } + + private getIcon(percentage: number, threshold?: number): string { + if (!threshold) { + return ''; + } + + if (percentage >= threshold) { + return '✓'; + } + if (percentage >= threshold * 0.9) { + return '⚠'; + } + return '✗'; + } + + private getColor(percentage: number, threshold?: number): (text: string) => string { + if (!threshold) { + return chalk.white; + } + + if (percentage >= threshold) { + return chalk.green; + } + if (percentage >= threshold * 0.9) { + return chalk.yellow; + } + return chalk.red; + } + + private printOverallSummary(coverage: CoverageReport): void { + const { packages, config } = coverage; + const passingPackages = packages.filter(pkg => + this.packageMeetsThresholds(pkg, config.thresholds) + ).length; + + const warningPackages = packages.filter(pkg => { + const meetsThresholds = this.packageMeetsThresholds(pkg, config.thresholds); + const almostMeets = this.packageAlmostMeetsThresholds(pkg, config.thresholds); + return !meetsThresholds && almostMeets; + }).length; + + const failingPackages = packages.length - passingPackages - warningPackages; + + console.log(chalk.green(`✓ ${passingPackages} packages meet coverage thresholds`)); + + if (warningPackages > 0) { + console.log(chalk.yellow(`⚠ ${warningPackages} packages below threshold`)); + } + + if (failingPackages > 0) { + console.log(chalk.red(`✗ ${failingPackages} packages critically low`)); + } + } + + private packageMeetsThresholds(pkg: PackageCoverage, thresholds: CoverageThresholds): boolean { + return ( + (!thresholds.lines || pkg.lines.percentage >= thresholds.lines) && + (!thresholds.functions || pkg.functions.percentage >= thresholds.functions) && + (!thresholds.branches || pkg.branches.percentage >= thresholds.branches) && + (!thresholds.statements || pkg.statements.percentage >= thresholds.statements) + ); + } + + private packageAlmostMeetsThresholds( + pkg: PackageCoverage, + thresholds: CoverageThresholds + ): boolean { + return ( + (!thresholds.lines || pkg.lines.percentage >= thresholds.lines * 0.9) && + (!thresholds.functions || pkg.functions.percentage >= thresholds.functions * 0.9) && + (!thresholds.branches || pkg.branches.percentage >= thresholds.branches * 0.9) && + (!thresholds.statements || pkg.statements.percentage >= thresholds.statements * 0.9) + ); + } + + private printThresholdWarnings(coverage: CoverageReport): void { + const { overall, config } = coverage; + const failures: string[] = []; + + if (config.thresholds.lines && overall.lines.percentage < config.thresholds.lines) { + failures.push(`Lines: ${overall.lines.percentage.toFixed(1)}% < ${config.thresholds.lines}%`); + } + if (config.thresholds.functions && overall.functions.percentage < config.thresholds.functions) { + failures.push( + `Functions: ${overall.functions.percentage.toFixed(1)}% < ${config.thresholds.functions}%` + ); + } + if (config.thresholds.branches && overall.branches.percentage < config.thresholds.branches) { + failures.push( + `Branches: ${overall.branches.percentage.toFixed(1)}% < ${config.thresholds.branches}%` + ); + } + if ( + config.thresholds.statements && + overall.statements.percentage < config.thresholds.statements + ) { + failures.push( + `Statements: ${overall.statements.percentage.toFixed(1)}% < ${config.thresholds.statements}%` + ); + } + + if (failures.length > 0) { + console.log('\n' + chalk.red.bold('Coverage thresholds not met:')); + failures.forEach(failure => console.log(chalk.red(` • ${failure}`))); + } + + console.log('\n' + chalk.gray(`Run 'stock-bot-coverage --reporter html' for detailed report`)); + } +} diff --git a/tools/coverage-cli/src/reporters/text.ts b/tools/coverage-cli/src/reporters/text.ts index e7794453..d8395936 100644 --- a/tools/coverage-cli/src/reporters/text.ts +++ b/tools/coverage-cli/src/reporters/text.ts @@ -1,206 +1,226 @@ -import { writeFileSync } from 'fs'; -import { join } from 'path'; -import type { CoverageReport, PackageCoverage, CoverageMetric } from '../types'; - -export class TextReporter { - report(coverage: CoverageReport, outputDir: string): void { - const outputPath = join(outputDir, 'coverage.txt'); - const content = this.generateText(coverage); - - writeFileSync(outputPath, content); - console.log(`Text coverage report written to: ${outputPath}`); - } - - private generateText(coverage: CoverageReport): string { - const lines: string[] = []; - const width = 80; - - // Header - lines.push('='.repeat(width)); - lines.push(this.center('STOCK BOT COVERAGE REPORT', width)); - lines.push('='.repeat(width)); - lines.push(''); - lines.push(`Generated: ${new Date(coverage.timestamp).toLocaleString()}`); - lines.push(''); - - // Overall Summary - lines.push('-'.repeat(width)); - lines.push('OVERALL COVERAGE'); - lines.push('-'.repeat(width)); - lines.push(''); - - const overall = coverage.overall; - lines.push(this.formatMetricLine('Lines', overall.lines, coverage.config.thresholds.lines)); - lines.push(this.formatMetricLine('Functions', overall.functions, coverage.config.thresholds.functions)); - lines.push(this.formatMetricLine('Branches', overall.branches, coverage.config.thresholds.branches)); - lines.push(this.formatMetricLine('Statements', overall.statements, coverage.config.thresholds.statements)); - lines.push(''); - - // Package Summary - if (coverage.packages.length > 0) { - lines.push('-'.repeat(width)); - lines.push('PACKAGE COVERAGE'); - lines.push('-'.repeat(width)); - lines.push(''); - - // Table header - lines.push(this.padRight('Package', 30) + - this.padLeft('Lines', 10) + - this.padLeft('Funcs', 10) + - this.padLeft('Branch', 10) + - this.padLeft('Stmts', 10)); - lines.push('-'.repeat(70)); - - // Package rows - for (const pkg of coverage.packages) { - lines.push( - this.padRight(pkg.name, 30) + - this.padLeft(this.formatPercent(pkg.lines.percentage), 10) + - this.padLeft(this.formatPercent(pkg.functions.percentage), 10) + - this.padLeft(this.formatPercent(pkg.branches.percentage), 10) + - this.padLeft(this.formatPercent(pkg.statements.percentage), 10) - ); - } - - lines.push('-'.repeat(70)); - lines.push( - this.padRight('TOTAL', 30) + - this.padLeft(this.formatPercent(overall.lines.percentage), 10) + - this.padLeft(this.formatPercent(overall.functions.percentage), 10) + - this.padLeft(this.formatPercent(overall.branches.percentage), 10) + - this.padLeft(this.formatPercent(overall.statements.percentage), 10) - ); - lines.push(''); - - // Detailed breakdowns - lines.push('-'.repeat(width)); - lines.push('PACKAGE DETAILS'); - lines.push('-'.repeat(width)); - - for (const pkg of coverage.packages) { - lines.push(''); - lines.push(`Package: ${pkg.name}`); - lines.push(`Path: ${pkg.path}`); - lines.push(''); - - // Coverage details - lines.push(` Lines......: ${this.formatMetricDetail(pkg.lines)}`); - lines.push(` Functions..: ${this.formatMetricDetail(pkg.functions)}`); - lines.push(` Branches...: ${this.formatMetricDetail(pkg.branches)}`); - lines.push(` Statements.: ${this.formatMetricDetail(pkg.statements)}`); - lines.push(''); - - // File list (top 5 least covered) - if (pkg.files.length > 0) { - lines.push(' Least covered files:'); - const sortedFiles = [...pkg.files] - .sort((a, b) => a.lines.percentage - b.lines.percentage) - .slice(0, 5); - - for (const file of sortedFiles) { - const shortPath = this.shortenPath(file.path); - lines.push(` ${this.padRight(shortPath, 40)} ${this.formatPercent(file.lines.percentage)}`); - } - } - } - } - - // Threshold Summary - lines.push(''); - lines.push('-'.repeat(width)); - lines.push('THRESHOLD SUMMARY'); - lines.push('-'.repeat(width)); - lines.push(''); - - const thresholds = coverage.config.thresholds; - const results = this.checkThresholds(coverage); - - lines.push(`Status: ${results.passed ? 'PASS' : 'FAIL'}`); - lines.push(''); - - if (results.failures.length > 0) { - lines.push('Failed thresholds:'); - for (const failure of results.failures) { - lines.push(` - ${failure.metric}: ${failure.actual.toFixed(1)}% < ${failure.expected}% (required)`); - } - } else { - lines.push('All coverage thresholds met!'); - } - - lines.push(''); - lines.push('='.repeat(width)); - - return lines.join('\n'); - } - - private formatMetricLine(name: string, metric: CoverageMetric, threshold?: number): string { - const status = this.getStatus(metric.percentage, threshold); - return `${this.padRight(name + ':', 15)} ${this.padRight(this.formatPercent(metric.percentage), 10)} ` + - `(${metric.covered}/${metric.total}) ${status}`; - } - - private formatMetricDetail(metric: CoverageMetric): string { - return `${this.formatPercent(metric.percentage)} (${metric.covered}/${metric.total})`; - } - - private formatPercent(percentage: number): string { - return `${percentage.toFixed(1)}%`; - } - - private getStatus(percentage: number, threshold?: number): string { - if (!threshold) return ''; - - if (percentage >= threshold) return '[PASS]'; - if (percentage >= threshold * 0.9) return '[WARN]'; - return '[FAIL]'; - } - - private checkThresholds(coverage: CoverageReport): { - passed: boolean; - failures: Array<{ metric: string; expected: number; actual: number }>; - } { - const failures: Array<{ metric: string; expected: number; actual: number }> = []; - const { thresholds } = coverage.config; - const { overall } = coverage; - - const metrics = ['lines', 'functions', 'branches', 'statements'] as const; - for (const metric of metrics) { - const threshold = thresholds[metric]; - if (threshold && overall[metric].percentage < threshold) { - failures.push({ - metric: metric.charAt(0).toUpperCase() + metric.slice(1), - expected: threshold, - actual: overall[metric].percentage, - }); - } - } - - return { - passed: failures.length === 0, - failures, - }; - } - - private center(text: string, width: number): string { - const padding = Math.max(0, width - text.length); - const leftPad = Math.floor(padding / 2); - const rightPad = padding - leftPad; - return ' '.repeat(leftPad) + text + ' '.repeat(rightPad); - } - - private padRight(text: string, width: number): string { - return text + ' '.repeat(Math.max(0, width - text.length)); - } - - private padLeft(text: string, width: number): string { - return ' '.repeat(Math.max(0, width - text.length)) + text; - } - - private shortenPath(path: string): string { - const parts = path.split('/'); - if (parts.length > 4) { - return '.../' + parts.slice(-3).join('/'); - } - return path; - } -} \ No newline at end of file +import { writeFileSync } from 'fs'; +import { join } from 'path'; +import type { CoverageMetric, CoverageReport } from '../types'; + +export class TextReporter { + report(coverage: CoverageReport, outputDir: string): void { + const outputPath = join(outputDir, 'coverage.txt'); + const content = this.generateText(coverage); + + writeFileSync(outputPath, content); + console.log(`Text coverage report written to: ${outputPath}`); + } + + private generateText(coverage: CoverageReport): string { + const lines: string[] = []; + const width = 80; + + // Header + lines.push('='.repeat(width)); + lines.push(this.center('STOCK BOT COVERAGE REPORT', width)); + lines.push('='.repeat(width)); + lines.push(''); + lines.push(`Generated: ${new Date(coverage.timestamp).toLocaleString()}`); + lines.push(''); + + // Overall Summary + lines.push('-'.repeat(width)); + lines.push('OVERALL COVERAGE'); + lines.push('-'.repeat(width)); + lines.push(''); + + const overall = coverage.overall; + lines.push(this.formatMetricLine('Lines', overall.lines, coverage.config.thresholds.lines)); + lines.push( + this.formatMetricLine('Functions', overall.functions, coverage.config.thresholds.functions) + ); + lines.push( + this.formatMetricLine('Branches', overall.branches, coverage.config.thresholds.branches) + ); + lines.push( + this.formatMetricLine('Statements', overall.statements, coverage.config.thresholds.statements) + ); + lines.push(''); + + // Package Summary + if (coverage.packages.length > 0) { + lines.push('-'.repeat(width)); + lines.push('PACKAGE COVERAGE'); + lines.push('-'.repeat(width)); + lines.push(''); + + // Table header + lines.push( + this.padRight('Package', 30) + + this.padLeft('Lines', 10) + + this.padLeft('Funcs', 10) + + this.padLeft('Branch', 10) + + this.padLeft('Stmts', 10) + ); + lines.push('-'.repeat(70)); + + // Package rows + for (const pkg of coverage.packages) { + lines.push( + this.padRight(pkg.name, 30) + + this.padLeft(this.formatPercent(pkg.lines.percentage), 10) + + this.padLeft(this.formatPercent(pkg.functions.percentage), 10) + + this.padLeft(this.formatPercent(pkg.branches.percentage), 10) + + this.padLeft(this.formatPercent(pkg.statements.percentage), 10) + ); + } + + lines.push('-'.repeat(70)); + lines.push( + this.padRight('TOTAL', 30) + + this.padLeft(this.formatPercent(overall.lines.percentage), 10) + + this.padLeft(this.formatPercent(overall.functions.percentage), 10) + + this.padLeft(this.formatPercent(overall.branches.percentage), 10) + + this.padLeft(this.formatPercent(overall.statements.percentage), 10) + ); + lines.push(''); + + // Detailed breakdowns + lines.push('-'.repeat(width)); + lines.push('PACKAGE DETAILS'); + lines.push('-'.repeat(width)); + + for (const pkg of coverage.packages) { + lines.push(''); + lines.push(`Package: ${pkg.name}`); + lines.push(`Path: ${pkg.path}`); + lines.push(''); + + // Coverage details + lines.push(` Lines......: ${this.formatMetricDetail(pkg.lines)}`); + lines.push(` Functions..: ${this.formatMetricDetail(pkg.functions)}`); + lines.push(` Branches...: ${this.formatMetricDetail(pkg.branches)}`); + lines.push(` Statements.: ${this.formatMetricDetail(pkg.statements)}`); + lines.push(''); + + // File list (top 5 least covered) + if (pkg.files.length > 0) { + lines.push(' Least covered files:'); + const sortedFiles = [...pkg.files] + .sort((a, b) => a.lines.percentage - b.lines.percentage) + .slice(0, 5); + + for (const file of sortedFiles) { + const shortPath = this.shortenPath(file.path); + lines.push( + ` ${this.padRight(shortPath, 40)} ${this.formatPercent(file.lines.percentage)}` + ); + } + } + } + } + + // Threshold Summary + lines.push(''); + lines.push('-'.repeat(width)); + lines.push('THRESHOLD SUMMARY'); + lines.push('-'.repeat(width)); + lines.push(''); + + const _thresholds = coverage.config.thresholds; + const results = this.checkThresholds(coverage); + + lines.push(`Status: ${results.passed ? 'PASS' : 'FAIL'}`); + lines.push(''); + + if (results.failures.length > 0) { + lines.push('Failed thresholds:'); + for (const failure of results.failures) { + lines.push( + ` - ${failure.metric}: ${failure.actual.toFixed(1)}% < ${failure.expected}% (required)` + ); + } + } else { + lines.push('All coverage thresholds met!'); + } + + lines.push(''); + lines.push('='.repeat(width)); + + return lines.join('\n'); + } + + private formatMetricLine(name: string, metric: CoverageMetric, threshold?: number): string { + const status = this.getStatus(metric.percentage, threshold); + return ( + `${this.padRight(name + ':', 15)} ${this.padRight(this.formatPercent(metric.percentage), 10)} ` + + `(${metric.covered}/${metric.total}) ${status}` + ); + } + + private formatMetricDetail(metric: CoverageMetric): string { + return `${this.formatPercent(metric.percentage)} (${metric.covered}/${metric.total})`; + } + + private formatPercent(percentage: number): string { + return `${percentage.toFixed(1)}%`; + } + + private getStatus(percentage: number, threshold?: number): string { + if (!threshold) { + return ''; + } + + if (percentage >= threshold) { + return '[PASS]'; + } + if (percentage >= threshold * 0.9) { + return '[WARN]'; + } + return '[FAIL]'; + } + + private checkThresholds(coverage: CoverageReport): { + passed: boolean; + failures: Array<{ metric: string; expected: number; actual: number }>; + } { + const failures: Array<{ metric: string; expected: number; actual: number }> = []; + const { thresholds } = coverage.config; + const { overall } = coverage; + + const metrics = ['lines', 'functions', 'branches', 'statements'] as const; + for (const metric of metrics) { + const threshold = thresholds[metric]; + if (threshold && overall[metric].percentage < threshold) { + failures.push({ + metric: metric.charAt(0).toUpperCase() + metric.slice(1), + expected: threshold, + actual: overall[metric].percentage, + }); + } + } + + return { + passed: failures.length === 0, + failures, + }; + } + + private center(text: string, width: number): string { + const padding = Math.max(0, width - text.length); + const leftPad = Math.floor(padding / 2); + const rightPad = padding - leftPad; + return ' '.repeat(leftPad) + text + ' '.repeat(rightPad); + } + + private padRight(text: string, width: number): string { + return text + ' '.repeat(Math.max(0, width - text.length)); + } + + private padLeft(text: string, width: number): string { + return ' '.repeat(Math.max(0, width - text.length)) + text; + } + + private shortenPath(path: string): string { + const parts = path.split('/'); + if (parts.length > 4) { + return '.../' + parts.slice(-3).join('/'); + } + return path; + } +} diff --git a/tools/coverage-cli/src/runner.ts b/tools/coverage-cli/src/runner.ts index de7756b2..1c6bab72 100644 --- a/tools/coverage-cli/src/runner.ts +++ b/tools/coverage-cli/src/runner.ts @@ -1,538 +1,450 @@ -import { spawn } from 'child_process'; -import { existsSync, mkdirSync, readFileSync } from 'fs'; -import { join, resolve } from 'path'; -import { glob, globSync } from 'glob'; -import type { CoverageConfig } from './types'; - -export interface RunnerResult { - success: boolean; - coverage: any; - testResults: any; - error?: string; -} - -export class CoverageRunner { - constructor(private config: CoverageConfig) {} - - async run(): Promise { - const packages = await this.findPackages(); - if (packages.length === 0) { - console.log('No packages found to test'); - return { - success: true, - coverage: { files: [], lines: { found: 0, hit: 0 }, functions: { found: 0, hit: 0 }, branches: { found: 0, hit: 0 } }, - testResults: [], - }; - } - - console.log(`Found ${packages.length} packages to test`); - - const results: RunnerResult[] = []; - - // Ensure output directory exists - if (!existsSync(this.config.outputDir)) { - mkdirSync(this.config.outputDir, { recursive: true }); - } - - // Run tests for each package - for (const pkg of packages) { - console.log(`Running tests for ${pkg.name}...`); - const result = await this.runPackageTests(pkg); - results.push(result); - } - - // Merge coverage results - const mergedCoverage = this.mergeCoverageResults(results); - - return { - success: results.every(r => r.success), - coverage: mergedCoverage, - testResults: results.map(r => r.testResults), - }; - } - - private async findPackages(): Promise> { - const root = this.config.workspaceRoot || process.cwd(); - const packages: Array<{ name: string; path: string }> = []; - - - // If specific packages are requested - if (this.config.packages && this.config.packages.length > 0) { - for (const pkgName of this.config.packages) { - const patterns = [ - `tools/${pkgName}`, - `packages/${pkgName}`, - `apps/${pkgName}`, - `libs/${pkgName}`, - `libs/*/${pkgName}`, - `libs/core/${pkgName}`, - `libs/data/${pkgName}`, - `libs/services/${pkgName}`, - pkgName, - ]; - - for (const pattern of patterns) { - const pkgPath = join(root, pattern); - if (existsSync(join(pkgPath, 'package.json'))) { - const pkg = JSON.parse(readFileSync(join(pkgPath, 'package.json'), 'utf-8')); - packages.push({ name: pkg.name || pkgName, path: pkgPath }); - break; - } - } - } - } else { - // Find all packages - include all workspace patterns - const patterns = [ - 'tools/*/package.json', - 'packages/*/package.json', - 'apps/*/package.json', - 'apps/*/*/package.json', - 'libs/*/package.json', - 'libs/*/*/package.json', - 'libs/*/*/*/package.json' // Added for libs/core/handlers and similar - ]; - - for (const pattern of patterns) { - const files = await glob(pattern, { cwd: root }); - - for (const file of files) { - const pkgPath = resolve(root, file, '..'); - const pkg = JSON.parse(readFileSync(join(root, file), 'utf-8')); - packages.push({ name: pkg.name || pkgPath, path: pkgPath }); - console.log(`Found package: ${pkg.name} at ${pkgPath}`); - } - } - - // Also check root package.json - if (existsSync(join(root, 'package.json'))) { - const rootPkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')); - if (!rootPkg.workspaces) { - packages.push({ name: rootPkg.name || 'root', path: root }); - } - } - } - - return packages; - } - - private async runPackageTests(pkg: { name: string; path: string }): Promise { - return new Promise((resolve) => { - const sanitizedPkgName = pkg.name.replace('/', '-'); - const coverageDir = join(this.config.outputDir, 'tmp', sanitizedPkgName); - mkdirSync(coverageDir, { recursive: true }); - - // Run tests with coverage enabled - const args = [ - 'test', - '--coverage', - '--coverage-reporter=lcov', - `--coverage-dir=${coverageDir}`, - ]; - - const proc = spawn('bun', args, { - cwd: pkg.path, - stdio: 'pipe', - env: { - ...process.env, - NODE_ENV: 'test', - }, - }); - - let stdout = ''; - let stderr = ''; - let combinedOutput = ''; - - proc.stdout.on('data', (data) => { - const output = data.toString(); - stdout += output; - combinedOutput += output; - }); - - proc.stderr.on('data', (data) => { - const output = data.toString(); - stderr += output; - combinedOutput += output; - }); - - proc.on('close', (code) => { - const success = code === 0; - - // Parse LCOV coverage (even if tests failed, Bun still generates coverage) - let coverage = null; - // Always try to find coverage, not just when tests pass - // Look for LCOV in various possible locations - // Bun may generate LCOV at different locations depending on configuration - const possiblePaths = [ - join(pkg.path, 'coverage', 'lcov.info'), // Direct in package coverage dir - join(pkg.path, 'coverage', 'tmp', sanitizedPkgName, 'lcov.info'), // Nested with package name - join(coverageDir, 'tmp', sanitizedPkgName, 'lcov.info'), // In output coverage dir - join(coverageDir, 'lcov.info'), // Direct in coverage dir - ]; - - let lcovFound = false; - for (const lcovPath of possiblePaths) { - if (existsSync(lcovPath)) { - coverage = this.parseLcovFile(lcovPath, pkg); - lcovFound = true; - break; - } - } - - if (!lcovFound) { - // Fallback to simulated coverage if LCOV not found - console.log(`LCOV not found for ${pkg.name}, checked:`); - possiblePaths.forEach(p => console.log(` - ${p}`)); - coverage = this.parseTestOutputForCoverage(pkg, combinedOutput || stdout); - } - - // Now echo the output after parsing - if (stdout) process.stdout.write(stdout); - if (stderr) process.stderr.write(stderr); - - resolve({ - success, - coverage, - testResults: { - package: pkg.name, - stdout, - stderr, - exitCode: code, - }, - error: success ? undefined : stderr || 'Tests failed', - }); - }); - }); - } - - private parseTestOutputForCoverage(pkg: { name: string; path: string }, stdout: string): any { - // Parse test output to extract test statistics - const passMatch = stdout.match(/(\d+) pass/); - const failMatch = stdout.match(/(\d+) fail/); - const filesMatch = stdout.match(/Ran \d+ tests across (\d+) files/); - - const passCount = passMatch ? parseInt(passMatch[1]) : 0; - const failCount = failMatch ? parseInt(failMatch[1]) : 0; - const fileCount = filesMatch ? parseInt(filesMatch[1]) : 1; - - - // Generate simulated coverage based on test results - // This is a fallback when LCOV files are not generated (usually due to test failures) - const coverage: any = { - files: [], - }; - - // Find actual source files in the package (not test files) - const sourceFiles = this.findSourceFiles(pkg.path); - - // If we have source files, generate coverage for them - if (sourceFiles.length > 0) { - for (const srcFile of sourceFiles) { - // When tests fail, we assume 0% coverage - // When tests pass but no LCOV, we generate estimated coverage - const hasFailures = failCount > 0; - const estimatedCoverage = hasFailures ? 0 : Math.max(0, Math.min(100, 80 - (failCount * 10))); - - coverage.files.push({ - path: srcFile, - lines: { - found: 100, - hit: hasFailures ? 0 : Math.floor(100 * estimatedCoverage / 100) - }, - functions: { - found: 20, - hit: hasFailures ? 0 : Math.floor(20 * estimatedCoverage / 100) - }, - branches: { - found: 10, - hit: hasFailures ? 0 : Math.floor(10 * estimatedCoverage / 100) - }, - }); - } - } else { - // Fallback: if no source files found, create a placeholder - coverage.files.push({ - path: join(pkg.path, 'src/index.ts'), - lines: { - found: 100, - hit: failCount > 0 ? 0 : 80 - }, - functions: { - found: 20, - hit: failCount > 0 ? 0 : 16 - }, - branches: { - found: 10, - hit: failCount > 0 ? 0 : 8 - }, - }); - } - - return coverage; - } - - private findSourceFiles(packagePath: string): string[] { - const sourcePatterns = [ - 'src/**/*.ts', - 'src/**/*.js', - ]; - - const sourceFiles: string[] = []; - for (const pattern of sourcePatterns) { - try { - const files = globSync(pattern, { - cwd: packagePath, - ignore: [ - 'node_modules/**', - 'dist/**', - '**/*.test.ts', - '**/*.test.js', - '**/*.spec.ts', - '**/*.spec.js', - '**/*.d.ts', - ], - }); - - // Convert to absolute paths - const absoluteFiles = files.map(f => resolve(packagePath, f)); - sourceFiles.push(...absoluteFiles); - } catch (e) { - console.warn(`Error finding source files in ${packagePath}:`, e); - } - } - - return sourceFiles; - } - - private findTestFiles(packagePath: string): string[] { - const testPatterns = [ - 'test/**/*.test.ts', - 'test/**/*.test.js', - 'src/**/*.test.ts', - 'src/**/*.test.js', - '**/*.spec.ts', - '**/*.spec.js', - ]; - - const testFiles: string[] = []; - for (const pattern of testPatterns) { - try { - const files = globSync(pattern, { - cwd: packagePath, - ignore: ['node_modules/**', 'dist/**'], - }); - if (files.length > 0) { - } - testFiles.push(...files); - } catch (e) { - } - } - - return testFiles; - } - - private findSourceFileForTest(testFile: string, packagePath: string): string | null { - // Convert test file to source file path - let srcFile = testFile - .replace(/\.test\.(ts|js)$/, '.$1') - .replace(/\.spec\.(ts|js)$/, '.$1') - .replace(/^test\//, 'src/') - .replace(/\/__tests__\//, '/'); - - // Check if it's already in src - if (!srcFile.startsWith('src/')) { - srcFile = 'src/' + srcFile; - } - - const fullPath = join(packagePath, srcFile); - if (existsSync(fullPath)) { - return fullPath; - } - - // Try without src prefix - srcFile = testFile - .replace(/\.test\.(ts|js)$/, '.$1') - .replace(/\.spec\.(ts|js)$/, '.$1') - .replace(/^test\//, ''); - - const altPath = join(packagePath, srcFile); - if (existsSync(altPath)) { - return altPath; - } - - return null; - } - - private parseLcovFile(lcovPath: string, pkg: { name: string; path: string }): any { - try { - const lcovContent = readFileSync(lcovPath, 'utf-8'); - const coverage: any = { - files: [], - }; - - let currentFile: any = null; - const lines = lcovContent.split('\n'); - - for (const line of lines) { - if (line.startsWith('SF:')) { - if (currentFile) { - coverage.files.push(currentFile); - } - const relativePath = line.substring(3); - // Only include files that belong to this package - const fullPath = resolve(pkg.path, relativePath); - const normalizedPkgPath = pkg.path.replace(/\\/g, '/'); - const normalizedFullPath = fullPath.replace(/\\/g, '/'); - - // Skip files that are outside the package directory - if (!normalizedFullPath.startsWith(normalizedPkgPath)) { - currentFile = null; - continue; - } - - currentFile = { - path: fullPath, - lines: { found: 0, hit: 0 }, - functions: { found: 0, hit: 0 }, - branches: { found: 0, hit: 0 }, - }; - } else if (currentFile) { - if (line.startsWith('DA:')) { - const [lineNum, hitCount] = line.substring(3).split(','); - currentFile.lines.found++; - if (parseInt(hitCount) > 0) { - currentFile.lines.hit++; - } - } else if (line.startsWith('FN:')) { - currentFile.functions.found++; - } else if (line.startsWith('FNDA:')) { - const [hitCount] = line.substring(5).split(','); - if (parseInt(hitCount) > 0) { - currentFile.functions.hit++; - } - } else if (line.startsWith('FNF:')) { - // Functions Found - currentFile.functions.found = parseInt(line.substring(4)); - } else if (line.startsWith('FNH:')) { - // Functions Hit - currentFile.functions.hit = parseInt(line.substring(4)); - } else if (line.startsWith('BRF:')) { - // Branches Found - currentFile.branches.found = parseInt(line.substring(4)); - } else if (line.startsWith('BRH:')) { - // Branches Hit - currentFile.branches.hit = parseInt(line.substring(4)); - } else if (line.startsWith('LF:')) { - // Lines Found - currentFile.lines.found = parseInt(line.substring(3)); - } else if (line.startsWith('LH:')) { - // Lines Hit - currentFile.lines.hit = parseInt(line.substring(3)); - } - } - } - - if (currentFile) { - coverage.files.push(currentFile); - } - - // If no files were found for this package after filtering, return null to trigger fallback - if (coverage.files.length === 0) { - console.log(`No coverage files found for ${pkg.name} after filtering`); - return null; - } - - return coverage; - } catch (error) { - console.warn('Failed to parse LCOV file:', error); - return null; - } - } - - private mergeCoverageResults(results: RunnerResult[]): any { - const merged: any = { - files: [], - lines: { found: 0, hit: 0 }, - functions: { found: 0, hit: 0 }, - branches: { found: 0, hit: 0 }, - packages: {}, // Track per-package stats - }; - - for (const result of results) { - if (!result.coverage) continue; - - // Get package name from test results - const packageName = result.testResults?.package || 'unknown'; - - if (!merged.packages[packageName]) { - merged.packages[packageName] = { - files: [], - lines: { found: 0, hit: 0 }, - functions: { found: 0, hit: 0 }, - branches: { found: 0, hit: 0 }, - }; - } - - for (const file of result.coverage.files) { - // Skip excluded files - if (this.shouldExcludeFile(file.path)) { - continue; - } - - merged.files.push(file); - merged.packages[packageName].files.push(file); - - // Update overall stats - merged.lines.found += file.lines.found; - merged.lines.hit += file.lines.hit; - merged.functions.found += file.functions.found; - merged.functions.hit += file.functions.hit; - merged.branches.found += file.branches.found; - merged.branches.hit += file.branches.hit; - - // Update package stats - merged.packages[packageName].lines.found += file.lines.found; - merged.packages[packageName].lines.hit += file.lines.hit; - merged.packages[packageName].functions.found += file.functions.found; - merged.packages[packageName].functions.hit += file.functions.hit; - merged.packages[packageName].branches.found += file.branches.found; - merged.packages[packageName].branches.hit += file.branches.hit; - } - } - - return merged; - } - - private shouldExcludeFile(filePath: string): boolean { - const normalizedPath = filePath.replace(/\\/g, '/'); - - // Check exclusion patterns - for (const pattern of this.config.exclude) { - if (this.matchesPattern(normalizedPath, pattern)) { - return true; - } - } - - // Check inclusion patterns if specified - if (this.config.include && this.config.include.length > 0) { - for (const pattern of this.config.include) { - if (this.matchesPattern(normalizedPath, pattern)) { - return false; - } - } - return true; // Exclude if not in include list - } - - return false; - } - - private matchesPattern(path: string, pattern: string): boolean { - // Simple glob matching - in production, use a proper glob library - const regex = pattern - .replace(/\*\*/g, '.*') - .replace(/\*/g, '[^/]*') - .replace(/\?/g, '.') - .replace(/\//g, '\\/'); - - return new RegExp(regex).test(path); - } -} \ No newline at end of file +import { spawn } from 'child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync } from 'fs'; +import { join, resolve as resolvePath } from 'path'; +import { glob, globSync } from 'glob'; +import { defined } from '@stock-bot/invariants'; +import type { CoverageConfig, RawCoverage, RawFileCoverage } from './types'; + +export interface RunnerResult { + success: boolean; + coverage: RawCoverage; + testResults: + | { package?: string; stdout?: string; stderr?: string; exitCode?: number | null } + | unknown[]; + error?: string; +} + +export class CoverageRunner { + constructor(private config: CoverageConfig) {} + + async run(): Promise { + const packages = await this.findPackages(); + if (packages.length === 0) { + console.log('No packages found to test'); + return { + success: false, + error: 'No packages found to test', + coverage: { + files: [], + lines: { found: 0, hit: 0 }, + functions: { found: 0, hit: 0 }, + branches: { found: 0, hit: 0 }, + }, + testResults: [], + }; + } + + console.log(`Found ${packages.length} packages to test`); + + const results: RunnerResult[] = []; + + // Ensure output directory exists + if (!existsSync(this.config.outputDir)) { + mkdirSync(this.config.outputDir, { recursive: true }); + } + + // Run tests for each package + for (const pkg of packages) { + console.log(`Running tests for ${pkg.name}...`); + const result = await this.runPackageTests(pkg); + results.push(result); + } + + // Merge coverage results + const mergedCoverage = this.mergeCoverageResults(results); + + return { + success: results.every(r => r.success), + coverage: mergedCoverage, + testResults: results.map(r => r.testResults), + }; + } + + private async findPackages(): Promise> { + const root = this.config.workspaceRoot || process.cwd(); + const packages: Array<{ name: string; path: string }> = []; + + // If specific packages are requested + if (this.config.packages && this.config.packages.length > 0) { + for (const pkgName of this.config.packages) { + const patterns = [ + `tools/${pkgName}`, + `packages/${pkgName}`, + `apps/${pkgName}`, + `libs/${pkgName}`, + `libs/*/${pkgName}`, + `libs/core/${pkgName}`, + `libs/data/${pkgName}`, + `libs/services/${pkgName}`, + pkgName, + ]; + + for (const pattern of patterns) { + const pkgPath = join(root, pattern); + if (existsSync(join(pkgPath, 'package.json'))) { + const pkg = JSON.parse(readFileSync(join(pkgPath, 'package.json'), 'utf-8')); + packages.push({ name: pkg.name || pkgName, path: pkgPath }); + break; + } + } + } + } else { + // Find all packages - include all workspace patterns + const patterns = [ + 'tools/*/package.json', + 'packages/*/package.json', + 'apps/*/package.json', + 'apps/*/*/package.json', + 'libs/*/package.json', + 'libs/*/*/package.json', + 'libs/*/*/*/package.json', // Added for libs/core/handlers and similar + ]; + + for (const pattern of patterns) { + const files = await glob(pattern, { cwd: root }); + + for (const file of files) { + const pkgPath = resolvePath(root, file, '..'); + const pkg = JSON.parse(readFileSync(join(root, file), 'utf-8')); + packages.push({ name: pkg.name || pkgPath, path: pkgPath }); + console.log(`Found package: ${pkg.name} at ${pkgPath}`); + } + } + + // Also check root package.json + if (existsSync(join(root, 'package.json'))) { + const rootPkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf-8')); + if (!rootPkg.workspaces) { + packages.push({ name: rootPkg.name || 'root', path: root }); + } + } + } + + return packages; + } + + private async runPackageTests(pkg: { name: string; path: string }): Promise { + return new Promise(resolve => { + const sanitizedPkgName = pkg.name.replace('/', '-'); + const temporaryRoot = resolvePath(this.config.outputDir, 'tmp'); + mkdirSync(temporaryRoot, { recursive: true }); + const coverageDir = mkdtempSync( + join(temporaryRoot, sanitizedPkgName.replaceAll('/', '-') + '-') + ); + + // Run tests with coverage enabled + const args = [ + 'test', + '--coverage', + '--coverage-reporter=lcov', + `--coverage-dir=${coverageDir}`, + ]; + + const proc = spawn('bun', args, { + cwd: pkg.path, + stdio: 'pipe', + env: { + ...process.env, + NODE_ENV: 'test', + }, + }); + + let stdout = ''; + let stderr = ''; + + proc.stdout.on('data', data => { + const output = data.toString(); + stdout += output; + }); + + proc.stderr.on('data', data => { + const output = data.toString(); + stderr += output; + }); + + proc.on('close', code => { + const success = code === 0; + + // Parse LCOV coverage (even if tests failed, Bun still generates coverage) + let coverage = null; + // Always try to find coverage, not just when tests pass + // Look for LCOV in various possible locations + // Bun may generate LCOV at different locations depending on configuration + const possiblePaths = [join(coverageDir, 'lcov.info')]; + + let lcovFound = false; + for (const lcovPath of possiblePaths) { + if (existsSync(lcovPath)) { + coverage = this.parseLcovFile(lcovPath, pkg); + lcovFound = true; + break; + } + } + + if (!lcovFound) { + console.error(`No measured LCOV coverage was generated for ${pkg.name}`); + } + + // Now echo the output after parsing + if (stdout) { + process.stdout.write(stdout); + } + if (stderr) { + process.stderr.write(stderr); + } + + resolve({ + success: success && lcovFound && coverage !== null, + coverage: coverage ?? { files: [] }, + testResults: { + package: pkg.name, + stdout, + stderr, + exitCode: code, + }, + error: + !lcovFound || coverage === null + ? 'Measured coverage is missing' + : success + ? undefined + : stderr || 'Tests failed', + }); + }); + }); + } + + private findTestFiles(packagePath: string): string[] { + const testPatterns = [ + 'test/**/*.test.ts', + 'test/**/*.test.js', + 'src/**/*.test.ts', + 'src/**/*.test.js', + '**/*.spec.ts', + '**/*.spec.js', + ]; + + const testFiles: string[] = []; + for (const pattern of testPatterns) { + try { + const files = globSync(pattern, { + cwd: packagePath, + ignore: ['node_modules/**', 'dist/**'], + }); + testFiles.push(...files); + } catch (error) { + console.warn(`Unable to discover tests for ${packagePath}: ${String(error)}`); + } + } + + return testFiles; + } + + private findSourceFileForTest(testFile: string, packagePath: string): string | null { + // Convert test file to source file path + let srcFile = testFile + .replace(/\.test\.(ts|js)$/, '.$1') + .replace(/\.spec\.(ts|js)$/, '.$1') + .replace(/^test\//, 'src/') + .replace(/\/__tests__\//, '/'); + + // Check if it's already in src + if (!srcFile.startsWith('src/')) { + srcFile = 'src/' + srcFile; + } + + const fullPath = join(packagePath, srcFile); + if (existsSync(fullPath)) { + return fullPath; + } + + // Try without src prefix + srcFile = testFile + .replace(/\.test\.(ts|js)$/, '.$1') + .replace(/\.spec\.(ts|js)$/, '.$1') + .replace(/^test\//, ''); + + const altPath = join(packagePath, srcFile); + if (existsSync(altPath)) { + return altPath; + } + + return null; + } + + private parseLcovFile(lcovPath: string, pkg: { name: string; path: string }) { + try { + const lcovContent = readFileSync(lcovPath, 'utf-8'); + const coverage: RawCoverage = { + files: [], + }; + + let currentFile: RawFileCoverage | null = null; + const lines = lcovContent.split('\n'); + + for (const line of lines) { + if (line.startsWith('SF:')) { + if (currentFile) { + coverage.files.push(currentFile); + } + const relativePath = line.substring(3); + // Only include files that belong to this package + const fullPath = resolvePath(pkg.path, relativePath); + const normalizedPkgPath = pkg.path.replace(/\\/g, '/'); + const normalizedFullPath = fullPath.replace(/\\/g, '/'); + + // Skip files that are outside the package directory + if (!normalizedFullPath.startsWith(normalizedPkgPath)) { + currentFile = null; + continue; + } + + currentFile = { + path: fullPath, + lines: { found: 0, hit: 0 }, + functions: { found: 0, hit: 0 }, + branches: { found: 0, hit: 0 }, + }; + } else if (currentFile) { + if (line.startsWith('DA:')) { + const [_lineNum, hitCount = '0'] = line.substring(3).split(','); + currentFile.lines.found++; + if (parseInt(hitCount) > 0) { + currentFile.lines.hit++; + } + } else if (line.startsWith('FN:')) { + currentFile.functions.found++; + } else if (line.startsWith('FNDA:')) { + const [hitCount = '0'] = line.substring(5).split(','); + if (parseInt(hitCount) > 0) { + currentFile.functions.hit++; + } + } else if (line.startsWith('FNF:')) { + // Functions Found + currentFile.functions.found = parseInt(line.substring(4)); + } else if (line.startsWith('FNH:')) { + // Functions Hit + currentFile.functions.hit = parseInt(line.substring(4)); + } else if (line.startsWith('BRF:')) { + // Branches Found + currentFile.branches.found = parseInt(line.substring(4)); + } else if (line.startsWith('BRH:')) { + // Branches Hit + currentFile.branches.hit = parseInt(line.substring(4)); + } else if (line.startsWith('LF:')) { + // Lines Found + currentFile.lines.found = parseInt(line.substring(3)); + } else if (line.startsWith('LH:')) { + // Lines Hit + currentFile.lines.hit = parseInt(line.substring(3)); + } + } + } + + if (currentFile) { + coverage.files.push(currentFile); + } + + // If no files were found for this package after filtering, return null to trigger fallback + if (coverage.files.length === 0) { + console.log(`No coverage files found for ${pkg.name} after filtering`); + return null; + } + + return coverage; + } catch (error) { + console.warn('Failed to parse LCOV file:', error); + return null; + } + } + + private mergeCoverageResults(results: RunnerResult[]) { + const merged: Required = { + files: [], + lines: { found: 0, hit: 0 }, + functions: { found: 0, hit: 0 }, + branches: { found: 0, hit: 0 }, + packages: {}, // Track per-package stats + }; + + for (const result of results) { + if (!result.coverage) { + continue; + } + + // Get package name from test results + const packageName = + (!Array.isArray(result.testResults) ? result.testResults.package : undefined) || 'unknown'; + + if (!merged.packages[packageName]) { + merged.packages[packageName] = { + files: [], + lines: { found: 0, hit: 0 }, + functions: { found: 0, hit: 0 }, + branches: { found: 0, hit: 0 }, + }; + } + + for (const file of result.coverage.files) { + // Skip excluded files + if (this.shouldExcludeFile(file.path)) { + continue; + } + + merged.files.push(file); + defined(merged.packages[packageName]).files.push(file); + + // Update overall stats + merged.lines.found += file.lines.found; + merged.lines.hit += file.lines.hit; + merged.functions.found += file.functions.found; + merged.functions.hit += file.functions.hit; + merged.branches.found += file.branches.found; + merged.branches.hit += file.branches.hit; + + // Update package stats + merged.packages[packageName].lines.found += file.lines.found; + merged.packages[packageName].lines.hit += file.lines.hit; + merged.packages[packageName].functions.found += file.functions.found; + merged.packages[packageName].functions.hit += file.functions.hit; + merged.packages[packageName].branches.found += file.branches.found; + merged.packages[packageName].branches.hit += file.branches.hit; + } + } + + return merged; + } + + private shouldExcludeFile(filePath: string): boolean { + const normalizedPath = filePath.replace(/\\/g, '/'); + + // Check exclusion patterns + for (const pattern of this.config.exclude) { + if (this.matchesPattern(normalizedPath, pattern)) { + return true; + } + } + + // Check inclusion patterns if specified + if (this.config.include && this.config.include.length > 0) { + for (const pattern of this.config.include) { + if (this.matchesPattern(normalizedPath, pattern)) { + return false; + } + } + return true; // Exclude if not in include list + } + + return false; + } + + private matchesPattern(path: string, pattern: string): boolean { + // Simple glob matching - in production, use a proper glob library + const regex = pattern + .replace(/\*\*/g, '.*') + .replace(/\*/g, '[^/]*') + .replace(/\?/g, '.') + .replace(/\//g, '\\/'); + + return new RegExp(regex).test(path); + } +} diff --git a/tools/coverage-cli/src/types.ts b/tools/coverage-cli/src/types.ts index fe9fa044..fc8d93cd 100644 --- a/tools/coverage-cli/src/types.ts +++ b/tools/coverage-cli/src/types.ts @@ -1,71 +1,101 @@ -export interface CoverageConfig { - exclude: string[]; - include?: string[]; - reporters: ReporterType[]; - thresholds: CoverageThresholds; - outputDir: string; - workspaceRoot?: string; - packages?: string[]; -} - -export type ReporterType = 'terminal' | 'html' | 'html-full' | 'markdown' | 'json' | 'text' | 'lcov'; - -export interface CoverageThresholds { - lines?: number; - functions?: number; - branches?: number; - statements?: number; -} - -export interface PackageCoverage { - name: string; - path: string; - lines: CoverageMetric; - functions: CoverageMetric; - branches: CoverageMetric; - statements: CoverageMetric; - files: FileCoverage[]; -} - -export interface CoverageMetric { - total: number; - covered: number; - skipped: number; - percentage: number; -} - -export interface FileCoverage { - path: string; - lines: CoverageMetric; - functions: CoverageMetric; - branches: CoverageMetric; - statements: CoverageMetric; -} - -export interface CoverageReport { - timestamp: string; - packages: PackageCoverage[]; - overall: { - lines: CoverageMetric; - functions: CoverageMetric; - branches: CoverageMetric; - statements: CoverageMetric; - }; - config: CoverageConfig; -} - -export interface CLIOptions { - packages?: string[]; - exclude?: string[]; - include?: string[]; - reporters?: string[]; - threshold?: number; - thresholdLines?: number; - thresholdFunctions?: number; - thresholdBranches?: number; - thresholdStatements?: number; - outputDir?: string; - config?: string; - watch?: boolean; - failUnder?: boolean; -} \ No newline at end of file +export interface CoverageConfig { + exclude: string[]; + include?: string[]; + reporters: ReporterType[]; + thresholds: CoverageThresholds; + outputDir: string; + workspaceRoot?: string; + packages?: string[]; +} + +export type ReporterType = + | 'terminal' + | 'html' + | 'html-full' + | 'markdown' + | 'json' + | 'text' + | 'lcov'; + +export interface CoverageThresholds { + lines?: number; + functions?: number; + branches?: number; + statements?: number; +} + +export interface PackageCoverage { + name: string; + path: string; + lines: CoverageMetric; + functions: CoverageMetric; + branches: CoverageMetric; + statements: CoverageMetric; + files: FileCoverage[]; +} + +export interface CoverageMetric { + total: number; + covered: number; + skipped: number; + percentage: number; +} + +export interface FileCoverage { + path: string; + lines: CoverageMetric; + functions: CoverageMetric; + branches: CoverageMetric; + statements: CoverageMetric; +} + +export interface CoverageReport { + timestamp: string; + packages: PackageCoverage[]; + overall: { + lines: CoverageMetric; + functions: CoverageMetric; + branches: CoverageMetric; + statements: CoverageMetric; + }; + config: CoverageConfig; +} + +export interface CLIOptions { + packages?: string[]; + exclude?: string[]; + include?: string[]; + reporters?: string[]; + threshold?: number; + thresholdLines?: number; + thresholdFunctions?: number; + thresholdBranches?: number; + thresholdStatements?: number; + outputDir?: string; + config?: string; + watch?: boolean; + failUnder?: boolean; +} +export interface RawMetric { + found: number; + hit: number; +} +export interface RawFileCoverage { + path: string; + lines: RawMetric; + functions: RawMetric; + branches: RawMetric; +} +export interface RawPackageCoverage { + files: RawFileCoverage[]; + lines: RawMetric; + functions: RawMetric; + branches: RawMetric; +} +export interface RawCoverage { + files: RawFileCoverage[]; + packages?: Record; + lines?: RawMetric; + functions?: RawMetric; + branches?: RawMetric; +} diff --git a/tools/coverage-cli/tsconfig.json b/tools/coverage-cli/tsconfig.json index fca38f47..593a2b7a 100644 --- a/tools/coverage-cli/tsconfig.json +++ b/tools/coverage-cli/tsconfig.json @@ -1,12 +1,12 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "rootDir": "./src", - "outDir": "./dist", - "declaration": true, - "declarationMap": true, - "types": ["bun-types", "node"] - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "dist", "test"] -} \ No newline at end of file +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "outDir": "./dist", + "declaration": true, + "declarationMap": true, + "types": ["bun-types", "node"] + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "test"] +}