Remove legacy strategy frameworks and clarify supported execution paths

This commit is contained in:
Boki 2026-10-21 17:38:50 -04:00
parent 4207bf2c1c
commit 783b619846
28 changed files with 996 additions and 4689 deletions

View file

@ -1,293 +1,123 @@
# Orchestrator Architecture Improvements
## Overview
The orchestrator has been refactored to use the new Rust-based Technical Analysis library and improve separation of concerns. The architecture now follows a modular design with clear responsibilities for each component.
## Key Components
### 1. Technical Analysis (Rust Core)
- **Location**: `apps/stock/core/src/indicators/`
- **Purpose**: High-performance indicator calculations
- **Features**:
- 7 indicators: SMA, EMA, RSI, MACD, Bollinger Bands, Stochastic, ATR
- Both batch and incremental calculations
- Thread-safe, zero-copy implementations
- NAPI bindings for TypeScript access
### 2. Indicator Management
- **Component**: `IndicatorManager`
- **Responsibilities**:
- Price history management
- Indicator calculation and caching
- Incremental indicator updates
- Cross-indicator analysis (crossovers, etc.)
### 3. Position Management
- **Component**: `PositionManager`
- **Responsibilities**:
- Track open positions
- Calculate P&L (realized and unrealized)
- Position sizing algorithms
- Performance metrics tracking
### 4. Risk Management
- **Component**: `RiskManager`
- **Responsibilities**:
- Enforce position limits
- Monitor drawdown
- Calculate risk metrics (VaR, Sharpe ratio)
- Daily loss limits
- Position sizing based on risk
### 5. Signal Management
- **Component**: `SignalManager`
- **Responsibilities**:
- Rule-based signal generation
- Signal aggregation (weighted, majority, etc.)
- Signal filtering
- Historical signal tracking
## Architecture Diagram
```
┌─────────────────────────────────────────────────────────────┐
│ TypeScript Layer │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Strategy │ │ Signal │ │ Risk │ │
│ │ Engine │──│ Manager │──│ Manager │ │
│ └──────┬──────┘ └──────────────┘ └──────────────┘ │
│ │ │
│ ┌──────┴──────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Indicator │ │ Position │ │ Market │ │
│ │ Manager │ │ Manager │ │ Data │ │
│ └──────┬──────┘ └──────────────┘ └──────────────┘ │
│ │ │
├─────────┼─────────────────────────────────────────────────┤
│ │ NAPI Bindings │
├─────────┼─────────────────────────────────────────────────┤
│ │ │
│ ┌──────┴──────────────────────────────────────────┐ │
│ │ Rust Core (Technical Analysis) │ │
│ │ │ │
│ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌──────┐ ┌────────┐ │ │
│ │ │ SMA │ │ EMA │ │ RSI │ │ MACD │ │ Bollinger│ │ │
│ │ └─────┘ └─────┘ └─────┘ └──────┘ └────────┘ │ │
│ │ │ │
│ │ ┌───────────┐ ┌─────┐ ┌──────────────────┐ │ │
│ │ │ Stochastic│ │ ATR │ │ Common Utilities │ │ │
│ │ └───────────┘ └─────┘ └──────────────────┘ │ │
│ └──────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
```
## Strategy Implementation Pattern
### Before (Monolithic)
```typescript
class SimpleStrategy extends BaseStrategy {
// Everything mixed together
updateIndicators() { /* calculate MAs inline */ }
generateSignal() { /* risk checks, position sizing, signal logic */ }
onOrderFilled() { /* position tracking inline */ }
}
```
### After (Modular)
```typescript
class AdvancedStrategy extends BaseStrategy {
private indicatorManager: IndicatorManager;
private positionManager: PositionManager;
private riskManager: RiskManager;
private signalManager: SignalManager;
updateIndicators(data) {
// Delegate to specialized manager
this.indicatorManager.updatePrice(data);
}
generateSignal(data) {
// 1. Get indicators
const indicators = this.indicatorManager.prepareIndicators(symbol);
// 2. Check risk
const riskCheck = this.riskManager.checkNewPosition(...);
// 3. Generate signal
const signal = this.signalManager.generateSignal(...);
// 4. Size position
const size = this.positionManager.calculatePositionSize(...);
}
}
```
## Benefits
### 1. Performance
- Rust indicators are 10-100x faster than JavaScript
- Efficient memory usage with rolling windows
- Parallel computation support
### 2. Maintainability
- Clear separation of concerns
- Reusable components
- Easy to test individual pieces
- Consistent interfaces
### 3. Flexibility
- Strategies can mix and match components
- Easy to add new indicators
- Multiple position sizing methods
- Configurable risk limits
### 4. Reliability
- Type-safe interfaces
- Error handling at each layer
- Comprehensive logging
- Performance metrics tracking
## Migration Guide
### Converting Existing Strategies
1. **Replace inline calculations with IndicatorManager**:
```typescript
// Old
const sma = this.calculateSMA(prices, period);
// New
const sma = this.indicatorManager.getSMA(symbol, period);
```
2. **Use PositionManager for tracking**:
```typescript
// Old
this.positions.set(symbol, quantity);
// New
this.positionManager.updatePosition(trade);
```
3. **Add RiskManager checks**:
```typescript
// New - check before trading
const riskCheck = this.riskManager.checkNewPosition(...);
if (!riskCheck.allowed) return null;
```
4. **Use SignalManager for rules**:
```typescript
// Setup rules once
this.signalManager.addRule(CommonRules.goldenCross('sma20', 'sma50'));
// Generate signals
const signal = this.signalManager.generateSignal(symbol, timestamp, indicators);
```
## Example Strategies
### 1. SimpleMovingAverageCrossoverV2
- Uses IndicatorManager for MA calculations
- PositionManager for sizing
- Clean separation of indicator updates and signal generation
### 2. IndicatorBasedStrategy
- Demonstrates incremental indicators
- Uses SignalGenerator for multi-indicator signals
- Shows batch analysis capabilities
### 3. AdvancedMultiIndicatorStrategy
- Full integration of all managers
- Multiple signal rules with aggregation
- Risk-based position sizing
- Stop loss and take profit management
## Next Steps
### Immediate Improvements
1. ✅ Implement TA library in Rust
2. ✅ Create manager components
3. ✅ Refactor existing strategies
4. ✅ Add comprehensive tests
### Future Enhancements
1. **More Indicators**:
- Ichimoku Cloud
- Fibonacci retracements
- Volume-weighted indicators
2. **Advanced Risk Management**:
- Portfolio optimization
- Correlation analysis
- Dynamic position sizing
3. **Machine Learning Integration**:
- Feature extraction from indicators
- Signal strength prediction
- Adaptive rule weights
4. **Performance Optimization**:
- GPU acceleration for backtesting
- Distributed indicator calculation
- Real-time streaming optimizations
## Configuration Examples
### Basic Strategy
```typescript
{
strategy: 'SimpleMovingAverageCrossoverV2',
params: {
fastPeriod: 10,
slowPeriod: 20,
positionSizePct: 0.1
}
}
```
### Advanced Strategy
```typescript
{
strategy: 'AdvancedMultiIndicatorStrategy',
params: {
// Indicators
fastMA: 20,
slowMA: 50,
rsiPeriod: 14,
// Risk
riskPerTrade: 0.02,
maxPositions: 5,
maxDrawdown: 0.2,
// Signals
signalAggregation: 'weighted',
minSignalStrength: 0.6,
// Position sizing
positionSizing: 'risk',
useATRStops: true
}
}
```
## Testing
Run the new indicator tests:
```bash
bun run test:indicators
```
Run strategy tests:
```bash
bun test src/strategies
```
Run examples:
```bash
bun run example:indicators
```
# 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.
## 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.
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 `indicators/window-statistics.ts` 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,463 +1,487 @@
# Rust Core Enhancement Roadmap
## 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!
# 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

@ -1,212 +1,101 @@
# Technical Analysis Library Documentation
The stock-bot orchestrator includes a high-performance Technical Analysis (TA) library implemented in Rust with TypeScript bindings. This provides efficient calculation of common technical indicators for trading strategies.
## Architecture
The TA library consists of:
1. **Rust Core**: High-performance indicator calculations in `apps/stock/core/src/indicators/`
2. **NAPI Bindings**: TypeScript interfaces exposed through `@stock-bot/engine`
3. **TypeScript Wrapper**: Convenient API in `orchestrator/src/indicators/TechnicalAnalysis.ts`
## Available Indicators
### Simple Moving Average (SMA)
```typescript
const sma = ta.sma(prices, period);
```
### Exponential Moving Average (EMA)
```typescript
const ema = ta.ema(prices, period);
```
### Relative Strength Index (RSI)
```typescript
const rsi = ta.rsi(prices, period); // Returns values 0-100
```
### MACD (Moving Average Convergence Divergence)
```typescript
const macd = ta.macd(prices, fastPeriod, slowPeriod, signalPeriod);
// Returns: { macd: number[], signal: number[], histogram: number[] }
```
### Bollinger Bands
```typescript
const bb = ta.bollingerBands(prices, period, stdDev);
// Returns: { upper: number[], middle: number[], lower: number[] }
```
### Stochastic Oscillator
```typescript
const stoch = ta.stochastic(high, low, close, kPeriod, dPeriod, smoothK);
// Returns: { k: number[], d: number[] }
```
### Average True Range (ATR)
```typescript
const atr = ta.atr(high, low, close, period);
```
## Usage Examples
### Basic Indicator Calculation
```typescript
import { TechnicalAnalysis } from '../src/indicators/TechnicalAnalysis';
const ta = new TechnicalAnalysis();
const prices = [100, 102, 101, 103, 105, 104, 106];
// Calculate 5-period SMA
const sma5 = ta.sma(prices, 5);
console.log('SMA:', sma5);
// Get latest value
const latestSMA = TechnicalAnalysis.latest(sma5);
```
### Incremental Indicators for Streaming Data
```typescript
import { IncrementalIndicators } from '../src/indicators/TechnicalAnalysis';
const indicators = new IncrementalIndicators();
// Create indicators
indicators.createSMA('fast', 10);
indicators.createSMA('slow', 20);
indicators.createRSI('rsi', 14);
// Update with new price
const newPrice = 105.50;
const fastSMA = indicators.update('fast', newPrice);
const slowSMA = indicators.update('slow', newPrice);
const rsi = indicators.update('rsi', newPrice);
// Get current values
const currentRSI = indicators.current('rsi');
```
### Signal Generation
```typescript
import { SignalGenerator } from '../src/indicators/TechnicalAnalysis';
const generator = new SignalGenerator();
const signal = generator.generateSignals(
'AAPL',
{
close: closePrices,
high: highPrices,
low: lowPrices,
volume: volumes
},
Date.now()
);
if (signal.action === 'BUY' && signal.strength > 0.7) {
// Strong buy signal
console.log(`Buy signal: ${signal.reason}`);
}
```
### Crossover Detection
```typescript
// Detect when fast MA crosses above slow MA
if (TechnicalAnalysis.crossover(fastMA, slowMA)) {
console.log('Bullish crossover detected');
}
// Detect when fast MA crosses below slow MA
if (TechnicalAnalysis.crossunder(fastMA, slowMA)) {
console.log('Bearish crossover detected');
}
```
## Strategy Integration
Example strategy using multiple indicators:
```typescript
import { BaseStrategy } from '../BaseStrategy';
import { TechnicalAnalysis } from '../../indicators/TechnicalAnalysis';
export class MultiIndicatorStrategy extends BaseStrategy {
private ta = new TechnicalAnalysis();
private priceHistory: number[] = [];
onMarketData(data: any): Order | null {
this.priceHistory.push(data.close);
if (this.priceHistory.length < 50) return null;
// Calculate indicators
const rsi = this.ta.rsi(this.priceHistory, 14);
const macd = this.ta.macd(this.priceHistory);
const bb = this.ta.bollingerBands(this.priceHistory);
// Get latest values
const currentRSI = TechnicalAnalysis.latest(rsi);
const currentPrice = data.close;
const bbLower = TechnicalAnalysis.latest(bb.lower);
// Generate signals
if (currentRSI < 30 && currentPrice < bbLower) {
// Oversold + price below lower band = BUY
return this.createOrder('market', 'buy', this.positionSize);
}
return null;
}
}
```
## Performance Considerations
1. **Batch vs Incremental**: Use batch calculations for backtesting, incremental for live trading
2. **Memory Management**: The Rust implementation uses efficient rolling windows
3. **Thread Safety**: All Rust indicators are thread-safe
4. **Error Handling**: Invalid parameters return errors rather than panicking
## Testing
Run the indicator tests:
```bash
bun run test:indicators
```
Run the usage examples:
```bash
bun run example:indicators
```
## Extending the Library
To add a new indicator:
1. Create Rust implementation in `apps/stock/core/src/indicators/[indicator_name].rs`
2. Implement `Indicator` and optionally `IncrementalIndicator` traits
3. Add NAPI bindings in `apps/stock/core/src/api/indicators.rs`
4. Update TypeScript definitions in `apps/stock/core/index.d.ts`
5. Add wrapper methods in `orchestrator/src/indicators/TechnicalAnalysis.ts`
6. Write tests and examples
## Common Patterns
### Momentum Indicators
- RSI < 30: Oversold
- RSI > 70: Overbought
- MACD crossover: Trend change
### Volatility Indicators
- Bollinger Band squeeze: Low volatility
- ATR increase: Higher volatility
### Trend Indicators
- Price > SMA200: Long-term uptrend
- EMA crossovers: Short-term trend changes
### Combined Signals
Best results often come from combining multiple indicators:
- RSI oversold + MACD bullish crossover
- Price at Bollinger lower band + Stochastic oversold
- Volume confirmation with price indicators
# Technical indicators
Indicator math and strategy execution are separate concerns. Indicator helpers return
values; they do not own cash, positions, order submission, account risk or recovery.
## TypeScript trailing-window math
`src/indicators/window-statistics.ts` supplies the scalar operations used by the supported
TypeScript SMA and mean-reversion strategies:
```ts
import {
movingAverageCrossover,
trailingMean,
trailingPopulationDeviation,
} from '../src/indicators/window-statistics';
const prices = [3, 2, 1, 4];
const mean = trailingMean(prices, 3);
const deviation = trailingPopulationDeviation(prices, 3);
const crossover = movingAverageCrossover(prices, 2, 3);
```
Periods must be positive integers; prices in the requested window must be finite.
Incomplete warm-up returns `undefined`, not zero. Deviation uses population variance.
A crossover needs complete current and previous windows (`slowPeriod + 1` prices) and
`fastPeriod < slowPeriod`. Indexed loops avoid temporary price-window arrays; this is
not an incremental O(1) indicator implementation.
## Native batch and incremental indicators
Rust implementations live in `apps/stock/engine/src/indicators/`, exposed by
`@stock-bot/engine`. Build the native engine before importing the binding.
`src/indicators/TechnicalAnalysis.ts` provides typed batch wrappers for SMA, EMA, RSI,
MACD, Bollinger bands, stochastic and ATR:
```ts
import { TechnicalAnalysis } from '../src/indicators/TechnicalAnalysis';
const ta = new TechnicalAnalysis();
const prices = Array.from({ length: 80 }, (_, i) => 100 + Math.sin(i / 3));
const sma = ta.sma(prices, 20);
const macd = ta.macd(prices, 12, 26, 9);
const bands = ta.bollingerBands(prices, 20, 2);
const latestMean = TechnicalAnalysis.latest(sma);
```
Do not assume every batch result has the same length or warm-up offset. For example,
native MACD retains its full-length aligned series, while SMA returns only complete windows.
Align different indicators by source-bar time before testing a crossover. The wrapper's
`latest` returns `undefined` for an empty result.
`IncrementalIndicators` wraps native incremental SMA/EMA/RSI instances:
```ts
import { IncrementalIndicators } from '../src/indicators/TechnicalAnalysis';
const indicators = new IncrementalIndicators();
indicators.createSMA('AAPL.US:fast', 5);
const value = indicators.update('AAPL.US:fast', 100);
```
Use a separate instance/key per instrument and parameter set. Incremental warm-up is
`null`; sharing a key across instruments mixes their histories. Native indicator objects
are not a complete serializable paper checkpoint. A strategy using them must define a
replay-safe restoration procedure, including every custom decision input.
`SignalGenerator` remains an exploratory indicator-combination utility, not a registered
strategy or an order gateway. Using it does not bypass `BaseStrategy` and `ExecutionService`.
## Strategy integration and parity
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
and checkpoint requirements.
Tests compare scalar SMA/population deviation with actual native batch and incremental
bindings, including non-default windows and warm-up. That does not imply identical trading
algorithms or RSI conventions across backends. The TypeScript mean-reversion strategy keeps
its trailing-window RSI; native indicators can use a different recurrence.
## Verification and extension
From the repository root:
```sh
bun run build
bun test test/integration/strategy-contracts.test.ts scripts/test/native-bindings.test.ts
bun run test:native
```
The complete repository gate is `bun run check`. Run native builds before native-dependent
tests, not concurrently with them.
To add an indicator, implement and test its Rust math under `engine/src/indicators/`,
expose it through `engine/src/api/indicators.rs`, rebuild the generated declarations/binary,
and add the typed wrapper in `TechnicalAnalysis.ts`. Keep warm-up/alignment semantics
explicit and test known values and incremental/batch equivalence where appropriate.
Do not hand-edit generated declarations or claim performance improvements without measurement.