Record committed best-bid and ask changes for resumable quote history
This commit is contained in:
@@ -46,6 +46,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
"order"
|
||||
| "book"
|
||||
| "quote"
|
||||
| "quote_history"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
| "open_orders"
|
||||
|
||||
@@ -236,6 +236,7 @@ impl Listing {
|
||||
pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
PricesHistory(crate::prices_history::Request),
|
||||
QuoteHistory(crate::quotes::Filter),
|
||||
Resolution {
|
||||
market: String,
|
||||
},
|
||||
@@ -276,6 +277,7 @@ pub(crate) enum Query {
|
||||
impl Query {
|
||||
pub fn read(self, db: &Transaction, books: &mut crate::resident::Books) -> Result<Value> {
|
||||
match self {
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
Self::PricesHistory(request) => request.read(db),
|
||||
Self::Estimate(request) => request.read(db, books),
|
||||
Self::Resolution { market } => crate::resolution::read(db, &market),
|
||||
@@ -306,13 +308,8 @@ impl Query {
|
||||
}
|
||||
Self::Quote { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
let (bid, ask): (Option<i64>, Option<i64>) = db.query_row(
|
||||
"SELECT MAX(CASE WHEN side='buy' THEN price END),
|
||||
MIN(CASE WHEN side='sell' THEN price END)
|
||||
FROM visible_orders WHERE market=?1 AND outcome=?2",
|
||||
params![market, outcome],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let quote = crate::quotes::Quote::current(db, &market, &outcome)?;
|
||||
let (bid, ask) = (quote.bid, quote.ask);
|
||||
// Fills also cover databases created before timestamped history was introduced.
|
||||
let last: Option<i64> = db.query_row(
|
||||
"SELECT (SELECT price FROM (
|
||||
@@ -331,7 +328,7 @@ impl Query {
|
||||
};
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,
|
||||
"best_bid_micros":bid.map(|p|p*10000),"best_ask_micros":ask.map(|p|p*10000),
|
||||
"quote_seq":quote.seq,"best_bid_micros":bid.map(|p|p*10000),"best_ask_micros":ask.map(|p|p*10000),
|
||||
"last_trade_micros":last.map(|p|p*10000),"display_price_micros":display,"source":source}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,8 @@ pub(crate) fn transaction(
|
||||
let tx = Transaction::new_unchecked(db, behavior)?;
|
||||
let due: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())",
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !due {
|
||||
@@ -44,6 +45,7 @@ pub(crate) fn transaction(
|
||||
for market in markets {
|
||||
crate::market::close_market(&write, &market)?;
|
||||
}
|
||||
crate::quotes::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ mod market;
|
||||
mod neg_risk;
|
||||
mod portfolio;
|
||||
mod prices_history;
|
||||
mod quotes;
|
||||
mod resident;
|
||||
mod resolution;
|
||||
use resident::Books;
|
||||
@@ -43,6 +44,14 @@ impl Exchange {
|
||||
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 tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
@@ -60,6 +69,7 @@ impl Exchange {
|
||||
| "history"
|
||||
| "prices_history"
|
||||
| "quote"
|
||||
| "quote_history"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS quote_events (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
|
||||
yes_bid INTEGER, yes_ask INTEGER, at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS quote_market_seq ON quote_events(market,seq);
|
||||
CREATE INDEX IF NOT EXISTS live_order_price ON orders(market,outcome,side,price) WHERE status='live';
|
||||
CREATE TABLE IF NOT EXISTS quote_pending (market TEXT PRIMARY KEY);
|
||||
CREATE TRIGGER IF NOT EXISTS mark_quote_insert AFTER INSERT ON orders WHEN NEW.status='live' BEGIN
|
||||
INSERT OR IGNORE INTO quote_pending VALUES(NEW.market);
|
||||
END;
|
||||
-- Order market, side, outcome and price are immutable. Only entering or
|
||||
-- leaving the live set can change the best price of an existing order.
|
||||
CREATE TRIGGER IF NOT EXISTS mark_quote_status AFTER UPDATE OF status ON orders
|
||||
WHEN (OLD.status='live')<>(NEW.status='live') BEGIN
|
||||
INSERT OR IGNORE INTO quote_pending VALUES(NEW.market);
|
||||
END;
|
||||
|
||||
CREATE VIEW IF NOT EXISTS changed_quotes AS
|
||||
WITH edges AS MATERIALIZED (
|
||||
SELECT p.market,
|
||||
(SELECT MAX(price) FROM orders WHERE market=p.market AND outcome='YES' AND side='buy' AND status='live') AS direct_bid,
|
||||
(SELECT MIN(price) FROM orders WHERE market=p.market AND outcome='YES' AND side='sell' AND status='live') AS direct_ask,
|
||||
100-(SELECT MIN(price) FROM orders WHERE market=p.market AND outcome='NO' AND side='sell' AND status='live') AS reflected_bid,
|
||||
100-(SELECT MAX(price) FROM orders WHERE market=p.market AND outcome='NO' AND side='buy' AND status='live') AS reflected_ask,
|
||||
(SELECT MAX(seq) FROM quote_events WHERE market=p.market) AS previous
|
||||
FROM quote_pending p
|
||||
), best AS (
|
||||
SELECT market,previous,
|
||||
COALESCE(MAX(direct_bid,reflected_bid),direct_bid,reflected_bid) AS bid,
|
||||
COALESCE(MIN(direct_ask,reflected_ask),direct_ask,reflected_ask) AS ask
|
||||
FROM edges
|
||||
)
|
||||
SELECT b.market,b.bid,b.ask,CAST(unixepoch('subsec')*1000 AS INTEGER) AS at_ms
|
||||
FROM best b LEFT JOIN quote_events old ON old.seq=b.previous
|
||||
WHERE b.bid IS NOT old.yes_bid OR b.ask IS NOT old.yes_ask;
|
||||
-- Capture the final book of a successful command in its receipt transaction.
|
||||
CREATE TRIGGER IF NOT EXISTS record_quote_on_receipt AFTER INSERT ON requests
|
||||
WHEN EXISTS(SELECT 1 FROM quote_pending) BEGIN
|
||||
INSERT INTO quote_events(market,yes_bid,yes_ask,at_ms) SELECT * FROM changed_quotes;
|
||||
DELETE FROM quote_pending;
|
||||
END;
|
||||
|
||||
-- On first install, observe the current live book, without dating it to the
|
||||
-- original order time. Concurrent installers can only enqueue another diff.
|
||||
INSERT OR IGNORE INTO quote_pending SELECT DISTINCT market FROM orders WHERE status='live';
|
||||
COMMIT;
|
||||
@@ -0,0 +1,99 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn flush(tx: &Transaction) -> Result<()> {
|
||||
tx.execute_batch(
|
||||
"INSERT INTO quote_events(market,yes_bid,yes_ask,at_ms) SELECT * FROM changed_quotes;
|
||||
DELETE FROM quote_pending;",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Quote {
|
||||
pub seq: i64,
|
||||
pub bid: Option<i64>,
|
||||
pub ask: Option<i64>,
|
||||
at_ms: Option<i64>,
|
||||
}
|
||||
impl Quote {
|
||||
fn read(row: &Row, outcome: &str) -> rusqlite::Result<Self> {
|
||||
let bid: Option<i64> = row.get(1)?;
|
||||
let ask: Option<i64> = row.get(2)?;
|
||||
let (bid, ask) = if outcome == "YES" {
|
||||
(bid, ask)
|
||||
} else {
|
||||
(ask.map(|p| 100 - p), bid.map(|p| 100 - p))
|
||||
};
|
||||
Ok(Self {
|
||||
seq: row.get(0)?,
|
||||
bid,
|
||||
ask,
|
||||
at_ms: row.get(3)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn current(db: &Connection, market: &str, outcome: &str) -> Result<Self> {
|
||||
Ok(db.query_row("SELECT seq,yes_bid,yes_ask,at_ms FROM quote_events WHERE market=? ORDER BY seq DESC LIMIT 1",
|
||||
[market],|r|Self::read(r,outcome)).optional()?.unwrap_or_default())
|
||||
}
|
||||
|
||||
fn event(&self) -> Value {
|
||||
let pair = self.bid.zip(self.ask);
|
||||
json!({"seq":self.seq,"at_ms":self.at_ms,"best_bid_micros":self.bid.map(|p|p*10000),
|
||||
"best_ask_micros":self.ask.map(|p|p*10000),"spread_micros":pair.map(|(b,a)|(a-b)*10000),
|
||||
"midpoint_micros":pair.map(|(b,a)|(a+b)*5000)})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
market: String,
|
||||
outcome: String,
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
ensure!(
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
[&self.market],
|
||||
|r| r.get::<_, bool>(0)
|
||||
)?,
|
||||
"unknown market"
|
||||
);
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
(1..=1000).contains(&limit) && self.after >= 0,
|
||||
"invalid quote history pagination"
|
||||
);
|
||||
let mut stmt=db.prepare("SELECT seq,yes_bid,yes_ask,at_ms FROM quote_events WHERE market=?1 AND seq>?2 ORDER BY seq LIMIT ?3")?;
|
||||
let mut rows = stmt.query(params![self.market, self.after, limit + 1])?;
|
||||
let mut points = Vec::new();
|
||||
let mut cursor = self.after;
|
||||
let mut more = false;
|
||||
while let Some(row) = rows.next()? {
|
||||
if points.len() == limit as usize {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
let q = Quote::read(row, &self.outcome)?;
|
||||
cursor = q.seq;
|
||||
points.push(q.event());
|
||||
}
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&self.market,&self.outcome),"points":points,"cursor":cursor,"has_more":more}),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user