use crate::{command::TimeInForce, resident::Books}; use crate::{ ledger, validation::{amount, identifier, phase}, }; use anyhow::{ensure, Result}; use matching::{Fill, Order, Side}; use rusqlite::{params, Transaction}; use serde_json::{json, Value}; pub(crate) struct NewOrder { pub market: String, pub account: String, pub key_id: Option, pub outcome: String, pub side: String, pub price: i64, pub qty: i64, pub tif: TimeInForce, pub expiration: Option, pub post_only: bool, } pub(crate) struct ShareExecution { pub seq: i64, pub filled: i64, pub status: String, pub gross_cents: i64, pub fee_micros: i64, } impl ShareExecution { pub fn receipt(&self) -> Value { let mut receipt = json!({"order":self.seq,"filled":self.filled,"status":self.status}); if self.fee_micros > 0 { receipt["fee_micros"] = json!(self.fee_micros); } receipt } } pub(crate) fn gross_cents(fills: &[Fill]) -> i64 { fills.iter().map(|f| f.price * f.quantity).sum() } pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result { let NewOrder { market, account, key_id, outcome, side, price, qty, tif, expiration, post_only, } = order; identifier(&account)?; amount(qty)?; let stage = phase(tx, &market, &["preopen", "continuous"])?; ensure!( matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"), "invalid instrument or side" ); ensure!((0..=100).contains(&price), "invalid price"); ensure!( tif == TimeInForce::Gtc || stage == "continuous", "unsupported time in force" ); ensure!( !post_only || (stage == "continuous" && matches!(tif, TimeInForce::Gtc | TimeInForce::Gtd)), "post-only requires continuous GTC or GTD" ); if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { minimum.check_shares(qty)?; } if let Some(tick) = crate::tick_size::TickSize::load(tx, &market)? { tick.check(price * 10000)?; } let deadline = match tif { TimeInForce::Gtd => { let expiration = expiration.ok_or_else(|| anyhow::anyhow!("GTD requires expiration"))?; let now: i64 = tx.query_row("SELECT unixepoch()", [], |r| r.get(0))?; ensure!( expiration >= now + 180, "GTD expiration must be at least 180 seconds ahead" ); Some(expiration) } _ => { ensure!(expiration.unwrap_or(0) == 0, "expiration requires GTD"); None } }; if side == "buy" { ledger::cash(tx, &account, -price * qty)?; } else { ledger::position(tx, &account, &market, &outcome, -qty)?; } tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?; let seq = tx.last_insert_rowid(); crate::heartbeat::record_key(tx, seq, key_id.as_deref())?; if let Some(deadline) = deadline { tx.execute( "INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)", params![seq, deadline], )?; } let mut gross = 0; let mut fee_micros = 0; if stage == "continuous" { let incoming = Order { seq, side: if side == "buy" { Side::Buy } else { Side::Sell }, price, remaining: qty, }; let fills = books .get(&market, &outcome) .map(|book| book.match_incoming(&incoming)) .unwrap_or_default(); ensure!( !post_only || fills.is_empty(), "post-only order would take liquidity" ); if tif == TimeInForce::Fok { ensure!( fills.iter().map(|fill| fill.quantity).sum::() == qty, "FOK cannot fill the entire order" ); } ensure!( tif != TimeInForce::Fak || !fills.is_empty(), "FAK has no matching liquidity" ); gross = gross_cents(&fills); fee_micros = 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=?", [seq], |r| Ok((r.get(0)?, r.get(1)?)), )?; if matches!(tif, TimeInForce::Ioc | TimeInForce::Fak) && remaining > 0 { release(tx, seq, &account, CancelReason::Cancelled)?; status = "cancelled".into(); } if fee_micros > 0 { ledger::cash_micros(tx, &account, -fee_micros)?; } Ok(ShareExecution { fee_micros, seq, filled: qty - remaining, status, gross_cents: gross, }) } pub(crate) struct BudgetBuy { pub market: String, pub outcome: String, pub account: String, pub key_id: Option, pub amount_cents: i64, pub max_price: i64, pub tif: TimeInForce, } pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> Result { let BudgetBuy { key_id, 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" ); let rate = crate::fees::rate(tx, &market)?; if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { minimum.check_budget(amount_cents, max_price, rate)?; } if let Some(tick) = crate::tick_size::TickSize::load(tx, &market)? { tick.check(max_price * 10000)?; } 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(); crate::heartbeat::record_key(tx, seq, key_id.as_deref())?; let mut fills = books .get(&market, &outcome) .map(|b| b.match_budget_buy(seq, max_price, amount_cents)) .unwrap_or_default(); crate::fees::fit_budget(rate, &mut fills, amount_cents); ensure!(!fills.is_empty(), "no affordable liquidity"); let quantity: i64 = fills.iter().map(|f| f.quantity).sum(); let spent = gross_cents(&fills); let gross_remainder = amount_cents - spent; let unspent_micros = gross_remainder * 10000 - crate::fees::total(rate, &fills); ensure!( tif != TimeInForce::Fok || unspent_micros == 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], )?; let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?; ledger::cash_micros(tx, &account, gross_remainder * 10000 - fee)?; let status = if unspent_micros == 0 { "filled" } else { tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?; "cancelled" }; let mut receipt = json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent_micros/10000}); if fee > 0 { receipt["fee_micros"] = json!(fee); receipt["unspent_micros"] = json!(unspent_micros); receipt["total_spent_micros"] = json!(spent * 10000 + fee); } Ok(receipt) } #[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, side: String, price: i64, } fn book_leg( tx: &Transaction, market: &str, view: &str, fill: &Fill, seq: i64, taker: Option, ) -> Result { let (account, outcome, side, limit): (String, String, String, i64) = tx.query_row( "SELECT account,outcome,side,price FROM orders WHERE seq=? AND market=? AND status='live' AND remaining>=?", params![seq, market, fill.quantity], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), )?; let price = if outcome == view { fill.price } else { 100 - fill.price }; if side == "buy" { ensure!(price <= limit, "buy limit exceeded"); 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"); ledger::cash(tx, &account, price * fill.quantity)?; } Ok(ExecutedLeg { seq, outcome, side, price, }) } pub(crate) fn settle( tx: &Transaction, market: &str, outcome: &str, fills: Vec, taker: Option, ) -> Result { let rate = if taker.is_some() && !fills.is_empty() { crate::fees::rate(tx, market)? } else { 0 }; let mut fees = 0; for f in fills { 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) } else { (second, first) }; ensure!(buy.side == "buy" && sell.side == "sell", "invalid transfer"); tx.query_row("INSERT INTO fills(seq,bid,ask,price,quantity) SELECT id,?1,?2,?3,?4 FROM next_execution RETURNING seq", params![buy.seq,sell.seq,buy.price,f.quantity], |r|r.get(0))? } else { ensure!(first.side == second.side, "invalid complementary legs"); let mint = first.side == "buy"; let delta = if mint { 100 * f.quantity } else { -100 * f.quantity }; ensure!( tx.execute( "UPDATE markets SET collateral=collateral+?1 WHERE id=?2 AND collateral+?1>=0", params![delta, market] )? == 1, "insufficient collateral" ); let (yes, no) = if first.outcome == "YES" { (first, second) } else { (second, first) }; tx.query_row( "INSERT INTO paired_fills(seq,market,kind,yes_order,no_order,yes_price,quantity) SELECT id,?1,?2,?3,?4,?5,?6 FROM next_execution RETURNING seq", params![ market, if mint { "mint" } else { "merge" }, yes.seq, no.seq, yes.price, f.quantity ], |r| r.get(0), )? }; tx.execute( "INSERT INTO execution_context(execution,taker_order) VALUES(?,?)", params![execution, taker.map(Taker::seq)], )?; if let Some(taker) = taker { let fee = crate::fees::micros(rate, f.price * 10000, f.quantity); if fee > 0 { tx.execute( "INSERT INTO execution_fees VALUES(?,?,?)", params![execution, taker.seq(), fee], )?; fees += fee; } } 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])?; } } Ok(fees) } pub(crate) enum CancelReason { Cancelled, Expired, } pub(crate) fn release( tx: &Transaction, seq: i64, owner: &str, reason: CancelReason, ) -> Result { let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?; if side == "buy" { ledger::cash(tx, owner, price * qty)?; } else { ledger::position(tx, owner, &market, &outcome, qty)?; } let status = match reason { CancelReason::Cancelled => "cancelled", CancelReason::Expired => "expired", }; tx.execute( "UPDATE orders SET status=? WHERE seq=?", params![status, seq], )?; Ok(qty) }