This commit is contained in:
Boki 2026-11-26 22:23:07 -05:00
parent c353ddbe01
commit ce9e2df67c
310 changed files with 2550 additions and 36861 deletions

View file

@ -1,148 +0,0 @@
# Strategy architecture and extension guide
## Supported execution paths
HTTP and decorated backtest jobs use `BacktestRunner`, which owns input snapshots,
claims, leases, terminal persistence and completion publication.
- TypeScript backtests and paper trading use `StrategyManager` and `BaseStrategy`.
Signals become captured order intents, then pass through `ExecutionService`.
- Native backtests use `RustBacktestAdapter` and a disposable native worker process.
The worker registers Rust strategies, not TypeScript callbacks.
- The simulation ledger owns cash, positions, fills, pending reservations and risk admission.
Strategy checkpoints contain decision state and journal-derived projections; they are not
a second account ledger. Native market/analytics projections are not the paper account.
Live routing and native TypeScript callbacks are explicitly unsupported. Do not create
another inline executor, call native order submission, or bypass the runner for durable jobs.
## Runtime composition
`container.ts` creates the runtime graph and binds each required dependency explicitly.
The engines and strategy/mode/market-data lifecycle do not look up peers in `services.custom`.
Both backends receive the same storage instance; the native adapter never constructs one.
The strategy manager accepts a bound `createStrategy` callback instead of loading a registry
or discovering the mode manager. Custom registries supplied through `registerOrchestratorServices`
still receive `{ modeManager, execution }`; no strategy factory or checkpoint migration is needed.
Deferred callbacks are wired only at composition: market flush awaits strategy delivery, and
factories/backtests obtain the current mode's engine after mode initialization. `ModeManager`
owns that engine; `StrategyManager` no longer caches a second reference or exposes a getter.
Paper restoration still completes before feed startup, and shutdown still flushes the feed
before stopping strategies, execution and storage. HTTP/job adapters retain the existing
application lookup surface, separate from the internal graph.
## Strategy layout
```text
src/strategies/
BaseStrategy.ts common signal, intent and checkpoint lifecycle
StrategyManager.ts registration, delivery and restart recovery
StrategyRegistry.ts injectable factory/alias registry
builtin-strategies.ts lazy composition of concrete implementations
builtin/
SmaCrossoverStrategy.ts canonical registered SMA implementation
MeanReversionStrategy.ts canonical registered mean reversion
experimental/
MLEnhancedStrategy.ts optional, run-local experiment
```
Core/API code loads concrete strategies through the registry, not direct imports.
Built-ins cannot depend on experimental implementations. Parameter schemas live in
`src/contracts/strategies.ts`; alias identity lives in `strategy-names.ts`.
`backtest/strategy-plan.ts` gives both backends the same global-default/per-strategy-override
precedence while retaining explicit backend-specific parameters and behavior.
Run-wide fields are defined by `BacktestExecutionSettingsSchema` in the portable
`@stock-bot/stock-config/backtest` contract. The planner projects legacy mixed configs into
built-in parameters using that schema; do not add another manual execution-field exclusion
list. Per-strategy copies of execution settings never override the run. Unknown parameter
keys remain visible to strict strategy validation. Custom TypeScript factories keep their
factory-owned extension fields, and original request/result configs stay intact for replay.
The legacy `useTypeScriptImplementation` hint never changes the selected backend; `true`
is rejected by the native path.
Persisted aliases and checkpoint versions remain stable across this source relocation:
SMA still reports `sma-crossover-fixed/v2`, and mean reversion reports
`mean-reversion/v2`. The word `fixed` in the persisted version is compatibility metadata,
not a second implementation. No financial data or saved checkpoints are rewritten.
The earlier v1-to-v2 cutover requirement in the [root README](../../../../README.md#durable-strategy-recovery)
still applies; this layout cleanup introduces no additional version change.
## Adding a strategy
1. Extend `BaseStrategy`, adding a focused module under `builtin/` for supported behavior
or `experimental/` for research. Keep helpers independent of strategy lifecycle where possible.
2. Validate configuration at construction and inactive edits. Use explicit units, finite values
and bounded periods. Existing built-in contracts reject unsupported keys instead of ignoring them.
3. Implement bounded per-instrument indicator state in `updateIndicators` and return a
`Signal | null` from `generateSignal`. Reuse `@stock-bot/calculations/indicators` for trailing
scalar SMA/deviation/crossovers, or the documented native indicator wrapper for other math.
4. For paper execution, provide a version string and complete finite-JSON capture/restore
contract for custom state. Version changes and changed configurations require deliberate
new strategy IDs; never reset an existing account or coerce an incompatible checkpoint.
5. Register a lazy factory and stable aliases in `createBuiltinStrategyRegistry()`, or inject
a custom registry through `registerOrchestratorServices`. A custom registry must also be
provided on restart. No manager switch or alternate execution loop is needed.
6. Test schema rejection, warm-up, multiple instruments, fill-based position changes and
checkpoint/restart equivalence. Use real gateway admission and repository transactions,
including rollback and duplicate-delivery cases.
Callbacks run within a durable decision scope and must be deterministic and bounded.
Do not perform external I/O, use wall-clock/random decision inputs, train models, launch
fire-and-forget state mutations, or directly submit orders from callbacks. ExecutionService
applies the account-level limits even when a strategy adds its own signal/sizing constraints.
Do not recreate strategy-local cash/P&L books or a separate risk-admission manager.
The [registry/recovery fixture](../../../../test/fixtures/strategy-recovery.ts) and
[registry integration tests](../../../../test/integration/strategy-registry.test.ts) show
an injected extension using the same lifecycle. The supported built-ins show complete
configuration and indicator-checkpoint implementations.
## Experiments and examples
ML remains lazy-loaded and explicitly experimental. It has no replay-safe model artifact
or complete checkpoint contract, so paper activation fails before TensorFlow/model startup.
Moving it under `experimental/` does not make its training deterministic or production-ready.
[The multi-strategy example](../examples/multi-strategy-backtest.ts) accepts the application's
already-composed TypeScript `BacktestRunner` and a qualified historical range. Importing it
starts no services and executes nothing. The caller owns service shutdown; results come from
the ordinary ledger-backed workflow and are persisted by the runner. For example:
```ts
await runMultiStrategyBacktest(runner, {
symbols: ['AAPL.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-04-01T00:00:00.000Z',
});
```
This needs actual stored daily bars; it does not manufacture benchmark returns, correlations
or broker features. The example is included in root type checking and exercised by the
backtest workflow integration tests. Other old diagnostic scripts in `examples/` are not
the supported extension contract.
## Retired paths
The unused TypeScript `RustBacktestEngine`/`RustStrategy` callback wrapper and inline
`StrategyExecutor` were removed. The unregistered original/V2/Rust SMA variants,
`AdvancedMultiIndicatorStrategy`, `IndicatorBasedStrategy` and their private
indicator/position/risk/signal-manager framework were also removed. They are recoverable
from Git history (before this cleanup, commit `4207bf2`), not maintained runtime alternatives.
Deep imports of those internal files must migrate to the registry or canonical implementation.
The native SDK's explicit unsupported-operation errors remain as safety boundaries.
## Verification
From the repository root:
```sh
bun run check
bun test test/integration/strategy-registry.test.ts test/integration/strategy-contracts.test.ts
```
The root gate checks cycles, registry-only strategy loading, retired entry points,
worker-only native backtest access and the prohibition on direct strategy order submission.
See the root README for disposable PostgreSQL/Redis safety tests; never run fixture resets
against a development or production account.

View file

@ -1,487 +0,0 @@
# Rust Core Enhancement Roadmap
> Historical research ideas, not a current architecture/status assessment. Paper order
> lifecycle, accounting and risk admission now belong to the execution ledger, while native
> backtests run in isolated workers. TypeScript callbacks into the native backtest engine and
> live routing are unsupported. Use [the current extension guide](architecture-improvements.md)
> and the root README before implementing anything below; do not create another account ledger.
## Missing Components & Potential Additions
### 1. **Order Management System (OMS)**
Currently missing a comprehensive order lifecycle management system.
```rust
// Suggested additions to orders module
pub struct OrderManager {
active_orders: DashMap<String, Order>,
order_history: Vec<OrderEvent>,
order_routes: HashMap<String, OrderRoute>,
}
pub enum OrderEvent {
Submitted { order_id: String, timestamp: DateTime<Utc> },
Acknowledged { order_id: String, broker_id: String },
PartialFill { order_id: String, fill: Fill },
Filled { order_id: String, avg_price: f64 },
Cancelled { order_id: String, reason: String },
Rejected { order_id: String, reason: String },
Modified { order_id: String, changes: OrderModification },
}
pub struct OrderModification {
quantity: Option<f64>,
price: Option<f64>,
stop_price: Option<f64>,
}
```
### 2. **Advanced Order Types**
Current order types are basic. Missing:
```rust
pub enum OrderType {
// Existing
Market,
Limit { price: f64 },
Stop { stop_price: f64 },
StopLimit { stop_price: f64, limit_price: f64 },
// Missing
Iceberg { visible_quantity: f64, total_quantity: f64 },
TWAP { duration: Duration, slices: u32 },
VWAP { duration: Duration, participation_rate: f64 },
PeggedToMidpoint { offset: f64 },
TrailingStop { trail_amount: f64, trail_percent: Option<f64> },
OCO { order1: Box<Order>, order2: Box<Order> }, // One-Cancels-Other
Bracket { entry: Box<Order>, stop_loss: Box<Order>, take_profit: Box<Order> },
}
```
### 3. **Portfolio Management**
No portfolio-level analytics or optimization.
```rust
pub mod portfolio {
pub struct Portfolio {
positions: HashMap<String, Position>,
cash_balance: f64,
margin_used: f64,
buying_power: f64,
}
pub struct PortfolioAnalytics {
pub fn calculate_beta(&self, benchmark: &str) -> f64;
pub fn calculate_correlation_matrix(&self) -> Matrix<f64>;
pub fn calculate_var(&self, confidence: f64, horizon: Duration) -> f64;
pub fn calculate_sharpe_ratio(&self, risk_free_rate: f64) -> f64;
pub fn calculate_sortino_ratio(&self, mar: f64) -> f64;
pub fn calculate_max_drawdown(&self) -> DrawdownInfo;
}
pub struct PortfolioOptimizer {
pub fn optimize_weights(&self, constraints: Constraints) -> HashMap<String, f64>;
pub fn calculate_efficient_frontier(&self, points: usize) -> Vec<(f64, f64)>;
pub fn black_litterman(&self, views: Views) -> HashMap<String, f64>;
pub fn risk_parity(&self) -> HashMap<String, f64>;
}
}
```
### 4. **Market Data Enhancements**
Missing Level 2 data, options data, and advanced market data types.
```rust
pub enum MarketDataType {
// Existing
Quote(Quote),
Trade(Trade),
Bar(Bar),
// Missing
Level2 { bids: Vec<PriceLevel>, asks: Vec<PriceLevel> },
Imbalance { buy_quantity: f64, sell_quantity: f64, ref_price: f64 },
AuctionData { indicative_price: f64, indicative_volume: f64 },
OptionQuote {
strike: f64,
expiry: DateTime<Utc>,
call_bid: f64,
call_ask: f64,
put_bid: f64,
put_ask: f64,
implied_vol: f64,
},
Greeks {
delta: f64,
gamma: f64,
theta: f64,
vega: f64,
rho: f64,
},
}
```
### 5. **Execution Algorithms**
No implementation of common execution algorithms.
```rust
pub mod execution_algos {
pub trait ExecutionAlgorithm {
fn generate_child_orders(&mut self, parent: &Order, market_state: &MarketState) -> Vec<Order>;
fn on_fill(&mut self, fill: &Fill);
fn on_market_update(&mut self, update: &MarketUpdate);
}
pub struct TWAPAlgorithm {
duration: Duration,
slice_interval: Duration,
randomization: f64, // Add randomness to avoid detection
}
pub struct VWAPAlgorithm {
historical_volume_curve: Vec<f64>,
participation_rate: f64,
min_slice_size: f64,
}
pub struct ImplementationShortfall {
urgency: f64,
risk_aversion: f64,
arrival_price: f64,
}
pub struct Iceberg {
visible_size: f64,
refresh_strategy: RefreshStrategy,
}
}
```
### 6. **Options Support**
No options trading infrastructure.
```rust
pub mod options {
pub struct OptionContract {
underlying: String,
strike: f64,
expiry: DateTime<Utc>,
option_type: OptionType,
multiplier: f64,
}
pub enum OptionType {
Call,
Put,
}
pub struct OptionPricer {
pub fn black_scholes(&self, params: BSParams) -> OptionPrice;
pub fn binomial(&self, params: BinomialParams) -> OptionPrice;
pub fn monte_carlo(&self, params: MCParams, simulations: u32) -> OptionPrice;
}
pub struct OptionGreeks {
pub fn calculate_greeks(&self, contract: &OptionContract, market: &MarketData) -> Greeks;
pub fn calculate_implied_volatility(&self, price: f64) -> f64;
}
pub struct OptionStrategy {
legs: Vec<OptionLeg>,
pub fn calculate_payoff(&self, underlying_price: f64) -> f64;
pub fn calculate_breakeven(&self) -> Vec<f64>;
pub fn max_profit(&self) -> Option<f64>;
pub fn max_loss(&self) -> Option<f64>;
}
}
```
### 7. **Machine Learning Integration**
No ML feature generation or model integration.
```rust
pub mod ml {
pub struct FeatureEngine {
indicators: Vec<Box<dyn Indicator>>,
lookback_periods: Vec<usize>,
pub fn generate_features(&self, data: &MarketData) -> FeatureMatrix;
pub fn calculate_feature_importance(&self) -> HashMap<String, f64>;
}
pub trait MLModel {
fn predict(&self, features: &FeatureMatrix) -> Prediction;
fn update(&mut self, features: &FeatureMatrix, outcome: &Outcome);
}
pub struct ModelEnsemble {
models: Vec<Box<dyn MLModel>>,
weights: Vec<f64>,
pub fn predict(&self, features: &FeatureMatrix) -> Prediction;
pub fn update_weights(&mut self, performance: &ModelPerformance);
}
}
```
### 8. **Backtesting Engine Enhancements**
Current backtesting is basic. Missing:
```rust
pub mod backtesting {
pub struct BacktestEngine {
// Slippage models
slippage_model: Box<dyn SlippageModel>,
// Market impact models (you have this but not integrated)
market_impact: Box<dyn MarketImpactModel>,
// Multi-asset synchronization
clock_sync: ClockSynchronizer,
// Walk-forward analysis
walk_forward: WalkForwardConfig,
// Monte Carlo simulation
monte_carlo: MonteCarloConfig,
}
pub struct BacktestMetrics {
// Return metrics
total_return: f64,
annualized_return: f64,
volatility: f64,
// Risk metrics
sharpe_ratio: f64,
sortino_ratio: f64,
calmar_ratio: f64,
max_drawdown: f64,
var_95: f64,
cvar_95: f64,
// Trading metrics
win_rate: f64,
profit_factor: f64,
avg_win_loss_ratio: f64,
expectancy: f64,
// Execution metrics
avg_slippage: f64,
total_commission: f64,
turnover: f64,
}
}
```
### 9. **Real-time Monitoring & Alerts**
No monitoring or alerting system.
```rust
pub mod monitoring {
pub struct Monitor {
rules: Vec<MonitorRule>,
alert_channels: Vec<Box<dyn AlertChannel>>,
}
pub enum MonitorRule {
PositionLimit { symbol: String, max_size: f64 },
DrawdownAlert { threshold: f64 },
VolumeSpike { symbol: String, threshold: f64 },
SpreadWidening { symbol: String, max_spread: f64 },
LatencyAlert { max_latency: Duration },
ErrorRate { max_errors_per_minute: u32 },
}
pub trait AlertChannel {
fn send_alert(&self, alert: Alert) -> Result<(), Error>;
}
}
```
### 10. **Data Persistence Layer**
No built-in data storage/retrieval.
```rust
pub mod persistence {
pub trait DataStore {
fn save_market_data(&self, data: &MarketUpdate) -> Result<(), Error>;
fn load_market_data(&self, symbol: &str, range: DateRange) -> Result<Vec<MarketUpdate>, Error>;
fn save_order(&self, order: &Order) -> Result<(), Error>;
fn load_order_history(&self, filter: OrderFilter) -> Result<Vec<Order>, Error>;
fn save_trade(&self, trade: &TradeRecord) -> Result<(), Error>;
fn load_trades(&self, filter: TradeFilter) -> Result<Vec<TradeRecord>, Error>;
}
pub struct TimeSeriesDB {
// QuestDB or TimescaleDB adapter
}
pub struct Cache {
// Redis adapter for hot data
}
}
```
### 11. **Strategy Development Framework**
Missing strategy templates and utilities.
```rust
pub mod strategy_framework {
pub trait Strategy {
fn on_start(&mut self);
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal>;
fn on_fill(&mut self, fill: &Fill);
fn on_end_of_day(&mut self);
fn get_parameters(&self) -> StrategyParameters;
}
pub struct StrategyOptimizer {
pub fn optimize_parameters(
&self,
strategy: &dyn Strategy,
data: &HistoricalData,
objective: ObjectiveFunction
) -> OptimalParameters;
pub fn walk_forward_analysis(&self, windows: Vec<DateRange>) -> WalkForwardResults;
}
}
```
### 12. **Compliance & Regulation**
No compliance checks or audit trails.
```rust
pub mod compliance {
pub struct ComplianceEngine {
rules: Vec<ComplianceRule>,
audit_log: AuditLog,
}
pub enum ComplianceRule {
NoBuyDuringRestricted { restricted_periods: Vec<DateRange> },
MaxOrdersPerDay { limit: u32 },
MinOrderInterval { duration: Duration },
RestrictedSymbols { symbols: HashSet<String> },
MaxLeverageRatio { ratio: f64 },
}
pub struct AuditLog {
pub fn log_order(&self, order: &Order, metadata: AuditMetadata);
pub fn log_trade(&self, trade: &Trade, metadata: AuditMetadata);
pub fn generate_report(&self, period: DateRange) -> ComplianceReport;
}
}
```
### 13. **Advanced Indicators**
Missing many common indicators.
```rust
pub mod indicators {
// Additional indicators to add:
- Ichimoku Cloud
- Parabolic SAR
- Fibonacci Retracements
- Pivot Points
- Money Flow Index
- Williams %R
- Commodity Channel Index (CCI)
- On Balance Volume (OBV)
- Accumulation/Distribution Line
- Chaikin Money Flow
- TRIX
- Keltner Channels
- Donchian Channels
- Average Directional Index (ADX)
- Aroon Indicator
}
```
### 14. **Network & Connectivity**
No network resilience or multi-venue support.
```rust
pub mod connectivity {
pub struct ConnectionManager {
venues: HashMap<String, VenueConnection>,
fallback_routes: HashMap<String, Vec<String>>,
heartbeat_monitor: HeartbeatMonitor,
}
pub struct VenueConnection {
primary: Connection,
backup: Option<Connection>,
latency_stats: LatencyStats,
pub fn send_order(&self, order: &Order) -> Result<String, Error>;
pub fn cancel_order(&self, order_id: &str) -> Result<(), Error>;
}
}
```
### 15. **Performance Profiling**
No built-in performance monitoring.
```rust
pub mod profiling {
pub struct PerformanceProfiler {
metrics: DashMap<String, PerformanceMetric>,
pub fn record_latency(&self, operation: &str, duration: Duration);
pub fn record_throughput(&self, operation: &str, count: u64);
pub fn get_report(&self) -> PerformanceReport;
}
}
```
## Priority Recommendations
### High Priority
1. **Order Management System** - Critical for proper order lifecycle tracking
2. **Portfolio Analytics** - Essential for multi-asset strategies
3. **Execution Algorithms** - TWAP/VWAP for better execution
4. **Advanced Order Types** - Bracket orders, trailing stops
5. **Backtesting Enhancements** - Proper slippage and impact modeling
### Medium Priority
1. **Options Support** - If trading options
2. **ML Integration** - Feature generation framework
3. **Monitoring & Alerts** - Real-time system health
4. **Data Persistence** - Proper storage layer
5. **More Indicators** - Based on strategy needs
### Low Priority
1. **Compliance Engine** - Unless regulatory requirements
2. **Multi-venue Support** - Unless using multiple brokers
3. **Advanced Market Data** - Level 2, imbalance data
## Implementation Approach
1. **Modular Design**: Each component should be optional and pluggable
2. **Trait-Based**: Continue using traits for extensibility
3. **Performance First**: Maintain the current performance focus
4. **Backward Compatible**: Don't break existing APIs
5. **Incremental**: Add features based on actual needs
The core is solid, but these additions would make it a comprehensive institutional-grade trading system!

View file

@ -80,7 +80,7 @@ strategy or an order gateway. Using it does not bypass `BaseStrategy` and `Execu
Implement `updateIndicators` and `generateSignal` on `BaseStrategy`; do not override the
delivery loop to return orders or introduce another position/risk manager. The supported
implementations are under `src/strategies/builtin/`. Follow the
[strategy extension guide](architecture-improvements.md) for registration, bounded state
[strategy development guide](../../../../docs/guide/strategy-development.md) for registration, bounded state
and checkpoint requirements.
Tests compare scalar SMA/population deviation with actual native batch and incremental