122 lines
4.3 KiB
Rust
122 lines
4.3 KiB
Rust
use crate::{assets, book_snapshot, inventory::decimal, lots, resident::Books, tick_size::PAR};
|
|
use anyhow::{ensure, Result};
|
|
use rusqlite::{params, Transaction};
|
|
use serde::Deserialize;
|
|
use serde_json::{json, Value};
|
|
|
|
pub(crate) fn flush(tx: &Transaction) -> Result<()> {
|
|
if tx.query_row("SELECT EXISTS(SELECT 1 FROM depth_pending)", [], |r| {
|
|
r.get::<_, bool>(0)
|
|
})? {
|
|
tx.execute_batch(include_str!("depth_flush.sql"))?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn price(units: i64) -> String {
|
|
decimal(units.into(), PAR).to_string()
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub(crate) struct Request {
|
|
market: String,
|
|
after: Option<i64>,
|
|
limit: Option<u32>,
|
|
}
|
|
|
|
/// Batch numbers are local delivery cursors; they are never placed on the wire.
|
|
pub struct MarketPage {
|
|
pub cursor: i64,
|
|
pub frames: Vec<(i64, Value)>,
|
|
pub has_more: bool,
|
|
}
|
|
|
|
impl Request {
|
|
pub fn read(self, tx: &Transaction, books: &mut Books) -> Result<Value> {
|
|
let page = self.page(tx, books)?;
|
|
let events: Vec<_> = page.frames.into_iter().map(|(_, event)| event).collect();
|
|
Ok(json!({"cursor":page.cursor,"events":events,"has_more":page.has_more}))
|
|
}
|
|
|
|
fn page(self, tx: &Transaction, books: &mut Books) -> Result<MarketPage> {
|
|
let limit = self.limit.unwrap_or(100);
|
|
ensure!((1..=500).contains(&limit), "invalid book_feed batch limit");
|
|
let latest: i64 = tx.query_row(
|
|
"SELECT COALESCE((SELECT MAX(seq) FROM depth_batches WHERE market=?1),0) FROM markets WHERE id=?1",
|
|
[&self.market], |r| r.get(0))?;
|
|
let Some(mut cursor) = self.after else {
|
|
let changes = books.changes(tx)?;
|
|
books.apply(changes);
|
|
let mut events = Vec::new();
|
|
for outcome in ["YES", "NO"] {
|
|
let asset = assets::id(&self.market, outcome);
|
|
let frame = book_snapshot::event(tx, books, &asset, false)?;
|
|
events.push((latest, frame));
|
|
}
|
|
return Ok(MarketPage {
|
|
cursor: latest,
|
|
frames: events,
|
|
has_more: false,
|
|
});
|
|
};
|
|
ensure!((0..=latest).contains(&cursor), "invalid book_feed cursor");
|
|
let mut batches = tx.prepare_cached(
|
|
"SELECT seq,strftime('%Y-%m-%dT%H:%M:%f000Z',at_ms/1000.0,'unixepoch'),best_bid,best_ask
|
|
FROM depth_batches WHERE market=?1 AND seq>?2 ORDER BY seq LIMIT ?3")?;
|
|
let mut rows = batches.query(params![self.market, cursor, limit])?;
|
|
let mut events = Vec::new();
|
|
while let Some(row) = rows.next()? {
|
|
cursor = row.get(0)?;
|
|
let stamp: String = row.get(1)?;
|
|
let bid: Option<i64> = row.get(2)?;
|
|
let ask: Option<i64> = row.get(3)?;
|
|
let changes = changes(tx, &self.market, cursor, bid, ask)?;
|
|
let frame = json!({"topic":"market","type":"price_change","payload":{"condition_id":self.market,
|
|
"price_changes":changes,"timestamp":stamp}});
|
|
events.push((cursor, frame));
|
|
}
|
|
Ok(MarketPage {
|
|
cursor,
|
|
frames: events,
|
|
has_more: cursor < latest,
|
|
})
|
|
}
|
|
}
|
|
|
|
pub(crate) fn changes(
|
|
tx: &Transaction,
|
|
market: &str,
|
|
batch: i64,
|
|
bid: Option<i64>,
|
|
ask: Option<i64>,
|
|
) -> Result<Vec<Value>> {
|
|
let mut updates = tx.prepare_cached(
|
|
"SELECT side,price,size FROM depth_updates WHERE batch=? ORDER BY side,price",
|
|
)?;
|
|
let mut levels = updates.query([batch])?;
|
|
let mut changes = Vec::new();
|
|
while let Some(level) = levels.next()? {
|
|
let side: String = level.get(0)?;
|
|
let p: i64 = level.get(1)?;
|
|
let size: i64 = level.get(2)?;
|
|
for (outcome, is_bid, p, bid, ask) in [
|
|
("YES", side == "buy", p, bid, ask),
|
|
(
|
|
"NO",
|
|
side == "sell",
|
|
PAR - p,
|
|
ask.map(|v| PAR - v),
|
|
bid.map(|v| PAR - v),
|
|
),
|
|
] {
|
|
changes.push(
|
|
json!({"asset_id":assets::id(market,outcome),"side":if is_bid {"BUY"} else {"SELL"},
|
|
"price":price(p),"size":decimal(size.into(),lots::PER_SHARE).to_string(),
|
|
"best_bid":bid.map(price),"best_ask":ask.map(price),"hash":null}),
|
|
);
|
|
}
|
|
}
|
|
Ok(changes)
|
|
}
|