Expose event and market directory details with consistent outcome prices
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
use crate::{
|
||||
assets, inventory, lots,
|
||||
quotes::display_price,
|
||||
tick_size::{TickSize, PAR},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, ToSql};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Slugs and numeric IDs are independent namespaces, including numeric-looking slugs.
|
||||
pub enum DirectoryKey<'a> {
|
||||
Id(i64),
|
||||
Slug(&'a str),
|
||||
}
|
||||
|
||||
fn header(row: &Row<'_>) -> rusqlite::Result<(String, Value)> {
|
||||
let key = row.get("id")?;
|
||||
let event = json!({
|
||||
"id":row.get::<_,i64>("event_id")?.to_string(),"slug":row.get::<_,String>("slug")?,
|
||||
"title":row.get::<_,String>("title")?,"category":row.get::<_,String>("category")?
|
||||
});
|
||||
Ok((key, event))
|
||||
}
|
||||
|
||||
fn event_header(
|
||||
db: &Connection,
|
||||
column: &str,
|
||||
key: &dyn ToSql,
|
||||
) -> rusqlite::Result<Option<(String, Value)>> {
|
||||
let sql =
|
||||
format!("SELECT id,event_id,slug,title,category FROM numbered_events WHERE {column}=?1");
|
||||
db.prepare_cached(&sql)?.query_row([key], header).optional()
|
||||
}
|
||||
|
||||
fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
let key: String = row.get("market")?;
|
||||
let phase: String = row.get("phase")?;
|
||||
let accepts = matches!(phase.as_str(), "preopen" | "continuous");
|
||||
let size = row
|
||||
.get::<_, Option<i64>>("microshares")?
|
||||
.unwrap_or(lots::MICROS);
|
||||
let tick = row
|
||||
.get::<_, Option<i64>>("step_micros")?
|
||||
.map(TickSize)
|
||||
.unwrap_or(TickSize::WHOLE_CENT);
|
||||
let bid: Option<i64> = row.get("yes_bid")?;
|
||||
let ask: Option<i64> = row.get("yes_ask")?;
|
||||
let last: Option<i64> = row.get("yes_last")?;
|
||||
let no_last = row.get("no_last")?;
|
||||
let marks = match row.get::<_, Option<String>>("winner")?.as_deref() {
|
||||
Some("YES") => Some((inventory::UNIT, 0)),
|
||||
Some("NO") => Some((0, inventory::UNIT)),
|
||||
Some("VOID") => Some((inventory::UNIT / 2, inventory::UNIT / 2)),
|
||||
_ => display_price(bid, ask, last, &phase)
|
||||
.zip(display_price(
|
||||
ask.map(|p| PAR - p),
|
||||
bid.map(|p| PAR - p),
|
||||
no_last,
|
||||
&phase,
|
||||
))
|
||||
.map(|(yes, no)| (yes.0, no.0)),
|
||||
};
|
||||
let prices = marks.map(|(yes, no)| {
|
||||
json!([
|
||||
inventory::decimal(yes.into(), inventory::UNIT).to_string(),
|
||||
inventory::decimal(no.into(), inventory::UNIT).to_string()
|
||||
])
|
||||
.to_string()
|
||||
});
|
||||
let dollars = |p: i64| inventory::decimal(p.into(), PAR);
|
||||
Ok(json!({
|
||||
"id":row.get::<_,String>("id")?,"conditionId":key,"slug":row.get::<_,String>("slug")?,
|
||||
"question":row.get::<_,String>("question")?,"description":row.get::<_,String>("rules")?,
|
||||
"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(),
|
||||
"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,
|
||||
"negRisk":row.get::<_,bool>("neg_risk")?,"feesEnabled":row.get::<_,bool>("fees_enabled")?
|
||||
}))
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_market(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let (column, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("id", id),
|
||||
DirectoryKey::Slug(slug) => ("slug", slug),
|
||||
};
|
||||
let sql = format!(
|
||||
"{} AND w.market=(SELECT market FROM market_directory_ids WHERE {column}=?1)",
|
||||
include_str!("gamma_market.sql")
|
||||
);
|
||||
let record = tx
|
||||
.prepare_cached(&sql)?
|
||||
.query_row([arg], |r| {
|
||||
Ok((market(r)?, r.get::<_, Option<String>>("parent")?))
|
||||
})
|
||||
.optional()?;
|
||||
let Some((mut detail, parent)) = record else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
if let Some(parent) = parent {
|
||||
if let Some((_, event)) = event_header(&tx, "id", &parent)? {
|
||||
events.push(event);
|
||||
}
|
||||
}
|
||||
detail["events"] = Value::Array(events);
|
||||
tx.commit()?;
|
||||
Ok(Some(detail))
|
||||
}
|
||||
|
||||
pub fn gamma_event(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let found = match key {
|
||||
DirectoryKey::Id(id) => event_header(&tx, "event_id", &id)?,
|
||||
DirectoryKey::Slug(slug) => event_header(&tx, "slug", &slug)?,
|
||||
};
|
||||
let Some((parent, mut detail)) = found else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut stmt = tx.prepare_cached(concat!(include_str!("gamma_market.sql"),
|
||||
" AND w.market IN (SELECT market FROM sports_markets WHERE event=?1 UNION ALL SELECT market FROM topic_markets WHERE event=?1)
|
||||
ORDER BY COALESCE(t.group_order,0),w.market"))?;
|
||||
let markets = stmt
|
||||
.query_map([parent], market)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
drop(stmt);
|
||||
detail["markets"] = Value::Array(markets);
|
||||
tx.commit()?;
|
||||
Ok(Some(detail))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
SELECT w.market, w.id, w.slug, w.question, w.yes_label, w.no_label, m.rules, m.phase, m.winner, quotes.yes_bid, quotes.yes_ask,
|
||||
yes_trade.price AS yes_last, no_trade.price AS no_last,
|
||||
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
|
||||
FROM market_wire_metadata w
|
||||
JOIN markets m ON m.id=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
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
|
||||
LEFT JOIN neg_risk_members member ON member.market=w.market
|
||||
LEFT JOIN market_fee_rates fee ON fee.market=w.market
|
||||
LEFT JOIN quote_events quotes ON quotes.seq=(SELECT MAX(seq) FROM quote_events WHERE market=w.market)
|
||||
LEFT JOIN last_asset_trades yes_trade ON yes_trade.market=w.market AND yes_trade.outcome='YES'
|
||||
LEFT JOIN last_asset_trades no_trade ON no_trade.market=w.market AND no_trade.outcome='NO'
|
||||
WHERE COALESCE(a.role,'')<>'placeholder'
|
||||
@@ -8,6 +8,7 @@ mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod fees;
|
||||
mod gamma_directory;
|
||||
mod heartbeat;
|
||||
mod holders;
|
||||
mod twap;
|
||||
@@ -48,6 +49,7 @@ use std::{path::Path, time::Duration};
|
||||
|
||||
pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
|
||||
@@ -57,17 +57,7 @@ impl Quote {
|
||||
}
|
||||
|
||||
pub fn mark(&self, phase: &str) -> Option<(i64, &'static str)> {
|
||||
if phase == "continuous" {
|
||||
if let (Some(b), Some(a)) = (self.bid, self.ask) {
|
||||
if (0..=1000).contains(&(a - b)) {
|
||||
return Some(((a + b) * 50, "midpoint"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(phase, "continuous" | "closed") {
|
||||
return self.last.map(|p| (p * 100, "last_trade"));
|
||||
}
|
||||
None
|
||||
display_price(self.bid, self.ask, self.last, phase)
|
||||
}
|
||||
|
||||
fn spread_micros(&self) -> Option<i64> {
|
||||
@@ -85,6 +75,25 @@ impl Quote {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn display_price(
|
||||
bid: Option<i64>,
|
||||
ask: Option<i64>,
|
||||
last: Option<i64>,
|
||||
phase: &str,
|
||||
) -> Option<(i64, &'static str)> {
|
||||
if phase == "continuous" {
|
||||
if let (Some(b), Some(a)) = (bid, ask) {
|
||||
if (0..=1000).contains(&(a - b)) {
|
||||
return Some(((a + b) * 50, "midpoint"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(phase, "continuous" | "closed") {
|
||||
return last.map(|p| (p * 100, "last_trade"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
|
||||
Reference in New Issue
Block a user