Match immediate buys against a cash budget and price cap

This commit is contained in:
2026-12-03 04:27:01 +08:00
parent c27bb60fd2
commit 763b46f43e
11 changed files with 244 additions and 9 deletions
+3
View File
@@ -23,6 +23,9 @@ sequenceDiagram
alt 连续交易
B->>M: match_incoming,传入一条新订单
M->>M: 从对手方最优价起遍历,同价按原序号分配
else 盘中按金额买入
B->>M: match_budget_buy,传入买单序号、最高价、预算分数
M->>M: 在同一卖盘上逐单扣减可用预算,末档取可负担的整份
else 集合竞价
B->>M: opening,在本簿现有两侧计算统一成交价
end
+30
View File
@@ -37,6 +37,36 @@ impl OrderBook {
}
}
/// Buy whole shares at maker prices, walking the same FIFO ask tree as a limit buy.
pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec<Fill> {
let mut cash = budget;
let mut capacity = i64::MAX;
let mut fills = Vec::new();
for ask in self.asks.values() {
if cash <= 0 || ask.price > limit || capacity == 0 {
break;
}
let affordable = if ask.price == 0 {
capacity
} else {
cash / ask.price
};
let quantity = ask.remaining.min(affordable).min(capacity);
if quantity <= 0 {
break;
}
fills.push(Fill {
bid: seq,
ask: ask.seq,
price: ask.price,
quantity,
});
cash -= ask.price * quantity;
capacity -= quantity;
}
fills
}
pub fn opening(&self) -> Vec<Fill> {
let (Some(bid), Some(ask)) = (self.bids.values().next(), self.asks.values().next()) else {
return Vec::new();