Add futures exchange validators
This commit is contained in:
@@ -8,10 +8,10 @@ use fidc_core::{
|
||||
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,
|
||||
FuturesTradingParameter, FuturesValidationConfig, 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 {
|
||||
@@ -408,6 +408,99 @@ impl Strategy for FuturesLimitOrderStrategy {
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesInvalidTickLimitStrategy;
|
||||
|
||||
impl Strategy for FuturesInvalidTickLimitStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"futures-invalid-tick-limit"
|
||||
}
|
||||
|
||||
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),
|
||||
1,
|
||||
3988.13,
|
||||
0.0,
|
||||
"bad tick limit",
|
||||
),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesClosedPhaseOrderStrategy;
|
||||
|
||||
impl Strategy for FuturesClosedPhaseOrderStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"futures-closed-phase-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::open(
|
||||
"IF2501",
|
||||
FuturesDirection::Long,
|
||||
FuturesContractSpec::new(1.0, 0.0, 0.0),
|
||||
1,
|
||||
4000.0,
|
||||
0.0,
|
||||
"closed phase order",
|
||||
),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesAboveUpperLimitStrategy;
|
||||
|
||||
impl Strategy for FuturesAboveUpperLimitStrategy {
|
||||
fn name(&self) -> &str {
|
||||
"futures-above-upper-limit"
|
||||
}
|
||||
|
||||
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),
|
||||
1,
|
||||
5000.0,
|
||||
0.0,
|
||||
"outside upper limit",
|
||||
),
|
||||
}],
|
||||
..StrategyDecision::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct FuturesDepthLimitOrderStrategy;
|
||||
|
||||
impl Strategy for FuturesDepthLimitOrderStrategy {
|
||||
@@ -1431,6 +1524,190 @@ fn engine_matches_pending_futures_limit_order_with_data_driven_costs() {
|
||||
assert!((position.contract_multiplier - 300.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_rejects_futures_limit_orders_not_aligned_to_tick() {
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
two_day_futures_data(),
|
||||
FuturesInvalidTickLimitStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(d(2025, 1, 2)),
|
||||
end_date: Some(d(2025, 1, 2)),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Rejected
|
||||
&& event.reason.contains("not aligned to tick")
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_allows_disabling_futures_limit_tick_validation() {
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
two_day_futures_data(),
|
||||
FuturesInvalidTickLimitStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(d(2025, 1, 2)),
|
||||
end_date: Some(d(2025, 1, 3)),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0)
|
||||
.with_futures_validation_config(FuturesValidationConfig {
|
||||
enforce_limit_price_tick: false,
|
||||
..FuturesValidationConfig::default()
|
||||
});
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert!(
|
||||
result
|
||||
.order_events
|
||||
.iter()
|
||||
.any(|event| event.symbol == "IF2501" && event.status == OrderStatus::Pending)
|
||||
);
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Filled
|
||||
&& event.filled_quantity == 1
|
||||
}));
|
||||
let fill = result
|
||||
.fills
|
||||
.iter()
|
||||
.find(|fill| fill.symbol == "IF2501")
|
||||
.expect("futures fill");
|
||||
assert!((fill.price - 3988.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_rejects_futures_limit_orders_outside_price_limits() {
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
two_day_futures_data(),
|
||||
FuturesAboveUpperLimitStrategy,
|
||||
broker,
|
||||
BacktestConfig {
|
||||
initial_cash: 100_000.0,
|
||||
benchmark_code: "000300.SH".to_string(),
|
||||
start_date: Some(d(2025, 1, 2)),
|
||||
end_date: Some(d(2025, 1, 2)),
|
||||
decision_lag_trading_days: 0,
|
||||
execution_price_field: PriceField::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Rejected
|
||||
&& event.reason.contains("above upper limit")
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_rejects_futures_orders_when_trading_phase_is_closed() {
|
||||
let date = d(2025, 1, 2);
|
||||
let mut future_market = market_row(date, "IF2501", 4000.0, 4000.0);
|
||||
future_market.trading_phase = Some("closed".to_string());
|
||||
let data = DataSet::from_components_with_actions_quotes_and_futures(
|
||||
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), future_market],
|
||||
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,
|
||||
}],
|
||||
)
|
||||
.expect("futures dataset");
|
||||
let broker = BrokerSimulator::new_with_execution_price(
|
||||
ChinaAShareCostModel::default(),
|
||||
ChinaEquityRuleHooks::default(),
|
||||
PriceField::Open,
|
||||
);
|
||||
let mut engine = BacktestEngine::new(
|
||||
data,
|
||||
FuturesClosedPhaseOrderStrategy,
|
||||
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::Open,
|
||||
},
|
||||
)
|
||||
.with_futures_initial_cash(1_000_000.0);
|
||||
|
||||
let result = engine.run().expect("backtest succeeds");
|
||||
|
||||
assert!(result.order_events.iter().any(|event| {
|
||||
event.symbol == "IF2501"
|
||||
&& event.status == OrderStatus::Rejected
|
||||
&& event.reason.contains("trading phase")
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_sweeps_futures_order_book_depth_when_available() {
|
||||
let date = d(2025, 1, 2);
|
||||
|
||||
Reference in New Issue
Block a user