Record committed best-bid and ask changes for resumable quote history
This commit is contained in:
@@ -394,3 +394,21 @@ sequenceDiagram
|
||||
E->>D: 读取该时刻或之前最后一笔成交或实际裁决
|
||||
E-->>C: 一个观测或空数组
|
||||
```
|
||||
|
||||
## 最优报价变化与断线续读
|
||||
|
||||
`lib.rs` 安装 `quote_schema.sql`,按市场保存事务提交时的买一和卖一。常规交易随请求回执写入,`expiry.rs` 在订单到期或定时封盘的事务内用 `quotes.rs` 写入变化。`assets.rs` 和 `catalog.rs` 将资产路由至当前报价或历史查询。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: quote 获取结果资产当前报价
|
||||
E-->>C: 买一、卖一、quote_seq
|
||||
E->>D: 撮合或撤单,同事务标记发生变化的市场
|
||||
D->>D: 提交回执前核对四个直接或互补最优价
|
||||
D->>D: 买一或卖一变化时写入一个市场序号
|
||||
C->>E: quote_history 从 quote_seq 之后续读
|
||||
E-->>C: 顺序返回报价、价差、中点、时间和游标
|
||||
```
|
||||
|
||||
@@ -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}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1576,3 +1576,69 @@ fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
|
||||
.execute(json!({"op":"prices_history","asset_id":"eb:YES:e","start":0,"end":1296001}))
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quote_cursor_replays_only_committed_changes_to_best_prices() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("quotes.sqlite");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
e.execute(json!({"op":"open","id":"start","market":"e"}))
|
||||
.unwrap();
|
||||
let snapshot = json!({"op":"quote","asset_id":"eb:YES:e"});
|
||||
assert_eq!(e.execute(snapshot.clone()).unwrap()["quote_seq"], 0);
|
||||
let bid = order("best", "bob", "buy", 8, 1);
|
||||
e.execute(bid.clone()).unwrap();
|
||||
let first = e.execute(snapshot.clone()).unwrap()["quote_seq"].clone();
|
||||
e.execute(bid).unwrap();
|
||||
let mut mirrored = order("no-buy", "bob", "buy", 91, 1);
|
||||
mirrored["outcome"] = json!("NO");
|
||||
let maker = e.execute(mirrored).unwrap();
|
||||
e.execute(order("behind", "bob", "buy", 7, 1)).unwrap();
|
||||
let page = |asset: &str, seq: &Value| json!({"op":"quote_history","asset_id":asset,"after":seq,"limit":1});
|
||||
let change = e.execute(page("eb:YES:e", &first)).unwrap();
|
||||
let q = &change["points"][0];
|
||||
assert_eq!(q["best_bid_micros"], 80000);
|
||||
assert_eq!(q["best_ask_micros"], 90000);
|
||||
assert_eq!(q["midpoint_micros"], 85000);
|
||||
assert_eq!(q["spread_micros"], 10000);
|
||||
assert_eq!(change["has_more"], false);
|
||||
let reflected = e.execute(page("eb:NO:e", &first)).unwrap();
|
||||
assert_eq!(reflected["points"][0]["best_ask_micros"], 920000);
|
||||
assert_eq!(reflected["points"][0]["best_bid_micros"], 910000);
|
||||
assert_eq!(reflected["cursor"], change["cursor"]);
|
||||
assert_eq!(state(&mut e)["fills"], json!([]));
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
let now: i64 = db
|
||||
.query_row("SELECT unixepoch()", [], |r| r.get(0))
|
||||
.unwrap();
|
||||
let mut dated = order("gtd", "alice", "sell", 9, 1);
|
||||
dated["expiration"] = json!(now + 900);
|
||||
let dated_id = e.execute(dated).unwrap()["order"].clone();
|
||||
e.execute(json!({"op":"cancel","id":"cancel-no","order":maker["order"],"account":"bob"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
e.execute(snapshot.clone()).unwrap()["quote_seq"],
|
||||
change["cursor"]
|
||||
);
|
||||
db.execute(
|
||||
"UPDATE order_deadlines SET expiration=unixepoch()+60 WHERE seq=?",
|
||||
[dated_id.as_i64().unwrap()],
|
||||
)
|
||||
.unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
e.execute(json!({"op":"cancel_all","id":"cancel-bids","account":"bob"}))
|
||||
.unwrap();
|
||||
let one = e.execute(page("eb:YES:e", &change["cursor"])).unwrap();
|
||||
assert_eq!(one["has_more"], true);
|
||||
assert_eq!(one["points"][0]["best_bid_micros"], 80000);
|
||||
assert!(one["points"][0]["best_ask_micros"].is_null());
|
||||
let two = e.execute(page("eb:YES:e", &one["cursor"])).unwrap();
|
||||
assert!(two["points"][0]["best_bid_micros"].is_null());
|
||||
assert!(two["points"][0]["midpoint_micros"].is_null());
|
||||
assert_eq!(two["has_more"], false);
|
||||
let empty = e.execute(page("eb:YES:e", &two["cursor"])).unwrap();
|
||||
assert_eq!(empty["points"], json!([]));
|
||||
assert_eq!(empty["cursor"], two["cursor"]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user