138 lines
8.8 KiB
Markdown
138 lines
8.8 KiB
Markdown
# Stock Bot
|
|
|
|
Bun/TypeScript workspaces for market-data collection, processing, APIs, and a React dashboard,
|
|
with a Rust native trading engine. `apps/wcag-ada` is an independent project and is not part of
|
|
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/integration checks do not require running databases or provider
|
|
credentials.
|
|
|
|
```sh
|
|
bun install --frozen-lockfile
|
|
bun run build
|
|
bun run check
|
|
```
|
|
|
|
The root build selects every buildable leaf workspace, including all stock services and the
|
|
native engine. `bun run build --dry=json` shows the actual Turbo task plan.
|
|
|
|
| Command | Scope |
|
|
| ------------------------ | ------------------------------------------------------------------------------------------- |
|
|
| `bun run build:libs` | Build shared libraries in dependency order |
|
|
| `bun run build --clean` | Force every workspace build without cached results |
|
|
| `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/integration tests, and lint; report every failed gate |
|
|
|
|
`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 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
|
|
|
|
`@stock-bot/types` contains independent domain, job, and handler types.
|
|
`@stock-bot/services` composes service capabilities from the public APIs exported by the
|
|
owning adapters. It uses type-only imports and does not initialize connections.
|
|
|
|
```ts
|
|
import type { IServiceContainer, ServiceTypes } from '@stock-bot/services';
|
|
import type { ExecutionContext } from '@stock-bot/types';
|
|
```
|
|
|
|
The DI and handler packages re-export `IServiceContainer` for existing consumers. Queue
|
|
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.
|
|
|
|
## Backtest execution workflow
|
|
|
|
The orchestrator's `BacktestRunner` is the application boundary for both HTTP and decorated
|
|
jobs. It validates the request, claims a run, executes the configured native or TypeScript
|
|
backend, normalizes the result, and commits the result and terminal status in one transaction.
|
|
Completion events are published only after that commit. Progress cannot revive a terminal
|
|
run, duplicate claims are rejected, and unsupported controls do not change persisted state.
|
|
|
|
`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI.
|
|
Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%).
|
|
Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts
|
|
completed round trips. Undefined ratios remain `null`. Engine-specific supplemental metrics
|
|
retain their documented backend meaning.
|
|
|
|
The web API owns backtest definitions and pending-run creation; the orchestrator owns
|
|
execution state and result writes. V1 is a compatibility facade over V2, not a second SQL
|
|
schema or execution path. Strategy parameters and exact run configuration are preserved.
|
|
All historical readers delegate to the same storage policy; simulated fills do not enter
|
|
the trading ledger. Shared adapters are closed by DI, not by a backtest mode transition.
|
|
|
|
Deployment requires the additive migration
|
|
`database/postgres/init/09-backtest-run-contract.sql`, after the existing runs migration.
|
|
The web API's migration allowlist includes it. It adds configuration/provenance columns and
|
|
a unique result-per-run index without deleting history. Existing duplicate result rows must
|
|
be reconciled before applying that index. Historical rows without snapshots remain readable
|
|
and are explicitly marked `legacy`; their configuration is reconstructed from the definition.
|
|
New executions require PostgreSQL; there is no implicit in-memory production repository.
|
|
|
|
Native execution uses a disposable **worker process**, not the HTTP thread. A small
|
|
`BacktestExecutionEngine` port separates the runner from both implementations. The parent
|
|
owns storage reads and persistence; only serializable configuration, bars, progress, and
|
|
results cross IPC. One native worker runs at a time per orchestrator instance; additional
|
|
requests receive a conflict rather than spawning unbounded workers. The existing
|
|
`maxConcurrent` setting does not enable parallel runs through this serialized runner.
|
|
|
|
`services.orchestrator.backtesting.executionTimeoutMs` defaults to 300000 (five minutes)
|
|
and covers historical reads, worker startup, and native execution, not result persistence.
|
|
Cancellation and deadlines kill and reap the worker even during a synchronous Rust call.
|
|
A forced cancellation commits `cancelled` without a result row or fabricated partial metrics;
|
|
the original execution request returns HTTP 409 with `status: 'cancelled'`, and `/stop`
|
|
acknowledges only after that status is persisted. SSE publishes a terminal `cancelled` event.
|
|
Native pause/resume and speed controls remain explicitly unsupported. Native progress is
|
|
stage-level, not an invented percentage inside Rust's synchronous loop. Shutdown handles
|
|
SIGINT and SIGTERM, stops the worker, and settles its run before service cleanup.
|
|
|
|
The orchestrator build emits **both** `dist/index.js` and `dist/native-worker.js`; deploy
|
|
them together with the external `@stock-bot/engine` package/native binary. The worker does
|
|
not require source TypeScript in production. Process isolation is intentional: terminating
|
|
a thread cannot guarantee interruption or contain a native process crash.
|
|
|
|
The integration suite covers both real engines, REST/job parity, V1/V2 dispatch and result
|
|
reads, missing data, duplicate/concurrent requests, failed persistence/rollback, controls,
|
|
responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests
|
|
use an in-process PostgreSQL emulator and the real transaction manager, not a live database.
|
|
Durable queued dispatch and recovery after an orchestrator crash remain follow-up work.
|