Skip to main content

Crate navi_vm

Crate navi_vm 

Source
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

TypeDescription
InstanceA running script. Owns the compiled program and all VM state.
InstanceBuilderCompiles an Navi 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::Chart]Accumulates 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 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::Bar before HistoryEnd — treated as a confirmed bar; barstate.ishistory is true.
  • CandlestickItem::Bar after HistoryEnd — 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::HistoryEnd emits an Event::HistoryEnd event.

§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§

AlertEvent
An alert event emitted by alert()/alertcondition-like behavior.
AuxDataPoint
A single timestamped data point in an auxiliary data stream.
BacktraceFrame
One frame in a runtime call-stack backtrace.
BarStartEvent
Emitted at the start of each bar’s execution.
Candlestick
OHLCV candlestick data used as VM input.
EventCompactionRules
Configuration rules for EventCompactor.
EventCompactor
Incremental compactor that tracks realtime bar lifecycle.
ExecutionLimits
Configures runtime execution limits for the VM.
InputSessions
Controls which trading sessions are accepted as input bars.
Instance
An instance used to execute a compiled program.
InstanceBuilder
Builder that compiles Navi source and produces an executable Instance.
InstanceBuilderFromProgram
Builder that produces an Instance from an already-compiled Program, skipping source compilation entirely.
InvalidSymbolError
An error that occurs when an invalid symbol format is encountered.
LastInfo
The last information about the input candlesticks. Metadata about the last available input bar.
LogEvent
A log event emitted by script execution.
NativeFuncs
Registry of native functions implemented by navi-vm.
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.
PlotRowStream
An iterator over per-bar plot() rows returned by Instance::plot_rows.
Program
The compiled program representation.
RealtimeConfirmedInfo
Information about a confirmed realtime bar.
RunHandle
A handle to an active execution run returned by Instance::run.
RuntimeError
Runtime exception raised during script execution.
Series
A bar-aligned series of values.
StrategyAccumulator
Reconstructs a StrategyReport from a stream of StrategyEvents.
StrategyConfigOverride
Partial override for strategy execution parameters.
Symbol
A parsed PREFIX:TICKER symbol identifier (e.g. "NASDAQ:AAPL").
SymbolInfo
Symbol metadata used by syminfo.* builtins.
SyminfoFields
Bitset of syminfo property fields requested by a compiled script.
Tick
A single market tick (one trade event).
TimeFrame
Represents a timeframe with a quantity and a unit.
UnknownMarketError
Error returned when parsing an unknown market string.

Enums§

AuxDataItem
An item yielded by auxiliary data streams (currency rates, financials, etc.).
BarState
Describes the execution phase of the current bar.
CandlestickItem
An item yielded by a data provider’s candlestick stream.
CloseEntriesRule
Strategy rule used to choose which open entries are closed.
CommissionType
Strategy commission calculation mode. Percent=0, CashPerOrder=1, CashPerContract=2 matches Navi CommissionType enum.
Currency
Currency codes as per ISO 4217 standard.
DataProviderError
Error returned by DataProvider methods.
Direction
Trade direction used by strategies.
DividendsField
Field selector for [DataProvider::dividends]. Gross=0, Net=1 — matches Navi DividendsField enum.
DrawEvent
A drawing event emitted during VM execution.
EarningsField
Field selector for [DataProvider::earnings]. Actual=0, Estimate=1, Standardized=2 — matches Navi EarningsField enum.
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.
OrderType
Order type for strategy orders.
OutputMode
Controls how series graph data is produced during execution.
QuantityType
Strategy order quantity mode. PercentOfEquity=0, Fixed=1, Cash=2 matches Navi DefaultQtyType enum.
RealtimeConfirmReason
Reason why a realtime bar was confirmed.
SplitsField
Field selector for [DataProvider::splits]. Numerator=0, Denominator=1 — matches Navi SplitsField enum.
StrategyEvent
Events emitted by the strategy engine during execution.
SymbolType
The type of market the symbol belongs to.
TickItem
An item yielded by a data provider’s tick stream ([DataProvider::ticks]).
TimeUnit
Unit component of a TimeFrame.
TimeZone
A parsed timezone representation.
TradeSession
Represents different trading sessions within a market day.
VolumeType
How volume values should be interpreted.

Traits§

DataProvider
Supplies candlestick data and symbol metadata to the VM.
EventCompactionSink
Callback interface for EventCompactor.
HistoryProvider
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 ScriptInfo from an already-loaded [Project].
version
Returns the version of the navi-vm crate (e.g. "0.2.0").