Skip to content

openpine-vm 概述

openpine-vm 是編譯和執行 Pine Script 程式的 Rust crate。它提供了以 Instance 類型為中心的高階 API。

添加依賴

toml
[dependencies]
openpine-vm = { git = "https://github.com/longbridge/openpine.git" }

核心概念

執行模型

OpenPine 使用逐 K 線執行模型。你每次餵入一根 K 線的資料,VM 為每根 K 線執行整個指令碼。這與 Pine Script 在 TradingView 上的運作方式一致。

Candlestick 1 → Execute → Outputs updated
Candlestick 2 → Execute → Outputs updated
Candlestick 3 → Execute → Outputs updated
...

核心類型

類型描述
Instance已編譯的可執行腳本實例
InstanceBuilder用於設定和編譯腳本的建構器
Candlestick餵入 VM 的 OHLCV K 線資料
TimeFrame圖表時間週期(1D、5m、1W 等)
SymbolInfo交易標的元資料——由 DataProvider 自動提供,無需手動構造
DataProvider非同步 trait,為 request.security() 提供 K 線資料和標的資訊
CandlestickItemDataProvider::candlesticks yield 的列舉:Confirmed(candle)Realtime(candle)HistoryEnd
Chart視覺輸出集合(繪圖、標籤、線條等)
Event執行期間發出的日誌和警報事件
ScriptInfo已編譯腳本的元資料(類型、輸入、警報)
Error編譯或執行時錯誤

最小範例

rust
use openpine_vm::{Instance, TimeFrame};

#[tokio::main]
async fn main() -> Result<(), openpine_vm::Error> {
    // 1. 定義 Pine 腳本
    let source = r#"
//@version=6
indicator("SMA Crossover")
fast = ta.sma(close, 5)
slow = ta.sma(close, 20)
plot(fast, "Fast SMA", color.blue)
plot(slow, "Slow SMA", color.red)
plotshape(ta.crossover(fast, slow), style=shape.triangleup)
"#;

    // 2. 建構實例,直接傳入 K 線資料
    let timeframe = TimeFrame::days(1);
    let symbol = "NASDAQ:AAPL";
    let bars = load_candles(); // 你的資料來源——Vec<Candlestick>
    let mut instance = Instance::builder(bars, source, timeframe, symbol)
        .build().await?;

    // 3. 檢查編譯警告
    for warning in instance.warnings() {
        eprintln!("Warning: {}", warning.display_as_warning());
    }

    // 4. 執行腳本——從 provider 讀取所有 K 線
    instance.run_to_end(symbol, timeframe).await?;

    // 5. 讀取輸出
    for (_id, graph) in instance.chart().series_graphs() {
        if let Some(plot) = graph.as_plot() {
            let title = plot.title.as_deref().unwrap_or("unnamed");
            println!("Plot '{}': {} bars", title, plot.series.len());
        }
    }

    Ok(())
}

執行模型

Instance::run() 消費 DataProvider 的 K 線流,驅動整個執行迴圈:

DataProvider::candlesticks() 流
  Confirmed(_)  -> 已收盤的 K 線(bar_index 遞增,barstate.isconfirmed = true)
  Realtime(_)   -> 正在形成的 K 線(可回滾,流結束時自動確認)
  HistoryEnd    -> 標記歷史資料已全部推送完畢

instance.run() 回傳事件 Stream。使用 run_to_end() 消費所有事件後存取圖表,或直接消費流進行逐 K 線事件處理。

下一步

基於 MIT 許可證發佈。