Expose strategy runtime data APIs

This commit is contained in:
boris
2026-04-23 19:29:12 -07:00
parent 1760fc6cd1
commit c3ef0bd49a
9 changed files with 678 additions and 6 deletions

View File

@@ -7,9 +7,10 @@ use std::sync::OnceLock;
use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use crate::cost::ChinaAShareCostModel;
use crate::data::{DataSet, IntradayExecutionQuote, PriceField};
use crate::data::{DailyMarketSnapshot, DataSet, IntradayExecutionQuote, PriceField};
use crate::engine::BacktestError;
use crate::events::{OrderSide, ProcessEvent};
use crate::instrument::Instrument;
use crate::portfolio::PortfolioState;
use crate::scheduler::ScheduleRule;
use crate::universe::{DynamicMarketCapBandSelector, SelectionContext, UniverseSelector};
@@ -86,9 +87,18 @@ pub struct StrategyContext<'a> {
pub subscriptions: &'a BTreeSet<String>,
pub process_events: &'a [ProcessEvent],
pub active_process_event: Option<&'a ProcessEvent>,
pub active_datetime: Option<NaiveDateTime>,
}
impl StrategyContext<'_> {
pub fn current_datetime(&self) -> Option<NaiveDateTime> {
self.active_datetime
}
pub fn current_time(&self) -> Option<NaiveTime> {
self.active_datetime.map(|value| value.time())
}
pub fn has_open_orders(&self) -> bool {
!self.open_orders.is_empty()
}
@@ -200,6 +210,81 @@ impl StrategyContext<'_> {
}
}
pub fn current_snapshot(&self, symbol: &str) -> Option<&DailyMarketSnapshot> {
self.data.market(self.execution_date, symbol)
}
pub fn history_bars(
&self,
symbol: &str,
bar_count: usize,
frequency: &str,
field: &str,
include_now: bool,
) -> Vec<f64> {
self.data.history_bars_at(
self.execution_date,
self.active_datetime,
symbol,
bar_count,
frequency,
field,
include_now,
)
}
pub fn history_daily_snapshots(
&self,
symbol: &str,
bar_count: usize,
include_now: bool,
) -> Vec<DailyMarketSnapshot> {
self.data
.history_daily_snapshots(self.execution_date, symbol, bar_count, include_now)
}
pub fn history_intraday_quotes(
&self,
symbol: &str,
bar_count: usize,
include_now: bool,
) -> Vec<IntradayExecutionQuote> {
self.data.history_intraday_quotes_at(
self.execution_date,
self.active_datetime,
symbol,
bar_count,
include_now,
)
}
pub fn instrument(&self, symbol: &str) -> Option<&Instrument> {
self.data.instrument(symbol)
}
pub fn instruments(&self, symbols: &[&str]) -> Vec<&Instrument> {
symbols
.iter()
.filter_map(|symbol| self.data.instrument(symbol))
.collect()
}
pub fn all_instruments(&self) -> Vec<&Instrument> {
self.data.all_instruments()
}
pub fn get_trading_dates(&self, start: NaiveDate, end: NaiveDate) -> Vec<NaiveDate> {
self.data.trading_dates(start, end)
}
pub fn get_previous_trading_date(&self, date: NaiveDate, n: usize) -> Option<NaiveDate> {
self.data.previous_trading_date(date, n)
}
pub fn get_next_trading_date(&self, date: NaiveDate, n: usize) -> Option<NaiveDate> {
self.data.next_trading_date(date, n)
}
pub fn has_subscriptions(&self) -> bool {
!self.subscriptions.is_empty()
}