Cancel account orders by ID batch, market or outcome asset

This commit is contained in:
2026-12-03 04:23:08 +08:00
parent 67426ae617
commit c27bb60fd2
8 changed files with 221 additions and 2 deletions
+18
View File
@@ -35,6 +35,8 @@ flowchart LR
expiry -->|到期封盘并释放订单预留| market
twap -->|保存定点价格与证据| schema
res -->|规则与裁决状态| schema
market -->|批量、市场或账户撤单| cancellation["src/cancellation.rs"]
cancellation -->|释放订单未成交的预留| book
market -->|匹配命令类型| cmd
market -->|检查数量、标识和市场阶段| valid
market -->|下单、撤单与开盘| book["src/book.rs"]
@@ -250,3 +252,19 @@ sequenceDiagram
E->>D: 比较两个端点,校验抵押并记录结果
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
```
+9 -1
View File
@@ -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<()> {
if !matches!(
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(());
}
+73
View File
@@ -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":{}}))
}
+15
View File
@@ -50,6 +50,21 @@ pub(crate) enum Command {
account: String,
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 {
market: String,
},
+1
View File
@@ -7,6 +7,7 @@ mod twap;
mod validation;
use validation::identifier;
mod book;
mod cancellation;
mod command;
mod ledger;
mod market;
+9
View File
@@ -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)?;
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 } => {
phase(tx, &market, &["preopen"])?;
// Run one auction. Using the earliest order's outcome as the quote unit
+89
View File
@@ -1000,3 +1000,92 @@ fn twap_market_closes_before_settlement_and_reuses_exact_observations() {
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":{}}));
}