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
| Type | Description |
|---|---|
Instance | A running script. Owns the compiled program and all VM state. |
InstanceBuilder | Compiles a Pine Script source string into an Instance. |
Candlestick | One OHLCV bar. |
CandlestickItem | Stream item yielded by DataProvider::candlesticks (Confirmed, Realtime, or HistoryEnd). |
DataProvider | Supplies candlestick data and symbol metadata to the VM. Implemented for Vec<Candlestick>. |
SymbolInfo | Symbol metadata (syminfo.* built-ins). |
TimeFrame | Bar interval (e.g. TimeFrame::days(1)). |
visuals::Chart | Accumulates all visual outputs (plots, lines, labels, …). |
script_info::ScriptInfo | Script metadata extracted at compile time (type, inputs, alerts). |
Error | Top-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:
CandlestickItem::Confirmedbars advancebar_index;barstate.ishistoryistrue.CandlestickItem::Realtimebars may be updated multiple times (each tick). A new timestamp triggers automatic confirmation of the previous bar. When the stream ends on aRealtimebar, it is confirmed automatically.CandlestickItem::HistoryEndis a boundary marker; the VM skips it.
§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§
- Alert
Event - An alert event emitted by
alert()/alertcondition-like behavior. - Backtrace
- A complete runtime call stack captured when an exception occurs.
- Backtrace
Frame - A single frame in a runtime call stack.
- BarStart
Event - Emitted at the start of each bar’s execution.
- Candlestick
- OHLCV candlestick data used as VM input.
- Compile
Error - A single compiler error bundling a diagnostic with the source files.
- Compile
Errors - A collection of compiler errors.
- Error
Display - A formatted, optionally colorized diagnostic for an [
Error]. - Exception
- A runtime exception.
- Execution
Limits - Configures runtime execution limits for the VM.
- Identity
Currency Converter - A no-op converter that returns the input value unchanged.
- Input
Sessions - Instance execution options.
- Instance
- An instance used to execute a compiled program.
- Instance
Builder - Builder for compiling a script into an executable
Instance. - Last
Info - The last information about the input candlesticks. Metadata about the last available input bar.
- LogEvent
- A log event emitted by script execution.
- Parse
Time Frame Error - Error returned when parsing a
TimeFramefails. - Parse
Time Zone Error - Error returned when parsing a
TimeZonefails. - Partial
Symbol Info - Partial symbol metadata returned by
DataProvider::symbol_info. - Series
- A bar-aligned series of values.
- Symbol
Info - Symbol metadata used by
syminfo.*builtins. - Time
Frame - Represents a timeframe with a quantity and a unit.
- Unknown
Market Error - An error occurs when an unknown market string is encountered.
Enums§
- BarState
- Describes the execution phase of the current bar.
- Candlestick
Item - An item yielded by
DataProvider::candlesticks. - Close
Entries Rule - Strategy rule used to choose which open entries are closed.
- Commission
Type - Strategy commission calculation mode.
- Create
Symbol Info Error - Errors returned when creating a
SymbolInfo. - Currency
- Currency codes as per ISO 4217 standard.
- Data
Provider Error - Error returned by
DataProvidermethods. - Direction
- Trade direction used by strategies.
- Draw
Event - 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.
- Output
Mode - Controls how series graph data is produced during execution.
- Quantity
Type - Strategy order quantity mode.
- Symbol
Type - The type of market the symbol belongs to.
- Time
Unit - Unit component of a
TimeFrame. - Time
Zone - A parsed timezone representation.
- Trade
Session - Represents different trading sessions within a market day. Trading session identifier.
- Volume
Type - How volume values should be interpreted.
Traits§
- Currency
Converter - Converts monetary values between currencies.
- Data
Provider - Supplies candlestick data and symbol metadata to the VM.
Functions§
- script_
info - Compile a script from source and return its
ScriptInfowithout building anInstanceor requiring a data provider. - script_
info_ from_ project - Return
ScriptInfofrom an already-loaded [Project] without building anInstanceor requiring a data provider.