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