# 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
```