> ## 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** 提交订单。

* **接口：**`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": "add_order",
  "params": {
    "symbol": "AAPL-USD",
    "side": "BUY",
    "order_type": "LIMIT",
    "order_time_in_force": "GTC",
    "quantity": 1,
    "price": 200,
    "take_profit": 0,
    "stop_loss": 0,
    "reduce_only": 0
  }
}
```

## 参数

| 字段 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `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)。 |
| `order_time_in_force` | enum | 是 | 有效期规则，见 [OrderTimeInForce](https://docs.qfex.com/cn/api-reference/enums.md#ordertimeinforce)。 |
| `quantity` | number | 是 | 订单数量，须符合最小数量增量及最小／最大限额，详见参考数据。 |
| `price` | number | 限价／ALO 订单必填 | 限价或 ALO 订单价格；市价单忽略此值。须符合最小价格增量及价格区间。 |
| `take_profit` | number | 可选 | 止盈价格；不使用时设为 `0`。 |
| `stop_loss` | number | 可选 | 止损价格；不使用时设为 `0`。 |
| `client_order_id` | string | 可选 | 客户端指定的订单跟踪 ID；为空时自动生成。 |

> [!WARNING]
>
> `LIMIT` 和 `ALO` 订单必须提供 `price`，`MARKET` 则忽略该值。最小价格增量、最小数量增量及订单数量上下限因品种而异，请查询参考数据 API。参数无效时，订单可能以 [OrderStatus](https://docs.qfex.com/cn/api-reference/enums.md#orderstatus) 中的状态码被拒绝。

## 示例代码

```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) Sub to order responses
    # https://docs.qfex.com/websocket/channels/trade/order
    send(ws, {"type": "subscribe", "params": {"channels": ["order_responses"]}})
    # 3) Add order
    send(ws, {
        "type": "add_order",
        "params": {
            "symbol": "AAPL-USD",
            "side": "BUY",
            "order_type": "LIMIT",
            "order_time_in_force": "GTC",
            "quantity": 1,
            "price": 200,
            "take_profit": 0,   # Optional
            "stop_loss": 0,     # Optional
            "resuce_only": True # Optional
        }
    })

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 ws = new WebSocket("wss://trade.qfex.com?api_key=YOUR_API_KEY");

ws.on("open", () => {
  // 1) Authenticate
  // https://docs.qfex.com/websocket/channels/trade/authenticate#how-it-works
  ws.send(JSON.stringify({"type": "auth", "params": { "hmac": { "public_key": "qfex_pub_xxxxx", "nonce": "c0ffee...", "unix_ts": 1760545414, "signature": "5f2e..." }}}));
  // 2) Sub to order responses
  // https://docs.qfex.com/websocket/channels/trade/order
  ws.send(
      JSON.stringify({
        type: "subscribe",
        params: { channels: ["order_responses"] },
      })
    );
  });
  // 3) Add order
  ws.send(JSON.stringify({
    type: "add_order",
    params: {
      symbol: "AAPL-USD",
      side: "BUY",
      order_type: "LIMIT",
      order_time_in_force: "GTC",
      quantity: 1,
      price: 200,
      take_profit: 0,   // Optional
      stop_loss: 0,      // Optional
      reduce_only: true  // Optional
    }
  }));
});

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) Sub to order responses
  // https://docs.qfex.com/websocket/channels/trade/order
  mustWriteJSON(c, map[string]any{
		"type": "subscribe",
		"params": map[string]any{"channels": []string{"order_responses"}},
	})

  // 3) Add order
	mustWriteJSON(c, map[string]any{
		"type": "add_order",
		"params": map[string]any{
			"symbol":              "AAPL-USD",
			"side":                "BUY",
			"order_type":          "LIMIT",
			"order_time_in_force": "GTC",
			"quantity":            1,
			"price":               200,
			"take_profit":         0,     // Optional
			"stop_loss":           0,    // Optional
			"reduce_only":         true, // Optional
		},
	})
}
```

```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 AddOrderWs {
  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) Sub to order responses
        // https://docs.qfex.com/websocket/channels/trade/order
        ws.send("{\"type\":\"subscribe\",\"params\":{\"channels\":[\"order_responses\"]}}");
        // 3) Add order
        ws.send("{\"type\":\"add_order\",\"params\":{\"symbol\":\"AAPL-USD\",\"side\":\"BUY\",\"order_type\":\"LIMIT\",\"order_time_in_force\":\"GFD\",\"quantity\":1,\"price\":200,\"take_profit\":0,\"stop_loss\":0}}");
      }
      @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) {}
  }
}
```

## 响应示例

下单后会收到状态为 `ACK` 的 `order_response`：

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


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