Serve subscribed order book updates over a market WebSocket
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::{parse_asset_id, Exchange, MarketPage};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Control {
|
||||
#[serde(rename = "type")]
|
||||
channel: Option<String>,
|
||||
operation: Option<String>,
|
||||
assets_ids: Vec<String>,
|
||||
initial_dump: Option<bool>,
|
||||
custom_feature_enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Asset {
|
||||
since: i64,
|
||||
bid: Option<String>,
|
||||
ask: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct Market {
|
||||
cursor: i64,
|
||||
assets: BTreeMap<String, Asset>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct Session {
|
||||
opened: bool,
|
||||
custom: bool,
|
||||
markets: BTreeMap<String, Market>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn control(&mut self, engine: &mut Exchange, text: &str) -> Result<Vec<Value>> {
|
||||
let c: Control = serde_json::from_str(text)?;
|
||||
let opening = !self.opened;
|
||||
let subscribe = match (opening, c.channel.as_deref(), c.operation.as_deref()) {
|
||||
(true, Some("market"), None) | (false, None, Some("subscribe")) => true,
|
||||
(false, None, Some("unsubscribe")) => false,
|
||||
_ => anyhow::bail!("invalid market subscription operation"),
|
||||
};
|
||||
ensure!(!c.assets_ids.is_empty(), "assets_ids required");
|
||||
let mut groups = BTreeMap::<String, BTreeSet<String>>::new();
|
||||
for token in c.assets_ids {
|
||||
let (_, market) = parse_asset_id(&token)?;
|
||||
groups.entry(market.into()).or_default().insert(token);
|
||||
}
|
||||
// Validate all assets before replacing a live subscription.
|
||||
let mut next = self.clone();
|
||||
if opening {
|
||||
next.opened = true;
|
||||
next.custom = c.custom_feature_enabled.unwrap_or(false);
|
||||
}
|
||||
let mut snapshots = Vec::new();
|
||||
for (market, mut tokens) in groups {
|
||||
if !subscribe {
|
||||
if let Some(watch) = next.markets.get_mut(&market) {
|
||||
watch.assets.retain(|id, _| !tokens.contains(id));
|
||||
if watch.assets.is_empty() {
|
||||
next.markets.remove(&market);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(watch) = next.markets.get(&market) {
|
||||
tokens.retain(|id| !watch.assets.contains_key(id));
|
||||
}
|
||||
if tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let page = engine.market_stream_page(&market, None)?;
|
||||
let watch = next.markets.entry(market).or_insert_with(|| Market {
|
||||
cursor: page.cursor,
|
||||
assets: BTreeMap::new(),
|
||||
});
|
||||
for (_, snapshot) in page.frames {
|
||||
let id = snapshot["asset_id"]
|
||||
.as_str()
|
||||
.context("snapshot asset missing")?;
|
||||
if !tokens.contains(id) {
|
||||
continue;
|
||||
}
|
||||
let best = |field: &str| {
|
||||
snapshot[field].as_array()?.last()?["price"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
};
|
||||
watch.assets.insert(
|
||||
id.into(),
|
||||
Asset {
|
||||
since: page.cursor,
|
||||
bid: best("bids"),
|
||||
ask: best("asks"),
|
||||
},
|
||||
);
|
||||
if !opening || c.initial_dump.unwrap_or(true) {
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
*self = next;
|
||||
Ok(snapshots)
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, engine: &mut Exchange) -> Result<Vec<Value>> {
|
||||
let mut frames = Vec::new();
|
||||
for (market, watch) in &mut self.markets {
|
||||
let page = engine.market_stream_page(market, Some(watch.cursor))?;
|
||||
watch.project(market, page, self.custom, &mut frames)?;
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
}
|
||||
|
||||
impl Market {
|
||||
fn project(
|
||||
&mut self,
|
||||
market: &str,
|
||||
page: MarketPage,
|
||||
custom: bool,
|
||||
frames: &mut Vec<Value>,
|
||||
) -> Result<()> {
|
||||
for (seq, mut event) in page.frames {
|
||||
let changes = event["price_changes"]
|
||||
.as_array_mut()
|
||||
.context("missing price changes")?;
|
||||
changes.retain(|c| {
|
||||
c["asset_id"]
|
||||
.as_str()
|
||||
.and_then(|id| self.assets.get(id))
|
||||
.is_some_and(|asset| seq > asset.since)
|
||||
});
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut top = Vec::new();
|
||||
if custom {
|
||||
for c in changes.iter() {
|
||||
let token = c["asset_id"].as_str().context("missing changed asset")?;
|
||||
let asset = self
|
||||
.assets
|
||||
.get_mut(token)
|
||||
.context("unknown changed asset")?;
|
||||
let bid = c["best_bid"].as_str();
|
||||
let ask = c["best_ask"].as_str();
|
||||
if (asset.bid.as_deref(), asset.ask.as_deref()) == (bid, ask) {
|
||||
continue;
|
||||
}
|
||||
asset.bid = bid.map(str::to_owned);
|
||||
asset.ask = ask.map(str::to_owned);
|
||||
let spread = bid.zip(ask).map(|(b, a)| spread(a, b)).transpose()?;
|
||||
top.push(
|
||||
json!({"event_type":"best_bid_ask","market":market,"asset_id":token,
|
||||
"best_bid":bid,"best_ask":ask,"spread":spread}),
|
||||
);
|
||||
}
|
||||
}
|
||||
for quote in &mut top {
|
||||
quote["timestamp"] = event["timestamp"].clone();
|
||||
}
|
||||
frames.push(event);
|
||||
frames.extend(top);
|
||||
}
|
||||
self.cursor = page.cursor;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn spread(ask: &str, bid: &str) -> Result<String> {
|
||||
fn units(s: &str) -> Result<i64> {
|
||||
let (w, f) = s.split_once('.').unwrap_or((s, ""));
|
||||
ensure!(f.len() <= 4, "invalid book price precision");
|
||||
Ok(w.parse::<i64>()? * 10000 + format!("{f:0<4}").parse::<i64>()?)
|
||||
}
|
||||
let n = units(ask)? - units(bid)?;
|
||||
let sign = if n < 0 { "-" } else { "" };
|
||||
let n = n.abs();
|
||||
Ok(format!("{sign}{}.{:04}", n / 10000, n % 10000)
|
||||
.trim_end_matches('0')
|
||||
.trim_end_matches('.')
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn adding_an_asset_does_not_skip_backlog_or_replay_before_its_snapshot() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"l","market":"demo","rules":"r"}),
|
||||
json!({"op":"fund","id":"f","account":"maker","cents":200}),
|
||||
json!({"op":"open","id":"o","market":"demo"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let mut session = Session::default();
|
||||
let opening = r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#;
|
||||
assert_eq!(session.control(&mut db, opening).unwrap().len(), 1);
|
||||
db.execute(json!({"op":"order","id":"a","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1})).unwrap();
|
||||
let subscribe = r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#;
|
||||
let snap = session.control(&mut db, subscribe).unwrap();
|
||||
assert_eq!(snap[0]["asks"][0]["price"], "0.8");
|
||||
assert!(session.control(&mut db, subscribe).unwrap().is_empty());
|
||||
let frames = session.poll(&mut db).unwrap();
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0]["price_changes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(frames[0]["price_changes"][0]["asset_id"], "eb:YES:demo");
|
||||
assert!(session.poll(&mut db).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user