Add order runtime lookup

This commit is contained in:
boris
2026-04-23 19:57:02 -07:00
parent c12a883d28
commit 9f10afddec
8 changed files with 351 additions and 8 deletions

View File

@@ -157,6 +157,10 @@ struct DataApiProbeStrategy {
snapshots: Rc<RefCell<Vec<String>>>,
}
struct OrderInspectionStrategy {
observed: Rc<RefCell<Vec<String>>>,
}
impl Strategy for ScheduledProbeStrategy {
fn name(&self) -> &str {
"scheduled-probe"
@@ -448,6 +452,45 @@ impl Strategy for DataApiProbeStrategy {
}
}
impl Strategy for OrderInspectionStrategy {
fn name(&self) -> &str {
"order-inspection"
}
fn on_day(
&mut self,
_ctx: &StrategyContext<'_>,
) -> Result<StrategyDecision, fidc_core::BacktestError> {
Ok(StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Shares {
symbol: "000001.SZ".to_string(),
quantity: 100,
reason: "inspect_buy".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
})
}
fn after_trading(&mut self, ctx: &StrategyContext<'_>) -> Result<(), fidc_core::BacktestError> {
let order = ctx.order(1).expect("order 1 visible after trading");
self.observed.borrow_mut().push(format!(
"status={};filled={};unfilled={};avg={:.2};cost={:.2};symbol={};side={}",
order.status.as_str(),
order.filled_quantity,
order.unfilled_quantity,
order.avg_price,
order.transaction_cost,
order.symbol,
order.side.as_str()
));
Ok(())
}
}
#[test]
fn engine_runs_strategy_hooks_in_daily_order() {
let date1 = d(2025, 1, 2);
@@ -1084,6 +1127,105 @@ fn strategy_context_exposes_rqalpha_style_data_helpers() {
);
}
#[test]
fn strategy_context_exposes_final_order_runtime_view() {
let date = d(2025, 1, 2);
let data = DataSet::from_components(
vec![Instrument {
symbol: "000001.SZ".to_string(),
name: "Anchor".to_string(),
board: "SZ".to_string(),
round_lot: 100,
listed_at: Some(d(2020, 1, 1)),
delisted_at: None,
status: "active".to_string(),
}],
vec![DailyMarketSnapshot {
date,
symbol: "000001.SZ".to_string(),
timestamp: Some("2025-01-02 10:18:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.4,
low: 9.9,
close: 10.2,
last_price: 10.2,
bid1: 10.19,
ask1: 10.2,
prev_close: 10.0,
volume: 100_000,
tick_volume: 100_000,
bid1_volume: 100_000,
ask1_volume: 100_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: "000001.SZ".to_string(),
market_cap_bn: 20.0,
free_float_cap_bn: 18.0,
pe_ttm: 10.0,
turnover_ratio: Some(1.0),
effective_turnover_ratio: Some(1.0),
extra_factors: BTreeMap::new(),
}],
vec![CandidateEligibility {
date,
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,
benchmark: "000300.SH".to_string(),
open: 100.0,
close: 100.0,
prev_close: 99.0,
volume: 1_000_000,
}],
)
.expect("dataset");
let observed = Rc::new(RefCell::new(Vec::new()));
let strategy = OrderInspectionStrategy {
observed: observed.clone(),
};
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Close,
);
let mut engine = BacktestEngine::new(
data,
strategy,
broker,
BacktestConfig {
initial_cash: 10_000.0,
benchmark_code: "000300.SH".to_string(),
start_date: Some(date),
end_date: Some(date),
decision_lag_trading_days: 0,
execution_price_field: PriceField::Close,
},
);
engine.run().expect("backtest run");
assert_eq!(
observed.borrow().as_slice(),
["status=filled;filled=100;unfilled=0;avg=10.20;cost=5.00;symbol=000001.SZ;side=buy"]
);
}
#[test]
fn engine_rejects_pending_limit_orders_at_market_close() {
let date1 = d(2025, 1, 2);

View File

@@ -33,6 +33,8 @@ fn strategy_emits_target_weights_and_diagnostics() {
process_events: &[],
active_process_event: None,
active_datetime: None,
order_events: &[],
fills: &[],
})
.expect("decision");
@@ -77,6 +79,8 @@ fn jq_strategy_emits_same_day_decision() {
process_events: &[],
active_process_event: None,
active_datetime: None,
order_events: &[],
fills: &[],
})
.expect("jq decision");