Report single-sided traded shares and taker notional by event and market
This commit is contained in:
@@ -20,6 +20,9 @@ flowchart LR
|
||||
api -->|解析写命令| cmd["src/command.rs"]
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
estimate -->|同步并读取常驻盘口| cache
|
||||
estimate -->|成交金额| book
|
||||
@@ -412,3 +415,22 @@ sequenceDiagram
|
||||
C->>E: quote_history 从 quote_seq 之后续读
|
||||
E-->>C: 顺序返回报价、价差、中点、时间和游标
|
||||
```
|
||||
|
||||
## 赛事目录与成交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: catalog(event) 或 volume(event)
|
||||
E->>D: 打开同一读快照,选择已展示的市场
|
||||
E->>D: 普通成交按 bid 定位市场,互补成交按 market 定位
|
||||
D-->>E: 每笔取一次份额,按吃单方实际结果价统计金额
|
||||
E->>E: 汇总每盘的累计及最近 24 小时,再求赛事总量
|
||||
alt catalog
|
||||
E-->>C: 保留目录顺序,事件和各市场附带 volume
|
||||
else volume
|
||||
E-->>C: 统计时刻、总量及按累计吃单份额降序的成员
|
||||
end
|
||||
```
|
||||
|
||||
@@ -237,6 +237,10 @@ pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
PricesHistory(crate::prices_history::Request),
|
||||
QuoteHistory(crate::quotes::Filter),
|
||||
Volume {
|
||||
event: Option<String>,
|
||||
market: Option<String>,
|
||||
},
|
||||
Resolution {
|
||||
market: String,
|
||||
},
|
||||
@@ -277,6 +281,12 @@ pub(crate) enum Query {
|
||||
impl Query {
|
||||
pub fn read(self, db: &Transaction, books: &mut crate::resident::Books) -> Result<Value> {
|
||||
match self {
|
||||
Self::Volume { event, market } => {
|
||||
Ok(
|
||||
crate::volume::Report::read(db, event.as_deref(), market.as_deref())?
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
Self::PricesHistory(request) => request.read(db),
|
||||
Self::Estimate(request) => request.read(db, books),
|
||||
@@ -357,7 +367,7 @@ impl Query {
|
||||
_ => anyhow::bail!("specify either event or slug"),
|
||||
};
|
||||
identifier(&key)?;
|
||||
let (id, detail) = db.query_row(sql, [key], |r| {
|
||||
let (id, mut detail) = db.query_row(sql, [key], |r| {
|
||||
let id: String = r.get("id")?;
|
||||
let mut event = json!({
|
||||
"id": id, "slug": r.get::<_, String>("slug")?,
|
||||
@@ -381,6 +391,8 @@ impl Query {
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
WHERE event=? AND (a.role IS NULL OR a.role<>'placeholder') ORDER BY group_order,s.market"
|
||||
)?;
|
||||
let volume = crate::volume::Report::read(db, Some(&id), None)?;
|
||||
detail["volume"] = json!(volume.total);
|
||||
let mut rows = stmt.query([id])?;
|
||||
let mut markets = Vec::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
@@ -388,7 +400,7 @@ impl Query {
|
||||
let yes: String = r.get(2)?;
|
||||
let no: String = r.get(3)?;
|
||||
markets.push(
|
||||
json!({"market":market, "outcomes":assets::outcomes(&market,&yes,&no),
|
||||
json!({"market":market, "volume":volume.markets.get(&market), "outcomes":assets::outcomes(&market,&yes,&no),
|
||||
"question":r.get::<_,String>(1)?,
|
||||
"yes_label":yes,
|
||||
"no_label":no,
|
||||
|
||||
@@ -8,6 +8,7 @@ mod estimate;
|
||||
mod expiry;
|
||||
mod twap;
|
||||
mod validation;
|
||||
mod volume;
|
||||
use validation::identifier;
|
||||
mod book;
|
||||
mod cancellation;
|
||||
@@ -70,6 +71,7 @@ impl Exchange {
|
||||
| "prices_history"
|
||||
| "quote"
|
||||
| "quote_history"
|
||||
| "volume"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
|
||||
@@ -128,6 +128,7 @@ CREATE TABLE IF NOT EXISTS execution_context (
|
||||
execution INTEGER PRIMARY KEY, taker_order INTEGER REFERENCES orders(seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS account_orders_history ON orders(account,seq);
|
||||
CREATE INDEX IF NOT EXISTS market_buy_orders ON orders(market,seq) WHERE side='buy';
|
||||
CREATE INDEX IF NOT EXISTS fills_by_bid ON fills(bid,seq);
|
||||
CREATE INDEX IF NOT EXISTS fills_by_ask ON fills(ask,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_yes ON paired_fills(yes_order,seq);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct Totals {
|
||||
matched_shares: i64,
|
||||
taker_shares: i64,
|
||||
taker_notional_cents: i64,
|
||||
unknown_role_shares: i64,
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
fn add(&mut self, other: &Self) -> Result<()> {
|
||||
for (total, value) in [
|
||||
(&mut self.matched_shares, other.matched_shares),
|
||||
(&mut self.taker_shares, other.taker_shares),
|
||||
(&mut self.taker_notional_cents, other.taker_notional_cents),
|
||||
(&mut self.unknown_role_shares, other.unknown_role_shares),
|
||||
] {
|
||||
*total = total.checked_add(value).context("volume overflow")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
pub(crate) struct Volume {
|
||||
all_time: Totals,
|
||||
last_24h: Totals,
|
||||
unknown_time_shares: i64,
|
||||
}
|
||||
|
||||
pub(crate) struct Report {
|
||||
pub as_of_ms: i64,
|
||||
pub total: Volume,
|
||||
pub markets: BTreeMap<String, Volume>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub fn read(db: &Transaction, event: Option<&str>, market: Option<&str>) -> Result<Self> {
|
||||
ensure!(
|
||||
event.is_some() != market.is_some(),
|
||||
"specify event or market"
|
||||
);
|
||||
let as_of_ms = db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut report = Self {
|
||||
as_of_ms,
|
||||
total: Volume::default(),
|
||||
markets: BTreeMap::new(),
|
||||
};
|
||||
let mut stmt = db.prepare_cached(include_str!("volume.sql"))?;
|
||||
let mut rows = stmt.query(params![event, market, as_of_ms])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let volume = report.markets.entry(row.get(0)?).or_default();
|
||||
let recent: Option<bool> = row.get(1)?;
|
||||
let totals = Totals {
|
||||
matched_shares: row.get(2)?,
|
||||
taker_shares: row.get(3)?,
|
||||
taker_notional_cents: row.get(4)?,
|
||||
unknown_role_shares: row.get(5)?,
|
||||
};
|
||||
for v in [volume, &mut report.total] {
|
||||
v.all_time.add(&totals)?;
|
||||
if recent == Some(true) {
|
||||
v.last_24h.add(&totals)?;
|
||||
} else if recent.is_none() {
|
||||
v.unknown_time_shares = v
|
||||
.unknown_time_shares
|
||||
.checked_add(totals.matched_shares)
|
||||
.context("volume overflow")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
market.is_none() || !report.markets.is_empty(),
|
||||
"unknown market"
|
||||
);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub fn response(&self) -> Value {
|
||||
let mut conditions: Vec<_> = self.markets.iter().collect();
|
||||
conditions.sort_by_key(|(id, v)| (std::cmp::Reverse(v.all_time.taker_shares), *id));
|
||||
let conditions: Vec<_> = conditions
|
||||
.into_iter()
|
||||
.map(|(market, volume)| json!({"market":market,"volume":volume}))
|
||||
.collect();
|
||||
json!({"as_of_ms":self.as_of_ms,"volume":self.total,"conditions":conditions})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
-- ?1 selects an event's visible conditions; ?2 selects a single market.
|
||||
WITH selected(market) AS MATERIALIZED (
|
||||
SELECT s.market FROM listed_markets s
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
WHERE s.event=?1 AND (a.role IS NULL OR a.role<>'placeholder')
|
||||
UNION ALL SELECT id FROM markets WHERE id=?2
|
||||
), executions AS (
|
||||
SELECT s.market, f.seq, f.quantity, p.at_ms, f.price AS taker_price
|
||||
FROM selected s CROSS JOIN orders o ON o.market=s.market AND o.side='buy'
|
||||
CROSS JOIN fills f ON f.bid=o.seq LEFT JOIN trade_prices p ON p.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT s.market, f.seq, f.quantity, f.at_ms,
|
||||
CASE c.taker_order WHEN f.yes_order THEN f.yes_price
|
||||
WHEN f.no_order THEN 100-f.yes_price END
|
||||
FROM selected s CROSS JOIN paired_fills f ON f.market=s.market
|
||||
LEFT JOIN execution_context c ON c.execution=f.seq
|
||||
)
|
||||
SELECT s.market, e.at_ms BETWEEN ?3-86400000 AND ?3 AS recent,
|
||||
COALESCE(SUM(e.quantity),0),
|
||||
COALESCE(SUM(e.quantity) FILTER (WHERE c.taker_order IS NOT NULL),0),
|
||||
COALESCE(SUM(e.quantity*e.taker_price) FILTER (WHERE c.taker_order IS NOT NULL),0),
|
||||
COALESCE(SUM(e.quantity) FILTER (WHERE c.execution IS NULL),0)
|
||||
FROM selected s LEFT JOIN executions e ON e.market=s.market
|
||||
LEFT JOIN execution_context c ON c.execution=e.seq
|
||||
GROUP BY s.market,recent
|
||||
@@ -1642,3 +1642,35 @@ fn quote_cursor_replays_only_committed_changes_to_best_prices() {
|
||||
assert_eq!(empty["points"], json!([]));
|
||||
assert_eq!(empty["cursor"], two["cursor"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_and_ranked_volume_count_executions_once_across_conditions() {
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
let mut result = Value::Null;
|
||||
for line in include_str!("../../../docs/examples/football.jsonl")
|
||||
.lines()
|
||||
.chain(include_str!("../../../docs/examples/volume.jsonl").lines())
|
||||
{
|
||||
result = e.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
result["volume"]["all_time"],
|
||||
json!({"matched_shares":5,"taker_shares":5,"taker_notional_cents":180,"unknown_role_shares":0})
|
||||
);
|
||||
assert_eq!(result["volume"]["all_time"], result["volume"]["last_24h"]);
|
||||
assert_eq!(result["conditions"][0]["market"], "full-2-1");
|
||||
assert_eq!(result["conditions"][1]["market"], "half-1-0");
|
||||
let catalog = e
|
||||
.execute(json!({"op":"catalog","event":"cup-a-b"}))
|
||||
.unwrap();
|
||||
assert_eq!(catalog["event"]["volume"], result["volume"]);
|
||||
for condition in result["conditions"].as_array().unwrap() {
|
||||
let listing = catalog["markets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|m| m["market"] == condition["market"])
|
||||
.unwrap();
|
||||
assert_eq!(listing["volume"], condition["volume"]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user