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
+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])?;