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

# Subscribe — Balances

Subscribe to the `balances` channel to receive account balance snapshots in a
`balance_response` object. Periodic snapshots are published every 60 seconds,
with additional event-driven updates after trades, deposits, withdrawals,
funding, rewards, and order-margin changes.

## Update timing and initial snapshot

After a new subscription, the gateway sends `{"subscribed":"balances"}` and
immediately queues a `balance_response` from its latest cached account state.
You do not wait for the next periodic refresh. This is a cached snapshot, not a
fresh balance query; if the gateway has no cached balance yet, it sends a
default zero-valued balance until an update arrives.

Placing or cancelling an order triggers an update when it changes reserved
order margin, including changes to `order_margin` and `available_balance`.
Reservation updates are coalesced per account on an approximately one-second
cadence. Other account events can trigger an earlier snapshot. There is no
one-message-per-order guarantee, and delivery is asynchronous.

The 60-second interval is the periodic refresh cadence, not a maximum delivery
latency guarantee. Every message contains a balance snapshot, not a delta.

## 1) Authenticate

Send this immediately after connecting to `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) Subscribe

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

## Sample Code

```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) {}
  }
}
```

## Example Responses

```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]
>
> Initial, periodic, and event-driven snapshots all use `balance_response`.
> The legacy `balance_update` / `v4_balances` envelope does not apply to
> `wss://trade.qfex.com`.


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