市场成交与持仓数据及含吃单手续费的本地交割 #7
@@ -20,6 +20,9 @@ flowchart LR
|
||||
api -->|解析写命令| cmd["src/command.rs"]
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
estimate -->|同步并读取常驻盘口| cache
|
||||
estimate -->|成交金额| book
|
||||
@@ -412,3 +415,22 @@ sequenceDiagram
|
||||
C->>E: quote_history 从 quote_seq 之后续读
|
||||
E-->>C: 顺序返回报价、价差、中点、时间和游标
|
||||
```
|
||||
|
||||
## 赛事目录与成交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: catalog(event) 或 volume(event)
|
||||
E->>D: 打开同一读快照,选择已展示的市场
|
||||
E->>D: 普通成交按 bid 定位市场,互补成交按 market 定位
|
||||
D-->>E: 每笔取一次份额,按吃单方实际结果价统计金额
|
||||
E->>E: 汇总每盘的累计及最近 24 小时,再求赛事总量
|
||||
alt catalog
|
||||
E-->>C: 保留目录顺序,事件和各市场附带 volume
|
||||
else volume
|
||||
E-->>C: 统计时刻、总量及按累计吃单份额降序的成员
|
||||
end
|
||||
```
|
||||
|
||||
@@ -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
|
||||
@@ -1642,3 +1642,35 @@ fn quote_cursor_replays_only_committed_changes_to_best_prices() {
|
||||
assert_eq!(empty["points"], json!([]));
|
||||
assert_eq!(empty["cursor"], two["cursor"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_and_ranked_volume_count_executions_once_across_conditions() {
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
let mut result = Value::Null;
|
||||
for line in include_str!("../../../docs/examples/football.jsonl")
|
||||
.lines()
|
||||
.chain(include_str!("../../../docs/examples/volume.jsonl").lines())
|
||||
{
|
||||
result = e.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
result["volume"]["all_time"],
|
||||
json!({"matched_shares":5,"taker_shares":5,"taker_notional_cents":180,"unknown_role_shares":0})
|
||||
);
|
||||
assert_eq!(result["volume"]["all_time"], result["volume"]["last_24h"]);
|
||||
assert_eq!(result["conditions"][0]["market"], "full-2-1");
|
||||
assert_eq!(result["conditions"][1]["market"], "half-1-0");
|
||||
let catalog = e
|
||||
.execute(json!({"op":"catalog","event":"cup-a-b"}))
|
||||
.unwrap();
|
||||
assert_eq!(catalog["event"]["volume"], result["volume"]);
|
||||
for condition in result["conditions"].as_array().unwrap() {
|
||||
let listing = catalog["markets"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|m| m["market"] == condition["market"])
|
||||
.unwrap();
|
||||
assert_eq!(listing["volume"], condition["volume"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{"op":"fund","id":"vol-a","account":"alice","cents":1000}
|
||||
{"op":"fund","id":"vol-b","account":"bob","cents":1000}
|
||||
{"op":"open","id":"vol-open-full","market":"full-2-1"}
|
||||
{"op":"order","id":"vol-yes","account":"alice","market":"full-2-1","outcome":"YES","side":"buy","price":60,"qty":3}
|
||||
{"op":"order","id":"vol-no","account":"bob","market":"full-2-1","outcome":"NO","side":"buy","price":40,"qty":3}
|
||||
{"op":"order","id":"vol-no","account":"bob","market":"full-2-1","outcome":"NO","side":"buy","price":40,"qty":3}
|
||||
{"op":"split","id":"vol-split","account":"alice","market":"half-1-0","qty":2}
|
||||
{"op":"open","id":"vol-open-half","market":"half-1-0"}
|
||||
{"op":"order","id":"vol-ask","account":"alice","market":"half-1-0","outcome":"YES","side":"sell","price":30,"qty":2}
|
||||
{"op":"order","id":"vol-buy","account":"bob","market":"half-1-0","outcome":"YES","side":"buy","price":30,"qty":2}
|
||||
{"op":"volume","event":"cup-a-b"}
|
||||
@@ -154,3 +154,11 @@ FOK 要求整笔金额成交,无法用完预算时交易回滚。超过最高
|
||||
前端先查询 `{"op":"quote","asset_id":"eb:YES:e"}`,取得 `quote_seq`,随后用 `{"op":"quote_history","asset_id":"eb:YES:e","after":0,"limit":100}` 将 after 换为快照序号或上次返回的 `cursor`。从零开始可以读完整记录。返回空页时保留当前游标;同毫秒事件按序号排序。价格单位为每美元一百万微单位。这里的中点是双边报价的算术平均,连续交易的展示价仍执行价差超过 10 分时使用最近成交价的规则。本地盘前允许交叉挂单,其价差可以为负。
|
||||
|
||||
这条曲线记录本地事务完成后的盘口。已有挂单的旧库升级时从当前盘口生成首个观测,不补写升级前的挂撤单时间。逐笔及分桶成交继续通过 history 和 prices_history 查询。当前入口为按游标读取,官方 WebSocket 协议、推送延迟与生产数据逐条对照仍待验证。
|
||||
|
||||
## 赛事及盘口成交量
|
||||
|
||||
官方 Data API 的 `/v2/live-volume` 返回各条件累计的单边吃单份额,按份额降序排列;赛事总量等于各条件之和。截图赛事标题和盘口行的美元金额还需要同时间的前端与后台响应才能确定口径。[官方字段定义 ConditionVolume 和 Envelope_LiveVolume](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
先重放[足球目录](examples/football.jsonl),再重放[成交量样例](examples/volume.jsonl)。全场比分盘由吃单方买入 NO 三份,每份 40 分;半场比分盘由吃单方买入 YES 两份,每份 30 分。事件累计为 5 份、180 分(模拟美元 1.80),其余四盘为零。挂单、普通拆分以及重复请求不增加成交量。目录保留显示顺序,`volume` 独立查询则按累计吃单份额降序,同量时按市场 ID 升序。单盘也可传 `{"op":"volume","market":"full-2-1"}`。
|
||||
|
||||
每个统计包含 `all_time` 和 `last_24h`,后者为查询时刻往前 86,400,000 毫秒,两端均含。每笔已撮合的数量计入 `matched_shares` 一次;确认吃单的一侧另记 `taker_shares` 和成交价乘数量的 `taker_notional_cents`。互补成交按吃单方实际交易的 YES 或 NO 定价。本地开盘集合竞价没有吃单方,只计入撮合量;缺失角色的旧成交另标 `unknown_role_shares`,缺失时间的计入累计量并标 `unknown_time_shares`。成交金额、滚动窗口及竞价拆分均为本地字段。当前只支持整数份额、整分成交价,官方份额精度可到小数点后六位。
|
||||
|
||||
Reference in New Issue
Block a user