181 lines
5.6 KiB
Rust
181 lines
5.6 KiB
Rust
use crate::{
|
|
assets,
|
|
inventory::decimal,
|
|
lots,
|
|
minimum_size::MinimumSize,
|
|
quotes::Quote,
|
|
resident::Books,
|
|
tick_size::{TickSize, PAR},
|
|
};
|
|
use anyhow::{Context, Result};
|
|
use matching::Side;
|
|
use rusqlite::{OptionalExtension, Transaction};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{json, Value};
|
|
use sha1::{Digest, Sha1};
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct Level {
|
|
price: String,
|
|
size: String,
|
|
}
|
|
|
|
// Field order is part of the official SDK's SHA-1 preimage.
|
|
#[derive(Serialize, Deserialize)]
|
|
struct Snapshot {
|
|
market: String,
|
|
asset_id: String,
|
|
timestamp: String,
|
|
hash: String,
|
|
bids: Vec<Level>,
|
|
asks: Vec<Level>,
|
|
min_order_size: String,
|
|
tick_size: String,
|
|
neg_risk: bool,
|
|
last_trade_price: String,
|
|
}
|
|
|
|
impl Snapshot {
|
|
fn set_hash(&mut self) -> Result<()> {
|
|
self.hash.clear();
|
|
self.hash = format!("{:x}", Sha1::digest(serde_json::to_vec(self)?));
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
|
|
let (outcome, market) = assets::parse_id(token)?;
|
|
find(tx, books, token, outcome, market)?
|
|
.context("No orderbook exists for the requested token id")
|
|
}
|
|
|
|
fn find(
|
|
tx: &Transaction,
|
|
books: &Books,
|
|
token: &str,
|
|
outcome: &str,
|
|
market: &str,
|
|
) -> Result<Option<Snapshot>> {
|
|
let row: Option<(i64, bool)> = tx
|
|
.query_row(
|
|
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
|
|
FROM book_snapshot_times WHERE market=?1",
|
|
[market],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)
|
|
.optional()?;
|
|
let Some((at_ms, neg_risk)) = row else {
|
|
return Ok(None);
|
|
};
|
|
let book = books.get(market, outcome);
|
|
let levels = |taker| {
|
|
let mut result = Vec::new();
|
|
if let Some(book) = book {
|
|
for (price, size) in book.opposing_levels(taker) {
|
|
result.push(Level {
|
|
price: decimal(price.into(), PAR).to_string(),
|
|
size: decimal(size, lots::PER_SHARE).to_string(),
|
|
});
|
|
}
|
|
result.reverse(); // The reference client walks from the end of each side.
|
|
}
|
|
result
|
|
};
|
|
let mut snapshot = Snapshot {
|
|
market: market.into(),
|
|
asset_id: token.into(),
|
|
timestamp: at_ms.to_string(),
|
|
hash: String::new(),
|
|
bids: levels(Side::Sell),
|
|
asks: levels(Side::Buy),
|
|
min_order_size: MinimumSize::load(tx, market)?
|
|
.map(|s| s.text())
|
|
.unwrap_or_else(|| MinimumSize::format_microshares(lots::MICROS)),
|
|
tick_size: TickSize::load(tx, market)?
|
|
.unwrap_or(TickSize::WHOLE_CENT)
|
|
.text(),
|
|
neg_risk,
|
|
last_trade_price: Quote::current(tx, market, outcome)?
|
|
.last
|
|
.map(|p| decimal(p.into(), PAR).to_string())
|
|
.unwrap_or_default(),
|
|
};
|
|
snapshot.set_hash()?;
|
|
Ok(Some(snapshot))
|
|
}
|
|
|
|
pub(crate) fn read_many(
|
|
tx: &Transaction,
|
|
books: &mut Books,
|
|
tokens: &[String],
|
|
) -> Result<Vec<Value>> {
|
|
let changes = books.changes(tx)?;
|
|
books.apply(changes);
|
|
let mut result = Vec::with_capacity(tokens.len());
|
|
for token in tokens {
|
|
if let Ok((outcome, market)) = assets::parse_id(token) {
|
|
if let Some(book) = find(tx, books, token, outcome, market)? {
|
|
result.push(serde_json::to_value(book)?);
|
|
}
|
|
}
|
|
}
|
|
Ok(result)
|
|
}
|
|
|
|
pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result<Value> {
|
|
let changes = books.changes(tx)?;
|
|
books.apply(changes);
|
|
Ok(serde_json::to_value(build(tx, books, token)?)?)
|
|
}
|
|
|
|
pub(crate) fn event(tx: &Transaction, books: &Books, token: &str, raw: bool) -> Result<Value> {
|
|
let s = build(tx, books, token)?;
|
|
if raw {
|
|
let mut frame = serde_json::to_value(s)?;
|
|
frame["event_type"] = json!("book");
|
|
return Ok(frame);
|
|
}
|
|
let stamp: String = tx.query_row(
|
|
"SELECT strftime('%Y-%m-%dT%H:%M:%f000Z',?1/1000.0,'unixepoch')",
|
|
[&s.timestamp],
|
|
|r| r.get(0),
|
|
)?;
|
|
let last_trade = (!s.last_trade_price.is_empty()).then_some(s.last_trade_price);
|
|
Ok(json!({"topic":"market","type":"book","payload":{
|
|
"condition_id":s.market,"asset_id":s.asset_id,"timestamp":stamp,"bids":s.bids,"asks":s.asks,
|
|
"hash":s.hash,"min_order_size":s.min_order_size,"tick_size":s.tick_size,"neg_risk":s.neg_risk,
|
|
"last_trade_price":last_trade
|
|
}}))
|
|
}
|
|
|
|
pub(crate) fn local_levels(books: &Books, market: &str, outcome: &str, taker: Side) -> Vec<Value> {
|
|
let Some(book) = books.get(market, outcome) else {
|
|
return Vec::new();
|
|
};
|
|
book.opposing_levels(taker)
|
|
.map(|(price, size)| {
|
|
json!({
|
|
"price_micros": price * crate::tick_size::PRICE_MICROS,
|
|
"size": decimal(size, lots::PER_SHARE),
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn reproduces_pinned_python_sdk_hash_vector() {
|
|
let mut sample: Snapshot = serde_json::from_value(json!({
|
|
"market":"0xaabbcc","asset_id":"100","timestamp":"123456789","hash":"prior",
|
|
"bids":[{"price":"0.3","size":"100"},{"price":"0.4","size":"100"}],
|
|
"asks":[{"price":"0.6","size":"100"},{"price":"0.7","size":"100"}],
|
|
"min_order_size":"100","tick_size":"0.01","neg_risk":false,"last_trade_price":"0.5"
|
|
}))
|
|
.unwrap();
|
|
sample.set_hash().unwrap();
|
|
assert_eq!(sample.hash, "0458ea5755c9f73d64a14636fa5c36ed460ec394");
|
|
}
|
|
}
|