市场成交与持仓数据及含吃单手续费的本地交割 #7
@@ -73,6 +73,9 @@ flowchart LR
|
||||
trades -->|读取两类成交| legsql["src/account_trades.sql"]
|
||||
trades -->|返回结果资产| assets
|
||||
queries -->|账户挂单与单笔状态| acct["src/account_orders.rs"]
|
||||
acct -->|原单类型、post-only、受理时间| terms["src/order_submission_schema.sql"]
|
||||
book -->|受理订单时保存指令| terms
|
||||
api -->|从旧命令回执恢复指令| terms
|
||||
acct -->|校验账户和市场| valid
|
||||
queries -->|账户持仓| portfolio["src/portfolio.rs"]
|
||||
portfolio -->|获取每份持仓估值| marks["src/quotes.rs"]
|
||||
@@ -195,12 +198,14 @@ sequenceDiagram
|
||||
participant C as CLI
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: 提交限价单或市价单
|
||||
E->>D: 同一写事务保存订单、有效订单类型、post-only 和受理时间
|
||||
C->>E: open_orders 指定本地账户,可选市场和结果
|
||||
E->>D: 读取该账户活跃订单,按原始订单号分页
|
||||
E-->>C: 原始数量、累计成交、可成交余量和下一页游标
|
||||
C->>E: 撤单后按账户和订单号再次查询
|
||||
E->>D: 查找该账户名下的指定订单,包含终态
|
||||
E-->>C: 已撤状态、保留的累计成交、零可成交余量
|
||||
E-->>C: 原单受理时间与类型、已撤状态、累计成交、零可成交余量
|
||||
```
|
||||
|
||||
## 查询当前持仓与待兑付份额
|
||||
|
||||
@@ -46,7 +46,9 @@ impl Filter {
|
||||
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
|
||||
b.amount_cents,COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq) FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at
|
||||
FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
LEFT JOIN order_submissions s ON s.order_seq=orders.seq
|
||||
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
|
||||
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
|
||||
);
|
||||
@@ -79,6 +81,8 @@ impl Filter {
|
||||
"price_micros":row.get::<_,i64>(4)?*100,"original_size":crate::lots::display(quantity),
|
||||
"size_matched":crate::lots::display(quantity-remaining),"open_size":crate::lots::display(if status=="live"{remaining}else{0}),
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
|
||||
"order_type":row.get::<_,Option<String>>(13)?,"post_only":row.get::<_,Option<bool>>(14)?,
|
||||
"created_at":row.get::<_,Option<i64>>(15)?,
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
|
||||
@@ -42,6 +42,27 @@ pub(crate) fn gross_micros(fills: &[Fill]) -> i64 {
|
||||
fills.iter().map(|f| f.price * f.quantity).sum()
|
||||
}
|
||||
|
||||
fn record_submission(
|
||||
tx: &Transaction,
|
||||
seq: i64,
|
||||
tif: TimeInForce,
|
||||
post_only: bool,
|
||||
key: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let order_type = match tif {
|
||||
TimeInForce::Gtc => "GTC",
|
||||
TimeInForce::Gtd => "GTD",
|
||||
TimeInForce::Ioc => "IOC",
|
||||
TimeInForce::Fok => "FOK",
|
||||
TimeInForce::Fak => "FAK",
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO order_submissions(order_seq,order_type,post_only) VALUES(?,?,?)",
|
||||
params![seq, order_type, post_only],
|
||||
)?;
|
||||
crate::heartbeat::record_key(tx, seq, key)
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<ShareExecution> {
|
||||
let NewOrder {
|
||||
market,
|
||||
@@ -107,7 +128,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
}
|
||||
tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
crate::heartbeat::record_key(tx, seq, key_id.as_deref())?;
|
||||
record_submission(tx, seq, tif, post_only, key_id.as_deref())?;
|
||||
if let Some(deadline) = deadline {
|
||||
tx.execute(
|
||||
"INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)",
|
||||
@@ -216,7 +237,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
params![account, market, outcome, max_price],
|
||||
)?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
crate::heartbeat::record_key(tx, seq, key_id.as_deref())?;
|
||||
record_submission(tx, seq, tif, false, key_id.as_deref())?;
|
||||
let mut fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| b.match_budget_buy(seq, max_price, amount_cents * 10000))
|
||||
|
||||
@@ -84,6 +84,13 @@ impl Exchange {
|
||||
db.busy_timeout(Duration::from_secs(10))?;
|
||||
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
||||
db.execute_batch(include_str!("schema.sql"))?;
|
||||
let submissions_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_submissions')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !submissions_ready {
|
||||
db.execute_batch(include_str!("order_submission_schema.sql"))?;
|
||||
}
|
||||
let directory_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='event_directory_ids')",
|
||||
[], |row| row.get(0),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS order_submissions (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq),
|
||||
order_type TEXT NOT NULL,
|
||||
post_only INTEGER NOT NULL CHECK(post_only IN (0,1)),
|
||||
created_at INTEGER DEFAULT (unixepoch())
|
||||
);
|
||||
|
||||
-- Old receipts preserve the accepted instruction but do not record when it was submitted.
|
||||
INSERT INTO order_submissions(order_seq,order_type,post_only,created_at)
|
||||
SELECT o.seq, COALESCE(json_extract(r.payload,'$.tif'),
|
||||
CASE WHEN json_extract(r.payload,'$.op') IN ('market_buy','market_sell') THEN 'FAK'
|
||||
WHEN d.seq IS NOT NULL THEN 'GTD' ELSE 'GTC' END),
|
||||
COALESCE(json_extract(r.payload,'$.post_only'),0), NULL
|
||||
FROM requests r JOIN orders o ON o.seq=json_extract(r.response,'$.order')
|
||||
LEFT JOIN order_deadlines d ON d.seq=o.seq
|
||||
WHERE json_extract(r.payload,'$.op') IN ('order','market_buy','market_sell')
|
||||
AND json_type(r.response,'$.order')='integer'
|
||||
ON CONFLICT(order_seq) DO NOTHING;
|
||||
COMMIT;
|
||||
@@ -712,6 +712,8 @@ fn gtd_expiry_survives_rejection_and_recovery() {
|
||||
.execute(json!({"op":"open_orders","account":"alice","order":ask_id}))
|
||||
.unwrap();
|
||||
assert_eq!(lookup["orders"][0]["status"], "expired");
|
||||
assert_eq!(lookup["orders"][0]["order_type"], "GTD");
|
||||
assert_eq!(lookup["orders"][0]["post_only"], true);
|
||||
assert_eq!(lookup["orders"][0]["size_matched"], 2);
|
||||
assert_eq!(lookup["orders"][0]["open_size"], 0);
|
||||
let held = e
|
||||
@@ -4022,3 +4024,54 @@ fn explicit_redemption_requires_a_resolved_adapter_market_even_for_zero() {
|
||||
1000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("submission.sqlite");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let cmds: Vec<Value> = include_str!("../../../docs/examples/order-status.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect();
|
||||
for cmd in &cmds[..6] {
|
||||
e.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let before = e.execute(cmds[6].clone()).unwrap()["orders"][0].clone();
|
||||
assert!(before["created_at"].as_i64().unwrap() > 0);
|
||||
assert_eq!(before["order_type"], "GTC");
|
||||
assert_eq!(before["post_only"], true);
|
||||
assert_eq!(before["open_size"], 5);
|
||||
e.execute(cmds[7].clone()).unwrap();
|
||||
let partial = e.execute(cmds[8].clone()).unwrap()["orders"][0].clone();
|
||||
assert_eq!(partial["size_matched"], 2);
|
||||
assert_eq!(partial["open_size"], 3);
|
||||
assert_eq!(partial["created_at"], before["created_at"]);
|
||||
e.execute(cmds[9].clone()).unwrap();
|
||||
drop(e);
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
e.execute(cmds[5].clone()).unwrap();
|
||||
let closed = e.execute(cmds[10].clone()).unwrap()["orders"][0].clone();
|
||||
assert_eq!(closed["status"], "cancelled");
|
||||
assert_eq!(closed["open_size"], 0);
|
||||
assert_eq!(closed["created_at"], before["created_at"]);
|
||||
let filled = e.execute(cmds[11].clone()).unwrap()["orders"][0].clone();
|
||||
assert_eq!(filled["order_type"], "FAK");
|
||||
assert_eq!(filled["post_only"], false);
|
||||
assert_eq!(filled["status"], "filled");
|
||||
assert_eq!(
|
||||
e.execute(cmds[12].clone()).unwrap()["trades"][0]["size"],
|
||||
closed["size_matched"]
|
||||
);
|
||||
|
||||
drop(e);
|
||||
rusqlite::Connection::open(&path)
|
||||
.unwrap()
|
||||
.execute("DROP TABLE order_submissions", [])
|
||||
.unwrap();
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
for (cmd, mut expected) in [(&cmds[10], closed), (&cmds[11], filled)] {
|
||||
expected["created_at"] = Value::Null;
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{"op":"list","id":"market","market":"match","rules":"Official match winner"}
|
||||
{"op":"fund","id":"fund-seller","account":"seller","cents":500}
|
||||
{"op":"fund","id":"fund-buyer","account":"buyer","cents":120}
|
||||
{"op":"split","id":"pairs","account":"seller","market":"match","qty":5}
|
||||
{"op":"open","id":"start","market":"match"}
|
||||
{"op":"order","id":"offer","market":"match","outcome":"YES","side":"sell","account":"seller","qty":5,"price":60,"post_only":true}
|
||||
{"op":"open_orders","account":"seller","order":1}
|
||||
{"op":"market_buy","id":"take","market":"match","outcome":"YES","account":"buyer","amount_cents":120,"max_price":60}
|
||||
{"op":"open_orders","account":"seller","order":1}
|
||||
{"op":"cancel","id":"cancel-offer","account":"seller","order":1}
|
||||
{"op":"open_orders","account":"seller","order":1}
|
||||
{"op":"open_orders","account":"buyer","order":2}
|
||||
{"op":"trades","account":"seller","order":1}
|
||||
@@ -456,3 +456,9 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
当前 SDK 的 `redeem_positions(condition_id)` 选择该市场的协议路径,领取持有人两侧的余额。另一个公开入口是 NegRiskAdapter 的 `redeemPositions(conditionId, amounts)`,先将调用人指定的 YES 和 NO 转入适配器,再执行底层兑付。即使兑付额为零,适配器仍发出带有输入数量和兑付额的事件。以下样例验证该适配器的数量语义;生产协议版本、批量交易及链上回执尚待比对。[官方持仓接口](https://docs.polymarket.com/trading/positions/manage) · [适配器源码](https://github.com/Polymarket/neg-risk-ctf-adapter/blob/main/src/NegRiskAdapter.sol#L191-L207)
|
||||
|
||||
先重放[费用样例](examples/neg-risk-fee.jsonl),再重放[按量赎回样例](examples/neg-risk-redemption.jsonl)。在已裁决的互斥市场,`redeem.amounts_micros` 依次填写 YES 和 NO 微份。甲判 NO 后,交入 `[125001,500001]`,共销毁 625002 微份,兑付 500001 微美元。随后仅交入落败的 YES,现金兑付为零。两侧均为零时留下零额赎回记录。省略数量仍会赎回两侧剩余余额;甲的剩余 NO 可兑付 1000000 微美元。任一侧不足会回滚整笔操作。回执中的 `paid` 以分计,按量模式另给出整数微美元 `paid_micros`。钱包活动同时列出总销毁份额、两侧微份数和净现金变化。
|
||||
|
||||
### 原单受理信息和成交核对
|
||||
|
||||
用空数据库重放[原单状态样例](examples/order-status.jsonl)。卖方以 0.60 挂 5 份 post-only 卖单,买方按金额吃掉 2 份。卖方撤回余单后,按原订单号查询,累计成交仍为 2,可成交余量为 0,`order_type` 为 GTC。买方的原单类型为 FAK。按卖方订单号查询 `trades`,这笔执行的份额也是 2。重启和重发相同命令沿用原回执与受理时间。
|
||||
|
||||
`open_orders` 的列表和精确查询均返回 `created_at`(Unix 秒)、`order_type` 和本地扩展 `post_only`。升级已有数据库时,用已受理的命令回执和 GTD 截止记录恢复提交指令;没有原始时钟记录的受理时间为 null。缺少原始回执的历史行仍可查询,未知字段保留为 null。官方当前将累计成交和逐笔对账分别放在订单的 size_matched 和账户成交记录;其单笔订单 HTTP 接口需要账户认证。本地验证使用可信操作员的 JSONL 接口,订单号与账户是模拟环境的标识。生产私有接口尚未实测。[官方订单查询](https://docs.polymarket.com/trading/manage-orders)
|
||||
|
||||
Reference in New Issue
Block a user