Match immediate buys against a cash budget and price cap
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
| "history"
|
||||
| "open_orders"
|
||||
| "trades"
|
||||
| "market_buy"
|
||||
| "cancel_market_orders"
|
||||
)
|
||||
) {
|
||||
|
||||
@@ -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])?;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user