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

# 订阅余额

订阅 `balances` 频道，以 `balance_response` 对象接收账户余额快照。系统每 60 秒定期发布快照，并在成交、入金、出金、资金费用、奖励及订单保证金变化后发送额外的事件驱动更新。

## 更新时机与初始快照

新订阅建立后，网关发送 `{"subscribed":"balances"}`，并立即将根据最新缓存账户状态生成的 `balance_response` 加入发送队列，无需等到下一次定期刷新。这是缓存快照，不是重新查询的余额；若网关尚未缓存余额，则在更新到达之前发送默认的零值余额。

下单或撤单导致预留订单保证金变化时会触发更新，包括 `order_margin` 和 `available_balance` 的变化。预留保证金更新按账户以约一秒的频率合并，其他账户事件可能更早触发快照。系统不保证每笔订单对应一条消息，且消息为异步投递。

60 秒是定期刷新间隔，并非最大投递延迟保证。每条消息均为余额快照，而不是增量。

## 1. 身份认证

连接 `wss://trade.qfex.com?api_key=YOUR_API_KEY` 后立即发送：

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

## 2. 订阅

```json theme={null}
{ "type": "subscribe", "params": { "channels": ["balances"] } }
```

## 示例代码

```python python theme={null}
# Python (websocket-client)
# pip install websocket-client
import json, 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) Subscribe to balances
    send(ws, {"type": "subscribe", "params": {"channels": ["balances"]}})

ws = websocket.WebSocketApp(
    "wss://trade.qfex.com?api_key=YOUR_API_KEY",
    on_open=on_open,
    on_message=lambda _, m: print("Message:", 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
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", () => {
  ws.send(JSON.stringify({ type: "auth", params: { api_key: API_KEY } }));
  ws.send(
    JSON.stringify({ type: "subscribe", params: { channels: ["balances"] } }),
  );
});

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

```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) Subscribe to balances
	mustWriteJSON(c, map[string]any{
		"type": "subscribe",
		"params": map[string]any{"channels": []string{"balances"}},
	})

	// Read messages (optional)
	for {
		_, data, err := c.ReadMessage()
		if err != nil { log.Fatal("read:", err) }
		log.Println(string(data))
	}
}
```

```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 BalancesSub {
  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\":\"subscribe\",\"params\":{\"channels\":[\"balances\"]}}");
      }
      @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) {}
  }
}
```

## 响应示例

```json theme={null}
{ "subscribed": "balances" }
```

```json theme={null}
{
  "balance_response": {
    "id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "user_id": "0020ce8e-eaee-480e-8d7f-b9241d756ee5",
    "deposit": 9990000000.0,
    "realised_pnl": 0.0,
    "order_margin": 0.0,
    "position_margin": 0.0,
    "unrealised_pnl": 0.0,
    "net_funding": 0.0,
    "available_balance": 9990000000.0,
    "referral_rewards": 0.0,
    "builder_rewards": 0.0,
    "fees": 0.0
  }
}
```

> [!NOTE]
>
> 初始、定期及事件驱动快照均使用 `balance_response`。旧版 `balance_update`／`v4_balances` 消息封装不适用于 `wss://trade.qfex.com`。


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