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 warnings(&self) -> &[CompileError]

Returns the warnings generated during compilation.

Source

pub fn run( &mut self, symbol: &str, timeframe: TimeFrame, ) -> impl Stream<Item = Result<Event, Error>> + '_

Runs the script against the full candlestick stream supplied by the injected DataProvider, starting from the beginning of available data.

This is equivalent to calling run_from with from_time = 0.

Returns immediately with Ok(()) if no DataProvider was passed to Instance::builder. Returns a stream of events produced by running the script against the candlestick stream from the injected DataProvider.

Equivalent to run_from with from_time = 0.

Source

pub fn run_from( &mut self, symbol: &str, timeframe: TimeFrame, from_time: i64, ) -> impl Stream<Item = Result<Event, Error>> + '_

Returns a stream of events produced by running the script, starting at from_time.

Each bar’s execution yields Event::BarStart, any log/alert/draw events, then Event::BarEnd. The stream yields Event::HistoryEnd when the boundary marker is received.

Source

pub async fn run_to_end( &mut self, symbol: &str, timeframe: TimeFrame, ) -> Result<(), 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.

Source

pub async fn run_from_to_end( &mut self, symbol: &str, timeframe: TimeFrame, from_time: i64, ) -> Result<(), Error>

Runs the script to completion starting at from_time, discarding all events.

Source

pub fn chart(&self) -> &Chart

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);
    }
}
Source

pub fn script_info(&self) -> &ScriptInfo

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

Source

pub fn candlesticks(&self) -> &Series<Candlestick>

Returns a reference to the candlestick series accumulated during execution.

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<'a, P>( provider: P, source: &'a str, timeframe: TimeFrame, symbol: impl Into<String>, ) -> InstanceBuilder<'a, ()>
where P: DataProvider + 'static,

Creates a new InstanceBuilder for the given provider, source, timeframe and symbol string.

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

§Examples
use openpine_vm::{Candlestick, Instance, TimeFrame, TradeSession};

let source = r#"
    //@version=6
    indicator("My Script")
    plot(close)
"#;
let bar = Candlestick::new(
    1_700_000_000_000,
    150.0,
    155.0,
    149.0,
    153.0,
    1_000_000.0,
    0.0,
    TradeSession::Regular,
);
let provider = vec![bar];
let mut instance = Instance::builder(provider, source, TimeFrame::days(1), "NASDAQ:AAPL")
    .with_path("my_script.pine")
    .build()
    .await?;

instance
    .run_to_end("NASDAQ:AAPL", TimeFrame::days(1))
    .await?;

let chart = instance.chart();
for (id, graph) in chart.series_graphs() {
    println!("Graph {:?}: {:?}", id, graph);
}
Source

pub fn builder_from_project<'a, P>( provider: P, project: &'a Project, timeframe: TimeFrame, symbol: impl Into<String>, ) -> InstanceBuilder<'a, ()>
where P: DataProvider + 'static,

Creates a new InstanceBuilder from an already-loaded [Project].

Skips the parse + load phase, going straight to optimize + compile when InstanceBuilder::build() is called. This is useful when the caller has already loaded the project (e.g. to share a cached LoadResult between compilation and LSP analysis).

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.

§Errors

Returns SnapshotError::Encode if bincode 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
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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