Crate openpine_vm

Source
Expand description

OpenPine virtual machine.

This crate provides the runtime used to execute compiled OpenPine programs. It includes the execution engine, built-in types, and the data structures used to collect script outputs (e.g. plots and other visuals).

§Key types

TypeDescription
InstanceA running script. Owns the compiled program and all VM state.
InstanceBuilderCompiles a Pine Script source string into an Instance.
CandlestickOne OHLCV bar.
CandlestickItemStream item yielded by DataProvider::candlesticks (Confirmed, Realtime, or HistoryEnd).
DataProviderSupplies candlestick data and symbol metadata to the VM. Implemented for Vec<Candlestick>.
SymbolInfoSymbol metadata (syminfo.* built-ins).
TimeFrameBar interval (e.g. TimeFrame::days(1)).
visuals::ChartAccumulates all visual outputs (plots, lines, labels, …).
script_info::ScriptInfoScript metadata extracted at compile time (type, inputs, alerts).
ErrorTop-level error type covering both compilation and runtime failures.

The compiled Program is embedded inside Instance and is not directly manipulated at this layer.

§Basic usage

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

let source = r#"
    //@version=6
    indicator("SMA", overlay=true)
    plot(ta.sma(close, 20))
"#;

// 1. Collect historical bars (Vec<Candlestick> implements DataProvider).
let bars: Vec<Candlestick> = historical_bars;

// 2. Compile the script into a runnable Instance.
let mut instance = Instance::builder(bars, source, TimeFrame::days(1), "NASDAQ:AAPL")
    .build()
    .await?;

// 3. Run the script — feeds all bars from the provider.
instance.run_to_end("NASDAQ:AAPL", TimeFrame::days(1)).await?;

// 4. Read visual outputs.
let chart = instance.chart();
for (_id, series_graph) in chart.series_graphs() {
    if let Some(plot) = series_graph.as_plot() {
        println!("{:?}: {} values", plot.title, plot.series.len());
    }
}

§Execution model

Pine Script executes bar by bar. Instance::run feeds each bar from the DataProvider stream:

§Overriding inputs

Script inputs declared with input.*() can be overridden at build time:

let instance = Instance::builder(provider, source, timeframe, "NASDAQ:AAPL")
    .with_input_value(0, 50_i64)   // override first input (e.g. "Length") to 50
    .build()
    .await?;

Use script_info() to inspect available inputs and their types before building.

§Strategy scripts

Strategy scripts (strategy(…)) are handled identically to indicators at the API level. After feeding all bars, call Instance::strategy_report to retrieve the backtest summary.

§Snapshots

See the snapshot module for how to checkpoint and restore VM state, which is useful for avoiding full historical replays on server restarts.

Re-exports§

pub use openpine_compiler::loader;

Modules§

report
Strategy report data structures for exporting backtest results.
script_info
Metadata extracted from a compiled script (inputs, script type, alerts).
snapshot
Save and restore VM instance state. Save and restore VM instance state.
visuals
Types describing visual outputs (plots, lines, labels, etc.).

Structs§

AlertEvent
An alert event emitted by alert()/alertcondition-like behavior.
Backtrace
A complete runtime call stack captured when an exception occurs.
BacktraceFrame
A single frame in a runtime call stack.
BarStartEvent
Emitted at the start of each bar’s execution.
Candlestick
OHLCV candlestick data used as VM input.
CompileError
A single compiler error bundling a diagnostic with the source files.
CompileErrors
A collection of compiler errors.
ErrorDisplay
A formatted, optionally colorized diagnostic for an [Error].
Exception
A runtime exception.
ExecutionLimits
Configures runtime execution limits for the VM.
IdentityCurrencyConverter
A no-op converter that returns the input value unchanged.
InputSessions
Instance execution options.
Instance
An instance used to execute a compiled program.
InstanceBuilder
Builder for compiling a script into an executable Instance.
LastInfo
The last information about the input candlesticks. Metadata about the last available input bar.
LogEvent
A log event emitted by script execution.
ParseTimeFrameError
Error returned when parsing a TimeFrame fails.
ParseTimeZoneError
Error returned when parsing a TimeZone fails.
PartialSymbolInfo
Partial symbol metadata returned by DataProvider::symbol_info.
Series
A bar-aligned series of values.
SymbolInfo
Symbol metadata used by syminfo.* builtins.
TimeFrame
Represents a timeframe with a quantity and a unit.
UnknownMarketError
An error occurs when an unknown market string is encountered.

Enums§

BarState
Describes the execution phase of the current bar.
CandlestickItem
An item yielded by DataProvider::candlesticks.
CloseEntriesRule
Strategy rule used to choose which open entries are closed.
CommissionType
Strategy commission calculation mode.
CreateSymbolInfoError
Errors returned when creating a SymbolInfo.
Currency
Currency codes as per ISO 4217 standard.
DataProviderError
Error returned by DataProvider methods.
Direction
Trade direction used by strategies.
DrawEvent
A drawing event emitted during VM execution.
Error
Errors that can occur while building or executing an Instance.
Event
An event generated during VM execution.
LogLevel
Logging severity used by LogEvent.
Market
Represents various stock markets.
OutputMode
Controls how series graph data is produced during execution.
QuantityType
Strategy order quantity mode.
SymbolType
The type of market the symbol belongs to.
TimeUnit
Unit component of a TimeFrame.
TimeZone
A parsed timezone representation.
TradeSession
Represents different trading sessions within a market day. Trading session identifier.
VolumeType
How volume values should be interpreted.

Traits§

CurrencyConverter
Converts monetary values between currencies.
DataProvider
Supplies candlestick data and symbol metadata to the VM.

Functions§

script_info
Compile a script from source and return its ScriptInfo without building an Instance or requiring a data provider.
script_info_from_project
Return ScriptInfo from an already-loaded [Project] without building an Instance or requiring a data provider.