Report single-sided traded shares and taker notional by event and market
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user