> ## 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** 修改订单。只有 **`price`**、**`quantity`**、**`take_profit`** 和 **`stop_loss`** 可以改变。

* **必须**指定订单的 **`order_id`**（UUID v4）。
* **必须**指定 **`symbol`**。
* **必须**指定 **`side`**。
* **必须**指定 **`order_type`**。
* **必须**指定与当前订单一致的 **`reduce_only`**。
* 不能使用 `client_order_id` 改单。

> [!NOTE]
>
> 软清算可以在没有客户端请求时，将挂单的 `reduce_only` 改为 `true`。应使用当前标志，而非最初提交的值。转换后发送 `false` 会以 `CANNOT_MODIFY_NO_SUCH_ORDER` 拒绝。自动转换保留订单 ID；下述 ID 替换只适用于客户端请求的改单。详情见[自动转换为只减仓](https://docs.qfex.com/cn/websocket/channels/trade/order.md#automatic-reduce-only-conversion)。

## 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": "modify_order",
  "params": {
    "order_id": "510333ac-3f7b-4d88-934a-4396d48824cc",
    "symbol": "AAPL-USD",
    "side": "BUY",
    "order_type": "LIMIT",
    "quantity": 2,
    "price": 200,
    "take_profit": 200,
    "stop_loss": 150,
    "reduce_only": false
  }
}
```

## 参数

| 字段 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `order_id` | string | 是 | 待修改订单的 UUID v4。 |
| `symbol` | string | 是 | 交易品种，例如 `AAPL-USD`。 |
| `side` | enum | 是 | 必须与原订单方向一致，见 [OrderDirection](https://docs.qfex.com/cn/api-reference/enums.md#orderdirection)。 |
| `order_type` | enum | 是 | 必须与原订单类型一致，见 [OrderType](https://docs.qfex.com/cn/api-reference/enums.md#ordertype)。 |
| `reduce_only` | bool | 是 | 必须与挂单当前的只减仓标志一致，改单不能改变此值。 |
| `quantity` | number | 可选 | 新数量，须满足该品种的数量增量及上下限要求。 |
| `price` | number | 可选 | 限价／ALO 订单的新价格；市价单忽略此值。须符合最小价格增量及价格区间。 |
| `take_profit` | number | 可选 | 更新后的止盈价格，不使用时设为 `0`。 |
| `stop_loss` | number | 可选 | 更新后的止损价格，不使用时设为 `0`。 |

注意：

* 只能修改 `price`、`quantity`、`take_profit` 和 `stop_loss`。
* 每次改单都必须提供 `reduce_only`。省略会以 `InvalidJSONFormat` 拒绝；与挂单当前值不一致则以 `CANNOT_MODIFY_NO_SUCH_ORDER` 拒绝。
* 不能使用 `client_order_id` 改单。
* **改单会改变 `order_id`。**响应包含一个**新的**订单 ID，并替换旧 ID，因为当前不支持多个同时在途的改单请求。
* 若修改会导致无效状态，例如数量小于已部分成交数量，会以 [OrderStatus](https://docs.qfex.com/cn/api-reference/enums.md#orderstatus) 中的 `CANNOT_MODIFY_PARTIAL_FILL`、`CANNOT_MODIFY_NO_SUCH_ORDER` 等状态拒绝。

## 示例代码

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

API_KEY = "YOUR_API_KEY"

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

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..." }}})
    # Modify order
    send(ws, {
        "type": "modify_order",
        "params": {
            "order_id": "510333ac-3f7b-4d88-934a-4396d48824cc",
            "symbol": "AAPL-USD",
            "side": "BUY",
            "order_type": "LIMIT",
            "quantity": 2,
            "price": 200,
            "take_profit": 200,
            "stop_loss": 150,
            "reduce_only": False
        }
    })

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

```javascript node theme={null}
// Node.js (ws)
import WebSocket from "ws";
const ws = new WebSocket("wss://trade.qfex.com?api_key=YOUR_API_KEY");
const API_KEY = "YOUR_API_KEY";

ws.on("open", () => {
  // Authenticate
  ws.send(JSON.stringify({ type: "auth", params: { api_key: API_KEY } }));
  // Modify order
  ws.send(
    JSON.stringify({
      type: "modify_order",
      params: {
        order_id: "510333ac-3f7b-4d88-934a-4396d48824cc",
        symbol: "AAPL-USD",
        side: "BUY",
        order_type: "LIMIT",
        quantity: 2,
        price: 200,
        take_profit: 200,
        stop_loss: 150,
        reduce_only: false,
      },
    })
  );
});

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

	// Modify order
	mustWriteJSON(c, map[string]any{
		"type": "modify_order",
		"params": map[string]any{
			"order_id":           "510333ac-3f7b-4d88-934a-4396d48824cc",
			"symbol":             "AAPL-USD",
			"side":               "BUY",
      "order_type":         "LIMIT",
			"quantity":           2,
			"price":              200,
			"take_profit":        200,
			"stop_loss":          150,
			"reduce_only":        false,
		},
	})
}
```

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

public class ModifyOrderWs {
  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) {
        // Authenticate
        ws.send("{\"type\": \"auth\", \"params\": { \"hmac\": { \"public_key\": \"qfex_pub_xxxxx\", \"nonce\": \"c0ffee...\..\", \"unix_ts\": 1760545414, \"signature\": \"5f2e...\" }}}");

        // Modify order
        ws.send("{\"type\":\"modify_order\",\"params\":{\"order_id\":\"510333ac-3f7b-4d88-934a-4396d48824cc\",\"symbol\":\"AAPL-USD\",\"side\":\"BUY\",\"order_type\":\"LIMIT\",\"original_quantity\":1,\"quantity\":2,\"price\":200,\"take_profit\":200,\"stop_loss\":150,\"reduce_only\":false}}");
      }
      @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) {}
  }
}
```

## 响应示例

改单成功时，返回与新增订单相同的 `order_response` 对象，但状态为 **`MODIFIED`**，并包含替换旧值的**新 `order_id`**。

```json theme={null}
{
  "order_response": {
    "order_id": "88888888-4444-4444-4444-1234567890ab",
    "symbol": "AAPL-USD",
    "status": "MODIFIED",
    "quantity": 2.0,
    "price": 200.0,
    "take_profit": 200.0,
    "stop_loss": 150.0,
    "side": "BUY",
    "type": "LIMIT",
    "time_in_force": "GTC",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "client_order_id": "",
    "quantity_remaining": 2.0,
    "trade_id": null
  }
}
```


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