use crate::{assets, book::gross_micros, command::TimeInForce, resident::Books, validation::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: Option, amount_micros: Option, max_price: Option, max_price_micros: Option, tif: Option, }, Sell { market: String, outcome: String, qty: Option, size_micros: Option, min_price: Option, min_price_micros: 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, amount_micros, max_price, max_price_micros, tif, } => ( market, outcome, Side::Buy, crate::market_amounts::cash_cents(amount_cents, amount_micros)?, crate::tick_size::input(max_price, max_price_micros)?, tif, ), Self::Sell { market, outcome, qty, size_micros, min_price, min_price_micros, tif, } => ( market, outcome, Side::Sell, crate::lots::amount(qty, size_micros)?, crate::tick_size::input(min_price, min_price_micros)?, tif, ), }; let tick = crate::tick_size::TickSize::load(tx, &market)?; let tif = tif.unwrap_or(TimeInForce::Fak); ensure!( matches!(tif, TimeInForce::Fak | TimeInForce::Fok), "estimate requires FAK or FOK" ); ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome"); phase(tx, &market, &["continuous"])?; let changes = books.changes(tx)?; books.apply(changes); let protection = books.protection_price(&market, &outcome, side, requested, limit, tif); let amounts = match protection { Some(price) => { crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, price)? } None => None, }; let rate = crate::fees::rate(tx, &market)?; if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? { match (side, protection) { (Side::Buy, Some(price)) => minimum.check_budget(requested, price, rate)?, (Side::Sell, _) => minimum.check_microshares(requested * crate::lots::MICROS)?, (Side::Buy, None) => {} } } // A failed FOK estimate still reports how much depth was visible. let limit = protection.unwrap_or(if side == Side::Buy { crate::tick_size::PAR } else { 0 }); // 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 * 10000), 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 = protection.is_some() && 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|crate::inventory::decimal(f.price.into(),100)), "worst_fill_price":fills.last().map(|f|crate::inventory::decimal(f.price.into(),100)), "average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)), "fee_micros":fee,"taker_fee_rate_ppm":rate, "protection_price_micros":protection.map(|p|p * crate::tick_size::PRICE_MICROS), "fully_fillable":fully_fillable,"executable":protection.is_some() && shares>0 && (tif==TimeInForce::Fak || fully_fillable)}); if let Some(amounts) = amounts { result["order_amounts"] = amounts.json(); } 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) } }