Reserve sellable quantity for open orders

This commit is contained in:
boris
2026-04-23 03:17:09 -07:00
parent 14326c0847
commit f65267accf
2 changed files with 139 additions and 4 deletions

View File

@@ -739,6 +739,19 @@ where
.retain(|existing| existing.order_id != order_id);
}
fn reserved_open_sell_quantity(&self, symbol: &str, exclude_order_id: Option<u64>) -> u32 {
self.open_orders
.borrow()
.iter()
.filter(|order| {
order.side == OrderSide::Sell
&& order.symbol == symbol
&& exclude_order_id.is_none_or(|order_id| order.order_id != order_id)
})
.map(|order| order.remaining_quantity)
.sum()
}
fn process_open_orders(
&self,
date: NaiveDate,
@@ -1154,7 +1167,9 @@ where
if !rule.allowed {
return current_qty;
}
let sellable = position.sellable_qty(date);
let sellable = position
.sellable_qty(date)
.saturating_sub(self.reserved_open_sell_quantity(symbol, None));
let sell_limit = match self.market_fillable_quantity(
snapshot,
OrderSide::Sell,
@@ -1242,7 +1257,9 @@ where
if !rule.allowed {
return rule.reason;
}
let sellable = position.sellable_qty(date);
let sellable = position
.sellable_qty(date)
.saturating_sub(self.reserved_open_sell_quantity(symbol, None));
match self.market_fillable_quantity(
snapshot,
OrderSide::Sell,
@@ -1397,7 +1414,9 @@ where
);
}
let sellable = position.sellable_qty(date);
let sellable = position
.sellable_qty(date)
.saturating_sub(self.reserved_open_sell_quantity(symbol, Some(order_id)));
let mut partial_fill_reason = if sellable < requested_qty {
Some("sellable quantity limit".to_string())
} else {
@@ -1415,7 +1434,7 @@ where
let fillable_qty = match market_limited_qty {
Ok(quantity) => {
let quantity = quantity.min(sellable);
if quantity < requested_qty {
if quantity < requested_qty.min(sellable) {
partial_fill_reason = merge_partial_fill_reason(
partial_fill_reason,
Some("market liquidity or volume limit"),