| .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:utils |
Test HTTP/date/proxy helpers and their handler HTTP consumer without infrastructure |
bun run test:calculations |
Test shared math, OHLCV transforms, legacy capability preservation and research snapshots |
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, contracts, tooling, utilities, calculations, integration, native tests, and lint |
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.
Shared calculation and utility boundaries
@stock-bot/calculations owns pure reusable math for strategies, data processing and
feature engineering. Its supported subpaths expose reviewed returns, indicators, OHLCV
transforms and the previously tested orchestrator analytics/window math. The orchestrator
now consumes that library; no database, native binding, HTTP or application service is
required to import it. Existing strategy checkpoint versions and financial execution
behavior are unchanged by this relocation.
All 105 formerly active financial calculation functions remain available behind the
explicit @stock-bot/calculations/legacy namespace, with unchanged executable bodies.
This is preservation, not a production-correctness endorsement. All seven previously
disabled prototypes, including unique additional indicators, survive as non-executable
source-verified research snapshots. See the calculation contract
for supported units, undefined values, alignment and the review/promotion path.
@stock-bot/utils retains HTTP/user-agent, proxy/sleep and validated UTC date/weekday
helpers through explicit capability subpaths. Deprecated dateUtils names are aliases,
not an exchange holiday/session calendar. Assertions belong to @stock-bot/invariants,
and domain types to @stock-bot/types. The coverage CLI no longer declares an unused
utility dependency, and unused simple-statistics is removed.
Only empty placeholder/redundant entry points remain removed; old numerical and Redis test sources are retained as explicit legacy/research references rather than runnable backups or claimed passing coverage. The cleanup audit accounts for every removal in this batch. The utility contract documents the restored helpers and migration notes. Architecture tests enforce the ownership and dependency boundaries without forbidding useful shared domain libraries.
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.
Orchestrator boundaries and extension points
Keep runtime composition in container.ts; domain code receives explicit capabilities,
not the application service container:
contracts/holds runtime validation schemas. Contracts and the native worker protocol cannot load storage, native engines, or server adapters.execution/model.tsowns accounting/risk rules;execution/repository.tsis the storage port, independent of either implementation.SimulationExecutionapplies order admission, matching and accounting inside the caller's transaction. It does not open transactions or publish notifications.StrategyRecoveryowns decision scopes, checkpoint/cursor commits and outbox replay. Its typed runtime port preserves the gateway's transaction and serialization boundaries.ExecutionServicecomposes those components, owns lifecycle/market admission, selects the repository, and publishes only after commit. HTTP and strategies continue using this gateway.StrategyManagerowns lifecycle/delivery;StrategyRegistryowns strategy factories and aliases. Add a lazy factory tocreateBuiltinStrategyRegistry(), or provide a customstrategyRegistrytoregisterOrchestratorServices. No manager switch needs updating. Keep persisted aliases stable; a custom registry must also be supplied on restart.
Supported TypeScript implementations live in strategies/builtin/: SmaCrossoverStrategy
and MeanReversionStrategy. Optional ML research lives in strategies/experimental/, still
lazy-loaded and unavailable for paper execution. The unregistered strategy variants and their
private position/risk framework have been removed; ExecutionService remains the financial
authority. File/class relocation preserves the existing aliases and v2 checkpoint versions.
Use the strategy extension guide
for the supported lifecycle and a type-checked, integration-tested runner example. Removed
internal deep imports must migrate; their source remains recoverable in Git history.
New paper strategies must provide a complete versioned checkpoint contract and recovery tests. Registering a factory does not bypass risk checks or the durable-checkpoint requirement. The experimental ML strategy remains unavailable for paper execution.
Architecture tests run in bun run check, checking runtime dependency cycles and the
contract/domain/adapter boundaries. The run-local ledger stages only transaction writes,
indexes active work and client IDs, and binary-searches the journal; retained history is not
deep-copied for every read. Reads/writes remain detached and failed transactions publish
nothing. History is still retained in memory for the run; this is not a streaming/retention
solution. Run bun run scripts/benchmark-execution.ts for a local journal-read microbenchmark,
not an end-to-end backtest performance estimate.
Strategy parameters and indicator math
contracts/strategy-names.ts owns built-in aliases; spaces, underscores and hyphens normalize
to the same identity. contracts/strategies.ts owns backend-specific parameter schemas, and
backtest/strategy-plan.ts applies shared defaults followed by per-strategy overrides for
both backends. Disabled entries do not run or consume TypeScript allocation. Invalid built-in
parameters fail before historical input loading; unknown/unsupported keys, numeric strings,
fractional periods and nonfinite values are rejected rather than ignored or truncated.
Custom TypeScript factories retain their own parameter contracts and extension fields.
Periods are integer bars bounded by 10000, with fastPeriod < slowPeriod for SMA. Both SMA
backends default to 5/15 and accept an explicit quantity in shares (1e-8 through 1e9).
Without quantity, TypeScript SMA uses positionFraction (default 0.1 of account equity),
while native SMA uses 100 shares. Native mean reversion, momentum and pairs retain their
positionSize parameter in shares, not an equity fraction. TypeScript mean reversion
accepts configurable lookback/trend/RSI windows, entry/exit thresholds and notional-volume
filter; its optional quantity is also shares. Do not transfer backend-only parameters blindly.
@stock-bot/calculations/indicators shares slice-free trailing mean, population deviation
and crossover calculations across TypeScript strategies. A crossover requires slowPeriod + 1
bars, including a complete previous window; missing warm-up is not a synthetic zero average.
Tests compare the scalar math with real Rust batch/incremental indicators and exercise
configured SMA fills in both backends. This is not full algorithm/result parity: entry/exit
and RSI rules differ, and native backtests force liquidation at the end while TypeScript
backtests retain open positions. Corrected warm-up and previously ignored settings can change
historical results.
TypeScript backtest composition
BacktestEngine coordinates fresh components for each run:
BacktestPlaybackowns the input cursor, pacing and interruptible pause/resume/stop. Frozen bars are consumed in order without a second event array or queue shifting; unlimited playback periodically yields so cancellation and lease heartbeats can run.BacktestMarketowns seeded market projection and per-symbol microstructure defaults. It cannot submit orders; financial state still belongs to the execution ledger.BacktestReportrecords ledger equity and builds a detached completed snapshot.report-format.tsformats that snapshot without re-reading the engine or adding trades.
Overlapping runs fail before state changes. Cancellation raises BacktestCancelledError;
the runner records cancellation without persisting a partial successful result. Pending
historical reads cannot resume a cancelled run, and stop wakes paused/paced playback.
Arbitrary custom strategy callbacks are still cooperative, not forcibly isolated.
Equity and final position valuations come from ExecutionService, not a best-effort native
P&L projection. Missing ledger state fails; zero/negative equity is never replaced with
starting capital. Drawdown duration uses simulated time. Month-end returns use UTC boundaries
and the preceding month-end balance (initial capital for the first month); percentage returns
with a nonpositive baseline are omitted. These corrections can change historical metrics.
exportResults() is available after successful completion until the next run begins.
Repeated JSON/CSV/HTML exports retain the finished equity and trade count; exports cannot
mutate analysis. Charts and quality observations group frozen bars in one pass, but datasets
and detailed equity history still reside in memory; this is not a streaming backtest engine.
Analytics correctness and availability
orchestrator/src/analytics/{equity,return-statistics,trade-statistics,performance}.ts
contains pure shared math. PerformanceAnalyzer is a detached, cached compatibility facade;
BacktestReport consumes that same analysis instead of recalculating daily returns, drawdowns
and risk statistics. Core returns and risk magnitudes are fractions. The legacy direct-backend
and report-summary percentage-point fields are converted only at the facade; the runner's
persisted/public BacktestRunResult still uses fractions. Risk statistics no longer apply
volatility/VaR calculations directly to percentage-point returns (the former 100× scaling bug).
Conventions are explicit and covered by golden fixtures:
- UTC daily/month-end observations use the final value in each period. The first period uses initial capital, so its gain/loss is not discarded. Nonpositive subsequent denominators are omitted rather than replaced; same-timestamp observations use the last value.
- CAGR uses observed elapsed calendar time (365 days/year), and is
nullfor zero elapsed time, nonpositive ending equity or an unrepresentable result. Total losses and drawdowns beyond 100% remain valid observations; no opening balance is invented. - Volatility uses sample standard deviation and 252 observed daily periods/year. Sharpe uses arithmetic daily excess returns against a 2% annual reference rate divided by 252, not CAGR divided by volatility. See Sharpe's definition.
- Sortino uses full-series downside RMS relative to that daily reference target, not the standard deviation of only negative returns. The denominator includes every observed return; see PerformanceAnalytics' downside-deviation conventions.
- Historical VaR/CVaR are nonnegative loss magnitudes from the worst empirical tail. The 95% tail requires at least 20 returns; the 99% tail requires 100. These are historical statistics, not forecasts. Sparse observed dates are not an exchange-calendar completeness guarantee.
- Drawdown periods have independent peak-to-trough depth, recover on equality with the peak, and measure calendar days from the first below-peak observation to recovery or the observed end. Ongoing periods are explicit; neither duration nor depth comes from another period.
- Undefined ratios and insufficient-sample statistics are
null, not zero or infinity. Profit factor isnullwith no losses; breakeven trades reset win/loss streaks. Empty trade series retain zero trade count/win rate as a convention. UI/text ratios display unavailable values as “N/A” or “-”; JSON preservesnull. The old leverage field remains a compatibility heuristic, not an optimizer or trading recommendation.
Corrected analytics can change new-run results. Existing saved rows are not recalculated and no database migration/reset is performed. Native trading algorithms and engine-specific supplemental statistics are not silently redefined by this TypeScript math refactor.
The external analytics client validates finite responses, ordered instrument/model identity, portfolio weights and correlation matrices (including positive semidefiniteness). Requests have a five-second timeout and one-MiB response limit. Its success cache is capped at 128 entries with per-entry TTL; failed/expired requests never become fresh fake observations. HTTP 503 means unavailable upstream/data; 502 means an invalid upstream response; invalid client input remains 400. No outage produces zero risk metrics, equal portfolio weights, an identity correlation matrix or a “normal” market regime.
The Python portfolio-performance/risk, regime, correlation, saved-backtest-analysis and attribution endpoints currently have no observed-data adapter. They now return explicit 503 instead of random samples or constant reports. They remain unavailable until real data is integrated; research helpers are not production data sources. Optimization still consumes caller-provided returns/symbols, and prediction requires an actual loaded model. TypeScript maps their snake-case Python wire fields explicitly rather than guessing weights/identities.
Run bun run check for TypeScript/native checks and analytics regression fixtures.
Separately run bun run test:analytics-api for real FastAPI router HTTP tests. That optional
command needs Python 3.12 and uv; it obtains the FastAPI/HTTPX/Pydantic versions already
pinned by the Python service, without installing the research/ML runtime. It tests the router,
not full Python-service startup or a live upstream deployment.
Backtest data integrity
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.
Dataset preparation has no application-level instrument, bar-count or payload-size caps.
Internal handoffs reuse deeply frozen validated inputs; restored snapshots are always
content-checked. Existing v1 hashes and replay identities are unchanged. Snapshots remain
JSONB and load in memory. See dataset preparation.
Simulation order execution
Durable strategy recovery
Apply additive migration 13-strategy-recovery.sql through the web API before starting
the orchestrator. Paper startup restores registered strategy configurations and their
checkpoints before connecting the feed. No running database is migrated by the tests.
The recovery path has four checked transaction boundaries:
- Validate and durably admit a uniquely identified market payload into
simulation_market_inputs; retries cannot append a second input or change its payload. - Apply the next input's quote/account changes and resting-order fills, journal the execution notifications and market payload, and mark the input applied atomically.
- Restore each strategy's latest checkpoint under the account row lock, evaluate its next journal record, then commit indicator/base state, cursor, and order intents together.
- Dispatch an intent through the ordinary risk/idempotency gateway; order/fill accounting, its execution journal notification, and the intent's dispatched status commit together.
New inputs can queue during an outage or strategy error. Later inputs and new manual
orders cannot advance past unfinished enabled-strategy delivery or pending intents.
Idempotent order retries still return their committed report; explicit cancellations remain
available. Execution/fill notifications have their own durable cursor delivery, not a
volatile callback. Strategy reads use the journal's as-of account view, not future quotes.
Competing service instances always restore the locked checkpoint before evaluating a step.
The manager retries recovery every second without requiring another feed tick, and
GET /api/recovery exposes pending work and per-strategy cursor lag behind normal API auth.
SMA (both implementations) and mean reversion have explicit versioned indicator contracts. Base checkpoints include positions, pending orders, performance and a bounded recent-fill cache; the durable cursor, not the cache size, guarantees delivery deduplication. A changed configuration or checkpoint/implementation version requires an explicit new strategy ID; there is no implicit state reset or best-effort schema coercion. Developers must bump the strategy version when its state or decision semantics change. Custom paper strategies must implement and validate their complete finite-JSON checkpoint. Uncheckpointed/experimental ML paper strategies fail before model startup: asynchronous model training and weights do not yet have a replay-safe artifact contract. Run-local backtests can still use explicitly unversioned experimental strategies, without claiming restart recovery for their custom state.
The configurable SMA and mean-reversion implementations now use checkpoint version v2. They do not resume v1 registrations. Before deploying against an existing paper account, explicitly pause the affected v1 registrations using the compatible runtime, review pending intents/open orders, and register new strategy IDs with validated v2 parameters and fresh indicator warm-up. Enabled v1 registrations block recovery even if a new ID is also supplied. Pausing does not cancel committed work. No upgrade step rewrites checkpoints, resets account balances or deletes historical registrations; tests do not modify running development accounts.
Strategy evaluation must be bounded and deterministic: no fire-and-forget state mutation, wall-clock/random decisions, broker calls, model training or external I/O in callbacks. Repository I/O/direct submissions from a callback fail closed; use the as-of account view and captured order intents. These callbacks run under an account lock, so an unbounded custom callback stalls that account until its owner exits; isolation/time limits for arbitrary third-party code are not provided here. Noncritical signal/UI observers run after commit; their failure cannot erase a financial intent, but those observations are not a durable bus.
Graceful shutdown suspends strategies without cancelling durable orders or erasing indicators.
StrategyManager.disableStrategy pauses new decisions, preserving already committed
intents and open orders; it is not an emergency order-cancel switch. Disabled-period market
records do not become retroactive signals on re-enable. To cancel, use the explicit order
API (or an intentional strategy stop). If a recovered paper quote has aged out, its indicator
state is recovered but it cannot generate fabricated historical fills: resulting stale-price
orders are rejected by the normal gateway.
Legacy fingerprints without payloads are preserved, not invented into replay history. New registrations begin at the current journal boundary with the existing financial projection; pre-migration indicators/performance cannot be reconstructed automatically. This guarantees recovery of admitted inputs, not delivery from an upstream socket before admission. A provider replay/acknowledgement protocol is still required for that boundary. Journal/input/history tables currently retain JSONB payloads and as-of account snapshots; configure an archival/retention design before high-volume production use. Do not delete history still needed by a paused strategy's cursor.
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 checkpointed for supported strategies; a new strategy still needs its
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). Admitted source events, strategy delivery and financial notifications
now have durable recovery as described above; this is not a real-broker exactly-once 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/stock-config/backtest owns the pure execution request schema, parsing and
defaults used by API definition snapshots, the runner and both backends. The subpath
loads no configuration manager or infrastructure. API date labels are translated to UTC
before execution; direct execution requests keep their existing full-ISO timestamp shape.
Strategy-specific parameter validation remains with each execution backend. Invalid
execution settings now fail before a definition/run write rather than being queued for
later rejection. Existing schema imports from the orchestrator remain compatibility exports.
BacktestExecutionSettingsSchema also identifies execution-only fields in legacy mixed
config bags. After shared defaults and per-strategy overrides are merged, the common
planner removes those fields before validating built-in parameters. For example,
dataFrequency selects run input, not an indicator parameter; a per-strategy copy cannot
override the run. Unknown parameter keys still fail validation. Custom TypeScript factories
retain their existing extension-field contract. Original mixed configs remain unchanged in
request snapshots and result provenance, including replay; no saved configuration migration
or checkpoint-version change is required.
@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.
Stored-result compatibility conversion lives in the web API's pure backtest-result.ts
mapper, separate from SQL and run control. Current snapshots are returned without unit
conversion; pre-contract native/TypeScript rows retain their existing legacy unit rules.
Reading a result never rewrites the stored history or recalculates its metrics.
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.