From 76f721786cb5a74527644af757efb5e6b52b6d0e Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Sat, 5 Dec 2026 04:55:24 +0800 Subject: [PATCH] Reconstruct trade-only position basis and realized results --- crates/exchange/README.md | 2 + crates/exchange/src/portfolio.rs | 1 + crates/exchange/src/portfolio/economics.rs | 120 +++++++++++++++++++ crates/exchange/src/portfolio/economics.sql | 18 +++ crates/exchange/src/portfolio/positions.rs | 29 ++++- crates/exchange/tests/market.rs | 29 +++++ docs/examples/public-position-economics.json | 47 ++++++++ docs/prediction-parity.md | 5 +- 8 files changed, 246 insertions(+), 5 deletions(-) create mode 100644 crates/exchange/src/portfolio/economics.rs create mode 100644 crates/exchange/src/portfolio/economics.sql create mode 100644 docs/examples/public-position-economics.json diff --git a/crates/exchange/README.md b/crates/exchange/README.md index 8874355..8e2221b 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -1444,6 +1444,8 @@ flowchart LR positions --> sql["portfolio/positions.sql"] sql --> activity["成交、钱包流水及分侧赎回时间"] positions --> mark["portfolio.rs 中的估值"] + positions --> cost["portfolio/economics.rs"] + cost --> fills["portfolio/economics.sql"] ``` ```mermaid diff --git a/crates/exchange/src/portfolio.rs b/crates/exchange/src/portfolio.rs index d3f8569..6233f2a 100644 --- a/crates/exchange/src/portfolio.rs +++ b/crates/exchange/src/portfolio.rs @@ -1,3 +1,4 @@ +mod economics; pub(crate) mod http; pub(crate) mod positions; mod protocol; diff --git a/crates/exchange/src/portfolio/economics.rs b/crates/exchange/src/portfolio/economics.rs new file mode 100644 index 0000000..d0e5dae --- /dev/null +++ b/crates/exchange/src/portfolio/economics.rs @@ -0,0 +1,120 @@ +use crate::{inventory::decimal, lots}; +use rusqlite::{params, Connection}; +use serde_json::{json, Value}; + +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)] +struct Cost { + held_lots: i128, + bought_lots: i128, + principal: i128, + entry_fees: i128, + realized: 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.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, + } + Some(()) + } + + fn fields(&self, current_value: Option) -> Value { + let basis = round_money(self.principal); + let realized = round_money(self.realized); + let unrealized = current_value.map(|v| round_money(v) - basis); + let avg = (self.held_lots > 0).then(|| { + let scale = i128::from(lots::PER_SHARE); + round_money((self.principal * scale + self.held_lots / 2) / self.held_lots) + }); + json!({ + "avg_price": avg.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)), + }) + } +} + +/// 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, + current_value: Option, +) -> rusqlite::Result { + 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(Value::Null); + } + } + if cost.bought_lots == 0 + || cost.held_lots * i128::from(lots::MICROS) != i128::from(current_size) + { + return Ok(Value::Null); + } + Ok(cost.fields(current_value)) +} + +#[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); + } +} diff --git a/crates/exchange/src/portfolio/economics.sql b/crates/exchange/src/portfolio/economics.sql new file mode 100644 index 0000000..38f229f --- /dev/null +++ b/crates/exchange/src/portfolio/economics.sql @@ -0,0 +1,18 @@ +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 diff --git a/crates/exchange/src/portfolio/positions.rs b/crates/exchange/src/portfolio/positions.rs index f76cbaa..b313687 100644 --- a/crates/exchange/src/portfolio/positions.rs +++ b/crates/exchange/src/portfolio/positions.rs @@ -327,20 +327,20 @@ impl Exchange { } else { "OPEN" }; - page.insert(key, json!({ + page.insert(key, (json!({ "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(v,UNIT)), + "current_value": value.map(|v| decimal(super::economics::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)?, "outcome": row.get::<_, String>(if yes {10} else {11})?, "opposite_outcome": row.get::<_, String>(if yes {11} else {10})?, "outcome_index": if yes {0} else {1} - })); + }), size, value)); if page.len() > limit as usize + 1 { page.pop_last(); } @@ -360,7 +360,28 @@ impl Exchange { } else { None }; - let data: Vec<_> = page.into_values().collect(); + let mut data = Vec::with_capacity(page.len()); + for ((_, _, account, market, outcome), (mut row, size, value)) in page { + let fields = super::economics::read(&tx, &account, &market, &outcome, size, value)?; + let row_fields = row.as_object_mut().expect("position is an object"); + if let Value::Object(fields) = fields { + 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); + } + } + data.push(row); + } tx.commit()?; Ok( json!({"data":data,"pagination":{"limit":limit,"offset":offset,"has_more":has_more,"next_cursor":next}}), diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index b518570..fc929f9 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -4293,3 +4293,32 @@ 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 public_positions_reconstructs_trade_basis_after_a_partial_sale() { + let mut e = Exchange::open(":memory:").unwrap(); + setup(&mut e); + for cmd in [ + json!({"op":"fund","id":"fund-trader","account":"trader","cents":2000}), + json!({"op":"open","id":"open","market":"e"}), + order("ask", "alice", "sell", 40, 10), + order("entry", "trader", "buy", 40, 10), + order("exit", "trader", "sell", 80, 3), + order("buyer", "bob", "buy", 80, 3), + ] { + e.execute(cmd).unwrap(); + } + let read = |user| { + e.public_positions(serde_json::from_value(json!({"user":user})).unwrap()) + .unwrap() + }; + let page = read("trader"); + let row = &page["data"][0]; + assert_eq!(row["current_size"], 7); + assert_eq!(row["total_size"], 10); + assert_eq!(row["entry_cost_usdc"], 2.8); + assert_eq!(row["realized_pnl"], 1.2); + assert_eq!(row["unrealized_pnl"], 2.8); + assert_eq!(row["total_pnl"], 4); + assert!(read("alice")["data"][0]["entry_cost_usdc"].is_null()); +} diff --git a/docs/examples/public-position-economics.json b/docs/examples/public-position-economics.json new file mode 100644 index 0000000..c96a88d --- /dev/null +++ b/docs/examples/public-position-economics.json @@ -0,0 +1,47 @@ +{ + "position": { + "condition_id": "0xdc8c47c5b5d38a0da237b5a82f500ebc5cf5150de902962ac6ff76051ffe9159", + "token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029", + "proxy_wallet": "0xbc79e27f2c94124aeefb08d74b4e4fd3ac834e4d", + "current_size": 18.8333, + "total_size": 63.8333, + "avg_price": 0.0767, + "current_value": 0.9322, + "entry_cost_usdc": 1.4451, + "entry_fees_usdc": 0.066709, + "total_cost_usdc": 1.511809, + "realized_pnl": -2.7801, + "unrealized_pnl": -0.5129, + "total_pnl": -3.293 + }, + "trades": { + "url": "https://data-api.polymarket.com/v2/trades?user=0xbc79e27f2c94124aeefb08d74b4e4fd3ac834e4d&condition=0xdc8c47c5b5d38a0da237b5a82f500ebc5cf5150de902962ac6ff76051ffe9159&limit=50", + "status": 200, + "date": "Fri, 04 Dec 2026 20:53:08 GMT", + "body": { + "data": [ + { + "token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029", + "side": "SELL", + "price": 0.0194444444, + "size": 45.0, + "timestamp": 1796380585 + }, + { + "token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029", + "side": "BUY", + "price": 0.077, + "size": 24.65, + "timestamp": 1796319905 + }, + { + "token_id": "49932611791842248277648635261891267637049151266001723816279042019553905945029", + "side": "BUY", + "price": 0.0765630793, + "size": 39.183377, + "timestamp": 1796319905 + } + ] + } + } +} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index d77b3d8..a17bbab 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -472,10 +472,13 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场 公开 GET /v2/positions 已接入本地账本。可按钱包查询,或用一个市场查持有人,也可对钱包附加市场条件。OPEN 包含仍持有的已裁决资产,REDEEMABLE 保留待兑付的胜负两侧,REDEEMABLE_LOST 选出尚未核销的零兑付资产。MERGEABLE 返回持有互补份额的两侧,CLOSED 查询已经退出或低于 0.1 份的仓位。当前持仓使用 0.1 份下限。游标由本地签名,绑定查询、页大小及最后一行的排序键。逐页使用各自的已提交快照,仓位变动可能改变后续排序。 -这一版返回数量、估值、配对与赎回标记、结果身份和目录标题。本地支持份额、价格和当前价值排序。成本、盈亏、历史总入场量、跨钱包关闭记录仍待接入。实测 0.0088 份已裁决余额出现在 CLOSED,仍标记 redeemable。用相同条件查询 OPEN 和 REDEEMABLE 均为空,即使传入 filter_amount=0。生产响应中的姓名和签名游标未保存在样本里。[公开生产响应摘要](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) 持仓活动时间按结果资产从成交、拆分、合并、互斥转换及赎回推导。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)