> ## 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** 平仓。此命令指示引擎在当前持仓的**相反方向**提交 `LIMIT IOC` 订单，并将价格设在标记价格附近，以尽可能完成全部平仓。引擎自动将委托数量设置为当前未平仓数量，即始终以全部持仓为平仓目标；实际未成交部分按下文 IOC 规则取消。

* **接口：**`wss://trade.qfex.com?api_key=YOUR_API_KEY`。
* **连接后必须在 1 分钟内完成身份认证。**

## 1. 身份认证

连接后立即发送：

```json theme={null}
{ "type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." } } }
```

## 2. 平仓

```json theme={null}
{
  "type": "close_position",
  "params": {
    "symbol": "AAPL-USD"
  }
}
```

## 参数

| 字段 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `symbol` | string | 是 | 希望平仓的交易品种，例如 `AAPL-USD`。 |

注意：

* 生成的订单始终为 `LIMIT` 加 `IOC`、只减仓，并采用正确的平仓方向。
* 订阅 [`fills`](https://docs.qfex.com/cn/websocket/channels/trade/fills) 接收成交。
* 订阅 [`order_responses`](https://docs.qfex.com/cn/websocket/channels/trade/order) 接收最终状态更新。

## 示例代码

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

API_KEY = "YOUR_API_KEY"


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


def on_open(ws):
    # 1) 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..." }}})

    # 2) Close position
    send(ws, {
        "type": "close_position",
        "params": {
            "symbol": "AAPL-USD",
        },
    })


ws = websocket.WebSocketApp(
    "wss://trade.qfex.com?api_key=YOUR_API_KEY",
    on_open=on_open,
    on_message=lambda _, m: print(m),
    on_error=lambda _, e: print("Error:", e),
    on_close=lambda *_: print("Closed"),
)
ws.run_forever()
```

```javascript node theme={null}
// Node.js (ws)
// npm i ws
const WebSocket = require("ws");

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

ws.on("open", () => {
  // 1) Authenticate
  ws.send(JSON.stringify({ type: "auth", params: { api_key: API_KEY } }));

  // 2) Close position
  ws.send(
    JSON.stringify({
      type: "close_position",
      params: {
        symbol: "AAPL-USD",
      },
    })
  );
});

ws.on("message", (m) => console.log(m.toString()));
ws.on("error", (e) => console.error("WS error:", e));
ws.on("close", (code, reason) =>
  console.log("Closed:", code, reason?.toString())
);
```

```go go theme={null}
// Go (gorilla/websocket)
// go get github.com/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()

	// 1) 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..."}}
	})

	// 2) Close position
	mustWriteJSON(c, map[string]any{
		"type": "close_position",
		"params": map[string]any{
			"symbol": "AAPL-USD",
		},
	})
}
```

```java java theme={null}
// Java (OkHttp WebSocket)
// Gradle: implementation("com.squareup.okhttp3:okhttp:4.12.0")
import java.util.concurrent.TimeUnit;
import okhttp3.*;

public class ClosePositionWs {
  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=YOUR_API_KEY")
        .build();

    WebSocketListener li = new WebSocketListener() {
      @Override public void onOpen(WebSocket ws, Response r) {
        // 1) Authenticate
        ws.send("{\"type\": \"auth\", \"params\": { \"hmac\": { \"public_key\": \"qfex_pub_xxxxx\", \"nonce\": \"c0ffee...\..\", \"unix_ts\": 1760545414, \"signature\": \"5f2e...\" }}}");

        // 2) Close position
        ws.send("{\"type\":\"close_position\",\"params\":{\"symbol\":\"AAPL-USD\"}}");
      }

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

      @Override public void onFailure(WebSocket ws, Throwable t, Response r) {
        System.err.println("WS error: " + t.getMessage());
      }
    };

    client.newWebSocket(req, li);

    try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {}
  }
}
```

## 响应示例

首先立即收到 `order_response` 确认；若有成交，随后收到成交更新。

```json theme={null}
{
  "order_response": {
    "order_id": "5b309929-206f-40ec-804d-cbe46e81afc1",
    "symbol": "AAPL-USD",
    "status": "ACK",
    "quantity": 2.0,
    "price": 199.8,
    "take_profit": 0.0,
    "stop_loss": 0.0,
    "side": "SELL",
    "type": "LIMIT",
    "time_in_force": "IOC",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "client_order_id": "",
    "quantity_remaining": 2.0
  }
}
```

```json theme={null}
{
  "order_response": {
    "order_id": "5b309929-206f-40ec-804d-cbe46e81afc1",
    "symbol": "AAPL-USD",
    "status": "FILLED",
    "quantity": 2.0,
    "price": 199.75,
    "take_profit": 0.0,
    "stop_loss": 0.0,
    "side": "SELL",
    "type": "LIMIT",
    "time_in_force": "IOC",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "client_order_id": "",
    "quantity_remaining": 0.0
  }
}
```

> [!NOTE]
>
> 引擎始终使用 `IOC`，因此未成交的剩余数量会自动取消。若该品种没有未平仓头寸，命令会被拒绝。


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