diff --git a/crates/cli/README.md b/crates/cli/README.md index 4c3c1c2..cfca67f 100644 --- a/crates/cli/README.md +++ b/crates/cli/README.md @@ -427,3 +427,5 @@ sequenceDiagram GET /v2/positions 查询钱包或单一市场的当前持仓、待赎回份额、互补仓位及已退出记录。用 pagination.next_cursor 续读时沿用原钱包或市场与筛选条件。 持仓页支持按标题、事件或最低份额与金额筛选。使用下一页游标时重发这三个筛选参数。 + +持仓页支持 sort_by=TIMESTAMP。start 和 end 按 Unix 秒包含两端,翻页时需重发。 diff --git a/crates/exchange/README.md b/crates/exchange/README.md index b323bfe..8874355 100644 --- a/crates/exchange/README.md +++ b/crates/exchange/README.md @@ -1442,6 +1442,7 @@ sequenceDiagram flowchart LR cli["cli/market_http.rs"] --> positions["portfolio/positions.rs"] positions --> sql["portfolio/positions.sql"] + sql --> activity["成交、钱包流水及分侧赎回时间"] positions --> mark["portfolio.rs 中的估值"] ``` @@ -1452,7 +1453,7 @@ sequenceDiagram participant D as SQLite H->>P: 钱包或市场、持仓状态和游标 P->>D: 清理到期任务并读取同一快照中的仓位与市场 - D-->>P: 持仓、配对份额、裁决和目录 + D-->>P: 持仓、配对份额、裁决、目录及活动时间 P->>P: 按排序键保留一页、签署下一页游标 P-->>H: data 和 pagination ``` diff --git a/crates/exchange/src/market.rs b/crates/exchange/src/market.rs index 3d12185..4c250d7 100644 --- a/crates/exchange/src/market.rs +++ b/crates/exchange/src/market.rs @@ -479,6 +479,19 @@ fn redeem( request_id: &str, amounts: Option<[i64; 2]>, ) -> Result { + tx.execute( + "INSERT INTO position_redemption_times(account,market,outcome,at_ms) + SELECT account,market,outcome,CAST(unixepoch('subsec')*1000 AS INTEGER) + FROM position_units WHERE account=?1 AND market=?2 AND available>0 + AND (?3 IS NULL OR CASE outcome WHEN 'YES' THEN ?3 ELSE ?4 END>0) + ON CONFLICT(account,market,outcome) DO UPDATE SET at_ms=excluded.at_ms", + params![ + account, + market, + amounts.map(|a| a[0]), + amounts.map(|a| a[1]) + ], + )?; let (shares, paid) = match amounts { Some(amounts) => crate::neg_risk::burn_for_redemption(tx, market, account, amounts)?, None => burn_full_balance(tx, market, account)?, diff --git a/crates/exchange/src/portfolio/positions.rs b/crates/exchange/src/portfolio/positions.rs index d40316e..f76cbaa 100644 --- a/crates/exchange/src/portfolio/positions.rs +++ b/crates/exchange/src/portfolio/positions.rs @@ -32,6 +32,8 @@ pub struct PositionQuery { sort_direction: Option, #[serde(alias = "includeArchived")] include_archived: Option, + start: Option, + end: Option, limit: Option, cursor: Option, } @@ -183,6 +185,12 @@ impl Exchange { } } + let start = query.start.filter(|n| *n > 0); + let end = query.end.filter(|n| *n > 0); + if matches!((start, end), (Some(a), Some(b)) if b < a) { + return Err(invalid("end must not be before start")); + } + let cursor = query .cursor .as_deref() @@ -220,8 +228,10 @@ impl Exchange { .sort_direction .or_else(|| prior.map(|s| s.direction.clone())) .unwrap_or_else(|| "DESC".into()); - if !matches!(sort.as_str(), "CURRENT_VALUE" | "PRICE" | "TOKENS") - || !matches!(direction.as_str(), "ASC" | "DESC") + if !matches!( + sort.as_str(), + "CURRENT_VALUE" | "PRICE" | "TOKENS" | "TIMESTAMP" + ) || !matches!(direction.as_str(), "ASC" | "DESC") { return Err(invalid("invalid or unsupported position sort")); } @@ -254,7 +264,9 @@ impl Exchange { selection.archived, events, title, - shares_floor + shares_floor, + start, + end ])?; while let Some(row) = rows.next()? { let account: String = row.get(0)?; @@ -270,19 +282,30 @@ impl Exchange { if cash && floor > 0 && value.is_none_or(|v| v < i128::from(floor)) { continue; } + let last_event_at: Option = row.get(13)?; + let first_entry_at: Option = row.get(14)?; let rank = match selection.sort.as_str() { - "TOKENS" => size, - "PRICE" => mark.unwrap_or(0), - _ => value - .unwrap_or(0) - .try_into() - .map_err(|_| MarketDataError::Unavailable)?, - }; - let rank = if selection.direction == "DESC" { - -rank - } else { - rank + "TIMESTAMP" => last_event_at, + "TOKENS" => Some(size), + "PRICE" => Some(mark.unwrap_or(0)), + _ => Some( + value + .unwrap_or(0) + .try_into() + .map_err(|_| MarketDataError::Unavailable)?, + ), }; + let rank = + rank.map_or( + i64::MAX, + |n| { + if selection.direction == "DESC" { + -n + } else { + n + } + }, + ); let losing = selection.status == "REDEEMABLE" && payout == Some(0); let key = ( losing, @@ -308,6 +331,7 @@ impl Exchange { "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)), "status": status, "redeemable": redeemable, "mergeable": row.get::<_, bool>(7)?, diff --git a/crates/exchange/src/portfolio/positions.sql b/crates/exchange/src/portfolio/positions.sql index 435634a..7d451cc 100644 --- a/crates/exchange/src/portfolio/positions.sql +++ b/crates/exchange/src/portfolio/positions.sql @@ -8,7 +8,7 @@ WITH held AS ( SELECT l.market FROM listed_markets l JOIN event_directory_ids e ON e.event=l.event WHERE e.id IN (SELECT value FROM json_each(?6)) )) -) +), selected AS ( SELECT p.account,p.market,p.outcome,p.size,p.phase,p.payout_per_share,p.archived, p.phase<>'resolved' AND p.size>=100000 AND COALESCE(other.size,0)>=100000 AS mergeable, w.question,w.slug,w.yes_label,w.no_label,n.market IS NOT NULL AS negative_risk @@ -25,3 +25,39 @@ WHERE (?7 IS NULL OR w.question LIKE ?7) AND CASE ?4 WHEN 'MERGEABLE' THEN mergeable END END +), observations AS ( + SELECT s.account,s.market,s.outcome,t.at_ms,t.side='buy' AS entry + FROM selected s JOIN wallet_trade_legs t + ON t.account=s.account AND t.market=s.market AND t.outcome=s.outcome + UNION ALL + SELECT s.account,s.market,s.outcome,w.at_ms,w.kind='SPLIT' + FROM selected s JOIN wallet_movements w ON w.account=s.account AND w.market=s.market + WHERE w.kind IN ('SPLIT','MERGE') + UNION ALL + SELECT s.account,s.market,s.outcome,w.at_ms,0 + FROM selected s + JOIN wallet_movements w ON w.account=s.account AND w.market=s.market AND w.kind='REDEEM' + JOIN requests r ON r.id=w.request_id + WHERE json_extract(r.response,CASE s.outcome WHEN 'YES' THEN '$.amounts_micros[0]' ELSE '$.amounts_micros[1]' END)>0 + UNION ALL + SELECT s.account,s.market,s.outcome,w.at_ms,s.outcome='YES' + FROM selected s + JOIN neg_risk_members n ON n.market=s.market + JOIN wallet_movements w ON w.account=s.account AND w.group_id=n.group_id AND w.kind='CONVERSION' + JOIN requests r ON r.id=w.request_id + WHERE s.market IN ( + SELECT value FROM json_each(r.response,CASE s.outcome WHEN 'YES' THEN '$.yes_markets' ELSE '$.no_markets' END) + ) + AND (s.outcome='NO' OR COALESCE(json_extract(r.response,'$.conversion_fee.bps'),0)<10000) + UNION ALL + SELECT s.account,s.market,s.outcome,r.at_ms,0 + FROM selected s JOIN position_redemption_times r USING(account,market,outcome) +), clocks AS ( + SELECT account,market,outcome,MAX(at_ms)/1000 AS last_event_at, + MIN(CASE WHEN entry THEN at_ms END)/1000 AS first_entry_at + FROM observations GROUP BY account,market,outcome +) +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) diff --git a/crates/exchange/src/schema.sql b/crates/exchange/src/schema.sql index 166e619..5b75c12 100644 --- a/crates/exchange/src/schema.sql +++ b/crates/exchange/src/schema.sql @@ -322,6 +322,15 @@ CREATE TABLE IF NOT EXISTS budget_spend_micros ( ); -- Keep issued public trade cursors valid after a restart, scoped to this database. +-- Preserve which outcome was actually burned by a full redemption. +CREATE TABLE IF NOT EXISTS position_redemption_times ( + account TEXT NOT NULL REFERENCES accounts, + market TEXT NOT NULL REFERENCES markets, + outcome TEXT NOT NULL, + at_ms INTEGER NOT NULL, + PRIMARY KEY(account,market,outcome) +); + CREATE TABLE IF NOT EXISTS trade_cursor_key ( singleton INTEGER PRIMARY KEY CHECK(singleton=1), secret BLOB NOT NULL CHECK(length(secret)=32) ); diff --git a/crates/exchange/tests/market.rs b/crates/exchange/tests/market.rs index 07cc216..b518570 100644 --- a/crates/exchange/tests/market.rs +++ b/crates/exchange/tests/market.rs @@ -4234,6 +4234,26 @@ fn public_positions_walk_a_mergeable_pair_and_held_settlement() { json!([]) ); assert!(read(&e, json!({"user":"alice","event_id":"1","condition":"e"})).is_err()); + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute( + "UPDATE wallet_movements SET at_ms=123999 WHERE request_id='s'", + [], + ) + .unwrap(); + let instant = read( + &e, + json!({"user":"alice","start":123,"end":123,"sort_by":"TIMESTAMP"}), + ) + .unwrap(); + assert_eq!(instant["data"].as_array().unwrap().len(), 2); + assert_eq!(instant["data"][0]["first_entry_at"], 123); + assert_eq!(instant["data"][0]["last_event_at"], 123); + assert_eq!( + read(&e, json!({"user":"alice","start":124})).unwrap()["data"], + json!([]) + ); + assert!(read(&e, json!({"user":"alice","start":124,"end":123})).is_err()); + drop(db); let first = read(&e, json!({"user":"alice","status":"MERGEABLE","limit":1})).unwrap(); assert_eq!(first["data"][0]["mergeable"], true); let cursor = first["pagination"]["next_cursor"].as_str().unwrap(); diff --git a/docs/examples/public-position-time.json b/docs/examples/public-position-time.json new file mode 100644 index 0000000..61dbce9 --- /dev/null +++ b/docs/examples/public-position-time.json @@ -0,0 +1,10 @@ +{ + "sort_desc": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&status=OPEN&sort_by=TIMESTAMP&limit=5","status":200,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"data":[{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116865","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417119},{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417318,"first_entry_at":1796417101},{"token_id":"643049684020821311351796507355633171121115944121291300545830924465303715840","condition_id":"0x016bf4066e82571228813b876d04127934000000000000000000000000000000","status":"REDEEMABLE","last_event_at":1796417123,"first_entry_at":1796416804},{"token_id":"623948551310085686003807523523823512265834388288292452103061352323364159489","condition_id":"0x016124720ad566f88bc302b21b492db296000000000000000000000000000000","status":"REDEEMABLE","last_event_at":1796416819,"first_entry_at":1796416496},{"token_id":"595598232364135711271605858900428478751902694056243533045033760895327535105","condition_id":"0x015118be44ab1eaf0539263c3943a4c95f000000000000000000000000000000","status":"REDEEMABLE","last_event_at":1796416525,"first_entry_at":1796416165}]}}, + "sort_asc": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&status=OPEN&sort_by=TIMESTAMP&sort_direction=ASC&limit=5","status":200,"date":"Fri, 04 Dec 2026 20:49:47 GMT","body":{"data":[{"token_id":"108211118887905827198085240321612246840377385685588945381741674294231397172455","condition_id":"0xbe5219d1c82daaa110a20c0b50dae77f681f05eb43094e05ea24fe833c5ec47f","status":"REDEEMABLE","last_event_at":1744791574,"first_entry_at":1744779538},{"token_id":"44939317539819072767368114561139572498853620329975668979095413555067370578574","condition_id":"0xb12a219f75d35ad91ee9428d22e47f1ee6de61f5d79466b1749c8b66aed2f2d9","status":"REDEEMABLE","last_event_at":1748760251,"first_entry_at":1747881352},{"token_id":"77444435762420711044339640645792265526010696615911175439180482698545420366139","condition_id":"0xa4f51ae09144ebedb1e4329a28597dcb25217be1050fb76b86335837943bf519","status":"REDEEMABLE","last_event_at":1748986412,"first_entry_at":1748847554},{"token_id":"46741667374359006482611348910695433711657619345444561736608864383253626406210","condition_id":"0x461bc99cf3a7d76bd9fd52ab850d62d1d985cee88b940c80ae9888a94176e83b","status":"REDEEMABLE","last_event_at":1749879384,"first_entry_at":1749701035},{"token_id":"57190891280800009123681638917785245658930686322518532172325806346323335059331","condition_id":"0x6edc6c77c16ef3ba1bcd646159f12f8b8a39528e500dcff95b9220ccfbb75141","status":"REDEEMABLE","last_event_at":1750663953,"first_entry_at":1747628175}]}}, + "instant": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&start=1796417320&end=1796417320","status":200,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"data":[{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116865","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417119}]}}, + "after": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&start=1796417321","status":200,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"data":[]}}, + "before": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&end=1796417319","status":200,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"data":[{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417318,"first_entry_at":1796417101}]}}, + "inversion": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&start=1796417321&end=1796417320","status":400,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"error":"end must not be before start","code":"invalid_request","retryable":false}}, + "negative": {"url":"https://data-api.polymarket.com/v2/positions?user=0x19b3823092892c026517fd0ff58df4889abe0b9b&condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&start=-1","status":200,"date":"Fri, 04 Dec 2026 20:49:44 GMT","body":{"data":[{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417318,"first_entry_at":1796417101},{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116865","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417119}]}}, + "market_instant": {"url":"https://data-api.polymarket.com/v2/positions?condition=0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000&start=1796417320&end=1796417320&limit=3","status":200,"date":"Fri, 04 Dec 2026 20:49:45 GMT","body":{"data":[{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417122},{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417128},{"token_id":"720714510152246054130276515843293825241395125263705983303209818949486116864","condition_id":"0x0197e8f2f080b39c8703e35e54c228192b000000000000000000000000000000","status":"OPEN","last_event_at":1796417320,"first_entry_at":1796417129}]}} +} diff --git a/docs/prediction-parity.md b/docs/prediction-parity.md index 9e4ead4..d77b3d8 100644 --- a/docs/prediction-parity.md +++ b/docs/prediction-parity.md @@ -472,7 +472,10 @@ 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)