nautechsystems/nautilus_trader · error

Cannot cancel Polymarket orders while a modification or canc

Error message

Cannot cancel Polymarket orders while a modification or cancellation is in flight

What it means

The execution client serializes cancellation flows with a CancelCommandGuard: only one modify/cancel operation may be in flight per client. cancel_all_orders_command acquires this guard; if a concurrent modification or cancellation is still in flight, acquiring the guard fails and the cancel-all command is rejected rather than racing with the in-flight operation.

Source

Thrown at crates/adapters/polymarket/src/execution/cancellations.rs:319

            log::debug!(
                "No cached {side:?} orders to cancel for instrument_id={}",
                cmd.instrument_id
            );
            return Ok(());
        }

        let cancel_guard = if side.is_none() {
            CancelCommandGuard::market(self.ws_dispatch_state.clone(), cmd.instrument_id)
        } else {
            let pending = open_orders
                .iter()
                .map(|order| (order.client_order_id(), order.instrument_id()))
                .collect::<Vec<_>>();
            CancelCommandGuard::available_orders(self.ws_dispatch_state.clone(), &pending)
        };

        let Some(cancel_guard) = cancel_guard else {
            anyhow::bail!(
                "Cannot cancel Polymarket orders while a modification or cancellation is in flight"
            );
        };

        let mut orders = Vec::new();

        for order in open_orders {
            if side.is_some()
                && !cancel_guard
                    .client_order_ids
                    .contains(&order.client_order_id())
            {
                continue;
            }

            if let Some(venue_order_id) = self.cancel_venue_order_id(&order) {
                orders.push((venue_order_id, order.clone()));
            } else {

View on GitHub (pinned to 18893faf8b)

Solutions

  1. Wait for the in-flight modify/cancel operation to complete before issuing cancel_all_orders, then retry.
  2. Serialize order management so risk-driven cancel-all and strategy order amendments don't run concurrently.
  3. Add retry-with-backoff around cancel_all_orders for this transient contention error.
  4. Check whether the in-flight modify is stuck (e.g. no WS response) and reset/reconnect the execution WebSocket if needed.

Example fix

// before
client.cancel_all_orders(command)?; // may fail while modify in flight

// after
match client.cancel_all_orders(command) {
    Ok(()) => {},
    Err(e) if is_cancel_guard_busy(&e) => {
        std::thread::sleep(Duration::from_millis(200));
        client.cancel_all_orders(command)?;
    }
    Err(e) => return Err(e),
}
Defensive patterns

Strategy: retry

Validate before calling

// Track in-flight modify/cancel operations in your strategy layer before issuing cancel-all
let busy = inflight_modifies.load(Ordering::SeqCst) > 0;
if busy { wait_for_quiescence()?; }

Try / catch

for attempt in 0..5 {
    match client.cancel_all_orders(cmd.clone()) {
        Ok(()) => break,
        Err(e) if e.to_string().contains("in flight") => {
            std::thread::sleep(Duration::from_millis(200 * (attempt + 1)));
        }
        Err(e) => return Err(e),
    }
}

Prevention

When it happens

Trigger: Calling cancel_all_orders (via cancel_all_orders_command) while another order modification or cancellation request is currently in flight, so no CancelCommandGuard is available for the pending orders.

Common situations: Risk/kill-switch logic issuing cancel-all from a separate thread or event handler while the strategy is concurrently amending orders; rapid-fire cancel-all calls without waiting for the previous one to complete; WebSocket in-flight modify requests overlapping a market-wide flatten.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08). Data as JSON: /api/errors/300a7603d5ab5c41. Report an issue: GitHub.