Add versioned streaming indicators and share chart calculations
This commit is contained in:
parent
7827220b9b
commit
cca5d71e6e
20 changed files with 1470 additions and 331 deletions
|
|
@ -29,6 +29,13 @@ not an incremental O(1) indicator implementation.
|
|||
|
||||
## Native batch and incremental indicators
|
||||
|
||||
Portable reviewed EMA, Wilder RSI and Wilder ATR (batch and restartable streaming),
|
||||
plus derived chart calculations, are available from `@stock-bot/calculations/indicators`.
|
||||
See [the versioned contracts](../../../../libs/calculations/docs/indicators.md) before
|
||||
choosing a seed, flat-data policy or ATR first range. They are not drop-in aliases for
|
||||
every historical native behavior. Mean-reversion v2 keeps its rolling simple RSI;
|
||||
adopting Wilder RSI for an existing strategy requires a deliberate new version.
|
||||
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
trailingSimpleRsi,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import { at, defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { MeanReversionParameters } from '../../contracts/strategies';
|
||||
import type { ModeManager } from '../../core/ModeManager';
|
||||
import { trailingMean, trailingPopulationDeviation } from '@stock-bot/calculations/indicators';
|
||||
import type { ExecutionService } from '../../services/ExecutionService';
|
||||
import type { StrategyConfig } from '../../types';
|
||||
import { type MarketData } from '../../types';
|
||||
|
|
@ -209,34 +213,8 @@ export class MeanReversionStrategy extends BaseStrategy {
|
|||
}
|
||||
|
||||
private calculateRSI(prices: number[], period: number = 14): number {
|
||||
if (prices.length < period + 1) {
|
||||
return 50;
|
||||
}
|
||||
|
||||
let gains = 0;
|
||||
let losses = 0;
|
||||
|
||||
// Calculate initial average gain/loss
|
||||
for (let i = 1; i <= period; i++) {
|
||||
const change = at(prices, prices.length - i) - at(prices, prices.length - i - 1);
|
||||
if (change > 0) {
|
||||
gains += change;
|
||||
} else {
|
||||
losses += Math.abs(change);
|
||||
}
|
||||
}
|
||||
|
||||
const avgGain = gains / period;
|
||||
const avgLoss = losses / period;
|
||||
|
||||
if (avgLoss === 0) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
const rs = avgGain / avgLoss;
|
||||
const rsi = 100 - 100 / (1 + rs);
|
||||
|
||||
return rsi;
|
||||
// v2 uses rolling simple averages and flat=100, NOT the new Wilder contract.
|
||||
return trailingSimpleRsi(prices, period, 100) ?? 50;
|
||||
}
|
||||
|
||||
protected override onStart(): void {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@stock-bot/calculations": "workspace:*",
|
||||
"@headlessui/react": "^1.7.17",
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"@hookform/resolvers": "^3.3.4",
|
||||
|
|
|
|||
|
|
@ -1,321 +1,80 @@
|
|||
import {
|
||||
atr,
|
||||
bollingerBands,
|
||||
ema,
|
||||
macd,
|
||||
rsi,
|
||||
sma,
|
||||
stochastic,
|
||||
} from '@stock-bot/calculations/indicators';
|
||||
import { calculateVWAP as vwap } from '@stock-bot/calculations/market-data';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import type { CandlestickData, LineData } from '../types';
|
||||
|
||||
// Simple Moving Average
|
||||
/** Corrected chart math is a new display contract, not a persisted strategy migration. */
|
||||
export const CHART_INDICATOR_CONTRACT = 'chart-indicators/v2';
|
||||
|
||||
function lines(
|
||||
data: readonly CandlestickData[],
|
||||
values: readonly number[],
|
||||
startIndex: number
|
||||
): LineData[] {
|
||||
return values.map((value, i) => ({
|
||||
time: at(data, startIndex + i).time,
|
||||
value: Number(value.toFixed(2)),
|
||||
}));
|
||||
}
|
||||
const closes = (data: readonly CandlestickData[]): number[] => Array.from(data, bar => bar.close);
|
||||
|
||||
export function calculateSMA(data: CandlestickData[], period: number): LineData[] {
|
||||
const result: LineData[] = [];
|
||||
|
||||
for (let i = period - 1; i < data.length; i++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < period; j++) {
|
||||
const item = data[i - j];
|
||||
if (item) {
|
||||
sum += item.close;
|
||||
}
|
||||
}
|
||||
const current = data[i];
|
||||
if (current) {
|
||||
result.push({
|
||||
time: current.time,
|
||||
value: parseFloat((sum / period).toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
return lines(data, sma(closes(data), period), period - 1);
|
||||
}
|
||||
|
||||
// Exponential Moving Average
|
||||
export function calculateEMA(data: CandlestickData[], period: number): LineData[] {
|
||||
const result: LineData[] = [];
|
||||
const multiplier = 2 / (period + 1);
|
||||
|
||||
// Start with SMA for the first period
|
||||
let sum = 0;
|
||||
for (let i = 0; i < period; i++) {
|
||||
const item = data[i];
|
||||
if (item) {
|
||||
sum += item.close;
|
||||
}
|
||||
}
|
||||
let ema = sum / period;
|
||||
|
||||
const firstItem = data[period - 1];
|
||||
if (firstItem) {
|
||||
result.push({
|
||||
time: firstItem.time,
|
||||
value: parseFloat(ema.toFixed(2)),
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate EMA for the rest
|
||||
for (let i = period; i < data.length; i++) {
|
||||
const current = data[i];
|
||||
if (current) {
|
||||
ema = (current.close - ema) * multiplier + ema;
|
||||
result.push({
|
||||
time: current.time,
|
||||
value: parseFloat(ema.toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
const result = ema(closes(data), period, { seed: 'sma' });
|
||||
return lines(data, result.values, result.startIndex);
|
||||
}
|
||||
|
||||
// Bollinger Bands
|
||||
export function calculateBollingerBands(
|
||||
data: CandlestickData[],
|
||||
period: number = 20,
|
||||
stdDev: number = 2
|
||||
) {
|
||||
const sma = calculateSMA(data, period);
|
||||
const upper: LineData[] = [];
|
||||
const lower: LineData[] = [];
|
||||
|
||||
for (let i = period - 1; i < data.length; i++) {
|
||||
let sumSquaredDiff = 0;
|
||||
const smaItem = sma[i - (period - 1)];
|
||||
if (!smaItem) {
|
||||
continue;
|
||||
}
|
||||
const smaValue = smaItem.value;
|
||||
|
||||
for (let j = 0; j < period; j++) {
|
||||
const item = data[i - j];
|
||||
if (item) {
|
||||
const diff = item.close - smaValue;
|
||||
sumSquaredDiff += diff * diff;
|
||||
}
|
||||
}
|
||||
|
||||
const standardDeviation = Math.sqrt(sumSquaredDiff / period);
|
||||
const upperBand = smaValue + standardDeviation * stdDev;
|
||||
const lowerBand = smaValue - standardDeviation * stdDev;
|
||||
|
||||
const current = data[i];
|
||||
if (current) {
|
||||
upper.push({
|
||||
time: current.time,
|
||||
value: parseFloat(upperBand.toFixed(2)),
|
||||
});
|
||||
|
||||
lower.push({
|
||||
time: current.time,
|
||||
value: parseFloat(lowerBand.toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { upper, middle: sma, lower };
|
||||
export function calculateBollingerBands(data: CandlestickData[], period = 20, stdDev = 2) {
|
||||
const result = bollingerBands(closes(data), period, stdDev);
|
||||
return {
|
||||
middle: lines(data, result.middle, result.startIndex),
|
||||
upper: lines(data, result.upper, result.startIndex),
|
||||
lower: lines(data, result.lower, result.startIndex),
|
||||
};
|
||||
}
|
||||
|
||||
// Relative Strength Index (RSI)
|
||||
export function calculateRSI(data: CandlestickData[], period: number = 14): LineData[] {
|
||||
const result: LineData[] = [];
|
||||
|
||||
if (data.length < period + 1) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Calculate initial average gain/loss
|
||||
let avgGain = 0;
|
||||
let avgLoss = 0;
|
||||
|
||||
for (let i = 1; i <= period; i++) {
|
||||
const current = data[i];
|
||||
const prev = data[i - 1];
|
||||
if (current && prev) {
|
||||
const change = current.close - prev.close;
|
||||
if (change > 0) {
|
||||
avgGain += change;
|
||||
} else {
|
||||
avgLoss += Math.abs(change);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
avgGain /= period;
|
||||
avgLoss /= period;
|
||||
|
||||
// Calculate RSI for each period
|
||||
for (let i = period; i < data.length; i++) {
|
||||
const current = data[i];
|
||||
const prev = data[i - 1];
|
||||
if (!current || !prev) {
|
||||
continue;
|
||||
}
|
||||
const change = current.close - prev.close;
|
||||
const gain = change > 0 ? change : 0;
|
||||
const loss = change < 0 ? Math.abs(change) : 0;
|
||||
|
||||
avgGain = (avgGain * (period - 1) + gain) / period;
|
||||
avgLoss = (avgLoss * (period - 1) + loss) / period;
|
||||
|
||||
const rs = avgLoss === 0 ? 100 : avgGain / avgLoss;
|
||||
const rsi = 100 - 100 / (1 + rs);
|
||||
|
||||
result.push({
|
||||
time: current.time,
|
||||
value: parseFloat(rsi.toFixed(2)),
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
export function calculateRSI(data: CandlestickData[], period = 14): LineData[] {
|
||||
const result = rsi(closes(data), period, { flatValue: 50 });
|
||||
return lines(data, result.values, result.startIndex);
|
||||
}
|
||||
export function calculateATR(data: CandlestickData[], period = 14): LineData[] {
|
||||
const result = atr(data, period, { firstRange: 'previous-close' });
|
||||
return lines(data, result.values, result.startIndex);
|
||||
}
|
||||
|
||||
// MACD (Moving Average Convergence Divergence)
|
||||
export function calculateMACD(
|
||||
data: CandlestickData[],
|
||||
fastPeriod: number = 12,
|
||||
slowPeriod: number = 26,
|
||||
signalPeriod: number = 9
|
||||
fastPeriod = 12,
|
||||
slowPeriod = 26,
|
||||
signalPeriod = 9
|
||||
) {
|
||||
const emaFast = calculateEMA(data, fastPeriod);
|
||||
const emaSlow = calculateEMA(data, slowPeriod);
|
||||
|
||||
const macdLine: LineData[] = [];
|
||||
const macdData: number[] = [];
|
||||
|
||||
// Calculate MACD line
|
||||
for (let i = 0; i < Math.min(emaFast.length, emaSlow.length); i++) {
|
||||
const fastIdx = emaFast.findIndex(d => d.time === at(emaSlow, i).time);
|
||||
if (fastIdx !== -1) {
|
||||
const macdValue = at(emaFast, fastIdx).value - at(emaSlow, i).value;
|
||||
macdLine.push({
|
||||
time: at(emaSlow, i).time,
|
||||
value: parseFloat(macdValue.toFixed(2)),
|
||||
});
|
||||
macdData.push(macdValue);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate signal line (EMA of MACD)
|
||||
const signalLine: LineData[] = [];
|
||||
if (macdData.length >= signalPeriod) {
|
||||
const multiplier = 2 / (signalPeriod + 1);
|
||||
let ema = macdData.slice(0, signalPeriod).reduce((a, b) => a + b, 0) / signalPeriod;
|
||||
|
||||
const firstMacd = macdLine[signalPeriod - 1];
|
||||
if (firstMacd) {
|
||||
signalLine.push({
|
||||
time: firstMacd.time,
|
||||
value: parseFloat(ema.toFixed(2)),
|
||||
});
|
||||
}
|
||||
|
||||
for (let i = signalPeriod; i < macdData.length; i++) {
|
||||
ema = (at(macdData, i) - ema) * multiplier + ema;
|
||||
const macdItem = macdLine[i];
|
||||
if (macdItem) {
|
||||
signalLine.push({
|
||||
time: macdItem.time,
|
||||
value: parseFloat(ema.toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate histogram
|
||||
const histogram: LineData[] = [];
|
||||
for (let i = 0; i < signalLine.length; i++) {
|
||||
const macdIdx = macdLine.findIndex(d => d.time === at(signalLine, i).time);
|
||||
if (macdIdx !== -1) {
|
||||
histogram.push({
|
||||
time: at(signalLine, i).time,
|
||||
value: parseFloat((at(macdLine, macdIdx).value - at(signalLine, i).value).toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { macdLine, signalLine, histogram };
|
||||
const result = macd(closes(data), fastPeriod, slowPeriod, signalPeriod, { seed: 'sma' });
|
||||
return {
|
||||
macdLine: lines(data, result.macd.values, result.macd.startIndex),
|
||||
signalLine: lines(data, result.signal.values, result.signal.startIndex),
|
||||
histogram: lines(data, result.histogram.values, result.histogram.startIndex),
|
||||
};
|
||||
}
|
||||
|
||||
// Volume Weighted Average Price (VWAP)
|
||||
export function calculateVWAP(data: CandlestickData[]): LineData[] {
|
||||
const result: LineData[] = [];
|
||||
let cumulativeTPV = 0; // Cumulative Typical Price × Volume
|
||||
let cumulativeVolume = 0;
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const current = data[i];
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
const typicalPrice = (current.high + current.low + current.close) / 3;
|
||||
const volume = current.volume || 0;
|
||||
|
||||
cumulativeTPV += typicalPrice * volume;
|
||||
cumulativeVolume += volume;
|
||||
|
||||
if (cumulativeVolume > 0) {
|
||||
result.push({
|
||||
time: current.time,
|
||||
value: parseFloat((cumulativeTPV / cumulativeVolume).toFixed(2)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
const values = vwap(data.map(bar => ({ ...bar, volume: bar.volume ?? 0 })));
|
||||
return values.flatMap((value, i) => (value === null ? [] : lines(data, [value], i)));
|
||||
}
|
||||
|
||||
// Stochastic Oscillator
|
||||
export function calculateStochastic(
|
||||
data: CandlestickData[],
|
||||
period: number = 14,
|
||||
smoothK: number = 3,
|
||||
smoothD: number = 3
|
||||
period = 14,
|
||||
smoothK = 3,
|
||||
smoothD = 3
|
||||
) {
|
||||
const kValues: LineData[] = [];
|
||||
|
||||
// Calculate %K
|
||||
for (let i = period - 1; i < data.length; i++) {
|
||||
const current = data[i];
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
let lowestLow = current.low;
|
||||
let highestHigh = current.high;
|
||||
|
||||
for (let j = 1; j < period; j++) {
|
||||
const prev = data[i - j];
|
||||
if (!prev) {
|
||||
continue;
|
||||
}
|
||||
lowestLow = Math.min(lowestLow, prev.low);
|
||||
highestHigh = Math.max(highestHigh, prev.high);
|
||||
}
|
||||
|
||||
const k = ((current.close - lowestLow) / (highestHigh - lowestLow)) * 100;
|
||||
kValues.push({
|
||||
time: current.time,
|
||||
value: parseFloat(k.toFixed(2)),
|
||||
});
|
||||
}
|
||||
|
||||
// Smooth %K if needed
|
||||
const smoothedK = smoothK > 1 ? calculateSMAFromLineData(kValues, smoothK) : kValues;
|
||||
|
||||
// Calculate %D (SMA of %K)
|
||||
const smoothedD = calculateSMAFromLineData(smoothedK, smoothD);
|
||||
|
||||
return { k: smoothedK, d: smoothedD };
|
||||
}
|
||||
|
||||
// Helper function to calculate SMA from LineData
|
||||
function calculateSMAFromLineData(data: LineData[], period: number): LineData[] {
|
||||
const result: LineData[] = [];
|
||||
|
||||
for (let i = period - 1; i < data.length; i++) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < period; j++) {
|
||||
sum += at(data, i - j).value;
|
||||
}
|
||||
result.push({
|
||||
time: at(data, i).time,
|
||||
value: parseFloat((sum / period).toFixed(2)),
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
const result = stochastic(data, period, smoothK, smoothD);
|
||||
return {
|
||||
k: lines(data, result.k.values, result.k.startIndex),
|
||||
d: lines(data, result.d.values, result.d.startIndex),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue