Cancel account orders by ID batch, market or outcome asset
This commit is contained in:
@@ -35,6 +35,8 @@ flowchart LR
|
|||||||
expiry -->|到期封盘并释放订单预留| market
|
expiry -->|到期封盘并释放订单预留| market
|
||||||
twap -->|保存定点价格与证据| schema
|
twap -->|保存定点价格与证据| schema
|
||||||
res -->|规则与裁决状态| schema
|
res -->|规则与裁决状态| schema
|
||||||
|
market -->|批量、市场或账户撤单| cancellation["src/cancellation.rs"]
|
||||||
|
cancellation -->|释放订单未成交的预留| book
|
||||||
market -->|匹配命令类型| cmd
|
market -->|匹配命令类型| cmd
|
||||||
market -->|检查数量、标识和市场阶段| valid
|
market -->|检查数量、标识和市场阶段| valid
|
||||||
market -->|下单、撤单与开盘| book["src/book.rs"]
|
market -->|下单、撤单与开盘| book["src/book.rs"]
|
||||||
@@ -250,3 +252,19 @@ sequenceDiagram
|
|||||||
E->>D: 比较两个端点,校验抵押并记录结果
|
E->>D: 比较两个端点,校验抵押并记录结果
|
||||||
E-->>I: 返回最终结果与待兑付金额
|
E-->>I: 返回最终结果与待兑付金额
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 批量撤单
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant C as CLI
|
||||||
|
participant E as Exchange
|
||||||
|
participant D as SQLite
|
||||||
|
participant B as 常驻盘口
|
||||||
|
C->>E: cancel_orders 提交账户、请求键与订单号列表
|
||||||
|
E->>D: 查历史回执,或在写事务内按账户检查原单
|
||||||
|
E->>D: 对可撤订单释放余量,记录未撤原因与回执
|
||||||
|
D-->>E: 提交订单、资产和回执
|
||||||
|
E->>B: 同步撤单并移除对应互补挂单
|
||||||
|
E-->>C: canceled 与 not_canceled
|
||||||
|
```
|
||||||
|
|||||||
@@ -33,7 +33,15 @@ pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
|||||||
pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||||
if !matches!(
|
if !matches!(
|
||||||
request["op"].as_str(),
|
request["op"].as_str(),
|
||||||
Some("order" | "book" | "quote" | "history" | "open_orders" | "trades")
|
Some(
|
||||||
|
"order"
|
||||||
|
| "book"
|
||||||
|
| "quote"
|
||||||
|
| "history"
|
||||||
|
| "open_orders"
|
||||||
|
| "trades"
|
||||||
|
| "cancel_market_orders"
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use crate::{
|
||||||
|
book::{release, CancelReason},
|
||||||
|
validation::identifier,
|
||||||
|
};
|
||||||
|
use anyhow::{ensure, Result};
|
||||||
|
use rusqlite::{params, Transaction};
|
||||||
|
use serde_json::{json, Map, Value};
|
||||||
|
|
||||||
|
pub(crate) fn by_id(tx: &Transaction, account: &str, orders: &[i64]) -> Result<Value> {
|
||||||
|
identifier(account)?;
|
||||||
|
ensure!(
|
||||||
|
(1..=3000).contains(&orders.len()),
|
||||||
|
"cancel_orders requires 1 to 3000 order IDs"
|
||||||
|
);
|
||||||
|
let mut stmt = tx.prepare(
|
||||||
|
"WITH requested AS (
|
||||||
|
SELECT value AS id, MIN(key) AS ordinal FROM json_each(?1) GROUP BY value
|
||||||
|
)
|
||||||
|
SELECT r.id,o.status FROM requested r LEFT JOIN orders o ON o.seq=r.id AND o.account=?2
|
||||||
|
ORDER BY r.ordinal",
|
||||||
|
)?;
|
||||||
|
// Capture the candidate set before touching orders via the same connection.
|
||||||
|
let selected = stmt
|
||||||
|
.query_map(params![serde_json::to_string(orders)?, account], |r| {
|
||||||
|
Ok((r.get::<_, i64>(0)?, r.get::<_, Option<String>>(1)?))
|
||||||
|
})?
|
||||||
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
|
let mut canceled = Vec::new();
|
||||||
|
let mut not_canceled = Map::new();
|
||||||
|
for (order, status) in selected {
|
||||||
|
match status.as_deref() {
|
||||||
|
Some("live") => {
|
||||||
|
release(tx, order, account, CancelReason::Cancelled)?;
|
||||||
|
canceled.push(order);
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
let reason =
|
||||||
|
other.map_or_else(|| "order not found".to_owned(), |s| format!("order is {s}"));
|
||||||
|
not_canceled.insert(order.to_string(), json!(reason));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(json!({"canceled":canceled,"not_canceled":not_canceled}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn in_scope(
|
||||||
|
tx: &Transaction,
|
||||||
|
account: &str,
|
||||||
|
market: Option<&str>,
|
||||||
|
outcome: Option<&str>,
|
||||||
|
) -> Result<Value> {
|
||||||
|
identifier(account)?;
|
||||||
|
if let Some(market) = market {
|
||||||
|
identifier(market)?;
|
||||||
|
}
|
||||||
|
if let Some(outcome) = outcome {
|
||||||
|
ensure!(
|
||||||
|
market.is_some() && matches!(outcome, "YES" | "NO"),
|
||||||
|
"invalid cancellation scope"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut stmt = tx.prepare(
|
||||||
|
"SELECT seq FROM orders WHERE account=?1 AND status='live'
|
||||||
|
AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3) ORDER BY seq",
|
||||||
|
)?;
|
||||||
|
let canceled = stmt
|
||||||
|
.query_map(params![account, market, outcome], |r| r.get::<_, i64>(0))?
|
||||||
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
|
for order in &canceled {
|
||||||
|
release(tx, *order, account, CancelReason::Cancelled)?;
|
||||||
|
}
|
||||||
|
Ok(json!({"canceled":canceled,"not_canceled":{}}))
|
||||||
|
}
|
||||||
@@ -50,6 +50,21 @@ pub(crate) enum Command {
|
|||||||
account: String,
|
account: String,
|
||||||
order: i64,
|
order: i64,
|
||||||
},
|
},
|
||||||
|
#[serde(rename = "cancel_orders")]
|
||||||
|
CancelOrders {
|
||||||
|
account: String,
|
||||||
|
orders: Vec<i64>,
|
||||||
|
},
|
||||||
|
#[serde(rename = "cancel_market_orders")]
|
||||||
|
CancelMarketOrders {
|
||||||
|
account: String,
|
||||||
|
market: String,
|
||||||
|
outcome: Option<String>,
|
||||||
|
},
|
||||||
|
#[serde(rename = "cancel_all")]
|
||||||
|
CancelAll {
|
||||||
|
account: String,
|
||||||
|
},
|
||||||
Open {
|
Open {
|
||||||
market: String,
|
market: String,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ mod twap;
|
|||||||
mod validation;
|
mod validation;
|
||||||
use validation::identifier;
|
use validation::identifier;
|
||||||
mod book;
|
mod book;
|
||||||
|
mod cancellation;
|
||||||
mod command;
|
mod command;
|
||||||
mod ledger;
|
mod ledger;
|
||||||
mod market;
|
mod market;
|
||||||
|
|||||||
@@ -143,6 +143,15 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
|||||||
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
||||||
Ok(json!({"cancelled":qty}))
|
Ok(json!({"cancelled":qty}))
|
||||||
}
|
}
|
||||||
|
Command::CancelOrders { account, orders } => {
|
||||||
|
crate::cancellation::by_id(tx, &account, &orders)
|
||||||
|
}
|
||||||
|
Command::CancelMarketOrders {
|
||||||
|
account,
|
||||||
|
market,
|
||||||
|
outcome,
|
||||||
|
} => crate::cancellation::in_scope(tx, &account, Some(&market), outcome.as_deref()),
|
||||||
|
Command::CancelAll { account } => crate::cancellation::in_scope(tx, &account, None, None),
|
||||||
Command::Open { market } => {
|
Command::Open { market } => {
|
||||||
phase(tx, &market, &["preopen"])?;
|
phase(tx, &market, &["preopen"])?;
|
||||||
// Run one auction. Using the earliest order's outcome as the quote unit
|
// Run one auction. Using the earliest order's outcome as the quote unit
|
||||||
|
|||||||
@@ -1000,3 +1000,92 @@ fn twap_market_closes_before_settlement_and_reuses_exact_observations() {
|
|||||||
300
|
300
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_cancel_releases_only_remaining_owned_orders_and_replays_receipt() {
|
||||||
|
let dir = tempdir().unwrap();
|
||||||
|
let path = dir.path().join("cancel.db");
|
||||||
|
let mut e = Exchange::open(&path).unwrap();
|
||||||
|
setup(&mut e);
|
||||||
|
e.execute(json!({"op":"open","id":"start","market":"e"}))
|
||||||
|
.unwrap();
|
||||||
|
let ask = e.execute(order("offer", "alice", "sell", 63, 5)).unwrap()["order"].clone();
|
||||||
|
let filled = e.execute(order("take", "bob", "buy", 65, 2)).unwrap()["order"].clone();
|
||||||
|
let foreign = e.execute(order("other", "bob", "buy", 10, 1)).unwrap()["order"].clone();
|
||||||
|
let mut no = order("no", "alice", "buy", 20, 4);
|
||||||
|
no["outcome"] = json!("NO");
|
||||||
|
let bid = e.execute(no).unwrap()["order"].clone();
|
||||||
|
let batch = json!({"op":"cancel_orders","id":"withdraw","account":"alice",
|
||||||
|
"orders":[bid,ask,bid,foreign,99999]});
|
||||||
|
let result = e.execute(batch.clone()).unwrap();
|
||||||
|
assert_eq!(result["canceled"], json!([bid, ask]));
|
||||||
|
assert_eq!(
|
||||||
|
result["not_canceled"][foreign.to_string().as_str()],
|
||||||
|
"order not found"
|
||||||
|
);
|
||||||
|
assert_eq!(result["not_canceled"]["99999"], "order not found");
|
||||||
|
let again = e
|
||||||
|
.execute(json!({"op":"cancel_orders","id":"again","account":"bob","orders":[filled]}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
again["not_canceled"][filled.to_string().as_str()],
|
||||||
|
"order is filled"
|
||||||
|
);
|
||||||
|
drop(e);
|
||||||
|
let mut e = Exchange::open(path).unwrap();
|
||||||
|
assert_eq!(e.execute(batch).unwrap(), result);
|
||||||
|
let state = state(&mut e);
|
||||||
|
assert_eq!(state["accounts"][0]["cash"], 1126);
|
||||||
|
let yes = state["positions"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|p| p["account"] == "alice" && p["outcome"] == "YES")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(yes["quantity"], 8);
|
||||||
|
let bob = e
|
||||||
|
.execute(json!({"op":"open_orders","account":"bob"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(bob["orders"][0]["order"], foreign);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn market_and_asset_cancels_are_scoped_to_the_original_side() {
|
||||||
|
let mut e = Exchange::open(":memory:").unwrap();
|
||||||
|
setup(&mut e);
|
||||||
|
e.execute(json!({"op":"list","id":"m2","market":"other","rules":"official"}))
|
||||||
|
.unwrap();
|
||||||
|
let yes = e.execute(order("yes", "alice", "sell", 60, 1)).unwrap()["order"].clone();
|
||||||
|
let mut n = order("no", "alice", "buy", 40, 1);
|
||||||
|
n["outcome"] = json!("NO");
|
||||||
|
let no = e.execute(n).unwrap()["order"].clone();
|
||||||
|
let mut elsewhere = order("other-bid", "alice", "buy", 10, 1);
|
||||||
|
elsewhere["market"] = json!("other");
|
||||||
|
let other = e.execute(elsewhere).unwrap()["order"].clone();
|
||||||
|
let scoped = json!({"op":"cancel_market_orders","id":"yes-only","account":"alice","asset_id":"eb:YES:e"});
|
||||||
|
assert_eq!(e.execute(scoped.clone()).unwrap()["canceled"], json!([yes]));
|
||||||
|
let new = e.execute(order("later", "alice", "sell", 60, 1)).unwrap()["order"].clone();
|
||||||
|
assert_eq!(e.execute(scoped).unwrap()["canceled"], json!([yes]));
|
||||||
|
assert!(e
|
||||||
|
.execute(json!({"op":"cancel_market_orders","id":"missing","account":"alice"}))
|
||||||
|
.is_err());
|
||||||
|
assert!(e
|
||||||
|
.execute(json!({"op":"cancel_all","id":"wrong","account":"alice","market":"e"}))
|
||||||
|
.is_err());
|
||||||
|
assert!(e
|
||||||
|
.execute(json!({"op":"cancel_orders","id":"empty","account":"alice","orders":[]}))
|
||||||
|
.is_err());
|
||||||
|
assert!(e
|
||||||
|
.execute(
|
||||||
|
json!({"op":"cancel_orders","id":"oversize","account":"alice","orders":vec![1;3001]})
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
let market = e
|
||||||
|
.execute(json!({"op":"cancel_market_orders","id":"m-only","account":"alice","market":"e"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(market["canceled"], json!([no, new]));
|
||||||
|
let all = e
|
||||||
|
.execute(json!({"op":"cancel_all","id":"everything","account":"alice"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(all, json!({"canceled":[other],"not_canceled":{}}));
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 事件、市场和结果 | 体育事件下有多个二元合约、规则、结果标签与稳定本地资产 ID | 场所资产映射、非体育事件、多结果组合和版本映射 |
|
| 事件、市场和结果 | 体育事件下有多个二元合约、规则、结果标签与稳定本地资产 ID | 场所资产映射、非体育事件、多结果组合和版本映射 |
|
||||||
| 报价与走势 | 本地成交曲线、连续交易展示价、分档盘口 | 细分报价单位、外场快照和实际历史样本 |
|
| 报价与走势 | 本地成交曲线、连续交易展示价、分档盘口 | 细分报价单位、外场快照和实际历史样本 |
|
||||||
| 委托与成交 | 单簿价格时间优先、GTC、GTD、IOC、FAK、FOK、连续交易 post-only 与互补买卖单 | 按金额买入及场所延迟和失败回报 |
|
| 委托与成交 | 单簿价格时间优先、GTC、GTD、IOC、FAK、FOK、连续交易 post-only、互补买卖单与批量撤单 | 按金额买入及场所延迟和失败回报 |
|
||||||
| 持仓与抵押 | 模拟资产拆分、成套合并、裁决后按账户主动赎回 | 链上赎回回执、费用与多结果转换 |
|
| 持仓与抵押 | 模拟资产拆分、成套合并、裁决后按账户主动赎回 | 链上赎回回执、费用与多结果转换 |
|
||||||
| 裁决与交割 | 人工、两轮乐观裁决或双端点 TWAP 比较,保存证据并兑付 | 保证金及奖励、真实 UMA 仲裁、Chainlink 签名与现场报价、链上交割状态 |
|
| 裁决与交割 | 人工、两轮乐观裁决或双端点 TWAP 比较,保存证据并兑付 | 保证金及奖励、真实 UMA 仲裁、Chainlink 签名与现场报价、链上交割状态 |
|
||||||
| 客户端 | CLI 查询规则、价格曲线、报价、账户挂单、逐笔成交、单笔终态与持仓状态 | 账户认证与会话可见范围、非交易活动、成本与盈亏及断线回补 |
|
| 客户端 | CLI 查询规则、价格曲线、报价、账户挂单、逐笔成交、单笔终态与持仓状态 | 账户认证与会话可见范围、非交易活动、成本与盈亏及断线回补 |
|
||||||
@@ -96,3 +96,9 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果
|
|||||||
达到 end_at 后,下一次请求或重启先封盘并释放余单。缺失观测时 resolution 返回 awaiting_observations;取得双方观测后返回 ready_to_finalize、价格、证据与 computed_winner。用 finalize 指定市场即可应用计算结果。旧 resolve 和显式指定 winner 的 finalize 同样核对计算结果。同一流和时刻可供相邻市场共用;重报须具有相同规范价格与证据。提早、错流、错时或冲突报告均拒绝。
|
达到 end_at 后,下一次请求或重启先封盘并释放余单。缺失观测时 resolution 返回 awaiting_observations;取得双方观测后返回 ready_to_finalize、价格、证据与 computed_winner。用 finalize 指定市场即可应用计算结果。旧 resolve 和显式指定 winner 的 finalize 同样核对计算结果。同一流和时刻可供相邻市场共用;重报须具有相同规范价格与证据。提早、错流、错时或冲突报告均拒绝。
|
||||||
|
|
||||||
本地从可信模拟输入接收已计算的端点值。真实 Chainlink 报告获取、签名验证与流标识映射仍待完成。本地的封盘由请求或恢复触发,实际外场延迟未实测。[官方涨跌裁决规则](https://docs.polymarket.com/concepts/resolution.md)
|
本地从可信模拟输入接收已计算的端点值。真实 Chainlink 报告获取、签名验证与流标识映射仍待完成。本地的封盘由请求或恢复触发,实际外场延迟未实测。[官方涨跌裁决规则](https://docs.polymarket.com/concepts/resolution.md)
|
||||||
|
|
||||||
|
## 按订单或市场范围撤单
|
||||||
|
|
||||||
|
`{"op":"cancel_orders","id":"batch-1","account":"alice","orders":[12,7,12,19]}` 接受 1 至 3000 个原始订单号,忽略重复项。假设 12 号仍有余量、7 号已全部成交、19 号不属于 Alice,回执为 `{"canceled":[12],"not_canceled":{"7":"order is filled","19":"order not found"}}`。买单只退还限价乘以未成交份数的已预留资金;卖单只返还未卖出的份额。新请求键会重新评估订单,重试原请求键和原内容会重放第一次的结果。
|
||||||
|
|
||||||
|
`cancel_market_orders` 必须指定 market 或 asset_id。仅提供 market 会撤销该账户在市场两侧的活跃订单,指定资产则只选择该结果的原始委托。例如撤掉原始 YES 卖单后,同价位由 NO 买单映射的流动性仍然存在。`{"op":"cancel_all","id":"all-1","account":"alice"}` 覆盖 Alice 在所有市场的活跃单。匹配不到挂单时返回空列表;账户名称是模拟 CLI 参数,外场认证范围与错误文本仍待实测。单笔 cancel 保留原有回执。[官方撤单范围与回执](https://docs.polymarket.com/trading/manage-orders.md)
|
||||||
|
|||||||
Reference in New Issue
Block a user