Add futures depth matching and mod loader
This commit is contained in:
@@ -4,13 +4,14 @@ use std::rc::Rc;
|
||||
|
||||
use chrono::{NaiveDate, NaiveDateTime};
|
||||
use fidc_core::{
|
||||
BacktestConfig, BacktestEngine, BacktestProcessMod, BenchmarkSnapshot, BrokerSimulator,
|
||||
CandidateEligibility, ChinaAShareCostModel, ChinaEquityRuleHooks, DailyFactorSnapshot,
|
||||
DailyMarketSnapshot, DataSet, FuturesAccountState, FuturesCommissionType, FuturesContractSpec,
|
||||
FuturesDirection, FuturesOrderIntent, FuturesTradingParameter, Instrument,
|
||||
IntradayExecutionQuote, OpenOrderView, OrderIntent, OrderSide, OrderStatus, PortfolioState,
|
||||
PriceField, ProcessEvent, ProcessEventBus, ProcessEventKind, ScheduleRule, ScheduleStage,
|
||||
ScheduleTimeRule, Strategy, StrategyContext, StrategyDecision,
|
||||
BacktestConfig, BacktestEngine, BacktestProcessMod, BacktestProcessModLoader,
|
||||
BenchmarkSnapshot, BrokerSimulator, CandidateEligibility, ChinaAShareCostModel,
|
||||
ChinaEquityRuleHooks, DailyFactorSnapshot, DailyMarketSnapshot, DataSet, FuturesAccountState,
|
||||
FuturesCommissionType, FuturesContractSpec, FuturesDirection, FuturesOrderIntent,
|
||||
FuturesTradingParameter, Instrument, IntradayExecutionQuote, IntradayOrderBookDepthLevel,
|
||||
MatchingType, OpenOrderView, OrderIntent, OrderSide, OrderStatus, PortfolioState, PriceField,
|
||||
ProcessEvent, ProcessEventBus, ProcessEventKind, ScheduleRule, ScheduleStage, ScheduleTimeRule,
|
||||
Strategy, StrategyContext, StrategyDecision,
|
||||
};
|
||||
|
||||
fn d(year: i32, month: u32, day: u32) -> NaiveDate {
|
||||
@@ -407,6 +408,37 @@ impl Strategy for FuturesLimitOrderStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesDepthLimitOrderStrategy;
|
||||
|
||||
impl Strategy for FuturesDepthLimitOrderStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"futures-depth-limit-order"
|
||||
}
|
||||
|
||||
fn on_day(
|
||||
&mut self,
|
||||
ctx: &StrategyContext<'_>,
|
||||
) -> Result<StrategyDecision, fidc_core::BacktestError> {
|
||||
if ctx.execution_date != d(2025, 1, 2) {
|
||||
return Ok(StrategyDecision::default());
|
||||
}
|
||||
Ok(StrategyDecision {
|
||||
order_intents: vec![OrderIntent::Futures {
|
||||
intent: FuturesOrderIntent::limit_open(
|
||||
"IF2501",
|
||||
FuturesDirection::Long,
|
||||
FuturesContractSpec::new(1.0, 0.0, 0.0),
|
||||
3,
|
||||
3990.0,
|
||||
0.0,
|
||||
"sweep depth until limit",
|
||||
),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct AdvancedDataApiProbeStrategy {
|
||||
observed: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
@@ -1399,6 +1431,127 @@ fn engine_matches_pending_futures_limit_order_with_data_driven_costs() {
|
||||
assert!((position.contract_multiplier - 300.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_sweeps_futures_order_book_depth_when_available() {
|
||||
let date = d(2025, 1, 2);
|
||||
let data = DataSet::from_components_with_actions_quotes_futures_and_depth(
|
||||
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(),
|
||||
},
|
||||
Instrument {
|
||||
symbol: "IF2501".to_string(),
|
||||
name: "IF".to_string(),
|
||||
board: "FUTURE".to_string(),
|
||||
round_lot: 1,
|
||||
listed_at: Some(d(2024, 1, 1)),
|
||||
delisted_at: None,
|
||||
status: "active".to_string(),
|
||||
},
|
||||
],
|
||||
vec![
|
||||
market_row(date, "000001.SZ", 10.0, 10.0),
|
||||
market_row(date, "IF2501", 4000.0, 4000.0),
|
||||
],
|
||||
vec![factor_row(date, "000001.SZ", BTreeMap::new())],
|
||||
vec![candidate_row(date, "000001.SZ")],
|
||||
vec![benchmark_row(date)],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![FuturesTradingParameter {
|
||||
symbol: "IF2501".to_string(),
|
||||
effective_date: Some(date),
|
||||
contract_multiplier: 300.0,
|
||||
long_margin_rate: 0.12,
|
||||
short_margin_rate: 0.14,
|
||||
commission_type: FuturesCommissionType::ByVolume,
|
||||
open_commission_ratio: 2.5,
|
||||
close_commission_ratio: 2.0,
|
||||
close_today_commission_ratio: 3.0,
|
||||
price_tick: 0.2,
|
||||
}],
|
||||
vec![
|
||||
IntradayOrderBookDepthLevel {
|
||||
date,
|
||||
symbol: "IF2501".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 0).unwrap(),
|
||||
level: 1,
|
||||
bid_price: 3987.8,
|
||||
bid_volume: 1,
|
||||
ask_price: 3988.0,
|
||||
ask_volume: 1,
|
||||
},
|
||||
IntradayOrderBookDepthLevel {
|
||||
date,
|
||||
symbol: "IF2501".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 0).unwrap(),
|
||||
level: 2,
|
||||
bid_price: 3987.6,
|
||||
bid_volume: 1,
|
||||
ask_price: 3990.0,
|
||||
ask_volume: 1,
|
||||
},
|
||||
IntradayOrderBookDepthLevel {
|
||||
date,
|
||||
symbol: "IF2501".to_string(),
|
||||
timestamp: date.and_hms_opt(10, 18, 0).unwrap(),
|
||||
level: 3,
|
||||
bid_price: 3987.4,
|
||||
bid_volume: 10,
|
||||
ask_price: 3994.0,
|
||||
ask_volume: 10,
|
||||
},
|
||||
],
|
||||
)
|
||||
.expect("depth dataset");
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Last,
|
||||
)
|
||||
.with_matching_type(MatchingType::CounterpartyOffer);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
FuturesDepthLimitOrderStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_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::Last,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
let fill = result
|
||||
.fills
|
||||
.iter()
|
||||
.find(|fill| fill.symbol == "IF2501")
|
||||
.expect("depth futures fill");
|
||||
assert_eq!(fill.quantity, 2);
|
||||
assert!((fill.price - 3989.0).abs() < 1e-6);
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::PartiallyFilled
|
||||
&& event.filled_quantity == 2
|
||||
}));
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Pending
|
||||
&& event.requested_quantity == 3
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strategy_context_exposes_advanced_rqdata_helpers() {
|
||||
let observed = Rc::new(RefCell::new(Vec::new()));
|
||||
@@ -2837,6 +2990,25 @@ impl BacktestProcessMod for AnyEventCountingMod {
|
||||
}
|
||||
}
|
||||
|
||||
struct NamedEventCountingMod {
|
||||
name: &'static str,
|
||||
sink: Rc<RefCell<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl BacktestProcessMod for NamedEventCountingMod {
|
||||
fn name(&self) -> &str {
|
||||
self.name
|
||||
}
|
||||
|
||||
fn install(&mut self, bus: &mut ProcessEventBus) {
|
||||
let sink = self.sink.clone();
|
||||
bus.add_any_listener(move |event: &ProcessEvent| {
|
||||
sink.borrow_mut()
|
||||
.push(format!("{:?}:{}", event.kind, event.detail));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_installs_process_mods_on_event_bus() {
|
||||
let date = d(2025, 1, 2);
|
||||
@@ -2874,6 +3046,58 @@ fn engine_installs_process_mods_on_event_bus() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_installs_enabled_process_mods_from_loader() {
|
||||
let date = d(2025, 1, 2);
|
||||
let data = single_day_anchor_data(date);
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::DayOpen,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
HookProbeStrategy {
|
||||
log: Rc::new(RefCell::new(Vec::new())),
|
||||
},
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_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::DayOpen,
|
||||
},
|
||||
);
|
||||
let enabled_sink = Rc::new(RefCell::new(Vec::new()));
|
||||
let disabled_sink = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut loader = BacktestProcessModLoader::new();
|
||||
loader.register(NamedEventCountingMod {
|
||||
name: "enabled-counter",
|
||||
sink: enabled_sink.clone(),
|
||||
});
|
||||
loader.register(NamedEventCountingMod {
|
||||
name: "disabled-counter",
|
||||
sink: disabled_sink.clone(),
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
loader.module_names(),
|
||||
vec![
|
||||
"enabled-counter".to_string(),
|
||||
"disabled-counter".to_string()
|
||||
]
|
||||
);
|
||||
let installed =
|
||||
engine.install_enabled_process_mods(&mut loader, &["enabled-counter".to_string()]);
|
||||
engine.run().expect("backtest run");
|
||||
|
||||
assert_eq!(installed, vec!["enabled-counter".to_string()]);
|
||||
assert!(!enabled_sink.borrow().is_empty());
|
||||
assert!(disabled_sink.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_applies_dynamic_universe_and_subscription_directives() {
|
||||
let dates = [d(2025, 1, 2), d(2025, 1, 3), d(2025, 1, 6)];
|
||||
|
||||
Reference in New Issue
Block a user