Compare commits

...
7 changed files with 160 additions and 15 deletions

No files matched your search

+12
View File
@@ -86,10 +86,22 @@ sequenceDiagram
`cli DATABASE --market-http 127.0.0.1:9002` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。[HTTP 请求样例](../../docs/examples/clob-http.http)
```mermaid
sequenceDiagram
participant C as 客户端
participant H as market_http.rs
participant E as exchange::Exchange
C->>H: GET /v2/live-volume?event_id=20,10
H->>E: public_live_volume
E-->>H: 各条件累计吃单份额及总和
H-->>C: 200 与 data 对象
```
```mermaid
flowchart LR
main["main.rs"] --> http["market_http.rs"]
http --> api["exchange::Exchange::public_books"]
http --> volume["exchange::Exchange::public_live_volume"]
```
```mermaid
+56 -1
View File
@@ -329,7 +329,12 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
if req.method() == &Method::Get
&& matches!(
path,
"/v2/prices-history" | "/v2/trades" | "/v2/resolutions" | "/v2/value" | "/v2/oi"
"/v2/prices-history"
| "/v2/trades"
| "/v2/resolutions"
| "/v2/value"
| "/v2/oi"
| "/v2/live-volume"
)
{
let (status, body) = data_page(path, params, engine);
@@ -472,6 +477,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
| "/events"
| "/market-clarifications"
| "/v2/oi"
| "/v2/live-volume"
| "/v2/value"
| "/v2/trades"
| "/v2/resolutions"
@@ -514,6 +520,7 @@ fn read_page<Q: serde::de::DeserializeOwned>(
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
let page = match path {
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
"/v2/live-volume" => read_page(params, engine, Exchange::public_live_volume),
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
@@ -529,6 +536,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
503,
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
),
Err(HistoryError::Unavailable) if path == "/v2/live-volume" => (
503,
json!({"code":"unavailable","error":"live volume unavailable","retryable":true}),
),
Err(HistoryError::Unavailable) if path == "/v2/value" => (
503,
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
@@ -658,6 +669,43 @@ mod tests {
.unwrap()
.unwrap();
let event_path = format!("/events/{}", topic["id"].as_str().unwrap());
for command in include_str!("../../../docs/examples/football.jsonl")
.lines()
.chain(include_str!("../../../docs/examples/volume.jsonl").lines())
{
db.execute(serde_json::from_str(command).unwrap()).unwrap();
}
let cup = db
.gamma_event(exchange::DirectoryKey::Slug("cup-a-b"))
.unwrap()
.unwrap();
let cup_id = cup["id"].as_str().unwrap();
let topic_id = topic["id"].as_str().unwrap();
let volume_query = format!("/v2/live-volume?eventId={topic_id},bad,{cup_id},{cup_id}");
let cup_volume_query = format!("/v2/live-volume?event_id={cup_id}");
let too_many_events = format!(
"/v2/live-volume?event_id={}",
(1..=21)
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",")
);
let cup_conditions = json!([
{"condition_id":"full-2-1","taker_volume":3},
{"condition_id":"half-1-0","taker_volume":2},
{"condition_id":"first-home","taker_volume":0},
{"condition_id":"first-ten","taker_volume":0},
{"condition_id":"home-minus","taker_volume":0},
{"condition_id":"over-25","taker_volume":0}
]);
let mut joint_conditions = cup_conditions.as_array().unwrap().clone();
joint_conditions.splice(
5..5,
[
json!({"condition_id":"nvda-200","taker_volume":0}),
json!({"condition_id":"nvda-300","taker_volume":0}),
],
);
let first_child = &topic["markets"][0];
assert_eq!(first_child["conditionId"], "nvda-200");
assert_eq!(topic["markets"].as_array().unwrap().len(), 2);
@@ -694,6 +742,13 @@ mod tests {
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
("GET","/v2/oi",String::new(),503,None),
("POST","/v2/oi",String::new(),405,None),
("GET",volume_query.as_str(),String::new(),200,Some(json!({"data":{"conditions":joint_conditions,"taker_volume_total":5}}))),
("GET",cup_volume_query.as_str(),String::new(),200,Some(json!({"data":{"conditions":cup_conditions,"taker_volume_total":5}}))),
("GET","/v2/live-volume?id=9223372036854775807",String::new(),200,Some(json!({"data":{"conditions":[],"taker_volume_total":0}}))),
("GET","/v2/live-volume?event_id=bad,,oops",String::new(),400,None),
("GET","/v2/live-volume",String::new(),400,None),
("GET",too_many_events.as_str(),String::new(),400,None),
("POST","/v2/live-volume",String::new(),405,None),
("GET","/v2/value?user=0x0000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":{"proxy_wallet":"0x0000000000000000000000000000000000000001","value":0}}))),
("GET","/v2/value",String::new(),400,None),
("GET","/v2/value?user=unpriced-owner",String::new(),503,None),
+5 -2
View File
@@ -41,6 +41,7 @@ flowchart LR
api -->|事务内派发| market["src/market.rs"]
api -->|解析只读查询| queries["src/catalog.rs"]
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
api -->|公开多赛事吃单份额| volume
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
volumesql -->|成交、时间及吃单方| schema
queries -->|市价预估| estimate["src/estimate.rs"]
@@ -483,8 +484,8 @@ sequenceDiagram
participant C as 客户端
participant E as Exchange
participant D as SQLite
C->>E: catalog(event) 或 volume(event)
E->>D: 打开同一读快照,选择已展示的市场
C->>E: catalog、volume 或 GET /v2/live-volume
E->>D: 打开读快照,按赛事键或数字目录 ID 选择市场
E->>D: 普通成交按 bid 定位市场,互补成交按 market 定位
D-->>E: 每笔取一次份额,按吃单方实际结果价统计金额
E->>E: 汇总每盘的累计及最近 24 小时,再求赛事总量
@@ -492,6 +493,8 @@ sequenceDiagram
E-->>C: 保留目录顺序,事件和各市场附带 volume
else volume
E-->>C: 统计时刻、总量及按累计吃单份额降序的成员
else /v2/live-volume
E-->>C: 各条件累计吃单份额与跨赛事合计
end
```
+1
View File
@@ -59,6 +59,7 @@ pub use prices_history::legacy::ClobHistoryQuery;
pub use public_trades::http::TradeQuery;
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
pub use resolution::http::ResolutionQuery;
pub use volume::LiveVolumeQuery;
#[derive(Debug)]
pub enum MarketDataError {
+74 -8
View File
@@ -1,8 +1,57 @@
use crate::{Exchange, MarketDataError};
use anyhow::{ensure, Context, Result};
use rusqlite::{params, Transaction};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::{
cmp::Reverse,
collections::{BTreeMap, BTreeSet},
};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LiveVolumeQuery {
#[serde(alias = "eventId", alias = "id")]
event_id: Option<String>,
}
impl LiveVolumeQuery {
fn event_ids(&self) -> Result<BTreeSet<i64>, MarketDataError> {
let mut ids = BTreeSet::new();
for id in self.event_id.as_deref().unwrap_or_default().split(',') {
if let Ok(id) = id.trim().parse::<i64>() {
ids.insert(id);
if ids.len() > 20 {
return Err(MarketDataError::Invalid(
"expected at most 20 distinct event IDs".into(),
));
}
}
}
if ids.is_empty() {
return Err(MarketDataError::Invalid(
"event_id must contain an integer".into(),
));
}
Ok(ids)
}
}
impl Exchange {
pub fn public_live_volume(&self, query: LiveVolumeQuery) -> Result<Value, MarketDataError> {
let events = json!(query.event_ids()?).to_string();
let tx = self.db.unchecked_transaction()?;
let report = Report::read_selection(&tx, Some(&events), None, None)
.map_err(|_| MarketDataError::Unavailable)?;
let conditions: Vec<_> = report.ranked().into_iter().map(|(market, volume)| {
json!({"condition_id":market,"taker_volume":crate::lots::display(volume.all_time.taker_shares)})
}).collect();
tx.commit()?;
Ok(
json!({"data":{"conditions":conditions,"taker_volume_total":crate::lots::display(report.total.all_time.taker_shares)}}),
)
}
}
fn serialize_hundredths<S: serde::Serializer>(
value: &i64,
@@ -69,13 +118,23 @@ impl Report {
[],
|r| r.get(0),
)?;
let events = event.map(|event| json!([event]).to_string());
Self::read_selection(db, events.as_deref(), market, Some(as_of_ms))
}
fn read_selection(
db: &Transaction,
events: Option<&str>,
market: Option<&str>,
as_of_ms: Option<i64>,
) -> Result<Self> {
let mut report = Self {
as_of_ms,
as_of_ms: as_of_ms.unwrap_or_default(),
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])?;
let mut rows = stmt.query(params![events, 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)?;
@@ -89,7 +148,7 @@ impl Report {
v.all_time.add(&totals)?;
if recent == Some(true) {
v.last_24h.add(&totals)?;
} else if recent.is_none() {
} else if as_of_ms.is_some() && recent.is_none() {
v.unknown_time_shares = v
.unknown_time_shares
.checked_add(totals.matched_shares)
@@ -104,10 +163,17 @@ impl Report {
Ok(report)
}
pub fn response(&self) -> Value {
fn ranked(&self) -> Vec<(&String, &Volume)> {
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
conditions.sort_by(|(a_id, a), (b_id, b)| {
(Reverse(a.all_time.taker_shares), a_id).cmp(&(Reverse(b.all_time.taker_shares), b_id))
});
conditions
}
pub fn response(&self) -> Value {
let conditions: Vec<_> = self
.ranked()
.into_iter()
.map(|(market, volume)| json!({"market":market,"volume":volume}))
.collect();
+10 -4
View File
@@ -1,8 +1,14 @@
-- ?1 selects an event's visible conditions; ?2 selects a single market.
WITH selected(market) AS MATERIALIZED (
-- ?1 contains local event keys (strings) or public directory ids (integers).
-- ?2 selects a single market. A null ?3 requests cumulative share totals only.
WITH event_keys(event) AS (
SELECT value FROM json_each(?1) WHERE type='text'
UNION ALL
SELECT d.event FROM json_each(?1) j JOIN event_directory_ids d ON d.id=j.value
WHERE j.type='integer'
), 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')
WHERE s.event IN (SELECT event FROM event_keys) 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
@@ -18,7 +24,7 @@ WITH selected(market) AS MATERIALIZED (
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*e.taker_price) FILTER (WHERE ?3 IS NOT NULL AND 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
+2
View File
@@ -163,6 +163,8 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
每个统计包含 `all_time` 和 `last_24h`,后者为查询时刻往前 86,400,000 毫秒,两端均含。每笔已撮合的数量计入 `matched_shares` 一次;确认吃单的一侧另记 `taker_shares` 和成交价乘数量的 `taker_notional_cents`。互补成交按吃单方实际交易的 YES 或 NO 定价。本地开盘集合竞价没有吃单方,只计入撮合量;缺失角色的旧成交另标 `unknown_role_shares`,缺失时间的计入累计量并标 `unknown_time_shares`。成交金额、滚动窗口及竞价拆分均为本地字段。当前只支持整数份额、整分成交价,官方份额精度可到小数点后六位。
HTTP 客户端可先从 Gamma 事件详情取得数字 `id`,再发 `GET /v2/live-volume?event_id=<id>`。`eventId` 和 `id` 也是参数别名。支持逗号分隔的多场赛事,忽略无法解析的项,去重后最多 20 个整数。全部无效或缺少参数返回 400,合法但没有盘口时返回零和空数组。多个赛事共用一个数据库快照,返回 `data.conditions` 和 `data.taker_volume_total`,无需翻页。上面的足球样例分别返回 3、2 和四个 0;第二场赛事若没有成交,合计仍为 5。份额相同时,本地按市场 ID 排序。未命名的互斥预留位暂随本地目录隐藏;成交份额沿用模拟撮合账本的精度。公开生产端点请求连接超时,因此响应规则来自 OpenAPI,截图美元数额及生产同量排序仍待核验。[官方成交量接口](https://docs.polymarket.com/api-reference/markets/get-live-volume-for-an-event)
## 持仓估值与赎回
官方 Position 的 current_value 以当前持有份额乘以每份估值计算。账户 value 汇总单市场持仓,另含未终结组合的成本。官方展示价在双边价差不超过 10 美分时取中点,超过时采用最近成交价。Data API 对持仓的 live mark 只给出字段定义,行情页展示价与生产持仓估值是否对每个市场相同仍需实际响应对账。[Data API 的 Position 与 PortfolioValue](https://data-api.polymarket.com/v2/openapi.json) · [订单簿展示价](https://docs.polymarket.com/concepts/prices-orderbook.md)