openpine_vm/
lib.rs

1#![deny(private_interfaces, unreachable_pub)]
2#![warn(missing_docs)]
3
4//! OpenPine virtual machine.
5//!
6//! This crate provides the runtime used to execute compiled OpenPine programs.
7//! It includes the execution engine, built-in types, and the data structures
8//! used to collect script outputs (e.g. plots and other visuals).
9//!
10//! # Key types
11//!
12//! | Type | Description |
13//! |------|-------------|
14//! | [`Instance`] | A running script. Owns the compiled program and all VM state. |
15//! | [`InstanceBuilder`] | Compiles a Pine Script source string into an [`Instance`]. |
16//! | [`Candlestick`] | One OHLCV bar. |
17//! | [`CandlestickItem`] | Stream item yielded by `DataProvider::candlesticks` (`Confirmed`, `Realtime`, or `HistoryEnd`). |
18//! | [`DataProvider`] | Supplies candlestick data and symbol metadata to the VM. Implemented for `Vec<Candlestick>`. |
19//! | [`SymbolInfo`] | Symbol metadata (`syminfo.*` built-ins). |
20//! | [`TimeFrame`] | Bar interval (e.g. `TimeFrame::days(1)`). |
21//! | [`visuals::Chart`] | Accumulates all visual outputs (plots, lines, labels, …). |
22//! | [`script_info::ScriptInfo`] | Script metadata extracted at compile time (type, inputs, alerts). |
23//! | [`Error`] | Top-level error type covering both compilation and runtime failures. |
24//!
25//! The compiled [`Program`](openpine_compiler::program::Program) is embedded
26//! inside `Instance` and is not directly manipulated at this layer.
27//!
28//! # Basic usage
29//!
30//! ```rust,ignore
31//! use openpine_vm::{Candlestick, Instance, TimeFrame, TradeSession};
32//!
33//! let source = r#"
34//!     //@version=6
35//!     indicator("SMA", overlay=true)
36//!     plot(ta.sma(close, 20))
37//! "#;
38//!
39//! // 1. Collect historical bars (Vec<Candlestick> implements DataProvider).
40//! let bars: Vec<Candlestick> = historical_bars;
41//!
42//! // 2. Compile the script into a runnable Instance.
43//! let mut instance = Instance::builder(bars, source, TimeFrame::days(1), "NASDAQ:AAPL")
44//!     .build()
45//!     .await?;
46//!
47//! // 3. Run the script — feeds all bars from the provider.
48//! instance.run_to_end("NASDAQ:AAPL", TimeFrame::days(1)).await?;
49//!
50//! // 4. Read visual outputs.
51//! let chart = instance.chart();
52//! for (_id, series_graph) in chart.series_graphs() {
53//!     if let Some(plot) = series_graph.as_plot() {
54//!         println!("{:?}: {} values", plot.title, plot.series.len());
55//!     }
56//! }
57//! # Ok::<(), openpine_vm::Error>(())
58//! ```
59//!
60//! # Execution model
61//!
62//! Pine Script executes **bar by bar**. [`Instance::run`] feeds each bar from
63//! the [`DataProvider`] stream:
64//!
65//! - [`CandlestickItem::Confirmed`] bars advance `bar_index`;
66//!   `barstate.ishistory` is `true`.
67//! - [`CandlestickItem::Realtime`] bars may be updated multiple times (each
68//!   tick). A new timestamp triggers automatic confirmation of the previous
69//!   bar. When the stream ends on a `Realtime` bar, it is confirmed
70//!   automatically.
71//! - [`CandlestickItem::HistoryEnd`] is a boundary marker; the VM skips it.
72//!
73//! # Overriding inputs
74//!
75//! Script inputs declared with `input.*()` can be overridden at build time:
76//!
77//! ```rust,ignore
78//! let instance = Instance::builder(provider, source, timeframe, "NASDAQ:AAPL")
79//!     .with_input_value(0, 50_i64)   // override first input (e.g. "Length") to 50
80//!     .build()
81//!     .await?;
82//! ```
83//!
84//! Use [`script_info()`] to inspect available inputs and their
85//! types before building.
86//!
87//! # Strategy scripts
88//!
89//! Strategy scripts (`strategy(…)`) are handled identically to indicators at
90//! the API level. After feeding all bars, call [`Instance::strategy_report`]
91//! to retrieve the backtest summary.
92//!
93//! # Snapshots
94//!
95//! See the [`snapshot`] module for how to checkpoint and restore VM state,
96//! which is useful for avoiding full historical replays on server restarts.
97
98mod bar_state;
99mod context;
100mod currency;
101pub(crate) mod data_provider;
102mod draw_event;
103mod error;
104mod events;
105mod execution_limits;
106pub(crate) mod gc_serde;
107mod inst_executor;
108mod instance;
109mod instance_builder;
110mod instructions;
111mod market;
112mod native_funcs;
113pub(crate) mod objects;
114mod output_mode;
115mod quote_types;
116mod raw_value;
117mod rollback;
118/// Metadata extracted from a compiled script (inputs, script type, alerts).
119pub mod script_info;
120pub(crate) mod security;
121mod series;
122/// Save and restore VM instance state.
123pub mod snapshot;
124mod state;
125mod str_format;
126mod strategy;
127mod symbol;
128mod symbol_info;
129mod ticker_expr;
130mod time;
131/// Types describing visual outputs (plots, lines, labels, etc.).
132pub mod visuals;
133
134pub use bar_state::BarState;
135pub use currency::*;
136pub use data_provider::{DataProvider, DataProviderError, PartialSymbolInfo};
137pub use draw_event::DrawEvent;
138pub use error::*;
139pub use events::*;
140pub use execution_limits::*;
141pub use instance::*;
142pub use instance_builder::*;
143pub use market::*;
144pub use openpine_compiler::{CompileError, CompileErrors, loader};
145pub use openpine_error::ErrorDisplay;
146pub use output_mode::OutputMode;
147pub use quote_types::*;
148pub use series::*;
149pub use strategy::*;
150pub use symbol_info::*;
151pub use time::*;