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
+20
View File
@@ -268,3 +268,23 @@ sequenceDiagram
E->>B: 同步撤单并移除对应互补挂单
E-->>C: canceled 与 not_canceled
```
## 按金额买入
```mermaid
sequenceDiagram
participant C as CLI
participant E as Exchange
participant B as 常驻盘口
participant D as SQLite
C->>E: market_buy 指定预算分数、结果、最高价
E->>D: 写事务中预留预算,分配订单号
E->>B: 从最低卖价起按预算计划成交
alt 无可买份额或 FOK 无法用尽预算
E->>D: 回滚预留和新单
else FAK 有成交或 FOK 足额
E->>D: 逐笔交割、退回未花预算、记录回执
E->>B: 提交后更新受影响的盘口
E-->>C: 返回成交份数、实付与未花金额
end
```
+4 -2
View File
@@ -43,7 +43,8 @@ impl Filter {
};
let sql = format!(
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq) FROM orders
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
b.amount_cents,b.spent_cents FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
);
@@ -75,7 +76,8 @@ impl Filter {
"outcome":outcome,"side":row.get::<_,String>(3)?,
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
"status":status,"expiration":row.get::<_,Option<i64>>(8)?}),
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?}),
);
last_id = Some(id);
}
+1
View File
@@ -40,6 +40,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
| "history"
| "open_orders"
| "trades"
| "market_buy"
| "cancel_market_orders"
)
) {
+91 -6
View File
@@ -102,7 +102,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
tif != TimeInForce::Fak || !fills.is_empty(),
"FAK has no matching liquidity"
);
settle(tx, &market, &outcome, fills, Some(seq))?;
settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
}
let (remaining, mut status): (i64, String) = tx.query_row(
"SELECT remaining,status FROM orders WHERE seq=?",
@@ -116,6 +116,88 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
}
pub(crate) struct BudgetBuy {
pub market: String,
pub outcome: String,
pub account: String,
pub amount_cents: i64,
pub max_price: i64,
pub tif: TimeInForce,
}
pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> Result<Value> {
let BudgetBuy {
market,
outcome,
account,
amount_cents,
max_price,
tif,
} = order;
identifier(&account)?;
amount(amount_cents)?;
phase(tx, &market, &["continuous"])?;
ensure!(
matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&max_price),
"invalid outcome or price"
);
ensure!(
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
"market buy requires FAK or FOK"
);
ledger::cash(tx, &account, -amount_cents)?;
tx.execute(
"INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status)
VALUES(?,?,?,'buy',?,0,0,'live')",
params![account, market, outcome, max_price],
)?;
let seq = tx.last_insert_rowid();
let fills = books
.get(&market, &outcome)
.map(|b| b.match_budget_buy(seq, max_price, amount_cents))
.unwrap_or_default();
ensure!(!fills.is_empty(), "no affordable liquidity");
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
let spent: i64 = fills.iter().map(|f| f.price * f.quantity).sum();
let unspent = amount_cents - spent;
ensure!(
tif != TimeInForce::Fok || unspent == 0,
"FOK cannot fill the entire cash amount"
);
tx.execute(
"UPDATE orders SET quantity=?1,remaining=?1 WHERE seq=?2",
params![quantity, seq],
)?;
tx.execute(
"INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
params![seq, amount_cents, spent],
)?;
settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
ledger::cash(tx, &account, unspent)?;
let status = if unspent == 0 {
"filled"
} else {
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
"cancelled"
};
Ok(
json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent}),
)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Taker {
Limit(i64),
Budget(i64),
}
impl Taker {
fn seq(self) -> i64 {
match self {
Self::Limit(seq) | Self::Budget(seq) => seq,
}
}
}
struct ExecutedLeg {
seq: i64,
outcome: String,
@@ -129,6 +211,7 @@ fn book_leg(
view: &str,
fill: &Fill,
seq: i64,
taker: Option<Taker>,
) -> Result<ExecutedLeg> {
let (account, outcome, side, limit): (String, String, String, i64) = tx.query_row(
"SELECT account,outcome,side,price FROM orders
@@ -143,7 +226,9 @@ fn book_leg(
};
if side == "buy" {
ensure!(price <= limit, "buy limit exceeded");
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
if taker != Some(Taker::Budget(seq)) {
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
}
ledger::position(tx, &account, market, &outcome, fill.quantity)?;
} else {
ensure!(price >= limit, "sell limit exceeded");
@@ -162,11 +247,11 @@ pub(crate) fn settle(
market: &str,
outcome: &str,
fills: Vec<Fill>,
taker: Option<i64>,
taker: Option<Taker>,
) -> Result<()> {
for f in fills {
let first = book_leg(tx, market, outcome, &f, f.bid)?;
let second = book_leg(tx, market, outcome, &f, f.ask)?;
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
let second = book_leg(tx, market, outcome, &f, f.ask, taker)?;
let execution: i64 = if first.outcome == second.outcome {
let (buy, sell) = if first.side == "buy" {
(first, second)
@@ -212,7 +297,7 @@ pub(crate) fn settle(
};
tx.execute(
"INSERT INTO execution_context(execution,taker_order) VALUES(?,?)",
params![execution, taker],
params![execution, taker.map(Taker::seq)],
)?;
for seq in [f.bid, f.ask] {
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
+9
View File
@@ -46,6 +46,15 @@ pub(crate) enum Command {
#[serde(default)]
post_only: bool,
},
#[serde(rename = "market_buy")]
MarketBuy {
market: String,
outcome: String,
account: String,
amount_cents: i64,
max_price: i64,
tif: Option<TimeInForce>,
},
Cancel {
account: String,
order: i64,
+19
View File
@@ -138,6 +138,25 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
post_only,
},
),
Command::MarketBuy {
market,
outcome,
account,
amount_cents,
max_price,
tif,
} => book::market_buy(
tx,
books,
book::BudgetBuy {
market,
outcome,
account,
amount_cents,
max_price,
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
},
),
Command::Cancel { order, account } => {
identifier(&account)?;
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
+6
View File
@@ -155,3 +155,9 @@ CREATE VIEW IF NOT EXISTS twap_result AS
FROM twap_markets t
LEFT JOIN twap_reports a ON a.stream=t.stream AND a.observed_at=t.start_at
LEFT JOIN twap_reports b ON b.stream=t.stream AND b.observed_at=t.end_at;
CREATE TABLE IF NOT EXISTS budget_buys (
order_seq INTEGER PRIMARY KEY REFERENCES orders,
amount_cents INTEGER NOT NULL CHECK(amount_cents>0),
spent_cents INTEGER NOT NULL CHECK(spent_cents BETWEEN 0 AND amount_cents)
);
+54
View File
@@ -1089,3 +1089,57 @@ fn market_and_asset_cancels_are_scoped_to_the_original_side() {
.unwrap();
assert_eq!(all, json!({"canceled":[other],"not_canceled":{}}));
}
#[test]
fn cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget() {
let dir = tempdir().unwrap();
let path = dir.path().join("budget.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"fund","id":"c","account":"buyer","cents":170}))
.unwrap();
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
e.execute(order("ask", "alice", "sell", 35, 2)).unwrap();
let mut no = order("other-side", "alice", "buy", 55, 3);
no["outcome"] = json!("NO");
e.execute(no).unwrap();
let request = json!({"op":"market_buy","id":"budget","asset_id":"eb:YES:e","account":"buyer",
"amount_cents":170,"max_price":50});
let before = state(&mut e);
for (field, value) in [
("tif", json!("FOK")),
("amount_cents", json!(171)),
("max_price", json!(34)),
] {
let mut invalid = request.clone();
invalid[field] = value;
assert!(e.execute(invalid).is_err());
assert_eq!(state(&mut e), before);
}
let receipt = e.execute(request.clone()).unwrap();
assert_eq!(receipt["spent_cents"], 160);
assert_eq!(receipt["unspent_cents"], 10);
assert_eq!(receipt["filled"], 4);
assert_eq!(receipt["status"], "cancelled");
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(request).unwrap(), receipt);
let s = state(&mut e);
assert_eq!(s["accounts"][2]["cash"], 10);
assert_eq!(s["paired_fills"][0]["kind"], "mint");
assert_eq!(s["markets"][0]["collateral"], 1200);
let lookup = e
.execute(json!({"op":"open_orders","account":"buyer","order":receipt["order"]}))
.unwrap();
assert_eq!(lookup["orders"][0]["spent_cents"], 160);
assert_eq!(lookup["orders"][0]["open_size"], 0);
let fok = e
.execute(
json!({"op":"market_buy","id":"exact","market":"e","outcome":"YES",
"account":"bob","amount_cents":45,"max_price":45,"tif":"FOK"}),
)
.unwrap();
assert_eq!(fok["spent_cents"], 45);
assert_eq!(fok["status"], "filled");
}