pub struct Instance { /* private fields */ }Expand description
An instance used to execute a compiled program.
Implementations§
Source§impl Instance
impl Instance
Sourcepub fn program(&self) -> &Program
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.
Sourcepub fn reset(&mut self)
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_valueare 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-runSourcepub fn warnings(&self) -> Warnings
pub fn warnings(&self) -> Warnings
Returns the warnings generated during compilation, bundled with
source files so the caller can render them via Warnings::display().
Sourcepub fn gc_collect_all(&mut self)
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.
Sourcepub fn run(self, symbol: &str, timeframe: TimeFrame) -> RunHandle
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::BarbeforeHistoryEnd— treated as a confirmed bar, advancesbar_index. -
CandlestickItem::BarafterHistoryEnd— treated as a realtime bar; same-timestamp ticks becomeRealtimeUpdateautomatically; confirmed at stream end.
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.
Sourcepub fn plot_rows(self, symbol: &str, timeframe: TimeFrame) -> PlotRowStream
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.
Sourcepub fn symbol_info(&self) -> &SymbolInfo
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.
Sourcepub fn script_info(&self) -> &ScriptInfo
pub fn script_info(&self) -> &ScriptInfo
Returns a reference to the script info (script type, inputs, etc.).
Sourcepub fn total_bars(&self) -> usize
pub fn total_bars(&self) -> usize
Returns the total number of bars processed since execution started, including bars that have been truncated from memory.
Sourcepub fn current_bar_confirmed(&self) -> bool
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.
Sourcepub fn strategy_report(&self) -> Option<StrategyReport>
pub fn strategy_report(&self) -> Option<StrategyReport>
Returns the strategy backtest report, or None if the script is
not a strategy.
Sourcepub fn into_chart(self) -> Chart
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
impl Instance
Sourcepub fn builder<P>(
provider: P,
source: impl Into<String>,
timeframe: TimeFrame,
symbol: impl Into<String>,
) -> InstanceBuilderwhere
P: DataProvider + 'static,
pub fn builder<P>(
provider: P,
source: impl Into<String>,
timeframe: TimeFrame,
symbol: impl Into<String>,
) -> InstanceBuilderwhere
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
impl Instance
Sourcepub fn builder_from_program<P>(
program: Program,
provider: P,
timeframe: TimeFrame,
symbol: impl Into<String>,
) -> InstanceBuilderFromProgramwhere
P: DataProvider + 'static,
pub fn builder_from_program<P>(
program: Program,
provider: P,
timeframe: TimeFrame,
symbol: impl Into<String>,
) -> InstanceBuilderFromProgramwhere
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
impl Instance
Sourcepub fn restore_state(data: &[u8]) -> Result<RestoreBuilder, SnapshotError>
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
impl Instance
Sourcepub fn save_state(&mut self) -> Result<Vec<u8>, SnapshotError>
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§
impl Freeze for Instance
impl !RefUnwindSafe for Instance
impl !Send for Instance
impl !Sync for Instance
impl Unpin for Instance
impl UnsafeUnpin for Instance
impl !UnwindSafe for Instance
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read more§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.