> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qfex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 断线撤单

为 WebSocket 会话启用断线撤单，可在连接意外断开时，让交易引擎取消该账户的**全部未完成订单**，而不仅是通过当前连接提交的订单。此标志只适用于单条连接，每次重连后都必须重新启用。

在需要保护的连接上完成认证后，立即发送 `cancel_on_disconnect` 消息，并将 `cancel_on_disconnect` 设为 `true`。

## 请求示例

```json theme={null}
{
  "type": "cancel_on_disconnect",
  "params": { "cancel_on_disconnect": true }
}
```

## 示例代码

```python python theme={null}
# Python (websocket-client)
import json
import websocket

API_KEY = "YOUR_API_KEY"


def send(ws, payload):
    ws.send(json.dumps(payload))


def on_open(ws):
    # Authenticate
    # https://docs.qfex.com/websocket/channels/trade/authenticate#how-it-works
    send(ws, {"type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." }}})
    # Enable cancel-on-disconnect for this connection
    send(ws, {"type": "cancel_on_disconnect", "params": {"cancel_on_disconnect": True}})


ws = websocket.WebSocketApp(
    "wss://trade.qfex.com?api_key=YOUR_API_KEY",
    on_open=on_open,
    on_message=lambda _, message: print("Message:", message),
)
ws.run_forever()
```

```javascript node theme={null}
// Node.js (ws)
import WebSocket from "ws";

const API_KEY = "YOUR_API_KEY";
const ws = new WebSocket("wss://trade.qfex.com?api_key=YOUR_API_KEY");

ws.on("open", () => {
  // Authenticate
  ws.send(JSON.stringify({ type: "auth", params: { api_key: API_KEY } }));
  // Enable cancel-on-disconnect for this connection
  ws.send(
    JSON.stringify({
      type: "cancel_on_disconnect",
      params: { cancel_on_disconnect: true },
    })
  );
});

ws.on("message", (msg) => console.log("Message:", msg.toString()));
```

```go go theme={null}
// Go (gorilla/websocket)
package main

import (
    "log"

    "github.com/gorilla/websocket"
)

func mustWriteJSON(c *websocket.Conn, v any) {
    if err := c.WriteJSON(v); err != nil {
        log.Fatal("write:", err)
    }
}

func main() {
    c, _, err := websocket.DefaultDialer.Dial("wss://trade.qfex.com?api_key=YOUR_API_KEY", nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    defer c.Close()

    // Authenticate
    mustWriteJSON(c, map[string]any{
        "type":   "auth",
        "params": map[string]any{"hmac": map[string]any{"public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..."}}
    })

    // Enable cancel-on-disconnect for this connection
    mustWriteJSON(c, map[string]any{
        "type":   "cancel_on_disconnect",
        "params": map[string]any{"cancel_on_disconnect": true},
    })
}
```

```java java theme={null}
// Java (OkHttp WebSocket)
import java.util.concurrent.TimeUnit;
import okhttp3.*;

public class CancelAllOrdersWs {
  private static final String API_KEY = "YOUR_API_KEY";

  public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient.Builder()
        .pingInterval(20, TimeUnit.SECONDS)
        .build();

    Request req = new Request.Builder()
        .url("wss://trade.qfex.com?api_key=" + API_KEY)
        .build();

    WebSocketListener listener = new WebSocketListener() {
      @Override public void onOpen(WebSocket ws, Response response) {
        // Authenticate
        ws.send("{\"type\":\"auth\",\"params\":{\"api_key\":\"" + API_KEY + "\"}}");
        // Enable cancel-on-disconnect for this connection
        ws.send("{\"type\":\"cancel_on_disconnect\",\"params\":{\"cancel_on_disconnect\":true}}");
      }

      @Override public void onMessage(WebSocket ws, String text) {
        System.out.println(text);
      }
    };

    client.newWebSocket(req, listener);
    try {
      Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
```

## 响应示例

通过此标志执行撤单时，每笔订单会产生状态为 `CANCELLED` 的 **`order_response`** 事件。

```json theme={null}
{
  "order_response": {
    "order_id": "5b309929-206f-40ec-804d-cbe46e81afc1",
    "symbol": "AAPL-USD",
    "status": "CANCELLED",
    "quantity": 1.0,
    "price": 200.0,
    "side": "BUY",
    "type": "LIMIT",
    "time_in_force": "GTC",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "client_order_id": "my-client-oid",
    "quantity_remaining": 1.0,
    "trade_id": null
  }
}
```

> [!NOTE]
>
> 断线撤单的作用范围是已认证账户在**所有品种上的全部未完成订单**。如只需取消指定订单，请使用[取消订单](https://docs.qfex.com/cn/websocket/channels/trade/cancel_order.md)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.