moved indicators to rust

This commit is contained in:
Boki 2025-07-03 16:54:43 -04:00
parent c106a719e8
commit 6df32dc18b
27 changed files with 6113 additions and 1 deletions

View file

@ -0,0 +1,293 @@
# 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
```

View file

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

View file

@ -0,0 +1,212 @@
# 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/core`
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