stock-bot/README.md
2026-10-20 20:11:40 -04:00

249 lines
17 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 migrations
`database/postgres/init/09-backtest-run-contract.sql` and `10-durable-backtest-dispatch.sql`,
after the existing runs migration. The web API's migration allowlist includes both.
The first 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 dispatch and recovery
`POST /api/v2/backtests/:id/runs` returns **202** with a pending run ID and a `Location`
header. In one PostgreSQL transaction it stores the run, its immutable execution request,
and a `backtest_dispatch` intent. No Redis/HTTP call is needed to accept the run. Editing
a definition later does not change an accepted run. The V1 facade uses the same workflow.
The orchestrator's direct synchronous REST execution routes remain compatibility endpoints.
The web API runs a producer-only dispatcher (zero workers) every five seconds. It reserves
due intents with `FOR UPDATE SKIP LOCKED` and publishes identity-only notifications to the
existing `{orchestrator_orchestrator}` queue. Stable job IDs deduplicate outstanding jobs;
pending intents are republished every 30 seconds, including after a lost Redis job or a
publisher restart. Redis outages leave accepted runs pending; they do not falsely fail them.
The queue clients honor explicit Redis endpoints and reconnect after transient outages.
Each orchestrator consumes one job at a time. It atomically claims a pending run with a new
attempt UUID and a 30-second PostgreSQL-clock lease, renewed every five seconds. Progress,
controls, failure, cancellation, and terminal result writes are fenced by that attempt and
an unexpired lease. A lost heartbeat stops the local execution and leaves recovery to the
dispatcher. Expired owners are retried from their saved request, up to three execution
attempts; exhaustion becomes `failed`. Terminal redelivery is acknowledged without rerunning.
Computation is at-least-once, not exactly-once; only an owned result can commit, atomically
with terminal status, and the unique result-per-run constraint remains the final guard.
Recovery also depends on BullMQ detecting stalled jobs and the API dispatcher being available.
Cancellation is durable: queued runs become `cancelled` before a claim; active runs record
`cancel_requested` for their owner to observe, stop, and acknowledge. The V2 cancel endpoint
returns **202**, not a claim that execution already stopped. A cancelled abandoned lease
becomes `cancelled`, without a result. The dashboard keeps polling until persisted terminal
state; WebSocket updates are read from committed SQL state, not an in-memory dispatch request.
Native pause/resume/speed remain unsupported; those compatibility controls still require
the HTTP request to reach the owning instance.
Before applying migration 10, **stop all older orchestrators**, start the migrated web API,
then start lease-aware orchestrators. Legacy pending runs receive a one-time snapshot of
their current definition; legacy active runs with no owner token are marked failed rather
than pretending they are recoverable. Existing results are preserved. Infrastructure should
supervise the orchestrator process tree: SIGKILL of a parent cannot guarantee reaping a child
blocked in native code, though a stale child cannot persist a result through the fenced parent.
No migration or restart is performed against your existing local databases by the tests.
## HTTP access and secrets
HTTP services now fail closed unless server-side access tokens are configured. Use the
root `.env` (`.env.example` documents the settings) and set independent `STOCK_BOT_ADMIN_TOKEN` and
`STOCK_BOT_SERVICE_TOKEN` values (at least 32 characters; generate each with
`openssl rand -hex 32`). An optional distinct `STOCK_BOT_READ_TOKEN` permits read-only
access. The same service token must be available to internal HTTP clients and servers.
Never put these tokens in `VITE_*` settings, URLs, source files, or logs.
CLI clients use `Authorization: Bearer <token>`. The dashboard sign-in exchanges an
admin/read token for a signed one-hour HttpOnly, SameSite=Strict cookie; it does not store
the token in localStorage or include it in the bundle. Production cookies require HTTPS.
Read-only access cannot mutate data; all mutation/admin operations require admin/service
access. Internal services do not accept browser cookies. WebSocket upgrades authenticate
and validate browser Origin. Session-key rotation invalidates issued cookies; logout clears
the browser cookie (copied cookies remain valid until expiry or key rotation). This is an
operator-access boundary, not a multi-user identity/tenant system.
Dashboard/API URLs must be same-site for the strict cookie policy. In local development,
use matching hostnames (`localhost` for both, or `127.0.0.1` for both), not a mixture.
`STOCK_BOT_HTTP_HOST` defaults to `127.0.0.1`. Set it explicitly for containers. Set
`STOCK_BOT_ALLOWED_ORIGINS` to an exact comma-separated list of trusted frontend origins;
production same-origin requests are supported, and reverse-proxy deployments must include
the public HTTPS origin. Wildcard/null origins are rejected. For isolated local demos only,
`STOCK_BOT_AUTH_DISABLED=true` is allowed on a loopback development/test listener, never
in production. Health endpoints remain public. TLS termination and external rate limiting
belong at the deployment boundary; do not expose development services directly.
The root `.env` and `apps/stock/web-app/.env` are intentionally tracked for this private,
local-development repository. Other environment files remain ignored;
`bun run audit:secrets` rejects unexpected tracked environment files outside these two
explicit exceptions (WCAG excluded). It is not a complete secret scanner. Keep production
credentials out of these files. Committed values remain in Git history; rotate any real
credentials before sharing the repository or if access changes. Logging still redacts
sensitive fields, bearer tokens, credentialed URLs, and sensitive URL query parameters.
Development database/admin-UI Compose ports bind to loopback; existing containers must
be recreated for changed port bindings to take effect.
## Pipeline safety
Routine exchange/symbol/provider-mapping syncs are non-destructive. Legacy
`clearFirst: true` requests are rejected; scheduled exchange syncs no longer reset data.
The transactional sync paths share one checked-out PostgreSQL connection and one
transaction-scoped advisory lock. SQL errors roll back the whole batch and sync status,
and existing curated exchange/provider mappings are preserved. Do not add pooled
`query('BEGIN')` calls: use a transaction-scoped repository.
Reference-data reset is a separate admin maintenance operation. Send a JSON body to
`POST /api/pipeline/clear/postgresql` with an explicit `type` (`provider_mappings`,
`exchanges`, or `all`) and `confirmation: "DELETE STOCK REFERENCE DATA:<type>"`.
There is no default scope. A mapping-only reset deletes symbol-provider mappings only;
an exchange-only reset fails atomically if symbols still reference exchanges; `all`
deletes reference mappings, symbols, and exchanges in foreign-key order. These resets do
not delete backtest history, prices, or trading records. The dashboard requires typing
the matching confirmation. Generic queue access remains administrator-only.
`bun run test:native` is part of `bun run check`. The stochastic tests explicitly cover
warm-up (14-bar K plus 3-value D needs 16 bars), invalid periods, golden values, and
incremental/batch parity; no synthetic D values are produced before warm-up completes.
`bun run test:postgres` additionally requires `PIPELINE_TEST_DATABASE_URL` pointing to a
**disposable database whose name starts with `stock_bot_safety`**. It creates/drops isolated
test schemas and verifies real rollback, foreign-key constraints, idempotency, and competing
transaction locking. Set `BACKTEST_TEST_REDIS_URL` to a dedicated Redis fixture using database
15 as well; queue names are unique per test. The durability tests cover HTTP acceptance,
outbox rollback, immutable requests, migration replay, hard-killed owners, stale-write fencing,
cancellation races, retry exhaustion, disconnected publishing, and lost-job redelivery with
the real native engine. CI provisions PostgreSQL and Redis and runs this additional gate.
It is separate from the infrastructure-free `check`; never point tests at production.