Centralize strategy contracts and share indicator calculations
This commit is contained in:
parent
366d39001b
commit
4207bf2c1c
25 changed files with 1323 additions and 477 deletions
35
README.md
35
README.md
|
|
@ -97,6 +97,33 @@ nothing. History is still retained in memory for the run; this is not a streamin
|
|||
solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark,
|
||||
not an end-to-end backtest performance estimate.
|
||||
|
||||
### Strategy parameters and indicator math
|
||||
|
||||
`contracts/strategy-names.ts` owns built-in aliases; spaces, underscores and hyphens normalize
|
||||
to the same identity. `contracts/strategies.ts` owns backend-specific parameter schemas, and
|
||||
`backtest/strategy-plan.ts` applies shared defaults followed by per-strategy overrides for
|
||||
both backends. Disabled entries do not run or consume TypeScript allocation. Invalid built-in
|
||||
parameters fail before historical input loading; unknown/unsupported keys, numeric strings,
|
||||
fractional periods and nonfinite values are rejected rather than ignored or truncated.
|
||||
Custom TypeScript factories retain their own parameter contracts and extension fields.
|
||||
|
||||
Periods are integer bars bounded by 10000, with `fastPeriod < slowPeriod` for SMA. Both SMA
|
||||
backends default to 5/15 and accept an explicit `quantity` in shares (1e-8 through 1e9).
|
||||
Without `quantity`, TypeScript SMA uses `positionFraction` (default 0.1 of account equity),
|
||||
while native SMA uses 100 shares. Native mean reversion, momentum and pairs retain their
|
||||
`positionSize` parameter in **shares**, not an equity fraction. TypeScript mean reversion
|
||||
accepts configurable lookback/trend/RSI windows, entry/exit thresholds and notional-volume
|
||||
filter; its optional `quantity` is also shares. Do not transfer backend-only parameters blindly.
|
||||
|
||||
`indicators/window-statistics.ts` shares slice-free trailing mean, population deviation
|
||||
and crossover calculations across TypeScript strategies. A crossover requires `slowPeriod + 1`
|
||||
bars, including a complete previous window; missing warm-up is not a synthetic zero average.
|
||||
Tests compare the scalar math with real Rust batch/incremental indicators and exercise
|
||||
configured SMA fills in both backends. This is not full algorithm/result parity: entry/exit
|
||||
and RSI rules differ, and native backtests force liquidation at the end while TypeScript
|
||||
backtests retain open positions. Corrected warm-up and previously ignored settings can change
|
||||
historical results.
|
||||
|
||||
### TypeScript backtest composition
|
||||
|
||||
`BacktestEngine` coordinates fresh components for each run:
|
||||
|
|
@ -227,6 +254,14 @@ ML paper strategies fail **before** model startup: asynchronous model training a
|
|||
do not yet have a replay-safe artifact contract. Run-local backtests can still use explicitly
|
||||
unversioned experimental strategies, without claiming restart recovery for their custom state.
|
||||
|
||||
The configurable SMA and mean-reversion implementations now use checkpoint version **v2**.
|
||||
They do not resume v1 registrations. Before deploying against an existing paper account,
|
||||
explicitly pause the affected v1 registrations using the compatible runtime, review pending
|
||||
intents/open orders, and register new strategy IDs with validated v2 parameters and fresh
|
||||
indicator warm-up. Enabled v1 registrations block recovery even if a new ID is also supplied.
|
||||
Pausing does not cancel committed work. No upgrade step rewrites checkpoints, resets account
|
||||
balances or deletes historical registrations; tests do not modify running development accounts.
|
||||
|
||||
Strategy evaluation must be bounded and deterministic: no fire-and-forget state mutation,
|
||||
wall-clock/random decisions, broker calls, model training or external I/O in callbacks.
|
||||
Repository I/O/direct submissions from a callback fail closed; use the as-of account view
|
||||
|
|
|
|||
|
|
@ -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(¶meters, &["fastPeriod", "slowPeriod", "quantity"])?;
|
||||
let error = || {
|
||||
Error::from_reason("SMA periods must satisfy 0 < fastPeriod < slowPeriod <= 10000 (finite integers)")
|
||||
};
|
||||
let fast =
|
||||
parameters::period(¶meters, "fastPeriod", 5.0, 1.0).map_err(|_| error())?;
|
||||
let slow = parameters::period(¶meters, "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(¶meters, "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(
|
||||
¶meters,
|
||||
&["lookbackPeriod", "entryThreshold", "positionSize"],
|
||||
)?;
|
||||
let lookback = parameters::period(¶meters, "lookbackPeriod", 20.0, 2.0)?;
|
||||
let threshold = parameters::number(
|
||||
¶meters,
|
||||
"entryThreshold",
|
||||
2.0,
|
||||
f64::from_bits(1),
|
||||
f64::MAX,
|
||||
false,
|
||||
)?;
|
||||
let size =
|
||||
parameters::number(¶meters, "positionSize", 100.0, 1e-8, 1e9, false)?;
|
||||
engine.add_strategy(Box::new(
|
||||
crate::strategies::MeanReversionFixedStrategy::new(
|
||||
name, id, lookback, threshold, size,
|
||||
),
|
||||
));
|
||||
}
|
||||
"momentum" => {
|
||||
parameters::keys(
|
||||
¶meters,
|
||||
&["lookbackPeriod", "momentumThreshold", "positionSize"],
|
||||
)?;
|
||||
let lookback = parameters::period(¶meters, "lookbackPeriod", 14.0, 1.0)?;
|
||||
let threshold = parameters::number(
|
||||
¶meters,
|
||||
"momentumThreshold",
|
||||
5.0,
|
||||
f64::from_bits(1),
|
||||
f64::MAX,
|
||||
false,
|
||||
)?;
|
||||
let size =
|
||||
parameters::number(¶meters, "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(
|
||||
¶meters,
|
||||
&[
|
||||
"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(¶meters, "lookbackPeriod", 20.0, 2.0)?;
|
||||
let threshold = parameters::number(
|
||||
¶meters,
|
||||
"entryThreshold",
|
||||
2.0,
|
||||
f64::from_bits(1),
|
||||
f64::MAX,
|
||||
false,
|
||||
)?;
|
||||
let size =
|
||||
parameters::number(¶meters, "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
|
||||
}))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
mod backtest;
|
||||
mod indicators;
|
||||
mod risk;
|
||||
mod strategy_parameters;
|
||||
|
||||
pub use backtest::BacktestEngine;
|
||||
pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators};
|
||||
|
|
|
|||
54
apps/stock/engine/src/api/strategy_parameters.rs
Normal file
54
apps/stock/engine/src/api/strategy_parameters.rs
Normal 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(())
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
213
apps/stock/engine/src/strategies/sma_crossover.rs
Normal file
213
apps/stock/engine/src/strategies/sma_crossover.rs
Normal 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
});
|
||||
}
|
||||
|
|
|
|||
48
apps/stock/orchestrator/src/backtest/strategy-plan.ts
Normal file
48
apps/stock/orchestrator/src/backtest/strategy-plan.ts
Normal 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 };
|
||||
});
|
||||
}
|
||||
131
apps/stock/orchestrator/src/contracts/strategies.ts
Normal file
131
apps/stock/orchestrator/src/contracts/strategies.ts
Normal 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}`);
|
||||
}
|
||||
}
|
||||
20
apps/stock/orchestrator/src/contracts/strategy-names.ts
Normal file
20
apps/stock/orchestrator/src/contracts/strategy-names.ts
Normal 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)
|
||||
);
|
||||
}
|
||||
74
apps/stock/orchestrator/src/indicators/window-statistics.ts
Normal file
74
apps/stock/orchestrator/src/indicators/window-statistics.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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}`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
18
apps/stock/orchestrator/src/strategies/strategy-config.ts
Normal file
18
apps/stock/orchestrator/src/strategies/strategy-config.ts
Normal 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) };
|
||||
}
|
||||
|
|
@ -96,7 +96,8 @@ describe('orchestrator architecture boundaries', () => {
|
|||
const file = join(root, 'strategies/StrategyManager.ts');
|
||||
expect(imports.get(file)?.some(specifier => specifier.includes('/examples/'))).toBe(false);
|
||||
expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/);
|
||||
expect(imports.get(join(root, 'strategies/StrategyRegistry.ts'))).toEqual([]);
|
||||
expect([...reachable(join(root, 'strategies/StrategyRegistry.ts'))].map(file => relative(root, file)).sort())
|
||||
.toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']);
|
||||
});
|
||||
|
||||
it('backtest playback cannot depend on trading, data, reporting or service adapters', () => {
|
||||
|
|
|
|||
5
test/fixtures/native-backtest-worker.ts
vendored
5
test/fixtures/native-backtest-worker.ts
vendored
|
|
@ -11,7 +11,10 @@ function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void
|
|||
|
||||
process.once('message', async (input: unknown) => {
|
||||
const { config } = nativeWorkerRequestSchema.parse(input);
|
||||
const behavior = config.config?.fixtureBehavior;
|
||||
// Fixture controls are run labels, not unsupported production strategy parameters.
|
||||
const behavior = config.name?.startsWith('fixture:')
|
||||
? config.name.slice('fixture:'.length)
|
||||
: undefined;
|
||||
if (!behavior) {
|
||||
// The same adapter can recover and run the actual Rust engine after a failed worker.
|
||||
await import('../../apps/stock/orchestrator/src/backtest/native-worker');
|
||||
|
|
|
|||
|
|
@ -539,13 +539,22 @@ describe('one backtest execution workflow', () => {
|
|||
});
|
||||
|
||||
const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url);
|
||||
const blockingConfig = { ...config, config: { ...config.config, fixtureBehavior: 'block' } };
|
||||
const blockingConfig = { ...config, name: 'fixture:block' };
|
||||
|
||||
function workerReady(runner: BacktestRunner) {
|
||||
return new Promise<{ pid: number; runId: string }>(resolve => {
|
||||
runner.once('progress', (progress: { message: string; runId: string }) => {
|
||||
return new Promise<{ pid: number; runId: string }>((resolve, reject) => {
|
||||
const onError = (error: Error) => {
|
||||
runner.off('progress', onProgress);
|
||||
reject(error);
|
||||
};
|
||||
const onProgress = (progress: { message: string; runId: string }) => {
|
||||
if (!progress.message.startsWith('Fixture worker ready:')) return;
|
||||
runner.off('progress', onProgress);
|
||||
runner.off('error', onError);
|
||||
resolve({ pid: Number(progress.message.split(':')[1]), runId: progress.runId });
|
||||
});
|
||||
};
|
||||
runner.once('error', onError);
|
||||
runner.on('progress', onProgress);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -633,7 +642,7 @@ describe('isolated native backtest workers', () => {
|
|||
});
|
||||
const ready = workerReady(f.runner);
|
||||
const failed = f.runner
|
||||
.runBacktest({ ...config, config: { fixtureBehavior: behavior } })
|
||||
.runBacktest({ ...config, name: `fixture:${behavior}` })
|
||||
.catch(error => error);
|
||||
const { pid } = await ready;
|
||||
expect(String(await failed)).toContain(message);
|
||||
|
|
@ -693,7 +702,7 @@ describe('isolated native backtest workers', () => {
|
|||
const f = await fixture(false, { workerUrl });
|
||||
const ready = workerReady(f.runner);
|
||||
const cancelled = f.runner
|
||||
.runBacktest({ ...config, config: { fixtureBehavior: 'result-then-block' } })
|
||||
.runBacktest({ ...config, name: 'fixture:result-then-block' })
|
||||
.catch(error => error);
|
||||
const { pid, runId } = await ready;
|
||||
await f.runner.stopBacktest(runId);
|
||||
|
|
@ -827,10 +836,7 @@ describe('isolated native backtest workers', () => {
|
|||
}
|
||||
};
|
||||
Object.defineProperty(api, 'wsHandler', { value: handler });
|
||||
const definition = await api.createBacktest(
|
||||
{ ...blockingConfig, name: config.name! },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const definition = await api.createBacktest(blockingConfig, { autoStart: false });
|
||||
const ready = workerReady(f.runner);
|
||||
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
|
||||
const execution = f.runner.runQueued(run.id).catch(error => error);
|
||||
|
|
|
|||
408
test/integration/strategy-contracts.test.ts
Normal file
408
test/integration/strategy-contracts.test.ts
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
IncrementalSMA,
|
||||
BacktestEngine as NativeEngine,
|
||||
TechnicalIndicators,
|
||||
} from '@stock-bot/engine';
|
||||
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
|
||||
import { resolveNativeStrategies } from '../../apps/stock/orchestrator/src/backtest/native-strategies';
|
||||
import { backtestStrategies } from '../../apps/stock/orchestrator/src/backtest/strategy-plan';
|
||||
import {
|
||||
nativeMeanReversionParameters,
|
||||
nativeMomentumParameters,
|
||||
nativePairsParameters,
|
||||
nativeSmaParameters,
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategies';
|
||||
import {
|
||||
builtinStrategy,
|
||||
normalizeStrategyName,
|
||||
} from '../../apps/stock/orchestrator/src/contracts/strategy-names';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import {
|
||||
movingAverageCrossover,
|
||||
trailingMean,
|
||||
trailingPopulationDeviation,
|
||||
} from '../../apps/stock/orchestrator/src/indicators/window-statistics';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/examples/MeanReversionStrategy';
|
||||
import { SimpleMovingAverageCrossover } from '../../apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution, start } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
const definition: StrategyConfig = {
|
||||
id: 'sma',
|
||||
name: 'sma-crossover',
|
||||
enabled: true,
|
||||
parameters: {},
|
||||
symbols: ['A.US'],
|
||||
allocation: 1,
|
||||
};
|
||||
function nativeEngine() {
|
||||
return new NativeEngine({
|
||||
name: 'contracts',
|
||||
symbols: ['A.US'],
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: 10000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
}
|
||||
const bar = (close: number, index: number, symbol = 'A.US') => ({
|
||||
type: 'bar' as const,
|
||||
eventId: symbol + ':' + index,
|
||||
data: {
|
||||
symbol,
|
||||
close,
|
||||
open: close,
|
||||
high: close + 0.1,
|
||||
low: close - 0.1,
|
||||
volume: 1000,
|
||||
timestamp: start + index * 86400000,
|
||||
},
|
||||
});
|
||||
async function runtime(parameters: Record<string, unknown> = {}, name = definition.name) {
|
||||
const f = makeExecution();
|
||||
await f.execution.initialize({ ...config, commission: 0 }, f.engine);
|
||||
cleanup.push(() => f.execution.shutdown());
|
||||
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
||||
const manager = new StrategyManager({
|
||||
logger,
|
||||
custom: { ExecutionService: f.execution, ModeManager: mode },
|
||||
});
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await manager.initializeStrategies([{ ...definition, name, parameters }]);
|
||||
return { ...f, manager, mode, strategy: manager.getStrategy('sma')! };
|
||||
}
|
||||
|
||||
describe('explicit strategy contracts and shared planning', () => {
|
||||
test('aliases have one canonical identity across registries and native planning', () => {
|
||||
for (const name of [
|
||||
'SMA',
|
||||
' sma-crossover ',
|
||||
'sma_crossover',
|
||||
'Simple Moving Average Crossover',
|
||||
'moving-average',
|
||||
]) {
|
||||
expect(builtinStrategy(name)).toBe('sma_crossover');
|
||||
expect(resolveNativeStrategies({ ...config, strategy: name })[0]?.strategy).toBe(
|
||||
'sma_crossover'
|
||||
);
|
||||
}
|
||||
expect(normalizeStrategyName(' Mean-Reversion ')).toBe('meanreversion');
|
||||
expect(builtinStrategy('unknown')).toBeUndefined();
|
||||
});
|
||||
|
||||
test('both backends use the same shared-default then per-strategy override rule', () => {
|
||||
const request = {
|
||||
...config,
|
||||
config: { fastPeriod: 2, slowPeriod: 9, commission: 0, slippage: 0 },
|
||||
strategies: [
|
||||
{ name: 'sma', enabled: true, config: { slowPeriod: 5 } },
|
||||
{ name: 'not-installed', enabled: false, config: {} },
|
||||
{ name: 'sma_crossover', enabled: true, config: { fastPeriod: 3 } },
|
||||
],
|
||||
};
|
||||
const before = structuredClone(request);
|
||||
for (const backend of ['typescript', 'native'] as const) {
|
||||
const plan = backtestStrategies(request, backend);
|
||||
expect(plan.map(entry => [entry.parameters.fastPeriod, entry.parameters.slowPeriod])).toEqual(
|
||||
[
|
||||
[2, 5],
|
||||
[3, 9],
|
||||
]
|
||||
);
|
||||
expect(plan.every(entry => !('commission' in entry.parameters))).toBe(true);
|
||||
}
|
||||
expect(request).toEqual(before);
|
||||
const custom = backtestStrategies(
|
||||
{ ...config, strategy: 'custom-extension', config: { vendorOption: 42 } },
|
||||
'typescript'
|
||||
);
|
||||
expect(custom[0]?.parameters).toMatchObject({
|
||||
vendorOption: 42,
|
||||
initialCapital: config.initialCapital,
|
||||
});
|
||||
});
|
||||
|
||||
test('periods and units have explicit defaults and fail rather than coerce or truncate', () => {
|
||||
expect(typescriptSmaParameters.parse({})).toMatchObject({
|
||||
fastPeriod: 5,
|
||||
slowPeriod: 15,
|
||||
positionFraction: 0.1,
|
||||
minHoldingBars: 3,
|
||||
});
|
||||
expect(nativeSmaParameters.parse({})).toEqual({ fastPeriod: 5, slowPeriod: 15, quantity: 100 });
|
||||
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
||||
expect(nativeSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ fastPeriod: bad }).success).toBe(false);
|
||||
}
|
||||
expect(typescriptSmaParameters.safeParse({ fastPeriod: 20, slowPeriod: 5 }).success).toBe(
|
||||
false
|
||||
);
|
||||
for (const bad of [0, -1, Infinity, 1e10]) {
|
||||
expect(nativeSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ quantity: bad }).success).toBe(false);
|
||||
}
|
||||
expect(typescriptSmaParameters.safeParse({ positionFraction: 2 }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ positionSize: 100 }).success).toBe(false);
|
||||
expect(typescriptSmaParameters.safeParse({ fastPreriod: 3 }).success).toBe(false);
|
||||
expect(nativeSmaParameters.safeParse({ positionFraction: 0.1 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('mean reversion and native-only strategies validate their actual, different contracts', () => {
|
||||
const mean = typescriptMeanReversionParameters.parse({ lookbackPeriod: 80 });
|
||||
expect(mean.trendPeriod).toBe(80);
|
||||
expect(mean.entryThreshold).toBe(2);
|
||||
expect(typescriptMeanReversionParameters.safeParse({ exitZScore: 3 }).success).toBe(false);
|
||||
expect(
|
||||
typescriptMeanReversionParameters.safeParse({ rsiOversold: 80, rsiOverbought: 20 }).success
|
||||
).toBe(false);
|
||||
expect(
|
||||
typescriptMeanReversionParameters.safeParse({ lookbackPeriod: 30, trendPeriod: 20 }).success
|
||||
).toBe(false);
|
||||
expect(nativeMeanReversionParameters.safeParse({ exitZScore: 0.5 }).success).toBe(false);
|
||||
expect(nativeMeanReversionParameters.safeParse({ lookbackPeriod: 0 }).success).toBe(false);
|
||||
expect(nativeMomentumParameters.safeParse({ momentumThreshold: NaN }).success).toBe(false);
|
||||
expect(nativePairsParameters.safeParse({ pairA: 'A.US', pairB: 'A.US' }).success).toBe(false);
|
||||
expect(() =>
|
||||
backtestStrategies(
|
||||
{ ...config, strategy: 'pairs', config: { pairA: 'A.US', pairB: 'C.US' } },
|
||||
'native'
|
||||
)
|
||||
).toThrow('included in backtest symbols');
|
||||
});
|
||||
|
||||
test('invalid native plans fail before loading input and unsupported execution flags are explicit', () => {
|
||||
expect(() => backtestStrategies({ ...config, strategies: [] }, 'native')).toThrow('No enabled');
|
||||
expect(() => backtestStrategies({ ...config, strategies: [] }, 'typescript')).toThrow(
|
||||
'No enabled'
|
||||
);
|
||||
expect(() =>
|
||||
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: true } })
|
||||
).toThrow('does not execute TypeScript');
|
||||
expect(() =>
|
||||
resolveNativeStrategies({ ...config, config: { useTypeScriptImplementation: 'false' } })
|
||||
).toThrow();
|
||||
expect(
|
||||
backtestStrategies({ ...config, config: { useTypeScriptImplementation: true } }, 'typescript')
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
|
||||
const f = await runtime();
|
||||
const storage = new StorageService({ logger }, null, null, null);
|
||||
const backend = new BacktestEngine(
|
||||
{ logger, custom: { ExecutionService: f.execution } },
|
||||
storage,
|
||||
f.manager
|
||||
);
|
||||
cleanup.push(() => backend.shutdown());
|
||||
let reads = 0;
|
||||
await expect(
|
||||
backend.runBacktest({ ...config, config: { fastPeriod: 5, slowPeriod: 2 } }, async () => {
|
||||
reads++;
|
||||
throw new Error('Must not load data');
|
||||
})
|
||||
).rejects.toThrow('SMA periods must satisfy');
|
||||
expect(reads).toBe(0);
|
||||
});
|
||||
|
||||
test('definitions are detached and rejected inactive edits leave effective settings intact', async () => {
|
||||
const f = await runtime();
|
||||
const input = { ...definition, parameters: { fastPeriod: 2, slowPeriod: 3, quantity: 7 } };
|
||||
const strategy = new SimpleMovingAverageCrossover(input, f.mode, f.execution);
|
||||
input.parameters.fastPeriod = 0;
|
||||
const view = strategy.getConfig();
|
||||
view.parameters.slowPeriod = 0;
|
||||
expect(strategy.getConfig().parameters).toMatchObject({
|
||||
fastPeriod: 2,
|
||||
slowPeriod: 3,
|
||||
quantity: 7,
|
||||
});
|
||||
await expect(
|
||||
strategy.updateConfig({ parameters: { fastPeriod: 9, slowPeriod: 3 } })
|
||||
).rejects.toThrow('SMA periods');
|
||||
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 2, slowPeriod: 3 });
|
||||
await strategy.updateConfig({ parameters: { fastPeriod: 3, slowPeriod: 8 } });
|
||||
expect(strategy.getConfig().parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 8 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('shared trailing-window math and native parity', () => {
|
||||
test('warm-up never manufactures zero averages or first-window crossovers', () => {
|
||||
expect(trailingMean([3, 2], 3)).toBeUndefined();
|
||||
expect(movingAverageCrossover([3, 2, 1], 2, 3)).toBeUndefined();
|
||||
expect(movingAverageCrossover([3, 2, 1, 4], 2, 3)).toMatchObject({
|
||||
goldenCross: true,
|
||||
deathCross: false,
|
||||
});
|
||||
expect(movingAverageCrossover([1, 2, 3, 1], 2, 3)).toMatchObject({
|
||||
goldenCross: false,
|
||||
deathCross: false,
|
||||
});
|
||||
expect(movingAverageCrossover([1, 2, 3, 0.5], 2, 3)).toMatchObject({
|
||||
goldenCross: false,
|
||||
deathCross: true,
|
||||
});
|
||||
expect(trailingPopulationDeviation([10, 10, 10], 3)).toBe(0);
|
||||
for (const period of [0, -1, 1.5, Infinity])
|
||||
expect(() => trailingMean([1, 2, 3], period)).toThrow();
|
||||
expect(() => trailingMean([1, NaN, 3], 3)).toThrow('finite');
|
||||
expect(() => trailingMean([Number.MAX_VALUE, Number.MAX_VALUE], 2)).toThrow('overflow');
|
||||
});
|
||||
|
||||
test('scalar SMA and population deviation match native batch and incremental indicators', () => {
|
||||
const native = new TechnicalIndicators();
|
||||
const prices = Array.from(
|
||||
{ length: 130 },
|
||||
(_, index) => 100 + Math.sin(index / 3) * 8 + index / 100
|
||||
);
|
||||
for (const period of [2, 5, 15, 80]) {
|
||||
const rolling = new IncrementalSMA(period);
|
||||
const series = native.calculateSma(prices, period);
|
||||
const bands = JSON.parse(native.calculateBollingerBands(prices, period, 2));
|
||||
for (let index = 0; index < prices.length; index++) {
|
||||
const value = rolling.update(prices[index]!);
|
||||
const scalar = trailingMean(prices.slice(0, index + 1), period);
|
||||
if (scalar === undefined) {
|
||||
expect(value == null).toBe(true);
|
||||
continue;
|
||||
}
|
||||
expect(value!).toBeCloseTo(scalar, 9);
|
||||
expect(series[index + 1 - period]!).toBeCloseTo(scalar, 9);
|
||||
const deviation = trailingPopulationDeviation(prices.slice(0, index + 1), period)!;
|
||||
expect(
|
||||
(bands.upper[index + 1 - period] - bands.middle[index + 1 - period]) / 2
|
||||
).toBeCloseTo(deviation, 8);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('configured SMA periods and explicit shares reach real fills in both backends', async () => {
|
||||
const f = await runtime({ fastPeriod: 2, slowPeriod: 3, quantity: 7, minHoldingBars: 0 });
|
||||
const prices = [3, 2, 1, 4];
|
||||
for (let i = 0; i < 3; i++) await f.manager.onMarketData(bar(prices[i]!, i));
|
||||
expect((await f.execution.getAccount()).positions['A.US']).toBeUndefined();
|
||||
await f.manager.onMarketData(bar(prices[3]!, 3));
|
||||
expect((await f.execution.getAccount()).positions['A.US']?.quantity).toBe(7);
|
||||
const native = nativeEngine();
|
||||
native.addNativeStrategy('sma_crossover', 'sma', 'id', {
|
||||
fastPeriod: 2,
|
||||
slowPeriod: 3,
|
||||
quantity: 7,
|
||||
});
|
||||
native.loadMarketData(
|
||||
prices.map((price, i) => ({ ...bar(price, i).data, type: 'bar', vwap: price }))
|
||||
);
|
||||
const result = JSON.parse(native.run());
|
||||
// Native backtests liquidate at the end; that exit is not a second strategy entry.
|
||||
expect(result.trades).toHaveLength(2);
|
||||
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 7, symbol: 'A.US' });
|
||||
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 7, symbol: 'A.US' });
|
||||
expect(() => native.addNativeStrategy('sma_crossover', 'late', 'late', {})).toThrow('consumed');
|
||||
});
|
||||
|
||||
test('configured long windows remain checkpointable and preserve state through replacement', async () => {
|
||||
const settings = { fastPeriod: 5, slowPeriod: 80, quantity: 1 };
|
||||
const f = await runtime(settings);
|
||||
for (let i = 0; i < 90; i++) await f.manager.onMarketData(bar(100 + Math.sin(i / 3), i));
|
||||
const state = f.strategy.captureCheckpoint();
|
||||
const replacement = new SimpleMovingAverageCrossover(
|
||||
f.strategy.getConfig(),
|
||||
f.mode,
|
||||
f.execution
|
||||
);
|
||||
replacement.restoreCheckpoint(state);
|
||||
expect(replacement.captureCheckpoint()).toEqual(state);
|
||||
expect(replacement.getCheckpointVersion()).toBe('sma-crossover-fixed/v2');
|
||||
const mean = await runtime({ lookbackPeriod: 80 }, 'mean-reversion');
|
||||
const prices = Array.from({ length: 90 }, (_, i) => 100 + Math.sin(i / 3));
|
||||
for (let i = 0; i < prices.length; i++) {
|
||||
await mean.manager.onMarketData(bar(prices[i]!, i));
|
||||
}
|
||||
const meanState = mean.strategy.captureCheckpoint();
|
||||
expect(meanState).toMatchObject({
|
||||
indicators: {
|
||||
priceHistory: [['A.US', prices]],
|
||||
indicators: [
|
||||
[
|
||||
'A.US',
|
||||
{
|
||||
mean: trailingMean(prices, 80),
|
||||
trendMean: trailingMean(prices, 80),
|
||||
stdDev: trailingPopulationDeviation(prices, 80),
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
const restoredMean = new MeanReversionStrategy(
|
||||
mean.strategy.getConfig(),
|
||||
mean.mode,
|
||||
mean.execution
|
||||
);
|
||||
restoredMean.restoreCheckpoint(meanState);
|
||||
expect(restoredMean.captureCheckpoint()).toEqual(meanState);
|
||||
expect(restoredMean.getConfig().parameters.trendPeriod).toBe(80);
|
||||
});
|
||||
|
||||
test('v2 cannot silently reset a legacy paper definition; explicit new IDs preserve old registration', async () => {
|
||||
const f = makeExecution();
|
||||
await f.execution.initialize(config, f.engine);
|
||||
cleanup.push(() => f.execution.shutdown());
|
||||
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
||||
const legacy = new SimpleMovingAverageCrossover(definition, mode, f.execution);
|
||||
legacy.getCheckpointVersion = () => 'sma-crossover-fixed/v1';
|
||||
await f.execution.registerStrategy(legacy);
|
||||
const before = await f.execution.getRecoveryStatus();
|
||||
const upgraded = new SimpleMovingAverageCrossover(definition, mode, f.execution);
|
||||
await expect(f.execution.registerStrategy(upgraded)).rejects.toThrow('version changed');
|
||||
expect(await f.execution.getRecoveryStatus()).toEqual(before);
|
||||
await f.execution.pauseStrategy('sma');
|
||||
const fresh = new SimpleMovingAverageCrossover(
|
||||
{ ...definition, id: 'sma-v2' },
|
||||
mode,
|
||||
f.execution
|
||||
);
|
||||
await f.execution.registerStrategy(fresh);
|
||||
expect((await f.execution.getRecoveryStatus()).strategies).toMatchObject([
|
||||
{ strategyId: 'sma', enabled: false, version: 'sma-crossover-fixed/v1' },
|
||||
{ strategyId: 'sma-v2', enabled: true, version: 'sma-crossover-fixed/v2' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('native parameter trust boundary', () => {
|
||||
test('native bindings reject invalid numeric types, fractions, infinities and unknown keys independently', () => {
|
||||
const engine = nativeEngine();
|
||||
for (const bad of [0, -1, 1.5, NaN, Infinity, '3', null, 10001]) {
|
||||
expect(() =>
|
||||
engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: bad })
|
||||
).toThrow('SMA periods');
|
||||
}
|
||||
for (const [name, parameters] of [
|
||||
['sma_crossover', { fastPreriod: 3 }],
|
||||
['sma_crossover', { quantity: -1 }],
|
||||
['mean_reversion', { lookbackPeriod: 0 }],
|
||||
['mean_reversion', { lookbackPeriod: 1.5 }],
|
||||
['mean_reversion', { entryThreshold: NaN }],
|
||||
['momentum', { positionSize: Infinity }],
|
||||
['momentum', { momentumThreshold: '5' }],
|
||||
['pairs_trading', { pairA: 'A.US', pairB: 'A.US' }],
|
||||
] as const) {
|
||||
expect(() => engine.addNativeStrategy(name, 'invalid', 'invalid', parameters)).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
engine.addNativeStrategy('sma_crossover', 'defaults', 'defaults', {})
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -79,12 +79,12 @@ describe('strategy registration and expansion', () => {
|
|||
for (const name of ['meanreversion', 'mean-reversion']) {
|
||||
expect(
|
||||
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
|
||||
).toBe('mean-reversion/v1');
|
||||
).toBe('mean-reversion/v2');
|
||||
}
|
||||
for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) {
|
||||
expect(
|
||||
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
|
||||
).toBe('sma-crossover-fixed/v1');
|
||||
).toBe('sma-crossover-fixed/v2');
|
||||
}
|
||||
for (const name of ['mlenhanced', 'ml-enhanced']) {
|
||||
expect(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue