Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 33b3991c69 |
@@ -425,3 +425,18 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
### 钱包成交量
|
||||
|
||||
`GET /v2/user-volume?user=alice&start=1785542400&end=1785628800` 返回 `data.volume`(份数)、`data.volume_usdc` 和 `data.trade_count`。省略边界或填 0 表示该侧不限。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/user-volume
|
||||
H->>E: 钱包、起止时间
|
||||
E-->>H: UTC 整日成交汇总
|
||||
H-->>C: data 对象
|
||||
```
|
||||
|
||||
@@ -335,6 +335,13 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
if path == "/v2/user-volume" {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let route = path.strip_prefix('/').unwrap_or(path);
|
||||
let (name, segment) = route
|
||||
.split_once('/')
|
||||
@@ -515,6 +522,7 @@ 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/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/user-volume" => read_page(params, engine, Exchange::public_user_volume),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
@@ -533,6 +541,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/user-volume" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"user volume unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
@@ -703,6 +715,10 @@ mod tests {
|
||||
("GET","/v2/value?user=a&condition=",String::new(),400,None),
|
||||
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("POST","/v2/value",String::new(),405,None),
|
||||
("GET","/v2/user-volume?user=unknown",String::new(),200,Some(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}))),
|
||||
("GET","/v2/user-volume?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("GET","/v2/user-volume",String::new(),400,None),
|
||||
("POST","/v2/user-volume",String::new(),405,None),
|
||||
("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),
|
||||
|
||||
@@ -2,6 +2,19 @@
|
||||
|
||||
维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。
|
||||
|
||||
## 钱包成交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP
|
||||
participant E as portfolio/user_volume.rs
|
||||
participant D as SQLite
|
||||
H->>E: 钱包与 Unix 秒起止参数
|
||||
E->>E: 校验钱包,把有效边界转换为 UTC 日
|
||||
E->>D: 读取该钱包的买卖成交,汇总窗口内份数、成交额和笔数
|
||||
E-->>H: 单个数据对象
|
||||
```
|
||||
|
||||
## 文件依赖
|
||||
|
||||
箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。
|
||||
@@ -41,6 +54,9 @@ flowchart LR
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
api -->|查询钱包成交量| user_volume["src/portfolio/user_volume.rs"]
|
||||
user_volume -->|按 UTC 日期汇总钱包成交| user_volume_sql["src/portfolio/user_volume.sql"]
|
||||
user_volume_sql -->|读取按账户拆开的成交| wallet_legs["src/price_migration.sql"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
|
||||
@@ -54,6 +54,7 @@ pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use portfolio::UserVolumeQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
|
||||
@@ -10,6 +10,9 @@ use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
mod user_volume;
|
||||
pub use user_volume::UserVolumeQuery;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
use super::protocol::CONTRACTS;
|
||||
use crate::{
|
||||
inventory::decimal,
|
||||
lots::PER_SHARE,
|
||||
tick_size::PAR,
|
||||
validation::{hex_id, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::params;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UserVolumeQuery {
|
||||
user: String,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_user_volume(&self, query: UserVolumeQuery) -> Result<Value, MarketDataError> {
|
||||
let user = &query.user;
|
||||
identifier(user).map_err(|_| MarketDataError::Invalid("invalid user".into()))?;
|
||||
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"protocol contract is not a user".into(),
|
||||
));
|
||||
}
|
||||
let start = query.start.filter(|&at| at != 0);
|
||||
let end = query.end.filter(|&at| at != 0);
|
||||
if matches!(start.zip(end), Some((start, end)) if start > end) {
|
||||
return Ok(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}));
|
||||
}
|
||||
let day = |at: i64| at.div_euclid(86_400);
|
||||
let (shares, notional, count): (i64, i64, i64) = self
|
||||
.db
|
||||
.prepare_cached(include_str!("user_volume.sql"))?
|
||||
.query_row(
|
||||
params![user, hex_id(user, 40), start.map(day), end.map(day)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(json!({"data":{
|
||||
"volume":decimal(shares.into(), PER_SHARE),
|
||||
"volume_usdc":decimal(notional.into(), PER_SHARE * PAR),
|
||||
"trade_count":count
|
||||
}}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
WITH owners AS (
|
||||
SELECT ?1 AS id WHERE NOT ?2
|
||||
UNION ALL
|
||||
SELECT id FROM accounts WHERE ?2 AND id=?1 COLLATE NOCASE
|
||||
), legs AS (
|
||||
SELECT execution, quantity, price,
|
||||
at_ms/86400000 - (at_ms%86400000<0) AS utc_day
|
||||
FROM wallet_trade_legs
|
||||
WHERE account IN (SELECT id FROM owners)
|
||||
)
|
||||
SELECT COALESCE(SUM(quantity),0), COALESCE(SUM(quantity*price),0), COUNT(DISTINCT execution)
|
||||
FROM legs
|
||||
WHERE (?3 IS NULL OR utc_day>=?3) AND (?4 IS NULL OR utc_day<=?4)
|
||||
@@ -0,0 +1,67 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn volume(db: &Exchange, query: Value) -> Value {
|
||||
db.public_user_volume(serde_json::from_value(query).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_volume_counts_both_roles_and_rounds_bounds_to_utc_days() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("wallet-volume.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/valuation.jsonl")
|
||||
.lines()
|
||||
.take(7)
|
||||
{
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list-pair","market":"pair","rules":"赛果"}),
|
||||
json!({"op":"open","id":"open-pair","market":"pair"}),
|
||||
json!({"op":"order","id":"buy-no","market":"pair","account":"alice","outcome":"NO","side":"buy","price":40,"qty":3}),
|
||||
json!({"op":"order","id":"buy-yes","market":"pair","account":"bob","outcome":"YES","side":"buy","price":60,"qty":3}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
// Put the executions on opposite sides of UTC midnight.
|
||||
let sqlite = rusqlite::Connection::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE trade_prices SET at_ms=86399999", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE paired_fills SET at_ms=86400000", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
drop(sqlite);
|
||||
|
||||
let zero = json!({"volume":0,"volume_usdc":0,"trade_count":0});
|
||||
assert_eq!(volume(&db, json!({"user":"unknown"})), zero);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86400})),
|
||||
zero
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":1,"end":1})),
|
||||
json!({"volume":2,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86500})),
|
||||
json!({"volume":3,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":0,"end":0})),
|
||||
json!({"volume":5,"volume_usdc":2.4,"trade_count":2})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"bob"})),
|
||||
json!({"volume":5,"volume_usdc":3,"trade_count":2})
|
||||
);
|
||||
}
|
||||
@@ -223,6 +223,12 @@ JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价
|
||||
|
||||
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
||||
|
||||
### 钱包成交量 Data API
|
||||
|
||||
官方 `GET /v2/user-volume` 按 UTC 整日统计钱包的买卖成交,返回份数、USDC 金额和成交笔数。起止参数以 Unix 秒表示,省略或填 0 关闭该侧边界。倒置窗口及无成交钱包返回零。[官方接口](https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume)
|
||||
|
||||
在空数据库重放 [估值样例](examples/valuation.jsonl) 的前七条命令。Alice 和 Bob 分别查询 `/v2/user-volume`,均应得到 2 份、1.2 USDC 和 1 笔。互补成交使用各自的结果资产价格。金额为成交价乘份数,费用与抵押拆并不计。盘口关闭后历史成交仍可查询。本地按成交编号去重计笔数,无可信时间的旧成交只进入不限日期的汇总。独立的组合 RFQ 账本及生产端点的持续对账仍待接入。
|
||||
|
||||
## 精确抵押币现金余额
|
||||
|
||||
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。
|
||||
|
||||
Reference in New Issue
Block a user