use crate::{ assets, book_snapshot, depth_feed, inventory::decimal, lots, resident::Books, tick_size::TickSize, MarketPage, }; use anyhow::{ensure, Result}; use rusqlite::{params, Transaction}; use serde_json::{json, Value}; pub(crate) fn page( tx: &Transaction, books: &mut Books, market: &str, after: Option, ) -> Result { let latest:i64=tx.query_row( "SELECT COALESCE((SELECT MAX(seq) FROM market_stream_events WHERE market=?1),0) FROM markets WHERE id=?1", [market], |r|r.get(0))?; let mut frames = Vec::new(); let Some(mut cursor) = after else { let changes = books.changes(tx)?; books.apply(changes); for outcome in ["YES", "NO"] { frames.push(( latest, book_snapshot::event(tx, books, &assets::id(market, outcome), true)?, )); } return Ok(MarketPage { cursor: latest, frames, has_more: false, }); }; ensure!( (0..=latest).contains(&cursor), "invalid market stream cursor" ); let mut stmt = tx.prepare_cached( "SELECT seq,kind,source,fee_ppm FROM market_stream_events WHERE market=? AND seq>? ORDER BY seq LIMIT 64", )?; let mut records = stmt.query(params![market, cursor])?; while let Some(row) = records.next()? { cursor = row.get(0)?; let kind: String = row.get(1)?; let source: i64 = row.get(2)?; match kind.as_str() { "depth" => { let (at, bid, ask): (i64, Option, Option) = tx.query_row( "SELECT at_ms,best_bid,best_ask FROM depth_batches WHERE seq=?", [source], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), )?; let changes = depth_feed::changes(tx, market, source, bid, ask)?; frames.push(( cursor, json!({"event_type":"price_change","market":market, "timestamp":at.to_string(),"price_changes":changes}), )); } "tick" => { let (at, old, new): (i64, Option, i64) = tx.query_row( "SELECT at_ms,old_micros,new_micros FROM tick_changes WHERE seq=?", [source], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), )?; for outcome in ["YES", "NO"] { frames.push((cursor,json!({"event_type":"tick_size_change","market":market,"asset_id":assets::id(market,outcome), "timestamp":at.to_string(),"old_tick_size":TickSize(old.unwrap_or(10000)).text(),"new_tick_size":TickSize(new).text()}))); } } "trade" => { for frame in trades(tx, market, source, row.get(3)?)? { frames.push((cursor, frame)); } } _ => anyhow::bail!("invalid market stream record"), } } Ok(MarketPage { cursor, frames, has_more: cursor < latest, }) } fn trades(tx: &Transaction, market: &str, source: i64, fee_ppm: i64) -> Result> { let mut stmt = tx.prepare_cached( "SELECT p.outcome,p.at_ms,p.price_micros,p.quantity, CASE WHEN t.outcome=p.outcome THEN upper(t.side) WHEN t.side='buy' THEN 'SELL' WHEN t.side='sell' THEN 'BUY' END FROM outcome_trade_prices p JOIN execution_context c ON c.execution=p.fill LEFT JOIN orders t ON t.seq=c.taker_order WHERE p.fill=? ORDER BY p.outcome DESC", )?; let mut rows = stmt.query([source])?; let mut frames = Vec::new(); while let Some(r) = rows.next()? { let outcome: String = r.get(0)?; let stamp: i64 = r.get(1)?; let price: i64 = r.get(2)?; let quantity: i64 = r.get(3)?; let side: Option = r.get(4)?; frames.push(json!({"event_type":"last_trade_price","market":market,"asset_id":assets::id(market,&outcome), "timestamp":stamp.to_string(),"price":decimal(price.into(),1_000_000).to_string(), "size":decimal(quantity.into(),lots::PER_SHARE).to_string(),"side":side, "fee_rate_bps":decimal(fee_ppm.into(),100).to_string(),"transaction_hash":null})); } Ok(frames) }