Serve priced open interest for active unarchived market listings
This commit is contained in:
@@ -15,6 +15,12 @@ pub(crate) enum Command {
|
||||
previous_ms: i64,
|
||||
scheduled_at_ms: i64,
|
||||
},
|
||||
#[serde(rename = "set_market_visibility")]
|
||||
SetMarketVisibility {
|
||||
market: String,
|
||||
active: bool,
|
||||
archived: bool,
|
||||
},
|
||||
#[serde(rename = "tick_size_change")]
|
||||
TickSizeChange(crate::tick_changes::Change),
|
||||
List {
|
||||
|
||||
@@ -74,7 +74,7 @@ pub(super) fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
"resolutionSource":row.get::<_,Option<String>>("source")?,
|
||||
"outcomes":json!([row.get::<_,String>("yes_label")?,row.get::<_,String>("no_label")?]).to_string(),
|
||||
"clobTokenIds":json!([assets::id(&key,"YES"),assets::id(&key,"NO")]).to_string(),
|
||||
"active":true,"enableOrderBook":true,"acceptingOrders":accepts,"closed":!accepts,
|
||||
"active":row.get::<_,bool>("active")?,"archived":row.get::<_,bool>("archived")?,"enableOrderBook":true,"acceptingOrders":accepts,"closed":!accepts,
|
||||
"orderPriceMinTickSize":tick.number(),"orderMinSize":inventory::decimal(size.into(),inventory::UNIT),
|
||||
"groupItemTitle":row.get::<_,Option<String>>("group_title")?,
|
||||
"bestBid":bid.map(dollars),"bestAsk":ask.map(dollars),"lastTradePrice":last.map(dollars),"outcomePrices":prices,
|
||||
|
||||
@@ -129,7 +129,8 @@ const MARKET_FILTER: &str = "
|
||||
AND (?2='[]' OR w.slug IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3='[]' OR w.market IN (SELECT value FROM json_each(?3)))
|
||||
AND (?4 IS NULL OR w.market IN (SELECT value FROM json_each(?4)))
|
||||
AND (?5 IS NULL OR (m.phase NOT IN ('preopen','continuous'))=?5)";
|
||||
AND (?5 IS NULL OR (m.phase NOT IN ('preopen','continuous'))=?5)
|
||||
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)";
|
||||
const EVENT_FILTER: &str = "
|
||||
WHERE (?1='[]' OR e.event_id IN (SELECT value FROM json_each(?1)))
|
||||
AND (?2='[]' OR e.slug IN (SELECT value FROM json_each(?2)))
|
||||
@@ -159,7 +160,8 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
token_markets,
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset
|
||||
f.offset,
|
||||
f.active
|
||||
],
|
||||
|r| Ok((market(r)?, r.get::<_, Option<String>>("parent")?)),
|
||||
)?
|
||||
@@ -233,8 +235,8 @@ impl Exchange {
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
let f = Filters::parse(resource, fields)?;
|
||||
let order = f.ordering(resource)?;
|
||||
// All current local listings are published, including closed listings.
|
||||
if f.active == Some(false) || f.limit == 0 {
|
||||
// Event publication is independent of each child market.
|
||||
if (resource == DirectoryResource::Events && f.active == Some(false)) || f.limit == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
|
||||
@@ -3,9 +3,10 @@ SELECT w.market, w.id, w.slug, w.question, w.yes_label, w.no_label, m.rules, m.p
|
||||
COALESCE(s.source,t.source) AS source, COALESCE(s.event,t.event) AS parent,
|
||||
COALESCE(a.name,t.group_title) AS group_title,
|
||||
tick.step_micros, minimum.microshares, member.market IS NOT NULL AS neg_risk,
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled, COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
|
||||
FROM market_wire_metadata w
|
||||
JOIN markets m ON m.id=w.market
|
||||
LEFT JOIN market_visibility v ON v.market=w.market
|
||||
LEFT JOIN sports_markets s ON s.market=w.market
|
||||
LEFT JOIN topic_markets t ON t.market=w.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=w.market
|
||||
|
||||
@@ -52,6 +52,7 @@ pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
|
||||
@@ -43,6 +43,19 @@ pub(crate) fn apply(
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::SetMarketVisibility {
|
||||
market,
|
||||
active,
|
||||
archived,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
tx.execute(
|
||||
"INSERT INTO market_visibility(market,active,archived) VALUES(?,?,?)
|
||||
ON CONFLICT(market) DO UPDATE SET active=excluded.active,archived=excluded.archived",
|
||||
params![market,active,archived],
|
||||
)?;
|
||||
Ok(json!({"market":market,"active":active,"archived":archived}))
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::RescheduleSports {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
use crate::{portfolio, validation::IdSelector};
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
portfolio,
|
||||
validation::{condition_filter, IdSelector},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::{params, Connection, TransactionBehavior};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Number, Value};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -48,38 +54,70 @@ impl Request {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let selected = self.market.as_ref().map(IdSelector::ids).transpose()?;
|
||||
let ids = selected.as_ref().map(serde_json::to_string).transpose()?;
|
||||
let mut stmt = db.prepare_cached(include_str!("open_interest.sql"))?;
|
||||
let mut rows = stmt.query([ids])?;
|
||||
let mut by_market = BTreeMap::<String, Interest>::new();
|
||||
let mut global = Interest::default();
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let interest = if selected.is_some() {
|
||||
by_market.entry(market.clone()).or_default()
|
||||
} else {
|
||||
&mut global
|
||||
};
|
||||
let Some(shares) = row.get::<_, Option<i64>>(3)? else {
|
||||
continue;
|
||||
};
|
||||
if shares == 0 {
|
||||
continue;
|
||||
}
|
||||
let outcome: String = row.get(2)?;
|
||||
let phase: String = row.get(1)?;
|
||||
let price =
|
||||
portfolio::price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
|
||||
let value = price.map(|p| i128::from(p) * i128::from(shares));
|
||||
interest.add(shares, value);
|
||||
}
|
||||
let data = if selected.is_none() {
|
||||
vec![global.row(None)?]
|
||||
} else {
|
||||
by_market
|
||||
.iter()
|
||||
.map(|(market, interest)| interest.row(Some(market)))
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
};
|
||||
let data = aggregate(db, ids.as_deref(), false)?
|
||||
.into_iter()
|
||||
.map(|(market, interest)| interest.row(selected.as_ref().map(|_| market.as_str())))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
|
||||
fn aggregate(
|
||||
db: &Connection,
|
||||
ids: Option<&str>,
|
||||
public: bool,
|
||||
) -> Result<BTreeMap<String, Interest>> {
|
||||
let mut stmt = db.prepare_cached(include_str!("open_interest.sql"))?;
|
||||
let mut rows = stmt.query(params![ids, public])?;
|
||||
let mut totals = BTreeMap::<String, Interest>::new();
|
||||
if ids.is_none() {
|
||||
totals.entry("GLOBAL".into()).or_default();
|
||||
}
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let key = if ids.is_some() {
|
||||
market.as_str()
|
||||
} else {
|
||||
"GLOBAL"
|
||||
};
|
||||
let interest = totals.entry(key.to_owned()).or_default();
|
||||
let Some(shares) = row.get::<_, Option<i64>>(3)? else {
|
||||
continue;
|
||||
};
|
||||
if shares == 0 {
|
||||
continue;
|
||||
}
|
||||
let outcome: String = row.get(2)?;
|
||||
let phase: String = row.get(1)?;
|
||||
let price = portfolio::price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
|
||||
let value = price.map(|p| i128::from(p) * i128::from(shares));
|
||||
interest.add(shares, value);
|
||||
}
|
||||
Ok(totals)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct InterestQuery {
|
||||
#[serde(alias = "conditionId", alias = "condition_id")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_open_interest(&self, query: InterestQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
let ids = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let totals =
|
||||
aggregate(&tx, ids.as_deref(), true).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = Vec::with_capacity(totals.len());
|
||||
for (market, interest) in totals {
|
||||
if interest.unpriced_shares > 0 {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
data.push(json!({"condition_id":market,"value":decimal(interest.priced_submicros,1_000_000_000_000)}));
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
WITH candidates AS (
|
||||
WITH requested(id) AS (
|
||||
SELECT value FROM json_each(?1)
|
||||
), candidates AS (
|
||||
SELECT id,phase FROM markets WHERE ?1 IS NULL
|
||||
UNION ALL
|
||||
SELECT id,phase FROM markets WHERE id IN (SELECT value FROM json_each(?1))
|
||||
SELECT id,phase FROM markets WHERE id IN (
|
||||
SELECT id FROM requested
|
||||
UNION ALL
|
||||
SELECT m.id FROM requested r JOIN markets m ON m.id=r.id COLLATE NOCASE
|
||||
WHERE ?2 AND length(r.id)=66 AND r.id GLOB '0x*' AND substr(r.id,3) NOT GLOB '*[^0-9a-fA-F]*'
|
||||
)
|
||||
), selected AS MATERIALIZED (
|
||||
SELECT m.id,m.phase FROM candidates m
|
||||
LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
WHERE a.role IS NULL OR a.role<>'placeholder'
|
||||
LEFT JOIN market_visibility v ON v.market=m.id
|
||||
WHERE (a.role IS NULL OR a.role<>'placeholder')
|
||||
AND (NOT ?2 OR (COALESCE(v.active,1) AND NOT COALESCE(v.archived,0)))
|
||||
), balances AS (
|
||||
SELECT s.id,p.outcome,SUM(p.available+p.reserved) AS shares,p.payout_per_share
|
||||
FROM selected s CROSS JOIN position_units p ON p.market=s.id
|
||||
|
||||
@@ -2,10 +2,10 @@ use super::{marked_holdings, protocol::CONTRACTS};
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
validation::{hex_id, IdSelector},
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::{Connection, TransactionBehavior};
|
||||
use rusqlite::TransactionBehavior;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -17,36 +17,6 @@ pub struct ValueQuery {
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl ValueQuery {
|
||||
fn conditions(&self, db: &Connection) -> Result<Option<String>, MarketDataError> {
|
||||
let Some(raw) = &self.condition else {
|
||||
return Ok(None);
|
||||
};
|
||||
let selector = IdSelector::Many(
|
||||
raw.split(',')
|
||||
.map(str::trim)
|
||||
.map(|id| {
|
||||
if hex_id(id, 64) {
|
||||
id.to_ascii_lowercase()
|
||||
} else {
|
||||
id.to_owned()
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let ids = selector
|
||||
.ids()
|
||||
.map_err(|e| MarketDataError::Invalid(e.to_string()))?;
|
||||
let mut exists = db.prepare_cached("SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)")?;
|
||||
for id in &ids {
|
||||
if !hex_id(id, 64) && !exists.query_row([id], |r| r.get::<_, bool>(0))? {
|
||||
return Err(MarketDataError::Invalid("invalid condition".into()));
|
||||
}
|
||||
}
|
||||
Ok(Some(json!(ids).to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_portfolio_value(&self, query: ValueQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
|
||||
@@ -68,7 +38,7 @@ impl Exchange {
|
||||
{
|
||||
return Err(MarketDataError::Invalid("invalid user".into()));
|
||||
}
|
||||
let conditions = query.conditions(&tx)?;
|
||||
let conditions = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let (priced, missing) = marked_holdings(&tx, user, conditions.as_deref(), wallet)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
if missing != 0 {
|
||||
|
||||
@@ -6,6 +6,11 @@ CREATE TABLE IF NOT EXISTS markets (
|
||||
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
|
||||
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_visibility (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
active INTEGER NOT NULL CHECK(active IN (0,1)), archived INTEGER NOT NULL CHECK(archived IN (0,1))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS market_condition_case ON markets(id COLLATE NOCASE);
|
||||
CREATE TABLE IF NOT EXISTS market_clarifications (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id),
|
||||
content TEXT NOT NULL CHECK(length(trim(content))>0),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::MarketDataError;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{Connection, Transaction};
|
||||
use serde_json::json;
|
||||
pub(crate) fn identifier(id: &str) -> Result<()> {
|
||||
ensure!(
|
||||
!id.trim().is_empty() && id.trim().chars().count() <= 256,
|
||||
@@ -81,3 +83,34 @@ pub(crate) fn directory_selector(
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn condition_filter(
|
||||
raw: Option<&str>,
|
||||
db: &Connection,
|
||||
) -> Result<Option<String>, MarketDataError> {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(None);
|
||||
};
|
||||
let selector = IdSelector::Many(
|
||||
raw.split(',')
|
||||
.map(str::trim)
|
||||
.map(|id| {
|
||||
if hex_id(id, 64) {
|
||||
id.to_ascii_lowercase()
|
||||
} else {
|
||||
id.to_owned()
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let ids = selector
|
||||
.ids()
|
||||
.map_err(|e| MarketDataError::Invalid(e.to_string()))?;
|
||||
let mut exists = db.prepare_cached("SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)")?;
|
||||
for id in &ids {
|
||||
if !hex_id(id, 64) && !exists.query_row([id], |r| r.get::<_, bool>(0))? {
|
||||
return Err(MarketDataError::Invalid(format!("invalid condition: {id}")));
|
||||
}
|
||||
}
|
||||
Ok(Some(json!(ids).to_string()))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user