> ## 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.

# 订单提交——TWAP 分笔下单

通过 **WebSocket** 提交 TWAP（时间加权平均）分笔订单。

* **接口：**`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. 新增 TWAP

```json theme={null}
{
  "type": "add_twap",
  "params": {
    "symbol": "AAPL-USD",
    "side": "BUY",
    "total_quantity": 10,
    "num_orders": 5,
    "order_interval_secs": 30,
    "reduce_only": false,
    "client_twap_id": "rebalance-aapl-001",
    "start_time": 1785499200.25,
    "worst_price": 250
  }
}
```

## 参数

| 字段 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `symbol` | string | 是 | 交易品种，例如 `AAPL-USD`。 |
| `side` | enum | 是 | TWAP 方向，见 [OrderDirection](https://docs.qfex.com/cn/api-reference/enums.md#orderdirection)。 |
| `total_quantity` | number | 是 | 整个 TWAP 的总目标成交数量，按品种的最小子订单数量要求校验。 |
| `num_orders` | number | 是 | 引擎计划提交的子订单数。 |
| `order_interval_secs` | number | 是 | 子订单之间的间隔秒数。 |
| `reduce_only` | bool | 是 | 为 `true` 时，TWAP 只能减少现有持仓。 |
| `client_twap_id` | string | 可选 | 客户端指定的 TWAP 标识符，用于跟踪及取消。 |
| `start_time` | number | 可选 | 首个子订单最早提交的 Unix 秒时间戳，可含小数。省略或早于当前时间时立即开始。 |
| `worst_price` | number | 可选 | 每个子订单使用的准确 IOC 限价，即买单最高成交价或卖单最低成交价。省略时根据标记价格计算。 |

注意：

* 通过向 `trade.qfex.com` 发送 `add_twap` 入站消息提交 TWAP。
* 成功的 TWAP 以 `twap_response` 返回，也出现在 `all_orders_response.twaps` 中。
* 可使用 `cancel_order` 取消，并将 `cancel_order_id_type` 设置为 `twap_id` 或 `client_twap_id`。
* 账户须满足与普通下单相同的条款接受要求。

## 校验规则

服务器将请求转发给 TWAP 服务前，会校验 `add_twap`：

| 规则 | 行为 |
| - | - |
| 品种必须有效 | 无效或未知品种会被拒绝。 |
| `order_interval_secs >= 30` | 最小间隔为 **30 秒**。 |
| `num_orders >= 2` | TWAP 至少包含 **2 个子订单**。 |
| `total_quantity / num_orders >= min_quantity` | 平均子订单数量不得低于品种的 `min_quantity`。 |
| `client_twap_id` 长度 | 提供时，须满足与 `client_order_id` 相同的已配置长度上下限。 |
| `start_time` 格式 | 提供时，必须为 protobuf 支持时间戳范围内的有限 Unix 秒数。过去的时间戳按当前时间处理。 |
| `worst_price` 价格边界 | 提供时，必须为允许区间内的有限值：买单不得超过品种最高价；卖单不得低于品种最低价，也不得高于平台最高价。 |
| `worst_price` 价格增量 | 提供时，须与品种的 `tick_size` 对齐。 |

补充实现说明：

* 校验前，`total_quantity` 会按品种数量精度缩放。
* 本页描述的当前校验**没有**明确要求 `total_quantity` 必须对齐 `lot_size`，只要求平均子订单数量不低于 `min_quantity`。
* 本地校验错误以 `err` 返回，包含 `error_code: "invalid_parameter"` 和说明性的 `message`。

## 示例代码

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

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

def on_open(ws):
    send(ws, {"type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." }}})
    send(ws, {
        "type": "add_twap",
        "params": {
            "symbol": "AAPL-USD",
            "side": "BUY",
            "total_quantity": 10,
            "num_orders": 5,
            "order_interval_secs": 30,
            "reduce_only": False,
            "client_twap_id": "rebalance-aapl-001",
            "start_time": 1785499200.25,
            "worst_price": 250
        }
    })

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

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

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

ws.on("open", () => {
  ws.send(JSON.stringify({
    type: "auth",
    params: {
      hmac: {
        public_key: "qfex_pub_xxxxx",
        nonce: "c0ffee...",
        unix_ts: 1760545414,
        signature: "5f2e...",
      },
    },
  }));

  ws.send(JSON.stringify({
    type: "add_twap",
    params: {
      symbol: "AAPL-USD",
      side: "BUY",
      total_quantity: 10,
      num_orders: 5,
      order_interval_secs: 30,
      reduce_only: false,
      client_twap_id: "rebalance-aapl-001",
      start_time: 1785499200.25,
      worst_price: 250,
    },
  }));
});

ws.on("message", (m) => console.log(m.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()

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

	mustWriteJSON(c, map[string]any{
		"type": "add_twap",
		"params": map[string]any{
			"symbol":              "AAPL-USD",
			"side":                "BUY",
			"total_quantity":      10,
			"num_orders":          5,
			"order_interval_secs": 30,
			"reduce_only":         false,
			"client_twap_id":      "rebalance-aapl-001",
			"start_time":          1785499200.25,
			"worst_price":         250,
		},
	})
}
```

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

public class AddTwapWs {
  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) {
        ws.send("{\"type\":\"auth\",\"params\":{\"hmac\":{\"public_key\":\"qfex_pub_xxxxx\",\"nonce\":\"c0ffee...\",\"unix_ts\":1760545414,\"signature\":\"5f2e...\"}}}");
        ws.send("{\"type\":\"add_twap\",\"params\":{\"symbol\":\"AAPL-USD\",\"side\":\"BUY\",\"total_quantity\":10,\"num_orders\":5,\"order_interval_secs\":30,\"reduce_only\":false,\"client_twap_id\":\"rebalance-aapl-001\",\"start_time\":1785499200.25,\"worst_price\":250}}");
      }

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

    client.newWebSocket(req, li);
    try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {}
  }
}
```

## TWAP 响应结构

成功的 TWAP 请求以 `twap_response` 对象返回：

```json theme={null}
{
  "twap_response": {
    "twap_id": "0c7c8e4d-f67e-4aa5-9c64-36a1a622ac35",
    "client_twap_id": "rebalance-aapl-001",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "status": "ENGINE_STATUS",
    "symbol": "AAPL-USD",
    "total_quantity": 10,
    "filled_quantity": 0,
    "average_fill_price": 0,
    "worst_price": 250,
    "total_num_orders": 5,
    "order_interval_secs": 30,
    "reduce_only": false,
    "side": "BUY",
    "start_time": 1785499200.25,
    "updated_at": 1760545414.123,
    "created_at": 1760545414.123
  }
}
```

| 字段 | 类型 | 说明 |
| - | - | - |
| `twap_id` | string | 服务器生成的 TWAP 标识符。 |
| `client_twap_id` | string 或 null | 可选的客户端 TWAP 标识符。 |
| `user_id` | string | TWAP 所有者的账户标识符。 |
| `status` | string | 当前 TWAP 引擎状态。 |
| `symbol` | string | 交易品种。 |
| `total_quantity` | number | 整个 TWAP 请求的总数量。 |
| `filled_quantity` | number | 已成交数量。 |
| `average_fill_price` | number | 截至当前全部成交的平均价格。 |
| `worst_price` | number 或 null | 为每个子订单配置的 IOC 限价；根据标记价格计算限价时为 `null`。 |
| `total_num_orders` | number | 计划提交的子订单总数。 |
| `order_interval_secs` | number | 子订单之间的间隔秒数。 |
| `reduce_only` | bool | TWAP 是否为只减仓。 |
| `side` | enum | TWAP 方向。 |
| `start_time` | number 或 null | 实际计划开始时间，以可含小数的 Unix 秒表示；请求省略或提供过去时间时，返回 TWAP 被接受的时间。 |
| `updated_at` | number 或 null | 最后更新时间戳，单位为秒，可含小数。 |
| `created_at` | number 或 null | 创建时间戳，单位为秒，可含小数。 |


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