diff --git a/README.md b/README.md index effc1bbe..da1d5b4e 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,15 @@ not the application service container: `strategyRegistry` to `registerOrchestratorServices`. 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](apps/stock/orchestrator/docs/architecture-improvements.md) +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. diff --git a/apps/stock/orchestrator/docs/architecture-improvements.md b/apps/stock/orchestrator/docs/architecture-improvements.md index 1b83ed1f..9a87ba8e 100644 --- a/apps/stock/orchestrator/docs/architecture-improvements.md +++ b/apps/stock/orchestrator/docs/architecture-improvements.md @@ -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 -``` \ No newline at end of file +# 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. diff --git a/apps/stock/orchestrator/docs/rust-core-enhancements.md b/apps/stock/orchestrator/docs/rust-core-enhancements.md index a09cdfbb..a0807e9f 100644 --- a/apps/stock/orchestrator/docs/rust-core-enhancements.md +++ b/apps/stock/orchestrator/docs/rust-core-enhancements.md @@ -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, - order_history: Vec, - order_routes: HashMap, -} - -pub enum OrderEvent { - Submitted { order_id: String, timestamp: DateTime }, - 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, - price: Option, - stop_price: Option, -} -``` - -### 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 }, - OCO { order1: Box, order2: Box }, // One-Cancels-Other - Bracket { entry: Box, stop_loss: Box, take_profit: Box }, -} -``` - -### 3. **Portfolio Management** -No portfolio-level analytics or optimization. - -```rust -pub mod portfolio { - pub struct Portfolio { - positions: HashMap, - 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; - 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; - pub fn calculate_efficient_frontier(&self, points: usize) -> Vec<(f64, f64)>; - pub fn black_litterman(&self, views: Views) -> HashMap; - pub fn risk_parity(&self) -> HashMap; - } -} -``` - -### 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, asks: Vec }, - Imbalance { buy_quantity: f64, sell_quantity: f64, ref_price: f64 }, - AuctionData { indicative_price: f64, indicative_volume: f64 }, - OptionQuote { - strike: f64, - expiry: DateTime, - 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; - 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, - 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, - 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, - pub fn calculate_payoff(&self, underlying_price: f64) -> f64; - pub fn calculate_breakeven(&self) -> Vec; - pub fn max_profit(&self) -> Option; - pub fn max_loss(&self) -> Option; - } -} -``` - -### 7. **Machine Learning Integration** -No ML feature generation or model integration. - -```rust -pub mod ml { - pub struct FeatureEngine { - indicators: Vec>, - lookback_periods: Vec, - - pub fn generate_features(&self, data: &MarketData) -> FeatureMatrix; - pub fn calculate_feature_importance(&self) -> HashMap; - } - - pub trait MLModel { - fn predict(&self, features: &FeatureMatrix) -> Prediction; - fn update(&mut self, features: &FeatureMatrix, outcome: &Outcome); - } - - pub struct ModelEnsemble { - models: Vec>, - weights: Vec, - - 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, - - // Market impact models (you have this but not integrated) - market_impact: Box, - - // 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, - alert_channels: Vec>, - } - - 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, Error>; - - fn save_order(&self, order: &Order) -> Result<(), Error>; - fn load_order_history(&self, filter: OrderFilter) -> Result, Error>; - - fn save_trade(&self, trade: &TradeRecord) -> Result<(), Error>; - fn load_trades(&self, filter: TradeFilter) -> Result, 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; - 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) -> WalkForwardResults; - } -} -``` - -### 12. **Compliance & Regulation** -No compliance checks or audit trails. - -```rust -pub mod compliance { - pub struct ComplianceEngine { - rules: Vec, - audit_log: AuditLog, - } - - pub enum ComplianceRule { - NoBuyDuringRestricted { restricted_periods: Vec }, - MaxOrdersPerDay { limit: u32 }, - MinOrderInterval { duration: Duration }, - RestrictedSymbols { symbols: HashSet }, - 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, - fallback_routes: HashMap>, - heartbeat_monitor: HeartbeatMonitor, - } - - pub struct VenueConnection { - primary: Connection, - backup: Option, - latency_stats: LatencyStats, - pub fn send_order(&self, order: &Order) -> Result; - 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, - - 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! \ No newline at end of file +# 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, + order_history: Vec, + order_routes: HashMap, +} + +pub enum OrderEvent { + Submitted { order_id: String, timestamp: DateTime }, + 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, + price: Option, + stop_price: Option, +} +``` + +### 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 }, + OCO { order1: Box, order2: Box }, // One-Cancels-Other + Bracket { entry: Box, stop_loss: Box, take_profit: Box }, +} +``` + +### 3. **Portfolio Management** + +No portfolio-level analytics or optimization. + +```rust +pub mod portfolio { + pub struct Portfolio { + positions: HashMap, + 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; + 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; + pub fn calculate_efficient_frontier(&self, points: usize) -> Vec<(f64, f64)>; + pub fn black_litterman(&self, views: Views) -> HashMap; + pub fn risk_parity(&self) -> HashMap; + } +} +``` + +### 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, asks: Vec }, + Imbalance { buy_quantity: f64, sell_quantity: f64, ref_price: f64 }, + AuctionData { indicative_price: f64, indicative_volume: f64 }, + OptionQuote { + strike: f64, + expiry: DateTime, + 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; + 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, + 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, + 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, + pub fn calculate_payoff(&self, underlying_price: f64) -> f64; + pub fn calculate_breakeven(&self) -> Vec; + pub fn max_profit(&self) -> Option; + pub fn max_loss(&self) -> Option; + } +} +``` + +### 7. **Machine Learning Integration** + +No ML feature generation or model integration. + +```rust +pub mod ml { + pub struct FeatureEngine { + indicators: Vec>, + lookback_periods: Vec, + + pub fn generate_features(&self, data: &MarketData) -> FeatureMatrix; + pub fn calculate_feature_importance(&self) -> HashMap; + } + + pub trait MLModel { + fn predict(&self, features: &FeatureMatrix) -> Prediction; + fn update(&mut self, features: &FeatureMatrix, outcome: &Outcome); + } + + pub struct ModelEnsemble { + models: Vec>, + weights: Vec, + + 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, + + // Market impact models (you have this but not integrated) + market_impact: Box, + + // 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, + alert_channels: Vec>, + } + + 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, Error>; + + fn save_order(&self, order: &Order) -> Result<(), Error>; + fn load_order_history(&self, filter: OrderFilter) -> Result, Error>; + + fn save_trade(&self, trade: &TradeRecord) -> Result<(), Error>; + fn load_trades(&self, filter: TradeFilter) -> Result, 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; + 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) -> WalkForwardResults; + } +} +``` + +### 12. **Compliance & Regulation** + +No compliance checks or audit trails. + +```rust +pub mod compliance { + pub struct ComplianceEngine { + rules: Vec, + audit_log: AuditLog, + } + + pub enum ComplianceRule { + NoBuyDuringRestricted { restricted_periods: Vec }, + MaxOrdersPerDay { limit: u32 }, + MinOrderInterval { duration: Duration }, + RestrictedSymbols { symbols: HashSet }, + 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, + fallback_routes: HashMap>, + heartbeat_monitor: HeartbeatMonitor, + } + + pub struct VenueConnection { + primary: Connection, + backup: Option, + latency_stats: LatencyStats, + pub fn send_order(&self, order: &Order) -> Result; + 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, + + 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! diff --git a/apps/stock/orchestrator/docs/technical-indicators.md b/apps/stock/orchestrator/docs/technical-indicators.md index 5ab6cb86..b504c127 100644 --- a/apps/stock/orchestrator/docs/technical-indicators.md +++ b/apps/stock/orchestrator/docs/technical-indicators.md @@ -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 \ No newline at end of file +# 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. diff --git a/apps/stock/orchestrator/examples/multi-strategy-backtest.ts b/apps/stock/orchestrator/examples/multi-strategy-backtest.ts new file mode 100644 index 00000000..f9f3f36d --- /dev/null +++ b/apps/stock/orchestrator/examples/multi-strategy-backtest.ts @@ -0,0 +1,38 @@ +import type { BacktestRunner } from '../src/backtest/BacktestRunner'; +import { BacktestConfigSchema, type BacktestConfig } from '../src/types'; + +/** + * Call with the application's already-composed TypeScript runner and real historical range. + * Importing this example starts no services, loads no model and submits no work. + * The caller owns runner/service shutdown; the ordinary runner persists the actual result. + */ +export function runMultiStrategyBacktest( + runner: Pick, + range: Pick +) { + const request = BacktestConfigSchema.parse({ + symbols: range.symbols, + startDate: range.startDate, + endDate: range.endDate, + mode: 'backtest', + name: 'SMA and mean-reversion example', + strategy: 'sma-crossover', + initialCapital: 100000, + dataFrequency: '1d', + commission: 0.001, + slippage: 0.0001, + strategies: [ + { + name: 'sma-crossover', + enabled: true, + config: { fastPeriod: 5, slowPeriod: 15, positionFraction: 0.1 }, + }, + { + name: 'mean-reversion', + enabled: true, + config: { lookbackPeriod: 20, entryThreshold: 2, exitZScore: 0.5 }, + }, + ], + }); + return runner.runBacktest(request); +} diff --git a/apps/stock/orchestrator/examples/sophisticated-backtest.ts b/apps/stock/orchestrator/examples/sophisticated-backtest.ts deleted file mode 100644 index 00fae43d..00000000 --- a/apps/stock/orchestrator/examples/sophisticated-backtest.ts +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env bun - -/** - * Example of running a sophisticated backtest with all advanced features - */ -import { BacktestEngine } from '../src/backtest/BacktestEngine'; -import { AnalyticsService } from '../src/services/AnalyticsService'; -import { StorageService } from '../src/services/StorageService'; -import { StrategyManager } from '../src/strategies/StrategyManager'; -import '../src/strategies/examples/MeanReversionStrategy'; -import '../src/strategies/examples/MLEnhancedStrategy'; -import { logger } from '@stock-bot/logger'; - -async function runSophisticatedBacktest() { - // Initialize services - const storageService = new StorageService(); - await storageService.initialize({ mode: 'backtest' }); - - const analyticsService = new AnalyticsService({ - analyticsUrl: process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003', - }); - - const strategyManager = new StrategyManager(); - - // Create backtest engine - const backtestEngine = new BacktestEngine(storageService, strategyManager); - - // Configure backtest with advanced options - const config = { - mode: 'backtest' as const, - startDate: '2023-01-01T00:00:00Z', - endDate: '2023-12-31T23:59:59Z', - symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US', 'AMZN.US', 'TSLA.US'], - initialCapital: 1_000_000, - dataFrequency: '5m' as const, // 5-minute bars for detailed analysis - - // Advanced fill model configuration - fillModel: { - slippage: 'realistic' as const, - marketImpact: true, - partialFills: true, - // Use sophisticated market impact models - impactModel: 'AlmgrenChriss', - // Model hidden liquidity and dark pools - includeHiddenLiquidity: true, - darkPoolParticipation: 0.2, // 20% of volume in dark pools - // Realistic latency simulation - latencyMs: { - mean: 1, - std: 0.5, - tail: 10, // Occasional high latency - }, - }, - - // Risk limits - riskLimits: { - maxPositionSize: 100_000, - maxDailyLoss: 50_000, - maxDrawdown: 0.2, // 20% max drawdown - maxLeverage: 2.0, - maxConcentration: 0.3, // Max 30% in single position - }, - - // Transaction costs - costs: { - commission: 0.0005, // 5 bps - borrowRate: 0.03, // 3% annual for shorts - slippageModel: 'volumeDependent', - }, - - // Strategies to test - strategies: [ - { - id: 'mean_reversion_1', - name: 'Mean Reversion Strategy', - type: 'MeanReversion', - enabled: true, - allocation: 0.5, - symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US'], - parameters: { - lookback: 20, - entryZScore: 2.0, - exitZScore: 0.5, - minVolume: 1_000_000, - stopLoss: 0.05, // 5% stop loss - }, - }, - { - id: 'ml_enhanced_1', - name: 'ML Enhanced Strategy', - type: 'MLEnhanced', - enabled: true, - allocation: 0.5, - symbols: ['AMZN.US', 'TSLA.US'], - parameters: { - modelPath: './models/ml_strategy_v1', - updateFrequency: 1440, // Daily retraining - minConfidence: 0.6, - }, - }, - ], - }; - - logger.info('Starting sophisticated backtest...'); - - try { - // Run the backtest - const result = await backtestEngine.runBacktest(config); - - logger.info('Backtest completed successfully'); - logger.info(`Total Return: ${result.performance.totalReturn.toFixed(2)}%`); - logger.info(`Sharpe Ratio: ${result.performance.sharpeRatio.toFixed(2)}`); - logger.info(`Max Drawdown: ${result.performance.maxDrawdown.toFixed(2)}%`); - - // Run statistical validation - logger.info('Running statistical validation...'); - const validationResult = await analyticsService.validateBacktest({ - backtestId: result.id, - returns: result.dailyReturns, - trades: result.trades, - parameters: extractParameters(config.strategies), - }); - - if (validationResult.is_overfit) { - logger.warn('⚠️ WARNING: Backtest shows signs of overfitting!'); - logger.warn(`Confidence Level: ${(validationResult.confidence_level * 100).toFixed(1)}%`); - logger.warn('Recommendations:'); - validationResult.recommendations.forEach(rec => { - logger.warn(` - ${rec}`); - }); - } else { - logger.info('✅ Backtest passed statistical validation'); - logger.info(`PSR: ${validationResult.psr.toFixed(3)}`); - logger.info(`DSR: ${validationResult.dsr.toFixed(3)}`); - } - - // Generate comprehensive report - logger.info('Generating performance report...'); - const report = await backtestEngine.exportResults('html'); - - // Save report - const fs = require('fs'); - const reportPath = `./reports/backtest_${result.id}.html`; - fs.writeFileSync(reportPath, report); - logger.info(`Report saved to: ${reportPath}`); - - // Advanced analytics - logger.info('Running advanced analytics...'); - - // Factor attribution - const factorAnalysis = await analyticsService.analyzeFactors({ - returns: result.dailyReturns, - positions: result.finalPositions, - marketReturns: await getMarketReturns(config.startDate, config.endDate), - }); - - logger.info('Factor Attribution:'); - logger.info(` Alpha: ${(factorAnalysis.alpha * 100).toFixed(2)}%`); - logger.info(` Beta: ${factorAnalysis.beta.toFixed(2)}`); - logger.info(` Information Ratio: ${factorAnalysis.information_ratio.toFixed(2)}`); - - // Transaction cost analysis - const tcaReport = await analyticsService.analyzeTCA({ - trades: result.trades, - orders: result.orders, - }); - - logger.info('Transaction Cost Analysis:'); - logger.info(` Total Costs: $${tcaReport.total_costs.toFixed(2)}`); - logger.info(` Avg Cost per Trade: ${tcaReport.avg_cost_bps.toFixed(1)} bps`); - logger.info( - ` Implementation Shortfall: ${tcaReport.implementation_shortfall_bps.toFixed(1)} bps` - ); - - // Performance by time period - const periodAnalysis = analyzeByPeriod(result); - logger.info('Performance by Period:'); - Object.entries(periodAnalysis).forEach(([period, metrics]) => { - logger.info( - ` ${period}: ${metrics.return.toFixed(2)}% (Sharpe: ${metrics.sharpe.toFixed(2)})` - ); - }); - - // Strategy correlation analysis - if (config.strategies.length > 1) { - const correlations = await calculateStrategyCorrelations(result); - logger.info('Strategy Correlations:'); - correlations.forEach(({ pair, correlation }) => { - logger.info(` ${pair}: ${correlation.toFixed(3)}`); - }); - } - - // Monte Carlo simulation - logger.info('Running Monte Carlo simulation...'); - const monteCarloResults = await runMonteCarloSimulation(result, 1000); - logger.info(`Monte Carlo 95% VaR: ${monteCarloResults.var95.toFixed(2)}%`); - logger.info(`Monte Carlo 95% CVaR: ${monteCarloResults.cvar95.toFixed(2)}%`); - - // Walk-forward analysis suggestion - if (result.performance.totalTrades > 100) { - logger.info('\n💡 Suggestion: Run walk-forward analysis for more robust validation'); - logger.info('Example: bun run examples/walk-forward-analysis.ts'); - } - } catch (error) { - logger.error('Backtest failed:', error); - } finally { - await storageService.shutdown(); - } -} - -// Helper functions - -function extractParameters( - strategies: { id: string; parameters: Record }[] -): Record { - const params: Record = {}; - strategies.forEach(strategy => { - Object.entries(strategy.parameters).forEach(([key, value]) => { - params[`${strategy.id}_${key}`] = value; - }); - }); - return params; -} - -async function getMarketReturns(startDate: string, endDate: string): Promise { - // In real implementation, would fetch SPY or market index returns - // For demo, return synthetic market returns - const days = Math.floor( - (new Date(endDate).getTime() - new Date(startDate).getTime()) / (1000 * 60 * 60 * 24) - ); - return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02); -} - -function analyzeByPeriod(result: { - dailyReturns: number[]; -}): Record { - const periods = { - Q1: { start: 0, end: 63 }, - Q2: { start: 63, end: 126 }, - Q3: { start: 126, end: 189 }, - Q4: { start: 189, end: 252 }, - }; - - const analysis: Record = {}; - - Object.entries(periods).forEach(([name, { start, end }]) => { - const periodReturns = result.dailyReturns.slice(start, end); - if (periodReturns.length > 0) { - const avgReturn = periodReturns.reduce((a, b) => a + b, 0) / periodReturns.length; - const std = Math.sqrt( - periodReturns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / periodReturns.length - ); - - analysis[name] = { - return: avgReturn * periodReturns.length * 100, - sharpe: std > 0 ? (avgReturn / std) * Math.sqrt(252) : 0, - }; - } - }); - - return analysis; -} - -async function calculateStrategyCorrelations(_result: { - dailyReturns: number[]; -}): Promise> { - // In real implementation, would calculate actual strategy return correlations - // For demo, return sample correlations - return [{ pair: 'mean_reversion_1 vs ml_enhanced_1', correlation: 0.234 }]; -} - -async function runMonteCarloSimulation( - result: { dailyReturns: number[] }, - numSims: number -): Promise<{ var95: number; cvar95: number }> { - const returns = result.dailyReturns; - const simulatedReturns: number[] = []; - - for (let i = 0; i < numSims; i++) { - // Bootstrap resample returns - let cumReturn = 0; - for (let j = 0; j < returns.length; j++) { - const randomIndex = Math.floor(Math.random() * returns.length); - cumReturn += returns[randomIndex]; - } - simulatedReturns.push(cumReturn * 100); - } - - // Calculate VaR and CVaR - simulatedReturns.sort((a, b) => a - b); - const index95 = Math.floor(numSims * 0.05); - const var95 = Math.abs(simulatedReturns[index95]); - const cvar95 = Math.abs(simulatedReturns.slice(0, index95).reduce((a, b) => a + b, 0) / index95); - - return { var95, cvar95 }; -} - -// Run the backtest -runSophisticatedBacktest().catch(console.error); diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts b/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts deleted file mode 100644 index 0b58cda5..00000000 --- a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { BacktestEngine as RustEngine } from '@stock-bot/engine'; -import { resolveDataset } from '../data/historical-dataset'; -import { StorageService } from '../services/StorageService'; -import { RustStrategy } from '../strategies/RustStrategy'; -import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types'; -import { nativeResultSchema } from './native-result'; - -export interface RustBacktestConfig { - name: string; - symbols: string[]; - startDate: string; - endDate: string; - initialCapital: number; - commission: number; - slippage: number; - dataFrequency: string; -} - -export interface RustBacktestResult { - config: RustBacktestConfig; - metrics: { - totalReturn: number; - totalTrades: number; - profitableTrades: number; - winRate: number; - profitFactor: number | null; - sharpeRatio: number; - maxDrawdown: number; - totalPnl: number; - avgWin: number; - avgLoss: number; - }; - equityCurve: Array<{ date: string; value: number }>; - trades: import('./native-result').NativeBacktestResult['trades']; - finalPositions: Record; -} - -/** @deprecated Diagnostic wrapper only. Use BacktestRunner for durable, isolated execution. */ -export class RustBacktestEngine { - private engine: RustEngine; - private container: IServiceContainer; - private storageService: StorageService; - private config: RustBacktestConfig; - private readonly request: BacktestConfig; - - constructor( - container: IServiceContainer, - storageService: StorageService, - config: BacktestConfig - ) { - this.container = container; - this.storageService = storageService; - this.request = config; - - // Convert config for Rust - const rustConfig: RustBacktestConfig = { - name: config.name || 'Backtest', - symbols: config.symbols, - startDate: config.startDate, - endDate: config.endDate, - initialCapital: config.initialCapital, - commission: config.commission ?? 0.001, - slippage: config.slippage ?? 0.0001, - dataFrequency: config.dataFrequency || '1d', - }; - - this.config = rustConfig; - this.engine = new RustEngine(rustConfig); - } - - /** - * Add a TypeScript strategy to the backtest - */ - addStrategy(strategy: RustStrategy): void { - strategy.register(this.engine); - } - - /** - * Load historical data for the backtest - */ - async loadData(): Promise { - const dataset = await resolveDataset(this.storageService, this.request); - this.engine.loadMarketData(dataset.bars.map(bar => ({ ...bar, type: 'bar' }))); - } - - /** - * Run the backtest - */ - async run(): Promise { - this.container.logger.info('Starting backtest run...'); - - // Load data first - await this.loadData(); - - // Run backtest in Rust - const resultJson = await this.engine.run(); - - // Parse result and convert snake_case to camelCase - const rustResult = nativeResultSchema.parse(JSON.parse(resultJson)); - - const result: RustBacktestResult = { - config: this.config, - metrics: { - totalReturn: rustResult.metrics.totalReturn, - totalTrades: rustResult.metrics.totalTrades, - profitableTrades: rustResult.trades.filter(trade => (trade.pnl ?? 0) > 0).length, - winRate: rustResult.metrics.winRate, - profitFactor: rustResult.metrics.profitFactor, - sharpeRatio: rustResult.metrics.sharpeRatio, - maxDrawdown: rustResult.metrics.maxDrawdown, - totalPnl: rustResult.trades.reduce((sum, trade) => sum + (trade.pnl ?? 0), 0), - avgWin: rustResult.metrics.avgWin, - avgLoss: rustResult.metrics.avgLoss, - }, - equityCurve: rustResult.equity, - trades: rustResult.trades, - finalPositions: Object.fromEntries( - rustResult.positions.map(position => [position.symbol, position]) - ), - }; - - // Log results - this.container.logger.info('Rust backtest completed', { - totalReturn: result.metrics.totalReturn, - totalTrades: result.metrics.totalTrades, - sharpeRatio: result.metrics.sharpeRatio, - }); - - return result; - } - - /** - * Get the backtest configuration - */ - private getConfig(): RustBacktestConfig { - return this.config; - } -} - -/** - * Factory function to create a Rust-powered backtest - */ -export async function createRustBacktest( - container: IServiceContainer, - config: BacktestConfig, - strategies: RustStrategy[] -): Promise { - const storageService = - container.custom?.StorageService || - new StorageService(container, container.mongodb, container.postgres, container.questdb ?? null); - - // Create engine - const engine = new RustBacktestEngine(container, storageService, config); - - // Add strategies - for (const strategy of strategies) { - engine.addStrategy(strategy); - } - - // Run backtest - return await engine.run(); -} diff --git a/apps/stock/orchestrator/src/strategies/RustStrategy.ts b/apps/stock/orchestrator/src/strategies/RustStrategy.ts deleted file mode 100644 index b28116d6..00000000 --- a/apps/stock/orchestrator/src/strategies/RustStrategy.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { BacktestEngine } from '@stock-bot/engine'; -import { getLogger } from '@stock-bot/logger'; -import { type MarketData } from '../types'; - -const logger = getLogger('rust-strategy'); - -export interface Signal { - symbol: string; - signal_type: 'Buy' | 'Sell' | 'Close'; - strength: number; // -1.0 to 1.0 - quantity?: number; - reason?: string; - metadata?: unknown; -} - -export type StrategyCall = - | { method: 'on_market_data'; data: MarketData } - | { method: 'on_fill'; data: { symbol: string; quantity: number; price: number; side: string } }; - -export interface StrategyResponse { - signals: Signal[]; -} - -/** - * Base class for TypeScript strategies that run in the Rust backtest engine - */ -export abstract class RustStrategy { - protected name: string; - protected id: string; - protected parameters: Record; - protected positions: Map = new Map(); - - constructor(name: string, id: string, parameters: Record = {}) { - this.name = name; - this.id = id; - this.parameters = parameters; - } - - /** - * Main callback that Rust will call - */ - public handleCall(call: StrategyCall): StrategyResponse { - switch (call.method) { - case 'on_market_data': { - const signals = this.onMarketData(call.data); - return { signals }; - } - - case 'on_fill': - this.onFill(call.data.symbol, call.data.quantity, call.data.price, call.data.side); - return { signals: [] }; - - default: - return { signals: [] }; - } - } - - /** - * Called when new market data is received - */ - protected abstract onMarketData(data: MarketData): Signal[]; - - /** - * Called when an order is filled - */ - protected onFill(symbol: string, quantity: number, price: number, side: string): void { - const currentPosition = this.positions.get(symbol) || 0; - const newPosition = side === 'buy' ? currentPosition + quantity : currentPosition - quantity; - - if (Math.abs(newPosition) < 0.0001) { - this.positions.delete(symbol); - } else { - this.positions.set(symbol, newPosition); - } - } - - /** - * Helper to create a buy signal - */ - protected buySignal(symbol: string, strength: number = 1.0, reason?: string): Signal { - return { - symbol, - signal_type: 'Buy', - strength, - reason, - }; - } - - /** - * Helper to create a sell signal - */ - protected sellSignal(symbol: string, strength: number = 1.0, reason?: string): Signal { - return { - symbol, - signal_type: 'Sell', - strength, - reason, - }; - } - - /** - * Helper to create a close position signal - */ - protected closeSignal(symbol: string, reason?: string): Signal { - return { - symbol, - signal_type: 'Close', - strength: 1.0, - reason, - }; - } - - /** - * Register this strategy with a backtest engine - */ - public register(engine: BacktestEngine): void { - logger.debug(`Registering strategy ${this.name} with id ${this.id}`); - - // Convert the handleCall method to what Rust expects - const callback = (callJson: string) => { - logger.debug('Strategy callback', { callJson }); - const call: StrategyCall = JSON.parse(callJson); - const response = this.handleCall(call); - logger.debug('Strategy response:', response); - return JSON.stringify(response); - }; - - engine.addTypescriptStrategy(this.name, this.id, this.parameters, callback); - } -} diff --git a/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts b/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts deleted file mode 100644 index c615836f..00000000 --- a/apps/stock/orchestrator/src/strategies/StrategyExecutor.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import type { MarketData } from '../types'; -import type { Signal } from './RustStrategy'; - -interface StrategyState { - priceHistory: Map; - positions: Map; -} -interface InlineStrategy { - onMarketData(data: MarketData, state: StrategyState): Signal[]; - onFill?( - fill: { symbol: string; quantity: number; price: number; side: string }, - state: StrategyState - ): void; -} - -export interface IStrategyExecutor { - onMarketData(data: MarketData): Signal[]; - onFill(symbol: string, quantity: number, price: number, side: string): void; - getState(): Record; - setState(state: Record): void; -} - -/** - * Executes strategies in-process for backtesting - * This avoids the complexity of async callbacks between Rust and TypeScript - */ -export class StrategyExecutor implements IStrategyExecutor { - private strategies: Map = new Map(); - private strategyStates: Map = new Map(); - - registerStrategy(id: string, strategy: InlineStrategy) { - this.strategies.set(id, strategy); - this.strategyStates.set(id, { - priceHistory: new Map(), - positions: new Map(), - }); - } - - onMarketData(data: MarketData): Signal[] { - const allSignals: Signal[] = []; - - for (const [id, strategy] of this.strategies) { - const state = defined(this.strategyStates.get(id)); - const signals = strategy.onMarketData(data, state); - - if (signals && signals.length > 0) { - allSignals.push(...signals); - } - } - - return allSignals; - } - - onFill(symbol: string, quantity: number, price: number, side: string): void { - for (const [id, strategy] of this.strategies) { - const state = defined(this.strategyStates.get(id)); - - if (strategy.onFill) { - strategy.onFill({ symbol, quantity, price, side }, state); - } - - // Update position tracking - const currentPos = state.positions.get(symbol) || 0; - const newPos = side === 'buy' ? currentPos + quantity : currentPos - quantity; - - if (Math.abs(newPos) < 0.0001) { - state.positions.delete(symbol); - } else { - state.positions.set(symbol, newPos); - } - } - } - - getState() { - return Object.fromEntries(this.strategyStates); - } - - setState(state: Record): void { - this.strategyStates = new Map(Object.entries(state)); - } -} - -// Example SMA Crossover Strategy -export const SMACrossoverStrategy = { - onMarketData(data: MarketData, state: StrategyState): Signal[] { - const signals: Signal[] = []; - - // Check if it's bar data - if (data.type !== 'bar') { - return signals; - } - - const { symbol, close } = data.data; - const fastPeriod = 5; - const slowPeriod = 15; - - // Update price history - if (!state.priceHistory.has(symbol)) { - state.priceHistory.set(symbol, []); - } - - const history = defined(state.priceHistory.get(symbol)); - history.push(close); - - // Keep only necessary history - if (history.length > slowPeriod + 1) { - history.shift(); - } - - // Need enough data - if (history.length >= slowPeriod) { - // Calculate SMAs - const fastSMA = history.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; - const slowSMA = history.reduce((a, b) => a + b, 0) / history.length; - - // Previous SMAs (if we have enough history) - if (history.length > slowPeriod) { - const prevHistory = history.slice(0, -1); - const prevFastSMA = prevHistory.slice(-fastPeriod).reduce((a, b) => a + b, 0) / fastPeriod; - const prevSlowSMA = prevHistory.reduce((a, b) => a + b, 0) / prevHistory.length; - - const currentPosition = state.positions.get(symbol) || 0; - - // Golden cross - buy signal - if (prevFastSMA <= prevSlowSMA && fastSMA > slowSMA && currentPosition <= 0) { - signals.push({ - symbol, - signal_type: 'Buy', - strength: 1.0, - quantity: 100, - reason: 'Golden cross', - }); - } - - // Death cross - sell signal - else if (prevFastSMA >= prevSlowSMA && fastSMA < slowSMA && currentPosition >= 0) { - signals.push({ - symbol, - signal_type: 'Sell', - strength: 1.0, - quantity: 100, - reason: 'Death cross', - }); - } - } - } - - return signals; - }, -}; diff --git a/apps/stock/orchestrator/src/strategies/builtin-strategies.ts b/apps/stock/orchestrator/src/strategies/builtin-strategies.ts index 69b0627e..b92ce673 100644 --- a/apps/stock/orchestrator/src/strategies/builtin-strategies.ts +++ b/apps/stock/orchestrator/src/strategies/builtin-strategies.ts @@ -5,17 +5,15 @@ import { StrategyRegistry } from './StrategyRegistry'; export function createBuiltinStrategyRegistry(): StrategyRegistry { return new StrategyRegistry() .register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => { - const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy'); + const { MeanReversionStrategy } = await import('./builtin/MeanReversionStrategy'); return new MeanReversionStrategy(config, modeManager, execution); }) .register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => { - const { SimpleMovingAverageCrossover } = await import( - './examples/SimpleMovingAverageCrossoverFixed' - ); - return new SimpleMovingAverageCrossover(config, modeManager, execution); + const { SmaCrossoverStrategy } = await import('./builtin/SmaCrossoverStrategy'); + return new SmaCrossoverStrategy(config, modeManager, execution); }) .register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => { - const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy'); + const { MLEnhancedStrategy } = await import('./experimental/MLEnhancedStrategy'); return new MLEnhancedStrategy(config, modeManager, execution); }); } diff --git a/apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts b/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts similarity index 98% rename from apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts rename to apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts index c97eda38..f5c4984f 100644 --- a/apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy.ts @@ -21,6 +21,7 @@ interface MeanReversionIndicators { rsi: number; } +/** Versioned implementation used by the built-in mean-reversion aliases. */ export class MeanReversionStrategy extends BaseStrategy { private priceHistory = new Map(); private indicators = new Map(); diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts b/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts similarity index 99% rename from apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts rename to apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts index 559b6a72..951730fe 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts +++ b/apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy.ts @@ -12,7 +12,7 @@ import { smaConfig } from '../strategy-config'; const logger = getLogger('SimpleMovingAverageCrossover'); -export class SimpleMovingAverageCrossover extends BaseStrategy { +export class SmaCrossoverStrategy extends BaseStrategy { private priceHistory = new Map(); private lastSignalBar = new Map(); private barCount = new Map(); diff --git a/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts deleted file mode 100644 index 39aeb991..00000000 --- a/apps/stock/orchestrator/src/strategies/examples/AdvancedMultiIndicatorStrategy.ts +++ /dev/null @@ -1,590 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/utils'; -import type { ModeManager } from '../../core/ModeManager'; -import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService'; -import type { StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; -import { IndicatorManager } from '../indicators/IndicatorManager'; -import { PositionManager } from '../position/PositionManager'; -import { RiskManager } from '../risk/RiskManager'; -import { - CommonFilters, - CommonRules, - SignalManager, - type TradingSignal, -} from '../signals/SignalManager'; - -const logger = getLogger('AdvancedMultiIndicatorStrategy'); - -export interface AdvancedStrategyConfig { - // Indicator settings - fastMA?: number; - slowMA?: number; - rsiPeriod?: number; - atrPeriod?: number; - - // Risk settings - riskPerTrade?: number; - maxPositions?: number; - maxDrawdown?: number; - useATRStops?: boolean; - atrMultiplier?: number; - - // Signal settings - signalAggregation?: 'weighted' | 'majority' | 'unanimous' | 'threshold'; - minSignalStrength?: number; - minSignalConfidence?: number; - - // Position sizing - positionSizing?: 'fixed' | 'risk' | 'kelly' | 'volatility'; - - // Other - debugMode?: boolean; -} - -/** - * Advanced strategy using multiple indicators, risk management, and signal aggregation - */ -export class AdvancedMultiIndicatorStrategy extends BaseStrategy { - private indicatorManager: IndicatorManager; - private positionManager: PositionManager; - private riskManager: RiskManager; - private signalManager: SignalManager; - - private readonly indicatorConfig: Required; - private stopLosses: Map = new Map(); - private takeProfits: Map = new Map(); - - constructor( - strategyConfig: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - super(strategyConfig, modeManager, executionService); - - // Initialize config - this.indicatorConfig = { - fastMA: 20, - slowMA: 50, - rsiPeriod: 14, - atrPeriod: 14, - riskPerTrade: 0.02, - maxPositions: 5, - maxDrawdown: 0.2, - useATRStops: true, - atrMultiplier: 2, - signalAggregation: 'weighted', - minSignalStrength: 0.5, - minSignalConfidence: 0.3, - positionSizing: 'risk', - debugMode: false, - ...strategyConfig.parameters, - }; - - // Initialize managers - const initialCapital = Number(strategyConfig.parameters.initialCapital ?? 100000); - this.indicatorManager = new IndicatorManager(); - this.positionManager = new PositionManager(initialCapital); - this.riskManager = new RiskManager(initialCapital, { - maxPositions: this.indicatorConfig.maxPositions, - maxDrawdownPct: this.indicatorConfig.maxDrawdown, - maxPositionSizePct: 0.1, - }); - - this.signalManager = new SignalManager({ - method: this.indicatorConfig.signalAggregation, - }); - - // Setup signal rules - this.setupSignalRules(); - - logger.info('AdvancedMultiIndicatorStrategy initialized:', this.indicatorConfig); - } - - private setupSignalRules(): void { - // Moving average rules - this.signalManager.addRule({ - name: `MA Crossover (${this.indicatorConfig.fastMA}/${this.indicatorConfig.slowMA})`, - condition: indicators => { - const fast = indicators[`sma${this.indicatorConfig.fastMA}`]; - const slow = indicators[`sma${this.indicatorConfig.slowMA}`]; - const prevFast = indicators[`sma${this.indicatorConfig.fastMA}_prev`]; - const prevSlow = indicators[`sma${this.indicatorConfig.slowMA}_prev`]; - - if (!fast || !slow || !prevFast || !prevSlow) { - return false; - } - - // Check for crossover - const crossover = prevFast <= prevSlow && fast > slow; - const crossunder = prevFast >= prevSlow && fast < slow; - - return crossover || crossunder; - }, - weight: 1, - direction: 'both', - }); - - // RSI rules - this.signalManager.addRules([CommonRules.rsiOversold(30), CommonRules.rsiOverbought(70)]); - - // MACD rules - this.signalManager.addRules([CommonRules.macdBullishCross(), CommonRules.macdBearishCross()]); - - // Bollinger Band rules - this.signalManager.addRules([ - CommonRules.priceAtLowerBand(), - CommonRules.priceAtUpperBand(), - CommonRules.bollingerSqueeze(), - ]); - - // Add filters - this.signalManager.addFilter(CommonFilters.minStrength(this.indicatorConfig.minSignalStrength)); - this.signalManager.addFilter( - CommonFilters.minConfidence(this.indicatorConfig.minSignalConfidence) - ); - this.signalManager.addFilter(CommonFilters.trendAlignment('sma200')); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const { symbol, timestamp, open, high, low, close, volume } = data.data; - - // First time setup for symbol - if (!this.indicatorManager.getHistoryLength(symbol)) { - this.setupSymbolIndicators(symbol); - } - - // Update price history - this.indicatorManager.updatePrice({ - symbol, - timestamp, - open, - high, - low, - close, - volume, - }); - - // Update position market values - this.updatePositionValues(symbol, close); - - // Check stop losses and take profits - this.checkExitConditions(symbol, close); - } - - private setupSymbolIndicators(symbol: string): void { - // Setup incremental indicators - this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { - type: 'sma', - period: this.indicatorConfig.fastMA, - }); - - this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { - type: 'sma', - period: this.indicatorConfig.slowMA, - }); - - this.indicatorManager.setupIncrementalIndicator(symbol, 'rsi', { - type: 'rsi', - period: this.indicatorConfig.rsiPeriod, - }); - - logger.info(`Initialized indicators for ${symbol}`); - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const { symbol, timestamp, close } = data.data; - const historyLength = this.indicatorManager.getHistoryLength(symbol); - - // Need enough data - if (historyLength < Math.max(this.indicatorConfig.slowMA, 26)) { - return null; - } - - // Prepare indicators for signal generation - const indicators = this.prepareIndicators(symbol, close); - if (!indicators) { - return null; - } - - // Check risk before generating signals - const currentPositions = this.getCurrentPositionMap(); - const riskCheck = this.riskManager.checkNewPosition( - symbol, - 100, // Dummy size for check - close, - currentPositions - ); - - if (!riskCheck.allowed && !this.positionManager.hasPosition(symbol)) { - if (this.indicatorConfig.debugMode) { - logger.warn(`Risk check failed for ${symbol}: ${riskCheck.reason}`); - } - return null; - } - - // Generate trading signal - const tradingSignal = this.signalManager.generateSignal(symbol, timestamp, indicators, { - position: this.positionManager.getPositionQuantity(symbol), - }); - - if (!tradingSignal) { - return null; - } - - // Log signal if in debug mode - if (this.indicatorConfig.debugMode) { - logger.info(`Signal generated for ${symbol}:`, { - direction: tradingSignal.direction, - strength: tradingSignal.strength.toFixed(2), - confidence: tradingSignal.confidence.toFixed(2), - rules: tradingSignal.rules, - }); - } - - // Convert to strategy signal - return this.convertToStrategySignal(tradingSignal, symbol, close); - } - - private prepareIndicators(symbol: string, currentPrice: number): Record | null { - const indicators: Record = { price: currentPrice }; - - // Get moving averages - const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastMA); - const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowMA); - const sma200 = this.indicatorManager.getSMA(symbol, 200); - - if (!fastMA || !slowMA) { - return null; - } - - // Current and previous values - indicators[`sma${this.indicatorConfig.fastMA}`] = defined( - this.indicatorManager.getLatest(fastMA) - ); - indicators[`sma${this.indicatorConfig.slowMA}`] = defined( - this.indicatorManager.getLatest(slowMA) - ); - - if (fastMA.length >= 2 && slowMA.length >= 2) { - indicators[`sma${this.indicatorConfig.fastMA}_prev`] = at(fastMA, fastMA.length - 2); - indicators[`sma${this.indicatorConfig.slowMA}_prev`] = at(slowMA, slowMA.length - 2); - } - - if (sma200) { - indicators.sma200 = defined(this.indicatorManager.getLatest(sma200)); - } - - // RSI - const rsi = this.indicatorManager.getRSI(symbol, this.indicatorConfig.rsiPeriod); - if (rsi) { - indicators.rsi = defined(this.indicatorManager.getLatest(rsi)); - } - - // MACD - const macd = this.indicatorManager.getMACD(symbol); - if (macd) { - indicators.macd = defined(this.indicatorManager.getLatest(macd.macd)); - indicators.macd_signal = defined(this.indicatorManager.getLatest(macd.signal)); - indicators.macd_histogram = defined(this.indicatorManager.getLatest(macd.histogram)); - - if (macd.macd.length >= 2) { - indicators.macd_prev = at(macd.macd, macd.macd.length - 2); - indicators.macd_signal_prev = at(macd.signal, macd.signal.length - 2); - } - } - - // Bollinger Bands - const bb = this.indicatorManager.getBollingerBands(symbol); - if (bb) { - indicators.bb_upper = defined(this.indicatorManager.getLatest(bb.upper)); - indicators.bb_middle = defined(this.indicatorManager.getLatest(bb.middle)); - indicators.bb_lower = defined(this.indicatorManager.getLatest(bb.lower)); - } - - // ATR for volatility - const atr = this.indicatorManager.getATR(symbol, this.indicatorConfig.atrPeriod); - if (atr) { - indicators.atr = defined(this.indicatorManager.getLatest(atr)); - } - - // Volume - const priceHistory = this.indicatorManager.getPriceHistory(symbol); - if (priceHistory) { - indicators.volume = at(priceHistory.volume, priceHistory.volume.length - 1); - const avgVolume = priceHistory.volume.slice(-20).reduce((a, b) => a + b, 0) / 20; - indicators.avg_volume = avgVolume; - } - - return indicators; - } - - private convertToStrategySignal( - tradingSignal: TradingSignal, - symbol: string, - currentPrice: number - ): Signal | null { - const currentPosition = this.positionManager.getPositionQuantity(symbol); - - // Determine action based on signal and current position - let type: 'buy' | 'sell' | 'close'; - let quantity: number; - - if (tradingSignal.direction === 'buy') { - if (currentPosition < 0) { - // Close short position - type = 'buy'; - quantity = Math.abs(currentPosition); - } else if (currentPosition === 0) { - // Open long position - type = 'buy'; - quantity = this.calculateIndicatorPositionSize(symbol, currentPrice, tradingSignal); - } else { - // Already long - return null; - } - } else if (tradingSignal.direction === 'sell') { - if (currentPosition > 0) { - // Close long position - type = 'sell'; - quantity = currentPosition; - } else { - return null; - } - } else { - return null; - } - - return { - type, - symbol, - strength: tradingSignal.strength, - reason: tradingSignal.rules.join(', '), - metadata: { - ...tradingSignal.indicators, - quantity, - confidence: tradingSignal.confidence, - rules: tradingSignal.rules, - }, - }; - } - - private calculateIndicatorPositionSize( - symbol: string, - price: number, - signal: TradingSignal - ): number { - const accountBalance = this.positionManager.getAccountBalance(); - - switch (this.indicatorConfig.positionSizing) { - case 'fixed': // Fixed percentage of account - { - const fixedValue = accountBalance * this.indicatorConfig.riskPerTrade * 5; - return Math.floor(fixedValue / price); - } - - case 'risk': // Risk-based sizing with ATR stop - { - const atr = signal.indicators.atr; - if (atr && this.indicatorConfig.useATRStops) { - const stopDistance = atr * this.indicatorConfig.atrMultiplier; - return this.positionManager.calculatePositionSize( - { - accountBalance, - riskPerTrade: this.indicatorConfig.riskPerTrade, - stopLossDistance: stopDistance, - }, - price - ); - } - break; - } - - case 'kelly': // Kelly criterion based on historical performance - { - const metrics = this.positionManager.getPerformanceMetrics(); - if (metrics.totalTrades >= 20) { - return this.positionManager.calculateKellySize( - metrics.winRate / 100, - metrics.avgWin, - metrics.avgLoss, - price - ); - } - break; - } - - case 'volatility': // Volatility-adjusted sizing - { - const atrVol = signal.indicators.atr; - if (atrVol) { - return this.positionManager.calculatePositionSize( - { - accountBalance, - riskPerTrade: this.indicatorConfig.riskPerTrade, - volatilityAdjustment: true, - atr: atrVol, - }, - price - ); - } - break; - } - } - - // Default sizing - return this.positionManager.calculatePositionSize( - { - accountBalance, - riskPerTrade: this.indicatorConfig.riskPerTrade, - }, - price - ); - } - - private updatePositionValues(symbol: string, currentPrice: number): void { - const prices = new Map([[symbol, currentPrice]]); - this.positionManager.updateMarketPrices(prices); - } - - private checkExitConditions(symbol: string, currentPrice: number): void { - const position = this.positionManager.getPosition(symbol); - if (!position) { - return; - } - - const stopLoss = this.stopLosses.get(symbol); - const takeProfit = this.takeProfits.get(symbol); - - // Check stop loss - if (stopLoss) { - if ( - (position.quantity > 0 && currentPrice <= stopLoss) || - (position.quantity < 0 && currentPrice >= stopLoss) - ) { - logger.info(`Stop loss triggered for ${symbol} at ${currentPrice}`); - this.emit('signal', { - type: 'close', - symbol, - strength: 1, - reason: 'Stop loss triggered', - metadata: { stopLoss, currentPrice }, - }); - } - } - - // Check take profit - if (takeProfit) { - if ( - (position.quantity > 0 && currentPrice >= takeProfit) || - (position.quantity < 0 && currentPrice <= takeProfit) - ) { - logger.info(`Take profit triggered for ${symbol} at ${currentPrice}`); - this.emit('signal', { - type: 'close', - symbol, - strength: 1, - reason: 'Take profit triggered', - metadata: { takeProfit, currentPrice }, - }); - } - } - } - - private getCurrentPositionMap(): Map { - const positionMap = new Map(); - - for (const position of this.positionManager.getOpenPositions()) { - positionMap.set(position.symbol, { - quantity: position.quantity, - value: Math.abs(position.quantity * (position.currentPrice || position.avgPrice)), - }); - } - - return positionMap; - } - - override async onOrderUpdate(update: StrategyOrderUpdate): Promise { - await super.onOrderUpdate(update); - - if (update.status === 'filled' && update.fills?.length > 0) { - for (const fill of update.fills) { - const trade = { - symbol: update.symbol, - side: update.side as 'buy' | 'sell', - quantity: fill.quantity, - price: fill.price, - commission: fill.commission || 0, - timestamp: new Date(fill.timestamp), - }; - - const position = this.positionManager.updatePosition(trade); - - // Update risk manager - if (typeof fill.pnl === 'number') { - this.riskManager.updateAfterTrade(fill.pnl ?? 0); - } - - // Set stop loss and take profit for new positions - if (this.indicatorConfig.useATRStops && position.quantity !== 0) { - const atr = this.indicatorManager.getATR(update.symbol); - if (atr) { - const currentATR = this.indicatorManager.getLatest(atr); - if (currentATR) { - const stopDistance = currentATR * this.indicatorConfig.atrMultiplier; - const profitDistance = currentATR * this.indicatorConfig.atrMultiplier * 2; - - if (position.quantity > 0) { - this.stopLosses.set(update.symbol, fill.price - stopDistance); - this.takeProfits.set(update.symbol, fill.price + profitDistance); - } else { - this.stopLosses.set(update.symbol, fill.price + stopDistance); - this.takeProfits.set(update.symbol, fill.price - profitDistance); - } - - logger.info( - `Set stop/take profit for ${update.symbol}: Stop=${this.stopLosses.get(update.symbol)?.toFixed(2)}, TP=${this.takeProfits.get(update.symbol)?.toFixed(2)}` - ); - } - } - } - - // Clear stops if position closed - if (position.quantity === 0) { - this.stopLosses.delete(update.symbol); - this.takeProfits.delete(update.symbol); - } - } - } - } - - override getPerformance() { - const basePerf = super.getPerformance(); - const positionMetrics = this.positionManager.getPerformanceMetrics(); - const riskMetrics = this.riskManager.getMetrics(this.getCurrentPositionMap()); - const signalStats = this.signalManager.getSignalStats(); - - return { - ...basePerf, - ...positionMetrics, - risk: riskMetrics, - signals: signalStats, - }; - } - - // Daily reset for risk metrics - onDayEnd(): void { - this.riskManager.resetDaily(); - logger.info('Daily risk metrics reset'); - } -} diff --git a/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts b/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts deleted file mode 100644 index 94adaea6..00000000 --- a/apps/stock/orchestrator/src/strategies/examples/IndicatorBasedStrategy.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type { ModeManager } from '../../core/ModeManager'; -import { - IncrementalIndicators, - SignalGenerator, - type TradingSignal, -} from '../../indicators/TechnicalAnalysis'; -import type { ExecutionService } from '../../services/ExecutionService'; -import type { MarketData, StrategyConfig } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; - -/** Example of the common strategy lifecycle with native incremental indicators. */ -export class IndicatorBasedStrategy extends BaseStrategy { - private readonly incrementalIndicators = new IncrementalIndicators(); - private readonly signalGenerator = new SignalGenerator(); - private readonly priceHistory = { - close: [] as number[], - high: [] as number[], - low: [] as number[], - volume: [] as number[], - }; - private lastSignal: TradingSignal | null = null; - - constructor( - config: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - super(config, modeManager, executionService); - this.incrementalIndicators.createSMA('sma20', 20); - this.incrementalIndicators.createSMA('sma50', 50); - this.incrementalIndicators.createEMA('ema12', 12); - this.incrementalIndicators.createEMA('ema26', 26); - this.incrementalIndicators.createRSI('rsi14', 14); - } - - protected override updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - const bar = data.data; - this.priceHistory.close.push(bar.close); - this.priceHistory.high.push(bar.high); - this.priceHistory.low.push(bar.low); - this.priceHistory.volume.push(bar.volume); - for (const values of Object.values(this.priceHistory)) { - if (values.length > 100) { - values.shift(); - } - } - for (const key of ['sma20', 'sma50', 'ema12', 'ema26', 'rsi14']) { - this.incrementalIndicators.update(key, bar.close); - } - } - - protected override async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar' || this.priceHistory.close.length < 50) { - return null; - } - const signal = this.signalGenerator.generateSignals( - data.data.symbol, - this.priceHistory, - data.data.timestamp - ); - this.lastSignal = signal; - const minimum = Number(this.config.parameters.minSignalStrength ?? 0.6); - if (signal.action === 'HOLD' || signal.strength < minimum) { - return null; - } - return { - type: signal.action === 'BUY' ? 'buy' : 'sell', - symbol: signal.symbol, - strength: signal.strength, - reason: signal.reason, - metadata: { quantity: Number(this.config.parameters.positionSize ?? 100) }, - }; - } - - getState() { - return { - priceHistoryLength: this.priceHistory.close.length, - lastSignal: this.lastSignal, - config: this.config, - }; - } -} diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts deleted file mode 100644 index 11916983..00000000 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import type { SmaParameters } from '../../contracts/strategies'; -import type { ModeManager } from '../../core/ModeManager'; -import { movingAverageCrossover } from '../../indicators/window-statistics'; -import type { ExecutionService, StrategyFill } from '../../services/ExecutionService'; -import type { OrderRequest, StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; -import { crossoverCheckpointSchema } from '../checkpoint-schemas'; -import { smaConfig } from '../strategy-config'; - -const logger = getLogger('SimpleMovingAverageCrossover'); - -export class SimpleMovingAverageCrossover extends BaseStrategy { - private priceHistory = new Map(); - private lastTradeTime = new Map(); - private barCount = new Map(); - private totalSignals = 0; - override getCheckpointVersion() { - return 'sma-crossover-original/v2'; - } - protected override captureIndicators() { - return { - priceHistory: [...this.priceHistory], - lastSignalBar: [...this.lastTradeTime], - barCount: [...this.barCount], - totalSignals: this.totalSignals, - lastCrossoverType: [], - }; - } - protected override restoreIndicators(input: unknown) { - const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input); - this.priceHistory = new Map(state.priceHistory); - this.lastTradeTime = new Map(state.lastSignalBar); - this.barCount = new Map(state.barCount); - this.totalSignals = state.totalSignals; - } - - private settings: SmaParameters; - private readonly DEBUG_INTERVAL = 10; - - constructor( - config: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - const validated = smaConfig(config, 1); - super(validated, modeManager, executionService); - this.settings = validated.parameters; - logger.info( - `SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}` - ); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const symbol = data.data.symbol; - const price = data.data.close; - - // Update price history - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, []); - this.barCount.set(symbol, 0); - logger.info(`📊 Starting to track ${symbol} @ ${price}`); - } - - const history = defined(this.priceHistory.get(symbol)); - history.push(price); - - // Increment bar count - const currentBar = (this.barCount.get(symbol) || 0) + 1; - this.barCount.set(symbol, currentBar); - - // Keep only needed history - if (history.length > this.settings.slowPeriod * 2) { - history.shift(); - } - - // Log when we have enough data to start trading - if (history.length === this.settings.slowPeriod) { - logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`); - } - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const symbol = data.data.symbol; - const history = this.priceHistory.get(symbol); - - if (!history || history.length <= this.settings.slowPeriod) { - if (history && history.length % 5 === 0) { - logger.debug( - `${symbol} - Not enough history: ${history.length}/${this.settings.slowPeriod + 1} bars` - ); - } - return null; - } - - const crossover = movingAverageCrossover( - history, - this.settings.fastPeriod, - this.settings.slowPeriod - ); - if (!crossover) { - return null; - } - const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover; - - const currentPosition = this.getPosition(symbol); - const currentPrice = data.data.close; - const timestamp = new Date(data.data.timestamp).toISOString().split('T')[0]; - - // Check minimum holding period - const currentBar = this.barCount.get(symbol) || 0; - const lastTradeBar = this.lastTradeTime.get(symbol) || 0; - const barsSinceLastTrade = - lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; - - // Enhanced debugging - log more frequently and when MAs are close - const maDiff = fastMA - slowMA; - const maDiffPct = (maDiff / slowMA) * 100; - const masAreClose = Math.abs(maDiffPct) < 1.0; // Within 1% - - if (history.length % this.DEBUG_INTERVAL === 0 || masAreClose || goldenCross || deathCross) { - logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`); - logger.info(` Price: $${currentPrice.toFixed(2)}`); - logger.info(` Fast MA (${this.settings.fastPeriod}): $${fastMA.toFixed(2)}`); - logger.info(` Slow MA (${this.settings.slowPeriod}): $${slowMA.toFixed(2)}`); - logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); - logger.info(` Position: ${currentPosition} shares`); - logger.info(` Bars since last trade: ${barsSinceLastTrade}`); - - if (goldenCross) { - logger.info(` 🟢 GOLDEN CROSS DETECTED!`); - } - if (deathCross) { - logger.info(` 🔴 DEATH CROSS DETECTED!`); - } - } - - // Note: We removed the MIN_HOLDING_BARS check here to allow closing and opening on same bar - // The check is now done individually for new position entries - - if (goldenCross) { - logger.info(`🟢 Golden cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - // For golden cross, we want to be long - if (currentPosition < 0) { - // Close short position first - logger.info(` Closing short position of ${Math.abs(currentPosition)} shares`); - const signal: Signal = { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Closing short position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'golden', - price: currentPrice, - quantity: Math.abs(currentPosition), // Buy to close short - }, - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else if (currentPosition === 0) { - // No position, open long - logger.info(` No current position, opening long`); - logger.info( - ` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} > Slow MA: ${slowMA.toFixed(2)}` - ); - logger.info( - ` Prev Fast MA: ${prevFastMA.toFixed(2)} <= Prev Slow MA: ${prevSlowMA.toFixed(2)}` - ); - - // Calculate position size - const positionSize = await this.calculateCrossoverPositionSize(currentPrice); - logger.info(` Opening long position: ${positionSize} shares`); - - const signal: Signal = { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Fast MA crossed above Slow MA', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'golden', - price: currentPrice, - quantity: positionSize, - }, - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else { - logger.info(` ⚠️ Already long, skipping buy signal`); - } - } else if (deathCross) { - logger.info(`🔴 Death cross detected for ${symbol} @ ${timestamp}`); - logger.info(` Current position: ${currentPosition} shares`); - - // For death cross, we want to be flat or short - if (currentPosition > 0) { - // Close long position - logger.info(` Closing long position of ${currentPosition} shares`); - logger.info( - ` Price: ${currentPrice.toFixed(2)}, Fast MA: ${fastMA.toFixed(2)} < Slow MA: ${slowMA.toFixed(2)}` - ); - logger.info( - ` Prev Fast MA: ${prevFastMA.toFixed(2)} >= Prev Slow MA: ${prevSlowMA.toFixed(2)}` - ); - - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Fast MA crossed below Slow MA', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'death', - price: currentPrice, - quantity: currentPosition, - }, - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else if (currentPosition === 0) { - // Open short position for long/short strategy - logger.info(` No current position, opening short`); - - const positionSize = await this.calculateCrossoverPositionSize(currentPrice); - logger.info(` Opening short position: ${positionSize} shares`); - - const signal: Signal = { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Opening short position', - metadata: { - fastMA, - slowMA, - prevFastMA, - prevSlowMA, - crossoverType: 'death', - price: currentPrice, - quantity: positionSize, - }, - }; - - this.lastTradeTime.set(symbol, currentBar); - this.totalSignals++; - logger.info(`👉 Total signals generated: ${this.totalSignals}`); - return signal; - } else { - logger.info(` ⚠️ Already short, skipping sell signal`); - } - } - - // Log near-crossover conditions - const fastApproachingSlow = Math.abs(fastMA - slowMA) / slowMA < 0.01; // Within 1% - if (fastApproachingSlow && history.length % 20 === 0) { - logger.debug( - `${symbol} - MAs converging: Fast MA ${fastMA.toFixed(2)} ~ Slow MA ${slowMA.toFixed(2)} (${((Math.abs(fastMA - slowMA) / slowMA) * 100).toFixed(2)}% diff)` - ); - } - - return null; - } - - protected override validateConfig(config: StrategyConfig): StrategyConfig { - const validated = smaConfig(config, 1); - this.settings = validated.parameters; - return validated; - } - - private async calculateCrossoverPositionSize(price: number): Promise { - if (this.settings.quantity !== undefined) { - return this.settings.quantity; - } - const accountBalance = (await this.executionService.getAccount()).equity; - const positionValue = accountBalance * this.settings.positionFraction; - const shares = Math.floor(positionValue / price); - - logger.debug( - `Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}` - ); - - return Math.max(1, shares); // At least 1 share - } - - protected onOrderFilled(fill: StrategyFill): void { - const { symbol, side, quantity, price } = fill; - - logger.info(`✅ ${side.toUpperCase()} filled: ${symbol} - ${quantity} shares @ ${price}`); - - // Position tracking is handled by BaseStrategy.onOrderUpdate - // Just log the current position - const currentPosition = this.getPosition(symbol); - logger.info(`Position for ${symbol}: ${currentPosition} shares`); - } - - // Override to provide custom order generation - protected override async signalToOrder(signal: Signal): Promise { - logger.info(`🔄 Converting signal to order:`, signal); - - const _currentPosition = this.getPosition(signal.symbol); - - // Get position sizing from metadata - const quantity = typeof signal.metadata?.quantity === 'number' ? signal.metadata.quantity : 100; - - if (signal.type === 'buy') { - const order: OrderRequest = { - symbol: signal.symbol, - side: 'buy', - quantity, - orderType: 'market', - timeInForce: 'DAY', - }; - logger.info(`📈 Generated BUY order:`, order); - return order; - } else if (signal.type === 'sell') { - const order: OrderRequest = { - symbol: signal.symbol, - side: 'sell', - quantity, - orderType: 'market', - timeInForce: 'DAY', - }; - logger.info(`📉 Generated SELL order:`, order); - return order; - } - - return null; - } -} diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts deleted file mode 100644 index 669d82bc..00000000 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverV2.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import type { ModeManager } from '../../core/ModeManager'; -import type { ExecutionService, StrategyOrderUpdate } from '../../services/ExecutionService'; -import type { StrategyConfig } from '../../types'; -import { type MarketData } from '../../types'; -import { BaseStrategy, type Signal } from '../BaseStrategy'; -import { IndicatorManager } from '../indicators/IndicatorManager'; -import { PositionManager, type PositionSizingParams } from '../position/PositionManager'; - -const logger = getLogger('SimpleMovingAverageCrossoverV2'); - -export interface SMAStrategyConfig { - fastPeriod?: number; - slowPeriod?: number; - positionSizePct?: number; - riskPerTrade?: number; - useATRStops?: boolean; - minHoldingBars?: number; - debugInterval?: number; -} - -/** - * Refactored SMA Crossover Strategy using new TA library - */ -export class SimpleMovingAverageCrossoverV2 extends BaseStrategy { - private indicatorManager: IndicatorManager; - private positionManager: PositionManager; - - // Strategy parameters - private readonly indicatorConfig: Required; - private lastTradeBar = new Map(); - private barCount = new Map(); - private totalSignals = 0; - - constructor( - strategyConfig: StrategyConfig, - modeManager: ModeManager, - executionService: ExecutionService - ) { - super(strategyConfig, modeManager, executionService); - - // Initialize config with defaults - this.indicatorConfig = { - fastPeriod: 10, - slowPeriod: 20, - positionSizePct: 0.1, - riskPerTrade: 0.02, - useATRStops: true, - minHoldingBars: 1, - debugInterval: 20, - ...strategyConfig.parameters, - }; - - this.indicatorManager = new IndicatorManager(); - this.positionManager = new PositionManager( - Number(strategyConfig.parameters.initialCapital ?? 100000) - ); - - logger.info(`SimpleMovingAverageCrossoverV2 initialized:`, this.indicatorConfig); - } - - protected updateIndicators(data: MarketData): void { - if (data.type !== 'bar') { - return; - } - - const { symbol, timestamp } = data.data; - const { open, high, low, close, volume } = data.data; - - // Update bar count - const currentBar = (this.barCount.get(symbol) || 0) + 1; - this.barCount.set(symbol, currentBar); - - // First time seeing this symbol - if (!this.indicatorManager.getHistoryLength(symbol)) { - logger.info(`📊 Starting to track ${symbol} @ ${close}`); - - // Setup incremental indicators for real-time updates - this.indicatorManager.setupIncrementalIndicator(symbol, 'fast_sma', { - type: 'sma', - period: this.indicatorConfig.fastPeriod, - }); - this.indicatorManager.setupIncrementalIndicator(symbol, 'slow_sma', { - type: 'sma', - period: this.indicatorConfig.slowPeriod, - }); - - if (this.indicatorConfig.useATRStops) { - this.indicatorManager.setupIncrementalIndicator(symbol, 'atr', { - type: 'sma', // Using SMA as proxy for now - period: 14, - }); - } - } - - // Update price history - this.indicatorManager.updatePrice({ - symbol, - timestamp, - open, - high, - low, - close, - volume, - }); - - // Update position market prices - const currentPrices = new Map([[symbol, close]]); - this.positionManager.updateMarketPrices(currentPrices); - - // Log when we have enough data - const historyLength = this.indicatorManager.getHistoryLength(symbol); - if (historyLength === this.indicatorConfig.slowPeriod) { - logger.info(`✅ ${symbol} has enough history (${historyLength} bars) to start trading`); - } - } - - protected async generateSignal(data: MarketData): Promise { - if (data.type !== 'bar') { - return null; - } - - const { symbol, timestamp } = data.data; - const { close } = data.data; - const historyLength = this.indicatorManager.getHistoryLength(symbol); - - // Need enough data for slow MA - if (historyLength < this.indicatorConfig.slowPeriod) { - if (historyLength % 5 === 0) { - logger.debug( - `${symbol} - Building history: ${historyLength}/${this.indicatorConfig.slowPeriod} bars` - ); - } - return null; - } - - // Calculate indicators - const fastMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.fastPeriod); - const slowMA = this.indicatorManager.getSMA(symbol, this.indicatorConfig.slowPeriod); - - if (!fastMA || !slowMA) { - return null; - } - - // Get current and previous values - const currentFast = this.indicatorManager.getLatest(fastMA); - const currentSlow = this.indicatorManager.getLatest(slowMA); - - if (currentFast === null || currentSlow === null) { - return null; - } - - // Check for crossovers - const goldenCross = this.indicatorManager.checkCrossover(fastMA, slowMA); - const deathCross = this.indicatorManager.checkCrossunder(fastMA, slowMA); - - // Get current position - const currentPosition = this.positionManager.getPositionQuantity(symbol); - const currentBar = this.barCount.get(symbol) || 0; - const lastTradeBar = this.lastTradeBar.get(symbol) || 0; - const barsSinceLastTrade = - lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER; - - // Enhanced debugging - const maDiff = currentFast - currentSlow; - const maDiffPct = (maDiff / currentSlow) * 100; - const shouldLog = - historyLength % this.indicatorConfig.debugInterval === 0 || - Math.abs(maDiffPct) < 1.0 || - goldenCross || - deathCross; - - if (shouldLog) { - const dateStr = new Date(timestamp).toISOString().split('T')[0]; - logger.info(`${symbol} @ ${dateStr} [Bar ${currentBar}]:`); - logger.info(` Price: $${close.toFixed(2)}`); - logger.info(` Fast MA (${this.indicatorConfig.fastPeriod}): $${currentFast.toFixed(2)}`); - logger.info(` Slow MA (${this.indicatorConfig.slowPeriod}): $${currentSlow.toFixed(2)}`); - logger.info(` MA Diff: ${maDiff.toFixed(2)} (${maDiffPct.toFixed(2)}%)`); - logger.info(` Position: ${currentPosition} shares`); - - // Show additional indicators if available - const rsi = this.indicatorManager.getRSI(symbol); - if (rsi) { - const currentRSI = this.indicatorManager.getLatest(rsi); - logger.info(` RSI: ${currentRSI?.toFixed(2)}`); - } - - if (goldenCross) { - logger.info(` 🟢 GOLDEN CROSS DETECTED!`); - } - if (deathCross) { - logger.info(` 🔴 DEATH CROSS DETECTED!`); - } - } - - // Check minimum holding period - if (barsSinceLastTrade < this.indicatorConfig.minHoldingBars && lastTradeBar > 0) { - return null; - } - - // Position sizing parameters - const sizingParams: PositionSizingParams = { - accountBalance: this.positionManager.getAccountBalance(), - riskPerTrade: this.indicatorConfig.riskPerTrade, - volatilityAdjustment: this.indicatorConfig.useATRStops, - }; - - if (this.indicatorConfig.useATRStops) { - const atr = this.indicatorManager.getATR(symbol); - if (atr) { - sizingParams.atr = this.indicatorManager.getLatest(atr) || undefined; - } - } - - // Generate signals - if (goldenCross) { - logger.info(`🟢 Golden cross detected for ${symbol}`); - - if (currentPosition < 0) { - // Close short position - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - return { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Closing short position', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'golden', - price: close, - quantity: Math.abs(currentPosition), - }, - }; - } else if (currentPosition === 0) { - // Calculate position size - const positionSize = this.positionManager.calculatePositionSize(sizingParams, close); - - logger.info(` Opening long position: ${positionSize} shares`); - logger.info(` Account balance: $${sizingParams.accountBalance.toFixed(2)}`); - - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - - return { - type: 'buy', - symbol, - strength: 0.8, - reason: 'Golden cross - Fast MA crossed above Slow MA', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'golden', - price: close, - quantity: positionSize, - }, - }; - } - } else if (deathCross && currentPosition > 0) { - logger.info(`🔴 Death cross detected for ${symbol}`); - - this.lastTradeBar.set(symbol, currentBar); - this.totalSignals++; - - return { - type: 'sell', - symbol, - strength: 0.8, - reason: 'Death cross - Fast MA crossed below Slow MA', - metadata: { - fastMA: currentFast, - slowMA: currentSlow, - crossoverType: 'death', - price: close, - quantity: currentPosition, - }, - }; - } - - return null; - } - - override async onOrderUpdate(update: StrategyOrderUpdate): Promise { - await super.onOrderUpdate(update); - - // Update position manager with fills - if (update.status === 'filled' && update.fills?.length > 0) { - for (const fill of update.fills) { - this.positionManager.updatePosition({ - symbol: update.symbol, - side: update.side, - quantity: fill.quantity, - price: fill.price, - commission: fill.commission || 0, - timestamp: new Date(fill.timestamp), - }); - } - - // Log performance metrics periodically - if (this.totalSignals % 5 === 0) { - const metrics = this.positionManager.getPerformanceMetrics(); - logger.info('📊 Strategy Performance:', { - trades: metrics.totalTrades, - winRate: `${metrics.winRate.toFixed(2)}%`, - totalPnL: `$${metrics.totalPnl.toFixed(2)}`, - returnPct: `${metrics.returnPct.toFixed(2)}%`, - }); - } - } - } - - override getPerformance() { - const metrics = this.positionManager.getPerformanceMetrics(); - return { - ...super.getPerformance(), - ...metrics, - totalSignals: this.totalSignals, - openPositions: this.positionManager.getOpenPositions(), - }; - } - - // Optional: Get current state for debugging - getState() { - return { - config: this.indicatorConfig, - totalSignals: this.totalSignals, - performance: this.getPerformance(), - positions: Array.from(this.positions.entries()), - }; - } -} diff --git a/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts b/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts similarity index 99% rename from apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts rename to apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts index 660e2234..c5bc7a3c 100644 --- a/apps/stock/orchestrator/src/strategies/examples/MLEnhancedStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/experimental/MLEnhancedStrategy.ts @@ -17,6 +17,7 @@ interface MLModelConfig { minTrainingSize: number; } +/** Optional run-local experiment; deliberately lacks a durable paper checkpoint contract. */ export class MLEnhancedStrategy extends BaseStrategy { private tensorflow: typeof tf | undefined; private get tf(): typeof tf { diff --git a/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts b/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts deleted file mode 100644 index ae392a60..00000000 --- a/apps/stock/orchestrator/src/strategies/indicators/IndicatorManager.ts +++ /dev/null @@ -1,337 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import { getLogger } from '@stock-bot/logger'; -import { IncrementalIndicators, TechnicalAnalysis } from '../../indicators/TechnicalAnalysis'; - -const logger = getLogger('IndicatorManager'); - -export interface IndicatorConfig { - type: 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger' | 'stochastic' | 'atr'; - period?: number; - fastPeriod?: number; - slowPeriod?: number; - signalPeriod?: number; - stdDev?: number; - kPeriod?: number; - dPeriod?: number; - smoothK?: number; -} - -export interface PriceData { - symbol: string; - timestamp: number; - open: number; - high: number; - low: number; - close: number; - volume: number; -} - -/** - * Manages technical indicators for a strategy - * Handles both batch and incremental calculations - */ -export class IndicatorManager { - private ta: TechnicalAnalysis; - private incrementalIndicators: IncrementalIndicators; - private priceHistory: Map< - string, - { - open: number[]; - high: number[]; - low: number[]; - close: number[]; - volume: number[]; - } - > = new Map(); - - private indicatorCache: Map> = new Map(); - private maxHistoryLength: number; - - constructor(maxHistoryLength = 500) { - this.ta = new TechnicalAnalysis(); - this.incrementalIndicators = new IncrementalIndicators(); - this.maxHistoryLength = maxHistoryLength; - } - - /** - * Update price history with new data - */ - updatePrice(data: PriceData): void { - const { symbol, open, high, low, close, volume } = data; - - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, { - open: [], - high: [], - low: [], - close: [], - volume: [], - }); - } - - const history = defined(this.priceHistory.get(symbol)); - - // Add new data - history.open.push(open); - history.high.push(high); - history.low.push(low); - history.close.push(close); - history.volume.push(volume); - - // Trim to max length - if (history.close.length > this.maxHistoryLength) { - history.open.shift(); - history.high.shift(); - history.low.shift(); - history.close.shift(); - history.volume.shift(); - } - - // Clear cache for this symbol as data has changed - this.indicatorCache.delete(symbol); - - // Update incremental indicators - this.updateIncrementalIndicators(symbol, close); - } - - /** - * Get price history for a symbol - */ - getPriceHistory(symbol: string) { - return this.priceHistory.get(symbol); - } - - /** - * Get the number of price bars for a symbol - */ - getHistoryLength(symbol: string): number { - const history = this.priceHistory.get(symbol); - return history ? history.close.length : 0; - } - - /** - * Calculate SMA - */ - getSMA(symbol: string, period: number): number[] | null { - const cacheKey = `sma_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) { - return null; - } - return this.ta.sma(history.close, period); - }); - } - - /** - * Calculate EMA - */ - getEMA(symbol: string, period: number): number[] | null { - const cacheKey = `ema_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) { - return null; - } - return this.ta.ema(history.close, period); - }); - } - - /** - * Calculate RSI - */ - getRSI(symbol: string, period: number = 14): number[] | null { - const cacheKey = `rsi_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period + 1) { - return null; - } - return this.ta.rsi(history.close, period); - }); - } - - /** - * Calculate MACD - */ - getMACD(symbol: string, fastPeriod = 12, slowPeriod = 26, signalPeriod = 9) { - const cacheKey = `macd_${fastPeriod}_${slowPeriod}_${signalPeriod}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < slowPeriod + signalPeriod) { - return null; - } - return this.ta.macd(history.close, fastPeriod, slowPeriod, signalPeriod); - }); - } - - /** - * Calculate Bollinger Bands - */ - getBollingerBands(symbol: string, period = 20, stdDev = 2) { - const cacheKey = `bb_${period}_${stdDev}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period) { - return null; - } - return this.ta.bollingerBands(history.close, period, stdDev); - }); - } - - /** - * Calculate Stochastic - */ - getStochastic(symbol: string, kPeriod = 14, dPeriod = 3, smoothK = 1) { - const cacheKey = `stoch_${kPeriod}_${dPeriod}_${smoothK}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < kPeriod) { - return null; - } - return this.ta.stochastic( - history.high, - history.low, - history.close, - kPeriod, - dPeriod, - smoothK - ); - }); - } - - /** - * Calculate ATR - */ - getATR(symbol: string, period = 14): number[] | null { - const cacheKey = `atr_${period}`; - return this.getCachedOrCalculate(symbol, cacheKey, () => { - const history = this.priceHistory.get(symbol); - if (!history || history.close.length < period + 1) { - return null; - } - return this.ta.atr(history.high, history.low, history.close, period); - }); - } - - /** - * Get latest value from an indicator - */ - getLatest(values: number[] | null): number | null { - if (!values || values.length === 0) { - return null; - } - return values[values.length - 1] ?? null; - } - - /** - * Check for crossover - */ - checkCrossover(series1: number[] | null, series2: number[] | null): boolean { - if (!series1 || !series2) { - return false; - } - return TechnicalAnalysis.crossover(series1, series2); - } - - /** - * Check for crossunder - */ - checkCrossunder(series1: number[] | null, series2: number[] | null): boolean { - if (!series1 || !series2) { - return false; - } - return TechnicalAnalysis.crossunder(series1, series2); - } - - /** - * Setup incremental indicators - */ - setupIncrementalIndicator(symbol: string, name: string, config: IndicatorConfig): void { - const key = `${symbol}_${name}`; - - switch (config.type) { - case 'sma': - this.incrementalIndicators.createSMA(key, defined(config.period)); - break; - case 'ema': - this.incrementalIndicators.createEMA(key, defined(config.period)); - break; - case 'rsi': - this.incrementalIndicators.createRSI(key, defined(config.period)); - break; - default: - logger.warn(`Incremental indicator type ${config.type} not supported`); - } - } - - /** - * Get incremental indicator value - */ - getIncrementalValue(symbol: string, name: string): number | null { - const key = `${symbol}_${name}`; - return this.incrementalIndicators.current(key); - } - - /** - * Clear all data for a symbol - */ - clearSymbol(symbol: string): void { - this.priceHistory.delete(symbol); - this.indicatorCache.delete(symbol); - - // Reset incremental indicators for this symbol - for (const [key, indicator] of this.incrementalIndicators.entries()) { - if (key.startsWith(`${symbol}_`)) { - if ('reset' in indicator) { - indicator.reset(); - } - } - } - } - - /** - * Clear all data - */ - clearAll(): void { - this.priceHistory.clear(); - this.indicatorCache.clear(); - this.incrementalIndicators.resetAll(); - } - - private getCachedOrCalculate( - symbol: string, - cacheKey: string, - calculator: () => T | null - ): T | null { - if (!this.indicatorCache.has(symbol)) { - this.indicatorCache.set(symbol, new Map()); - } - - const symbolCache = defined(this.indicatorCache.get(symbol)); - - if (symbolCache.has(cacheKey)) { - return symbolCache.get(cacheKey) as T; - } - - const result = calculator(); - if (result !== null) { - symbolCache.set(cacheKey, result); - } - - return result; - } - - private updateIncrementalIndicators(symbol: string, price: number): void { - // Update all incremental indicators for this symbol - for (const [key] of this.incrementalIndicators.entries()) { - if (key.startsWith(`${symbol}_`)) { - try { - this.incrementalIndicators.update(key, price); - } catch (error) { - logger.error(`Error updating incremental indicator ${key}:`, error); - } - } - } - } -} diff --git a/apps/stock/orchestrator/src/strategies/position/PositionManager.ts b/apps/stock/orchestrator/src/strategies/position/PositionManager.ts deleted file mode 100644 index 4999ad03..00000000 --- a/apps/stock/orchestrator/src/strategies/position/PositionManager.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('PositionManager'); - -export interface Position { - symbol: string; - quantity: number; - avgPrice: number; - currentPrice?: number; - unrealizedPnl?: number; - realizedPnl: number; - openTime: Date; - lastUpdateTime: Date; -} - -export interface Trade { - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - timestamp: Date; - pnl?: number; -} - -export interface PositionSizingParams { - accountBalance: number; - riskPerTrade: number; // As percentage (e.g., 0.02 for 2%) - stopLossDistance?: number; // Price distance for stop loss - maxPositionSize?: number; // Max % of account in one position - volatilityAdjustment?: boolean; - atr?: number; // For volatility-based sizing -} - -/** - * Manages positions and calculates position sizes - */ -export class PositionManager { - private positions: Map = new Map(); - private trades: Trade[] = []; - private accountBalance: number; - private initialBalance: number; - - constructor(initialBalance: number = 100000) { - this.initialBalance = initialBalance; - this.accountBalance = initialBalance; - } - - /** - * Update position with a new trade - */ - updatePosition(trade: Trade): Position { - const { symbol, side, quantity, price, commission } = trade; - let position = this.positions.get(symbol); - - if (!position) { - // New position - position = { - symbol, - quantity: side === 'buy' ? quantity : -quantity, - avgPrice: price, - realizedPnl: -commission, - openTime: trade.timestamp, - lastUpdateTime: trade.timestamp, - }; - } else { - const oldQuantity = position.quantity; - const newQuantity = side === 'buy' ? oldQuantity + quantity : oldQuantity - quantity; - - if (Math.sign(oldQuantity) !== Math.sign(newQuantity) && oldQuantity !== 0) { - // Position flip or close - const closedQuantity = Math.min(Math.abs(oldQuantity), quantity); - const pnl = this.calculatePnl( - position.avgPrice, - price, - closedQuantity, - oldQuantity > 0 ? 'sell' : 'buy' - ); - - position.realizedPnl += pnl - commission; - trade.pnl = pnl - commission; - - // Update average price if position continues - if (Math.abs(newQuantity) > 0.0001) { - position.avgPrice = price; - } - } else if (Math.sign(oldQuantity) === Math.sign(newQuantity) || oldQuantity === 0) { - // Adding to position - const totalCost = Math.abs(oldQuantity) * position.avgPrice + quantity * price; - const totalQuantity = Math.abs(oldQuantity) + quantity; - position.avgPrice = totalCost / totalQuantity; - position.realizedPnl -= commission; - } - - position.quantity = newQuantity; - position.lastUpdateTime = trade.timestamp; - } - - // Store or remove position - if (Math.abs(position.quantity) < 0.0001) { - this.positions.delete(symbol); - logger.info( - `Closed position for ${symbol}, realized P&L: $${position.realizedPnl.toFixed(2)}` - ); - } else { - this.positions.set(symbol, position); - } - - // Record trade - this.trades.push(trade); - - // Update account balance - if (trade.pnl !== undefined) { - this.accountBalance += trade.pnl; - } - - return position; - } - - /** - * Get current position for a symbol - */ - getPosition(symbol: string): Position | undefined { - return this.positions.get(symbol); - } - - /** - * Get position quantity - */ - getPositionQuantity(symbol: string): number { - const position = this.positions.get(symbol); - return position ? position.quantity : 0; - } - - /** - * Check if has position - */ - hasPosition(symbol: string): boolean { - const position = this.positions.get(symbol); - return position !== undefined && Math.abs(position.quantity) > 0.0001; - } - - /** - * Get all open positions - */ - getOpenPositions(): Position[] { - return Array.from(this.positions.values()); - } - - /** - * Update market prices for positions - */ - updateMarketPrices(prices: Map): void { - for (const [symbol, position] of this.positions) { - const currentPrice = prices.get(symbol); - if (currentPrice) { - position.currentPrice = currentPrice; - position.unrealizedPnl = this.calculatePnl( - position.avgPrice, - currentPrice, - Math.abs(position.quantity), - position.quantity > 0 ? 'sell' : 'buy' - ); - } - } - } - - /** - * Calculate position size based on risk parameters - */ - calculatePositionSize(params: PositionSizingParams, currentPrice: number): number { - const { - accountBalance, - riskPerTrade, - stopLossDistance, - maxPositionSize = 0.25, - volatilityAdjustment = false, - atr, - } = params; - - let positionSize: number; - - if (stopLossDistance && stopLossDistance > 0) { - // Risk-based position sizing - const riskAmount = accountBalance * riskPerTrade; - positionSize = Math.floor(riskAmount / stopLossDistance); - } else if (volatilityAdjustment && atr) { - // Volatility-based position sizing - const riskAmount = accountBalance * riskPerTrade; - const stopDistance = atr * 2; // 2 ATR stop - positionSize = Math.floor(riskAmount / stopDistance); - } else { - // Fixed percentage position sizing - const positionValue = accountBalance * riskPerTrade * 10; // Simplified - positionSize = Math.floor(positionValue / currentPrice); - } - - // Apply max position size limit - const maxShares = Math.floor((accountBalance * maxPositionSize) / currentPrice); - positionSize = Math.min(positionSize, maxShares); - - // Ensure minimum position size - return Math.max(1, positionSize); - } - - /** - * Calculate Kelly Criterion position size - */ - calculateKellySize( - winRate: number, - avgWin: number, - avgLoss: number, - currentPrice: number - ): number { - if (avgLoss === 0) { - return 0; - } - - const b = avgWin / avgLoss; - const p = winRate; - const q = 1 - p; - const kelly = (p * b - q) / b; - - // Apply Kelly fraction (usually 0.25 to be conservative) - const kellyFraction = 0.25; - const percentageOfCapital = Math.max(0, Math.min(0.25, kelly * kellyFraction)); - - const positionValue = this.accountBalance * percentageOfCapital; - return Math.max(1, Math.floor(positionValue / currentPrice)); - } - - /** - * Get performance metrics - */ - getPerformanceMetrics() { - const totalTrades = this.trades.length; - const winningTrades = this.trades.filter(t => (t.pnl || 0) > 0); - const losingTrades = this.trades.filter(t => (t.pnl || 0) < 0); - - const totalPnl = this.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); - const unrealizedPnl = Array.from(this.positions.values()).reduce( - (sum, p) => sum + (p.unrealizedPnl || 0), - 0 - ); - - const winRate = totalTrades > 0 ? winningTrades.length / totalTrades : 0; - const avgWin = - winningTrades.length > 0 - ? winningTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / winningTrades.length - : 0; - const avgLoss = - losingTrades.length > 0 - ? Math.abs(losingTrades.reduce((sum, t) => sum + (t.pnl || 0), 0) / losingTrades.length) - : 0; - - const profitFactor = - avgLoss > 0 ? (avgWin * winningTrades.length) / (avgLoss * losingTrades.length) : 0; - - return { - totalTrades, - winningTrades: winningTrades.length, - losingTrades: losingTrades.length, - winRate: winRate * 100, - totalPnl, - unrealizedPnl, - totalEquity: this.accountBalance + unrealizedPnl, - avgWin, - avgLoss, - profitFactor, - returnPct: ((this.accountBalance - this.initialBalance) / this.initialBalance) * 100, - }; - } - - /** - * Get account balance - */ - getAccountBalance(): number { - return this.accountBalance; - } - - /** - * Get total equity (balance + unrealized P&L) - */ - getTotalEquity(): number { - const unrealizedPnl = Array.from(this.positions.values()).reduce( - (sum, p) => sum + (p.unrealizedPnl || 0), - 0 - ); - return this.accountBalance + unrealizedPnl; - } - - private calculatePnl( - entryPrice: number, - exitPrice: number, - quantity: number, - side: 'buy' | 'sell' - ): number { - if (side === 'sell') { - return (exitPrice - entryPrice) * quantity; - } else { - return (entryPrice - exitPrice) * quantity; - } - } -} diff --git a/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts b/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts deleted file mode 100644 index f4f4b2a1..00000000 --- a/apps/stock/orchestrator/src/strategies/risk/RiskManager.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/utils'; - -const logger = getLogger('RiskManager'); - -export interface RiskLimits { - maxPositions?: number; - maxPositionSizePct?: number; // Max % of account per position - maxTotalExposurePct?: number; // Max % of account in all positions - maxDailyLossPct?: number; // Max daily loss as % of account - maxDrawdownPct?: number; // Max drawdown allowed - maxConsecutiveLosses?: number; - minWinRate?: number; // Minimum win rate to continue trading -} - -export interface RiskMetrics { - currentExposure: number; - currentExposurePct: number; - dailyPnl: number; - dailyPnlPct: number; - currentDrawdown: number; - currentDrawdownPct: number; - maxDrawdown: number; - maxDrawdownPct: number; - consecutiveLosses: number; - volatility: number; - sharpeRatio: number; - var95: number; // Value at Risk 95% -} - -export interface RiskCheckResult { - allowed: boolean; - reason?: string; - adjustedSize?: number; -} - -/** - * Manages risk limits and calculates risk metrics - */ -export class RiskManager { - private limits: Required; - private dailyPnl = 0; - private dailyStartBalance: number; - private peakBalance: number; - private consecutiveLosses = 0; - private dailyReturns: number[] = []; - private readonly lookbackDays = 30; - - constructor( - private accountBalance: number, - limits: RiskLimits = {} - ) { - this.limits = { - maxPositions: 10, - maxPositionSizePct: 0.1, - maxTotalExposurePct: 0.6, - maxDailyLossPct: 0.05, - maxDrawdownPct: 0.2, - maxConsecutiveLosses: 5, - minWinRate: 0.3, - ...limits, - }; - - this.dailyStartBalance = accountBalance; - this.peakBalance = accountBalance; - } - - /** - * Check if a new position is allowed - */ - checkNewPosition( - symbol: string, - proposedSize: number, - price: number, - currentPositions: Map - ): RiskCheckResult { - const proposedValue = Math.abs(proposedSize * price); - const proposedPct = proposedValue / this.accountBalance; - - // Check max position size - if (proposedPct > this.limits.maxPositionSizePct) { - const maxValue = this.accountBalance * this.limits.maxPositionSizePct; - const adjustedSize = Math.floor(maxValue / price); - - return { - allowed: true, - reason: `Position size reduced from ${proposedSize} to ${adjustedSize} (max ${(this.limits.maxPositionSizePct * 100).toFixed(1)}% per position)`, - adjustedSize, - }; - } - - // Check max positions - if (currentPositions.size >= this.limits.maxPositions && !currentPositions.has(symbol)) { - return { - allowed: false, - reason: `Maximum number of positions (${this.limits.maxPositions}) reached`, - }; - } - - // Check total exposure - let totalExposure = proposedValue; - for (const [sym, pos] of currentPositions) { - if (sym !== symbol) { - totalExposure += Math.abs(pos.value); - } - } - - const totalExposurePct = totalExposure / this.accountBalance; - if (totalExposurePct > this.limits.maxTotalExposurePct) { - return { - allowed: false, - reason: `Total exposure would be ${(totalExposurePct * 100).toFixed(1)}% (max ${(this.limits.maxTotalExposurePct * 100).toFixed(1)}%)`, - }; - } - - // Check daily loss limit - const dailyLossPct = Math.abs(this.dailyPnl) / this.dailyStartBalance; - if (this.dailyPnl < 0 && dailyLossPct >= this.limits.maxDailyLossPct) { - return { - allowed: false, - reason: `Daily loss limit reached (${(dailyLossPct * 100).toFixed(1)}%)`, - }; - } - - // Check consecutive losses - if (this.consecutiveLosses >= this.limits.maxConsecutiveLosses) { - return { - allowed: false, - reason: `Maximum consecutive losses (${this.limits.maxConsecutiveLosses}) reached`, - }; - } - - // Check drawdown - const currentDrawdownPct = (this.peakBalance - this.accountBalance) / this.peakBalance; - if (currentDrawdownPct >= this.limits.maxDrawdownPct) { - return { - allowed: false, - reason: `Maximum drawdown reached (${(currentDrawdownPct * 100).toFixed(1)}%)`, - }; - } - - return { allowed: true }; - } - - /** - * Update metrics after a trade - */ - updateAfterTrade(pnl: number): void { - this.dailyPnl += pnl; - this.accountBalance += pnl; - - if (pnl < 0) { - this.consecutiveLosses++; - } else if (pnl > 0) { - this.consecutiveLosses = 0; - } - - if (this.accountBalance > this.peakBalance) { - this.peakBalance = this.accountBalance; - } - } - - /** - * Reset daily metrics - */ - resetDaily(): void { - // Record daily return - const dailyReturn = (this.accountBalance - this.dailyStartBalance) / this.dailyStartBalance; - this.dailyReturns.push(dailyReturn); - - // Keep only recent returns - if (this.dailyReturns.length > this.lookbackDays) { - this.dailyReturns.shift(); - } - - this.dailyPnl = 0; - this.dailyStartBalance = this.accountBalance; - - logger.info( - `Daily reset - Balance: $${this.accountBalance.toFixed(2)}, Daily return: ${(dailyReturn * 100).toFixed(2)}%` - ); - } - - /** - * Calculate current risk metrics - */ - getMetrics(currentPositions: Map): RiskMetrics { - let currentExposure = 0; - for (const pos of currentPositions.values()) { - currentExposure += Math.abs(pos.value); - } - - const currentDrawdown = this.peakBalance - this.accountBalance; - const currentDrawdownPct = this.peakBalance > 0 ? currentDrawdown / this.peakBalance : 0; - - return { - currentExposure, - currentExposurePct: currentExposure / this.accountBalance, - dailyPnl: this.dailyPnl, - dailyPnlPct: this.dailyPnl / this.dailyStartBalance, - currentDrawdown, - currentDrawdownPct, - maxDrawdown: Math.max(currentDrawdown, 0), - maxDrawdownPct: Math.max(currentDrawdownPct, 0), - consecutiveLosses: this.consecutiveLosses, - volatility: this.calculateVolatility(), - sharpeRatio: this.calculateSharpeRatio(), - var95: this.calculateVaR(0.95), - }; - } - - /** - * Update risk limits - */ - updateLimits(newLimits: Partial): void { - this.limits = { ...this.limits, ...newLimits }; - logger.info('Risk limits updated:', this.limits); - } - - /** - * Get current limits - */ - getLimits(): Required { - return { ...this.limits }; - } - - /** - * Calculate portfolio volatility - */ - private calculateVolatility(): number { - if (this.dailyReturns.length < 2) { - return 0; - } - - const mean = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; - const variance = - this.dailyReturns.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / - (this.dailyReturns.length - 1); - - return Math.sqrt(variance) * Math.sqrt(252); // Annualized - } - - /** - * Calculate Sharpe ratio - */ - private calculateSharpeRatio(riskFreeRate = 0.02): number { - if (this.dailyReturns.length < 2) { - return 0; - } - - const avgReturn = this.dailyReturns.reduce((sum, r) => sum + r, 0) / this.dailyReturns.length; - const annualizedReturn = avgReturn * 252; - const volatility = this.calculateVolatility(); - - if (volatility === 0) { - return 0; - } - - return (annualizedReturn - riskFreeRate) / volatility; - } - - /** - * Calculate Value at Risk - */ - private calculateVaR(confidence: number): number { - if (this.dailyReturns.length < 5) { - return 0; - } - - const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sortedReturns.length); - - return Math.abs(at(sortedReturns, index) * this.accountBalance); - } -} diff --git a/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts b/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts deleted file mode 100644 index 841c1999..00000000 --- a/apps/stock/orchestrator/src/strategies/rust/SimpleMovingAverageCrossoverRust.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { defined } from '@stock-bot/invariants'; -import { type MarketData } from '../../types'; -import { RustStrategy, type Signal } from '../RustStrategy'; - -interface BarData { - open: number; - high: number; - low: number; - close: number; - volume: number; - timestamp: number; -} - -export class SimpleMovingAverageCrossoverRust extends RustStrategy { - private priceHistory: Map = new Map(); - private lastCrossover: Map = new Map(); - private barsSinceSignal: Map = new Map(); - - private fastPeriod: number; - private slowPeriod: number; - private minHoldingBars: number; - - constructor( - parameters: { - fastPeriod?: number; - slowPeriod?: number; - minHoldingBars?: number; - } = {} - ) { - super('SimpleMovingAverageCrossover', `sma-crossover-${Date.now()}`, parameters); - - this.fastPeriod = parameters.fastPeriod || 5; - this.slowPeriod = parameters.slowPeriod || 15; - this.minHoldingBars = parameters.minHoldingBars || 3; - } - - protected onMarketData(data: MarketData): Signal[] { - const signals: Signal[] = []; - - // Only process bar data - if (data.type !== 'bar') { - return signals; - } - - const bar = data.data as BarData; - const symbol = data.data.symbol; - const price = bar.close; - - // Update price history - if (!this.priceHistory.has(symbol)) { - this.priceHistory.set(symbol, []); - this.barsSinceSignal.set(symbol, 0); - } - - const history = defined(this.priceHistory.get(symbol)); - history.push(price); - - // Keep only necessary history - if (history.length > this.slowPeriod) { - history.shift(); - } - - // Update bars since signal - const currentBar = this.barsSinceSignal.get(symbol) || 0; - this.barsSinceSignal.set(symbol, currentBar + 1); - - // Need enough data - if (history.length < this.slowPeriod) { - return signals; - } - - // Calculate moving averages - const fastMA = this.calculateSMA(history, this.fastPeriod); - const slowMA = this.calculateSMA(history, this.slowPeriod); - - // Calculate previous MAs - const prevHistory = history.slice(0, -1); - const prevFastMA = this.calculateSMA(prevHistory, this.fastPeriod); - const prevSlowMA = this.calculateSMA(prevHistory, this.slowPeriod); - - // Check for crossovers - const currentPosition = this.positions.get(symbol) || 0; - const lastCrossover = this.lastCrossover.get(symbol); - const barsSinceSignal = this.barsSinceSignal.get(symbol) || 0; - - // Golden cross - bullish signal - if (prevFastMA <= prevSlowMA && fastMA > slowMA) { - this.lastCrossover.set(symbol, 'golden'); - - if (currentPosition < 0) { - // Close short position - signals.push(this.closeSignal(symbol, 'Golden cross - Close short')); - } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - // Open long position - signals.push(this.buySignal(symbol, 0.8, 'Golden cross - Open long')); - this.barsSinceSignal.set(symbol, 0); - } - } - - // Death cross - bearish signal - else if (prevFastMA >= prevSlowMA && fastMA < slowMA) { - this.lastCrossover.set(symbol, 'death'); - - if (currentPosition > 0) { - // Close long position - signals.push(this.closeSignal(symbol, 'Death cross - Close long')); - } else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - // Open short position - signals.push(this.sellSignal(symbol, 0.8, 'Death cross - Open short')); - this.barsSinceSignal.set(symbol, 0); - } - } - - // Trend following - enter on pullbacks - else if (currentPosition === 0 && barsSinceSignal >= this.minHoldingBars) { - if (lastCrossover === 'golden' && fastMA > slowMA) { - // Bullish trend continues - signals.push(this.buySignal(symbol, 0.8, 'Bullish trend - Open long')); - this.barsSinceSignal.set(symbol, 0); - } else if (lastCrossover === 'death' && fastMA < slowMA) { - // Bearish trend continues - signals.push(this.sellSignal(symbol, 0.8, 'Bearish trend - Open short')); - this.barsSinceSignal.set(symbol, 0); - } - } - - return signals; - } - - private calculateSMA(prices: number[], period: number): number { - if (prices.length < period) { - return 0; - } - - const relevantPrices = prices.slice(-period); - const sum = relevantPrices.reduce((a, b) => a + b, 0); - return sum / period; - } -} diff --git a/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts b/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts deleted file mode 100644 index e8cc549d..00000000 --- a/apps/stock/orchestrator/src/strategies/signals/SignalManager.ts +++ /dev/null @@ -1,497 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('SignalManager'); - -export interface SignalRule { - name: string; - condition: (indicators: Record) => boolean; - weight: number; - direction: 'buy' | 'sell' | 'both'; -} - -export interface SignalFilter { - name: string; - filter: (signal: TradingSignal, context: Record) => boolean; -} - -export interface TradingSignal { - symbol: string; - timestamp: number; - direction: 'buy' | 'sell' | 'neutral'; - strength: number; // -1 to 1 (-1 = strong sell, 1 = strong buy) - confidence: number; // 0 to 1 - rules: string[]; // Rules that triggered - indicators: Record; - metadata?: unknown; -} - -export interface SignalAggregation { - method: 'weighted' | 'majority' | 'unanimous' | 'threshold'; - threshold?: number; // For threshold method -} - -/** - * Manages trading signals and rules - */ -export class SignalManager { - private rules: SignalRule[] = []; - private filters: SignalFilter[] = []; - private signalHistory: TradingSignal[] = []; - private maxHistorySize = 1000; - - constructor(private aggregation: SignalAggregation = { method: 'weighted' }) {} - - /** - * Add a signal rule - */ - addRule(rule: SignalRule): void { - this.rules.push(rule); - logger.info(`Added signal rule: ${rule.name}`); - } - - /** - * Add multiple rules - */ - addRules(rules: SignalRule[]): void { - rules.forEach(rule => this.addRule(rule)); - } - - /** - * Add a signal filter - */ - addFilter(filter: SignalFilter): void { - this.filters.push(filter); - logger.info(`Added signal filter: ${filter.name}`); - } - - /** - * Remove a rule by name - */ - removeRule(name: string): void { - this.rules = this.rules.filter(r => r.name !== name); - } - - /** - * Generate signal based on indicators - */ - generateSignal( - symbol: string, - timestamp: number, - indicators: Record, - context: Record = {} - ): TradingSignal | null { - const triggeredRules: { rule: SignalRule; triggered: boolean }[] = []; - - // Check each rule - for (const rule of this.rules) { - try { - const triggered = rule.condition(indicators); - if (triggered) { - triggeredRules.push({ rule, triggered: true }); - } - } catch (error) { - logger.error(`Error evaluating rule ${rule.name}:`, error); - } - } - - if (triggeredRules.length === 0) { - return null; - } - - // Aggregate signals based on method - const signal = this.aggregateSignals(symbol, timestamp, indicators, triggeredRules); - - if (!signal) { - return null; - } - - // Apply filters - for (const filter of this.filters) { - try { - if (!filter.filter(signal, context)) { - logger.debug(`Signal filtered by ${filter.name}`); - return null; - } - } catch (error) { - logger.error(`Error applying filter ${filter.name}:`, error); - } - } - - // Store in history - this.addToHistory(signal); - - return signal; - } - - /** - * Aggregate multiple rule triggers into a single signal - */ - private aggregateSignals( - symbol: string, - timestamp: number, - indicators: Record, - triggeredRules: { rule: SignalRule; triggered: boolean }[] - ): TradingSignal | null { - let buyWeight = 0; - let sellWeight = 0; - let totalWeight = 0; - const rules: string[] = []; - - for (const { rule } of triggeredRules) { - rules.push(rule.name); - totalWeight += Math.abs(rule.weight); - - if (rule.direction === 'buy' || rule.direction === 'both') { - buyWeight += rule.weight; - } - if (rule.direction === 'sell' || rule.direction === 'both') { - sellWeight += rule.weight; - } - } - - let direction: 'buy' | 'sell' | 'neutral' = 'neutral'; - let strength = 0; - let confidence = 0; - - switch (this.aggregation.method) { - case 'weighted': { - const netWeight = buyWeight - sellWeight; - strength = totalWeight > 0 ? netWeight / totalWeight : 0; - confidence = Math.min(triggeredRules.length / this.rules.length, 1); - - if (Math.abs(strength) > 0.1) { - direction = strength > 0 ? 'buy' : 'sell'; - } - break; - } - - case 'majority': { - const buyCount = triggeredRules.filter( - t => t.rule.direction === 'buy' || t.rule.direction === 'both' - ).length; - const sellCount = triggeredRules.filter( - t => t.rule.direction === 'sell' || t.rule.direction === 'both' - ).length; - - if (buyCount > sellCount) { - direction = 'buy'; - strength = buyCount / triggeredRules.length; - } else if (sellCount > buyCount) { - direction = 'sell'; - strength = -sellCount / triggeredRules.length; - } - confidence = triggeredRules.length / this.rules.length; - break; - } - - case 'unanimous': { - const allBuy = triggeredRules.every( - t => t.rule.direction === 'buy' || t.rule.direction === 'both' - ); - const allSell = triggeredRules.every( - t => t.rule.direction === 'sell' || t.rule.direction === 'both' - ); - - if (allBuy && triggeredRules.length >= 2) { - direction = 'buy'; - strength = 1; - confidence = 1; - } else if (allSell && triggeredRules.length >= 2) { - direction = 'sell'; - strength = -1; - confidence = 1; - } - break; - } - - case 'threshold': { - const threshold = this.aggregation.threshold || 0.7; - const avgWeight = totalWeight > 0 ? (buyWeight - sellWeight) / totalWeight : 0; - - if (avgWeight >= threshold) { - direction = 'buy'; - strength = avgWeight; - confidence = triggeredRules.length / this.rules.length; - } else if (avgWeight <= -threshold) { - direction = 'sell'; - strength = avgWeight; - confidence = triggeredRules.length / this.rules.length; - } - break; - } - } - - if (direction === 'neutral') { - return null; - } - - return { - symbol, - timestamp, - direction, - strength, - confidence, - rules, - indicators, - }; - } - - /** - * Get recent signals for a symbol - */ - getRecentSignals(symbol: string, count = 10): TradingSignal[] { - return this.signalHistory.filter(s => s.symbol === symbol).slice(-count); - } - - /** - * Get signal statistics - */ - getSignalStats(symbol?: string) { - const signals = symbol - ? this.signalHistory.filter(s => s.symbol === symbol) - : this.signalHistory; - - const buySignals = signals.filter(s => s.direction === 'buy'); - const sellSignals = signals.filter(s => s.direction === 'sell'); - - const avgBuyStrength = - buySignals.length > 0 - ? buySignals.reduce((sum, s) => sum + s.strength, 0) / buySignals.length - : 0; - - const avgSellStrength = - sellSignals.length > 0 - ? sellSignals.reduce((sum, s) => sum + Math.abs(s.strength), 0) / sellSignals.length - : 0; - - const avgConfidence = - signals.length > 0 ? signals.reduce((sum, s) => sum + s.confidence, 0) / signals.length : 0; - - return { - totalSignals: signals.length, - buySignals: buySignals.length, - sellSignals: sellSignals.length, - avgBuyStrength, - avgSellStrength, - avgConfidence, - ruleHitRate: this.calculateRuleHitRate(), - }; - } - - /** - * Clear signal history - */ - clearHistory(): void { - this.signalHistory = []; - } - - private addToHistory(signal: TradingSignal): void { - this.signalHistory.push(signal); - - if (this.signalHistory.length > this.maxHistorySize) { - this.signalHistory.shift(); - } - } - - private calculateRuleHitRate(): Record { - const ruleHits: Record = {}; - - for (const signal of this.signalHistory) { - for (const rule of signal.rules) { - ruleHits[rule] = (ruleHits[rule] || 0) + 1; - } - } - - const hitRate: Record = {}; - for (const [rule, hits] of Object.entries(ruleHits)) { - hitRate[rule] = this.signalHistory.length > 0 ? hits / this.signalHistory.length : 0; - } - - return hitRate; - } -} - -/** - * Common signal rules - */ -export const CommonRules = { - // Moving Average Rules - goldenCross: (fastMA: string, slowMA: string): SignalRule => ({ - name: `Golden Cross (${fastMA}/${slowMA})`, - condition: indicators => { - const fast = indicators[fastMA]; - const slow = indicators[slowMA]; - const prevFast = indicators[`${fastMA}_prev`]; - const prevSlow = indicators[`${slowMA}_prev`]; - if ( - fast === undefined || - slow === undefined || - prevFast === undefined || - prevSlow === undefined - ) { - return false; - } - return prevFast <= prevSlow && fast > slow; - }, - weight: 1, - direction: 'buy', - }), - - deathCross: (fastMA: string, slowMA: string): SignalRule => ({ - name: `Death Cross (${fastMA}/${slowMA})`, - condition: indicators => { - const fast = indicators[fastMA]; - const slow = indicators[slowMA]; - const prevFast = indicators[`${fastMA}_prev`]; - const prevSlow = indicators[`${slowMA}_prev`]; - if ( - fast === undefined || - slow === undefined || - prevFast === undefined || - prevSlow === undefined - ) { - return false; - } - return prevFast >= prevSlow && fast < slow; - }, - weight: 1, - direction: 'sell', - }), - - // RSI Rules - rsiOversold: (threshold = 30): SignalRule => ({ - name: `RSI Oversold (<${threshold})`, - condition: indicators => Number(indicators.rsi) < threshold, - weight: 0.5, - direction: 'buy', - }), - - rsiOverbought: (threshold = 70): SignalRule => ({ - name: `RSI Overbought (>${threshold})`, - condition: indicators => Number(indicators.rsi) > threshold, - weight: 0.5, - direction: 'sell', - }), - - // MACD Rules - macdBullishCross: (): SignalRule => ({ - name: 'MACD Bullish Cross', - condition: indicators => { - return ( - Number(indicators.macd_prev) < Number(indicators.macd_signal_prev) && - Number(indicators.macd) > Number(indicators.macd_signal) - ); - }, - weight: 0.8, - direction: 'buy', - }), - - macdBearishCross: (): SignalRule => ({ - name: 'MACD Bearish Cross', - condition: indicators => { - return ( - Number(indicators.macd_prev) > Number(indicators.macd_signal_prev) && - Number(indicators.macd) < Number(indicators.macd_signal) - ); - }, - weight: 0.8, - direction: 'sell', - }), - - // Bollinger Band Rules - bollingerSqueeze: (threshold = 0.02): SignalRule => ({ - name: `Bollinger Squeeze (<${threshold})`, - condition: indicators => { - const bandwidth = - (Number(indicators.bb_upper) - Number(indicators.bb_lower)) / Number(indicators.bb_middle); - return bandwidth < threshold; - }, - weight: 0.3, - direction: 'both', - }), - - priceAtLowerBand: (): SignalRule => ({ - name: 'Price at Lower Bollinger Band', - condition: indicators => { - const bbPercent = - (Number(indicators.price) - Number(indicators.bb_lower)) / - (Number(indicators.bb_upper) - Number(indicators.bb_lower)); - return bbPercent < 0.05; - }, - weight: 0.6, - direction: 'buy', - }), - - priceAtUpperBand: (): SignalRule => ({ - name: 'Price at Upper Bollinger Band', - condition: indicators => { - const bbPercent = - (Number(indicators.price) - Number(indicators.bb_lower)) / - (Number(indicators.bb_upper) - Number(indicators.bb_lower)); - return bbPercent > 0.95; - }, - weight: 0.6, - direction: 'sell', - }), -}; - -/** - * Common signal filters - */ -export const CommonFilters = { - // Minimum signal strength - minStrength: (threshold = 0.5): SignalFilter => ({ - name: `Min Strength (${threshold})`, - filter: signal => Math.abs(signal.strength) >= threshold, - }), - - // Minimum confidence - minConfidence: (threshold = 0.3): SignalFilter => ({ - name: `Min Confidence (${threshold})`, - filter: signal => signal.confidence >= threshold, - }), - - // Time of day filter - tradingHours: (startHour = 9.5, endHour = 16): SignalFilter => ({ - name: `Trading Hours (${startHour}-${endHour})`, - filter: signal => { - const date = new Date(signal.timestamp); - const hour = date.getUTCHours() + date.getUTCMinutes() / 60; - return hour >= startHour && hour < endHour; - }, - }), - - // Trend alignment - trendAlignment: (trendIndicator = 'sma200'): SignalFilter => ({ - name: `Trend Alignment (${trendIndicator})`, - filter: signal => { - const trend = signal.indicators[trendIndicator]; - const price = signal.indicators.price; - if (!trend || !price) { - return true; - } - - // Buy signals only above trend, sell signals only below - if (signal.direction === 'buy') { - return price > trend; - } else if (signal.direction === 'sell') { - return price < trend; - } - return true; - }, - }), - - // Volume confirmation - volumeConfirmation: (multiplier = 1.5): SignalFilter => ({ - name: `Volume Confirmation (${multiplier}x)`, - filter: signal => { - const volume = signal.indicators.volume; - const avgVolume = signal.indicators.avg_volume; - if (!volume || !avgVolume) { - return true; - } - - return volume >= avgVolume * multiplier; - }, - }), -}; diff --git a/apps/stock/orchestrator/src/strategies/strategy-config.ts b/apps/stock/orchestrator/src/strategies/strategy-config.ts index 71c5d98e..5f6cf7cc 100644 --- a/apps/stock/orchestrator/src/strategies/strategy-config.ts +++ b/apps/stock/orchestrator/src/strategies/strategy-config.ts @@ -4,14 +4,8 @@ import { } from '../contracts/strategies'; import type { StrategyConfig } from '../types'; -export function smaConfig(config: StrategyConfig, defaultHoldingBars = 3) { - return { - ...config, - parameters: typescriptSmaParameters.parse({ - ...config.parameters, - minHoldingBars: config.parameters.minHoldingBars ?? defaultHoldingBars, - }), - }; +export function smaConfig(config: StrategyConfig) { + return { ...config, parameters: typescriptSmaParameters.parse(config.parameters) }; } export function meanReversionConfig(config: StrategyConfig) { return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) }; diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index 34d2252d..d971bbbf 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -9,24 +9,49 @@ const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => j /** Include static imports/re-exports and lazy imports; type-only edges do not load code. */ function runtimeImports(file: string): string[] { - const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true); + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true + ); const imports = new Set(); function visit(node: ts.Node) { if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { const clause = node.importClause; const bindings = clause?.namedBindings; - const typesOnly = clause?.isTypeOnly || - (clause && !clause.name && bindings && ts.isNamedImports(bindings) && - bindings.elements.length > 0 && bindings.elements.every(item => item.isTypeOnly)); + const typesOnly = + clause?.isTypeOnly || + (clause && + !clause.name && + bindings && + ts.isNamedImports(bindings) && + bindings.elements.length > 0 && + bindings.elements.every(item => item.isTypeOnly)); if (!typesOnly) imports.add(node.moduleSpecifier.text); } - if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) { + if ( + ts.isExportDeclaration(node) && + !node.isTypeOnly && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) + ) { const clause = node.exportClause; - if (!clause || !ts.isNamedExports(clause) || !clause.elements.length || clause.elements.some(item => !item.isTypeOnly)) { + if ( + !clause || + !ts.isNamedExports(clause) || + !clause.elements.length || + clause.elements.some(item => !item.isTypeOnly) + ) { imports.add(node.moduleSpecifier.text); } } - if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) { + if ( + ts.isCallExpression(node) && + node.expression.kind === ts.SyntaxKind.ImportKeyword && + node.arguments[0] && + ts.isStringLiteral(node.arguments[0]) + ) { imports.add(node.arguments[0].text); } ts.forEachChild(node, visit); @@ -39,13 +64,21 @@ const imports = new Map(files.map(file => [file, runtimeImports(file)])); function localFile(from: string, specifier: string): string | undefined { if (!specifier.startsWith('.')) return undefined; const path = resolve(dirname(from), specifier); - const target = [path, `${path}.ts`, join(path, 'index.ts')].find(file => existsSync(file) && imports.has(file)); - if (!target) throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`); + const target = [path, `${path}.ts`, join(path, 'index.ts')].find( + file => existsSync(file) && imports.has(file) + ); + if (!target) + throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`); return target; } -const graph = new Map([...imports].map(([file, dependencies]) => [file, - dependencies.map(specifier => localFile(file, specifier)).filter((file): file is string => !!file), -])); +const graph = new Map( + [...imports].map(([file, dependencies]) => [ + file, + dependencies + .map(specifier => localFile(file, specifier)) + .filter((file): file is string => !!file), + ]) +); function reachable(file: string, seen = new Set()): Set { if (seen.has(file)) return seen; @@ -58,7 +91,10 @@ describe('orchestrator architecture boundaries', () => { it('local runtime dependencies are acyclic', () => { const done = new Set(); function visit(file: string, stack: string[]) { - if (stack.includes(file)) throw new Error(`Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}`); + if (stack.includes(file)) + throw new Error( + `Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}` + ); if (done.has(file)) return; for (const next of graph.get(file) ?? []) visit(next, [...stack, file]); done.add(file); @@ -68,24 +104,44 @@ describe('orchestrator architecture boundaries', () => { it('contracts and native worker protocol cannot load services, storage or server adapters', () => { const contracts = files.filter(file => file.startsWith(join(root, 'contracts/'))); - for (const entry of [...contracts, join(root, 'types.ts'), join(root, 'backtest/native-worker-protocol.ts')]) { + for (const entry of [ + ...contracts, + join(root, 'types.ts'), + join(root, 'backtest/native-worker-protocol.ts'), + ]) { for (const file of reachable(entry)) { const path = relative(root, file); - expect(path === 'types.ts' || path.startsWith('contracts/') || path === 'backtest/native-worker-protocol.ts').toBe(true); + expect( + path === 'types.ts' || + path.startsWith('contracts/') || + path === 'backtest/native-worker-protocol.ts' + ).toBe(true); for (const specifier of imports.get(file) ?? []) { - expect(specifier.startsWith('.') || ['zod', '@stock-bot/types'].includes(specifier)).toBe(true); + expect(specifier.startsWith('.') || ['zod', '@stock-bot/types'].includes(specifier)).toBe( + true + ); } } } }); it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => { - for (const entry of ['execution/SimulationExecution.ts', 'execution/StrategyRecovery.ts', 'execution/repository.ts', 'execution/strategy-recovery.ts', 'execution/model.ts']) { + for (const entry of [ + 'execution/SimulationExecution.ts', + 'execution/StrategyRecovery.ts', + 'execution/repository.ts', + 'execution/strategy-recovery.ts', + 'execution/model.ts', + ]) { for (const file of reachable(join(root, entry))) { expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data)\//); expect(relative(root, file)).not.toMatch(/(Postgres|Backtest)ExecutionRepository/); for (const specifier of imports.get(file) ?? []) { - expect(['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes(specifier)).toBe(false); + expect( + ['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes( + specifier + ) + ).toBe(false); } } } @@ -94,14 +150,109 @@ describe('orchestrator architecture boundaries', () => { it('the strategy manager cannot select or directly import concrete strategies', () => { const file = join(root, 'strategies/StrategyManager.ts'); - expect(imports.get(file)?.some(specifier => specifier.includes('/examples/'))).toBe(false); + expect( + graph + .get(file) + ?.some(target => /^strategies\/(builtin|experimental)\//.test(relative(root, target))) + ).toBe(false); expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/); - expect([...reachable(join(root, 'strategies/StrategyRegistry.ts'))].map(file => relative(root, file)).sort()) - .toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']); + expect( + [...reachable(join(root, 'strategies/StrategyRegistry.ts'))] + .map(file => relative(root, file)) + .sort() + ).toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']); + }); + + it('concrete strategies can only be loaded by the registry or other strategy implementations', () => { + for (const [file, dependencies] of graph) { + const owner = relative(root, file); + for (const dependency of dependencies) { + const target = relative(root, dependency); + if (!/^strategies\/(builtin|experimental)\//.test(target)) continue; + expect( + owner === 'strategies/builtin-strategies.ts' || + /^strategies\/(builtin|experimental)\//.test(owner) + ).toBe(true); + if (owner.startsWith('strategies/builtin/')) { + expect(target.startsWith('strategies/experimental/')).toBe(false); + } + } + } + }); + + it('retired execution paths and strategy-local financial frameworks cannot return', () => { + const retired = [ + 'backtest/RustBacktestEngine.ts', + 'strategies/RustStrategy.ts', + 'strategies/StrategyExecutor.ts', + ]; + for (const file of retired) expect(existsSync(join(root, file))).toBe(false); + for (const file of files) { + expect(relative(root, file)).not.toMatch( + /^strategies\/(examples|rust|position|risk|signals|indicators)\// + ); + } + }); + + it('native backtest execution stays in the worker and strategies cannot submit orders directly', () => { + const nativeEntrypoints = files.filter( + file => + relative(root, file).startsWith('backtest/') && + imports.get(file)?.includes('@stock-bot/engine') + ); + expect(nativeEntrypoints.map(file => relative(root, file))).toEqual([ + 'backtest/native-worker.ts', + ]); + for (const file of files) { + const path = relative(root, file); + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true + ); + function visit(node: ts.Node) { + // Check named imports anywhere, including aliases; a new wrapper outside backtest/ is still forbidden. + if ( + ts.isImportDeclaration(node) && + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === '@stock-bot/engine' && + !node.importClause?.isTypeOnly + ) { + const bindings = node.importClause?.namedBindings; + if (bindings && ts.isNamedImports(bindings)) { + for (const binding of bindings.elements) { + if ( + !binding.isTypeOnly && + (binding.propertyName ?? binding.name).text === 'BacktestEngine' + ) { + expect(path).toBe('backtest/native-worker.ts'); + } + } + } + } + if (ts.isCallExpression(node)) { + const callee = node.expression; + const method = ts.isPropertyAccessExpression(callee) + ? callee.name.text + : ts.isElementAccessExpression(callee) && + callee.argumentExpression && + ts.isStringLiteral(callee.argumentExpression) + ? callee.argumentExpression.text + : undefined; + expect(method).not.toBe('addTypescriptStrategy'); + if (path.startsWith('strategies/')) expect(method).not.toBe('submitOrder'); + } + ts.forEachChild(node, visit); + } + visit(source); + } }); it('backtest playback cannot depend on trading, data, reporting or service adapters', () => { - const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))].map(file => relative(root, file)).sort(); + const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))] + .map(file => relative(root, file)) + .sort(); expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']); }); @@ -109,9 +260,16 @@ describe('orchestrator architecture boundaries', () => { for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) { for (const file of reachable(join(root, entry))) { expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data|execution)\//); - expect(relative(root, file)).not.toMatch(/backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/); + expect(relative(root, file)).not.toMatch( + /backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/ + ); for (const specifier of imports.get(file) ?? []) { - expect(specifier.startsWith('.') || ['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes(specifier)).toBe(true); + expect( + specifier.startsWith('.') || + ['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes( + specifier + ) + ).toBe(true); } } } diff --git a/test/integration/backtest-workflow.test.ts b/test/integration/backtest-workflow.test.ts index 404d9634..79e67b2b 100644 --- a/test/integration/backtest-workflow.test.ts +++ b/test/integration/backtest-workflow.test.ts @@ -9,6 +9,7 @@ import { PostgreSQLClient } from '@stock-bot/postgres'; import type { MongoDBClient } from '@stock-bot/services'; import type { BacktestRunResult } from '@stock-bot/types'; import { persistEodPrices } from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage'; +import { runMultiStrategyBacktest } from '../../apps/stock/orchestrator/examples/multi-strategy-backtest'; import { createBacktestRoutes } from '../../apps/stock/orchestrator/src/api/rest/backtest'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { @@ -276,6 +277,36 @@ describe('one backtest execution workflow', () => { } }); + test('the maintained multi-strategy example runs through the composed runner and persists real results', async () => { + const f = await fixture(); + const services = await typescriptRuntime(f); + const runner = services.custom!.BacktestRunner!; + cleanup.unshift(async () => { + await runner.shutdown(); + await services.custom?.ModeManager?.shutdown(); + }); + const result = await runMultiStrategyBacktest(runner, config); + expect(result.status).toBe('completed'); + expect(result.engine).toBe('typescript'); + expect(result.trades.length).toBeGreaterThan(0); + expect(result.config.config).toBeUndefined(); + expect(config.config).toEqual({ fastPeriod: 3, slowPeriod: 7 }); + expect(result.config.strategies?.map(strategy => strategy.name)).toEqual([ + 'sma-crossover', + 'mean-reversion', + ]); + const strategies = services.custom!.StrategyManager!.getAllStrategies(); + expect(strategies.map(strategy => strategy.getCheckpointVersion())).toEqual([ + 'sma-crossover-fixed/v2', + 'mean-reversion/v2', + ]); + expect(result.config.dataset?.barCount).toBe(70); + expect((await f.postgres.query('SELECT status FROM runs')).rows).toEqual([ + { status: 'completed' }, + ]); + expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1); + }); + test('TypeScript cancellation is persisted without a partial success or completion event', async () => { const f = await fixture(); const services = await typescriptRuntime(f); diff --git a/test/integration/strategy-contracts.test.ts b/test/integration/strategy-contracts.test.ts index 5fa3fcdf..493067ef 100644 --- a/test/integration/strategy-contracts.test.ts +++ b/test/integration/strategy-contracts.test.ts @@ -26,8 +26,8 @@ import { trailingPopulationDeviation, } from '../../apps/stock/orchestrator/src/indicators/window-statistics'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; -import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy'; -import { SimpleMovingAverageCrossover } from '../../apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed'; +import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; +import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types'; import { config, logger, makeExecution, start } from '../fixtures/execution'; @@ -219,7 +219,7 @@ describe('explicit strategy contracts and shared planning', () => { test('definitions are detached and rejected inactive edits leave effective settings intact', async () => { const f = await runtime(); const input = { ...definition, parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 7 } }; - const strategy = new SimpleMovingAverageCrossover(input, f.mode, f.execution); + const strategy = new SmaCrossoverStrategy(input, f.mode, f.execution); input.parameters.fastPeriod = 0; const view = strategy.getConfig(); view.parameters.slowPeriod = 0; @@ -316,11 +316,7 @@ describe('shared trailing-window math and native parity', () => { const f = await runtime(settings); for (let i = 0; i < 90; i++) await f.manager.onMarketData(bar(100 + Math.sin(i / 3), i)); const state = f.strategy.captureCheckpoint(); - const replacement = new SimpleMovingAverageCrossover( - f.strategy.getConfig(), - f.mode, - f.execution - ); + const replacement = new SmaCrossoverStrategy(f.strategy.getConfig(), f.mode, f.execution); replacement.restoreCheckpoint(state); expect(replacement.captureCheckpoint()).toEqual(state); expect(replacement.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); @@ -360,19 +356,15 @@ describe('shared trailing-window math and native parity', () => { await f.execution.initialize(config, f.engine); cleanup.push(() => f.execution.shutdown()); const mode = { getTradingEngine: () => f.engine } as ModeManager; - const legacy = new SimpleMovingAverageCrossover(definition, mode, f.execution); + const legacy = new SmaCrossoverStrategy(definition, mode, f.execution); legacy.getCheckpointVersion = () => 'sma-crossover-fixed/v1'; await f.execution.registerStrategy(legacy); const before = await f.execution.getRecoveryStatus(); - const upgraded = new SimpleMovingAverageCrossover(definition, mode, f.execution); + const upgraded = new SmaCrossoverStrategy(definition, mode, f.execution); await expect(f.execution.registerStrategy(upgraded)).rejects.toThrow('version changed'); expect(await f.execution.getRecoveryStatus()).toEqual(before); await f.execution.pauseStrategy('sma'); - const fresh = new SimpleMovingAverageCrossover( - { ...definition, id: 'sma-v2' }, - mode, - f.execution - ); + const fresh = new SmaCrossoverStrategy({ ...definition, id: 'sma-v2' }, mode, f.execution); await f.execution.registerStrategy(fresh); expect((await f.execution.getRecoveryStatus()).strategies).toMatchObject([ { strategyId: 'sma', enabled: false, version: 'sma-crossover-fixed/v1' }, diff --git a/test/integration/strategy-registry.test.ts b/test/integration/strategy-registry.test.ts index 15111a94..7f05bf19 100644 --- a/test/integration/strategy-registry.test.ts +++ b/test/integration/strategy-registry.test.ts @@ -1,6 +1,8 @@ import { afterEach, describe, expect, test } from 'bun:test'; import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; +import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; +import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; import { config, logger, makeExecution, quote } from '../fixtures/execution'; @@ -77,14 +79,14 @@ describe('strategy registration and expansion', () => { const f = await fixture(); const registry = createBuiltinStrategyRegistry(); for (const name of ['meanreversion', 'mean-reversion']) { - expect( - (await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion() - ).toBe('mean-reversion/v2'); + const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); + expect(strategy).toBeInstanceOf(MeanReversionStrategy); + expect(strategy.getCheckpointVersion()).toBe('mean-reversion/v2'); } for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) { - expect( - (await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion() - ).toBe('sma-crossover-fixed/v2'); + const strategy = await registry.create({ ...recoveryConfig, name }, f.dependencies); + expect(strategy).toBeInstanceOf(SmaCrossoverStrategy); + expect(strategy.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); } for (const name of ['mlenhanced', 'ml-enhanced']) { expect( diff --git a/tsconfig.check.json b/tsconfig.check.json index ed028ade..6c04ac53 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -26,6 +26,7 @@ "apps/stock/**/src/**/*.ts", "apps/stock/**/src/**/*.tsx", "tools/**/src/**/*.ts", + "apps/stock/orchestrator/examples/multi-strategy-backtest.ts", "libs/core/services/test/contracts.type-test.ts" ], "exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"]