| .githooks | ||
| .vscode | ||
| apps | ||
| database | ||
| docs | ||
| libs | ||
| monitoring | ||
| scripts | ||
| test | ||
| tools/coverage-cli | ||
| .coveragerc.json | ||
| .dockerignore | ||
| .env | ||
| .env.example | ||
| .gitignore | ||
| .gitlab-ci.yml | ||
| .prettierignore | ||
| .prettierrc | ||
| bun.lock | ||
| bunfig.toml | ||
| Cargo.lock | ||
| Cargo.toml | ||
| CLAUDE.md | ||
| docker-compose.dev.yml | ||
| docker-compose.yml | ||
| eslint.config.js | ||
| knip.json | ||
| package.json | ||
| proxy-playwrite.ts | ||
| README.md | ||
| test-e2e-backtest.sh | ||
| test-queue.ts | ||
| test-rust-strategies.js | ||
| test-typescript-strategy.js | ||
| tetest.ts | ||
| tsconfig.app.json | ||
| tsconfig.check.json | ||
| tsconfig.contracts.json | ||
| tsconfig.json | ||
| tsconfig.lib.json | ||
| tsconfig.unused.json | ||
| turbo.json | ||
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.
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.
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.
Historical input identity and reproducibility
Backtest symbols are exchange-qualified IDs such as AAPL.US or BRK.B.US, using
the existing EOD provider exchange namespace (not a guessed venue MIC). Ticker-only
definitions remain readable but must be explicitly updated before a new run. MongoDB
history reads match the qualified eodSearchCode and verify each returned identity;
QuestDB bars_<interval>.symbol must contain the same qualified ID. No ticker fallback,
automatic legacy-history rewrite, or cross-provider fallback is performed.
Provider namespace (providerExchange, also encoded in the ID) is distinct from the
source's exchange venue metadata. Older rows with a valid qualified key remain readable
without rewriting that metadata.
dataPolicy explicitly describes prices and timestamps:
adjustment: 'raw'is the default; no corporate-action accounting is implied.adjustment: 'provider-adjusted'scales all OHLC/VWAP prices byadjustedClose / close. Missing/nonpositive provider factors fail the run. This is the provider's combined split/dividend adjustment, not a split-only or point-in-time total-return model. Reported volume is unchanged; no extra dividend cash is credited.- Daily bars use
timestamp: 'utc-session-date': UTC-midnight session labels, not exchange close instants. Daily range boundaries must be UTC midnight. Intraday bars usetimestamp: 'utc-instant'with an explicit timezone. Ranges are[start, end). - Invalid prices, duplicate timestamps, mixed identities, or missing requested listings fail; prices are never interpolated or silently repaired. Market holidays are not synthesized, and exchange-calendar/session completeness is not yet verified.
Apply additive migration database/postgres/init/12-historical-datasets.sql via the
web API migration runner before starting a new backtest. The first execution attempt
validates and content-hashes the actual input bars and provenance, then atomically stores
them in backtest_datasets and pins runs.dataset_hash before executing any bar.
Recovered attempts reuse that snapshot, never revised provider data. Both execution
backends consume the same normalized, deterministically ordered bars with no second
corporate-action transformation. The TypeScript simulator's pseudo-random sequence is
seeded from the dataset hash; native same-timestamp seeks retain every listing.
The canonical result records the manifest in config.dataset: SHA-256 hash, listing
identities, range, interval, adjustment/timestamp/volume policies, source normalization
revision, and bar count. Replay through the runner by supplying datasetHash (or put it
in a V2 definition's config); the range, listings, interval and policy must match.
Missing, corrupted or incompatible snapshots fail instead of falling back to provider
history. Runs capture data at execution preparation, not HTTP acceptance time.
Reproducibility assumes the same engine/strategy code and configuration; the snapshot
is not an engine binary archive or a point-in-time constituent universe. Direct backend
calls can load data for diagnostics, but durable replay/persistence requires the runner.
Snapshots are currently JSONB and load in memory; large tick datasets need chunked storage
and an explicit retention policy before scaling.
Simulation order execution
ExecutionService is the runtime order gateway for REST, Socket.IO (when enabled), and
TypeScript strategies. PaperTradingManager is a compatibility facade, not a separate
simulator. Strategies consume only the ordered batch stream; individual-event broadcasts
cannot submit the same order a second time. Each event is delivered serially, including
awaited order/fill notifications before the next event. The TypeScript backtest uses this
same gateway with an explicit run-local repository; it does not write the paper ledger.
The isolated native backtest retains its own Rust loop and enforces its configured risk
limits before submission. Its projected notional and accounting rules have golden tests.
Paper execution requires PostgreSQL and additive migration
database/postgres/init/11-simulation-execution-ledger.sql (included in the web API migration
allowlist). Start the migrated web API before the orchestrator. New simulation_accounts,
simulation_orders, simulation_fills, and simulation_events tables are account-scoped.
The account snapshot (cash, positions, quotes, strategy quantities, risk state), order
reports, and uniquely identified fills commit on one checked-out connection under an
account row lock. No acceptance or fill notification is published before commit.
The snapshot is a bounded-by-instruments projection; normalized order/fill/event history is
kept separately. Historical rows in the old orders/fills/positions tables are preserved
but are not automatically adopted into the new ledger. Reconcile legacy paper holdings
explicitly before continuing an old account; this migration never infers an opening balance.
Unused direct financial writers were removed from StorageService.
Paper configuration accepts accountId (default paper-default), riskLimits, commission,
slippage, and maxQuoteAgeMs (default 60000). Restarting the same account restores cash,
positions, per-strategy quantities, consumed quote liquidity, and unfilled orders; it never
resets capital. A different starting capital requires an explicit new account ID. Strategy
indicator state is not checkpointed; strategies still need their normal warm-up. Pending
orders retain the commission/slippage policy under which they were accepted.
Order HTTP/Socket.IO submissions require a nonempty clientOrderId. Retrying an identical
request returns the existing order; reuse with different fields is a conflict (HTTP 409).
Strategies derive stable IDs from the strategy and source event. Supply a stable, unique
eventId on market data; identical replay is ignored, conflicting reuse is rejected. Without
an ID, a deterministic hash of the canonical event is used (identical same-timestamp payloads
are indistinguishable). Source events commit before strategy callbacks; a crash in that gap
can omit a signal, so this is not an exactly-once strategy-state recovery guarantee.
The deterministic simulator supports market/limit orders and DAY/GTC/IOC/FOK. Quote depth is consumed across orders, partial fills await fresh events, and limit orders never fill through their limit. DAY expiry is UTC/event-driven, not exchange-calendar-aware. Missing, stale, future, or invalid quotes cannot produce fills; unsupported stop orders are rejected. Backtests use completed-bar close/volume as a documented simulation input, not exchange execution guarantees. No random slippage or fabricated broker acknowledgements are used.
Position/order limits are shares; symbol/gross exposure and daily loss are account-currency amounts. Checks include projected positions, pending-order reservations, current marks, and an unlevered capital budget. Risk-reducing closes remain possible after a loss-limit breach. Daily loss rolls at UTC midnight, and each fill contributes its delta, never cumulative realized P&L. Fees are charged once, cash/equity include signed position value, and partial closes/reversals allocate entry/exit commissions proportionally. The paper model uses decimal arithmetic rounded to eight decimal places; it is single-currency and does not model FX, borrowing, interest, corporate actions, or exchange-specific settlement.
Live mode, broker/exchange routing, and direct native TradingEngine.submitOrder are
explicitly unsupported. They fail closed instead of reporting mock acceptance. Position,
P&L, and risk endpoints read the gateway ledger rather than native paper projections.
This milestone does not connect a broker, place real orders, or make the project live-ready.
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.