Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc39df0ee5 | |||
| 70695d8c92 | |||
| 0533e2db3a | |||
| 716149c06c | |||
| 0628dd528a | |||
| e146ad6e7d | |||
| cf2c4fd179 | |||
| 6ba61ef80b | |||
| e45f990487 | |||
| 8e6c912a07 | |||
| 9a411f2403 | |||
| d2c65c91b7 | |||
| 5078aec840 | |||
| df949ab8ee | |||
| 2e036783bf | |||
| ff145300b4 | |||
| c2de9d8e83 | |||
| baeda3773d | |||
| 725f1845d9 | |||
| e0949a0eaa | |||
| 5d2bcd8366 | |||
| 5181d0e403 | |||
| 1c31fa80d2 | |||
| d3d08276ae | |||
| 80b34280c2 |
+358
-30
@@ -31,6 +31,7 @@ pub struct BrokerExecutionReport {
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ExecutionLeg {
|
||||
price: f64,
|
||||
mark_price: f64,
|
||||
quantity: u32,
|
||||
}
|
||||
|
||||
@@ -96,7 +97,7 @@ impl DynamicSlippageConfig {
|
||||
}
|
||||
}
|
||||
|
||||
fn ratio(
|
||||
pub(crate) fn ratio(
|
||||
&self,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
raw_price: f64,
|
||||
@@ -361,7 +362,30 @@ where
|
||||
symbol: &str,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
) -> f64 {
|
||||
let _ = (date, data, symbol);
|
||||
if self.aiquant_rqalpha_execution_rules && self.execution_price_field == PriceField::Last {
|
||||
let start_cursor = self
|
||||
.runtime_intraday_start_time
|
||||
.get()
|
||||
.or(self.intraday_execution_start_time)
|
||||
.map(|start_time| date.and_time(start_time));
|
||||
let matching_type = self.matching_type_for_algo_request(None);
|
||||
if let Some(quote) = self.latest_known_quote_at_or_before(
|
||||
data.execution_quotes_on(date, symbol),
|
||||
start_cursor,
|
||||
snapshot,
|
||||
OrderSide::Buy,
|
||||
matching_type,
|
||||
false,
|
||||
) {
|
||||
let fallback = self
|
||||
.select_quote_reference_price(snapshot, quote, OrderSide::Buy, matching_type)
|
||||
.unwrap_or(snapshot.last_price);
|
||||
let mark_price = self.quote_mark_price(quote, fallback);
|
||||
if mark_price.is_finite() && mark_price > 0.0 {
|
||||
return mark_price;
|
||||
}
|
||||
}
|
||||
}
|
||||
if snapshot.close.is_finite() && snapshot.close > 0.0 {
|
||||
snapshot.close
|
||||
} else {
|
||||
@@ -401,19 +425,37 @@ where
|
||||
side: OrderSide,
|
||||
quantity: Option<u32>,
|
||||
) -> f64 {
|
||||
let raw_price = if self.execution_price_field == PriceField::Last
|
||||
let raw_price = self.snapshot_raw_execution_price(snapshot, side);
|
||||
self.apply_slippage(snapshot, side, raw_price, quantity)
|
||||
}
|
||||
|
||||
fn snapshot_raw_execution_price(
|
||||
&self,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
side: OrderSide,
|
||||
) -> f64 {
|
||||
if self.execution_price_field == PriceField::Last
|
||||
&& self.intraday_execution_start_time.is_some()
|
||||
{
|
||||
let _ = side;
|
||||
snapshot.price(PriceField::Last)
|
||||
} else {
|
||||
return snapshot.price(PriceField::Last);
|
||||
}
|
||||
match side {
|
||||
OrderSide::Buy => self.buy_price(snapshot),
|
||||
OrderSide::Sell => self.sell_price(snapshot),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
self.apply_slippage(snapshot, side, raw_price, quantity)
|
||||
fn snapshot_mark_price(
|
||||
&self,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
side: OrderSide,
|
||||
) -> f64 {
|
||||
let price = snapshot.price(self.execution_price_field);
|
||||
if price.is_finite() && price > 0.0 {
|
||||
price
|
||||
} else {
|
||||
self.snapshot_raw_execution_price(snapshot, side)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_open_auction_matching(&self) -> bool {
|
||||
@@ -573,6 +615,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn quote_mark_price(&self, quote: &IntradayExecutionQuote, fallback: f64) -> f64 {
|
||||
if quote.last_price.is_finite() && quote.last_price > 0.0 {
|
||||
quote.last_price
|
||||
} else {
|
||||
fallback
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute(
|
||||
&self,
|
||||
date: NaiveDate,
|
||||
@@ -2478,7 +2528,7 @@ where
|
||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||
(fill.quantity, fill.legs)
|
||||
} else {
|
||||
let mut execution_price =
|
||||
let execution_price =
|
||||
self.snapshot_execution_price(snapshot, OrderSide::Sell, Some(fillable_qty));
|
||||
if let Some(reason) =
|
||||
self.execution_limit_rejection_reason(snapshot, OrderSide::Sell, execution_price)
|
||||
@@ -2497,15 +2547,26 @@ where
|
||||
);
|
||||
(0, Vec::new())
|
||||
} else {
|
||||
execution_price =
|
||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||
(
|
||||
match self.execution_price_with_limit_slippage_or_rejection(
|
||||
snapshot,
|
||||
OrderSide::Sell,
|
||||
execution_price,
|
||||
limit_price,
|
||||
) {
|
||||
Ok(execution_price) => (
|
||||
fillable_qty,
|
||||
vec![ExecutionLeg {
|
||||
price: execution_price,
|
||||
mark_price: self.snapshot_mark_price(snapshot, OrderSide::Sell),
|
||||
quantity: fillable_qty,
|
||||
}],
|
||||
)
|
||||
),
|
||||
Err(reason) => {
|
||||
partial_fill_reason =
|
||||
merge_partial_fill_reason(partial_fill_reason, Some(reason));
|
||||
(0, Vec::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if filled_qty == 0 {
|
||||
@@ -2588,7 +2649,7 @@ where
|
||||
let net_cash = gross_amount - cost.total();
|
||||
let realized_pnl = portfolio
|
||||
.position_mut(symbol)
|
||||
.sell(leg.quantity, leg.price)
|
||||
.sell_with_mark_price(leg.quantity, leg.price, leg.mark_price)
|
||||
.map_err(BacktestError::Execution)?;
|
||||
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
||||
position.record_trade_cost(cost.total());
|
||||
@@ -2787,8 +2848,13 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let current_value = if self.aiquant_rqalpha_execution_rules {
|
||||
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
|
||||
let current_value = valuation_price * current_qty as f64;
|
||||
valuation_price * current_qty as f64
|
||||
} else {
|
||||
let valuation_price = self.target_value_valuation_price(date, data, symbol, snapshot);
|
||||
valuation_price * current_qty as f64
|
||||
};
|
||||
let cash_delta = target_value.max(0.0) - current_value;
|
||||
|
||||
if cash_delta.abs() > f64::EPSILON {
|
||||
@@ -3857,7 +3923,7 @@ where
|
||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||
(fill.quantity, fill.legs)
|
||||
} else {
|
||||
let mut execution_price =
|
||||
let execution_price =
|
||||
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(constrained_qty));
|
||||
if let Some(reason) =
|
||||
self.execution_limit_rejection_reason(snapshot, OrderSide::Buy, execution_price)
|
||||
@@ -3876,9 +3942,19 @@ where
|
||||
);
|
||||
(0, Vec::new())
|
||||
} else {
|
||||
execution_price =
|
||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||
let filled_qty = self.affordable_buy_quantity(
|
||||
match self.execution_price_with_limit_slippage_or_rejection(
|
||||
snapshot,
|
||||
OrderSide::Buy,
|
||||
execution_price,
|
||||
limit_price,
|
||||
) {
|
||||
Err(reason) => {
|
||||
partial_fill_reason =
|
||||
merge_partial_fill_reason(partial_fill_reason, Some(reason));
|
||||
(0, Vec::new())
|
||||
}
|
||||
Ok(mut execution_price) => {
|
||||
let mut filled_qty = self.affordable_buy_quantity(
|
||||
date,
|
||||
buy_cash_limit,
|
||||
value_gross_limit,
|
||||
@@ -3887,12 +3963,33 @@ where
|
||||
self.minimum_order_quantity(data, symbol),
|
||||
self.order_step_size(data, symbol),
|
||||
);
|
||||
let mut blocked_by_final_price = false;
|
||||
if filled_qty > 0 {
|
||||
execution_price =
|
||||
self.snapshot_execution_price(snapshot, OrderSide::Buy, Some(filled_qty));
|
||||
execution_price =
|
||||
self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||
execution_price = self.snapshot_execution_price(
|
||||
snapshot,
|
||||
OrderSide::Buy,
|
||||
Some(filled_qty),
|
||||
);
|
||||
match self.execution_price_with_limit_slippage_or_rejection(
|
||||
snapshot,
|
||||
OrderSide::Buy,
|
||||
execution_price,
|
||||
limit_price,
|
||||
) {
|
||||
Ok(price) => execution_price = price,
|
||||
Err(reason) => {
|
||||
partial_fill_reason = merge_partial_fill_reason(
|
||||
partial_fill_reason,
|
||||
Some(reason),
|
||||
);
|
||||
filled_qty = 0;
|
||||
blocked_by_final_price = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if blocked_by_final_price {
|
||||
(0, Vec::new())
|
||||
} else {
|
||||
if filled_qty < constrained_qty {
|
||||
partial_fill_reason = merge_partial_fill_reason(
|
||||
partial_fill_reason,
|
||||
@@ -3909,10 +4006,14 @@ where
|
||||
filled_qty,
|
||||
vec![ExecutionLeg {
|
||||
price: execution_price,
|
||||
mark_price: self.snapshot_mark_price(snapshot, OrderSide::Buy),
|
||||
quantity: filled_qty,
|
||||
}],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if filled_qty == 0 {
|
||||
let detail = partial_fill_reason
|
||||
@@ -3995,9 +4096,12 @@ where
|
||||
let cash_out = gross_amount + cost.total();
|
||||
|
||||
portfolio.apply_cash_delta(-cash_out);
|
||||
portfolio
|
||||
.position_mut(symbol)
|
||||
.buy(date, leg.quantity, leg.price);
|
||||
portfolio.position_mut(symbol).buy_with_mark_price(
|
||||
date,
|
||||
leg.quantity,
|
||||
leg.price,
|
||||
leg.mark_price,
|
||||
);
|
||||
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
||||
position.record_buy_trade_cost(leg.quantity, cost.total());
|
||||
}
|
||||
@@ -4535,6 +4639,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn execution_price_with_limit_slippage_or_rejection(
|
||||
&self,
|
||||
snapshot: &crate::data::DailyMarketSnapshot,
|
||||
side: OrderSide,
|
||||
execution_price: f64,
|
||||
limit_price: Option<f64>,
|
||||
) -> Result<f64, &'static str> {
|
||||
let adjusted = self.execution_price_with_limit_slippage(execution_price, limit_price);
|
||||
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, adjusted) {
|
||||
Err(reason)
|
||||
} else {
|
||||
Ok(adjusted)
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_order_can_remain_open(partial_reason: Option<&str>) -> bool {
|
||||
!partial_reason.is_some_and(|reason| {
|
||||
reason.contains("insufficient cash")
|
||||
@@ -4674,8 +4793,12 @@ where
|
||||
let quote_quantity_limited =
|
||||
self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor);
|
||||
let lot = round_lot.max(1);
|
||||
let use_decision_time_quote =
|
||||
matching_type == MatchingType::NextTickLast && start_cursor.is_some();
|
||||
let exact_time_order_quote = matching_type != MatchingType::NextTickLast
|
||||
&& start_cursor.is_some()
|
||||
&& end_cursor.is_some()
|
||||
&& start_cursor == end_cursor;
|
||||
let use_decision_time_quote = start_cursor.is_some()
|
||||
&& (matching_type == MatchingType::NextTickLast || exact_time_order_quote);
|
||||
let eligible_quotes: Vec<&IntradayExecutionQuote> = if use_decision_time_quote {
|
||||
self.latest_known_quote_at_or_before(
|
||||
quotes,
|
||||
@@ -4700,6 +4823,7 @@ where
|
||||
};
|
||||
let mut filled_qty = 0_u32;
|
||||
let mut gross_amount = 0.0_f64;
|
||||
let mut mark_amount = 0.0_f64;
|
||||
let mut last_timestamp = None;
|
||||
let mut legs = Vec::new();
|
||||
let mut budget_block_reason = None;
|
||||
@@ -4717,6 +4841,7 @@ where
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let mark_price = self.quote_mark_price(quote, raw_quote_price);
|
||||
let remaining_qty = requested_qty.saturating_sub(filled_qty);
|
||||
if remaining_qty == 0 {
|
||||
break;
|
||||
@@ -4781,6 +4906,14 @@ where
|
||||
}
|
||||
quote_price =
|
||||
self.execution_price_with_limit_slippage(quote_price, limit_price);
|
||||
if let Some(reason) =
|
||||
self.execution_limit_rejection_reason(snapshot, side, quote_price)
|
||||
{
|
||||
execution_block_reason.get_or_insert(reason);
|
||||
execution_block_timestamp = Some(quote.timestamp);
|
||||
take_qty = 0;
|
||||
break;
|
||||
}
|
||||
let candidate_gross = gross_amount + quote_price * take_qty as f64;
|
||||
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
|
||||
budget_block_reason = Some("value budget limit");
|
||||
@@ -4813,12 +4946,20 @@ where
|
||||
quote_price =
|
||||
self.quote_execution_price(snapshot, side, raw_quote_price, Some(take_qty));
|
||||
quote_price = self.execution_price_with_limit_slippage(quote_price, limit_price);
|
||||
if let Some(reason) = self.execution_limit_rejection_reason(snapshot, side, quote_price)
|
||||
{
|
||||
execution_block_reason.get_or_insert(reason);
|
||||
execution_block_timestamp = Some(quote.timestamp);
|
||||
continue;
|
||||
}
|
||||
|
||||
gross_amount += quote_price * take_qty as f64;
|
||||
mark_amount += mark_price * take_qty as f64;
|
||||
filled_qty += take_qty;
|
||||
last_timestamp = Some(quote.timestamp);
|
||||
legs.push(ExecutionLeg {
|
||||
price: quote_price,
|
||||
mark_price,
|
||||
quantity: take_qty,
|
||||
});
|
||||
|
||||
@@ -4849,6 +4990,7 @@ where
|
||||
legs: if matching_type == MatchingType::Vwap {
|
||||
vec![ExecutionLeg {
|
||||
price: gross_amount / filled_qty as f64,
|
||||
mark_price: mark_amount / filled_qty as f64,
|
||||
quantity: filled_qty,
|
||||
}]
|
||||
} else {
|
||||
@@ -5140,6 +5282,127 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiquant_target_value_delta_uses_scheduled_mark_price() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2023, 5, 8).expect("valid date");
|
||||
let symbol = "603101.SH";
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel {
|
||||
commission_rate: 0.0003,
|
||||
stamp_tax_rate_before_change: 0.0005,
|
||||
stamp_tax_rate_after_change: 0.0005,
|
||||
minimum_commission: 5.0,
|
||||
},
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_intraday_execution_start_time(date.and_hms_opt(10, 40, 0).unwrap().time())
|
||||
.with_slippage_model(SlippageModel::PriceRatio(0.002))
|
||||
.with_strict_value_budget(true)
|
||||
.with_aiquant_rqalpha_execution_rules(true)
|
||||
.with_volume_limit(false)
|
||||
.with_liquidity_limit(false)
|
||||
.with_inactive_limit(false);
|
||||
let snapshot = DailyMarketSnapshot {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: Some("2023-05-08 15:00:00".to_string()),
|
||||
day_open: 5.86,
|
||||
open: 5.86,
|
||||
high: 5.90,
|
||||
low: 5.76,
|
||||
close: 5.81,
|
||||
last_price: 5.81,
|
||||
bid1: 5.82,
|
||||
ask1: 5.83,
|
||||
prev_close: 5.85,
|
||||
volume: 1_000_000,
|
||||
tick_volume: 262,
|
||||
bid1_volume: 54,
|
||||
ask1_volume: 143,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 6.44,
|
||||
lower_limit: 5.27,
|
||||
price_tick: 0.01,
|
||||
};
|
||||
let quote = IntradayExecutionQuote {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
timestamp: date.and_hms_opt(10, 39, 59).expect("valid timestamp"),
|
||||
last_price: 5.83,
|
||||
bid1: 5.82,
|
||||
ask1: 5.83,
|
||||
bid1_volume: 54,
|
||||
ask1_volume: 143,
|
||||
volume_delta: 262,
|
||||
amount_delta: 152_501.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
};
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![Instrument {
|
||||
symbol: symbol.to_string(),
|
||||
name: symbol.to_string(),
|
||||
board: "SH".to_string(),
|
||||
round_lot: 100,
|
||||
listed_at: Some(date),
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
}],
|
||||
vec![snapshot],
|
||||
Vec::new(),
|
||||
vec![CandidateEligibility {
|
||||
date,
|
||||
symbol: symbol.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![quote],
|
||||
)
|
||||
.expect("valid dataset");
|
||||
let mut portfolio = PortfolioState::new(8_261_416.62);
|
||||
portfolio.position_mut(symbol).buy(date, 21_200, 5.8817);
|
||||
let mut report = BrokerExecutionReport::default();
|
||||
broker
|
||||
.process_target_value(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
symbol,
|
||||
9_996_284.62 * 0.5 / 40.0,
|
||||
"daily_position_target_adjust",
|
||||
&mut BTreeMap::new(),
|
||||
&mut BTreeMap::new(),
|
||||
&mut None,
|
||||
&mut BTreeMap::new(),
|
||||
&mut report,
|
||||
)
|
||||
.expect("process target value");
|
||||
|
||||
assert_eq!(
|
||||
portfolio.position(symbol).map(|pos| pos.quantity),
|
||||
Some(21_400)
|
||||
);
|
||||
if let Some(order) = report.order_events.last() {
|
||||
assert_eq!(order.requested_quantity, 200);
|
||||
assert_eq!(order.filled_quantity, 200);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_tick_last_execution_uses_latest_quote_before_decision_time() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
|
||||
@@ -5252,6 +5515,66 @@ mod tests {
|
||||
assert_eq!(report.order_events[0].filled_quantity, 14_300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_buy_rejects_when_slippage_clamps_execution_price_to_upper_limit() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Open,
|
||||
)
|
||||
.with_slippage_model(SlippageModel::PriceRatio(0.002))
|
||||
.with_strict_value_budget(true)
|
||||
.with_volume_limit(false)
|
||||
.with_liquidity_limit(false)
|
||||
.with_inactive_limit(false);
|
||||
let mut snapshot = limit_test_snapshot();
|
||||
snapshot.day_open = 10.98;
|
||||
snapshot.open = 10.98;
|
||||
snapshot.last_price = 10.98;
|
||||
snapshot.close = 10.98;
|
||||
snapshot.bid1 = 10.98;
|
||||
snapshot.ask1 = 10.98;
|
||||
snapshot.upper_limit = 11.0;
|
||||
let data = DataSet::from_components_with_actions_and_quotes(
|
||||
vec![limit_test_instrument()],
|
||||
vec![snapshot],
|
||||
Vec::new(),
|
||||
vec![limit_test_candidate(true, true)],
|
||||
vec![limit_test_benchmark()],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)
|
||||
.expect("valid dataset");
|
||||
let mut portfolio = PortfolioState::new(10_000_000.0);
|
||||
let mut report = BrokerExecutionReport::default();
|
||||
|
||||
broker
|
||||
.process_value(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
"000001.SZ",
|
||||
125_000.0,
|
||||
"periodic_rebalance_buy",
|
||||
&mut BTreeMap::new(),
|
||||
&mut BTreeMap::new(),
|
||||
&mut None,
|
||||
&mut BTreeMap::new(),
|
||||
&mut report,
|
||||
)
|
||||
.expect("value buy processed");
|
||||
|
||||
assert!(portfolio.position("000001.SZ").is_none());
|
||||
assert_eq!(report.order_events.len(), 1);
|
||||
assert_eq!(report.order_events[0].filled_quantity, 0);
|
||||
assert!(
|
||||
report.order_events[0]
|
||||
.reason
|
||||
.contains("open at or above upper limit")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_value_buy_budget_includes_commission_at_execution_price() {
|
||||
let date = chrono::NaiveDate::from_ymd_opt(2025, 1, 2).expect("valid date");
|
||||
@@ -5391,7 +5714,7 @@ mod tests {
|
||||
);
|
||||
let default_rule = default_broker.buy_rule_check(date, &snapshot, &candidate, None);
|
||||
assert!(!default_rule.allowed);
|
||||
assert_eq!(default_rule.reason.as_deref(), Some("trade_disabled"));
|
||||
assert_eq!(default_rule.reason.as_deref(), Some("buy_disabled"));
|
||||
|
||||
let aiquant_broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
@@ -5401,12 +5724,17 @@ mod tests {
|
||||
.with_aiquant_rqalpha_execution_rules(true);
|
||||
let aiquant_rule = aiquant_broker.buy_rule_check(date, &snapshot, &candidate, None);
|
||||
assert!(!aiquant_rule.allowed);
|
||||
assert_eq!(aiquant_rule.reason.as_deref(), Some("trade_disabled"));
|
||||
assert_eq!(aiquant_rule.reason.as_deref(), Some("buy_disabled"));
|
||||
|
||||
let tradable_candidate = limit_test_candidate(true, true);
|
||||
let aiquant_rule =
|
||||
aiquant_broker.buy_rule_check(date, &snapshot, &tradable_candidate, None);
|
||||
assert!(aiquant_rule.allowed);
|
||||
|
||||
let lower_limit_buyable_candidate = limit_test_candidate(true, false);
|
||||
let aiquant_rule =
|
||||
aiquant_broker.buy_rule_check(date, &snapshot, &lower_limit_buyable_candidate, None);
|
||||
assert!(aiquant_rule.allowed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -159,14 +159,14 @@ impl DailyMarketSnapshot {
|
||||
if !self.upper_limit.is_finite() || self.upper_limit <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
price >= self.upper_limit - self.effective_price_tick() + 1e-6
|
||||
price >= self.upper_limit - 1e-9
|
||||
}
|
||||
|
||||
pub fn is_at_lower_limit_price(&self, price: f64) -> bool {
|
||||
if !self.lower_limit.is_finite() || self.lower_limit <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
price <= self.lower_limit + self.effective_price_tick() - 1e-6
|
||||
price <= self.lower_limit + 1e-9
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1237,6 +1237,13 @@ impl DataSet {
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
pub fn has_execution_quotes_on_date(&self, date: NaiveDate) -> bool {
|
||||
self.execution_quotes_by_date
|
||||
.get(&date)
|
||||
.map(|rows_by_symbol| !rows_by_symbol.is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn execution_quote_key_set(&self) -> HashSet<(NaiveDate, String)> {
|
||||
self.execution_quotes_by_date
|
||||
.iter()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
use chrono::{Datelike, NaiveDate, NaiveTime};
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
@@ -341,6 +341,8 @@ pub struct BacktestEngine<S, C, R> {
|
||||
futures_cost_model: FuturesTransactionCostModel,
|
||||
futures_validation_config: FuturesValidationConfig,
|
||||
execution_quote_loader: Option<ExecutionQuoteLoader>,
|
||||
execution_quote_request_cache:
|
||||
BTreeSet<(NaiveDate, String, Option<NaiveTime>, Option<NaiveTime>)>,
|
||||
}
|
||||
|
||||
impl<S, C, R> BacktestEngine<S, C, R> {
|
||||
@@ -369,6 +371,7 @@ impl<S, C, R> BacktestEngine<S, C, R> {
|
||||
futures_cost_model: FuturesTransactionCostModel::default(),
|
||||
futures_validation_config: FuturesValidationConfig::default(),
|
||||
execution_quote_loader: None,
|
||||
execution_quote_request_cache: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,20 +526,55 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let start_time = start_time.or_else(|| self.broker.intraday_execution_start_time());
|
||||
let caller_start_time = start_time;
|
||||
let caller_end_time = end_time;
|
||||
let start_time = caller_start_time.or_else(|| self.broker.intraday_execution_start_time());
|
||||
let mut symbols = execution_quote_symbols_for_decision(decision, portfolio, open_orders);
|
||||
self.load_missing_execution_quotes(execution_date, start_time, end_time, &mut symbols)?;
|
||||
|
||||
if caller_start_time.is_none() && caller_end_time.is_none() {
|
||||
for ((intent_start_time, intent_end_time), mut intent_symbols) in
|
||||
algo_execution_quote_windows_for_decision(decision, portfolio)
|
||||
{
|
||||
self.load_missing_execution_quotes(
|
||||
execution_date,
|
||||
intent_start_time,
|
||||
intent_end_time,
|
||||
&mut intent_symbols,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_missing_execution_quotes(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
start_time: Option<NaiveTime>,
|
||||
end_time: Option<NaiveTime>,
|
||||
symbols: &mut BTreeSet<String>,
|
||||
) -> Result<(), BacktestError> {
|
||||
symbols.retain(|symbol| {
|
||||
let request_key = (execution_date, symbol.clone(), start_time, end_time);
|
||||
if self.execution_quote_request_cache.contains(&request_key) {
|
||||
return false;
|
||||
}
|
||||
if start_time.is_some() && end_time.is_none() {
|
||||
return true;
|
||||
}
|
||||
!has_execution_quote_in_window(&self.data, execution_date, symbol, start_time, end_time)
|
||||
});
|
||||
if symbols.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let requested_symbols = symbols.iter().cloned().collect::<Vec<_>>();
|
||||
let request = ExecutionQuoteRequest {
|
||||
date: execution_date,
|
||||
start_time,
|
||||
end_time,
|
||||
symbols,
|
||||
symbols: std::mem::take(symbols),
|
||||
};
|
||||
let quotes = self
|
||||
.execution_quote_loader
|
||||
@@ -544,6 +582,43 @@ where
|
||||
.expect("checked execution quote loader")
|
||||
.as_mut()(request)?;
|
||||
self.data.add_execution_quotes(quotes);
|
||||
for symbol in requested_symbols {
|
||||
self.execution_quote_request_cache.insert((
|
||||
execution_date,
|
||||
symbol,
|
||||
start_time,
|
||||
end_time,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_execution_quotes_for_portfolio_times(
|
||||
&mut self,
|
||||
execution_date: NaiveDate,
|
||||
portfolio: &PortfolioState,
|
||||
quote_times: &[NaiveTime],
|
||||
) -> Result<(), BacktestError> {
|
||||
if self.execution_quote_loader.is_none() || quote_times.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let base_symbols = portfolio
|
||||
.positions()
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if base_symbols.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for quote_time in quote_times {
|
||||
let mut symbols = base_symbols.clone();
|
||||
self.load_missing_execution_quotes(
|
||||
execution_date,
|
||||
Some(*quote_time),
|
||||
None,
|
||||
&mut symbols,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1875,6 +1950,12 @@ where
|
||||
"on_day:pre",
|
||||
)?;
|
||||
let on_day_open_orders = self.open_order_views();
|
||||
let decision_quote_times = self.strategy.decision_quote_times();
|
||||
self.ensure_execution_quotes_for_portfolio_times(
|
||||
execution_date,
|
||||
&portfolio,
|
||||
&decision_quote_times,
|
||||
)?;
|
||||
let mut decision = decision_slot
|
||||
.map(|(decision_idx, decision_date)| {
|
||||
self.strategy.on_day(&StrategyContext {
|
||||
@@ -3283,6 +3364,54 @@ fn execution_quote_symbols_for_decision(
|
||||
symbols
|
||||
}
|
||||
|
||||
fn algo_execution_quote_windows_for_decision(
|
||||
decision: &StrategyDecision,
|
||||
portfolio: &PortfolioState,
|
||||
) -> BTreeMap<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>> {
|
||||
let mut groups = BTreeMap::<(Option<NaiveTime>, Option<NaiveTime>), BTreeSet<String>>::new();
|
||||
for intent in &decision.order_intents {
|
||||
match intent {
|
||||
OrderIntent::AlgoValue {
|
||||
symbol,
|
||||
start_time,
|
||||
end_time,
|
||||
..
|
||||
}
|
||||
| OrderIntent::AlgoPercent {
|
||||
symbol,
|
||||
start_time,
|
||||
end_time,
|
||||
..
|
||||
} => {
|
||||
if start_time.is_some() || end_time.is_some() {
|
||||
groups
|
||||
.entry((*start_time, *end_time))
|
||||
.or_default()
|
||||
.insert(symbol.clone());
|
||||
}
|
||||
}
|
||||
OrderIntent::TargetPortfolioSmart {
|
||||
target_weights,
|
||||
order_prices:
|
||||
Some(TargetPortfolioOrderPricing::AlgoOrder {
|
||||
start_time,
|
||||
end_time,
|
||||
..
|
||||
}),
|
||||
..
|
||||
} => {
|
||||
if start_time.is_some() || end_time.is_some() {
|
||||
let symbols = groups.entry((*start_time, *end_time)).or_default();
|
||||
symbols.extend(portfolio.positions().keys().cloned());
|
||||
symbols.extend(target_weights.keys().cloned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
fn collect_scheduled_decisions<S: Strategy>(
|
||||
strategy: &mut S,
|
||||
scheduler: &Scheduler<'_>,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,9 +5,10 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
PlatformAccountActionKind, PlatformExplicitActionStage, PlatformExplicitCancelKind,
|
||||
PlatformExplicitOrderKind, PlatformExprStrategyConfig, PlatformRebalanceSchedule,
|
||||
PlatformScheduleFrequency, PlatformTradeAction, PlatformUniverseActionKind, ScheduleTimeRule,
|
||||
DynamicSlippageConfig, MatchingType, PlatformAccountActionKind, PlatformExplicitActionStage,
|
||||
PlatformExplicitCancelKind, PlatformExplicitOrderKind, PlatformExprStrategyConfig,
|
||||
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
|
||||
PlatformUniverseActionKind, ScheduleTimeRule, SlippageModel,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -22,6 +23,10 @@ pub struct StrategyRuntimeSpec {
|
||||
#[serde(default)]
|
||||
pub universe: Option<StrategyUniverseSpec>,
|
||||
#[serde(default)]
|
||||
pub rebalance: Option<StrategyRebalanceSpec>,
|
||||
#[serde(default)]
|
||||
pub trade_times: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub signal_symbol: Option<String>,
|
||||
#[serde(default)]
|
||||
pub execution: Option<StrategyExecutionSpec>,
|
||||
@@ -49,6 +54,13 @@ pub struct StrategyUniverseSpec {
|
||||
pub exclude: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StrategyRebalanceSpec {
|
||||
#[serde(default)]
|
||||
pub trade_times: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StrategyExecutionSpec {
|
||||
@@ -165,6 +177,10 @@ pub struct MovingAverageFilterConfig {
|
||||
#[serde(default)]
|
||||
pub long_days: Option<usize>,
|
||||
#[serde(default)]
|
||||
pub volume_short_days: Option<usize>,
|
||||
#[serde(default)]
|
||||
pub volume_long_days: Option<usize>,
|
||||
#[serde(default)]
|
||||
pub rsi_rate: Option<f64>,
|
||||
}
|
||||
|
||||
@@ -284,6 +300,12 @@ pub struct StrategyExpressionTradingConfig {
|
||||
#[serde(default)]
|
||||
pub retry_empty_rebalance: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub delayed_limit_open_exit: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub delayed_limit_open_exit_time: Option<String>,
|
||||
#[serde(default)]
|
||||
pub release_slot_on_exit_signal: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub subscription_guard_required: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub actions: Vec<StrategyExpressionActionConfig>,
|
||||
@@ -384,6 +406,97 @@ fn apply_cost_overrides(
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_model_name(value: &str) -> String {
|
||||
value.trim().to_ascii_lowercase().replace('-', "_")
|
||||
}
|
||||
|
||||
fn parse_matching_type(value: Option<&str>) -> Option<MatchingType> {
|
||||
match normalize_model_name(value?).as_str() {
|
||||
"open_auction" => Some(MatchingType::OpenAuction),
|
||||
"current_bar_close" => Some(MatchingType::CurrentBarClose),
|
||||
"next_bar_open" => Some(MatchingType::NextBarOpen),
|
||||
"next_tick_last" => Some(MatchingType::NextTickLast),
|
||||
"next_tick_best_own" => Some(MatchingType::NextTickBestOwn),
|
||||
"next_tick_best_counterparty" => Some(MatchingType::NextTickBestCounterparty),
|
||||
"counterparty_offer" => Some(MatchingType::CounterpartyOffer),
|
||||
"vwap" => Some(MatchingType::Vwap),
|
||||
"twap" => Some(MatchingType::Twap),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_slippage_model(
|
||||
model: Option<&str>,
|
||||
value: Option<f64>,
|
||||
impact_coefficient: Option<f64>,
|
||||
volatility_coefficient: Option<f64>,
|
||||
max_value: Option<f64>,
|
||||
) -> Option<SlippageModel> {
|
||||
let value = valid_non_negative(value);
|
||||
let impact_coefficient = valid_non_negative(impact_coefficient);
|
||||
let volatility_coefficient = valid_non_negative(volatility_coefficient);
|
||||
let max_value = valid_non_negative(max_value);
|
||||
let model = model
|
||||
.map(normalize_model_name)
|
||||
.filter(|item| !item.is_empty())
|
||||
.unwrap_or_else(|| {
|
||||
if value.is_some_and(|item| item > 0.0) {
|
||||
"price_ratio".to_string()
|
||||
} else {
|
||||
"none".to_string()
|
||||
}
|
||||
});
|
||||
|
||||
match model.as_str() {
|
||||
"none" => Some(SlippageModel::None),
|
||||
"price_ratio" => Some(SlippageModel::PriceRatio(value.unwrap_or(0.0))),
|
||||
"tick_size" => Some(SlippageModel::TickSize(value.unwrap_or(0.0))),
|
||||
"limit_price" => Some(SlippageModel::LimitPrice),
|
||||
"dynamic" | "dynamic_volume_volatility" => {
|
||||
Some(SlippageModel::Dynamic(DynamicSlippageConfig::new(
|
||||
impact_coefficient.unwrap_or(0.5),
|
||||
volatility_coefficient.unwrap_or(0.3),
|
||||
max_value.or(value).unwrap_or(0.01),
|
||||
)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_execution_behavior_overrides(
|
||||
cfg: &mut PlatformExprStrategyConfig,
|
||||
matching_type: Option<&str>,
|
||||
slippage_model: Option<&str>,
|
||||
slippage_value: Option<f64>,
|
||||
slippage_impact_coefficient: Option<f64>,
|
||||
slippage_volatility_coefficient: Option<f64>,
|
||||
slippage_max_value: Option<f64>,
|
||||
strict_value_budget: Option<bool>,
|
||||
) {
|
||||
if let Some(matching_type) = parse_matching_type(matching_type) {
|
||||
cfg.matching_type = matching_type;
|
||||
}
|
||||
if slippage_model.is_some()
|
||||
|| slippage_value.is_some()
|
||||
|| slippage_impact_coefficient.is_some()
|
||||
|| slippage_volatility_coefficient.is_some()
|
||||
|| slippage_max_value.is_some()
|
||||
{
|
||||
if let Some(parsed) = parse_slippage_model(
|
||||
slippage_model,
|
||||
slippage_value,
|
||||
slippage_impact_coefficient,
|
||||
slippage_volatility_coefficient,
|
||||
slippage_max_value,
|
||||
) {
|
||||
cfg.slippage_model = parsed;
|
||||
}
|
||||
}
|
||||
if let Some(enabled) = strict_value_budget {
|
||||
cfg.strict_value_budget = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_usize_after(text: &str, start: usize) -> Option<(usize, usize)> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut end = start;
|
||||
@@ -607,6 +720,16 @@ pub fn platform_expr_config_from_spec(
|
||||
engine.stamp_tax_rate_before_change,
|
||||
engine.stamp_tax_rate_after_change,
|
||||
);
|
||||
apply_execution_behavior_overrides(
|
||||
&mut cfg,
|
||||
engine.matching_type.as_deref(),
|
||||
engine.slippage_model.as_deref(),
|
||||
engine.slippage_value,
|
||||
engine.slippage_impact_coefficient,
|
||||
engine.slippage_volatility_coefficient,
|
||||
engine.slippage_max_value,
|
||||
engine.strict_value_budget,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(spec_signal_symbol) = spec
|
||||
@@ -804,6 +927,20 @@ pub fn platform_expr_config_from_spec(
|
||||
if let Some(enabled) = trading.retry_empty_rebalance {
|
||||
cfg.retry_empty_rebalance = enabled;
|
||||
}
|
||||
if let Some(enabled) = trading.release_slot_on_exit_signal {
|
||||
cfg.release_slot_on_exit_signal = enabled;
|
||||
}
|
||||
if let Some(enabled) = trading.delayed_limit_open_exit {
|
||||
cfg.delayed_limit_open_exit_enabled = enabled;
|
||||
if enabled {
|
||||
cfg.delayed_limit_open_exit_time = trading
|
||||
.delayed_limit_open_exit_time
|
||||
.as_deref()
|
||||
.and_then(|value| parse_schedule_clock_time(Some(value)));
|
||||
} else {
|
||||
cfg.delayed_limit_open_exit_time = None;
|
||||
}
|
||||
}
|
||||
if let Some(enabled) = spec
|
||||
.engine_config
|
||||
.as_ref()
|
||||
@@ -930,6 +1067,28 @@ pub fn platform_expr_config_from_spec(
|
||||
cfg.retry_empty_rebalance = true;
|
||||
}
|
||||
}
|
||||
let trade_times = spec_trade_times(spec);
|
||||
if let Some(main_trade_time) = trade_times.last().copied() {
|
||||
cfg.intraday_execution_time = Some(main_trade_time);
|
||||
}
|
||||
let delayed_limit_open_exit_explicit = spec
|
||||
.runtime_expressions
|
||||
.as_ref()
|
||||
.and_then(|runtime_expr| runtime_expr.trading.as_ref())
|
||||
.and_then(|trading| trading.delayed_limit_open_exit)
|
||||
.is_some();
|
||||
if aiquant_compat && !delayed_limit_open_exit_explicit && trade_times.len() > 1 {
|
||||
let delayed_time = trade_times[0];
|
||||
if trade_times
|
||||
.last()
|
||||
.copied()
|
||||
.map(|main_time| main_time != delayed_time)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
cfg.delayed_limit_open_exit_enabled = true;
|
||||
cfg.delayed_limit_open_exit_time = Some(delayed_time);
|
||||
}
|
||||
}
|
||||
if let Some(execution) = spec.execution.as_ref() {
|
||||
apply_cost_overrides(
|
||||
&mut cfg,
|
||||
@@ -938,6 +1097,23 @@ pub fn platform_expr_config_from_spec(
|
||||
execution.stamp_tax_rate_before_change,
|
||||
execution.stamp_tax_rate_after_change,
|
||||
);
|
||||
apply_execution_behavior_overrides(
|
||||
&mut cfg,
|
||||
execution.matching_type.as_deref(),
|
||||
execution.slippage_model.as_deref(),
|
||||
execution.slippage_value,
|
||||
execution.slippage_impact_coefficient,
|
||||
execution.slippage_volatility_coefficient,
|
||||
execution.slippage_max_value,
|
||||
execution.strict_value_budget,
|
||||
);
|
||||
}
|
||||
if cfg.aiquant_transaction_cost
|
||||
&& cfg
|
||||
.minimum_commission
|
||||
.is_some_and(|value| value.is_finite() && value <= 0.0)
|
||||
{
|
||||
cfg.minimum_commission = None;
|
||||
}
|
||||
|
||||
cfg
|
||||
@@ -1015,6 +1191,24 @@ fn parse_schedule_clock_time(raw: Option<&str>) -> Option<NaiveTime> {
|
||||
.or_else(|| NaiveTime::parse_from_str(value, "%H:%M").ok())
|
||||
}
|
||||
|
||||
fn parse_trade_times(raw: &[String]) -> Vec<NaiveTime> {
|
||||
raw.iter()
|
||||
.filter_map(|item| parse_schedule_clock_time(Some(item.as_str())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn spec_trade_times(spec: &StrategyRuntimeSpec) -> Vec<NaiveTime> {
|
||||
let rebalance_times = spec
|
||||
.rebalance
|
||||
.as_ref()
|
||||
.map(|rebalance| parse_trade_times(&rebalance.trade_times))
|
||||
.unwrap_or_default();
|
||||
if !rebalance_times.is_empty() {
|
||||
return rebalance_times;
|
||||
}
|
||||
parse_trade_times(&spec.trade_times)
|
||||
}
|
||||
|
||||
fn parse_platform_trade_action(
|
||||
action: &StrategyExpressionActionConfig,
|
||||
) -> Option<PlatformTradeAction> {
|
||||
@@ -1391,6 +1585,50 @@ mod tests {
|
||||
assert_eq!(cfg.stamp_tax_rate_after_change, Some(0.0005));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_execution_slippage_overrides_into_platform_config() {
|
||||
let spec = serde_json::json!({
|
||||
"execution": {
|
||||
"compatibilityProfile": "aiquant_rqalpha",
|
||||
"matchingType": "next_tick_last",
|
||||
"slippageModel": "price_ratio",
|
||||
"slippageValue": 0.001,
|
||||
"strictValueBudget": true
|
||||
},
|
||||
"engineConfig": {
|
||||
"matchingType": "current_bar_close",
|
||||
"slippageModel": "none",
|
||||
"slippageValue": 0.0,
|
||||
"strictValueBudget": false
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(cfg.matching_type, MatchingType::NextTickLast);
|
||||
assert_eq!(cfg.slippage_model, SlippageModel::PriceRatio(0.001));
|
||||
assert!(cfg.strict_value_budget);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_dynamic_slippage_into_platform_config() {
|
||||
let spec = serde_json::json!({
|
||||
"execution": {
|
||||
"slippageModel": "dynamic",
|
||||
"slippageImpactCoefficient": 0.6,
|
||||
"slippageVolatilityCoefficient": 0.2,
|
||||
"slippageMaxValue": 0.015
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.slippage_model,
|
||||
SlippageModel::Dynamic(DynamicSlippageConfig::new(0.6, 0.2, 0.015))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiquant_profile_defaults_to_daily_top_up_and_empty_retry() {
|
||||
let spec = serde_json::json!({
|
||||
@@ -1497,4 +1735,73 @@ mod tests {
|
||||
assert!(!cfg.calendar_rebalance_interval);
|
||||
assert!(cfg.aiquant_transaction_cost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_aiquant_rebalance_trade_times_for_delayed_limit_exit() {
|
||||
let spec = serde_json::json!({
|
||||
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||
"rebalance": { "tradeTimes": ["10:31", "10:40"] },
|
||||
"runtimeExpressions": {
|
||||
"schedule": { "frequency": "daily", "time": "10:40" }
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.intraday_execution_time,
|
||||
Some(NaiveTime::from_hms_opt(10, 40, 0).unwrap())
|
||||
);
|
||||
assert!(cfg.delayed_limit_open_exit_enabled);
|
||||
assert_eq!(
|
||||
cfg.delayed_limit_open_exit_time,
|
||||
Some(NaiveTime::from_hms_opt(10, 31, 0).unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_explicit_delayed_limit_open_exit() {
|
||||
let spec = serde_json::json!({
|
||||
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||
"runtimeExpressions": {
|
||||
"schedule": { "frequency": "daily", "time": "10:40" },
|
||||
"trading": {
|
||||
"delayedLimitOpenExit": true,
|
||||
"delayedLimitOpenExitTime": "10:31"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.intraday_execution_time,
|
||||
Some(NaiveTime::from_hms_opt(10, 40, 0).unwrap())
|
||||
);
|
||||
assert!(cfg.delayed_limit_open_exit_enabled);
|
||||
assert_eq!(
|
||||
cfg.delayed_limit_open_exit_time,
|
||||
Some(NaiveTime::from_hms_opt(10, 31, 0).unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_delayed_limit_open_exit_false_overrides_aiquant_trade_times() {
|
||||
let spec = serde_json::json!({
|
||||
"execution": { "compatibilityProfile": "aiquant_rqalpha" },
|
||||
"rebalance": { "tradeTimes": ["10:31", "10:40"] },
|
||||
"runtimeExpressions": {
|
||||
"schedule": { "frequency": "daily", "time": "10:40" },
|
||||
"trading": {
|
||||
"delayedLimitOpenExit": false,
|
||||
"delayedLimitOpenExitTime": "10:31"
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let cfg = platform_expr_config_from_value("", "", &spec).expect("config");
|
||||
|
||||
assert!(!cfg.delayed_limit_open_exit_enabled);
|
||||
assert_eq!(cfg.delayed_limit_open_exit_time, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,16 @@ impl Position {
|
||||
}
|
||||
|
||||
pub fn buy(&mut self, date: NaiveDate, quantity: u32, price: f64) {
|
||||
self.buy_with_mark_price(date, quantity, price, price);
|
||||
}
|
||||
|
||||
pub fn buy_with_mark_price(
|
||||
&mut self,
|
||||
date: NaiveDate,
|
||||
quantity: u32,
|
||||
execution_price: f64,
|
||||
mark_price: f64,
|
||||
) {
|
||||
if quantity == 0 {
|
||||
return;
|
||||
}
|
||||
@@ -73,19 +83,28 @@ impl Position {
|
||||
self.lots.push(PositionLot {
|
||||
acquired_date: date,
|
||||
quantity,
|
||||
entry_price: price,
|
||||
price,
|
||||
entry_price: execution_price,
|
||||
price: execution_price,
|
||||
});
|
||||
self.quantity += quantity;
|
||||
self.last_price = price;
|
||||
self.last_price = normalized_mark_price(mark_price, execution_price);
|
||||
self.day_trade_quantity_delta += quantity as i32;
|
||||
self.day_buy_quantity += quantity;
|
||||
self.day_buy_value += price * quantity as f64;
|
||||
self.day_buy_value += execution_price * quantity as f64;
|
||||
self.recalculate_average_cost();
|
||||
self.refresh_day_pnl();
|
||||
}
|
||||
|
||||
pub fn sell(&mut self, quantity: u32, price: f64) -> Result<f64, String> {
|
||||
self.sell_with_mark_price(quantity, price, price)
|
||||
}
|
||||
|
||||
pub fn sell_with_mark_price(
|
||||
&mut self,
|
||||
quantity: u32,
|
||||
execution_price: f64,
|
||||
mark_price: f64,
|
||||
) -> Result<f64, String> {
|
||||
if quantity > self.quantity {
|
||||
return Err(format!(
|
||||
"sell quantity {} exceeds current quantity {} for {}",
|
||||
@@ -102,7 +121,7 @@ impl Position {
|
||||
};
|
||||
|
||||
let lot_sell = remaining.min(first_lot.quantity);
|
||||
realized += (price - first_lot.price) * lot_sell as f64;
|
||||
realized += (execution_price - first_lot.price) * lot_sell as f64;
|
||||
first_lot.quantity -= lot_sell;
|
||||
remaining -= lot_sell;
|
||||
|
||||
@@ -112,11 +131,11 @@ impl Position {
|
||||
}
|
||||
|
||||
self.quantity -= quantity;
|
||||
self.last_price = price;
|
||||
self.last_price = normalized_mark_price(mark_price, execution_price);
|
||||
self.realized_pnl += realized;
|
||||
self.day_trade_quantity_delta -= quantity as i32;
|
||||
self.day_sell_quantity += quantity;
|
||||
self.day_sell_value += price * quantity as f64;
|
||||
self.day_sell_value += execution_price * quantity as f64;
|
||||
self.recalculate_average_cost();
|
||||
self.refresh_day_pnl();
|
||||
Ok(realized)
|
||||
@@ -356,6 +375,14 @@ impl Position {
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_mark_price(mark_price: f64, fallback: f64) -> f64 {
|
||||
if mark_price.is_finite() && mark_price > 0.0 {
|
||||
mark_price
|
||||
} else {
|
||||
fallback
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PortfolioState {
|
||||
initial_cash: f64,
|
||||
|
||||
@@ -41,6 +41,21 @@ impl ChinaAShareRiskControl {
|
||||
candidate: &CandidateEligibility,
|
||||
market: &DailyMarketSnapshot,
|
||||
instrument: Option<&Instrument>,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
|
||||
return Some(reason);
|
||||
}
|
||||
if !candidate.allow_buy || !candidate.allow_sell {
|
||||
return Some("trade_disabled");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn baseline_rejection_reason(
|
||||
date: NaiveDate,
|
||||
candidate: &CandidateEligibility,
|
||||
market: &DailyMarketSnapshot,
|
||||
instrument: Option<&Instrument>,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::instrument_rejection_reason(instrument, date) {
|
||||
return Some(reason);
|
||||
@@ -60,9 +75,6 @@ impl ChinaAShareRiskControl {
|
||||
if candidate.is_one_yuan || market.day_open <= 1.0 {
|
||||
return Some("one_yuan");
|
||||
}
|
||||
if !candidate.allow_buy || !candidate.allow_sell {
|
||||
return Some("trade_disabled");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -73,8 +85,7 @@ impl ChinaAShareRiskControl {
|
||||
instrument: Option<&Instrument>,
|
||||
check_price: f64,
|
||||
) -> Option<&'static str> {
|
||||
if let Some(reason) = Self::selection_rejection_reason(date, candidate, market, instrument)
|
||||
{
|
||||
if let Some(reason) = Self::baseline_rejection_reason(date, candidate, market, instrument) {
|
||||
return Some(reason);
|
||||
}
|
||||
if !candidate.allow_buy {
|
||||
|
||||
@@ -40,6 +40,9 @@ pub trait Strategy {
|
||||
fn schedule_rules(&self) -> Vec<ScheduleRule> {
|
||||
Vec::new()
|
||||
}
|
||||
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||
Vec::new()
|
||||
}
|
||||
fn on_scheduled(
|
||||
&mut self,
|
||||
_ctx: &StrategyContext<'_>,
|
||||
@@ -1536,6 +1539,8 @@ pub struct OmniMicroCapConfig {
|
||||
pub stock_short_ma_days: usize,
|
||||
pub stock_mid_ma_days: usize,
|
||||
pub stock_long_ma_days: usize,
|
||||
pub stock_volume_short_ma_days: usize,
|
||||
pub stock_volume_long_ma_days: usize,
|
||||
pub rsi_rate: f64,
|
||||
pub trade_rate: f64,
|
||||
pub stop_loss_ratio: f64,
|
||||
@@ -1562,6 +1567,8 @@ impl OmniMicroCapConfig {
|
||||
stock_short_ma_days: 5,
|
||||
stock_mid_ma_days: 10,
|
||||
stock_long_ma_days: 20,
|
||||
stock_volume_short_ma_days: 5,
|
||||
stock_volume_long_ma_days: 60,
|
||||
rsi_rate: 1.0001,
|
||||
trade_rate: 0.5,
|
||||
stop_loss_ratio: 0.93,
|
||||
@@ -1590,6 +1597,8 @@ impl OmniMicroCapConfig {
|
||||
stock_short_ma_days: 5,
|
||||
stock_mid_ma_days: 10,
|
||||
stock_long_ma_days: 30,
|
||||
stock_volume_short_ma_days: 5,
|
||||
stock_volume_long_ma_days: 60,
|
||||
rsi_rate: 1.0001,
|
||||
trade_rate: 0.5,
|
||||
stop_loss_ratio: 0.92,
|
||||
@@ -2268,62 +2277,33 @@ impl OmniMicroCapStrategy {
|
||||
return false;
|
||||
};
|
||||
|
||||
// MA filter: ma_short > ma_mid * rsi_rate && ma_mid * rsi_rate > ma_long
|
||||
let ma_pass =
|
||||
ma_short > ma_mid * self.config.rsi_rate && ma_mid * self.config.rsi_rate > ma_long;
|
||||
|
||||
// Debug logging for ALL stocks on first decision date
|
||||
static DEBUG_DATE: std::sync::Mutex<Option<NaiveDate>> = std::sync::Mutex::new(None);
|
||||
let mut debug_date = DEBUG_DATE.lock().unwrap();
|
||||
let should_debug = if let Some(d) = *debug_date {
|
||||
d == date
|
||||
} else {
|
||||
*debug_date = Some(date);
|
||||
true
|
||||
};
|
||||
|
||||
if should_debug {
|
||||
eprintln!(
|
||||
"[MA_FILTER] {} cap={:.2} ma5={:.4} ma10={:.4} ma30={:.4} ma10*rsi={:.4} pass={} ({}>{:.4}? {} && {:.4}>{}? {})",
|
||||
symbol,
|
||||
ctx.data.market_decision_close(date, symbol).unwrap_or(0.0),
|
||||
ma_short,
|
||||
ma_mid,
|
||||
ma_long,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_pass,
|
||||
ma_short,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_short > ma_mid * self.config.rsi_rate,
|
||||
ma_mid * self.config.rsi_rate,
|
||||
ma_long,
|
||||
ma_mid * self.config.rsi_rate > ma_long
|
||||
);
|
||||
}
|
||||
|
||||
if !ma_pass {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Volume filter: V5 < V60 (applied for omni_microcap strategies)
|
||||
if self.config.strategy_name.contains("aiquant")
|
||||
|| self.config.strategy_name.contains("AiQuant")
|
||||
|| self.config.strategy_name.contains("omni")
|
||||
{
|
||||
let Some(volume_ma5) = ctx
|
||||
.data
|
||||
.market_decision_volume_moving_average(date, symbol, 5)
|
||||
else {
|
||||
let Some(volume_ma5) = ctx.data.market_decision_volume_moving_average(
|
||||
date,
|
||||
symbol,
|
||||
self.config.stock_volume_short_ma_days,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let Some(volume_ma60) = ctx
|
||||
.data
|
||||
.market_decision_volume_moving_average(date, symbol, 60)
|
||||
else {
|
||||
let Some(volume_ma_long) = ctx.data.market_decision_volume_moving_average(
|
||||
date,
|
||||
symbol,
|
||||
self.config.stock_volume_long_ma_days,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if volume_ma5 >= volume_ma60 {
|
||||
if volume_ma5 >= volume_ma_long {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2516,18 +2496,6 @@ fn omni_truth_stock_list_candidates() -> Vec<PathBuf> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let suffix = PathBuf::from("data/demo/engine_truth_stock_list.csv");
|
||||
let manifest_root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
push_unique_truth_path(
|
||||
&mut candidates,
|
||||
manifest_root.join("../../../").join(&suffix),
|
||||
);
|
||||
if let Ok(current_dir) = env::current_dir() {
|
||||
for ancestor in current_dir.ancestors() {
|
||||
push_unique_truth_path(&mut candidates, ancestor.join(&suffix));
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
@@ -2696,10 +2664,6 @@ impl Strategy for OmniMicroCapStrategy {
|
||||
};
|
||||
// 使用前一交易日的指数价格计算市值区间(模拟实盘场景)
|
||||
let (band_low, band_high) = self.market_cap_band(prev_index_level);
|
||||
eprintln!(
|
||||
"[DEBUG] date={} current_index={:.2} prev_index={:.2} band=[{:.0}, {:.0}]",
|
||||
date, index_level, prev_index_level, band_low, band_high
|
||||
);
|
||||
let (stock_list, selection_notes) = self.select_symbols(ctx, date, band_low, band_high)?;
|
||||
let periodic_rebalance = ctx.decision_index % self.config.refresh_rate == 0;
|
||||
let mut projected = ctx.portfolio.clone();
|
||||
@@ -2723,7 +2687,8 @@ impl Strategy for OmniMicroCapStrategy {
|
||||
+ self.stop_loss_tolerance(market);
|
||||
let profit_hit = current_price / position.average_cost > self.config.take_profit_ratio;
|
||||
let can_sell = self.can_sell_position(ctx, date, &position.symbol);
|
||||
if stop_hit || profit_hit {
|
||||
let at_upper_limit = market.is_at_upper_limit_price(current_price);
|
||||
if stop_hit || (profit_hit && !at_upper_limit) {
|
||||
let sell_reason = if stop_hit {
|
||||
"stop_loss_exit"
|
||||
} else {
|
||||
|
||||
@@ -175,7 +175,7 @@ fn china_rule_hooks_block_buy_at_limit_up_and_sell_at_limit_down() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
||||
fn china_rule_hooks_use_strict_price_limits() {
|
||||
let hooks = ChinaEquityRuleHooks;
|
||||
let candidate = candidate();
|
||||
|
||||
@@ -184,6 +184,13 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
||||
..snapshot(10.9995, 11.0, 9.0)
|
||||
};
|
||||
let buy_check = hooks.can_buy(d(2024, 1, 3), &near_upper, &candidate, PriceField::Open);
|
||||
assert!(buy_check.allowed);
|
||||
|
||||
let exact_upper = DailyMarketSnapshot {
|
||||
price_tick: 0.001,
|
||||
..snapshot(11.0, 11.0, 9.0)
|
||||
};
|
||||
let buy_check = hooks.can_buy(d(2024, 1, 3), &exact_upper, &candidate, PriceField::Open);
|
||||
assert!(!buy_check.allowed);
|
||||
|
||||
let near_lower = DailyMarketSnapshot {
|
||||
@@ -199,6 +206,19 @@ fn china_rule_hooks_use_tick_size_tolerance_for_price_limits() {
|
||||
&position,
|
||||
PriceField::Open,
|
||||
);
|
||||
assert!(sell_check.allowed);
|
||||
|
||||
let exact_lower = DailyMarketSnapshot {
|
||||
price_tick: 0.001,
|
||||
..snapshot(9.0, 11.0, 9.0)
|
||||
};
|
||||
let sell_check = hooks.can_sell(
|
||||
d(2024, 1, 3),
|
||||
&exact_lower,
|
||||
&candidate,
|
||||
&position,
|
||||
PriceField::Open,
|
||||
);
|
||||
assert!(!sell_check.allowed);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,459 @@
|
||||
use chrono::{Duration, NaiveDate, NaiveTime};
|
||||
use fidc_core::{
|
||||
BacktestConfig, BacktestEngine, BenchmarkSnapshot, BrokerSimulator, CandidateEligibility,
|
||||
ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet,
|
||||
IntradayExecutionQuote, MatchingType, OrderIntent, PriceField, Strategy, StrategyContext,
|
||||
StrategyDecision,
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(year, month, day).expect("valid date")
|
||||
}
|
||||
|
||||
fn t(hour: u32, minute: u32, second: u32) -> NaiveTime {
|
||||
NaiveTime::from_hms_opt(hour, minute, second).expect("valid time")
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DecisionQuoteReader {
|
||||
day_count: usize,
|
||||
}
|
||||
|
||||
impl Strategy for DecisionQuoteReader {
|
||||
fn name(&self) -> &str {
|
||||
"decision_quote_reader"
|
||||
}
|
||||
|
||||
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||
vec![t(10, 40, 0)]
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
self.day_count += 1;
|
||||
if self.day_count == 1 {
|
||||
return Ok(StrategyDecision {
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000001.SZ".to_string(),
|
||||
value: 5_000.0,
|
||||
reason: "seed_position".to_string(),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
});
|
||||
}
|
||||
|
||||
assert!(
|
||||
ctx.portfolio.position("000001.SZ").is_some(),
|
||||
"second day should carry the first day position"
|
||||
);
|
||||
let quote_loaded_before_decision = ctx
|
||||
.data
|
||||
.execution_quotes_on(ctx.execution_date, "000001.SZ")
|
||||
.iter()
|
||||
.any(|quote| quote.timestamp.time() == t(10, 39, 59) && quote.last_price == 11.0);
|
||||
assert!(
|
||||
quote_loaded_before_decision,
|
||||
"engine must load declared decision quote before strategy.on_day"
|
||||
);
|
||||
Ok(StrategyDecision::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_preloads_declared_decision_quotes_for_current_positions() {
|
||||
let first = d(2026, 1, 5);
|
||||
let second = d(2026, 1, 6);
|
||||
let data = DataSet::from_components(
|
||||
Vec::new(),
|
||||
vec![
|
||||
DailyMarketSnapshot {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-05 15:00:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.2,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
prev_close: 9.8,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 10.78,
|
||||
lower_limit: 8.82,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
DailyMarketSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-06 15:00:00".to_string()),
|
||||
day_open: 10.5,
|
||||
open: 10.5,
|
||||
high: 11.2,
|
||||
low: 10.4,
|
||||
close: 10.6,
|
||||
last_price: 10.6,
|
||||
bid1: 10.6,
|
||||
ask1: 10.6,
|
||||
prev_close: 10.0,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 11.0,
|
||||
lower_limit: 9.0,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
DailyFactorSnapshot {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
DailyFactorSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
],
|
||||
vec![
|
||||
CandidateEligibility {
|
||||
date: first,
|
||||
symbol: "000001.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,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: second,
|
||||
symbol: "000001.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: first,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 990.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
BenchmarkSnapshot {
|
||||
date: second,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1001.0,
|
||||
prev_close: 1000.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("dataset");
|
||||
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_matching_type(MatchingType::NextTickLast)
|
||||
.with_intraday_execution_start_time(t(10, 40, 0));
|
||||
let config = BacktestConfig {
|
||||
initial_cash: 10_000.0,
|
||||
benchmark_code: "000852.SH".to_string(),
|
||||
start_date: Some(first),
|
||||
end_date: Some(second),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Last,
|
||||
};
|
||||
let mut engine = BacktestEngine::new(data, DecisionQuoteReader::default(), broker, config)
|
||||
.with_execution_quote_loader(move |request| {
|
||||
assert_eq!(
|
||||
request.end_time, None,
|
||||
"decision quote preload must request latest quote at or before start_time"
|
||||
);
|
||||
Ok(request
|
||||
.symbols
|
||||
.into_iter()
|
||||
.map(|symbol| IntradayExecutionQuote {
|
||||
date: request.date,
|
||||
symbol,
|
||||
timestamp: request.date.and_time(t(10, 39, 59)),
|
||||
last_price: if request.date == second { 11.0 } else { 10.0 },
|
||||
bid1: if request.date == second { 11.0 } else { 10.0 },
|
||||
ask1: if request.date == second { 11.0 } else { 10.0 },
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
volume_delta: 10_000,
|
||||
amount_delta: 100_000.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
})
|
||||
.collect())
|
||||
});
|
||||
|
||||
engine.run().expect("backtest should run");
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MultiTimeDecisionQuoteReader {
|
||||
day_count: usize,
|
||||
}
|
||||
|
||||
impl Strategy for MultiTimeDecisionQuoteReader {
|
||||
fn name(&self) -> &str {
|
||||
"multi_time_decision_quote_reader"
|
||||
}
|
||||
|
||||
fn decision_quote_times(&self) -> Vec<NaiveTime> {
|
||||
vec![t(10, 31, 0), t(10, 40, 0)]
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
self.day_count += 1;
|
||||
if self.day_count == 1 {
|
||||
return Ok(StrategyDecision {
|
||||
order_intents: vec![OrderIntent::Value {
|
||||
symbol: "000001.SZ".to_string(),
|
||||
value: 5_000.0,
|
||||
reason: "seed_position".to_string(),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
});
|
||||
}
|
||||
|
||||
let quote_times = ctx
|
||||
.data
|
||||
.execution_quotes_on(ctx.execution_date, "000001.SZ")
|
||||
.iter()
|
||||
.map(|quote| quote.timestamp.time())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
quote_times.contains(&t(10, 30, 59)),
|
||||
"10:31 decision quote must be loaded"
|
||||
);
|
||||
assert!(
|
||||
quote_times.contains(&t(10, 39, 59)),
|
||||
"10:40 decision quote must not be skipped because 10:31 was loaded"
|
||||
);
|
||||
Ok(StrategyDecision::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_loads_distinct_decision_quote_times_on_same_day() {
|
||||
let first = d(2026, 1, 5);
|
||||
let second = d(2026, 1, 6);
|
||||
let data = DataSet::from_components(
|
||||
Vec::new(),
|
||||
vec![
|
||||
DailyMarketSnapshot {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-05 15:00:00".to_string()),
|
||||
day_open: 10.0,
|
||||
open: 10.0,
|
||||
high: 10.2,
|
||||
low: 9.9,
|
||||
close: 10.0,
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
prev_close: 9.8,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 10.78,
|
||||
lower_limit: 8.82,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
DailyMarketSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
timestamp: Some("2026-01-06 15:00:00".to_string()),
|
||||
day_open: 10.5,
|
||||
open: 10.5,
|
||||
high: 11.2,
|
||||
low: 10.4,
|
||||
close: 10.6,
|
||||
last_price: 10.6,
|
||||
bid1: 10.6,
|
||||
ask1: 10.6,
|
||||
prev_close: 10.0,
|
||||
volume: 10_000,
|
||||
tick_volume: 1_000,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
paused: false,
|
||||
upper_limit: 11.0,
|
||||
lower_limit: 9.0,
|
||||
price_tick: 0.01,
|
||||
},
|
||||
],
|
||||
vec![
|
||||
DailyFactorSnapshot {
|
||||
date: first,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
DailyFactorSnapshot {
|
||||
date: second,
|
||||
symbol: "000001.SZ".to_string(),
|
||||
market_cap_bn: 10.0,
|
||||
free_float_cap_bn: 10.0,
|
||||
pe_ttm: 10.0,
|
||||
turnover_ratio: None,
|
||||
effective_turnover_ratio: None,
|
||||
extra_factors: Default::default(),
|
||||
},
|
||||
],
|
||||
vec![
|
||||
CandidateEligibility {
|
||||
date: first,
|
||||
symbol: "000001.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,
|
||||
},
|
||||
CandidateEligibility {
|
||||
date: second,
|
||||
symbol: "000001.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: first,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1000.0,
|
||||
prev_close: 990.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
BenchmarkSnapshot {
|
||||
date: second,
|
||||
benchmark: "000852.SH".to_string(),
|
||||
open: 1000.0,
|
||||
close: 1001.0,
|
||||
prev_close: 1000.0,
|
||||
volume: 1_000_000,
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("dataset");
|
||||
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks,
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_matching_type(MatchingType::NextTickLast)
|
||||
.with_intraday_execution_start_time(t(10, 40, 0));
|
||||
let config = BacktestConfig {
|
||||
initial_cash: 10_000.0,
|
||||
benchmark_code: "000852.SH".to_string(),
|
||||
start_date: Some(first),
|
||||
end_date: Some(second),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Last,
|
||||
};
|
||||
let requests = Arc::new(Mutex::new(Vec::<(NaiveDate, NaiveTime)>::new()));
|
||||
let captured_requests = Arc::clone(&requests);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
MultiTimeDecisionQuoteReader::default(),
|
||||
broker,
|
||||
config,
|
||||
)
|
||||
.with_execution_quote_loader(move |request| {
|
||||
let start_time = request
|
||||
.start_time
|
||||
.expect("decision quote loader request must include start_time");
|
||||
captured_requests
|
||||
.lock()
|
||||
.expect("request mutex")
|
||||
.push((request.date, start_time));
|
||||
Ok(request
|
||||
.symbols
|
||||
.into_iter()
|
||||
.map(|symbol| IntradayExecutionQuote {
|
||||
date: request.date,
|
||||
symbol,
|
||||
timestamp: request.date.and_time(start_time) - Duration::seconds(1),
|
||||
last_price: 10.0,
|
||||
bid1: 10.0,
|
||||
ask1: 10.0,
|
||||
bid1_volume: 10_000,
|
||||
ask1_volume: 10_000,
|
||||
volume_delta: 10_000,
|
||||
amount_delta: 100_000.0,
|
||||
trading_phase: Some("continuous".to_string()),
|
||||
})
|
||||
.collect())
|
||||
});
|
||||
|
||||
engine.run().expect("backtest should run");
|
||||
|
||||
let requests = requests.lock().expect("request mutex").clone();
|
||||
assert!(
|
||||
requests.contains(&(second, t(10, 31, 0))),
|
||||
"second-day 10:31 quote request is required"
|
||||
);
|
||||
assert!(
|
||||
requests.contains(&(second, t(10, 40, 0))),
|
||||
"second-day 10:40 quote request must not be skipped by earlier quote"
|
||||
);
|
||||
}
|
||||
@@ -1701,6 +1701,9 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
|
||||
|
||||
assert_eq!(report.fill_events.len(), 1);
|
||||
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
|
||||
let position = portfolio.position("000002.SZ").expect("position");
|
||||
assert!((position.last_price - 10.0).abs() < 1e-9);
|
||||
assert!((position.market_value() - position.quantity as f64 * 10.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4234,6 +4237,50 @@ fn broker_uses_limit_price_slippage_for_limit_orders() {
|
||||
assert!((report.fill_events[0].price - 10.1).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_rejects_limit_buy_when_final_execution_price_reaches_upper_limit() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
let data = two_day_limit_order_data(10.0, 10.2);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
)
|
||||
.with_slippage_model(SlippageModel::LimitPrice);
|
||||
let mut portfolio = PortfolioState::new(1_000_000.0);
|
||||
|
||||
let report = broker
|
||||
.execute(
|
||||
date,
|
||||
&mut portfolio,
|
||||
&data,
|
||||
&StrategyDecision {
|
||||
rebalance: false,
|
||||
target_weights: BTreeMap::new(),
|
||||
exit_symbols: BTreeSet::new(),
|
||||
order_intents: vec![OrderIntent::LimitShares {
|
||||
symbol: "000002.SZ".to_string(),
|
||||
quantity: 200,
|
||||
limit_price: 11.0,
|
||||
reason: "limit_entry_at_upper_limit".to_string(),
|
||||
}],
|
||||
notes: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
},
|
||||
)
|
||||
.expect("broker execution");
|
||||
|
||||
assert!(report.fill_events.is_empty());
|
||||
assert_eq!(report.order_events.len(), 1);
|
||||
assert_eq!(report.order_events[0].status, OrderStatus::Canceled);
|
||||
assert!(
|
||||
report.order_events[0]
|
||||
.reason
|
||||
.contains("open at or above upper limit")
|
||||
);
|
||||
assert!(portfolio.position("000002.SZ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broker_executes_limit_value_and_limit_percent_intents() {
|
||||
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user