Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 71f110273a | |||
| fdd747fe7f | |||
| c5728d9a32 |
+17
-4
@@ -338,6 +338,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 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
@@ -428,10 +445,6 @@ sequenceDiagram
|
||||
|
||||
GET /v2/positions 查询钱包或单一市场的当前持仓、待赎回份额、互补仓位及已退出记录。用 pagination.next_cursor 续读时沿用原钱包或市场与筛选条件。
|
||||
|
||||
持仓行带父事件的数字 ID 字符串、slug、标题与市场分组标题。盘口上架时可设置 `icon` 和 UTC 毫秒 `end_at_ms`。已有盘口可用可信 JSONL 命令 `set_market_presentation` 同时替换这两个字段,省略某字段可清除显式设置。持仓和 Gamma 共用图标和结束时间。未显式设置时,TWAP 使用观察窗的结束时间。
|
||||
|
||||
运营端用可信 JSONL 命令 `set_wallet_group` 登记一个模拟账户的活跃钱包和其他钱包。每次调用传完整成员列表。用活跃钱包查询 CLOSED 会返回该组各钱包的已退出记录,每行的 `proxy_wallet` 仍标明实际钱包。其他状态按请求钱包读取。
|
||||
|
||||
持仓页支持按标题、事件或最低份额与金额筛选。使用下一页游标时重发这三个筛选参数。
|
||||
|
||||
持仓页支持 sort_by=TIMESTAMP。start 和 end 按 Unix 秒包含两端,翻页时需重发。
|
||||
|
||||
@@ -335,6 +335,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
| "/v2/positions"
|
||||
| "/v2/holders"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
@@ -480,6 +481,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/v2/value"
|
||||
| "/v2/positions"
|
||||
| "/v2/trades"
|
||||
| "/v2/holders"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
@@ -523,15 +525,28 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
"/v2/positions" => read_page(params, engine, Exchange::public_positions),
|
||||
"/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}),
|
||||
@@ -548,6 +563,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}),
|
||||
@@ -721,6 +740,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,18 @@ sequenceDiagram
|
||||
E-->>C: 返回该结果资产的旧步长、新步长、时间和游标
|
||||
```
|
||||
|
||||
公开榜单经 `holders/http.rs` 复用同一排名与估值。毛持仓模式中,`portfolio/economics.sql` 回读本页账户的成交与钱包操作,`portfolio/economics.rs` 计算成本和盈亏。账本顺序由 `portfolio/economics_schema.sql` 的触发器记录。同一毫秒发生的成交和持仓操作也能按写入顺序重放。账户持仓和毛持仓榜使用同一份成本。部分卖出按份额摊销剩余本金和入场费用,费用在对应份额卖出或赎回时计入已实现盈亏。旧数据缺少明确顺序或转换成本时,相关经济字段返回 null。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["holders/http.rs"] --> L["holders.rs / holders.sql"]
|
||||
P["portfolio/positions.rs"] --> E["portfolio/economics.rs"]
|
||||
H --> E
|
||||
E --> Q["portfolio/economics.sql"]
|
||||
Q --> S["portfolio/economics_schema.sql"]
|
||||
I["lib.rs · Exchange::open"] --> S
|
||||
```
|
||||
|
||||
### 体育赛事开赛撤单
|
||||
|
||||
```mermaid
|
||||
@@ -1443,11 +1455,7 @@ flowchart LR
|
||||
cli["cli/market_http.rs"] --> positions["portfolio/positions.rs"]
|
||||
positions --> sql["portfolio/positions.sql"]
|
||||
sql --> activity["成交、钱包流水及分侧赎回时间"]
|
||||
sql --> wallets["position_wallet_members · 模拟账户的钱包归属"]
|
||||
registrar["portfolio/wallet_groups.rs"] --> wallets
|
||||
positions --> mark["portfolio.rs 中的估值"]
|
||||
positions --> metadata["portfolio/position_market_metadata.sql"]
|
||||
metadata --> display["市场资料、父事件与结果分组"]
|
||||
positions --> cost["portfolio/economics.rs"]
|
||||
cost --> fills["portfolio/economics.sql"]
|
||||
```
|
||||
@@ -1458,10 +1466,8 @@ sequenceDiagram
|
||||
participant P as public_positions
|
||||
participant D as SQLite
|
||||
H->>P: 钱包或市场、持仓状态和游标
|
||||
P->>D: 在同一快照读取钱包归属、仓位与市场
|
||||
Note over P,D: 只在活跃钱包查询 CLOSED 时展开登记的其他钱包
|
||||
P->>D: 清理到期任务并读取同一快照中的仓位与市场
|
||||
D-->>P: 持仓、配对份额、裁决、目录及活动时间
|
||||
P->>P: 按有效排序键保留一页、签署下一页游标
|
||||
P->>D: 批量读取本页盘口的父事件、分组、图标和结束时间
|
||||
P-->>H: data 和 pagination
|
||||
```
|
||||
|
||||
@@ -8,8 +8,6 @@ pub(crate) enum Command {
|
||||
cents: Option<i64>,
|
||||
micros: Option<i64>,
|
||||
},
|
||||
#[serde(rename = "set_wallet_group")]
|
||||
SetWalletGroup(crate::portfolio::wallet_groups::WalletGroup),
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
@@ -23,20 +21,12 @@ pub(crate) enum Command {
|
||||
active: bool,
|
||||
archived: bool,
|
||||
},
|
||||
#[serde(rename = "set_market_presentation")]
|
||||
SetMarketPresentation {
|
||||
market: String,
|
||||
icon: Option<String>,
|
||||
end_at_ms: Option<i64>,
|
||||
},
|
||||
#[serde(rename = "tick_size_change")]
|
||||
TickSizeChange(crate::tick_changes::Change),
|
||||
List {
|
||||
market: String,
|
||||
slug: Option<String>,
|
||||
question: Option<String>,
|
||||
icon: Option<String>,
|
||||
end_at_ms: Option<i64>,
|
||||
rules: String,
|
||||
taker_fee_rate_ppm: Option<i64>,
|
||||
base_fees: Option<crate::fees::BaseFees>,
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(super) fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
.to_string()
|
||||
});
|
||||
let dollars = |p: i64| inventory::decimal(p.into(), PAR);
|
||||
let mut value = json!({
|
||||
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")?,
|
||||
@@ -80,13 +80,7 @@ pub(super) fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
"bestBid":bid.map(dollars),"bestAsk":ask.map(dollars),"lastTradePrice":last.map(dollars),"outcomePrices":prices,
|
||||
"makerBaseFee":row.get::<_,i64>("maker_bps")?,"takerBaseFee":row.get::<_,Option<i64>>("taker_bps")?,
|
||||
"negRisk":row.get::<_,bool>("neg_risk")?,"feesEnabled":row.get::<_,bool>("fees_enabled")?
|
||||
});
|
||||
for (key, column) in [("icon", "icon"), ("endDate", "end_date")] {
|
||||
if let Some(text) = row.get::<_, Option<String>>(column)? {
|
||||
value[key] = json!(text);
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
}))
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
|
||||
@@ -2,15 +2,11 @@ SELECT w.market, w.id, w.slug, w.question, w.yes_label, w.no_label, m.rules, m.p
|
||||
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,
|
||||
presentation.icon,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ',COALESCE(presentation.end_at_ms/1000.0,twap.end_at),'unixepoch') AS end_date,
|
||||
tick.step_micros, minimum.microshares, member.market IS NOT NULL AS neg_risk,
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled, fee.maker_bps, fee.taker_bps, COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
|
||||
FROM market_wire_metadata w
|
||||
JOIN markets m ON m.id=w.market
|
||||
LEFT JOIN market_visibility v ON v.market=w.market
|
||||
LEFT JOIN market_presentation presentation ON presentation.market=w.market
|
||||
LEFT JOIN twap_markets twap ON twap.market=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
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::{assets, portfolio, validation::identifier};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
@@ -127,9 +129,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 +201,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,235 @@
|
||||
use super::{minimum_units, Basis, Page};
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
portfolio::economics::{round_money, Economics, HOLDER_FIELDS},
|
||||
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(round_money(p), UNIT)));
|
||||
let fields = economics
|
||||
.cost(account, outcome, units)
|
||||
.map(|cost| cost.fields(value, true));
|
||||
for field in HOLDER_FIELDS {
|
||||
row[field] = fields
|
||||
.as_ref()
|
||||
.map_or(Value::Null, |values| values[field].clone());
|
||||
}
|
||||
}
|
||||
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 portfolio::positions::PositionQuery;
|
||||
@@ -136,6 +137,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!("portfolio/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 {
|
||||
|
||||
@@ -9,29 +9,6 @@ use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn set_presentation(
|
||||
tx: &Transaction<'_>,
|
||||
market: &str,
|
||||
icon: Option<&str>,
|
||||
end_at_ms: Option<i64>,
|
||||
) -> Result<Value> {
|
||||
if let Some(end) = end_at_ms {
|
||||
let representable: bool = tx.query_row(
|
||||
"SELECT strftime('%Y-%m-%dT%H:%M:%fZ',?1/1000.0,'unixepoch') IS NOT NULL",
|
||||
[end],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
ensure!(end >= 0 && representable, "invalid market end_at_ms");
|
||||
}
|
||||
let icon = icon.map(str::trim).filter(|icon| !icon.is_empty());
|
||||
tx.execute(
|
||||
"INSERT INTO market_presentation(market,icon,end_at_ms) VALUES(?,?,?)
|
||||
ON CONFLICT(market) DO UPDATE SET icon=excluded.icon,end_at_ms=excluded.end_at_ms",
|
||||
params![market, icon, end_at_ms],
|
||||
)?;
|
||||
Ok(json!({"market":market,"icon":icon,"end_at_ms":end_at_ms}))
|
||||
}
|
||||
|
||||
pub(crate) fn apply(
|
||||
tx: &Transaction,
|
||||
books: &Books,
|
||||
@@ -66,7 +43,6 @@ pub(crate) fn apply(
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::SetWalletGroup(group) => group.save(tx),
|
||||
Command::SetMarketVisibility {
|
||||
market,
|
||||
active,
|
||||
@@ -80,14 +56,6 @@ pub(crate) fn apply(
|
||||
)?;
|
||||
Ok(json!({"market":market,"active":active,"archived":archived}))
|
||||
}
|
||||
Command::SetMarketPresentation {
|
||||
market,
|
||||
icon,
|
||||
end_at_ms,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
set_presentation(tx, &market, icon.as_deref(), end_at_ms)
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::RescheduleSports {
|
||||
@@ -99,8 +67,6 @@ pub(crate) fn apply(
|
||||
market,
|
||||
slug,
|
||||
question,
|
||||
icon,
|
||||
end_at_ms,
|
||||
rules,
|
||||
listing,
|
||||
resolution,
|
||||
@@ -115,9 +81,6 @@ pub(crate) fn apply(
|
||||
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
||||
params![market, rules],
|
||||
)?;
|
||||
if end_at_ms.is_some() || icon.is_some() {
|
||||
set_presentation(tx, &market, icon.as_deref(), end_at_ms)?;
|
||||
}
|
||||
if let Some(tick) = tick_size {
|
||||
crate::tick_size::TickSize::configure(tx, &market, &tick)?;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
mod economics;
|
||||
pub(crate) mod economics;
|
||||
pub(crate) mod http;
|
||||
pub(crate) mod positions;
|
||||
mod protocol;
|
||||
pub(crate) mod wallet_groups;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
|
||||
@@ -1,62 +1,97 @@
|
||||
use crate::{inventory::decimal, lots};
|
||||
use rusqlite::{params, Connection};
|
||||
use crate::inventory::{decimal, UNIT};
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
const DOLLAR: i64 = 1_000_000;
|
||||
|
||||
// Dollars rounded to four places for position basis and PnL. Fees retain the
|
||||
// exact ledger precision separately, and total cost sums the served columns.
|
||||
pub(super) fn round_money(micros: i128) -> i128 {
|
||||
micros.signum() * ((micros.abs() + 50) / 100) * 100
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Cost {
|
||||
held_lots: i128,
|
||||
bought_lots: i128,
|
||||
lifetime_principal: i128,
|
||||
principal: i128,
|
||||
entry_fees: i128,
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Cost {
|
||||
units: i128,
|
||||
cost: i128,
|
||||
realized: i128,
|
||||
acquired: i128,
|
||||
lifetime_principal: i128,
|
||||
bought: i128,
|
||||
entry_fees: i128,
|
||||
}
|
||||
|
||||
impl Cost {
|
||||
fn fill(&mut self, side: &str, quantity: i64, price: i64, fee: i64) -> Option<()> {
|
||||
let qty = i128::from(quantity);
|
||||
let amount = qty * i128::from(price);
|
||||
let fee = i128::from(fee);
|
||||
match side {
|
||||
"buy" => {
|
||||
self.held_lots += qty;
|
||||
self.bought_lots += qty;
|
||||
self.principal += amount;
|
||||
self.lifetime_principal += amount;
|
||||
self.entry_fees += fee;
|
||||
self.realized -= fee;
|
||||
}
|
||||
"sell" if qty > 0 && qty <= self.held_lots => {
|
||||
let basis = self.principal.checked_mul(qty)? / self.held_lots;
|
||||
let entry_fees = self.entry_fees.checked_mul(qty)? / self.held_lots;
|
||||
self.held_lots -= qty;
|
||||
self.principal -= basis;
|
||||
self.entry_fees -= entry_fees;
|
||||
self.realized += amount - basis - fee;
|
||||
}
|
||||
_ => return None,
|
||||
fn acquire(&mut self, units: i128, cost: i128, fee: i128, from_trade: bool) -> bool {
|
||||
if units <= 0
|
||||
|| !(0..=units).contains(&cost)
|
||||
|| fee < 0
|
||||
|| self.units + units > i128::from(i64::MAX)
|
||||
|| self.entry_fees + fee > i128::from(i64::MAX)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
Some(())
|
||||
self.units += units;
|
||||
self.cost += cost;
|
||||
self.acquired += units;
|
||||
self.lifetime_principal += cost;
|
||||
self.entry_fees += fee;
|
||||
if from_trade {
|
||||
self.bought += units;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn avg_price(&self) -> Option<i128> {
|
||||
let (basis, lots) = if self.held_lots > 0 {
|
||||
(self.principal, self.held_lots)
|
||||
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;
|
||||
let fees = self.entry_fees * units / self.units;
|
||||
self.entry_fees -= fees;
|
||||
self.units -= units;
|
||||
self.realized += proceeds - removed - fees;
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const POSITION_FIELDS: [&str; 10] = [
|
||||
"avg_price",
|
||||
"total_size",
|
||||
"entry_cost_usdc",
|
||||
"entry_fees_usdc",
|
||||
"total_cost_usdc",
|
||||
"realized_pnl",
|
||||
"unrealized_pnl",
|
||||
"total_pnl",
|
||||
"percent_pnl",
|
||||
"percent_realized_pnl",
|
||||
];
|
||||
pub(crate) const HOLDER_FIELDS: [&str; 5] = [
|
||||
"avg_price",
|
||||
"entry_cost_usdc",
|
||||
"realized_pnl",
|
||||
"unrealized_pnl",
|
||||
"total_pnl",
|
||||
];
|
||||
|
||||
pub(crate) fn round_money(micros: i128) -> i128 {
|
||||
micros.signum() * ((micros.abs() + 50) / 100) * 100
|
||||
}
|
||||
|
||||
fn percentage(delta: i128, basis: i128) -> Option<serde_json::Number> {
|
||||
(basis > 0).then_some(())?;
|
||||
Some(decimal(delta.checked_mul(i128::from(UNIT))? / basis, 10000))
|
||||
}
|
||||
|
||||
impl Cost {
|
||||
fn avg_price(&self, include_fees: bool) -> Option<i128> {
|
||||
let (principal, units) = if self.units > 0 {
|
||||
(
|
||||
self.cost + if include_fees { self.entry_fees } else { 0 },
|
||||
self.units,
|
||||
)
|
||||
} else {
|
||||
(self.lifetime_principal, self.bought_lots)
|
||||
(self.lifetime_principal, self.acquired)
|
||||
};
|
||||
(lots > 0).then(|| {
|
||||
let scale = i128::from(crate::lots::PER_SHARE);
|
||||
round_money((basis * scale + lots / 2) / lots)
|
||||
})
|
||||
(units > 0).then_some(())?;
|
||||
Some(principal.checked_mul(i128::from(UNIT))? / units / 100 * 100)
|
||||
}
|
||||
|
||||
fn realized_pnl(&self) -> i128 {
|
||||
@@ -64,23 +99,40 @@ impl Cost {
|
||||
}
|
||||
|
||||
fn unrealized_pnl(&self, value: Option<i128>) -> Option<i128> {
|
||||
value.map(|v| round_money(v) - round_money(self.principal))
|
||||
value.map(|mark| round_money(mark - self.cost))
|
||||
}
|
||||
|
||||
pub(super) fn fields(&self, current_value: Option<i128>) -> Value {
|
||||
let basis = round_money(self.principal);
|
||||
let realized = self.realized_pnl();
|
||||
let unrealized = self.unrealized_pnl(current_value);
|
||||
json!({
|
||||
"avg_price": self.avg_price().map(|v| decimal(v,DOLLAR)),
|
||||
"total_size": decimal(self.bought_lots,lots::PER_SHARE),
|
||||
"entry_cost_usdc":decimal(basis,DOLLAR),
|
||||
"entry_fees_usdc":decimal(self.entry_fees,DOLLAR),
|
||||
"total_cost_usdc":decimal(basis+self.entry_fees,DOLLAR),
|
||||
"realized_pnl":decimal(realized,DOLLAR),
|
||||
"unrealized_pnl":unrealized.map(|v|decimal(v,DOLLAR)),
|
||||
"total_pnl":unrealized.map(|v|decimal(v+realized,DOLLAR)),
|
||||
})
|
||||
fn total_pnl(&self, value: Option<i128>) -> Option<i128> {
|
||||
self.unrealized_pnl(value).map(|p| p + self.realized_pnl())
|
||||
}
|
||||
|
||||
fn historical_basis(&self) -> Option<i128> {
|
||||
if self.units > 0 {
|
||||
Some(self.cost.checked_mul(self.bought)? / self.units)
|
||||
} else {
|
||||
Some(self.lifetime_principal.checked_mul(self.bought)? / self.acquired)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fields(&self, value: Option<i128>, holder: bool) -> Value {
|
||||
let basis = round_money(self.cost);
|
||||
let mut fields = json!({
|
||||
"avg_price": self.avg_price(holder).map(|v| decimal(v,UNIT)),
|
||||
"entry_cost_usdc": decimal(basis,UNIT),
|
||||
"realized_pnl": decimal(self.realized_pnl(),UNIT),
|
||||
"unrealized_pnl": self.unrealized_pnl(value).map(|v| decimal(v,UNIT)),
|
||||
"total_pnl": self.total_pnl(value).map(|v| decimal(v,UNIT))
|
||||
});
|
||||
if !holder {
|
||||
fields["total_size"] = json!(decimal(self.bought, UNIT));
|
||||
fields["entry_fees_usdc"] = json!(decimal(self.entry_fees, UNIT));
|
||||
fields["total_cost_usdc"] = json!(decimal(basis + self.entry_fees, UNIT));
|
||||
fields["percent_pnl"] = json!(value.and_then(|v| percentage(v - self.cost, self.cost)));
|
||||
fields["percent_realized_pnl"] = json!(value
|
||||
.zip(self.historical_basis())
|
||||
.and_then(|(v, b)| percentage(v - b, b)));
|
||||
}
|
||||
fields
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,62 +157,127 @@ impl Metric {
|
||||
|
||||
pub(super) fn rank(self, cost: &Cost, value: Option<i128>) -> Option<i128> {
|
||||
match self {
|
||||
Self::Average => cost.avg_price(),
|
||||
Self::Average => cost.avg_price(false),
|
||||
Self::Realized => Some(cost.realized_pnl()),
|
||||
Self::Unrealized => cost.unrealized_pnl(value),
|
||||
Self::Total => cost.unrealized_pnl(value).map(|p| p + cost.realized_pnl()),
|
||||
Self::Total => cost.total_pnl(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstruct basis only when the recorded fills explain the actual holding.
|
||||
pub(super) fn read(
|
||||
db: &Connection,
|
||||
account: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
current_size: i64,
|
||||
) -> rusqlite::Result<Option<Cost>> {
|
||||
let mut stmt = db.prepare_cached(include_str!("economics.sql"))?;
|
||||
let mut rows = stmt.query(params![account, market, outcome])?;
|
||||
let mut cost = Cost::default();
|
||||
while let Some(row) = rows.next()? {
|
||||
let side: String = row.get(0)?;
|
||||
if cost
|
||||
.fill(&side, row.get(2)?, row.get(1)?, row.get(3)?)
|
||||
.is_none()
|
||||
{
|
||||
return Ok(None);
|
||||
#[derive(Default)]
|
||||
struct Account {
|
||||
sides: [Cost; 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, fee, true)
|
||||
} else {
|
||||
self.sides[idx].dispose(units, cash - fee)
|
||||
}
|
||||
}
|
||||
"SPLIT" => {
|
||||
let first = -cash / 2;
|
||||
self.sides[0].acquire(units, first, 0, false)
|
||||
&& self.sides[1].acquire(units, -cash - first, 0, false)
|
||||
}
|
||||
"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(crate) 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() && row.get::<_, bool>(10)? {
|
||||
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))
|
||||
}
|
||||
if cost.bought_lots == 0
|
||||
|| cost.held_lots * i128::from(lots::MICROS) != i128::from(current_size)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(cost))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prorates_entry_basis_and_fees_after_a_partial_sale() {
|
||||
let mut cost = Cost::default();
|
||||
cost.fill("buy", 600, 4000, 600).unwrap();
|
||||
cost.fill("buy", 400, 6500, 400).unwrap();
|
||||
cost.fill("sell", 300, 8000, 300).unwrap();
|
||||
assert_eq!(
|
||||
cost.fields(Some(4_200_000)),
|
||||
json!({
|
||||
"avg_price":0.5, "total_size":10, "entry_cost_usdc":3.5,
|
||||
"entry_fees_usdc":0.0007, "total_cost_usdc":3.5007,
|
||||
"realized_pnl":0.8987, "unrealized_pnl":0.7, "total_pnl":1.5987
|
||||
})
|
||||
);
|
||||
assert!(cost.fill("sell", 701, 5000, 0).is_none());
|
||||
cost.fill("sell", 700, 5000, 0).unwrap();
|
||||
assert_eq!(cost.fields(Some(0))["entry_cost_usdc"], 0);
|
||||
pub fn cost(&self, account: &str, outcome: &str, units: i64) -> Option<&Cost> {
|
||||
let account = self.0.get(account).filter(|a| !a.incomplete)?;
|
||||
let side = &account.sides[side_index(outcome)?];
|
||||
(side.units == i128::from(units) && side.acquired > 0).then_some(side)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,39 @@
|
||||
SELECT t.side,t.price,t.quantity,COALESCE(f.fee_micros,0)
|
||||
FROM wallet_trade_legs t
|
||||
LEFT JOIN execution_fees f ON f.execution=t.execution AND f.taker_order=t.order_seq
|
||||
WHERE t.account=?1 AND t.market=?2 AND t.outcome=?3
|
||||
-- A fill-only reconstruction cannot assign basis to these custody changes.
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM wallet_movements w
|
||||
WHERE w.account=?1 AND w.market=?2 AND w.kind IN ('SPLIT','MERGE','REDEEM')
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM neg_risk_members n WHERE n.market=?2 AND (
|
||||
EXISTS (SELECT 1 FROM wallet_movements w
|
||||
WHERE w.account=?1 AND w.group_id=n.group_id AND w.kind='CONVERSION')
|
||||
OR EXISTS (SELECT 1 FROM neg_risk_conversion_fees f
|
||||
WHERE f.group_id=n.group_id AND f.vault=?1)
|
||||
)
|
||||
)
|
||||
ORDER BY t.execution,t.order_seq
|
||||
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
|
||||
))
|
||||
UNION ALL
|
||||
SELECT v.vault,0,0,0,NULL,'CONVERSION',NULL,NULL,0,0,NULL
|
||||
FROM neg_risk_members n
|
||||
JOIN neg_risk_conversion_fees v USING(group_id) JOIN requested a ON a.account=v.vault
|
||||
WHERE n.market=?1 AND v.bps>0 AND EXISTS (
|
||||
SELECT 1 FROM wallet_movements w WHERE w.group_id=n.group_id AND w.kind='CONVERSION'
|
||||
)
|
||||
), ordered AS (
|
||||
SELECT l.*,o.seq AS write_seq,
|
||||
MAX(o.seq IS NULL AND l.source=0) OVER (PARTITION BY l.account)
|
||||
AND MAX(o.seq IS NULL AND l.source=1) OVER (PARTITION BY l.account) AS mixed_legacy
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
)
|
||||
SELECT account,source,at_ms,write_seq,operation,outcome,shares,cash,fee,redemption_amounts,mixed_legacy
|
||||
FROM ordered
|
||||
ORDER BY account,write_seq IS NOT NULL,
|
||||
CASE WHEN write_seq IS NULL AND mixed_legacy THEN at_ms END,write_seq,source,record,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;
|
||||
@@ -1,10 +0,0 @@
|
||||
SELECT m.id,CAST(e.event_id AS TEXT),e.slug,e.title,
|
||||
COALESCE(a.name,l.group_title),p.icon,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ',COALESCE(p.end_at_ms/1000.0,t.end_at),'unixepoch')
|
||||
FROM markets m
|
||||
LEFT JOIN listed_markets l ON l.market=m.id
|
||||
LEFT JOIN numbered_events e ON e.id=l.event
|
||||
LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
LEFT JOIN market_presentation p ON p.market=m.id
|
||||
LEFT JOIN twap_markets t ON t.market=m.id
|
||||
WHERE m.id IN (SELECT value FROM json_each(?1))
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::economics::{round_money, Economics, Metric, POSITION_FIELDS};
|
||||
use crate::{
|
||||
assets, expiry,
|
||||
inventory::{decimal, UNIT},
|
||||
@@ -58,7 +59,7 @@ struct Cursor {
|
||||
|
||||
// Negate only the numeric rank for descending order. Identity is a stable
|
||||
// tie-breaker regardless of direction or changes elsewhere in the portfolio.
|
||||
type Key = (bool, i64, String, String, String);
|
||||
type Key = (bool, i128, String, String, String);
|
||||
|
||||
fn invalid(message: &str) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.to_owned())
|
||||
@@ -242,7 +243,7 @@ impl Exchange {
|
||||
{
|
||||
sort = "REALIZED_PNL".into();
|
||||
}
|
||||
let metric = super::economics::Metric::parse(&sort);
|
||||
let metric = Metric::parse(&sort);
|
||||
let direction = query
|
||||
.sort_direction
|
||||
.or_else(|| prior.map(|s| s.direction.clone()))
|
||||
@@ -276,6 +277,7 @@ impl Exchange {
|
||||
let offset = cursor.as_ref().map_or(0, |p| p.offset);
|
||||
let mut page = BTreeMap::new();
|
||||
if limit != 0 {
|
||||
let mut cost_snapshot: Option<(String, String, Economics)> = None;
|
||||
let mut stmt = tx.prepare_cached(include_str!("positions.sql"))?;
|
||||
let mut rows = stmt.query(params![
|
||||
selection.user,
|
||||
@@ -306,38 +308,36 @@ impl Exchange {
|
||||
let last_event_at: Option<i64> = row.get(13)?;
|
||||
let first_entry_at: Option<i64> = row.get(14)?;
|
||||
let (rank, cost) = if let Some(metric) = metric {
|
||||
let cost = super::economics::read(&tx, &account, &market, &outcome, size)?;
|
||||
let rank = cost.as_ref().and_then(|c| metric.rank(c, value));
|
||||
let rank = rank
|
||||
.map(i64::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
(rank, cost)
|
||||
if cost_snapshot
|
||||
.as_ref()
|
||||
.is_none_or(|(a, m, _)| a != &account || m != &market)
|
||||
{
|
||||
let history = Economics::read(&tx, &market, &[account.as_str()])?;
|
||||
cost_snapshot = Some((account.clone(), market.clone(), history));
|
||||
}
|
||||
let cost = cost_snapshot.as_ref().and_then(|(_, _, history)| {
|
||||
history.cost(&account, &outcome, size).cloned()
|
||||
});
|
||||
(
|
||||
cost.as_ref().and_then(|cost| metric.rank(cost, value)),
|
||||
cost,
|
||||
)
|
||||
} else {
|
||||
let rank = match selection.sort.as_str() {
|
||||
"TIMESTAMP" => last_event_at,
|
||||
"TOKENS" => Some(size),
|
||||
"PRICE" => Some(mark.unwrap_or(0)),
|
||||
_ => Some(
|
||||
value
|
||||
.unwrap_or(0)
|
||||
.try_into()
|
||||
.map_err(|_| MarketDataError::Unavailable)?,
|
||||
),
|
||||
"TIMESTAMP" => last_event_at.map(i128::from),
|
||||
"TOKENS" => Some(i128::from(size)),
|
||||
"PRICE" => Some(i128::from(mark.unwrap_or(0))),
|
||||
_ => Some(value.unwrap_or(0)),
|
||||
};
|
||||
(rank, None)
|
||||
};
|
||||
let rank =
|
||||
rank.map_or(
|
||||
i64::MAX,
|
||||
|n| {
|
||||
if selection.direction == "DESC" {
|
||||
-n
|
||||
} else {
|
||||
n
|
||||
}
|
||||
},
|
||||
);
|
||||
let rank = rank.map_or(i128::MAX, |n| {
|
||||
if selection.direction == "DESC" {
|
||||
-n
|
||||
} else {
|
||||
n
|
||||
}
|
||||
});
|
||||
let losing = selection.status == "REDEEMABLE" && payout == Some(0);
|
||||
let key = (
|
||||
losing,
|
||||
@@ -359,18 +359,13 @@ impl Exchange {
|
||||
} else {
|
||||
"OPEN"
|
||||
};
|
||||
let proxy_wallet = if hex_id(&account, 40) {
|
||||
account.to_ascii_lowercase()
|
||||
} else {
|
||||
account.clone()
|
||||
};
|
||||
page.insert(key, (json!({
|
||||
"proxy_wallet": proxy_wallet, "condition_id": market,
|
||||
"proxy_wallet": account, "condition_id": market,
|
||||
"token_id": assets::id(&market,&outcome), "opposite_token_id": assets::id(&market,opposite),
|
||||
"current_size": decimal(size.into(),UNIT),
|
||||
"last_event_at":last_event_at, "first_entry_at":first_entry_at,
|
||||
"current_price": mark.map(|p| decimal(p.into(),UNIT)),
|
||||
"current_value": value.map(|v| decimal(super::economics::round_money(v),UNIT)),
|
||||
"current_value": value.map(|v| decimal(round_money(v),UNIT)),
|
||||
"status": status, "redeemable": redeemable, "mergeable": row.get::<_, bool>(7)?,
|
||||
"archived": row.get::<_, bool>(6)?, "negative_risk": row.get::<_, bool>(12)?,
|
||||
"title": row.get::<_, String>(8)?, "slug": row.get::<_, String>(9)?,
|
||||
@@ -397,60 +392,30 @@ impl Exchange {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut metadata = BTreeMap::new();
|
||||
if !page.is_empty() {
|
||||
let markets: Vec<_> = page
|
||||
.keys()
|
||||
.map(|(_, _, _, market, _)| market.as_str())
|
||||
.collect();
|
||||
let mut stmt = tx.prepare_cached(include_str!("position_market_metadata.sql"))?;
|
||||
let rows = stmt.query_map([json!(markets).to_string()], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
json!({
|
||||
"event_id": r.get::<_, Option<String>>(1)?,
|
||||
"event_slug": r.get::<_, Option<String>>(2)?,
|
||||
"event_title": r.get::<_, Option<String>>(3)?,
|
||||
"group_item_title": r.get::<_, Option<String>>(4)?,
|
||||
"icon": r.get::<_, Option<String>>(5)?,
|
||||
"end_date": r.get::<_, Option<String>>(6)?
|
||||
}),
|
||||
))
|
||||
})?;
|
||||
for row in rows {
|
||||
let (market, value) = row?;
|
||||
metadata.insert(market, value);
|
||||
let mut page_costs = BTreeMap::new();
|
||||
if metric.is_none() {
|
||||
let mut accounts_by_market: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
|
||||
for (_, _, account, market, _) in page.keys() {
|
||||
accounts_by_market.entry(market).or_default().push(account);
|
||||
}
|
||||
for (market, accounts) in accounts_by_market {
|
||||
page_costs.insert(market.to_owned(), Economics::read(&tx, market, &accounts)?);
|
||||
}
|
||||
}
|
||||
let mut data = Vec::with_capacity(page.len());
|
||||
for ((_, _, account, market, outcome), (mut row, size, value, cost)) in page {
|
||||
let cost = if metric.is_some() {
|
||||
cost
|
||||
cost.as_ref()
|
||||
} else {
|
||||
super::economics::read(&tx, &account, &market, &outcome, size)?
|
||||
page_costs
|
||||
.get(&market)
|
||||
.and_then(|history| history.cost(&account, &outcome, size))
|
||||
};
|
||||
let row_fields = row.as_object_mut().expect("position is an object");
|
||||
if let Some(fields) = metadata.get(&market).and_then(Value::as_object) {
|
||||
row_fields.extend(fields.clone());
|
||||
}
|
||||
if let Some(cost) = cost {
|
||||
let Value::Object(fields) = cost.fields(value) else {
|
||||
unreachable!("cost fields form an object")
|
||||
};
|
||||
row_fields.extend(fields);
|
||||
} else {
|
||||
for key in [
|
||||
"avg_price",
|
||||
"entry_cost_usdc",
|
||||
"entry_fees_usdc",
|
||||
"total_cost_usdc",
|
||||
"total_size",
|
||||
"realized_pnl",
|
||||
"unrealized_pnl",
|
||||
"total_pnl",
|
||||
] {
|
||||
row_fields.insert(key.into(), Value::Null);
|
||||
}
|
||||
let fields = cost.map(|cost| cost.fields(value, false));
|
||||
for key in POSITION_FIELDS {
|
||||
row[key] = fields
|
||||
.as_ref()
|
||||
.map_or(Value::Null, |values| values[key].clone());
|
||||
}
|
||||
data.push(row);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
WITH owners(wallet) AS (
|
||||
SELECT ?1
|
||||
UNION
|
||||
SELECT member.wallet
|
||||
FROM position_wallet_members anchor
|
||||
JOIN position_wallet_members member USING(group_id)
|
||||
WHERE ?2 AND ?4='CLOSED' AND anchor.wallet=?1 AND anchor.active
|
||||
), held AS (
|
||||
WITH held AS (
|
||||
SELECT p.*,p.available+p.reserved AS size,
|
||||
COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
|
||||
FROM position_units p LEFT JOIN market_visibility v USING(market)
|
||||
WHERE (?1 IS NULL OR CASE WHEN ?2 THEN p.account COLLATE NOCASE IN (SELECT wallet FROM owners)
|
||||
ELSE p.account=?1 END)
|
||||
WHERE (?1 IS NULL OR CASE WHEN ?2 THEN p.account COLLATE NOCASE=?1 ELSE p.account=?1 END)
|
||||
AND (?3 IS NULL OR p.market IN (SELECT value FROM json_each(?3)))
|
||||
AND (?6 IS NULL OR p.market IN (
|
||||
SELECT l.market FROM listed_markets l JOIN event_directory_ids e ON e.event=l.event
|
||||
@@ -69,3 +61,4 @@ SELECT s.*,c.last_event_at,c.first_entry_at
|
||||
FROM selected s LEFT JOIN clocks c USING(account,market,outcome)
|
||||
WHERE (?9 IS NULL OR c.last_event_at>=?9)
|
||||
AND (?10 IS NULL OR c.last_event_at<=?10)
|
||||
ORDER BY s.account,s.market,s.outcome
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
use super::protocol::CONTRACTS;
|
||||
use crate::validation::{hex_id, identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct WalletGroup {
|
||||
group: String,
|
||||
active_wallet: String,
|
||||
other_wallets: Vec<String>,
|
||||
}
|
||||
|
||||
impl WalletGroup {
|
||||
pub(crate) fn save(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
identifier(&self.group)?;
|
||||
let active_wallet = wallet(&self.active_wallet)?;
|
||||
let mut members = self
|
||||
.other_wallets
|
||||
.iter()
|
||||
.map(|address| wallet(address))
|
||||
.collect::<Result<BTreeSet<_>>>()?;
|
||||
members.insert(active_wallet.clone());
|
||||
|
||||
tx.execute(
|
||||
"DELETE FROM position_wallet_members WHERE group_id=?1",
|
||||
[&self.group],
|
||||
)?;
|
||||
let mut insert = tx.prepare_cached(
|
||||
"INSERT INTO position_wallet_members(wallet,group_id,active) VALUES(?1,?2,?3)",
|
||||
)?;
|
||||
for member in &members {
|
||||
insert.execute(params![member, self.group, member == &active_wallet])?;
|
||||
}
|
||||
Ok(json!({
|
||||
"group":self.group, "active_wallet":active_wallet, "wallet_count":members.len()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn wallet(address: &str) -> Result<String> {
|
||||
ensure!(
|
||||
hex_id(address, 40)
|
||||
&& !CONTRACTS
|
||||
.iter()
|
||||
.any(|known| known.eq_ignore_ascii_case(address)),
|
||||
"expected a wallet address"
|
||||
);
|
||||
Ok(address.to_ascii_lowercase())
|
||||
}
|
||||
@@ -2,22 +2,10 @@ CREATE TABLE IF NOT EXISTS accounts (
|
||||
id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS accounts_by_wallet ON accounts(id COLLATE NOCASE);
|
||||
CREATE TABLE IF NOT EXISTS position_wallet_members (
|
||||
wallet TEXT COLLATE NOCASE PRIMARY KEY NOT NULL,
|
||||
group_id TEXT NOT NULL,
|
||||
active INTEGER NOT NULL CHECK(active IN (0,1))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS position_wallet_group ON position_wallet_members(group_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS position_wallet_active ON position_wallet_members(group_id) WHERE active=1;
|
||||
CREATE TABLE IF NOT EXISTS markets (
|
||||
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
|
||||
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_presentation (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
icon TEXT,
|
||||
end_at_ms INTEGER CHECK(end_at_ms>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_visibility (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
active INTEGER NOT NULL CHECK(active IN (0,1)), archived INTEGER NOT NULL CHECK(archived IN (0,1))
|
||||
|
||||
+104
-205
@@ -1881,6 +1881,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!(
|
||||
@@ -4294,209 +4340,8 @@ fn public_positions_walk_a_mergeable_pair_and_held_settlement() {
|
||||
);
|
||||
let closed = read(&e, json!({"user":"alice","status":"CLOSED"})).unwrap();
|
||||
assert_eq!(closed["data"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_wallet_positions_expand_only_from_the_registered_active_wallet() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("wallet-groups.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let active = "0x00000000000000000000000000000000000000a1";
|
||||
let linked = "0x00000000000000000000000000000000000000B2";
|
||||
let linked_query = linked.to_ascii_lowercase();
|
||||
let outsider = "0x00000000000000000000000000000000000000c3";
|
||||
for market in ["exit", "live", "settled"] {
|
||||
engine
|
||||
.execute(json!({"op":"list","id":format!("list-{market}"),
|
||||
"market":market,"rules":"wallet position fixture"}))
|
||||
.unwrap();
|
||||
}
|
||||
for (n, account) in [active, linked, outsider].into_iter().enumerate() {
|
||||
engine
|
||||
.execute(json!({"op":"fund","id":format!("fund-{n}"),"account":account,"cents":2000}))
|
||||
.unwrap();
|
||||
for market in ["exit", "live", "settled"] {
|
||||
engine
|
||||
.execute(json!({"op":"split","id":format!("split-{n}-{market}"),
|
||||
"market":market,"account":account,"qty":2}))
|
||||
.unwrap();
|
||||
}
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"merge","id":format!("exit-{n}"),"market":"exit",
|
||||
"account":account,"qty":2}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
engine
|
||||
.execute(json!({"op":"close","id":"close-settled","market":"settled"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(json!({"op":"finalize","id":"final-settled","market":"settled","winner":"YES"}))
|
||||
.unwrap();
|
||||
let register = json!({"op":"set_wallet_group","id":"register","group":"person-a",
|
||||
"active_wallet":active,"other_wallets":[linked,linked_query]});
|
||||
assert_eq!(engine.execute(register.clone()).unwrap()["wallet_count"], 2);
|
||||
assert_eq!(engine.execute(register).unwrap()["wallet_count"], 2);
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"set_wallet_group","id":"other-group","group":"person-b",
|
||||
"active_wallet":outsider,"other_wallets":[]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(engine
|
||||
.execute(
|
||||
json!({"op":"set_wallet_group","id":"overlap","group":"person-a",
|
||||
"active_wallet":active,"other_wallets":[outsider]})
|
||||
)
|
||||
.is_err());
|
||||
|
||||
let read = |engine: &Exchange, query| {
|
||||
engine
|
||||
.public_positions(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
for (status, wallet, market, count) in [
|
||||
("OPEN", active, "live", 2),
|
||||
("MERGEABLE", active, "live", 2),
|
||||
("REDEEMABLE", active, "settled", 2),
|
||||
("CLOSED", &linked_query, "exit", 2),
|
||||
("CLOSED", outsider, "exit", 2),
|
||||
] {
|
||||
let page = read(
|
||||
&engine,
|
||||
json!({"user":wallet,"condition":market,"status":status}),
|
||||
);
|
||||
let rows = page["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), count);
|
||||
assert!(rows.iter().all(|row| row["proxy_wallet"] == wallet));
|
||||
}
|
||||
let market = read(&engine, json!({"condition":"exit","status":"CLOSED"}));
|
||||
assert_eq!(market["data"].as_array().unwrap().len(), 6);
|
||||
let first = read(
|
||||
&engine,
|
||||
json!({"user":active,"condition":"exit","status":"CLOSED","limit":1}),
|
||||
);
|
||||
drop(engine);
|
||||
let mut engine = Exchange::open(path).unwrap();
|
||||
let mut page = first;
|
||||
let mut wallets = Vec::new();
|
||||
loop {
|
||||
assert_eq!(page["data"].as_array().unwrap().len(), 1);
|
||||
wallets.push(page["data"][0]["proxy_wallet"].as_str().unwrap().to_owned());
|
||||
let Some(cursor) = page["pagination"]["next_cursor"].as_str() else {
|
||||
break;
|
||||
};
|
||||
page = read(
|
||||
&engine,
|
||||
json!({"user":active,"condition":"exit","cursor":cursor}),
|
||||
);
|
||||
assert!(wallets.len() < 4);
|
||||
}
|
||||
assert_eq!(
|
||||
wallets,
|
||||
vec![active, active, linked_query.as_str(), linked_query.as_str()]
|
||||
);
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"set_wallet_group","id":"rotate","group":"person-a",
|
||||
"active_wallet":linked,"other_wallets":[active]}),
|
||||
)
|
||||
.unwrap();
|
||||
let rows = |user: &str| {
|
||||
read(
|
||||
&engine,
|
||||
json!({"user":user,"condition":"exit","status":"CLOSED"}),
|
||||
)["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.len()
|
||||
};
|
||||
assert_eq!(rows(active), 2);
|
||||
assert_eq!(rows(&linked_query), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_positions_share_catalog_presentation_across_pages_and_queries() {
|
||||
let mut engine = Exchange::open(":memory:").unwrap();
|
||||
for line in include_str!("../../../docs/examples/topic.jsonl")
|
||||
.lines()
|
||||
.take(3)
|
||||
{
|
||||
engine.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
let icon = "https://example.com/market/nvda.png";
|
||||
engine
|
||||
.execute(
|
||||
json!({"op":"set_market_presentation","id":"presentation","market":"nvda-300",
|
||||
"icon":icon,"end_at_ms":1_800_000_000_123_i64}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(engine
|
||||
.execute(
|
||||
json!({"op":"set_market_presentation","id":"invalid","market":"nvda-300",
|
||||
"end_at_ms": i64::MAX})
|
||||
)
|
||||
.is_err());
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"fund-metadata","account":"owner","cents":500}),
|
||||
json!({"op":"list","id":"twap-list","market":"twap","rules":"TWAP fixture",
|
||||
"resolution":{"kind":"twap","stream":"fixture-stream","start_at":4102444790_i64,
|
||||
"end_at":4102444800_i64}}),
|
||||
json!({"op":"split","id":"hold-market","account":"owner","market":"nvda-300","qty":1}),
|
||||
json!({"op":"split","id":"hold-neighbor","account":"owner","market":"nvda-200","qty":1}),
|
||||
json!({"op":"split","id":"hold-twap","account":"owner","market":"twap","qty":1}),
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let event = engine
|
||||
.gamma_event(exchange::DirectoryKey::Slug("nvda-closing-price-2027"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let market = engine
|
||||
.gamma_market(exchange::DirectoryKey::Slug("nvda-300"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(market["icon"], icon);
|
||||
assert_eq!(market["endDate"], "2027-01-15T08:00:00.123Z");
|
||||
let read = |query| {
|
||||
engine
|
||||
.public_positions(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let page = read(json!({"user":"owner","event_id":event["id"],"limit":3}));
|
||||
let cursor = page["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let next = read(json!({"user":"owner","event_id":event["id"],"cursor":cursor}));
|
||||
let all = page["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.chain(next["data"].as_array().unwrap());
|
||||
let mut linked = 0;
|
||||
for row in all {
|
||||
assert_eq!(row["event_id"], event["id"]);
|
||||
assert_eq!(row["event_slug"], event["slug"]);
|
||||
assert_eq!(row["event_title"], event["title"]);
|
||||
if row["condition_id"] == "nvda-300" {
|
||||
linked += 1;
|
||||
assert_eq!(row["icon"], market["icon"]);
|
||||
assert_eq!(row["end_date"], market["endDate"]);
|
||||
assert_eq!(row["group_item_title"], market["groupItemTitle"]);
|
||||
} else {
|
||||
assert_eq!(row["condition_id"], "nvda-200");
|
||||
assert_eq!(row["group_item_title"], "$200");
|
||||
assert!(row["icon"].is_null());
|
||||
assert!(row["end_date"].is_null());
|
||||
}
|
||||
}
|
||||
assert_eq!(linked, 2);
|
||||
let standalone = read(json!({"condition":"twap"}));
|
||||
let row = &standalone["data"][0];
|
||||
assert!(row["event_id"].is_null());
|
||||
assert!(row["event_slug"].is_null());
|
||||
assert!(row["event_title"].is_null());
|
||||
assert!(row["group_item_title"].is_null());
|
||||
assert_eq!(row["end_date"], "2100-01-01T00:00:00.000Z");
|
||||
assert_eq!(closed["data"][0]["realized_pnl"], 5);
|
||||
assert_eq!(closed["data"][1]["realized_pnl"], -5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4551,6 +4396,60 @@ fn public_positions_reconstructs_trade_basis_after_a_partial_sale() {
|
||||
assert_eq!(market["data"][0]["proxy_wallet"], "bob");
|
||||
let cursor = market["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let next = sorted(json!({"condition":"e","cursor":cursor})).unwrap();
|
||||
assert_eq!(next["data"][0]["proxy_wallet"], "trader");
|
||||
assert!(read("alice")["data"][0]["entry_cost_usdc"].is_null());
|
||||
assert_eq!(next["data"][0]["proxy_wallet"], "alice");
|
||||
assert_eq!(next["data"][0]["entry_cost_usdc"], 5);
|
||||
assert_eq!(next["data"][0]["total_size"], 0);
|
||||
let cursor = next["pagination"]["next_cursor"].as_str().unwrap();
|
||||
let last = sorted(json!({"condition":"e","cursor":cursor})).unwrap();
|
||||
assert_eq!(last["data"][0]["proxy_wallet"], "trader");
|
||||
assert_eq!(row["percent_pnl"], 100);
|
||||
assert_eq!(row["percent_realized_pnl"], 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_and_holders_share_costs_but_use_different_average_prices() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("position-fees.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let position = |db: &Exchange| {
|
||||
db.public_positions(
|
||||
serde_json::from_value(json!({"user":"bob","condition":"cup"})).unwrap(),
|
||||
)
|
||||
.unwrap()["data"][0]
|
||||
.clone()
|
||||
};
|
||||
for line in include_str!("../../../docs/examples/fees.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "market_sell" {
|
||||
let open = position(&db);
|
||||
assert_eq!(open["entry_fees_usdc"], json!(1.25));
|
||||
assert_eq!(open["realized_pnl"], 0);
|
||||
}
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
drop(db);
|
||||
let db = Exchange::open(path).unwrap();
|
||||
let open = position(&db);
|
||||
assert_eq!(open["current_size"], 99);
|
||||
assert_eq!(open["entry_cost_usdc"], json!(49.5));
|
||||
assert_eq!(open["entry_fees_usdc"], json!(1.2375));
|
||||
assert_eq!(open["realized_pnl"], json!(-0.223));
|
||||
let holders = db
|
||||
.public_holders(
|
||||
serde_json::from_value(json!({"condition":"cup","include_pnl":true})).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let holder = &holders["data"][0]["holders"][0];
|
||||
assert_eq!(holder["proxy_wallet"], "bob");
|
||||
assert_eq!(holder["avg_price"], json!(0.5125));
|
||||
assert_eq!(open["avg_price"], json!(0.5));
|
||||
for field in [
|
||||
"entry_cost_usdc",
|
||||
"realized_pnl",
|
||||
"current_value",
|
||||
"unrealized_pnl",
|
||||
"total_pnl",
|
||||
] {
|
||||
assert_eq!(holder[field], open[field]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
{
|
||||
"comparison": [
|
||||
{
|
||||
"holder_request": {
|
||||
"url": "https://data-api.polymarket.com/v2/holders?condition=0xd429e8d7062eea25e3b8a4b668075fdcabc874ed7d7f2d8e27a10897f2d9e7e1&include_pnl=true&limit=3",
|
||||
"date": "Sat, 05 Dec 2026 10:02:14 GMT",
|
||||
"status": 200
|
||||
},
|
||||
"position_request": {
|
||||
"url": "https://data-api.polymarket.com/v2/positions?condition=0xd429e8d7062eea25e3b8a4b668075fdcabc874ed7d7f2d8e27a10897f2d9e7e1&user=0x94e4c271a84d72f9efc8326606cee80b6e7c87e0&limit=10",
|
||||
"date": "Sat, 05 Dec 2026 10:02:15 GMT",
|
||||
"status": 200
|
||||
},
|
||||
"holder": {
|
||||
"token_id": "66212785991181043242385918842184346061589075164444484655588738697632121784428",
|
||||
"amount": 10000.0,
|
||||
"avg_price": 0.2578,
|
||||
"entry_cost_usdc": 2536.2415,
|
||||
"current_price": 0.245,
|
||||
"current_value": 2450.0,
|
||||
"realized_pnl": 0.0,
|
||||
"unrealized_pnl": -86.2415,
|
||||
"total_pnl": -86.2415
|
||||
},
|
||||
"position": {
|
||||
"token_id": "66212785991181043242385918842184346061589075164444484655588738697632121784428",
|
||||
"current_size": 10000.0,
|
||||
"total_size": 10000.0,
|
||||
"avg_price": 0.2536,
|
||||
"entry_cost_usdc": 2536.2415,
|
||||
"entry_fees_usdc": 42.41846,
|
||||
"total_cost_usdc": 2578.65996,
|
||||
"current_price": 0.245,
|
||||
"current_value": 2450.0,
|
||||
"realized_pnl": 0.0,
|
||||
"unrealized_pnl": -86.2415,
|
||||
"total_pnl": -86.2415,
|
||||
"percent_pnl": -3.4003,
|
||||
"percent_realized_pnl": -3.4003
|
||||
}
|
||||
},
|
||||
{
|
||||
"holder_request": {
|
||||
"url": "https://data-api.polymarket.com/v2/holders?condition=0xd429e8d7062eea25e3b8a4b668075fdcabc874ed7d7f2d8e27a10897f2d9e7e1&include_pnl=true&limit=3",
|
||||
"date": "Sat, 05 Dec 2026 10:02:14 GMT",
|
||||
"status": 200
|
||||
},
|
||||
"position_request": {
|
||||
"url": "https://data-api.polymarket.com/v2/positions?condition=0xd429e8d7062eea25e3b8a4b668075fdcabc874ed7d7f2d8e27a10897f2d9e7e1&user=0x0346afae2603313d2bbee96b628536c8cbe352a5&limit=10",
|
||||
"date": "Sat, 05 Dec 2026 10:02:15 GMT",
|
||||
"status": 200
|
||||
},
|
||||
"holder": {
|
||||
"token_id": "29727007796287549821138814586181906366437913673914222647744463655310236602624",
|
||||
"amount": 2808.0,
|
||||
"avg_price": 0.7551,
|
||||
"entry_cost_usdc": 2105.9966,
|
||||
"current_price": 0.755,
|
||||
"current_value": 2120.04,
|
||||
"realized_pnl": 0.0,
|
||||
"unrealized_pnl": 14.0433,
|
||||
"total_pnl": 14.0433
|
||||
},
|
||||
"position": {
|
||||
"token_id": "29727007796287549821138814586181906366437913673914222647744463655310236602624",
|
||||
"current_size": 2808.0,
|
||||
"total_size": 2808.0,
|
||||
"avg_price": 0.7499,
|
||||
"entry_cost_usdc": 2105.9966,
|
||||
"entry_fees_usdc": 14.4,
|
||||
"total_cost_usdc": 2120.3966,
|
||||
"current_price": 0.755,
|
||||
"current_value": 2120.04,
|
||||
"realized_pnl": 0.0,
|
||||
"unrealized_pnl": 14.0433,
|
||||
"total_pnl": 14.0433,
|
||||
"percent_pnl": 0.6668,
|
||||
"percent_realized_pnl": 0.6668
|
||||
}
|
||||
}
|
||||
],
|
||||
"trade_activity": {
|
||||
"request": {
|
||||
"url": "https://data-api.polymarket.com/v2/activity?condition=0xdc8c47c5b5d38a0da237b5a82f500ebc5cf5150de902962ac6ff76051ffe9159&user=0xbc79e27f2c94124aeefb08d74b4e4fd3ac834e4d&type=TRADE&limit=20",
|
||||
"date": "Sat, 05 Dec 2026 10:02:16 GMT",
|
||||
"status": 200
|
||||
},
|
||||
"fields": [
|
||||
{
|
||||
"side": "SELL",
|
||||
"price": 0.024,
|
||||
"size": 18.83,
|
||||
"usdc_size": 0.42987,
|
||||
"timestamp": 1796425000,
|
||||
"token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029"
|
||||
},
|
||||
{
|
||||
"side": "SELL",
|
||||
"price": 0.0194444444,
|
||||
"size": 45.0,
|
||||
"usdc_size": 0.83211,
|
||||
"timestamp": 1796380585,
|
||||
"token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029"
|
||||
},
|
||||
{
|
||||
"side": "BUY",
|
||||
"price": 0.077,
|
||||
"size": 24.65,
|
||||
"usdc_size": 1.98564,
|
||||
"timestamp": 1796319905,
|
||||
"token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029"
|
||||
},
|
||||
{
|
||||
"side": "BUY",
|
||||
"price": 0.0765630793,
|
||||
"size": 39.183377,
|
||||
"usdc_size": 3.13851,
|
||||
"timestamp": 1796319905,
|
||||
"token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -476,7 +480,7 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
|
||||
公开 GET /v2/positions 已接入本地账本。可按钱包查询,或用一个市场查持有人,也可对钱包附加市场条件。OPEN 包含仍持有的已裁决资产,REDEEMABLE 保留待兑付的胜负两侧,REDEEMABLE_LOST 选出尚未核销的零兑付资产。MERGEABLE 返回持有互补份额的两侧,CLOSED 查询已经退出或低于 0.1 份的仓位。当前持仓使用 0.1 份下限。游标由本地签名,绑定查询、页大小及最后一行的排序键。逐页使用各自的已提交快照,仓位变动可能改变后续排序。
|
||||
|
||||
这一版返回数量、估值、配对与赎回标记、结果身份和目录标题。本地支持份额、价格和当前价值排序。活跃钱包的 CLOSED 查询包含同一模拟账户下已显式登记的其他钱包,结果保留每行的实际钱包。可以通过可信命令更换活跃钱包。生产钱包归属由 Polymarket 识别,本地归属由运营端登记。实测 0.0088 份已裁决余额出现在 CLOSED,仍标记 redeemable。用相同条件查询 OPEN 和 REDEEMABLE 均为空,即使传入 filter_amount=0。事件字段来自同一目录的父事件 ID、slug 与标题。分组标题沿用 Gamma 的优先级,以已命名的互斥结果优先。显式登记的市场结束时间和图标供两个接口共用。TWAP 市场可用观察窗结束时间,其他缺少有效日期的持仓返回 null。生产响应中的姓名和签名游标未保存在样本里。[公开生产响应摘要](examples/public-position-lifecycle.json) · [官方持仓规范](https://data-api.polymarket.com/v2/openapi.json)
|
||||
这一版返回数量、估值、配对与赎回标记、结果身份和目录标题。本地支持份额、价格和当前价值排序。跨钱包关闭记录仍待接入。实测 0.0088 份已裁决余额出现在 CLOSED,仍标记 redeemable。用相同条件查询 OPEN 和 REDEEMABLE 均为空,即使传入 filter_amount=0。生产响应中的姓名和签名游标未保存在样本里。[公开生产响应摘要](examples/public-position-lifecycle.json) · [官方持仓规范](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
|
||||
持仓列表支持 title(不区分 ASCII 大小写、保留 SQL LIKE 通配符)、event_id(最多 20 个事件、仅钱包查询、与 condition 互斥)和 filter_type / filter_amount。TOKENS 按当前份额过滤,CASH 按当前估值过滤,门槛包含等值。无效筛选类型返回 400,负门槛采用默认行为。翻页时继续发送标题、事件和金额参数。钱包 CLOSED 维持 0.1 份的边界,市场维度的份额门槛会移动 OPEN 与 CLOSED 分界。标题非 ASCII 大小写及市场维度边界仍待生产对照。[生产筛选样本](examples/public-position-filters.json)
|
||||
@@ -485,7 +489,7 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
持仓活动时间按结果资产从成交、拆分、合并、互斥转换及赎回推导。start/end 按 Unix 秒包含两端,非正数表示无界。有界查询排除没有可信时间的行。可用 TIMESTAMP 排序,翻页时重发窗口。本地 first_entry_at 是最早有记录的取得时间。历史全额赎回缺少分侧数据,转换费用金库的入账时间及在平仓后重新入场的时间口径仍待核验。新赎回按实际烧掉的结果记录时间。裁决、挂单或撤单本身不增加持仓活动。[生产时间窗口样本](examples/public-position-time.json)
|
||||
|
||||
|
||||
公开持仓的可重建成交仓位返回平均买入价、累计买入份额、剩余入场本金和费用、以及已实现和未实现盈亏。部分卖出按加权成本摊销本金和入场费用。费用从真实账本读取,发生时计入已实现盈亏。四位小数的本金、估值和盈亏与六位费用分开舍入。只有成交流水能解释当前持有量时才提供成本字段。涉及拆分、合并、赎回或互斥转换时现阶段返回 null。尚未核验外场买卖费用的逐笔归因、平仓再买后的成本口径。[生产持仓和对应成交](examples/public-position-economics.json) · [官方持仓字段](https://data-api.polymarket.com/v2/openapi.json)
|
||||
账户持仓和毛持仓榜共用一套账本。买入手续费单列并随卖出、合并或赎回按份额摊销。未实现盈亏沿用扣除剩余本金的口径。可重建的拆分和合并按两侧等额分摊本地抵押,已完成的赎回按真实兑付入账。混用多个日志来源且缺时钟或同毫秒无法判断顺序时,或互斥转换缺失分腿成本时,经济字段留空。百分比采用官方的剩余本金和累计买入份额口径,分母为零时留空。生产样本中 10,000 份的榜单平均价为 0.2578,账户持仓为 0.2536,两处的剩余本金、估值和盈亏一致。另一个部分卖出的样本,可由公开成交净额和按份额摊销的买入费重建出接近的已实现盈亏。生产扣费舍入和跨市场转换仍待逐笔验证。[生产对照](examples/public-shared-position-economics.json) · [官方持仓字段](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
|
||||
持仓页可按 AVG_PRICE、REALIZED_PNL、UNREALIZED_PNL 和 TOTAL_PNL 排序,已知值按返回精度比较,缺少可重建成本的仓位排列在末尾。钱包 CLOSED 默认按已实现盈亏排序,给它 TOKENS、CURRENT_VALUE、PRICE 或 UNREALIZED_PNL 时也采用已实现盈亏。钱包 CLOSED 和 REDEEMABLE_LOST 拒绝 AVG_PRICE。游标绑定实际采用的排序。旧 CLOSED 游标使用被替代的排序键时要从第一页重新获取。生产未核验缺成本行的相对位置。[生产排序样本](examples/public-position-economics-sorts.json)
|
||||
|
||||
Reference in New Issue
Block a user