Expand description
Navi virtual machine.
This crate provides the runtime used to execute compiled Navi 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 an Navi 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 navi_vm::{Candlestick, Instance, TimeFrame, TradeSession};
let source = r#"
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 instance = Instance::builder(bars, source, TimeFrame::days(1), "NASDAQ:AAPL")
.build()
.await?
.run_to_end("NASDAQ:AAPL", TimeFrame::days(1))
.await?;
// 3. 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
Navi executes bar by bar. Instance::run feeds each bar
from the DataProvider stream:
CandlestickItem::BarbeforeHistoryEnd— treated as a confirmed bar;barstate.ishistoryistrue.CandlestickItem::BarafterHistoryEnd— treated as a realtime bar; may be updated multiple times (same timestamp = tick update). A new timestamp triggers automatic confirmation of the previous bar. When the stream ends on a realtime bar, it is confirmed automatically.CandlestickItem::HistoryEndemits anEvent::HistoryEndevent.
§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 navi_compiler::loader;pub use navi_visuals as visuals;
Modules§
- report
- Strategy report data structures for exporting backtest results. Strategy report data structures for exporting backtest results. 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.
Structs§
- Alert
Event - An alert event emitted by
alert()/alertcondition-like behavior. - AuxData
Point - A single timestamped data point in an auxiliary data stream.
- Backtrace
Frame - One frame in a runtime call-stack backtrace.
- BarStart
Event - Emitted at the start of each bar’s execution.
- Candlestick
- OHLCV candlestick data used as VM input.
- Event
Compaction Rules - Configuration rules for
EventCompactor. - Event
Compactor - Incremental compactor that tracks realtime bar lifecycle.
- Execution
Limits - Configures runtime execution limits for the VM.
- Input
Sessions - Controls which trading sessions are accepted as input bars.
- Instance
- An instance used to execute a compiled program.
- Instance
Builder - Builder that compiles Navi source and produces an executable
Instance. - Instance
Builder From Program - Builder that produces an
Instancefrom an already-compiledProgram, skipping source compilation entirely. - Invalid
Symbol Error - An error that occurs when an invalid symbol format is encountered.
- Last
Info - The last information about the input candlesticks. Metadata about the last available input bar.
- LogEvent
- A log event emitted by script execution.
- Native
Funcs - Registry of native functions implemented by
navi-vm. - 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. - Plot
RowStream - An iterator over per-bar
plot()rows returned byInstance::plot_rows. - Program
- The compiled program representation.
- Realtime
Confirmed Info - Information about a confirmed realtime bar.
- RunHandle
- A handle to an active execution run returned by
Instance::run. - Runtime
Error - Runtime exception raised during script execution.
- Series
- A bar-aligned series of values.
- Strategy
Accumulator - Reconstructs a
StrategyReportfrom a stream ofStrategyEvents. - Strategy
Config Override - Partial override for strategy execution parameters.
- Symbol
- A parsed
PREFIX:TICKERsymbol identifier (e.g."NASDAQ:AAPL"). - Symbol
Info - Symbol metadata used by
syminfo.*builtins. - Syminfo
Fields - Bitset of
syminfoproperty fields requested by a compiled script. - Tick
- A single market tick (one trade event).
- Time
Frame - Represents a timeframe with a quantity and a unit.
- Unknown
Market Error - Error returned when parsing an unknown market string.
Enums§
- AuxData
Item - An item yielded by auxiliary data streams (currency rates, financials, etc.).
- BarState
- Describes the execution phase of the current bar.
- Candlestick
Item - An item yielded by a data provider’s candlestick stream.
- Close
Entries Rule - Strategy rule used to choose which open entries are closed.
- Commission
Type - Strategy commission calculation mode.
Percent=0, CashPerOrder=1, CashPerContract=2 matches Navi
CommissionTypeenum. - Currency
- Currency codes as per ISO 4217 standard.
- Data
Provider Error - Error returned by
DataProvidermethods. - Direction
- Trade direction used by strategies.
- Dividends
Field - Field selector for [
DataProvider::dividends]. Gross=0, Net=1 — matches NaviDividendsFieldenum. - Draw
Event - A drawing event emitted during VM execution.
- Earnings
Field - Field selector for [
DataProvider::earnings]. Actual=0, Estimate=1, Standardized=2 — matches NaviEarningsFieldenum. - Error
- Unified error type for script compilation and execution.
- Event
- An event generated during VM execution.
- LogLevel
- Logging severity used by
LogEvent. - Market
- A supported stock exchange.
- Order
Type - Order type for strategy orders.
- Output
Mode - Controls how series graph data is produced during execution.
- Quantity
Type - Strategy order quantity mode.
PercentOfEquity=0, Fixed=1, Cash=2 matches Navi
DefaultQtyTypeenum. - Realtime
Confirm Reason - Reason why a realtime bar was confirmed.
- Splits
Field - Field selector for [
DataProvider::splits]. Numerator=0, Denominator=1 — matches NaviSplitsFieldenum. - Strategy
Event - Events emitted by the strategy engine during execution.
- Symbol
Type - The type of market the symbol belongs to.
- Tick
Item - An item yielded by a data provider’s tick stream ([
DataProvider::ticks]). - Time
Unit - Unit component of a
TimeFrame. - Time
Zone - A parsed timezone representation.
- Trade
Session - Represents different trading sessions within a market day.
- Volume
Type - How volume values should be interpreted.
Traits§
- Data
Provider - Supplies candlestick data and symbol metadata to the VM.
- Event
Compaction Sink - Callback interface for
EventCompactor. - History
Provider - Supplies older historical bars for incremental history extension.
Functions§
- script_
info - Compile a script from source and return its
ScriptInfo. - script_
info_ from_ project - Return
ScriptInfofrom an already-loaded [Project]. - version
- Returns the version of the
navi-vmcrate (e.g."0.2.0").