use crate::{ assets, book::gross_micros, command::TimeInForce, resident::Books, validation::{amount, phase}, }; use anyhow::{ensure, Result}; use matching::{Order, Side}; use rusqlite::Transaction; use serde::Deserialize; use serde_json::{json, Value}; #[derive(Deserialize)] #[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)] pub(crate) enum Request { Buy { market: String, outcome: String, amount_cents: i64, max_price: Option, tif: Option, }, Sell { market: String, outcome: String, qty: Option, size_micros: Option, min_price: Option, tif: Option, }, } impl Request { pub(crate) fn read(self, tx: &Transaction, books: &mut Books) -> Result { let (market, outcome, side, requested, limit, tif) = match self { Self::Buy { market, outcome, amount_cents, max_price, tif, } => (market, outcome, Side::Buy, amount_cents, max_price, tif), Self::Sell { market, outcome, qty, size_micros, min_price, tif, } => ( market, outcome, Side::Sell, crate::lots::amount(qty, size_micros)?, min_price, tif, ), }; let tick = crate::tick_size::TickSize::load(tx, &market)?; let edge = tick.as_ref().map_or(0, |t| i64::from(t.local_step().get())); let limit = limit.unwrap_or(if side == Side::Buy { 100 - edge } else { edge }); let tif = tif.unwrap_or(TimeInForce::Fak); if side == Side::Buy { amount(requested)?; } ensure!( matches!(tif, TimeInForce::Fak | TimeInForce::Fok), "estimate requires FAK or FOK" ); ensure!( matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&limit), "invalid outcome or price" ); if let Some(tick) = tick { tick.check(limit * 10000)?; } phase(tx, &market, &["continuous"])?; let rate = crate::fees::rate(tx, &market)?; if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { match side { Side::Buy => minimum.check_budget(requested, limit, rate)?, Side::Sell => minimum.check_microshares(requested * crate::lots::MICROS)?, } } let changes = books.changes(tx)?; books.apply(changes); // The hypothetical incoming order follows all resting orders in time priority. let mut fills = books .get(&market, &outcome) .map(|b| match side { Side::Buy => b.match_budget_buy(i64::MAX, limit, requested * 100), Side::Sell => b.match_incoming(&Order { seq: i64::MAX, side, price: limit, remaining: requested, }), }) .unwrap_or_default(); if side == Side::Buy { crate::fees::fit_budget(rate, &mut fills, requested); } let fee = crate::fees::total(rate, &fills); let shares: i64 = fills.iter().map(|f| f.quantity).sum(); let gross = gross_micros(&fills); let remaining_cash = if side == Side::Buy { requested * 10000 - gross - fee } else { 0 }; let fully_fillable = match side { Side::Buy => remaining_cash == 0, Side::Sell => requested == shares, }; let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":crate::lots::display(shares), "gross_cents":crate::inventory::decimal(gross.into(),10000),"best_fill_price":fills.first().map(|f|f.price), "worst_fill_price":fills.last().map(|f|f.price), "average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)), "fee_micros":fee,"taker_fee_rate_ppm":rate, "fully_fillable":fully_fillable,"executable":shares>0 && (tif==TimeInForce::Fak || fully_fillable)}); match side { Side::Buy => { result["total_spent_micros"] = json!(gross + fee); result["unspent_cents"] = json!(crate::inventory::decimal(remaining_cash.into(), 10000)); result["unspent_micros"] = json!(remaining_cash); } Side::Sell => { result["net_proceeds_micros"] = json!(gross - fee); result["unsold_shares"] = json!(crate::lots::display(requested - shares)); } } Ok(result) } }