Skip to main content

Instance

Struct Instance 

Source
pub struct Instance { /* private fields */ }
Expand description

An instance used to execute a compiled program.

Implementations§

Source§

impl Instance

Source

pub fn program(&self) -> &Program

Returns the compiled program held by this instance.

The Program is reference-counted (Arc internally) so cloning it is cheap. Used by providers to cache compiled programs across stream restarts.

Source

pub fn reset(&mut self)

Resets the instance to its post-build state, as if no bars had been executed.

All runtime state — variable series, chart visuals, events, strategy positions, security sub-states, and bar counters — is discarded and re-initialised from scratch. The compiled program, symbol/timeframe configuration, data provider, execution limits, and output mode are preserved unchanged.

Note: Input values that were overridden via InstanceBuilder::with_input_value are not preserved across a reset; inputs revert to their script-default values.

§Examples
let mut instance = instance
    .run_to_end("NASDAQ:AAPL", TimeFrame::days(1))
    .await?;
instance.reset();
// instance is now clean and ready to re-run
Source

pub fn warnings(&self) -> Warnings

Returns the warnings generated during compilation, bundled with source files so the caller can render them via Warnings::display().

Source

pub fn gc_collect_all(&mut self)

Runs a full garbage collection cycle on the GC arena.

Normally the VM collects incrementally during execution. Call this after a batch of bars to reclaim all unreachable GC objects at once.

Source

pub fn run(self, symbol: &str, timeframe: TimeFrame) -> RunHandle

Runs the script against the candlestick stream from the injected DataProvider, returning a RunHandle for iterating events.

The data provider’s from_time is determined automatically:

  • For fresh instances: 0 (beginning of available data).

  • For restored instances: last_bar_time + 1 (resume after the last confirmed bar in the snapshot).

  • CandlestickItem::Bar before HistoryEnd — treated as a confirmed bar, advances bar_index.

  • CandlestickItem::Bar after HistoryEnd — treated as a realtime bar; same-timestamp ticks become RealtimeUpdate automatically; confirmed at stream end.

  • CandlestickItem::HistoryEnd — emits Event::HistoryEnd.

Returns a handle that immediately yields None if no DataProvider was injected.

The returned RunHandle owns this instance and implements Deref/DerefMut targeting Instance, so instance methods such as save_state() can be called directly through the handle while iterating events. Recover the instance afterwards with RunHandle::into_instance.

Source

pub async fn run_to_end( self, symbol: &str, timeframe: TimeFrame, ) -> Result<Self, Error>

Runs the script to completion, discarding all events.

This is a convenience wrapper around run for callers that only need the final chart state.

Because run transfers ownership into the RunHandle, this method also consumes the instance and returns it after execution finishes.

Source

pub fn plot_rows(self, symbol: &str, timeframe: TimeFrame) -> PlotRowStream

Returns a PlotRowStream for iterating plot() outputs one bar at a time.

Call PlotRowStream::columns to obtain the column titles, then drive the stream with PlotRowStream::next_row. Only plot() outputs are included; other series such as bgcolor() or fill() are ignored.

§Panics

Panics if the instance is not configured with OutputMode::Stream.

Source

pub fn symbol_info(&self) -> &SymbolInfo

Returns a reference to the chart containing the visuals.

The [Chart] holds all plots, lines, labels, boxes, and other visuals produced by the script. Query it after calling execute().

§Examples
let chart = instance.chart();

// Iterate over per-bar series graphs (plot, bgcolor, fill, etc.)
for (id, series_graph) in chart.series_graphs() {
    if let Some(plot) = series_graph.as_plot() {
        println!("Plot '{:?}': {} bars", plot.title, plot.series.len());
    }
}

// Iterate over non-series graphs (label, line, box, table, etc.)
for (id, graph) in chart.graphs() {
    if let Some(label) = graph.as_label() {
        println!("Label at ({}, {}): {:?}", label.x, label.y, label.text);
    }
}

Returns the symbol info for the current chart symbol.

Source

pub fn chart(&self) -> &Chart

Returns the chart state produced by this instance.

Source

pub fn script_info(&self) -> &ScriptInfo

Returns a reference to the script info (script type, inputs, etc.).

Source

pub fn total_bars(&self) -> usize

Returns the total number of bars processed since execution started, including bars that have been truncated from memory.

Source

pub fn current_bar_confirmed(&self) -> bool

Returns whether the current bar has been confirmed.

Historical bars are always confirmed immediately after execution. Realtime bars become confirmed only after RealtimeConfirmed runs, either explicitly at stream end or automatically when a later realtime timestamp arrives.

Source

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

Returns the strategy backtest report, or None if the script is not a strategy.

Source

pub fn into_chart(self) -> Chart

Consumes the instance and returns the chart data.

This avoids cloning the chart when the instance is no longer needed (e.g. in a WASM playground that only needs the chart for rendering).

Source§

impl Instance

Source

pub fn builder<P>( provider: P, source: impl Into<String>, timeframe: TimeFrame, symbol: impl Into<String>, ) -> InstanceBuilder
where P: DataProvider + 'static,

Creates a new InstanceBuilder for the given source code.

provider supplies the main chart K-lines and any request.security() data. For simple single-symbol backtests pass a Vec<Candlestick> directly; for live or multi-symbol data implement DataProvider.

The source is compiled when InstanceBuilder::build is called.

Source§

impl Instance

Source

pub fn builder_from_program<P>( program: Program, provider: P, timeframe: TimeFrame, symbol: impl Into<String>, ) -> InstanceBuilderFromProgram
where P: DataProvider + 'static,

Creates a new InstanceBuilderFromProgram from an already-compiled Program, skipping source compilation.

Use this when you compile a program once and want to reuse it across multiple instances (e.g. different providers or input configurations).

provider supplies the main chart K-lines and any request.security() data.

Source§

impl Instance

Source

pub fn restore_state(data: &[u8]) -> Result<RestoreBuilder, SnapshotError>

Deserializes a snapshot and returns a RestoreBuilder for configuring optional parameters before completing the restore.

§Errors

Returns SnapshotError::Decode if decoding fails, or SnapshotError::VersionMismatch if the snapshot version does not match the current build.

Source§

impl Instance

Source

pub fn save_state(&mut self) -> Result<Vec<u8>, SnapshotError>

Serializes the current VM state to a binary blob.

The returned bytes encode the full program, all variables, inputs, GC-heap objects, chart, strategy state, and configuration. Pass them to Instance::restore_state to resume execution.

The current realtime bar must be confirmed before calling this method (e.g. by executing ExecuteMode::Confirm). Returns SnapshotError::UnconfirmedBar otherwise.

Candlestick data is not included in the snapshot. When run() is called on a restored instance, the VM automatically passes last_bar_time + 1 to the data provider.

§Errors

Returns SnapshotError::UnconfirmedBar if the current bar has not been confirmed, or SnapshotError::Encode if postcard serialization fails.

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
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> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V