use anyhow::{ensure, Context, Result}; use rusqlite::{params, Transaction}; use serde::Serialize; use serde_json::{json, Value}; use std::collections::BTreeMap; fn serialize_hundredths( value: &i64, serializer: S, ) -> std::result::Result { crate::lots::display(*value).serialize(serializer) } fn serialize_cash_cents( value: &i64, serializer: S, ) -> std::result::Result { crate::inventory::decimal((*value).into(), 10000).serialize(serializer) } #[derive(Default, Serialize)] struct Totals { #[serde(serialize_with = "serialize_hundredths")] matched_shares: i64, #[serde(serialize_with = "serialize_hundredths")] taker_shares: i64, #[serde(serialize_with = "serialize_cash_cents")] taker_notional_cents: i64, #[serde(serialize_with = "serialize_hundredths")] unknown_role_shares: i64, } impl Totals { fn add(&mut self, other: &Self) -> Result<()> { for (total, value) in [ (&mut self.matched_shares, other.matched_shares), (&mut self.taker_shares, other.taker_shares), (&mut self.taker_notional_cents, other.taker_notional_cents), (&mut self.unknown_role_shares, other.unknown_role_shares), ] { *total = total.checked_add(value).context("volume overflow")?; } Ok(()) } } #[derive(Default, Serialize)] pub(crate) struct Volume { all_time: Totals, last_24h: Totals, #[serde(serialize_with = "serialize_hundredths")] unknown_time_shares: i64, } pub(crate) struct Report { pub as_of_ms: i64, pub total: Volume, pub markets: BTreeMap, } impl Report { pub fn read(db: &Transaction, event: Option<&str>, market: Option<&str>) -> Result { ensure!( event.is_some() != market.is_some(), "specify event or market" ); let as_of_ms = db.query_row( "SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)", [], |r| r.get(0), )?; let mut report = Self { as_of_ms, total: Volume::default(), markets: BTreeMap::new(), }; let mut stmt = db.prepare_cached(include_str!("volume.sql"))?; let mut rows = stmt.query(params![event, market, as_of_ms])?; while let Some(row) = rows.next()? { let volume = report.markets.entry(row.get(0)?).or_default(); let recent: Option = row.get(1)?; let totals = Totals { matched_shares: row.get(2)?, taker_shares: row.get(3)?, taker_notional_cents: row.get(4)?, unknown_role_shares: row.get(5)?, }; for v in [volume, &mut report.total] { v.all_time.add(&totals)?; if recent == Some(true) { v.last_24h.add(&totals)?; } else if recent.is_none() { v.unknown_time_shares = v .unknown_time_shares .checked_add(totals.matched_shares) .context("volume overflow")?; } } } ensure!( market.is_none() || !report.markets.is_empty(), "unknown market" ); Ok(report) } pub fn response(&self) -> Value { let mut conditions: Vec<_> = self.markets.iter().collect(); conditions.sort_by_key(|(id, v)| (std::cmp::Reverse(v.all_time.taker_shares), *id)); let conditions: Vec<_> = conditions .into_iter() .map(|(market, volume)| json!({"market":market,"volume":volume})) .collect(); json!({"as_of_ms":self.as_of_ms,"volume":self.total,"conditions":conditions}) } }