Centralize strategy contracts and share indicator calculations

This commit is contained in:
Boki 2026-10-21 15:50:39 -04:00
parent 366d39001b
commit 4207bf2c1c
25 changed files with 1323 additions and 477 deletions

View file

@ -1,4 +1,6 @@
use crate::backtest::{BacktestConfig, BacktestEngine as RustBacktestEngine, Signal, Strategy};
use super::strategy_parameters as parameters;
use crate::backtest::{BacktestConfig, BacktestEngine as RustBacktestEngine};
use crate::strategies::sma_crossover::SimpleSMAStrategy;
use crate::{MarketUpdate, TradingMode};
use chrono::{DateTime, Utc};
use napi::bindgen_prelude::*;
@ -78,97 +80,110 @@ impl BacktestEngine {
id: String,
parameters: napi::JsObject,
) -> Result<()> {
if let Some(engine) = self.inner.lock().as_mut() {
match strategy_type.as_str() {
"sma_crossover" => {
let fast_period: usize = parameters
.get_named_property::<f64>("fastPeriod")
.unwrap_or(5.0) as usize;
let slow_period: usize = parameters
.get_named_property::<f64>("slowPeriod")
.unwrap_or(15.0) as usize;
if fast_period == 0 || fast_period >= slow_period {
return Err(Error::from_reason(
"SMA periods must satisfy 0 < fastPeriod < slowPeriod",
));
}
engine.add_strategy(Box::new(SimpleSMAStrategy::new(
name.clone(),
id,
fast_period,
slow_period,
)));
let mut guard = self.inner.lock();
let engine = guard
.as_mut()
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
match strategy_type.as_str() {
"sma_crossover" => {
parameters::keys(&parameters, &["fastPeriod", "slowPeriod", "quantity"])?;
let error = || {
Error::from_reason("SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000 (finite integers)")
};
let fast =
parameters::period(&parameters, "fastPeriod", 5.0, 1.0).map_err(|_| error())?;
let slow = parameters::period(&parameters, "slowPeriod", 15.0, 2.0)
.map_err(|_| error())?;
if fast >= slow {
return Err(error());
}
"mean_reversion" => {
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.unwrap_or(20.0) as usize;
let entry_threshold: f64 = parameters
.get_named_property::<f64>("entryThreshold")
.unwrap_or(2.0);
let position_size: f64 = parameters
.get_named_property::<f64>("positionSize")
.unwrap_or(100.0);
engine.add_strategy(Box::new(
crate::strategies::MeanReversionFixedStrategy::new(
name.clone(),
id,
lookback_period,
entry_threshold,
position_size,
),
let quantity =
parameters::number(&parameters, "quantity", 100.0, 1e-8, 1e9, false)?;
engine.add_strategy(Box::new(
SimpleSMAStrategy::new(name, id, fast, slow, quantity)
.map_err(Error::from_reason)?,
));
}
"mean_reversion" => {
parameters::keys(
&parameters,
&["lookbackPeriod", "entryThreshold", "positionSize"],
)?;
let lookback = parameters::period(&parameters, "lookbackPeriod", 20.0, 2.0)?;
let threshold = parameters::number(
&parameters,
"entryThreshold",
2.0,
f64::from_bits(1),
f64::MAX,
false,
)?;
let size =
parameters::number(&parameters, "positionSize", 100.0, 1e-8, 1e9, false)?;
engine.add_strategy(Box::new(
crate::strategies::MeanReversionFixedStrategy::new(
name, id, lookback, threshold, size,
),
));
}
"momentum" => {
parameters::keys(
&parameters,
&["lookbackPeriod", "momentumThreshold", "positionSize"],
)?;
let lookback = parameters::period(&parameters, "lookbackPeriod", 14.0, 1.0)?;
let threshold = parameters::number(
&parameters,
"momentumThreshold",
5.0,
f64::from_bits(1),
f64::MAX,
false,
)?;
let size =
parameters::number(&parameters, "positionSize", 100.0, 1e-8, 1e9, false)?;
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
name, id, lookback, threshold, size,
)));
}
"pairs_trading" => {
parameters::keys(
&parameters,
&[
"pairA",
"pairB",
"lookbackPeriod",
"entryThreshold",
"positionSize",
],
)?;
let pair_a: String = parameters.get_named_property("pairA")?;
let pair_b: String = parameters.get_named_property("pairB")?;
if pair_a.trim().is_empty() || pair_b.trim().is_empty() || pair_a == pair_b {
return Err(Error::from_reason(
"Pairs must use distinct nonempty instruments",
));
}
"momentum" => {
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.unwrap_or(14.0) as usize;
let momentum_threshold: f64 = parameters
.get_named_property::<f64>("momentumThreshold")
.unwrap_or(5.0);
let position_size: f64 = parameters
.get_named_property::<f64>("positionSize")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::MomentumStrategy::new(
name.clone(),
id,
lookback_period,
momentum_threshold,
position_size,
)));
}
"pairs_trading" => {
let pair_a: String = parameters.get_named_property::<String>("pairA")?;
let pair_b: String = parameters.get_named_property::<String>("pairB")?;
let lookback_period: usize = parameters
.get_named_property::<f64>("lookbackPeriod")
.unwrap_or(20.0) as usize;
let entry_threshold: f64 = parameters
.get_named_property::<f64>("entryThreshold")
.unwrap_or(2.0);
let position_size: f64 = parameters
.get_named_property::<f64>("positionSize")
.unwrap_or(100.0);
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
name.clone(),
id,
pair_a,
pair_b,
lookback_period,
entry_threshold,
position_size,
)));
}
_ => {
return Err(Error::from_reason(format!(
"Unknown strategy type: {}",
strategy_type
)));
}
let lookback = parameters::period(&parameters, "lookbackPeriod", 20.0, 2.0)?;
let threshold = parameters::number(
&parameters,
"entryThreshold",
2.0,
f64::from_bits(1),
f64::MAX,
false,
)?;
let size =
parameters::number(&parameters, "positionSize", 100.0, 1e-8, 1e9, false)?;
engine.add_strategy(Box::new(crate::strategies::PairsTradingStrategy::new(
name, id, pair_a, pair_b, lookback, threshold, size,
)));
}
_ => {
return Err(Error::from_reason(format!(
"Unknown strategy type: {}",
strategy_type
)))
}
}
@ -277,154 +292,3 @@ fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
data,
})
}
// Simple SMA Strategy for testing
struct SimpleSMAStrategy {
name: String,
id: String,
fast_period: usize,
slow_period: usize,
price_history: std::collections::HashMap<String, Vec<f64>>,
positions: std::collections::HashMap<String, f64>,
}
impl SimpleSMAStrategy {
fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self {
Self {
name,
id,
fast_period,
slow_period,
price_history: std::collections::HashMap::new(),
positions: std::collections::HashMap::new(),
}
}
}
impl Strategy for SimpleSMAStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
let mut signals = Vec::new();
// Check if it's bar data
if let crate::MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol;
let price = bar.close;
// Update price history
let history = self
.price_history
.entry(symbol.clone())
.or_insert_with(Vec::new);
history.push(price);
// Keep only necessary history (need one extra for previous SMA calculation)
if history.len() > self.slow_period + 1 {
history.remove(0);
}
// Need enough data
if history.len() >= self.slow_period {
// Calculate SMAs
let fast_sma = history[history.len() - self.fast_period..]
.iter()
.sum::<f64>()
/ self.fast_period as f64;
let slow_sma = history[history.len() - self.slow_period..]
.iter()
.sum::<f64>()
/ self.slow_period as f64;
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period {
let prev_history = &history[..history.len() - 1];
let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..]
.iter()
.sum::<f64>()
/ self.fast_period as f64;
let prev_slow_sma =
prev_history.iter().sum::<f64>() / prev_history.len() as f64;
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
// Golden cross - buy signal
if prev_fast_sma <= prev_slow_sma
&& fast_sma > slow_sma
&& current_position <= 0.0
{
signals.push(Signal {
symbol: symbol.clone(),
signal_type: crate::backtest::SignalType::Buy,
strength: 1.0,
quantity: Some(100.0), // Fixed quantity for testing
reason: Some("Golden cross".to_string()),
metadata: None,
});
}
// Death cross - sell signal
else if prev_fast_sma >= prev_slow_sma
&& fast_sma < slow_sma
&& current_position >= 0.0
{
signals.push(Signal {
symbol: symbol.clone(),
signal_type: crate::backtest::SignalType::Sell,
strength: 1.0,
quantity: Some(100.0), // Fixed quantity for testing
reason: Some("Death cross".to_string()),
metadata: None,
});
}
}
}
}
signals
}
fn on_fill(&mut self, symbol: &str, quantity: f64, _price: f64, side: &str) {
let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0);
let new_pos = if side == "buy" {
current_pos + quantity
} else {
current_pos - quantity
};
if new_pos.abs() < 0.0001 {
self.positions.remove(symbol);
} else {
self.positions.insert(symbol.to_string(), new_pos);
}
}
fn get_name(&self) -> &str {
&self.name
}
fn get_parameters(&self) -> serde_json::Value {
serde_json::json!({
"fast_period": self.fast_period,
"slow_period": self.slow_period
})
}
}
// Error handling for threadsafe functions
struct ErrorStrategy;
impl From<napi::Error> for ErrorStrategy {
fn from(_e: napi::Error) -> Self {
ErrorStrategy
}
}
// Helper to convert NAPI parameters to JSON
fn napi_params_to_json(obj: napi::JsObject) -> Result<serde_json::Value> {
// For now, just extract the common parameters
let fast_period = obj.get_named_property::<f64>("fastPeriod").unwrap_or(5.0);
let slow_period = obj.get_named_property::<f64>("slowPeriod").unwrap_or(15.0);
Ok(serde_json::json!({
"fastPeriod": fast_period,
"slowPeriod": slow_period
}))
}

View file

@ -1,6 +1,7 @@
mod backtest;
mod indicators;
mod risk;
mod strategy_parameters;
pub use backtest::BacktestEngine;
pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators};

View file

@ -0,0 +1,54 @@
use napi::{Error, JsObject, JsUnknown, Result, ValueType};
/// Native bindings are a trust boundary too: never truncate fractional periods or default bad types.
pub fn number(
object: &JsObject,
key: &str,
default: f64,
min: f64,
max: f64,
integer: bool,
) -> Result<f64> {
if !object.has_named_property(key)? {
return Ok(default);
}
let value: JsUnknown = object.get_named_property(key)?;
if value.get_type()? == ValueType::Undefined {
return Ok(default);
}
let invalid = || {
Error::from_reason(format!(
"{} must be a finite {}number in [{}, {}]",
key,
if integer { "integer " } else { "" },
min,
max
))
};
let value = object
.get_named_property::<f64>(key)
.map_err(|_| invalid())?;
if !value.is_finite() || value < min || value > max || (integer && value.fract() != 0.0) {
return Err(invalid());
}
Ok(value)
}
pub fn period(object: &JsObject, key: &str, default: f64, min: f64) -> Result<usize> {
Ok(number(object, key, default, min, 10000.0, true)? as usize)
}
pub fn keys(object: &JsObject, allowed: &[&str]) -> Result<()> {
let names = object.get_property_names()?;
for index in 0..names.get_array_length()? {
let raw = names.get_element::<napi::JsString>(index)?.into_utf8()?;
let name = raw.as_str()?;
if !allowed.contains(&name) {
return Err(Error::from_reason(format!(
"Unknown strategy parameter: {}",
name
)));
}
}
Ok(())
}

View file

@ -1,9 +1,10 @@
pub mod mean_reversion;
pub mod mean_reversion_fixed;
pub mod momentum;
pub mod pairs_trading;
pub use mean_reversion::MeanReversionStrategy;
pub use mean_reversion_fixed::MeanReversionFixedStrategy;
pub use momentum::MomentumStrategy;
pub use pairs_trading::PairsTradingStrategy;
pub mod mean_reversion;
pub mod mean_reversion_fixed;
pub mod momentum;
pub mod pairs_trading;
pub mod sma_crossover;
pub use mean_reversion::MeanReversionStrategy;
pub use mean_reversion_fixed::MeanReversionFixedStrategy;
pub use momentum::MomentumStrategy;
pub use pairs_trading::PairsTradingStrategy;

View file

@ -0,0 +1,213 @@
use crate::{
backtest::{Signal, Strategy},
MarketUpdate,
};
/// Native fixed-share crossover strategy; fills, not emitted signals, advance position state.
pub struct SimpleSMAStrategy {
name: String,
id: String,
fast_period: usize,
slow_period: usize,
quantity: f64,
price_history: std::collections::HashMap<String, Vec<f64>>,
positions: std::collections::HashMap<String, f64>,
}
impl SimpleSMAStrategy {
pub fn new(
name: String,
id: String,
fast_period: usize,
slow_period: usize,
quantity: f64,
) -> Result<Self, &'static str> {
if fast_period == 0 || fast_period >= slow_period || slow_period > 10000 {
return Err("SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000");
}
if !quantity.is_finite() || !(1e-8..=1e9).contains(&quantity) {
return Err("quantity must be finite and within [1e-8, 1e9]");
}
Ok(Self {
name,
id,
fast_period,
slow_period,
quantity,
price_history: std::collections::HashMap::new(),
positions: std::collections::HashMap::new(),
})
}
}
impl Strategy for SimpleSMAStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
let mut signals = Vec::new();
// Check if it's bar data
if let crate::MarketDataType::Bar(bar) = &data.data {
let symbol = &data.symbol;
let price = bar.close;
// Update price history
let history = self
.price_history
.entry(symbol.clone())
.or_insert_with(Vec::new);
history.push(price);
// Keep only necessary history (need one extra for previous SMA calculation)
if history.len() > self.slow_period + 1 {
history.remove(0);
}
// Need enough data
if history.len() >= self.slow_period {
// Calculate SMAs
let fast_sma = history[history.len() - self.fast_period..]
.iter()
.sum::<f64>()
/ self.fast_period as f64;
let slow_sma = history[history.len() - self.slow_period..]
.iter()
.sum::<f64>()
/ self.slow_period as f64;
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period {
let prev_history = &history[..history.len() - 1];
let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..]
.iter()
.sum::<f64>()
/ self.fast_period as f64;
let prev_slow_sma =
prev_history.iter().sum::<f64>() / prev_history.len() as f64;
let current_position = self.positions.get(symbol).copied().unwrap_or(0.0);
// Golden cross - buy signal
if prev_fast_sma <= prev_slow_sma
&& fast_sma > slow_sma
&& current_position <= 0.0
{
signals.push(Signal {
symbol: symbol.clone(),
signal_type: crate::backtest::SignalType::Buy,
strength: 1.0,
quantity: Some(self.quantity),
reason: Some("Golden cross".to_string()),
metadata: None,
});
}
// Death cross - sell signal
else if prev_fast_sma >= prev_slow_sma
&& fast_sma < slow_sma
&& current_position >= 0.0
{
signals.push(Signal {
symbol: symbol.clone(),
signal_type: crate::backtest::SignalType::Sell,
strength: 1.0,
quantity: Some(self.quantity),
reason: Some("Death cross".to_string()),
metadata: None,
});
}
}
}
}
signals
}
fn on_fill(&mut self, symbol: &str, quantity: f64, _price: f64, side: &str) {
let current_pos = self.positions.get(symbol).copied().unwrap_or(0.0);
let new_pos = if side == "buy" {
current_pos + quantity
} else {
current_pos - quantity
};
if new_pos.abs() < 0.0001 {
self.positions.remove(symbol);
} else {
self.positions.insert(symbol.to_string(), new_pos);
}
}
fn get_name(&self) -> &str {
&self.name
}
fn get_parameters(&self) -> serde_json::Value {
serde_json::json!({
"id": self.id,
"fast_period": self.fast_period,
"slow_period": self.slow_period,
"quantity": self.quantity
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Bar, MarketDataType};
use chrono::TimeZone;
fn bar(symbol: &str, index: i64, close: f64) -> MarketUpdate {
MarketUpdate {
symbol: symbol.into(),
timestamp: chrono::Utc.timestamp_millis_opt(index * 60000).unwrap(),
data: MarketDataType::Bar(Bar {
open: close,
high: close,
low: close,
close,
volume: 1000.0,
vwap: Some(close),
}),
}
}
#[test]
fn configured_periods_require_both_windows_and_emit_configured_quantity() {
let mut strategy = SimpleSMAStrategy::new("sma".into(), "id".into(), 2, 3, 7.0).unwrap();
for (index, price) in [3.0, 2.0, 1.0].iter().enumerate() {
assert!(strategy
.on_market_data(&bar("A.US", index as i64, *price))
.is_empty());
}
let signals = strategy.on_market_data(&bar("A.US", 3, 4.0));
assert_eq!(signals.len(), 1);
assert!(matches!(
signals[0].signal_type,
crate::backtest::SignalType::Buy
));
assert_eq!(signals[0].quantity, Some(7.0));
assert!(strategy.positions.is_empty());
strategy.on_fill("A.US", 2.0, 4.0, "buy");
assert_eq!(strategy.positions["A.US"], 2.0);
}
#[test]
fn symbols_have_independent_bounded_windows() {
let mut strategy = SimpleSMAStrategy::new("sma".into(), "id".into(), 2, 3, 7.0).unwrap();
for index in 0..100 {
strategy.on_market_data(&bar("A.US", index, 100.0));
}
assert_eq!(strategy.price_history["A.US"].len(), 4);
assert!(strategy.on_market_data(&bar("B.US", 100, 20.0)).is_empty());
assert_eq!(strategy.price_history["B.US"].len(), 1);
}
#[test]
fn invalid_domain_parameters_fail_without_constructing_a_strategy() {
for (fast, slow) in [(0, 3), (3, 3), (4, 3), (1, 10001)] {
assert!(SimpleSMAStrategy::new("sma".into(), "id".into(), fast, slow, 1.0).is_err());
}
for size in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e10] {
assert!(SimpleSMAStrategy::new("sma".into(), "id".into(), 2, 3, size).is_err());
}
}
}

View file

@ -12,6 +12,7 @@ import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
import { BacktestReport } from './BacktestReport';
import type { BacktestExecutionEngine } from './execution-engine';
import { closedTradesSchema } from './native-result';
import { backtestStrategies } from './strategy-plan';
import type { BacktestResult } from './typescript-result';
export type { BacktestResult } from './typescript-result';
@ -57,6 +58,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
playback: BacktestPlayback,
resolver?: DatasetResolver
): Promise<BacktestResult> {
const plan = backtestStrategies(config, 'typescript');
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
const dataset = await playback.read(() =>
resolveDataset(this.storageService, config, resolver)
@ -64,27 +66,14 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
playback.assertRunning();
const dataManager = new DataManager(this.storageService);
dataManager.inspectDataset(dataset);
const strategies = config.strategies?.map((strategy, index) => ({
id: [strategy.name, index].join('-'),
name: strategy.name,
enabled: strategy.enabled,
parameters: { ...strategy.config, initialCapital: config.initialCapital },
const strategies = plan.map(({ name, parameters, index }) => ({
id: name + '-' + index,
name,
enabled: true,
parameters,
symbols: config.symbols,
allocation: 1 / (config.strategies?.length ?? 1),
})) ?? [
{
id: config.strategy + '-0',
name: config.strategy,
enabled: true,
parameters: {
symbols: config.symbols,
initialCapital: config.initialCapital,
...config.config,
},
symbols: config.symbols,
allocation: 1,
},
];
allocation: 1 / plan.length,
}));
await this.strategyManager.initializeStrategies(strategies);
playback.assertRunning();
const trading = defined(

View file

@ -1,36 +1,12 @@
import type { BacktestConfig } from '../types';
import { backtestStrategies } from './strategy-plan';
/** Resolve before fetching data, and validate again in the isolated worker. */
/** Resolve and validate before fetching data, and validate again in the isolated worker. */
export function resolveNativeStrategies(config: BacktestConfig) {
const strategies = config.strategies
? config.strategies
.filter(strategy => strategy.enabled)
.map(strategy => ({
name: strategy.name,
parameters: { ...config.config, ...strategy.config },
}))
: [{ name: config.strategy, parameters: config.config ?? {} }];
if (!strategies.length) {
throw new Error('No enabled backtest strategies');
}
const aliases: Record<string, string> = {
sma: 'sma_crossover',
smacrossover: 'sma_crossover',
simplemovingaveragecrossover: 'sma_crossover',
movingaverage: 'sma_crossover',
meanreversion: 'mean_reversion',
momentum: 'momentum',
pairs: 'pairs_trading',
pairstrading: 'pairs_trading',
};
return strategies.map(({ name, parameters }, index) => {
if (parameters.useTypeScriptImplementation) {
throw new Error('The native engine does not execute TypeScript strategy callbacks');
return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => {
if (!kind) {
throw new Error('Unknown native strategy: ' + name);
}
const strategy = aliases[name.toLowerCase().replace(/[-_ ]/g, '')];
if (!strategy) {
throw new Error(`Unknown native strategy: ${name}`);
}
return { strategy, name, id: `backtest-strategy-${index}`, parameters };
return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters };
});
}

View file

@ -0,0 +1,48 @@
import {
nativeParameters,
strategyParameters,
typescriptMeanReversionParameters,
typescriptSmaParameters,
} from '../contracts/strategies';
import { builtinStrategy } from '../contracts/strategy-names';
import type { BacktestConfig } from '../types';
/** One precedence rule for both backends: shared defaults, then per-strategy overrides. */
export function backtestStrategies(config: BacktestConfig, backend: 'native' | 'typescript') {
const entries = config.strategies ?? [{ name: config.strategy, enabled: true, config: {} }];
if (!entries.some(entry => entry.enabled)) {
throw new Error('No enabled backtest strategies');
}
return entries
.filter(entry => entry.enabled)
.map((entry, index) => {
const kind = builtinStrategy(entry.name);
const merged = { ...config.config, ...entry.config };
// Custom TypeScript factories own their parameter contract; do not strip their extension fields.
const parameters = kind ? strategyParameters(merged, backend) : structuredClone(merged);
if (backend === 'native') {
if (!kind) {
throw new Error(`Unknown native strategy: ${entry.name}`);
}
const parsed = nativeParameters(kind, parameters);
if (
kind === 'pairs_trading' &&
(typeof parsed.pairA !== 'string' ||
typeof parsed.pairB !== 'string' ||
!config.symbols.includes(parsed.pairA) ||
!config.symbols.includes(parsed.pairB))
) {
throw new Error('Both pair instruments must be included in backtest symbols');
}
return { name: entry.name, kind, index, parameters: parsed };
}
const context = { ...parameters, initialCapital: config.initialCapital };
const parsed =
kind === 'sma_crossover'
? typescriptSmaParameters.parse(context)
: kind === 'mean_reversion'
? typescriptMeanReversionParameters.parse(context)
: context;
return { name: entry.name, kind, index, parameters: parsed };
});
}

View file

@ -0,0 +1,131 @@
import { z } from 'zod';
import { instrumentIdSchema } from './historical';
import type { BuiltinStrategy } from './strategy-names';
export const maxStrategyPeriod = 10000;
const period = z.number().finite().int().min(1).max(maxStrategyPeriod);
const positive = z.number().finite().positive();
const quantity = positive.min(1e-8).max(1e9);
const context = {
initialCapital: positive.optional(),
symbols: z.array(z.string()).optional(),
};
const smaPeriods = { fastPeriod: period.default(5), slowPeriod: period.min(2).default(15) };
const validSma = (value: { fastPeriod: number; slowPeriod: number }) =>
value.fastPeriod < value.slowPeriod;
const smaMessage = 'SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000';
export const typescriptSmaParameters = z
.object({
...context,
...smaPeriods,
positionFraction: positive.max(1).default(0.1),
minHoldingBars: z.number().int().min(0).max(maxStrategyPeriod).default(3),
quantity: quantity.optional(),
})
.strict()
.refine(validSma, smaMessage);
export const nativeSmaParameters = z
.object({ ...smaPeriods, quantity: quantity.default(100) })
.strict()
.refine(validSma, smaMessage);
export type SmaParameters = z.infer<typeof typescriptSmaParameters>;
export const typescriptMeanReversionParameters = z
.object({
...context,
lookbackPeriod: period.min(2).default(20),
trendPeriod: period.optional(),
entryThreshold: positive.default(2),
exitZScore: z.number().finite().min(0).default(0.5),
rsiPeriod: period.default(14),
rsiOversold: z.number().finite().min(0).max(100).default(30),
rsiOverbought: z.number().finite().min(0).max(100).default(70),
minNotionalVolume: z.number().finite().min(0).default(1000000),
quantity: quantity.optional(),
})
.strict()
.refine(
value => value.exitZScore < value.entryThreshold,
'exitZScore must be below entryThreshold'
)
.refine(
value => value.rsiOversold < value.rsiOverbought,
'rsiOversold must be below rsiOverbought'
)
.refine(
value => value.trendPeriod === undefined || value.trendPeriod >= value.lookbackPeriod,
'trendPeriod must be at least lookbackPeriod'
)
.transform(value => ({
...value,
trendPeriod: value.trendPeriod ?? Math.max(50, value.lookbackPeriod),
}));
export type MeanReversionParameters = z.infer<typeof typescriptMeanReversionParameters>;
const nativeMean = {
lookbackPeriod: period.min(2).default(20),
entryThreshold: positive.default(2),
// Native mean/momentum/pairs retain their existing absolute-share positionSize contract.
positionSize: quantity.default(100),
};
export const nativeMeanReversionParameters = z.object(nativeMean).strict();
export const nativeMomentumParameters = z
.object({
lookbackPeriod: period.default(14),
momentumThreshold: positive.default(5),
positionSize: quantity.default(100),
})
.strict();
export const nativePairsParameters = z
.object({
...nativeMean,
pairA: instrumentIdSchema,
pairB: instrumentIdSchema,
})
.strict()
.refine(value => value.pairA !== value.pairB, 'Pairs must use distinct instruments');
/** These are run settings, not strategy parameters. Preserve the original request in the result. */
export function strategyParameters(
input: Record<string, unknown>,
backend: 'native' | 'typescript'
): Record<string, unknown> {
const {
commission: _commission,
slippage: _slippage,
dataPolicy: _dataPolicy,
datasetHash: _datasetHash,
riskLimits: _riskLimits,
fillModel: _fillModel,
initialCapital: _initialCapital,
symbols: _symbols,
...parameters
} = input;
if (parameters.useTypeScriptImplementation !== undefined) {
z.boolean().parse(parameters.useTypeScriptImplementation);
if (backend === 'native' && parameters.useTypeScriptImplementation) {
throw new Error('The native engine does not execute TypeScript strategy callbacks');
}
delete parameters.useTypeScriptImplementation;
}
return parameters;
}
export function nativeParameters(
kind: BuiltinStrategy,
input: Record<string, unknown>
): Record<string, unknown> {
switch (kind) {
case 'sma_crossover':
return nativeSmaParameters.parse(input);
case 'mean_reversion':
return nativeMeanReversionParameters.parse(input);
case 'momentum':
return nativeMomentumParameters.parse(input);
case 'pairs_trading':
return nativePairsParameters.parse(input);
default:
throw new Error(`Unsupported native strategy: ${kind}`);
}
}

View file

@ -0,0 +1,20 @@
export function normalizeStrategyName(name: string): string {
return name
.trim()
.toLowerCase()
.replace(/[\s_-]/g, '');
}
export const strategyAliases = {
sma_crossover: ['sma', 'smacrossover', 'simplemovingaveragecrossover', 'movingaverage'],
mean_reversion: ['meanreversion'],
momentum: ['momentum'],
pairs_trading: ['pairs', 'pairstrading'],
ml_enhanced: ['mlenhanced'],
} as const;
export type BuiltinStrategy = keyof typeof strategyAliases;
export function builtinStrategy(name: string): BuiltinStrategy | undefined {
const normalized = normalizeStrategyName(name);
return (Object.keys(strategyAliases) as BuiltinStrategy[]).find(kind =>
(strategyAliases[kind] as readonly string[]).includes(normalized)
);
}

View file

@ -0,0 +1,74 @@
import { at } from '@stock-bot/invariants';
/** Scalar trailing-window math. Missing warm-up is undefined, never a synthetic zero average. */
export function trailingMean(
values: readonly number[],
period: number,
offset = 0
): number | undefined {
if (!Number.isSafeInteger(period) || period < 1 || !Number.isSafeInteger(offset) || offset < 0) {
throw new Error('Indicator period must be positive and offset nonnegative integers');
}
const end = values.length - offset;
if (end < period) {
return undefined;
}
let sum = 0;
for (let i = end - period; i < end; i++) {
const value = values[i];
if (value === undefined || !Number.isFinite(value)) {
throw new Error('Indicator prices must be finite');
}
sum += value;
}
const mean = sum / period;
if (!Number.isFinite(mean)) {
throw new Error('Indicator mean overflow');
}
return mean;
}
export function trailingPopulationDeviation(
values: readonly number[],
period: number
): number | undefined {
const mean = trailingMean(values, period);
if (mean === undefined) {
return undefined;
}
let squared = 0;
for (let i = values.length - period; i < values.length; i++) {
squared += (at(values, i) - mean) ** 2;
}
const deviation = Math.sqrt(squared / period);
if (!Number.isFinite(deviation)) {
throw new Error('Indicator deviation overflow');
}
return deviation;
}
export function movingAverageCrossover(values: readonly number[], fast: number, slow: number) {
if (fast >= slow) {
throw new Error('fastPeriod must be below slowPeriod');
}
const fastMA = trailingMean(values, fast);
const slowMA = trailingMean(values, slow);
const prevFastMA = trailingMean(values, fast, 1);
const prevSlowMA = trailingMean(values, slow, 1);
if (
fastMA === undefined ||
slowMA === undefined ||
prevFastMA === undefined ||
prevSlowMA === undefined
) {
return undefined;
}
return {
fastMA,
slowMA,
prevFastMA,
prevSlowMA,
goldenCross: prevFastMA <= prevSlowMA && fastMA > slowMA,
deathCross: prevFastMA >= prevSlowMA && fastMA < slowMA,
};
}

View file

@ -70,7 +70,7 @@ export abstract class BaseStrategy extends EventEmitter {
protected executionService: ExecutionService
) {
super();
this.config = config;
this.config = structuredClone(config);
}
async initialize(): Promise<void> {
@ -192,7 +192,7 @@ export abstract class BaseStrategy extends EventEmitter {
}
getConfig(): Readonly<StrategyConfig> {
return this.config;
return structuredClone(this.config);
}
hasOrder(orderId: string): boolean {
@ -272,7 +272,7 @@ export abstract class BaseStrategy extends EventEmitter {
'Active strategy configuration is immutable; use an explicit new strategy ID'
);
}
this.config = { ...this.config, ...updates };
this.config = this.validateConfig(structuredClone({ ...this.config, ...updates }));
logger.info(`Updated config for strategy ${this.config.id}`);
// Strategies can override to handle specific config changes
@ -377,4 +377,8 @@ export abstract class BaseStrategy extends EventEmitter {
protected onStart(): void | Promise<void> {}
protected onStop(): void | Promise<void> {}
protected onConfigUpdate(_updates: Partial<StrategyConfig>): void {}
/** Validate before assignment, so a rejected inactive edit cannot poison the current definition. */
protected validateConfig(config: StrategyConfig): StrategyConfig {
return config;
}
}

View file

@ -1,3 +1,4 @@
import { normalizeStrategyName } from '../contracts/strategy-names';
import type { ModeManager } from '../core/ModeManager';
import type { ExecutionService } from '../services/ExecutionService';
import type { StrategyConfig } from '../types';
@ -17,7 +18,7 @@ export class StrategyRegistry {
private readonly factories = new Map<string, StrategyFactory>();
register(names: readonly string[], factory: StrategyFactory): this {
const keys = names.map(name => name.trim().toLowerCase());
const keys = names.map(normalizeStrategyName);
if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) {
throw new Error('Strategy aliases must be nonempty and distinct');
}
@ -33,7 +34,7 @@ export class StrategyRegistry {
}
async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise<BaseStrategy> {
const factory = this.factories.get(config.name.trim().toLowerCase());
const factory = this.factories.get(normalizeStrategyName(config.name));
if (!factory) {
throw new Error(`Unknown strategy: ${config.name}`);
}

View file

@ -1,22 +1,20 @@
import { strategyAliases } from '../contracts/strategy-names';
import { StrategyRegistry } from './StrategyRegistry';
/** Lazy factories avoid loading every strategy (and ML dependency) at startup. */
export function createBuiltinStrategyRegistry(): StrategyRegistry {
return new StrategyRegistry()
.register(['meanreversion', 'mean-reversion'], async (config, { modeManager, execution }) => {
.register(strategyAliases.mean_reversion, async (config, { modeManager, execution }) => {
const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy');
return new MeanReversionStrategy(config, modeManager, execution);
})
.register(
['smacrossover', 'sma-crossover', 'moving-average'],
async (config, { modeManager, execution }) => {
const { SimpleMovingAverageCrossover } = await import(
'./examples/SimpleMovingAverageCrossoverFixed'
);
return new SimpleMovingAverageCrossover(config, modeManager, execution);
}
)
.register(['mlenhanced', 'ml-enhanced'], async (config, { modeManager, execution }) => {
.register(strategyAliases.sma_crossover, async (config, { modeManager, execution }) => {
const { SimpleMovingAverageCrossover } = await import(
'./examples/SimpleMovingAverageCrossoverFixed'
);
return new SimpleMovingAverageCrossover(config, modeManager, execution);
})
.register(strategyAliases.ml_enhanced, async (config, { modeManager, execution }) => {
const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy');
return new MLEnhancedStrategy(config, modeManager, execution);
});

View file

@ -1,15 +1,15 @@
import { z } from 'zod';
export const priceHistoryState = z.array(
z.tuple([z.string(), z.array(z.number().finite().positive()).max(60)])
);
export const priceHistoryState = (capacity: number) =>
z.array(z.tuple([z.string(), z.array(z.number().finite().positive()).max(capacity)]));
export const barCounterState = z.array(z.tuple([z.string(), z.number().int().nonnegative()]));
export const crossoverCheckpointSchema = z
.object({
priceHistory: priceHistoryState,
barCount: barCounterState,
lastSignalBar: barCounterState,
totalSignals: z.number().int().nonnegative(),
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
})
.strict();
export const crossoverCheckpointSchema = (capacity: number) =>
z
.object({
priceHistory: priceHistoryState(capacity),
barCount: barCounterState,
lastSignalBar: barCounterState,
totalSignals: z.number().int().nonnegative(),
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
})
.strict();

View file

@ -1,17 +1,21 @@
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
import type { MeanReversionParameters } from '../../contracts/strategies';
import type { ModeManager } from '../../core/ModeManager';
import { trailingMean, trailingPopulationDeviation } from '../../indicators/window-statistics';
import type { ExecutionService } from '../../services/ExecutionService';
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';
import { BaseStrategy, type Signal } from '../BaseStrategy';
import { priceHistoryState } from '../checkpoint-schemas';
import { meanReversionConfig } from '../strategy-config';
const logger = getLogger('MeanReversionStrategy');
interface MeanReversionIndicators {
sma20: number;
sma50: number;
mean: number;
trendMean: number;
stdDev: number;
zScore: number;
rsi: number;
@ -21,7 +25,7 @@ export class MeanReversionStrategy extends BaseStrategy {
private priceHistory = new Map<string, number[]>();
private indicators = new Map<string, MeanReversionIndicators>();
override getCheckpointVersion() {
return 'mean-reversion/v1';
return 'mean-reversion/v2';
}
protected override captureIndicators() {
return { priceHistory: [...this.priceHistory], indicators: [...this.indicators] };
@ -30,11 +34,17 @@ export class MeanReversionStrategy extends BaseStrategy {
const finite = z.number().finite();
const state = z
.object({
priceHistory: priceHistoryState,
priceHistory: priceHistoryState(this.historyCapacity),
indicators: z.array(
z.tuple([
z.string(),
z.object({ sma20: finite, sma50: finite, stdDev: finite, zScore: finite, rsi: finite }),
z.object({
mean: finite,
trendMean: finite,
stdDev: finite,
zScore: finite,
rsi: finite,
}),
])
),
})
@ -44,13 +54,32 @@ export class MeanReversionStrategy extends BaseStrategy {
this.indicators = new Map(state.indicators);
}
// Strategy parameters
private readonly LOOKBACK_PERIOD = 20;
private readonly Z_SCORE_ENTRY = 2.0;
private readonly Z_SCORE_EXIT = 0.5;
private readonly RSI_OVERSOLD = 30;
private readonly RSI_OVERBOUGHT = 70;
private readonly MIN_VOLUME = 1000000; // $1M daily volume
private settings: MeanReversionParameters;
constructor(
config: StrategyConfig,
modeManager: ModeManager,
executionService: ExecutionService
) {
const validated = meanReversionConfig(config);
super(validated, modeManager, executionService);
this.settings = validated.parameters;
}
protected override validateConfig(config: StrategyConfig): StrategyConfig {
const validated = meanReversionConfig(config);
this.settings = validated.parameters;
return validated;
}
private get historyCapacity(): number {
return Math.max(
this.settings.lookbackPeriod * 3,
this.settings.trendPeriod,
this.settings.rsiPeriod + 1
);
}
protected override calculatePositionSize(signal: Signal): number {
return this.settings.quantity ?? super.calculatePositionSize(signal);
}
protected updateIndicators(data: MarketData): void {
if (data.type !== 'bar') {
@ -69,12 +98,12 @@ export class MeanReversionStrategy extends BaseStrategy {
history.push(price);
// Keep only needed history
if (history.length > this.LOOKBACK_PERIOD * 3) {
if (history.length > this.historyCapacity) {
history.shift();
}
// Calculate indicators if we have enough data
if (history.length >= this.LOOKBACK_PERIOD) {
if (history.length >= Math.max(this.settings.lookbackPeriod, this.settings.rsiPeriod + 1)) {
const indicators = this.calculateIndicators(history);
this.indicators.set(symbol, indicators);
}
@ -83,21 +112,18 @@ export class MeanReversionStrategy extends BaseStrategy {
private calculateIndicators(prices: number[]): MeanReversionIndicators {
const len = prices.length;
// Calculate SMAs
const sma20 = this.calculateSMA(prices, 20);
const sma50 = len >= 50 ? this.calculateSMA(prices, 50) : sma20;
// Calculate standard deviation
const stdDev = this.calculateStdDev(prices.slice(-20), sma20);
const mean = defined(trailingMean(prices, this.settings.lookbackPeriod));
const trendMean = trailingMean(prices, this.settings.trendPeriod) ?? mean;
const stdDev = defined(trailingPopulationDeviation(prices, this.settings.lookbackPeriod));
// Calculate Z-score
const currentPrice = at(prices, len - 1);
const zScore = stdDev > 0 ? (currentPrice - sma20) / stdDev : 0;
const zScore = stdDev > 0 ? (currentPrice - mean) / stdDev : 0;
// Calculate RSI
const rsi = this.calculateRSI(prices, 14);
const rsi = this.calculateRSI(prices, this.settings.rsiPeriod);
return { sma20, sma50, stdDev, zScore, rsi };
return { mean, trendMean, stdDev, zScore, rsi };
}
protected async generateSignal(data: MarketData): Promise<Signal | null> {
@ -113,17 +139,21 @@ export class MeanReversionStrategy extends BaseStrategy {
}
// Check volume filter
if (data.data.volume * data.data.close < this.MIN_VOLUME) {
if (data.data.volume * data.data.close < this.settings.minNotionalVolume) {
return null;
}
const position = this.getPosition(symbol);
const { zScore, rsi, sma20, sma50 } = indicators;
const { zScore, rsi, mean, trendMean } = indicators;
// Entry signals
if (position === 0) {
// Long entry: Oversold conditions
if (zScore < -this.Z_SCORE_ENTRY && rsi < this.RSI_OVERSOLD && sma20 > sma50) {
if (
zScore < -this.settings.entryThreshold &&
rsi < this.settings.rsiOversold &&
mean > trendMean
) {
return {
type: 'buy',
symbol,
@ -134,7 +164,11 @@ export class MeanReversionStrategy extends BaseStrategy {
}
// Short entry: Overbought conditions
if (zScore > this.Z_SCORE_ENTRY && rsi > this.RSI_OVERBOUGHT && sma20 < sma50) {
if (
zScore > this.settings.entryThreshold &&
rsi > this.settings.rsiOverbought &&
mean < trendMean
) {
return {
type: 'sell',
symbol,
@ -148,7 +182,7 @@ export class MeanReversionStrategy extends BaseStrategy {
// Exit signals
if (position > 0) {
// Exit long: Price reverted to mean or stop loss
if (zScore > -this.Z_SCORE_EXIT || zScore > this.Z_SCORE_ENTRY) {
if (zScore > -this.settings.exitZScore || zScore > this.settings.entryThreshold) {
return {
type: 'close',
symbol,
@ -159,7 +193,7 @@ export class MeanReversionStrategy extends BaseStrategy {
}
} else if (position < 0) {
// Exit short: Price reverted to mean or stop loss
if (zScore < this.Z_SCORE_EXIT || zScore < -this.Z_SCORE_ENTRY) {
if (zScore < this.settings.exitZScore || zScore < -this.settings.entryThreshold) {
return {
type: 'close',
symbol,
@ -173,17 +207,6 @@ export class MeanReversionStrategy extends BaseStrategy {
return null;
}
private calculateSMA(prices: number[], period: number): number {
const relevantPrices = prices.slice(-period);
return relevantPrices.reduce((sum, p) => sum + p, 0) / relevantPrices.length;
}
private calculateStdDev(prices: number[], mean: number): number {
const squaredDiffs = prices.map(p => Math.pow(p - mean, 2));
const variance = squaredDiffs.reduce((sum, d) => sum + d, 0) / prices.length;
return Math.sqrt(variance);
}
private calculateRSI(prices: number[], period: number = 14): number {
if (prices.length < period + 1) {
return 50;

View file

@ -1,11 +1,14 @@
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');
@ -15,7 +18,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
private barCount = new Map<string, number>();
private totalSignals = 0;
override getCheckpointVersion() {
return 'sma-crossover-original/v1';
return 'sma-crossover-original/v2';
}
protected override captureIndicators() {
return {
@ -27,28 +30,26 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
};
}
protected override restoreIndicators(input: unknown) {
const state = crossoverCheckpointSchema.parse(input);
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;
}
// Strategy parameters
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals
private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals
private readonly POSITION_SIZE = 0.1; // 10% of capital per position
private readonly MIN_HOLDING_BARS = 1; // Minimum bars to hold position
private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging
private settings: SmaParameters;
private readonly DEBUG_INTERVAL = 10;
constructor(
config: StrategyConfig,
modeManager: ModeManager,
executionService: ExecutionService
) {
super(config, modeManager, executionService);
const validated = smaConfig(config, 1);
super(validated, modeManager, executionService);
this.settings = validated.parameters;
logger.info(
`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
);
}
@ -75,12 +76,12 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
this.barCount.set(symbol, currentBar);
// Keep only needed history
if (history.length > this.SLOW_PERIOD * 2) {
if (history.length > this.settings.slowPeriod * 2) {
history.shift();
}
// Log when we have enough data to start trading
if (history.length === this.SLOW_PERIOD) {
if (history.length === this.settings.slowPeriod) {
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
}
}
@ -93,21 +94,24 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
const symbol = data.data.symbol;
const history = this.priceHistory.get(symbol);
if (!history || history.length < this.SLOW_PERIOD) {
if (!history || history.length <= this.settings.slowPeriod) {
if (history && history.length % 5 === 0) {
logger.debug(`${symbol} - Not enough history: ${history.length}/${this.SLOW_PERIOD} bars`);
logger.debug(
`${symbol} - Not enough history: ${history.length}/${this.settings.slowPeriod + 1} bars`
);
}
return null;
}
// Calculate moving averages
const fastMA = this.calculateSMA(history, this.FAST_PERIOD);
const slowMA = this.calculateSMA(history, this.SLOW_PERIOD);
// Get previous MAs for crossover detection
const prevHistory = history.slice(0, -1);
const prevFastMA = this.calculateSMA(prevHistory, this.FAST_PERIOD);
const prevSlowMA = this.calculateSMA(prevHistory, this.SLOW_PERIOD);
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;
@ -119,10 +123,6 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
const barsSinceLastTrade =
lastTradeBar > 0 ? currentBar - lastTradeBar : Number.MAX_SAFE_INTEGER;
// Detect crossovers FIRST
const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA;
const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA;
// Enhanced debugging - log more frequently and when MAs are close
const maDiff = fastMA - slowMA;
const maDiffPct = (maDiff / slowMA) * 100;
@ -131,8 +131,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
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.FAST_PERIOD}): $${fastMA.toFixed(2)}`);
logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.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}`);
@ -291,32 +291,22 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
return null;
}
private calculateSMA(prices: number[], period: number): number {
if (prices.length < period) {
logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`);
return 0;
}
const slice = prices.slice(-period);
const sum = slice.reduce((a, b) => a + b, 0);
const sma = sum / period;
// Sanity check
if (isNaN(sma) || !isFinite(sma)) {
logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`);
return 0;
}
return sma;
protected override validateConfig(config: StrategyConfig): StrategyConfig {
const validated = smaConfig(config, 1);
this.settings = validated.parameters;
return validated;
}
private async calculateCrossoverPositionSize(price: number): Promise<number> {
if (this.settings.quantity !== undefined) {
return this.settings.quantity;
}
const accountBalance = (await this.executionService.getAccount()).equity;
const positionValue = accountBalance * this.POSITION_SIZE;
const positionValue = accountBalance * this.settings.positionFraction;
const shares = Math.floor(positionValue / price);
logger.debug(
`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
);
return Math.max(1, shares); // At least 1 share

View file

@ -1,11 +1,14 @@
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 { 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');
@ -16,7 +19,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
private totalSignals = 0;
private lastCrossoverType = new Map<string, 'golden' | 'death' | null>();
override getCheckpointVersion() {
return 'sma-crossover-fixed/v1';
return 'sma-crossover-fixed/v2';
}
protected override captureIndicators() {
return {
@ -28,7 +31,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
};
}
protected override restoreIndicators(input: unknown) {
const state = crossoverCheckpointSchema.parse(input);
const state = crossoverCheckpointSchema(this.settings.slowPeriod * 2).parse(input);
this.priceHistory = new Map(state.priceHistory);
this.lastSignalBar = new Map(state.lastSignalBar);
this.barCount = new Map(state.barCount);
@ -36,21 +39,19 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
this.lastCrossoverType = new Map(state.lastCrossoverType);
}
// Strategy parameters
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals
private readonly SLOW_PERIOD = 15; // Changed from 20 to generate more signals
private readonly POSITION_SIZE = 0.1; // 10% of capital per position
private readonly MIN_HOLDING_BARS = 3; // Minimum bars to hold position
private readonly DEBUG_INTERVAL = 10; // Log every N bars for debugging
private settings: SmaParameters;
private readonly DEBUG_INTERVAL = 10;
constructor(
config: StrategyConfig,
modeManager: ModeManager,
executionService: ExecutionService
) {
super(config, modeManager, executionService);
const validated = smaConfig(config);
super(validated, modeManager, executionService);
this.settings = validated.parameters;
logger.info(
`SimpleMovingAverageCrossover initialized with Fast=${this.FAST_PERIOD}, Slow=${this.SLOW_PERIOD}`
`SimpleMovingAverageCrossover initialized with Fast=${this.settings.fastPeriod}, Slow=${this.settings.slowPeriod}`
);
}
@ -77,12 +78,12 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
this.barCount.set(symbol, currentBar);
// Keep only needed history
if (history.length > this.SLOW_PERIOD * 2) {
if (history.length > this.settings.slowPeriod * 2) {
history.shift();
}
// Log when we have enough data to start trading
if (history.length === this.SLOW_PERIOD) {
if (history.length === this.settings.slowPeriod + 1) {
logger.info(`✅ ${symbol} now has enough history (${history.length} bars) to start trading`);
}
}
@ -95,7 +96,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
const symbol = data.data.symbol;
const history = this.priceHistory.get(symbol);
if (!history || history.length < this.SLOW_PERIOD) {
if (!history || history.length < this.settings.slowPeriod) {
return null;
}
@ -103,18 +104,15 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
const timestamp = data.data.timestamp;
const currentBar = this.barCount.get(symbol) || 0;
// Calculate moving averages
const fastMA = this.calculateSMA(history, this.FAST_PERIOD);
const slowMA = this.calculateSMA(history, this.SLOW_PERIOD);
// Get previous MAs for crossover detection
const historyWithoutLast = history.slice(0, -1);
const prevFastMA = this.calculateSMA(historyWithoutLast, this.FAST_PERIOD);
const prevSlowMA = this.calculateSMA(historyWithoutLast, this.SLOW_PERIOD);
// Detect crossovers
const goldenCross = prevFastMA <= prevSlowMA && fastMA > slowMA;
const deathCross = prevFastMA >= prevSlowMA && fastMA < slowMA;
const crossover = movingAverageCrossover(
history,
this.settings.fastPeriod,
this.settings.slowPeriod
);
if (!crossover) {
return null;
}
const { fastMA, slowMA, prevFastMA, prevSlowMA, goldenCross, deathCross } = crossover;
// Get current position
const currentPosition = this.getPosition(symbol);
@ -131,8 +129,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
if (currentBar % this.DEBUG_INTERVAL === 0 || goldenCross || deathCross) {
logger.info(`${symbol} @ ${timestamp} [Bar ${currentBar}]:`);
logger.info(` Price: $${currentPrice.toFixed(2)}`);
logger.info(` Fast MA (${this.FAST_PERIOD}): $${fastMA.toFixed(2)}`);
logger.info(` Slow MA (${this.SLOW_PERIOD}): $${slowMA.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 signal: ${barsSinceLastSignal}`);
@ -155,7 +153,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
// Check if we should enter a position based on the current trend
const lastCrossover = this.lastCrossoverType.get(symbol);
if (currentPosition === 0 && barsSinceLastSignal >= this.MIN_HOLDING_BARS) {
if (currentPosition === 0 && barsSinceLastSignal >= this.settings.minHoldingBars) {
// No position - check if we should enter based on last crossover
if (lastCrossover === 'golden' && fastMA > slowMA) {
// Trend is still bullish after golden cross - open long
@ -278,32 +276,22 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
return null;
}
private calculateSMA(prices: number[], period: number): number {
if (prices.length < period) {
logger.warn(`Not enough data for SMA calculation: ${prices.length} < ${period}`);
return 0;
}
const slice = prices.slice(-period);
const sum = slice.reduce((a, b) => a + b, 0);
const sma = sum / period;
// Sanity check
if (isNaN(sma) || !isFinite(sma)) {
logger.error(`Invalid SMA calculation: sum=${sum}, period=${period}, prices=${slice.length}`);
return 0;
}
return sma;
protected override validateConfig(config: StrategyConfig): StrategyConfig {
const validated = smaConfig(config);
this.settings = validated.parameters;
return validated;
}
private async calculateCrossoverPositionSize(price: number): Promise<number> {
if (this.settings.quantity !== undefined) {
return this.settings.quantity;
}
const accountBalance = (await this.executionService.getAccount()).equity;
const positionValue = accountBalance * this.POSITION_SIZE;
const positionValue = accountBalance * this.settings.positionFraction;
const shares = Math.floor(positionValue / price);
logger.debug(
`Position sizing: Balance=$${accountBalance}, Position Size=${this.POSITION_SIZE}, Price=$${price}, Shares=${shares}`
`Position sizing: Balance=$${accountBalance}, Position Size=${this.settings.positionFraction}, Price=$${price}, Shares=${shares}`
);
return Math.max(1, shares); // At least 1 share

View file

@ -0,0 +1,18 @@
import {
typescriptMeanReversionParameters,
typescriptSmaParameters,
} 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 meanReversionConfig(config: StrategyConfig) {
return { ...config, parameters: typescriptMeanReversionParameters.parse(config.parameters) };
}