Add bar and tick strategy lifecycle

This commit is contained in:
boris
2026-04-23 19:17:04 -07:00
parent 86e4db6272
commit 1760fc6cd1
9 changed files with 525 additions and 10 deletions

View File

@@ -111,6 +111,8 @@ pub struct BrokerSimulator<C, R> {
inactive_limit: bool,
liquidity_limit: bool,
intraday_execution_start_time: Option<NaiveTime>,
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
next_order_id: Cell<u64>,
open_orders: RefCell<Vec<OpenOrder>>,
}
@@ -129,6 +131,8 @@ impl<C, R> BrokerSimulator<C, R> {
inactive_limit: true,
liquidity_limit: true,
intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None),
runtime_intraday_end_time: Cell::new(None),
next_order_id: Cell::new(1),
open_orders: RefCell::new(Vec::new()),
}
@@ -151,6 +155,8 @@ impl<C, R> BrokerSimulator<C, R> {
inactive_limit: true,
liquidity_limit: true,
intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None),
runtime_intraday_end_time: Cell::new(None),
next_order_id: Cell::new(1),
open_orders: RefCell::new(Vec::new()),
}
@@ -521,6 +527,25 @@ where
Ok(report)
}
pub fn execute_between(
&self,
date: NaiveDate,
portfolio: &mut PortfolioState,
data: &DataSet,
decision: &StrategyDecision,
start_time: Option<NaiveTime>,
end_time: Option<NaiveTime>,
) -> Result<BrokerExecutionReport, BacktestError> {
let previous_start_time = self.runtime_intraday_start_time.get();
let previous_end_time = self.runtime_intraday_end_time.get();
self.runtime_intraday_start_time.set(start_time);
self.runtime_intraday_end_time.set(end_time);
let result = self.execute(date, portfolio, data, decision);
self.runtime_intraday_start_time.set(previous_start_time);
self.runtime_intraday_end_time.set(previous_end_time);
result
}
fn process_order_intent(
&self,
date: NaiveDate,
@@ -4128,12 +4153,16 @@ where
return None;
}
let runtime_start_time = self.runtime_intraday_start_time.get();
let runtime_end_time = self.runtime_intraday_end_time.get();
let start_cursor = algo_request
.and_then(|request| request.start_time)
.or(runtime_start_time)
.or(self.intraday_execution_start_time)
.map(|start_time| date.and_time(start_time));
let end_cursor = algo_request
.and_then(|request| request.end_time)
.or(runtime_end_time)
.map(|end_time| date.and_time(end_time));
let quotes = data.execution_quotes_on(date, symbol);

View File

@@ -810,6 +810,21 @@ impl DataSet {
.unwrap_or(&[])
}
pub fn execution_quotes_on_date(&self, date: NaiveDate) -> Vec<IntradayExecutionQuote> {
let mut quotes = self
.execution_quotes_index
.iter()
.filter(|((quote_date, _), _)| *quote_date == date)
.flat_map(|(_, rows)| rows.iter().cloned())
.collect::<Vec<_>>();
quotes.sort_by(|left, right| {
left.timestamp
.cmp(&right.timestamp)
.then_with(|| left.symbol.cmp(&right.symbol))
});
quotes
}
pub fn benchmark_series(&self) -> Vec<BenchmarkSnapshot> {
self.benchmark_by_date.values().cloned().collect()
}

View File

@@ -640,6 +640,68 @@ where
ProcessEventKind::OnDay,
"on_day",
)?;
let bar_open_orders = self.broker.open_order_views();
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&bar_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::PreBar,
"bar:pre",
)?;
decision.merge_from(collect_scheduled_decisions(
&mut self.strategy,
&scheduler,
execution_date,
ScheduleStage::Bar,
&schedule_rules,
decision_date,
decision_index,
&self.data,
&portfolio,
&bar_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
&mut self.process_event_bus,
default_stage_time(ScheduleStage::Bar),
)?);
decision.merge_from(self.strategy.on_bar(&StrategyContext {
execution_date,
decision_date,
decision_index,
data: &self.data,
portfolio: &portfolio,
open_orders: &bar_open_orders,
dynamic_universe: self.dynamic_universe.as_ref(),
subscriptions: &self.subscriptions,
process_events: &process_events,
active_process_event: None,
})?);
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&bar_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::Bar,
"bar",
)?;
self.apply_strategy_directives(
execution_date,
decision_date,
@@ -691,6 +753,151 @@ where
ProcessEventKind::PostOnDay,
"on_day:post",
)?;
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&post_intraday_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::PostBar,
"bar:post",
)?;
if should_run_tick_events(&schedule_rules, &self.subscriptions) {
let filter_by_subscription = !self.subscriptions.is_empty();
let tick_quotes = self
.data
.execution_quotes_on_date(execution_date)
.into_iter()
.filter(|quote| {
!filter_by_subscription || self.subscriptions.contains(&quote.symbol)
})
.collect::<Vec<_>>();
for quote in tick_quotes {
let tick_time = quote.timestamp.time();
let tick_open_orders = self.broker.open_order_views();
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&tick_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::PreTick,
format!("tick:{}:{}:pre", quote.symbol, quote.timestamp),
)?;
let mut tick_decision = collect_scheduled_decisions(
&mut self.strategy,
&scheduler,
execution_date,
ScheduleStage::Tick,
&schedule_rules,
decision_date,
decision_index,
&self.data,
&portfolio,
&tick_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
&mut self.process_event_bus,
Some(tick_time),
)?;
tick_decision.merge_from(self.strategy.on_tick(
&StrategyContext {
execution_date,
decision_date,
decision_index,
data: &self.data,
portfolio: &portfolio,
open_orders: &tick_open_orders,
dynamic_universe: self.dynamic_universe.as_ref(),
subscriptions: &self.subscriptions,
process_events: &process_events,
active_process_event: None,
},
&quote,
)?);
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&tick_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::Tick,
format!("tick:{}:{}", quote.symbol, quote.timestamp),
)?;
self.apply_strategy_directives(
execution_date,
decision_date,
decision_index,
&portfolio,
&tick_open_orders,
&mut process_events,
&mut tick_decision,
)?;
let mut tick_report = self.broker.execute_between(
execution_date,
&mut portfolio,
&self.data,
&tick_decision,
Some(tick_time),
Some(tick_time),
)?;
let post_tick_open_orders = self.broker.open_order_views();
publish_process_events(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&post_tick_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
&mut tick_report.process_events,
)?;
merge_broker_report(&mut report, tick_report);
publish_phase_event(
&mut self.strategy,
&mut self.process_event_bus,
execution_date,
decision_date,
decision_index,
&self.data,
&portfolio,
&post_tick_open_orders,
self.dynamic_universe.as_ref(),
&self.subscriptions,
&mut process_events,
execution_date,
ProcessEventKind::PostTick,
format!("tick:{}:{}:post", quote.symbol, quote.timestamp),
)?;
}
}
portfolio.update_prices(execution_date, &self.data, PriceField::Close)?;
@@ -1557,12 +1764,27 @@ fn stage_label(stage: ScheduleStage) -> &'static str {
match stage {
ScheduleStage::BeforeTrading => "before_trading",
ScheduleStage::OpenAuction => "open_auction",
ScheduleStage::Bar => "bar",
ScheduleStage::Tick => "tick",
ScheduleStage::OnDay => "on_day",
ScheduleStage::AfterTrading => "after_trading",
ScheduleStage::Settlement => "settlement",
}
}
fn should_run_tick_events(rules: &[ScheduleRule], subscriptions: &BTreeSet<String>) -> bool {
!subscriptions.is_empty() || rules.iter().any(|rule| rule.stage == ScheduleStage::Tick)
}
fn merge_broker_report(target: &mut BrokerExecutionReport, incoming: BrokerExecutionReport) {
target.order_events.extend(incoming.order_events);
target.fill_events.extend(incoming.fill_events);
target.position_events.extend(incoming.position_events);
target.account_events.extend(incoming.account_events);
target.process_events.extend(incoming.process_events);
target.diagnostics.extend(incoming.diagnostics);
}
mod date_format {
use chrono::NaiveDate;
use serde::Serializer;

View File

@@ -108,6 +108,12 @@ pub enum ProcessEventKind {
PreOpenAuction,
OpenAuction,
PostOpenAuction,
PreBar,
Bar,
PostBar,
PreTick,
Tick,
PostTick,
PreScheduled,
PostScheduled,
PreOnDay,
@@ -141,6 +147,12 @@ impl ProcessEventKind {
Self::PreOpenAuction => "pre_open_auction",
Self::OpenAuction => "open_auction",
Self::PostOpenAuction => "post_open_auction",
Self::PreBar => "pre_bar",
Self::Bar => "bar",
Self::PostBar => "post_bar",
Self::PreTick => "pre_tick",
Self::Tick => "tick",
Self::PostTick => "post_tick",
Self::PreScheduled => "pre_scheduled",
Self::PostScheduled => "post_scheduled",
Self::PreOnDay => "pre_on_day",

View File

@@ -6,6 +6,8 @@ use crate::calendar::TradingCalendar;
pub enum ScheduleStage {
BeforeTrading,
OpenAuction,
Bar,
Tick,
OnDay,
AfterTrading,
Settlement,
@@ -222,6 +224,8 @@ pub fn default_stage_time(stage: ScheduleStage) -> Option<NaiveTime> {
match stage {
ScheduleStage::BeforeTrading => Some(NaiveTime::from_hms_opt(9, 0, 0).expect("valid time")),
ScheduleStage::OpenAuction => Some(NaiveTime::from_hms_opt(9, 31, 0).expect("valid time")),
ScheduleStage::Bar => Some(NaiveTime::from_hms_opt(10, 18, 0).expect("valid time")),
ScheduleStage::Tick => None,
ScheduleStage::OnDay => Some(NaiveTime::from_hms_opt(10, 18, 0).expect("valid time")),
ScheduleStage::AfterTrading => Some(NaiveTime::from_hms_opt(15, 0, 0).expect("valid time")),
ScheduleStage::Settlement => Some(NaiveTime::from_hms_opt(15, 1, 0).expect("valid time")),

View File

@@ -7,7 +7,7 @@ use std::sync::OnceLock;
use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use crate::cost::ChinaAShareCostModel;
use crate::data::{DataSet, PriceField};
use crate::data::{DataSet, IntradayExecutionQuote, PriceField};
use crate::engine::BacktestError;
use crate::events::{OrderSide, ProcessEvent};
use crate::portfolio::PortfolioState;
@@ -42,7 +42,19 @@ pub trait Strategy {
) -> Result<StrategyDecision, BacktestError> {
Ok(StrategyDecision::default())
}
fn on_day(&mut self, ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError>;
fn on_bar(&mut self, _ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError> {
Ok(StrategyDecision::default())
}
fn on_tick(
&mut self,
_ctx: &StrategyContext<'_>,
_quote: &IntradayExecutionQuote,
) -> Result<StrategyDecision, BacktestError> {
Ok(StrategyDecision::default())
}
fn on_day(&mut self, _ctx: &StrategyContext<'_>) -> Result<StrategyDecision, BacktestError> {
Ok(StrategyDecision::default())
}
fn after_trading(&mut self, _ctx: &StrategyContext<'_>) -> Result<(), BacktestError> {
Ok(())
}

View File

@@ -102,6 +102,10 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
title: "rebalance.weekly / rebalance.monthly".to_string(),
detail: "支持按交易周或交易月调仓,例如 rebalance.weekly(weekday=5).at([\"10:18\"])、rebalance.weekly(tradingday=-1).at([\"10:18\"])、rebalance.monthly(tradingday=1).at([\"10:18\"])。`.at([...])` 的最后一个时刻会编进分钟级 schedule/time_rule当前平台把 on_day 近似到 10:18把 open_auction 近似到 09:31。".to_string(),
},
ManualSection {
title: "bar / tick 生命周期".to_string(),
detail: "回测内核支持 rqalpha 风格的 bar/tick 生命周期:日内会发布 pre_bar/bar/post_bar 过程事件;存在 tick 订阅或 tick 调度规则时,会按 execution_quotes 的时间顺序发布 pre_tick/tick/post_tick并把 tick 阶段下单限制在当前 tick 时间窗内撮合。平台 DSL 中可通过 subscribe([...])、trading.subscription_guard(true) 和 process_event 字段配合显式订单模拟 tick 订阅策略。".to_string(),
},
ManualSection {
title: "selection.market_cap_band / selection.limit / ordering.rank_by / ordering.rank_expr".to_string(),
detail: "控制候选范围、数量和排序。支持表达式驱动的动态市值带和排序表达式。".to_string(),