Align board-specific stock order sizing

This commit is contained in:
boris
2026-04-22 23:12:23 -07:00
parent 7a67e815d7
commit d4f4af6221
3 changed files with 242 additions and 38 deletions

View File

@@ -33,7 +33,8 @@ struct TargetConstraint {
max_target_qty: u32, max_target_qty: u32,
provisional_target_qty: u32, provisional_target_qty: u32,
price: f64, price: f64,
round_lot: u32, minimum_order_quantity: u32,
order_step_size: u32,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -420,7 +421,11 @@ where
let raw_qty = ((equity * weight) / price).floor() as u32; let raw_qty = ((equity * weight) / price).floor() as u32;
desired_targets.insert( desired_targets.insert(
symbol.clone(), symbol.clone(),
self.round_buy_quantity(raw_qty, self.round_lot(data, symbol)), self.round_buy_quantity(
raw_qty,
self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
),
); );
} }
@@ -443,14 +448,16 @@ where
symbol: symbol.clone(), symbol: symbol.clone(),
field: price_field_name(self.execution_price_field), field: price_field_name(self.execution_price_field),
})?; })?;
let round_lot = self.round_lot(data, &symbol); let minimum_order_quantity = self.minimum_order_quantity(data, &symbol);
let order_step_size = self.order_step_size(data, &symbol);
let min_target_qty = self.minimum_target_quantity( let min_target_qty = self.minimum_target_quantity(
date, date,
portfolio, portfolio,
data, data,
&symbol, &symbol,
current_qty, current_qty,
round_lot, minimum_order_quantity,
order_step_size,
); );
let max_target_qty = self.maximum_target_quantity( let max_target_qty = self.maximum_target_quantity(
date, date,
@@ -458,7 +465,8 @@ where
data, data,
&symbol, &symbol,
current_qty, current_qty,
round_lot, minimum_order_quantity,
order_step_size,
); );
let provisional_target_qty = desired_qty.clamp(min_target_qty, max_target_qty); let provisional_target_qty = desired_qty.clamp(min_target_qty, max_target_qty);
if current_qty > provisional_target_qty { if current_qty > provisional_target_qty {
@@ -475,7 +483,8 @@ where
max_target_qty, max_target_qty,
provisional_target_qty, provisional_target_qty,
price, price,
round_lot, minimum_order_quantity,
order_step_size,
}); });
} }
@@ -490,7 +499,8 @@ where
None, None,
constraint.price, constraint.price,
desired_additional, desired_additional,
constraint.round_lot, constraint.minimum_order_quantity,
constraint.order_step_size,
); );
target_qty = (constraint.current_qty + affordable_additional) target_qty = (constraint.current_qty + affordable_additional)
.clamp(constraint.min_target_qty, constraint.max_target_qty); .clamp(constraint.min_target_qty, constraint.max_target_qty);
@@ -518,7 +528,8 @@ where
data: &DataSet, data: &DataSet,
symbol: &str, symbol: &str,
current_qty: u32, current_qty: u32,
round_lot: u32, minimum_order_quantity: u32,
order_step_size: u32,
) -> u32 { ) -> u32 {
if current_qty == 0 { if current_qty == 0 {
return 0; return 0;
@@ -547,7 +558,8 @@ where
snapshot, snapshot,
OrderSide::Sell, OrderSide::Sell,
sellable.min(current_qty), sellable.min(current_qty),
round_lot, minimum_order_quantity,
order_step_size,
0, 0,
sellable >= current_qty, sellable >= current_qty,
) { ) {
@@ -564,7 +576,8 @@ where
data: &DataSet, data: &DataSet,
symbol: &str, symbol: &str,
current_qty: u32, current_qty: u32,
round_lot: u32, minimum_order_quantity: u32,
order_step_size: u32,
) -> u32 { ) -> u32 {
let Ok(snapshot) = data.require_market(date, symbol) else { let Ok(snapshot) = data.require_market(date, symbol) else {
return current_qty; return current_qty;
@@ -582,7 +595,8 @@ where
snapshot, snapshot,
OrderSide::Buy, OrderSide::Buy,
u32::MAX, u32::MAX,
round_lot, minimum_order_quantity,
order_step_size,
0, 0,
false, false,
) { ) {
@@ -660,7 +674,8 @@ where
snapshot, snapshot,
OrderSide::Sell, OrderSide::Sell,
requested_qty.min(sellable), requested_qty.min(sellable),
self.round_lot(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
*intraday_turnover.get(symbol).unwrap_or(&0), *intraday_turnover.get(symbol).unwrap_or(&0),
requested_qty >= position.quantity && sellable >= position.quantity, requested_qty >= position.quantity && sellable >= position.quantity,
); );
@@ -701,6 +716,8 @@ where
data, data,
filled_qty, filled_qty,
self.round_lot(data, symbol), self.round_lot(data, symbol),
self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
filled_qty >= position.quantity, filled_qty >= position.quantity,
execution_cursors, execution_cursors,
None, None,
@@ -810,7 +827,8 @@ where
let current_value = price * current_qty as f64; let current_value = price * current_qty as f64;
let target_qty = self.round_buy_quantity( let target_qty = self.round_buy_quantity(
((target_value.max(0.0)) / price).floor() as u32, ((target_value.max(0.0)) / price).floor() as u32,
self.round_lot(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
); );
if current_qty > target_qty { if current_qty > target_qty {
@@ -884,9 +902,14 @@ where
})?; })?;
if value > 0.0 { if value > 0.0 {
let round_lot = self.round_lot(data, symbol); let round_lot = self.round_lot(data, symbol);
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
let order_step_size = self.order_step_size(data, symbol);
let price = self.sizing_price(snapshot); let price = self.sizing_price(snapshot);
let snapshot_requested_qty = let snapshot_requested_qty = self.round_buy_quantity(
self.round_buy_quantity(((value.abs()) / price).floor() as u32, round_lot); ((value.abs()) / price).floor() as u32,
minimum_order_quantity,
order_step_size,
);
let requested_qty = self.maybe_expand_periodic_value_buy_quantity( let requested_qty = self.maybe_expand_periodic_value_buy_quantity(
date, date,
portfolio, portfolio,
@@ -916,7 +939,8 @@ where
let price = self.sizing_price(snapshot); let price = self.sizing_price(snapshot);
let requested_qty = self.round_buy_quantity( let requested_qty = self.round_buy_quantity(
((value.abs()) / price).floor() as u32, ((value.abs()) / price).floor() as u32,
self.round_lot(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
); );
self.process_sell( self.process_sell(
date, date,
@@ -986,7 +1010,8 @@ where
snapshot, snapshot,
OrderSide::Buy, OrderSide::Buy,
requested_qty, requested_qty,
self.round_lot(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
*intraday_turnover.get(symbol).unwrap_or(&0), *intraday_turnover.get(symbol).unwrap_or(&0),
false, false,
); );
@@ -1014,6 +1039,8 @@ where
data, data,
constrained_qty, constrained_qty,
self.round_lot(data, symbol), self.round_lot(data, symbol),
self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
false, false,
execution_cursors, execution_cursors,
None, None,
@@ -1034,7 +1061,8 @@ where
value_budget.map(|budget| budget + 400.0), value_budget.map(|budget| budget + 400.0),
execution_price, execution_price,
constrained_qty, constrained_qty,
self.round_lot(data, symbol), self.minimum_order_quantity(data, symbol),
self.order_step_size(data, symbol),
); );
(filled_qty, execution_price) (filled_qty, execution_price)
}; };
@@ -1149,9 +1177,47 @@ where
.unwrap_or(self.board_lot_size.max(1)) .unwrap_or(self.board_lot_size.max(1))
} }
fn round_buy_quantity(&self, quantity: u32, round_lot: u32) -> u32 { fn minimum_order_quantity(&self, data: &DataSet, symbol: &str) -> u32 {
let lot = round_lot.max(1); data.instruments()
(quantity / lot) * lot .get(symbol)
.map(|instrument| instrument.minimum_order_quantity())
.unwrap_or(self.board_lot_size.max(1))
}
fn order_step_size(&self, data: &DataSet, symbol: &str) -> u32 {
data.instruments()
.get(symbol)
.map(|instrument| instrument.order_step_size())
.unwrap_or(self.board_lot_size.max(1))
}
fn round_buy_quantity(
&self,
quantity: u32,
minimum_order_quantity: u32,
order_step_size: u32,
) -> u32 {
let step = order_step_size.max(1);
let normalized = (quantity / step) * step;
if normalized < minimum_order_quantity.max(1) {
0
} else {
normalized
}
}
fn decrement_order_quantity(
&self,
quantity: u32,
minimum_order_quantity: u32,
order_step_size: u32,
) -> u32 {
let minimum = minimum_order_quantity.max(1);
if quantity <= minimum {
return 0;
}
let next = quantity.saturating_sub(order_step_size.max(1));
if next < minimum { 0 } else { next }
} }
fn affordable_buy_quantity( fn affordable_buy_quantity(
@@ -1161,21 +1227,27 @@ where
gross_limit: Option<f64>, gross_limit: Option<f64>,
price: f64, price: f64,
requested_qty: u32, requested_qty: u32,
round_lot: u32, minimum_order_quantity: u32,
order_step_size: u32,
) -> u32 { ) -> u32 {
let lot = round_lot.max(1); let mut quantity =
let mut quantity = self.round_buy_quantity(requested_qty, lot); self.round_buy_quantity(requested_qty, minimum_order_quantity, order_step_size);
while quantity > 0 { while quantity > 0 {
let gross = price * quantity as f64; let gross = price * quantity as f64;
if gross_limit.is_some_and(|limit| gross > limit + 1e-6) { if gross_limit.is_some_and(|limit| gross > limit + 1e-6) {
quantity = quantity.saturating_sub(lot); quantity = self.decrement_order_quantity(
quantity,
minimum_order_quantity,
order_step_size,
);
continue; continue;
} }
let cost = self.cost_model.calculate(date, OrderSide::Buy, gross); let cost = self.cost_model.calculate(date, OrderSide::Buy, gross);
if gross + cost.total() <= cash + 1e-6 { if gross + cost.total() <= cash + 1e-6 {
return quantity; return quantity;
} }
quantity = quantity.saturating_sub(lot); quantity =
self.decrement_order_quantity(quantity, minimum_order_quantity, order_step_size);
} }
0 0
} }
@@ -1185,7 +1257,8 @@ where
snapshot: &crate::data::DailyMarketSnapshot, snapshot: &crate::data::DailyMarketSnapshot,
side: OrderSide, side: OrderSide,
requested_qty: u32, requested_qty: u32,
round_lot: u32, minimum_order_quantity: u32,
order_step_size: u32,
consumed_turnover: u32, consumed_turnover: u32,
allow_odd_lot_sell: bool, allow_odd_lot_sell: bool,
) -> Result<u32, String> { ) -> Result<u32, String> {
@@ -1198,8 +1271,6 @@ where
} }
let mut max_fill = requested_qty; let mut max_fill = requested_qty;
let lot = round_lot.max(1);
if self.liquidity_limit { if self.liquidity_limit {
let top_level_liquidity = match side { let top_level_liquidity = match side {
OrderSide::Buy => snapshot.liquidity_for_buy(), OrderSide::Buy => snapshot.liquidity_for_buy(),
@@ -1212,7 +1283,11 @@ where
let top_level_limit = if side == OrderSide::Sell && allow_odd_lot_sell { let top_level_limit = if side == OrderSide::Sell && allow_odd_lot_sell {
top_level_liquidity top_level_liquidity
} else { } else {
self.round_buy_quantity(top_level_liquidity, lot) self.round_buy_quantity(
top_level_liquidity,
minimum_order_quantity,
order_step_size,
)
}; };
max_fill = max_fill.min(top_level_limit); max_fill = max_fill.min(top_level_limit);
} }
@@ -1226,7 +1301,7 @@ where
let volume_limited = if side == OrderSide::Sell && allow_odd_lot_sell { let volume_limited = if side == OrderSide::Sell && allow_odd_lot_sell {
raw_limit as u32 raw_limit as u32
} else { } else {
self.round_buy_quantity(raw_limit as u32, lot) self.round_buy_quantity(raw_limit as u32, minimum_order_quantity, order_step_size)
}; };
if volume_limited == 0 { if volume_limited == 0 {
return Err("tick volume limit".to_string()); return Err("tick volume limit".to_string());
@@ -1246,6 +1321,8 @@ where
data: &DataSet, data: &DataSet,
requested_qty: u32, requested_qty: u32,
round_lot: u32, round_lot: u32,
minimum_order_quantity: u32,
order_step_size: u32,
allow_odd_lot_sell: bool, allow_odd_lot_sell: bool,
_execution_cursors: &mut BTreeMap<String, NaiveDateTime>, _execution_cursors: &mut BTreeMap<String, NaiveDateTime>,
_global_execution_cursor: Option<NaiveDateTime>, _global_execution_cursor: Option<NaiveDateTime>,
@@ -1265,7 +1342,8 @@ where
gross_limit, gross_limit,
execution_price, execution_price,
requested_qty, requested_qty,
round_lot, minimum_order_quantity,
order_step_size,
), ),
OrderSide::Sell => requested_qty, OrderSide::Sell => requested_qty,
}; };
@@ -1295,6 +1373,8 @@ where
start_cursor, start_cursor,
requested_qty, requested_qty,
round_lot, round_lot,
minimum_order_quantity,
order_step_size,
allow_odd_lot_sell, allow_odd_lot_sell,
cash_limit, cash_limit,
gross_limit, gross_limit,
@@ -1313,6 +1393,8 @@ where
start_cursor: Option<NaiveDateTime>, start_cursor: Option<NaiveDateTime>,
requested_qty: u32, requested_qty: u32,
round_lot: u32, round_lot: u32,
minimum_order_quantity: u32,
order_step_size: u32,
allow_odd_lot_sell: bool, allow_odd_lot_sell: bool,
cash_limit: Option<f64>, cash_limit: Option<f64>,
gross_limit: Option<f64>, gross_limit: Option<f64>,
@@ -1357,7 +1439,8 @@ where
} }
let mut take_qty = remaining_qty.min(available_qty); let mut take_qty = remaining_qty.min(available_qty);
if !(side == OrderSide::Sell && allow_odd_lot_sell && take_qty == remaining_qty) { if !(side == OrderSide::Sell && allow_odd_lot_sell && take_qty == remaining_qty) {
take_qty = self.round_buy_quantity(take_qty, lot); take_qty =
self.round_buy_quantity(take_qty, minimum_order_quantity, order_step_size);
} }
if take_qty == 0 { if take_qty == 0 {
continue; continue;
@@ -1367,13 +1450,21 @@ where
while take_qty > 0 { while take_qty > 0 {
let candidate_gross = gross_amount + quote_price * take_qty as f64; let candidate_gross = gross_amount + quote_price * take_qty as f64;
if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) { if gross_limit.is_some_and(|limit| candidate_gross > limit + 1e-6) {
take_qty = take_qty.saturating_sub(lot); take_qty = self.decrement_order_quantity(
take_qty,
minimum_order_quantity,
order_step_size,
);
continue; continue;
} }
if candidate_gross <= cash + 1e-6 { if candidate_gross <= cash + 1e-6 {
break; break;
} }
take_qty = take_qty.saturating_sub(lot); take_qty = self.decrement_order_quantity(
take_qty,
minimum_order_quantity,
order_step_size,
);
} }
if take_qty == 0 { if take_qty == 0 {
break; break;

View File

@@ -20,6 +20,21 @@ impl Instrument {
self.round_lot.max(1) self.round_lot.max(1)
} }
pub fn minimum_order_quantity(&self) -> u32 {
match self.board.trim().to_ascii_uppercase().as_str() {
"KSH" => 200,
"BJS" | "BJ" | "BJSE" => 100,
_ => self.effective_round_lot(),
}
}
pub fn order_step_size(&self) -> u32 {
match self.board.trim().to_ascii_uppercase().as_str() {
"KSH" | "BJS" | "BJ" | "BJSE" => 1,
_ => self.effective_round_lot(),
}
}
pub fn is_delisted_before(&self, date: NaiveDate) -> bool { pub fn is_delisted_before(&self, date: NaiveDate) -> bool {
self.delisted_at self.delisted_at
.is_some_and(|delisted_at| delisted_at < date) .is_some_and(|delisted_at| delisted_at < date)

View File

@@ -478,7 +478,7 @@ fn rebalance_optimizer_skips_unfunded_buy_when_existing_position_cannot_sell() {
} }
#[test] #[test]
fn broker_uses_instrument_round_lot_for_buy_sizing() { fn broker_uses_board_specific_min_quantity_and_step_size_for_buy_sizing() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap(); let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components( let data = DataSet::from_components(
vec![Instrument { vec![Instrument {
@@ -563,7 +563,7 @@ fn broker_uses_instrument_round_lot_for_buy_sizing() {
order_intents: vec![OrderIntent::Value { order_intents: vec![OrderIntent::Value {
symbol: "688001.SH".to_string(), symbol: "688001.SH".to_string(),
value: 10_500.0, value: 10_500.0,
reason: "round_lot".to_string(), reason: "board_min_qty".to_string(),
}], }],
notes: Vec::new(), notes: Vec::new(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
@@ -572,7 +572,105 @@ fn broker_uses_instrument_round_lot_for_buy_sizing() {
.expect("broker execution"); .expect("broker execution");
assert_eq!(report.fill_events.len(), 1); assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 1000); assert_eq!(report.fill_events[0].quantity, 1049);
}
#[test]
fn broker_allows_bjse_quantities_above_minimum_without_round_lot_step() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components(
vec![Instrument {
symbol: "430001.BJ".to_string(),
name: "BJSE".to_string(),
board: "BJS".to_string(),
round_lot: 100,
listed_at: None,
delisted_at: None,
status: "active".to_string(),
}],
vec![DailyMarketSnapshot {
date,
symbol: "430001.BJ".to_string(),
timestamp: Some("2024-01-10 10:18:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.1,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 10.0,
volume: 100_000,
tick_volume: 100_000,
bid1_volume: 80_000,
ask1_volume: 80_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: "430001.BJ".to_string(),
market_cap_bn: 50.0,
free_float_cap_bn: 45.0,
pe_ttm: 20.0,
turnover_ratio: Some(2.0),
effective_turnover_ratio: Some(1.8),
extra_factors: BTreeMap::new(),
}],
vec![CandidateEligibility {
date,
symbol: "430001.BJ".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 mut portfolio = PortfolioState::new(1_010.0);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Open,
);
let report = broker
.execute(
date,
&mut portfolio,
&data,
&StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Value {
symbol: "430001.BJ".to_string(),
value: 1_010.0,
reason: "bj_min_qty".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
assert_eq!(report.fill_events[0].quantity, 100);
} }
#[test] #[test]