Skip to main content

Backtest

Struct Backtest 

Source
#[non_exhaustive]
pub struct Backtest { pub name: String, pub symbol: String, pub timeframe: Timeframe, pub settings: BacktestSettings, /* private fields */ }
Expand description

Runs a Strategy over bars and reports the result as a StrategyReport.

The strategy decides on each bar once it closes. Its orders fill no earlier than the next bar, along that bar’s price path: from the open to the extreme nearer the open (the high when both are as near within a few ulps), then to the other extreme, then to the close. A market order fills at the open. A limit, stop or stop-limit order fills where the path reaches it, at its limit or stop price, or at the open when the bar opened beyond it; a triggered stop-limit order works on as a limit order from its stop. Orders the path reaches at the same point fill in the order they were first placed. An exit with a take profit and a stop loss fills whichever the path reaches first. With settings.fill_on_close, market orders fill at the close of the bar they were placed on instead.

Each entry is a trade, closed by exits and opposite entries first in first out; each partial exit is its own trade with its share of the entry. A trade’s label names its entry and exit orders, such as “Long / Take profit”, or the entry alone while open. Profit is the price difference times the quantity, less its allocated fees. Without a start time, the equity curve holds the initial capital one interval before the first bar, then the account value at each bar’s close, stamped with the bar’s time. With a start time it begins there and subsequent marks use chart-bar closing times. Fills use the times of their chart or finer bars. Close fills on trade-based bars use the last source time, which stays fixed as bars arrive.

Bars are oldest first, in strictly increasing time order. A bar without finite prices, or whose high and low do not contain its open and close, fills no orders and has no equity value. Settings apply sizing, pyramiding, costs and margin at each execution; a margin deficit closes the position along the path. Optional finer bars determine fills within each chart bar.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§name: String

What the report calls the run.

§symbol: String

The instrument the bars are of.

§timeframe: Timeframe

The bar interval.

§settings: BacktestSettings

Account and execution assumptions, also recorded in the report’s properties.

Implementations§

Source§

impl Backtest

Source

pub fn report(&self) -> Option<&StrategyReport>

The current live report, available after the first Self::update. With tick recalculation, trades include forming-bar fills; equity marks are closed bars. Self::run remains an independent historical calculation and does not change this state.

Source

pub fn update( &mut self, strategy: &mut dyn Strategy, bars: &[Bar], lower: &[Bar], ) -> Vec<StrategyFill>

Continues a live strategy on bars, oldest first, with the last bar still forming. Pass the same strategy instance and the full retained history on each call. The first call processes the closed history and returns its fills; discard that batch when priming a run that should alert only on subsequent fills. lower has the meaning it has in run.

With settings.recalculate_on_every_update off, only newly closed bars execute, exactly as in run over bars without its last bar. With it on, an observed forming bar walks from its open to its close, then from its previous close to each new close, and decides again with that forming bar included in the context. Its fills and orders are retained when the bar closes; unseen intrabar extremes are never replayed over observed ticks. Identical snapshots do nothing. Fill callbacks still exclude the unfinished bar.

A correction before the previous forming bar, removed history, changed settings or inputs rebuilds from the start using Strategy::prepare to reset decision state. Replayed fills before the previous forming bar are not returned again. An observed forming bar can be revised freely without a rebuild. Start a new Backtest for a different strategy instance.

§Panics

Panics if starting capital is not finite or bar timestamps are not strictly increasing.

Source§

impl Backtest

Source

pub fn new( name: impl Into<String>, symbol: impl Into<String>, timeframe: Timeframe, initial_capital: f64, ) -> Self

A backtest that fills market orders at the next bar’s open.

Source

pub fn run( &self, strategy: &mut dyn Strategy, bars: &[Bar], lower: &[Bar], ) -> StrategyReport

Runs strategy over bars and reports its trades, equity and assumptions.

lower supplies finer bars of the same symbol. Valid bars are walked in time order inside each chart bar; a chart bar without any falls back to its own path. Decisions and equity remain on the chart interval. Pass &[] to use chart bars alone.

With a start time, prepare still receives all bars, but chart bars opening before it cannot trade. Equity starts at the requested time and subsequent points use chart-bar closes, so the starting value and first close have distinct timestamps. A final execution bar without a known end labels its equity mark one nanosecond after its last source time.

§Panics

Panics if the starting capital is not finite.

Source

pub async fn run_async( &self, strategy: &mut dyn Strategy, bars: &[Bar], lower: &[Bar], ) -> StrategyReport

Runs the same fills as Self::run, yielding between batches of 256 chart or finer bars.

Poll from an executor or once per frame. Dropping the future cancels the run. Strategy preparation and individual callbacks remain synchronous, so hosts should keep them bounded.

§Panics

Panics if the starting capital is not finite.

Trait Implementations§

Source§

impl Clone for Backtest

Source§

fn clone(&self) -> Backtest

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Backtest

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Backtest

Source§

fn eq(&self, other: &Backtest) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Backtest

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSend for T
where T: Send + Sync + ?Sized,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

§

impl<T> SerializableAny for T
where T: 'static + Any + Clone + for<'a> Send + Sync,

§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(_simd: S, value: T) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.