Rank market holders by net outcome exposure with per-token pagination
This commit is contained in:
@@ -248,6 +248,7 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
Holders(crate::holders::Request),
|
||||
PortfolioValue {
|
||||
account: String,
|
||||
},
|
||||
@@ -297,6 +298,7 @@ impl Query {
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Activity(filter) => filter.read(db),
|
||||
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
|
||||
Self::Holders(request) => request.read(db),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
use crate::{assets, portfolio, validation::identifier};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Basis {
|
||||
#[default]
|
||||
Net,
|
||||
Gross,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Page {
|
||||
markets: Vec<String>,
|
||||
basis: Basis,
|
||||
min_balance: f64,
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
market: Option<String>,
|
||||
markets: Option<Vec<String>>,
|
||||
basis: Option<Basis>,
|
||||
min_balance: Option<f64>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn page(self) -> Result<Page> {
|
||||
let markets = match (self.market, self.markets) {
|
||||
(Some(m), None) => Some(vec![m]),
|
||||
(None, ms) => ms,
|
||||
_ => anyhow::bail!("specify market or markets"),
|
||||
}
|
||||
.map(|mut ms| {
|
||||
ms.sort();
|
||||
ms.dedup();
|
||||
ms
|
||||
});
|
||||
let page = if let Some(cursor) = self.cursor {
|
||||
let page: Page = serde_json::from_str(&cursor).context("invalid holders cursor")?;
|
||||
ensure!(
|
||||
markets.as_ref().map_or(true, |ms| ms == &page.markets)
|
||||
&& self.basis.map_or(true, |v| v == page.basis)
|
||||
&& self.min_balance.map_or(true, |v| v == page.min_balance),
|
||||
"holders cursor filters differ"
|
||||
);
|
||||
page
|
||||
} else {
|
||||
Page {
|
||||
markets: markets.context("market selector required")?,
|
||||
basis: self.basis.unwrap_or_default(),
|
||||
min_balance: self.min_balance.unwrap_or(0.0),
|
||||
limit: self.limit.unwrap_or(100),
|
||||
offset: 0,
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
(1..=20).contains(&page.markets.len()) && page.markets.windows(2).all(|w| w[0] < w[1]),
|
||||
"expected 1 to 20 distinct markets"
|
||||
);
|
||||
for m in &page.markets {
|
||||
identifier(m)?;
|
||||
}
|
||||
ensure!(
|
||||
page.min_balance.is_finite()
|
||||
&& page.min_balance >= 0.0
|
||||
&& page.offset >= 0
|
||||
&& page.limit <= 1000,
|
||||
"invalid holders window"
|
||||
);
|
||||
if page.basis == Basis::Gross {
|
||||
ensure!(
|
||||
page.markets.len() == 1 && page.limit <= 100,
|
||||
"gross view accepts one market and at most 100 rows per outcome"
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let mut page = self.page()?;
|
||||
if page.limit == 0 {
|
||||
return Ok(json!({"basis":page.basis,"data":[],"next_cursor":null}));
|
||||
}
|
||||
let end = page
|
||||
.offset
|
||||
.checked_add(i64::from(page.limit))
|
||||
.context("holders offset overflow")?;
|
||||
let probe = end.checked_add(1).context("holders offset overflow")?;
|
||||
let mut data = Vec::new();
|
||||
let mut more = false;
|
||||
let mut stmt = db.prepare_cached(include_str!("holders.sql"))?;
|
||||
let gross = page.basis == Basis::Gross;
|
||||
for market in &page.markets {
|
||||
let mut rows =
|
||||
stmt.query(params![market, gross, page.min_balance, page.offset, probe])?;
|
||||
let mut groups: BTreeMap<String, Vec<(String, i64, i64)>> = BTreeMap::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
let rank: i64 = r.get(3)?;
|
||||
if rank > end {
|
||||
more = true;
|
||||
continue;
|
||||
}
|
||||
groups
|
||||
.entry(r.get(1)?)
|
||||
.or_default()
|
||||
.push((r.get(0)?, r.get(2)?, rank));
|
||||
}
|
||||
for outcome in ["YES", "NO"] {
|
||||
let Some(entries) = groups.remove(outcome) else {
|
||||
continue;
|
||||
};
|
||||
let mark = if gross {
|
||||
let (phase, payout): (String, Option<i64>) = db.query_row(
|
||||
"SELECT phase,payout_per_share FROM position_sizes
|
||||
WHERE market=?1 AND account=?2 AND outcome=?3",
|
||||
params![market, &entries[0].0, outcome],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
portfolio::price(db, market, outcome, &phase, payout)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let holders: Vec<_> = entries
|
||||
.into_iter()
|
||||
.map(|(account, amount, rank)| {
|
||||
let mut holder = json!({"account":account,"amount":amount,"rank":rank});
|
||||
if gross {
|
||||
let (price, source) = mark.unzip();
|
||||
holder["current_price_micros"] = json!(price);
|
||||
holder["price_source"] = json!(source);
|
||||
holder["current_value_micros"] =
|
||||
json!(portfolio::holding_value(amount, price));
|
||||
}
|
||||
holder
|
||||
})
|
||||
.collect();
|
||||
data.push(json!({"market":market,"asset_id":assets::id(market,outcome),"outcome":outcome,"holders":holders}));
|
||||
}
|
||||
}
|
||||
page.offset = end;
|
||||
let cursor = if more {
|
||||
Some(serde_json::to_string(&page)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"basis":page.basis,"data":data,"next_cursor":cursor}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
WITH balances AS MATERIALIZED (
|
||||
SELECT account,outcome,available+reserved AS size
|
||||
FROM position_sizes WHERE market=?1
|
||||
), wallets AS (
|
||||
SELECT account,
|
||||
MAX(CASE WHEN outcome='YES' THEN size ELSE 0 END) AS yes,
|
||||
MAX(CASE WHEN outcome='NO' THEN size ELSE 0 END) AS no
|
||||
FROM balances WHERE size>0 AND NOT ?2 GROUP BY account
|
||||
), served AS (
|
||||
SELECT account,CASE WHEN yes>=no THEN 'YES' ELSE 'NO' END AS outcome,ABS(yes-no) AS amount
|
||||
FROM wallets
|
||||
UNION ALL
|
||||
SELECT account,outcome,size FROM balances WHERE ?2 AND size>0
|
||||
), ranked AS (
|
||||
SELECT account,outcome,amount,
|
||||
ROW_NUMBER() OVER (PARTITION BY outcome ORDER BY amount DESC,account) AS ordinal
|
||||
FROM served WHERE amount>=?3
|
||||
)
|
||||
SELECT account,outcome,amount,ordinal FROM ranked
|
||||
WHERE ordinal>?4 AND ordinal<=?5 ORDER BY outcome,ordinal
|
||||
@@ -6,6 +6,7 @@ mod augmented;
|
||||
mod catalog;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod holders;
|
||||
mod twap;
|
||||
mod validation;
|
||||
mod volume;
|
||||
@@ -82,6 +83,7 @@ impl Exchange {
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "holders"
|
||||
| "portfolio_value"
|
||||
| "trades"
|
||||
| "activity"
|
||||
|
||||
@@ -72,7 +72,7 @@ impl Filter {
|
||||
}
|
||||
}
|
||||
|
||||
fn price(
|
||||
pub(crate) fn price(
|
||||
db: &Connection,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
@@ -85,7 +85,7 @@ fn price(
|
||||
Ok(crate::quotes::Quote::current(db, market, outcome)?.mark(phase))
|
||||
}
|
||||
|
||||
fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
|
||||
pub(crate) fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
|
||||
if size == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ CREATE TABLE IF NOT EXISTS positions (
|
||||
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
|
||||
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS positions_by_market ON positions(market,account,outcome);
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
seq INTEGER PRIMARY KEY, account TEXT REFERENCES accounts, market TEXT REFERENCES markets,
|
||||
outcome TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL,
|
||||
|
||||
Reference in New Issue
Block a user