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
+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":{}}))
}