From 58836a1c37f9d9b631ff10457bc2cad0db4a75d0 Mon Sep 17 00:00:00 2001 From: boris Date: Thu, 23 Apr 2026 18:48:14 -0700 Subject: [PATCH] Support algo order pricing in smart portfolio rebalances --- crates/fidc-core/src/broker.rs | 38 ++- crates/fidc-core/src/lib.rs | 5 +- .../fidc-core/src/platform_expr_strategy.rs | 239 +++++++++++++++++- crates/fidc-core/src/strategy.rs | 12 +- crates/fidc-core/src/strategy_ai.rs | 2 +- crates/fidc-core/tests/explicit_order_flow.rs | 146 ++++++++++- docs/rqalpha-gap-roadmap.md | 13 +- 7 files changed, 427 insertions(+), 28 deletions(-) diff --git a/crates/fidc-core/src/broker.rs b/crates/fidc-core/src/broker.rs index 42e7122..055a261 100644 --- a/crates/fidc-core/src/broker.rs +++ b/crates/fidc-core/src/broker.rs @@ -12,7 +12,9 @@ use crate::events::{ }; use crate::portfolio::PortfolioState; use crate::rules::EquityRuleHooks; -use crate::strategy::{AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision}; +use crate::strategy::{ + AlgoOrderStyle, OpenOrderView, OrderIntent, StrategyDecision, TargetPortfolioOrderPricing, +}; #[derive(Debug, Default)] pub struct BrokerExecutionReport { @@ -547,6 +549,7 @@ where execution_cursors, global_execution_cursor, commission_state, + None, report, ), OrderIntent::LimitShares { @@ -1567,7 +1570,7 @@ where portfolio: &mut PortfolioState, data: &DataSet, target_weights: &BTreeMap, - order_prices: Option<&BTreeMap>, + order_prices: Option<&TargetPortfolioOrderPricing>, valuation_prices: Option<&BTreeMap>, reason: &str, intraday_turnover: &mut BTreeMap, @@ -1584,6 +1587,25 @@ where valuation_prices, )?; report.diagnostics.extend(diagnostics); + let limit_prices = match order_prices { + Some(TargetPortfolioOrderPricing::LimitPrices(prices)) => Some(prices), + _ => None, + }; + let algo_request = match order_prices { + Some(TargetPortfolioOrderPricing::AlgoOrder { + style, + start_time, + end_time, + }) => Some(AlgoExecutionRequest { + style: match style { + AlgoOrderStyle::Vwap => AlgoExecutionStyle::Vwap, + AlgoOrderStyle::Twap => AlgoExecutionStyle::Twap, + }, + start_time: *start_time, + end_time: *end_time, + }), + _ => None, + }; let mut symbols = BTreeSet::new(); symbols.extend(portfolio.positions().keys().cloned()); @@ -1601,7 +1623,7 @@ where let sell_qty = current_qty - target_qty; let mut local_report = BrokerExecutionReport::default(); if let Some(limit_price) = - self.required_custom_order_price(date, symbol, order_prices)? + self.required_custom_order_price(date, symbol, limit_prices)? { self.process_limit_shares( date, @@ -1629,6 +1651,7 @@ where execution_cursors, global_execution_cursor, commission_state, + algo_request.as_ref(), &mut local_report, )?; } @@ -1647,7 +1670,7 @@ where let buy_qty = target_qty - current_qty; let mut local_report = BrokerExecutionReport::default(); if let Some(limit_price) = - self.required_custom_order_price(date, symbol, order_prices)? + self.required_custom_order_price(date, symbol, limit_prices)? { self.process_limit_shares( date, @@ -1675,6 +1698,7 @@ where execution_cursors, global_execution_cursor, commission_state, + algo_request.as_ref(), &mut local_report, )?; } @@ -3189,6 +3213,7 @@ where execution_cursors: &mut BTreeMap, global_execution_cursor: &mut Option, commission_state: &mut BTreeMap, + algo_request: Option<&AlgoExecutionRequest>, report: &mut BrokerExecutionReport, ) -> Result<(), BacktestError> { if quantity == 0 { @@ -3216,7 +3241,7 @@ where None, false, true, - None, + algo_request, report, ) } else { @@ -3235,7 +3260,7 @@ where None, false, true, - None, + algo_request, report, ) } @@ -3273,6 +3298,7 @@ where execution_cursors, global_execution_cursor, commission_state, + None, report, ) } diff --git a/crates/fidc-core/src/lib.rs b/crates/fidc-core/src/lib.rs index c977bb5..47b40dd 100644 --- a/crates/fidc-core/src/lib.rs +++ b/crates/fidc-core/src/lib.rs @@ -45,8 +45,9 @@ pub use scheduler::{ ScheduleFrequency, ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time, }; pub use strategy::{ - CnSmallCapRotationConfig, CnSmallCapRotationStrategy, JqMicroCapConfig, JqMicroCapStrategy, - AlgoOrderStyle, OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision, + AlgoOrderStyle, CnSmallCapRotationConfig, CnSmallCapRotationStrategy, JqMicroCapConfig, + JqMicroCapStrategy, OpenOrderView, OrderIntent, Strategy, StrategyContext, StrategyDecision, + TargetPortfolioOrderPricing, }; pub use strategy_ai::{ ManualExample, ManualFactorSource, ManualField, ManualFieldGroup, ManualFunction, diff --git a/crates/fidc-core/src/platform_expr_strategy.rs b/crates/fidc-core/src/platform_expr_strategy.rs index eb13fa2..cc4955c 100644 --- a/crates/fidc-core/src/platform_expr_strategy.rs +++ b/crates/fidc-core/src/platform_expr_strategy.rs @@ -11,7 +11,10 @@ use crate::portfolio::PortfolioState; use crate::scheduler::{ ScheduleRule, ScheduleStage, ScheduleTimeRule, Scheduler, default_stage_time, }; -use crate::strategy::{AlgoOrderStyle, OrderIntent, Strategy, StrategyContext, StrategyDecision}; +use crate::strategy::{ + AlgoOrderStyle, OrderIntent, Strategy, StrategyContext, StrategyDecision, + TargetPortfolioOrderPricing, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum PlatformScheduleFrequency { @@ -2229,6 +2232,10 @@ impl PlatformExprStrategy { expr ))); }; + Self::parse_time_string(raw.trim()) + } + + fn parse_time_string(raw: &str) -> Result { NaiveTime::parse_from_str(raw.trim(), "%H:%M") .or_else(|_| NaiveTime::parse_from_str(raw.trim(), "%H:%M:%S")) .map_err(|_| { @@ -2239,6 +2246,49 @@ impl PlatformExprStrategy { }) } + fn parse_numeric_time_code(code: i64, expr: &str) -> Result { + let value = code.abs(); + let (hour, minute, second) = if value >= 10_000 { + ( + (value / 10_000) as u32, + ((value / 100) % 100) as u32, + (value % 100) as u32, + ) + } else { + ((value / 100) as u32, (value % 100) as u32, 0) + }; + NaiveTime::from_hms_opt(hour, minute, second).ok_or_else(|| { + BacktestError::Execution(format!( + "platform expr did not produce a valid HHMM/HHMMSS time code: {}", + expr + )) + }) + } + + fn eval_time_code_expr( + &self, + ctx: &StrategyContext<'_>, + expr: &str, + day: &DayExpressionState, + stock: Option<&StockExpressionState>, + position: Option<&PositionExpressionState>, + ) -> Result { + let value = self.eval_dynamic(ctx, expr, day, stock, position)?; + if let Some(raw) = value.clone().try_cast::() { + return Self::parse_time_string(raw.trim()); + } + if let Some(number) = value.clone().try_cast::() { + return Self::parse_numeric_time_code(number.round() as i64, expr); + } + if let Some(number) = value.try_cast::() { + return Self::parse_numeric_time_code(number, expr); + } + Err(BacktestError::Execution(format!( + "platform expr did not produce a time string or HHMM/HHMMSS time code: {}", + expr + ))) + } + fn eval_float_map_expr( &self, ctx: &StrategyContext<'_>, @@ -2273,6 +2323,75 @@ impl PlatformExprStrategy { Ok(output) } + fn eval_target_portfolio_order_pricing_expr( + &self, + ctx: &StrategyContext<'_>, + expr: &str, + day: &DayExpressionState, + stock: Option<&StockExpressionState>, + position: Option<&PositionExpressionState>, + ) -> Result { + let trimmed = expr.trim(); + if trimmed.is_empty() { + return Err(BacktestError::Execution( + "target_portfolio_smart order_prices expr cannot be empty".to_string(), + )); + } + if trimmed.starts_with('{') { + return Ok(TargetPortfolioOrderPricing::LimitPrices( + self.eval_float_map_expr(ctx, trimmed, day, stock, position)?, + )); + } + self.eval_algo_order_pricing_expr(ctx, trimmed, day, stock, position) + } + + fn eval_algo_order_pricing_expr( + &self, + ctx: &StrategyContext<'_>, + expr: &str, + day: &DayExpressionState, + stock: Option<&StockExpressionState>, + position: Option<&PositionExpressionState>, + ) -> Result { + let Some(open_paren) = expr.find('(') else { + return Err(BacktestError::Execution(format!( + "target_portfolio_smart order_prices must be a {{...}} map or AlgoOrder(...) call: {expr}" + ))); + }; + let Some(args_src) = expr + .strip_suffix(')') + .map(|trimmed| &trimmed[open_paren + 1..]) + else { + return Err(BacktestError::Execution(format!( + "target_portfolio_smart order_prices must end with ')': {expr}" + ))); + }; + let name = expr[..open_paren].trim().to_ascii_lowercase(); + let style = match name.as_str() { + "vwap" | "vwaporder" => AlgoOrderStyle::Vwap, + "twap" | "twaporder" => AlgoOrderStyle::Twap, + _ => { + return Err(BacktestError::Execution(format!( + "unsupported target_portfolio_smart AlgoOrder style: {}", + expr[..open_paren].trim() + ))); + } + }; + let args = Self::split_top_level_args(args_src); + if args.len() != 2 { + return Err(BacktestError::Execution(format!( + "target_portfolio_smart AlgoOrder expects start and end time arguments: {expr}" + ))); + } + let start_time = self.eval_time_code_expr(ctx, &args[0], day, stock, position)?; + let end_time = self.eval_time_code_expr(ctx, &args[1], day, stock, position)?; + Ok(TargetPortfolioOrderPricing::AlgoOrder { + style, + start_time: Some(start_time), + end_time: Some(end_time), + }) + } + fn eval_symbol_set_expr( &self, ctx: &StrategyContext<'_>, @@ -2788,7 +2907,11 @@ impl PlatformExprStrategy { } let order_prices = order_prices_expr .as_deref() - .map(|expr| self.eval_float_map_expr(ctx, expr, day, None, None)) + .map(|expr| { + self.eval_target_portfolio_order_pricing_expr( + ctx, expr, day, None, None, + ) + }) .transpose()?; let valuation_prices = valuation_prices_expr .as_deref() @@ -3466,7 +3589,7 @@ mod tests { AlgoOrderStyle, BenchmarkSnapshot, CandidateEligibility, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument, OpenOrderView, PortfolioState, ProcessEvent, ProcessEventKind, ScheduleStage, ScheduleTimeRule, Strategy, StrategyContext, - TradingCalendar, default_stage_time, + TargetPortfolioOrderPricing, TradingCalendar, default_stage_time, }; fn d(year: i32, month: u32, day: u32) -> NaiveDate { @@ -4037,12 +4160,12 @@ mod tests { assert_eq!(reason, "platform_target_portfolio_smart"); assert_eq!(target_weights.get("000001.SZ").copied(), Some(0.30)); assert_eq!(target_weights.get("000002.SZ").copied(), Some(0.20)); - assert_eq!( - order_prices - .as_ref() - .and_then(|map| map.get("000001.SZ").copied()), - Some(1010.0) - ); + match order_prices { + Some(TargetPortfolioOrderPricing::LimitPrices(map)) => { + assert_eq!(map.get("000001.SZ").copied(), Some(1010.0)); + } + other => panic!("unexpected order pricing: {other:?}"), + } assert_eq!( valuation_prices .as_ref() @@ -4054,6 +4177,104 @@ mod tests { } } + #[test] + fn platform_strategy_emits_target_portfolio_smart_algo_order_style() { + let date = d(2025, 2, 3); + let data = DataSet::from_components( + vec![], + vec![DailyMarketSnapshot { + date, + symbol: "000001.SH".to_string(), + timestamp: Some("2025-02-03 10:18:00".to_string()), + day_open: 1000.0, + open: 1000.0, + high: 1002.0, + low: 998.0, + close: 1001.0, + last_price: 1001.0, + bid1: 1000.5, + ask1: 1001.5, + prev_close: 999.0, + volume: 100_000, + tick_volume: 5_000, + bid1_volume: 2_500, + ask1_volume: 2_500, + trading_phase: Some("continuous".to_string()), + paused: false, + upper_limit: 1098.9, + lower_limit: 899.1, + price_tick: 0.01, + }], + vec![], + vec![], + vec![BenchmarkSnapshot { + date, + benchmark: "000852.SH".to_string(), + open: 1000.0, + close: 1001.0, + prev_close: 999.0, + volume: 100_000, + }], + ) + .expect("dataset"); + let portfolio = PortfolioState::new(1_000_000.0); + let subscriptions = BTreeSet::new(); + let ctx = StrategyContext { + execution_date: date, + decision_date: date, + decision_index: 0, + data: &data, + portfolio: &portfolio, + open_orders: &[], + dynamic_universe: None, + subscriptions: &subscriptions, + process_events: &[], + active_process_event: None, + }; + let mut cfg = PlatformExprStrategyConfig::microcap_rotation(); + cfg.signal_symbol = "000001.SH".to_string(); + cfg.rotation_enabled = false; + cfg.benchmark_short_ma_days = 1; + cfg.benchmark_long_ma_days = 1; + cfg.explicit_actions = vec![PlatformTradeAction::TargetPortfolioSmart { + target_weights_expr: "{\"000001.SZ\": 0.30}".to_string(), + order_prices_expr: Some("VWAPOrder(930, 940)".to_string()), + valuation_prices_expr: Some("{\"000001.SZ\": signal_close}".to_string()), + when_expr: None, + reason: "platform_target_portfolio_smart_algo".to_string(), + }]; + let mut strategy = PlatformExprStrategy::new(cfg); + + let decision = strategy.on_day(&ctx).expect("platform decision"); + + assert_eq!(decision.order_intents.len(), 1); + match &decision.order_intents[0] { + crate::strategy::OrderIntent::TargetPortfolioSmart { + order_prices, + reason, + .. + } => { + assert_eq!(reason, "platform_target_portfolio_smart_algo"); + match order_prices { + Some(TargetPortfolioOrderPricing::AlgoOrder { + style, + start_time, + end_time, + }) => { + assert_eq!(*style, AlgoOrderStyle::Vwap); + assert_eq!( + *start_time, + Some(NaiveTime::from_hms_opt(9, 30, 0).unwrap()) + ); + assert_eq!(*end_time, Some(NaiveTime::from_hms_opt(9, 40, 0).unwrap())); + } + other => panic!("unexpected order pricing: {other:?}"), + } + } + other => panic!("unexpected explicit target portfolio intent: {other:?}"), + } + } + #[test] fn platform_strategy_emits_explicit_actions_in_open_auction_stage() { let date = d(2025, 2, 3); diff --git a/crates/fidc-core/src/strategy.rs b/crates/fidc-core/src/strategy.rs index c0447de..fbfc61f 100644 --- a/crates/fidc-core/src/strategy.rs +++ b/crates/fidc-core/src/strategy.rs @@ -334,6 +334,16 @@ pub enum AlgoOrderStyle { Twap, } +#[derive(Debug, Clone)] +pub enum TargetPortfolioOrderPricing { + LimitPrices(BTreeMap), + AlgoOrder { + style: AlgoOrderStyle, + start_time: Option, + end_time: Option, + }, +} + #[derive(Debug, Clone)] pub enum OrderIntent { Shares { @@ -431,7 +441,7 @@ pub enum OrderIntent { }, TargetPortfolioSmart { target_weights: BTreeMap, - order_prices: Option>, + order_prices: Option, valuation_prices: Option>, reason: String, }, diff --git a/crates/fidc-core/src/strategy_ai.rs b/crates/fidc-core/src/strategy_ai.rs index 47e43e3..73ccf1c 100644 --- a/crates/fidc-core/src/strategy_ai.rs +++ b/crates/fidc-core/src/strategy_ai.rs @@ -120,7 +120,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual { }, ManualSection { title: "trading.rotation / order.* / cancel.* / update_universe / subscribe".to_string(), - detail: "支持显式下单、撤单、AlgoOrder 和动态 universe 管理。可以用 trading.rotation(false) 关闭默认轮动链路,再用 trading.stage(\"open_auction\" | \"on_day\") 指定执行阶段,用 trading.schedule.daily().at([\"10:18\"]) / trading.schedule.weekly(weekday=5).at([\"10:18\"]) / trading.schedule.weekly(tradingday=-1).at([\"10:18\"]) / trading.schedule.monthly(tradingday=1).at([\"10:18\"]) 指定触发频率和分钟级 time_rule,然后写 order.shares(\"600000.SH\", 1000)、order.target_shares(\"600000.SH\", 2000)、order.value(\"600000.SH\", cash * 0.25)、order.target_percent(\"600000.SH\", 0.05)、order.limit_value(\"600000.SH\", cash * 0.25, open * 0.99)、order.vwap_value(\"600000.SH\", cash * 0.25, \"09:31\", \"09:40\")、order.twap_percent(\"600000.SH\", 0.05, \"10:00\", \"10:30\")、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices={\"600000.SH\": open * 0.99}, valuation_prices={\"600000.SH\": prev_close})、cancel.order(12345)、cancel.symbol(\"600000.SH\")、cancel.all()、update_universe([\"600000.SH\", \"000001.SZ\"])、subscribe([\"000001.SZ\"])、unsubscribe([\"000001.SZ\"])。其中 order.target_shares(...) 对应 rqalpha 的 order_to,order.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义,order.vwap_* / order.twap_* 对应 rqalpha 的 AlgoOrder 时间窗订单风格,而 update_universe/subscribe/unsubscribe 对应 rqalpha 的动态 universe 与订阅接口。symbol 使用标准证券代码;数量、金额、仓位、时间窗、限价、order_id 和 symbol 列表都支持表达式;这些语句也支持放进 when/unless 条件块。".to_string(), + detail: "支持显式下单、撤单、AlgoOrder 和动态 universe 管理。可以用 trading.rotation(false) 关闭默认轮动链路,再用 trading.stage(\"open_auction\" | \"on_day\") 指定执行阶段,用 trading.schedule.daily().at([\"10:18\"]) / trading.schedule.weekly(weekday=5).at([\"10:18\"]) / trading.schedule.weekly(tradingday=-1).at([\"10:18\"]) / trading.schedule.monthly(tradingday=1).at([\"10:18\"]) 指定触发频率和分钟级 time_rule,然后写 order.shares(\"600000.SH\", 1000)、order.target_shares(\"600000.SH\", 2000)、order.value(\"600000.SH\", cash * 0.25)、order.target_percent(\"600000.SH\", 0.05)、order.limit_value(\"600000.SH\", cash * 0.25, open * 0.99)、order.vwap_value(\"600000.SH\", cash * 0.25, \"09:31\", \"09:40\")、order.twap_percent(\"600000.SH\", 0.05, \"10:00\", \"10:30\")、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices=VWAPOrder(930, 940), valuation_prices={\"600000.SH\": prev_close})、order.target_portfolio_smart(weights={\"600000.SH\": 0.3, \"000001.SZ\": 0.2}, order_prices={\"600000.SH\": open * 0.99}, valuation_prices={\"600000.SH\": prev_close})、cancel.order(12345)、cancel.symbol(\"600000.SH\")、cancel.all()、update_universe([\"600000.SH\", \"000001.SZ\"])、subscribe([\"000001.SZ\"])、unsubscribe([\"000001.SZ\"])。其中 order.target_shares(...) 对应 rqalpha 的 order_to,order.target_portfolio_smart(...) 对应 rqalpha 的 order_target_portfolio_smart 批量目标权重语义;order_prices 既可以是逐标的限价映射,也可以是 VWAPOrder/TWAPOrder 这类全局 AlgoOrder;order.vwap_* / order.twap_* 对应 rqalpha 的 AlgoOrder 时间窗订单风格,而 update_universe/subscribe/unsubscribe 对应 rqalpha 的动态 universe 与订阅接口。symbol 使用标准证券代码;数量、金额、仓位、时间窗、限价、order_id 和 symbol 列表都支持表达式;这些语句也支持放进 when/unless 条件块。".to_string(), }, ManualSection { title: "when / unless / else".to_string(), diff --git a/crates/fidc-core/tests/explicit_order_flow.rs b/crates/fidc-core/tests/explicit_order_flow.rs index 476d24d..eeb8950 100644 --- a/crates/fidc-core/tests/explicit_order_flow.rs +++ b/crates/fidc-core/tests/explicit_order_flow.rs @@ -3,7 +3,7 @@ use fidc_core::{ AlgoOrderStyle, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, Instrument, IntradayExecutionQuote, MatchingType, OrderIntent, OrderStatus, PortfolioState, PriceField, - ProcessEventKind, SlippageModel, StrategyDecision, + ProcessEventKind, SlippageModel, StrategyDecision, TargetPortfolioOrderPricing, }; use std::collections::{BTreeMap, BTreeSet}; @@ -479,10 +479,10 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() { ("000001.SZ".to_string(), 0.0), ("000002.SZ".to_string(), 0.5), ]), - order_prices: Some(BTreeMap::from([ + order_prices: Some(TargetPortfolioOrderPricing::LimitPrices(BTreeMap::from([ ("000001.SZ".to_string(), 9.8), ("000002.SZ".to_string(), 10.2), - ])), + ]))), valuation_prices: Some(BTreeMap::from([ ("000001.SZ".to_string(), 10.0), ("000002.SZ".to_string(), 20.0), @@ -516,6 +516,146 @@ fn broker_executes_target_portfolio_smart_with_custom_prices() { ); } +#[test] +fn broker_executes_target_portfolio_smart_with_algo_order_style() { + let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap(); + let data = DataSet::from_components_with_actions_and_quotes( + vec![Instrument { + symbol: "000002.SZ".to_string(), + name: "New".to_string(), + board: "SZ".to_string(), + round_lot: 100, + listed_at: None, + delisted_at: None, + status: "active".to_string(), + }], + vec![DailyMarketSnapshot { + date, + symbol: "000002.SZ".to_string(), + timestamp: Some("2024-01-10 10:18:00".to_string()), + day_open: 10.0, + open: 10.0, + high: 10.3, + low: 9.9, + close: 10.2, + last_price: 10.2, + bid1: 10.19, + ask1: 10.21, + prev_close: 10.0, + volume: 100_000, + tick_volume: 100_000, + bid1_volume: 80_000, + ask1_volume: 80_000, + trading_phase: Some("continuous".to_string()), + paused: false, + upper_limit: 11.0, + lower_limit: 9.0, + price_tick: 0.01, + }], + vec![DailyFactorSnapshot { + date, + symbol: "000002.SZ".to_string(), + market_cap_bn: 45.0, + free_float_cap_bn: 40.0, + pe_ttm: 14.0, + turnover_ratio: Some(2.2), + effective_turnover_ratio: Some(2.0), + extra_factors: BTreeMap::new(), + }], + vec![CandidateEligibility { + date, + symbol: "000002.SZ".to_string(), + is_st: false, + is_new_listing: false, + is_paused: false, + allow_buy: true, + allow_sell: true, + is_kcb: false, + is_one_yuan: false, + }], + vec![BenchmarkSnapshot { + date, + benchmark: "000852.SH".to_string(), + open: 1000.0, + close: 1002.0, + prev_close: 998.0, + volume: 1_000_000, + }], + Vec::new(), + vec![ + IntradayExecutionQuote { + date, + symbol: "000002.SZ".to_string(), + timestamp: date.and_hms_opt(9, 31, 0).unwrap(), + last_price: 10.0, + ask1: 10.01, + bid1: 9.99, + ask1_volume: 1, + bid1_volume: 1, + volume_delta: 1, + amount_delta: 0.0, + trading_phase: Some("continuous".to_string()), + }, + IntradayExecutionQuote { + date, + symbol: "000002.SZ".to_string(), + timestamp: date.and_hms_opt(9, 35, 0).unwrap(), + last_price: 10.2, + ask1: 10.21, + bid1: 10.19, + ask1_volume: 1, + bid1_volume: 1, + volume_delta: 1, + amount_delta: 0.0, + trading_phase: Some("continuous".to_string()), + }, + ], + ) + .expect("dataset"); + + let mut portfolio = PortfolioState::new(2_100.0); + let broker = BrokerSimulator::new( + ChinaAShareCostModel::default(), + ChinaEquityRuleHooks::default(), + ); + + let report = broker + .execute( + date, + &mut portfolio, + &data, + &StrategyDecision { + rebalance: false, + target_weights: BTreeMap::new(), + exit_symbols: BTreeSet::new(), + order_intents: vec![OrderIntent::TargetPortfolioSmart { + target_weights: BTreeMap::from([("000002.SZ".to_string(), 1.0)]), + order_prices: Some(TargetPortfolioOrderPricing::AlgoOrder { + style: AlgoOrderStyle::Vwap, + start_time: Some(NaiveTime::from_hms_opt(9, 31, 0).unwrap()), + end_time: Some(NaiveTime::from_hms_opt(9, 35, 0).unwrap()), + }), + valuation_prices: Some(BTreeMap::from([("000002.SZ".to_string(), 10.0)])), + reason: "test_target_portfolio_smart_algo".to_string(), + }], + notes: Vec::new(), + diagnostics: Vec::new(), + }, + ) + .expect("broker execution"); + + assert_eq!(report.order_events.len(), 1); + assert_eq!(report.fill_events.len(), 1); + assert_eq!(report.fill_events[0].symbol, "000002.SZ"); + assert_eq!(report.fill_events[0].side, fidc_core::OrderSide::Buy); + assert_eq!(report.fill_events[0].quantity, 200); + assert!((report.fill_events[0].price - 10.1).abs() < 1e-9); + assert_eq!( + portfolio.position("000002.SZ").map(|pos| pos.quantity), + Some(200) + ); +} + #[test] fn broker_executes_order_percent_and_target_percent() { let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap(); diff --git a/docs/rqalpha-gap-roadmap.md b/docs/rqalpha-gap-roadmap.md index 9663aec..8130cd8 100644 --- a/docs/rqalpha-gap-roadmap.md +++ b/docs/rqalpha-gap-roadmap.md @@ -16,7 +16,7 @@ current alignment pass. - [x] `order_to` / target-shares style explicit order primitive - [x] `order_target_portfolio(_smart)` style public API surface -- [ ] richer explicit order styles exposed to platform scripts +- [x] richer explicit order styles exposed to platform scripts ### Phase 2: Scheduling and execution surface @@ -37,13 +37,13 @@ current alignment pass. - [x] `VWAPOrder` first-class explicit action parity (`order.vwap_value/percent`) - [x] `TWAPOrder` first-class explicit action parity (`order.twap_value/percent`) -- [ ] `order_target_portfolio_smart(..., order_prices=AlgoOrder, valuation_prices=...)` +- [x] `order_target_portfolio_smart(..., order_prices=AlgoOrder, valuation_prices=...)` ### Phase 5: Position accounting parity -- [ ] `trading_pnl` -- [ ] `position_pnl` -- [ ] `dividend_receivable` +- [x] `trading_pnl` +- [x] `position_pnl` +- [x] `dividend_receivable` - [ ] richer position lifecycle fields exposed to strategy runtime ## Execution Order @@ -57,4 +57,5 @@ current alignment pass. ## Current Step -Active implementation target: Phase 4, algo-order styles. +Active implementation target: Phase 2/3 follow-up, finer `1m`/`tick` +strategy execution entrypoints and subscription guards.