Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c5728d9a32 |
@@ -336,6 +336,23 @@ sequenceDiagram
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询公开持仓榜
|
||||
|
||||
`GET /v2/holders?condition=cup&limit=10` 按每个结果资产返回净持仓排名。传入 include_pnl=true 改查毛持仓,并返回可计算的持仓成本和盈亏。该模式限单个市场、每侧最多 100 行。续页要重新传 condition 及需要的筛选条件,并使用 pagination.next_cursor。按 token_id 合并翻页结果。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/holders,指定 condition 和可选 include_pnl
|
||||
H->>E: 查各结果资产的排名
|
||||
opt 毛持仓模式
|
||||
E->>E: 重放本页账户的账本流水,补充成本和盈亏
|
||||
end
|
||||
E-->>C: data 按 token_id 分组,pagination 提供续页游标
|
||||
```
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -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/holders"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -474,6 +479,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
| "/v2/holders"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
@@ -516,15 +522,28 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/holders" => read_page(params, engine, Exchange::public_holders),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
};
|
||||
match page {
|
||||
Ok(data) => (200, data),
|
||||
Err(HistoryError::Invalid(message)) => (
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Invalid(message)) => {
|
||||
let mut error = json!({"code":"invalid_request","error":message,"retryable":false});
|
||||
if path == "/v2/holders" {
|
||||
let parameter = match message.as_str() {
|
||||
"required query param 'condition' not provided"
|
||||
| "include_pnl accepts exactly one 'condition' per call" => Some("condition"),
|
||||
"limit must be at most 100 with include_pnl" => Some("limit"),
|
||||
msg if msg.starts_with("invalid condition id:") => Some("condition"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(parameter) = parameter {
|
||||
error["parameter"] = json!(parameter);
|
||||
}
|
||||
}
|
||||
(400, error)
|
||||
}
|
||||
Err(HistoryError::Unavailable) if path == "/v2/oi" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
@@ -537,6 +556,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/holders" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"holders unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/trades" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"trade feed unavailable","retryable":true}),
|
||||
@@ -703,6 +726,11 @@ mod tests {
|
||||
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
|
||||
("GET","/v2/trades?offset=2",String::new(),400,None),
|
||||
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
|
||||
("GET","/v2/holders",String::new(),400,Some(json!({"code":"invalid_request","error":"required query param 'condition' not provided","parameter":"condition","retryable":false}))),
|
||||
("GET","/v2/holders?condition=s&limit=0",String::new(),200,Some(json!({"data":[],"pagination":{"limit":0,"offset":0,"has_more":false,"next_cursor":null}}))),
|
||||
("GET","/v2/holders?condition=s&includePnl=true&limit=101",String::new(),400,Some(json!({"code":"invalid_request","error":"limit must be at most 100 with include_pnl","parameter":"limit","retryable":false}))),
|
||||
("GET","/v2/holders?condition=s&offset=0",String::new(),400,None),
|
||||
("POST","/v2/holders","{}".into(),405,None),
|
||||
("GET","/v2/resolutions?condition=unknown",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/resolutions?condition=m&eventId=1",String::new(),400,None),
|
||||
("GET","/v2/resolutions?questionId=invalid",String::new(),400,None),
|
||||
|
||||
@@ -716,6 +716,17 @@ sequenceDiagram
|
||||
E-->>C: 返回该结果资产的旧步长、新步长、时间和游标
|
||||
```
|
||||
|
||||
公开榜单经 `holders/http.rs` 复用同一排名与估值。毛持仓模式中,`holders/economics.sql` 回读本页账户的成交与钱包操作,`holders/economics.rs` 计算成本和盈亏。账本顺序由 `holders/economics_schema.sql` 的触发器记录。同一毫秒发生的成交和持仓操作也能按写入顺序重放。旧数据缺少明确顺序或转换成本时,相关经济字段返回 null。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["holders/http.rs"] --> L["holders.rs / holders.sql"]
|
||||
H --> E["holders/economics.rs"]
|
||||
E --> Q["holders/economics.sql"]
|
||||
Q --> S["holders/economics_schema.sql"]
|
||||
I["lib.rs · Exchange::open"] --> S
|
||||
```
|
||||
|
||||
### 体育赛事开赛撤单
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
mod economics;
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::{assets, portfolio, validation::identifier};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
@@ -127,9 +130,22 @@ impl Request {
|
||||
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let mut page = self.page()?;
|
||||
let (data, more) = page.read(db)?;
|
||||
page.offset = page
|
||||
.offset
|
||||
.checked_add(i64::from(page.limit))
|
||||
.context("holders offset overflow")?;
|
||||
let cursor = more.then(|| serde_json::to_string(&page)).transpose()?;
|
||||
Ok(json!({"basis":page.basis,"data":data,"next_cursor":cursor}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
fn read(&self, db: &Connection) -> Result<(Vec<Value>, bool)> {
|
||||
let page = self;
|
||||
let minimum = minimum_units(&page.min_balance)?;
|
||||
if page.limit == 0 || minimum.is_none() {
|
||||
return Ok(json!({"basis":page.basis,"data":[],"next_cursor":null}));
|
||||
return Ok((Vec::new(), false));
|
||||
}
|
||||
let end = page
|
||||
.offset
|
||||
@@ -186,12 +202,6 @@ impl Request {
|
||||
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}))
|
||||
Ok((data, more))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
use crate::inventory::{decimal, UNIT};
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Side {
|
||||
units: i128,
|
||||
cost: i128,
|
||||
realized: i128,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
fn acquire(&mut self, units: i128, cost: i128) -> bool {
|
||||
if units < 0 || !(0..=units).contains(&cost) || self.units + units > i128::from(i64::MAX) {
|
||||
return false;
|
||||
}
|
||||
self.units += units;
|
||||
self.cost += cost;
|
||||
true
|
||||
}
|
||||
|
||||
fn dispose(&mut self, units: i128, proceeds: i128) -> bool {
|
||||
if units < 0 || units > self.units {
|
||||
return false;
|
||||
}
|
||||
if units > 0 {
|
||||
let removed = self.cost * units / self.units;
|
||||
self.cost -= removed;
|
||||
self.units -= units;
|
||||
self.realized += proceeds - removed;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Account {
|
||||
sides: [Side; 2],
|
||||
incomplete: bool,
|
||||
last_legacy: Option<(i64, i64)>,
|
||||
}
|
||||
|
||||
fn side_index(outcome: &str) -> Option<usize> {
|
||||
match outcome {
|
||||
"YES" => Some(0),
|
||||
"NO" => Some(1),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Account {
|
||||
fn apply(&mut self, row: &Row<'_>, payout: [i128; 2]) -> rusqlite::Result<bool> {
|
||||
let operation: String = row.get(4)?;
|
||||
let shares = row.get::<_, Option<i64>>(6)?.map(i128::from);
|
||||
let cash = i128::from(row.get::<_, i64>(7)?);
|
||||
let fee = i128::from(row.get::<_, i64>(8)?);
|
||||
let units = match shares {
|
||||
Some(shares) if shares >= 0 => shares,
|
||||
_ => return Ok(false),
|
||||
};
|
||||
Ok(match operation.as_str() {
|
||||
"buy" | "sell" => {
|
||||
let outcome: String = row.get(5)?;
|
||||
let Some(idx) = side_index(&outcome) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if operation == "buy" {
|
||||
self.sides[idx].acquire(units, cash)
|
||||
} else {
|
||||
self.sides[idx].dispose(units, cash - fee)
|
||||
}
|
||||
}
|
||||
"SPLIT" => {
|
||||
let first = -cash / 2;
|
||||
self.sides[0].acquire(units, first) && self.sides[1].acquire(units, -cash - first)
|
||||
}
|
||||
"MERGE" => {
|
||||
let first = cash / 2;
|
||||
self.sides[0].dispose(units, first) && self.sides[1].dispose(units, cash - first)
|
||||
}
|
||||
"REDEEM" => {
|
||||
let raw: Option<String> = row.get(9)?;
|
||||
let amounts: [i128; 2] = if let Some(raw) = raw {
|
||||
let Ok(values) = serde_json::from_str::<[i64; 2]>(&raw) else {
|
||||
return Ok(false);
|
||||
};
|
||||
values.map(i128::from)
|
||||
} else {
|
||||
[self.sides[0].units, self.sides[1].units]
|
||||
};
|
||||
let settled = [amounts[0] * payout[0] / 100, amounts[1] * payout[1] / 100];
|
||||
amounts.iter().sum::<i128>() == units
|
||||
&& settled.iter().sum::<i128>() == cash
|
||||
&& self.sides[0].dispose(amounts[0], settled[0])
|
||||
&& self.sides[1].dispose(amounts[1], settled[1])
|
||||
}
|
||||
// The conversion journal has group totals but no per-leg cost allocation.
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Economics(HashMap<String, Account>);
|
||||
|
||||
impl Economics {
|
||||
pub fn read(db: &Connection, market: &str, accounts: &[&str]) -> rusqlite::Result<Self> {
|
||||
let winner: Option<String> =
|
||||
db.query_row("SELECT winner FROM markets WHERE id=?", [market], |r| {
|
||||
r.get(0)
|
||||
})?;
|
||||
let payout = match winner.as_deref() {
|
||||
Some("YES") => [100, 0],
|
||||
Some("NO") => [0, 100],
|
||||
Some("VOID") => [50, 50],
|
||||
_ => [0, 0],
|
||||
};
|
||||
let mut out: HashMap<String, Account> = HashMap::new();
|
||||
let mut stmt = db.prepare_cached(include_str!("economics.sql"))?;
|
||||
let mut rows = stmt.query(params![market, json!(accounts).to_string()])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let account = out.entry(row.get(0)?).or_default();
|
||||
if account.incomplete {
|
||||
continue;
|
||||
}
|
||||
if row.get::<_, Option<i64>>(3)?.is_none() {
|
||||
let source: i64 = row.get(1)?;
|
||||
let Some(at) = row.get::<_, Option<i64>>(2)? else {
|
||||
account.incomplete = true;
|
||||
continue;
|
||||
};
|
||||
if account
|
||||
.last_legacy
|
||||
.is_some_and(|(time, old_source)| time == at && source != old_source)
|
||||
{
|
||||
account.incomplete = true;
|
||||
continue;
|
||||
}
|
||||
account.last_legacy = Some((at, source));
|
||||
}
|
||||
account.incomplete = !account.apply(row, payout)?;
|
||||
}
|
||||
Ok(Self(out))
|
||||
}
|
||||
|
||||
pub fn fields(
|
||||
&self,
|
||||
account: &str,
|
||||
outcome: &str,
|
||||
units: i64,
|
||||
value: Option<i128>,
|
||||
) -> [(&'static str, Value); 5] {
|
||||
let known = self
|
||||
.0
|
||||
.get(account)
|
||||
.filter(|a| !a.incomplete)
|
||||
.and_then(|a| side_index(outcome).map(|idx| &a.sides[idx]))
|
||||
.filter(|side| side.units == i128::from(units) && side.units > 0);
|
||||
let avg = known.map(|s| decimal(s.cost * i128::from(UNIT) / s.units, UNIT));
|
||||
let cost = known.map(|s| decimal(s.cost, UNIT));
|
||||
let realized = known.map(|s| decimal(s.realized, UNIT));
|
||||
let unrealized = known.zip(value).map(|(s, v)| decimal(v - s.cost, UNIT));
|
||||
let total = known
|
||||
.zip(value)
|
||||
.map(|(s, v)| decimal(s.realized + v - s.cost, UNIT));
|
||||
[
|
||||
("avg_price", json!(avg)),
|
||||
("entry_cost_usdc", json!(cost)),
|
||||
("realized_pnl", json!(realized)),
|
||||
("unrealized_pnl", json!(unrealized)),
|
||||
("total_pnl", json!(total)),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
WITH requested(account) AS MATERIALIZED (
|
||||
SELECT DISTINCT value FROM json_each(?2)
|
||||
), legs AS (
|
||||
SELECT t.account,1 AS source,t.execution AS record,t.order_seq AS leg,t.at_ms,
|
||||
t.side AS operation,t.outcome,
|
||||
t.quantity*10000 AS shares,t.quantity*t.price AS cash,
|
||||
COALESCE(f.fee_micros,0) AS fee,NULL AS redemption_amounts
|
||||
FROM wallet_trade_legs t JOIN requested a USING(account)
|
||||
LEFT JOIN execution_fees f ON f.execution=t.execution AND f.taker_order=t.order_seq
|
||||
WHERE t.market=?1
|
||||
UNION ALL
|
||||
SELECT w.account,0,w.id,0,w.at_ms,w.kind,NULL,
|
||||
COALESCE(p.shares_micros,w.shares*1000000),
|
||||
COALESCE(p.cash_micros,w.cash_delta*10000),0,
|
||||
CASE WHEN w.kind='REDEEM' THEN json_extract(r.response,'$.amounts_micros') END
|
||||
FROM wallet_movements w JOIN requested a USING(account)
|
||||
LEFT JOIN precise_movements p ON p.request_id=w.request_id AND p.account=w.account
|
||||
LEFT JOIN requests r ON r.id=w.request_id
|
||||
WHERE (w.market=?1 AND w.kind IN ('SPLIT','MERGE','REDEEM'))
|
||||
OR (w.kind='CONVERSION' AND EXISTS (
|
||||
SELECT 1 FROM neg_risk_members n WHERE n.market=?1 AND n.group_id=w.group_id
|
||||
))
|
||||
)
|
||||
SELECT l.account,l.source,l.at_ms,o.seq,l.operation,l.outcome,
|
||||
l.shares,l.cash,l.fee,l.redemption_amounts
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
ORDER BY l.account,o.seq IS NOT NULL,
|
||||
CASE WHEN o.seq IS NULL THEN l.at_ms END,o.seq,l.source,l.record,l.leg
|
||||
@@ -0,0 +1,21 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Trade executions and wallet movements have independent ID sequences.
|
||||
-- Record their shared write order so a sale and a split in the same
|
||||
-- millisecond can be replayed in the order in which they committed.
|
||||
CREATE TABLE IF NOT EXISTS position_economics_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
source INTEGER NOT NULL,
|
||||
record INTEGER NOT NULL,
|
||||
UNIQUE(source,record)
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_fill AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_wallet AFTER INSERT ON wallet_movements
|
||||
WHEN NEW.kind IN ('SPLIT','MERGE','REDEEM','CONVERSION') BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(0,NEW.id);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,229 @@
|
||||
use super::{economics::Economics, minimum_units, Basis, Page};
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{Connection, OptionalExtension};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Number, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct HoldersQuery {
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
#[serde(alias = "minBalance")]
|
||||
min_balance: Option<String>,
|
||||
#[serde(alias = "includePnl")]
|
||||
include_pnl: Option<bool>,
|
||||
offset: Option<String>,
|
||||
#[serde(alias = "market_id", alias = "marketId")]
|
||||
market: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Window {
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
fn cursor_mac(db: &Connection) -> Result<Hmac<Sha256>> {
|
||||
let secret: Vec<u8> = db.query_row(
|
||||
"SELECT secret FROM trade_cursor_key WHERE singleton=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut mac = Hmac::<Sha256>::new_from_slice(&secret).expect("HMAC accepts any key length");
|
||||
mac.update(b"eventbook:/v2/holders:v1\0");
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
impl Window {
|
||||
fn decode(db: &Connection, token: &str) -> Result<Self> {
|
||||
ensure!(token.len() <= 256, "invalid cursor");
|
||||
let bytes = BASE64URL_NOPAD
|
||||
.decode(token.as_bytes())
|
||||
.context("invalid cursor")?;
|
||||
let split = bytes.len().checked_sub(32).context("invalid cursor")?;
|
||||
let (payload, signature) = bytes.split_at(split);
|
||||
let mut mac = cursor_mac(db)?;
|
||||
mac.update(payload);
|
||||
mac.verify_slice(signature)
|
||||
.map_err(|_| anyhow::anyhow!("invalid cursor"))?;
|
||||
Ok(serde_json::from_slice(payload).context("invalid cursor")?)
|
||||
}
|
||||
|
||||
fn encode(&self, db: &Connection) -> Result<String> {
|
||||
let mut bytes = serde_json::to_vec(self)?;
|
||||
let mut mac = cursor_mac(db)?;
|
||||
mac.update(&bytes);
|
||||
bytes.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&bytes))
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_group(group: &Value, economics: Option<&Economics>) -> Result<Value> {
|
||||
let outcome = group["outcome"]
|
||||
.as_str()
|
||||
.context("missing holder outcome")?;
|
||||
let token = group["asset_id"].as_str().context("missing holder token")?;
|
||||
let index = if outcome == "YES" { 0 } else { 1 };
|
||||
let holders = group["holders"].as_array().context("missing holder rows")?;
|
||||
let holders = holders
|
||||
.iter()
|
||||
.map(|holder| -> Result<Value> {
|
||||
let account = holder["account"]
|
||||
.as_str()
|
||||
.context("missing holder wallet")?;
|
||||
let amount = holder["amount"]
|
||||
.as_number()
|
||||
.context("missing holder amount")?;
|
||||
let mut row = json!({
|
||||
"proxy_wallet":account,"amount":amount,"token_id":token,"outcome_index":index,
|
||||
"bio":"","name":"","pseudonym":"","profile_image":"","profile_image_optimized":"",
|
||||
"display_username_public":false,"verified":false
|
||||
});
|
||||
if let Some(economics) = economics {
|
||||
let mark = holder["current_price_micros"].as_i64().map(i128::from);
|
||||
let value = holder["current_value_micros"].as_i64().map(i128::from);
|
||||
let units = minimum_units(amount)?.context("holder amount overflow")?;
|
||||
row["current_price"] = json!(mark.map(|p| decimal(p, UNIT)));
|
||||
row["current_value"] = json!(value.map(|p| decimal(p, UNIT)));
|
||||
for (key, value) in economics.fields(account, outcome, units, value) {
|
||||
row[key] = value;
|
||||
}
|
||||
}
|
||||
Ok(row)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"token_id":token,"holders":holders}))
|
||||
}
|
||||
|
||||
impl HoldersQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(self.offset.is_none(), "'offset' is not a query param on this API: pages are cursor-only, pass 'cursor' from a prior response's next_cursor");
|
||||
ensure!(self.market.is_none(), "'market' is not a query param on this API: filter by condition id with 'condition' (aliases 'condition_id', 'conditionId')");
|
||||
let conditions = self
|
||||
.condition
|
||||
.as_deref()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.context("required query param 'condition' not provided")?;
|
||||
let ids = condition_filter(Some(conditions), db)
|
||||
.map_err(|error| match error {
|
||||
MarketDataError::Invalid(message) => anyhow::anyhow!(
|
||||
"{}",
|
||||
message.replacen("invalid condition:", "invalid condition id:", 1)
|
||||
),
|
||||
MarketDataError::Unavailable => anyhow::Error::new(rusqlite::Error::InvalidQuery),
|
||||
})?
|
||||
.context("required query param 'condition' not provided")?;
|
||||
let mut markets: Vec<String> = serde_json::from_str(&ids)?;
|
||||
let gross = self.include_pnl.unwrap_or(false);
|
||||
ensure!(
|
||||
!gross || markets.len() == 1,
|
||||
"include_pnl accepts exactly one 'condition' per call"
|
||||
);
|
||||
for market in &mut markets {
|
||||
if hex_id(market, 64) {
|
||||
let canonical = db
|
||||
.query_row(
|
||||
"SELECT id FROM markets WHERE id=? COLLATE NOCASE ORDER BY id LIMIT 1",
|
||||
[&*market],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(id) = canonical {
|
||||
*market = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
let raw_limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
raw_limit <= 1000,
|
||||
"Failed to deserialize query string: limit: limit must be between 0 and 1000"
|
||||
);
|
||||
let window = self
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| Window::decode(db, cursor))
|
||||
.transpose()?
|
||||
.unwrap_or(Window {
|
||||
limit: raw_limit,
|
||||
offset: 0,
|
||||
});
|
||||
ensure!(
|
||||
!gross || window.limit <= 100,
|
||||
"limit must be at most 100 with include_pnl"
|
||||
);
|
||||
let min_balance = self
|
||||
.min_balance
|
||||
.as_deref()
|
||||
.filter(|raw| !raw.trim().is_empty())
|
||||
.map(|raw| raw.trim().parse::<Number>().context("invalid min_balance"))
|
||||
.transpose()?
|
||||
.filter(|number| !number.to_string().starts_with('-'))
|
||||
.unwrap_or_else(|| 0.into());
|
||||
let page = Page {
|
||||
markets,
|
||||
basis: if gross { Basis::Gross } else { Basis::Net },
|
||||
min_balance,
|
||||
limit: window.limit,
|
||||
offset: window.offset,
|
||||
};
|
||||
let (groups, more) = page.read(db)?;
|
||||
let economics = if gross && !groups.is_empty() {
|
||||
let accounts: Vec<_> = groups
|
||||
.iter()
|
||||
.filter_map(|g| g["holders"].as_array())
|
||||
.flatten()
|
||||
.filter_map(|h| h["account"].as_str())
|
||||
.collect();
|
||||
Some(Economics::read(db, &page.markets[0], &accounts)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data = groups
|
||||
.iter()
|
||||
.map(|group| wire_group(group, economics.as_ref()))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let next = if more {
|
||||
let offset = window
|
||||
.offset
|
||||
.checked_add(i64::from(window.limit))
|
||||
.context("holders offset overflow")?;
|
||||
Some(
|
||||
Window {
|
||||
limit: window.limit,
|
||||
offset,
|
||||
}
|
||||
.encode(db)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"data":data,"pagination":{
|
||||
"limit":window.limit,"offset":window.offset,"has_more":more,"next_cursor":next
|
||||
}}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_holders(&self, query: HoldersQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let result = query.read(&tx).map_err(|error| {
|
||||
if error.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
MarketDataError::Unavailable
|
||||
} else {
|
||||
MarketDataError::Invalid(error.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -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 holders::http::HoldersQuery;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
@@ -135,6 +136,13 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let economics_order_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='cost_order_wallet')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !economics_order_ready {
|
||||
db.execute_batch(include_str!("holders/economics_schema.sql"))?;
|
||||
}
|
||||
let snapshot_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
||||
if !snapshot_ready {
|
||||
|
||||
@@ -1879,6 +1879,52 @@ fn holders_net_reserved_and_hedged_balances_and_page_each_token() {
|
||||
assert!(e
|
||||
.execute(json!({"op":"holders","cursor":first["next_cursor"],"market":"different"}))
|
||||
.is_err());
|
||||
let request = |value| serde_json::from_value::<exchange::HoldersQuery>(value).unwrap();
|
||||
let first_public = e
|
||||
.public_holders(request(json!({"condition":"cup","limit":1})))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first_public["data"][0]["holders"][0]["proxy_wallet"],
|
||||
"alice"
|
||||
);
|
||||
assert_eq!(first_public["data"][0]["holders"][0]["amount"], 3);
|
||||
assert!(first_public["data"][0]["holders"][0]
|
||||
.get("entry_cost_usdc")
|
||||
.is_none());
|
||||
let cursor = first_public["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let next_public = e
|
||||
.public_holders(request(
|
||||
json!({"condition":"cup","cursor":cursor,"limit":9}),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(next_public["pagination"]["limit"], 1);
|
||||
assert_eq!(next_public["pagination"]["offset"], 1);
|
||||
assert_eq!(next_public["data"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
next_public["data"][0]["holders"][0]["proxy_wallet"],
|
||||
"carol"
|
||||
);
|
||||
assert_eq!(next_public["data"][0]["holders"][0]["amount"], 0);
|
||||
|
||||
let pnl = e
|
||||
.public_holders(request(json!({"condition":"cup","includePnl":true})))
|
||||
.unwrap();
|
||||
let alice_yes = &pnl["data"][0]["holders"][0];
|
||||
let alice_no = &pnl["data"][1]["holders"][0];
|
||||
let bob_no = &pnl["data"][1]["holders"][1];
|
||||
assert_eq!(alice_yes["amount"], 10);
|
||||
assert_eq!(alice_yes["entry_cost_usdc"], 5);
|
||||
assert_eq!(alice_no["amount"], 7);
|
||||
assert_eq!(alice_no["entry_cost_usdc"], json!(3.5));
|
||||
assert_eq!(alice_no["realized_pnl"], json!(-0.3));
|
||||
assert_eq!(bob_no["proxy_wallet"], "bob");
|
||||
assert_eq!(bob_no["entry_cost_usdc"], json!(3.2));
|
||||
assert!(
|
||||
(bob_no["unrealized_pnl"].as_f64().unwrap() + bob_no["realized_pnl"].as_f64().unwrap()
|
||||
- bob_no["total_pnl"].as_f64().unwrap())
|
||||
.abs()
|
||||
< 1e-9
|
||||
);
|
||||
assert_eq!(gross["data"][0]["holders"][0]["amount"], 10);
|
||||
assert_eq!(gross["data"][1]["holders"][0]["amount"], 7);
|
||||
assert_eq!(
|
||||
|
||||
@@ -306,6 +306,10 @@ order、market_sell 和卖出 estimate 可用 size_micros 输入数量,也可
|
||||
|
||||
本地覆盖盘口快照、档位变化、最优报价和文本心跳。最近成交、步长调整和启用扩展功能后的市场生命周期事件也可经同一连接订阅。初始快照使用数组发送;生产端帧分组、延迟和断线时机尚待实测。Rust 回环测试入口为 `market_socket_sends_snapshots_deltas_and_application_pongs`。
|
||||
|
||||
#### V2 公开持仓榜
|
||||
|
||||
2026-12-05 的生产对照中,limit=1 分别返回两个结果各一位,负数 min_balance 与零门槛一致。恰好一位达标时下一页为空指针。续页必须重送 condition,页宽和偏移由游标保留,min_balance 与 include_pnl 可在请求中重传。Eventbook 的 `/v2/holders` 对齐这些边界,并复用实际份额、冻结卖单和盘口估值。新账本保存成交与钱包操作的共同写入顺序。已知历史按移动平均成本重放,买入成本排除手续费,卖出用实收额计算已实现盈亏,拆分和合并按等额分摊。旧流水缺时钟、同毫秒顺序有歧义、转换缺少分腿成本或账本与持仓不符时,成本及盈亏留空。公开钱包资料和生产成本算法仍待逐户对照。一次生产样本中同一资产的榜单 avg_price 为 0.2578,持仓接口为 0.2536,两者的 entry_cost_usdc 相同。本地使用账本成本除以持有份额。[官方持仓榜接口](https://docs.polymarket.com/api-reference/markets/list-a-markets-top-holders)
|
||||
|
||||
### 最近成交和步长变化
|
||||
|
||||
[回放样例](examples/market-stream-trades.jsonl)先将空盘步长由 0.01 调到 0.001,再以 0.40 美元成交 2 份 YES,最后通过互补买单以 0.35 美元成交 1 份 YES。订阅 YES 的客户端收到新的步长、两笔最近成交和相应的档位变化;订阅 NO 的客户端也收到该结果的步长变化,以及互补成交对应的 0.65 美元成交价。[官方原始报文字段](https://docs.polymarket.com/market-data/realtime-data.md)
|
||||
|
||||
Reference in New Issue
Block a user