Skip to main content

Strategy

Trait Strategy 

Source
pub trait Strategy: Send + Sync {
    // Required methods
    fn name(&self) -> &str;
    fn required_indicators(&self) -> Vec<(String, Indicator)>;
    fn on_candle(&self, ctx: &StrategyContext<'_>) -> Signal;

    // Provided methods
    fn htf_requirements(&self) -> Vec<HtfIndicatorSpec> { ... }
    fn setup(&mut self, _indicators: &HashMap<String, Vec<Option<f64>>>) { ... }
    fn warmup_period(&self) -> usize { ... }
}
Expand description

Core strategy trait - implement this for custom strategies.

§Example

use finance_query::backtesting::{Strategy, StrategyContext, Signal};
use finance_query::indicators::Indicator;

struct MyStrategy {
    sma_period: usize,
}

impl Strategy for MyStrategy {
    fn name(&self) -> &str {
        "My Custom Strategy"
    }

    fn required_indicators(&self) -> Vec<(String, Indicator)> {
        vec![
            (format!("sma_{}", self.sma_period), Indicator::Sma(self.sma_period)),
        ]
    }

    fn on_candle(&self, ctx: &StrategyContext) -> Signal {
        let sma = ctx.indicator(&format!("sma_{}", self.sma_period));
        let close = ctx.close();

        match sma {
            Some(sma_val) if close > sma_val && !ctx.has_position() => {
                Signal::long(ctx.timestamp(), close)
            }
            Some(sma_val) if close < sma_val && ctx.is_long() => {
                Signal::exit(ctx.timestamp(), close)
            }
            _ => Signal::hold(),
        }
    }
}

Required Methods§

Source

fn name(&self) -> &str

Strategy name (for reporting)

Source

fn required_indicators(&self) -> Vec<(String, Indicator)>

Required indicators this strategy needs.

Returns list of (indicator_name, Indicator) pairs. The engine will pre-compute these and make them available via StrategyContext::indicator().

Source

fn on_candle(&self, ctx: &StrategyContext<'_>) -> Signal

Called on each candle to generate a signal.

Return Signal::hold() for no action, Signal::long() to enter long, Signal::short() to enter short, or Signal::exit() to close position.

Provided Methods§

Source

fn htf_requirements(&self) -> Vec<HtfIndicatorSpec>

Higher-timeframe indicators required by this strategy.

The engine resamples candles to each unique interval, computes the listed indicators on the resampled data, and stores stretched (base-timeframe-length) arrays in StrategyContext::indicators under the htf_key names. Strategies built with StrategyBuilder implement this automatically; raw Strategy implementations that use HTF conditions should override this to avoid the O(n²) dynamic fallback.

Source

fn setup(&mut self, _indicators: &HashMap<String, Vec<Option<f64>>>)

Called once by the engine after indicator pre-computation, before the simulation loop. Strategies may cache references into the indicator map here to avoid per-bar HashMap lookups. The default implementation does nothing; pre-built strategies override this for performance.

Source

fn warmup_period(&self) -> usize

Optional: minimum candles required before strategy can generate signals. Default is 1 (strategy can run from first candle).

Trait Implementations§

Source§

impl Strategy for Box<dyn Strategy>

Source§

fn name(&self) -> &str

Strategy name (for reporting)
Source§

fn required_indicators(&self) -> Vec<(String, Indicator)>

Required indicators this strategy needs. Read more
Source§

fn htf_requirements(&self) -> Vec<HtfIndicatorSpec>

Higher-timeframe indicators required by this strategy. Read more
Source§

fn setup(&mut self, indicators: &HashMap<String, Vec<Option<f64>>>)

Called once by the engine after indicator pre-computation, before the simulation loop. Strategies may cache references into the indicator map here to avoid per-bar HashMap lookups. The default implementation does nothing; pre-built strategies override this for performance.
Source§

fn on_candle(&self, ctx: &StrategyContext<'_>) -> Signal

Called on each candle to generate a signal. Read more
Source§

fn warmup_period(&self) -> usize

Optional: minimum candles required before strategy can generate signals. Default is 1 (strategy can run from first candle).

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl Strategy for Box<dyn Strategy>

Implementors§