354 lines
13 KiB
Rust
354 lines
13 KiB
Rust
mod account_orders;
|
|
mod account_trades;
|
|
mod activity;
|
|
mod assets;
|
|
mod augmented;
|
|
mod catalog;
|
|
mod depth_feed;
|
|
mod estimate;
|
|
mod expiry;
|
|
mod fees;
|
|
mod gamma_directory;
|
|
mod gamma_list;
|
|
mod heartbeat;
|
|
mod holders;
|
|
mod twap;
|
|
mod validation;
|
|
mod volume;
|
|
use validation::identifier;
|
|
mod book;
|
|
mod book_snapshot;
|
|
mod cancellation;
|
|
mod clarifications;
|
|
mod clob_market;
|
|
mod command;
|
|
mod inventory;
|
|
mod kickoff;
|
|
mod last_trades;
|
|
mod ledger;
|
|
mod lots;
|
|
mod market;
|
|
mod market_amounts;
|
|
mod market_stream;
|
|
mod minimum_size;
|
|
mod neg_risk;
|
|
mod open_interest;
|
|
mod portfolio;
|
|
mod prices_history;
|
|
mod public_trades;
|
|
mod quotes;
|
|
mod resident;
|
|
mod resolution;
|
|
mod tick_changes;
|
|
mod tick_size;
|
|
mod token_directory;
|
|
use resident::Books;
|
|
|
|
use anyhow::{ensure, Context, Result};
|
|
use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, TransactionBehavior};
|
|
use serde_json::{json, Map, Value};
|
|
use std::{path::Path, time::Duration};
|
|
|
|
pub use assets::parse_id as parse_asset_id;
|
|
pub use depth_feed::MarketPage;
|
|
pub use gamma_directory::DirectoryKey;
|
|
pub use gamma_list::DirectoryResource;
|
|
pub use open_interest::InterestQuery;
|
|
pub use portfolio::http::ValueQuery;
|
|
pub use prices_history::http::HistoryQuery;
|
|
pub use prices_history::legacy::ClobHistoryQuery;
|
|
pub use public_trades::http::TradeQuery;
|
|
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
|
pub use resolution::http::ResolutionQuery;
|
|
pub use token_directory::TokenDirectoryQuery;
|
|
|
|
#[derive(Debug)]
|
|
pub enum MarketDataError {
|
|
Invalid(String),
|
|
Unavailable,
|
|
}
|
|
|
|
impl From<rusqlite::Error> for MarketDataError {
|
|
fn from(_: rusqlite::Error) -> Self {
|
|
Self::Unavailable
|
|
}
|
|
}
|
|
|
|
pub type HistoryError = MarketDataError;
|
|
|
|
pub struct Exchange {
|
|
db: Connection,
|
|
books: Books,
|
|
}
|
|
impl Exchange {
|
|
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
|
let mut db = Connection::open(path)?;
|
|
db.busy_timeout(Duration::from_secs(10))?;
|
|
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
|
db.execute_batch(include_str!("schema.sql"))?;
|
|
let submissions_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_submissions')",
|
|
[], |r| r.get(0),
|
|
)?;
|
|
if !submissions_ready {
|
|
db.execute_batch(include_str!("order_submission_schema.sql"))?;
|
|
}
|
|
let directory_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='event_directory_ids')",
|
|
[], |row| row.get(0),
|
|
)?;
|
|
if !directory_ready {
|
|
db.execute_batch(include_str!("event_directory_schema.sql"))?;
|
|
}
|
|
let kickoff_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='sports_kickoffs')",
|
|
[], |r| r.get(0),
|
|
)?;
|
|
if !kickoff_ready {
|
|
db.execute_batch(include_str!("kickoff_schema.sql"))?;
|
|
}
|
|
let activity_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='record_wallet_receipt')",
|
|
[], |r| r.get(0),
|
|
)?;
|
|
if !activity_ready {
|
|
db.execute_batch(include_str!("activity_schema.sql"))?;
|
|
}
|
|
let quotes_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='quote_events')",
|
|
[],
|
|
|row| row.get(0),
|
|
)?;
|
|
if !quotes_ready {
|
|
db.execute_batch(include_str!("quote_schema.sql"))?;
|
|
}
|
|
let history_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_listed')",
|
|
[], |r| r.get(0),
|
|
)?;
|
|
if !history_ready {
|
|
db.execute_batch(include_str!("prices_history/chart_schema.sql"))?;
|
|
}
|
|
let marks_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='last_asset_trades')",
|
|
[], |row| row.get(0),
|
|
)?;
|
|
if !marks_ready {
|
|
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
|
}
|
|
lots::migrate(&mut db)?;
|
|
let snapshot_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
|
if !snapshot_ready {
|
|
db.execute_batch(include_str!("book_snapshot_schema.sql"))?;
|
|
}
|
|
let depth_ready: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='depth_batches')", [], |r| r.get(0))?;
|
|
if !depth_ready {
|
|
db.execute_batch(include_str!("depth_schema.sql"))?;
|
|
}
|
|
let stream_ready:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='market_stream_events')",[],|r|r.get(0))?;
|
|
if !stream_ready {
|
|
db.execute_batch(include_str!("market_stream_schema.sql"))?;
|
|
}
|
|
let lifecycle_ready:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='market_lifecycle_frames')",[],|r|r.get(0))?;
|
|
if !lifecycle_ready {
|
|
db.execute_batch(include_str!("lifecycle_schema.sql"))?;
|
|
}
|
|
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
|
let books = Books::recover(&tx)?;
|
|
tx.commit()?;
|
|
Ok(Self { db, books })
|
|
}
|
|
|
|
/// Run expiry and synchronize the resident book while the transport is idle.
|
|
pub fn maintain(&mut self) -> Result<()> {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let changes = self.books.changes(&tx)?;
|
|
tx.commit()?;
|
|
self.books.apply(changes);
|
|
Ok(())
|
|
}
|
|
|
|
/// Time until the next pending GTD stops trading, measured on the database clock.
|
|
pub fn next_gtd_expiry(&self) -> Result<Option<Duration>> {
|
|
let (first, now): (Option<i64>, i64) = self.db.query_row(
|
|
"SELECT MIN(expiration), CAST(unixepoch('subsec')*1000 AS INTEGER)
|
|
FROM order_deadlines WHERE pending=1",
|
|
[],
|
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
|
)?;
|
|
Ok(first.map(|stated| {
|
|
let cutoff = stated.saturating_sub(60).saturating_mul(1000);
|
|
Duration::from_millis(cutoff.saturating_sub(now).max(0) as u64)
|
|
}))
|
|
}
|
|
|
|
/// Read requested outcome books in one consistent database and resident-book snapshot.
|
|
pub fn public_books(&mut self, tokens: &[String]) -> Result<Vec<Value>> {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let books = book_snapshot::read_many(&tx, &mut self.books, tokens)?;
|
|
tx.commit()?;
|
|
Ok(books)
|
|
}
|
|
|
|
pub fn market_stream_page(&mut self, market: &str, after: Option<i64>) -> Result<MarketPage> {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let page = market_stream::page(&tx, &mut self.books, market, after)?;
|
|
tx.commit()?;
|
|
Ok(page)
|
|
}
|
|
|
|
/// Start at the current catalog boundary, or read announcements after a saved cursor.
|
|
pub fn market_discovery_page(&self, after: Option<i64>) -> Result<MarketPage> {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let page = market_stream::discovery(&tx, after)?;
|
|
tx.commit()?;
|
|
Ok(page)
|
|
}
|
|
|
|
pub fn execute(&mut self, mut payload: Value) -> Result<Value> {
|
|
if payload["op"].as_str() == Some("heartbeat") {
|
|
payload
|
|
.as_object_mut()
|
|
.context("expected object")?
|
|
.remove("op");
|
|
let beat: heartbeat::Beat = serde_json::from_value(payload)?;
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
|
let response = beat.accept(&tx)?;
|
|
tx.commit()?;
|
|
return Ok(response);
|
|
}
|
|
if matches!(
|
|
payload["op"].as_str(),
|
|
Some(
|
|
"assets"
|
|
| "estimate"
|
|
| "limit_amounts"
|
|
| "market_amounts"
|
|
| "tick_history"
|
|
| "catalog"
|
|
| "events"
|
|
| "history"
|
|
| "prices_history"
|
|
| "quote"
|
|
| "price"
|
|
| "prices"
|
|
| "quote_history"
|
|
| "volume"
|
|
| "book_feed"
|
|
| "clob_book"
|
|
| "book"
|
|
| "open_orders"
|
|
| "positions"
|
|
| "holders"
|
|
| "balance"
|
|
| "portfolio_value"
|
|
| "open_interest"
|
|
| "trades"
|
|
| "public_trades"
|
|
| "activity"
|
|
| "resolution"
|
|
)
|
|
) {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let mut request = payload;
|
|
assets::resolve(&tx, &mut request)?;
|
|
let query: catalog::Query = serde_json::from_value(request)?;
|
|
let value = query.read(&tx, &mut self.books)?;
|
|
tx.commit()?;
|
|
return Ok(value);
|
|
}
|
|
if payload == json!({"op":"state"}) {
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
|
let mut state = Map::new();
|
|
for table in [
|
|
"accounts",
|
|
"cash_remainders",
|
|
"position_remainders",
|
|
"collateral_remainders",
|
|
"settlement_dust",
|
|
"execution_fees",
|
|
"markets",
|
|
"positions",
|
|
"orders",
|
|
"fills",
|
|
"paired_fills",
|
|
"neg_risk_groups",
|
|
"neg_risk_conversion_fees",
|
|
"neg_risk_reserve_remainders",
|
|
"augmented_results",
|
|
] {
|
|
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
|
|
let names: Vec<String> =
|
|
stmt.column_names().into_iter().map(str::to_owned).collect();
|
|
let mut rows = stmt.query([])?;
|
|
let mut result = Vec::new();
|
|
while let Some(row) = rows.next()? {
|
|
let mut obj = Map::new();
|
|
for (i, name) in names.iter().enumerate() {
|
|
let v = match row.get_ref(i)? {
|
|
ValueRef::Null => Value::Null,
|
|
ValueRef::Integer(n)
|
|
if matches!(table, "orders" | "fills" | "paired_fills")
|
|
&& matches!(name.as_str(), "quantity" | "remaining") =>
|
|
{
|
|
json!(lots::display(n))
|
|
}
|
|
ValueRef::Integer(n)
|
|
if matches!(table, "orders" | "fills" | "paired_fills")
|
|
&& matches!(name.as_str(), "price" | "yes_price") =>
|
|
{
|
|
json!(crate::inventory::decimal(n.into(), 100))
|
|
}
|
|
ValueRef::Integer(n) => json!(n),
|
|
ValueRef::Text(s) => json!(std::str::from_utf8(s)?),
|
|
_ => anyhow::bail!("unexpected column type"),
|
|
};
|
|
obj.insert(name.clone(), v);
|
|
}
|
|
result.push(Value::Object(obj));
|
|
}
|
|
state.insert(table.into(), Value::Array(result));
|
|
}
|
|
tx.commit()?;
|
|
return Ok(Value::Object(state));
|
|
}
|
|
let id = payload["id"].as_str().context("request id required")?;
|
|
identifier(id)?;
|
|
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
|
let prior: Option<(String, String)> = tx
|
|
.query_row(
|
|
"SELECT payload,response FROM requests WHERE id=?",
|
|
[id],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)
|
|
.optional()?;
|
|
if let Some((saved, reply)) = prior {
|
|
ensure!(
|
|
serde_json::from_str::<Value>(&saved)? == payload,
|
|
"request id reused with different content"
|
|
);
|
|
return Ok(serde_json::from_str(&reply)?);
|
|
}
|
|
let mut body = payload.clone();
|
|
body.as_object_mut()
|
|
.context("expected object")?
|
|
.remove("id");
|
|
assets::resolve(&tx, &mut body)?;
|
|
let command = serde_json::from_value(body)?;
|
|
let external = self.books.changes(&tx)?;
|
|
self.books.apply(external);
|
|
let result = market::apply(&tx, &self.books, command, id)?;
|
|
tx.execute(
|
|
"INSERT INTO requests VALUES(?,?,?)",
|
|
params![id, payload.to_string(), result.to_string()],
|
|
)?;
|
|
depth_feed::flush(&tx)?;
|
|
let changes = self.books.changes(&tx)?;
|
|
tx.commit()?;
|
|
self.books.apply(changes);
|
|
Ok(result)
|
|
}
|
|
}
|