Files
eventbook-exchange/crates/exchange/src/resident.rs
T

150 lines
4.7 KiB
Rust

use anyhow::Result;
use matching::{Order, OrderBook, Side};
use rusqlite::{Row, Transaction};
use std::collections::HashMap;
struct Change {
market: String,
outcome: String,
order: Order,
revision: i64,
}
impl Change {
fn read(row: &Row<'_>) -> rusqlite::Result<Self> {
Ok(Self {
market: row.get(0)?,
outcome: row.get(1)?,
order: Order {
seq: row.get(2)?,
side: if row.get::<_, String>(3)? == "buy" {
Side::Buy
} else {
Side::Sell
},
price: row.get(4)?,
remaining: row.get(5)?,
},
revision: row.get(6)?,
})
}
}
#[derive(Default)]
pub(crate) struct Books {
markets: HashMap<String, HashMap<String, OrderBook>>,
revision: i64,
}
pub(crate) struct Changes(Vec<Change>);
impl Books {
pub fn get(&self, market: &str, outcome: &str) -> Option<&OrderBook> {
self.markets.get(market)?.get(outcome)
}
/// The cash input to an exchange command is in cents, the share input in lots.
pub fn protection_price(
&self,
market: &str,
outcome: &str,
side: Side,
requested: i64,
limit: Option<i64>,
tif: crate::command::TimeInForce,
) -> Option<i64> {
limit.or_else(|| {
// The reference Python SDK sums one binary64 value per public
// price level, in dollars (BUY) or shares (SELL). Match its limit
// selection here; all execution and settlement use integer units.
let target = requested as f64 / 100.0;
let mut depth = 0.0;
let mut last = None;
for (price, lots) in self.get(market, outcome)?.opposing_levels(side) {
let shares = lots as f64 / crate::lots::PER_SHARE as f64;
depth += match side {
Side::Buy => shares * (price as f64 / crate::tick_size::PAR as f64),
Side::Sell => shares,
};
last = Some(price);
if depth >= target {
return last;
}
}
if tif == crate::command::TimeInForce::Fak {
last
} else {
None
}
})
}
pub fn recover(tx: &Transaction) -> Result<Self> {
let mut books = Self::default();
let mut stmt = tx.prepare(
"SELECT market,outcome,seq,side,price,remaining,0 FROM orders WHERE status='live'",
)?;
for row in stmt.query_map([], Change::read)? {
books.install(row?);
}
books.revision = tx.query_row(
"SELECT COALESCE(MAX(revision),0) FROM book_changes",
[],
|r| r.get(0),
)?;
Ok(books)
}
pub fn changes(&self, tx: &Transaction) -> Result<Changes> {
let mut stmt = tx.prepare_cached(
"SELECT o.market, o.outcome, o.seq, o.side, o.price,
CASE WHEN o.status='live' THEN o.remaining ELSE 0 END, c.revision
FROM book_changes c CROSS JOIN orders o ON o.seq=c.seq
WHERE c.revision>? ORDER BY c.revision",
)?;
let rows = stmt
.query_map([self.revision], Change::read)?
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(Changes(rows))
}
pub fn apply(&mut self, changes: Changes) {
for change in changes.0 {
self.install(change);
}
}
fn install(&mut self, change: Change) {
let Change {
market,
outcome,
order,
revision,
} = change;
self.revision = revision;
let books = self.markets.entry(market.clone()).or_default();
let complement = if outcome == "YES" { "NO" } else { "YES" };
let reflected = Order {
seq: order.seq,
remaining: order.remaining,
price: crate::tick_size::PAR - order.price,
side: match order.side {
Side::Buy => Side::Sell,
Side::Sell => Side::Buy,
},
};
// Each view uses its own outcome's price and side. Both entries name the
// same source order, so a match only ever traverses one of the views.
for (name, entry) in [(outcome.as_str(), order), (complement, reflected)] {
let book = books.entry(name.to_owned()).or_default();
book.update(entry);
if book.is_empty() {
books.remove(name);
}
}
if books.is_empty() {
self.markets.remove(&market);
}
}
}