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

# 资金费率

QFEX 提供各品种**当前资金费率数据流**，其数值代表假设资金费用窗口**立即结束**时的费率。每个窗口结束后，最终费率用于计算**资金费用支付金额**。推送值为缩放后的最终费率：$F_{\text{final}} = F_{\text{raw}} / 100$。

> [!NOTE]
>
> 资金费用仅在各品种配置的市场时段内生效；时段之外费率为 `0`。详情见[资金费率](https://docs.qfex.com/cn/qfex/funding.md)。

## 使用方式

连接公开 WebSocket：

* URL：`wss://mds.qfex.com`。

然后发送订阅消息：

```json theme={null}
{
  "type": "subscribe",
  "channels": ["funding"],
  "symbols": ["AAPL-USD", "US500-USD"]
}
```

## 示例代码

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

def on_open(ws):
    sub = {
        "type": "subscribe",
        "channels": ["funding"],
        "symbols": ["US500-USD"]  # or ["*"]
    }
    ws.send(json.dumps(sub))

def on_message(ws, message):
    data = json.loads(message)
    print("Funding update:", json.dumps(data, indent=2))

def on_error(ws, error):
    print("Error:", error)

def on_close(ws, close_status_code, close_msg):
    print("Closed:", close_status_code, close_msg)

if __name__ == "__main__":
    ws = websocket.WebSocketApp(
        "wss://mds.qfex.com",
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close,
    )
    ws.run_forever()
```

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

const ws = new WebSocket("wss://mds.qfex.com");

ws.on("open", () => {
  const sub = {
    type: "subscribe",
    channels: ["funding"],
    symbols: ["US500-USD"], // or ["*"]
  };
  ws.send(JSON.stringify(sub));
});

ws.on("message", (msg) => {
  try {
    const data = JSON.parse(msg.toString());
    console.log("Funding update:", data);
  } catch (e) {
    console.error("Parse error:", e);
  }
});

ws.on("error", (err) => console.error("WS error:", err));
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 (
	"fmt"
	"log"
	"os"
	"os/signal"

	"github.com/gorilla/websocket"
)

func main() {
	c, _, err := websocket.DefaultDialer.Dial("wss://mds.qfex.com", nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	sub := map[string]interface{}{
		"type":     "subscribe",
		"channels": []string{"funding"},
		"symbols":  []string{"US500-USD"}, // or []string{"*"}
	}
	if err := c.WriteJSON(sub); err != nil {
		log.Fatal("write:", err)
	}

	done := make(chan struct{})
	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			fmt.Printf("Funding update: %s\n", message)
		}
	}()

	// keep running until Ctrl+C
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	<-interrupt
}
```

```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 FundingWs {
  public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient.Builder()
        .pingInterval(20, TimeUnit.SECONDS)
        .build();

    Request request = new Request.Builder()
        .url("wss://mds.qfex.com")
        .build();

    WebSocketListener listener = new WebSocketListener() {
      @Override public void onOpen(WebSocket webSocket, Response response) {
        String sub = "{\"type\":\"subscribe\",\"channels\":[\"funding\"],\"symbols\":[\"US500-USD\"]}";
        webSocket.send(sub);
      }
      @Override public void onMessage(WebSocket webSocket, String text) {
        System.out.println("Funding update: " + text);
      }
      @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        System.err.println("WS error: " + t.getMessage());
      }
    };

    client.newWebSocket(request, listener);

    // Keep JVM alive
    try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignored) {}
  }
}
```

## 响应示例

```json theme={null}
{
  "type": "funding",
  "sequence": 50,
  "time": "2014-11-07T08:19:27.028459Z",
  "symbol": "AAPL-USD",
  "time_remaining": 30,
  "funding_rate": "0.021"
}
```

### 取消订阅（可选）

```json theme={null}
{ "type": "unsubscribe", "channels": ["funding"], "symbols": ["US500-USD"] }
```

## 注意事项

* 数值表示假设窗口立即结束时的**当前隐含资金费率**。
* 在资金费用计算窗口内定时推送。
* 品种市场时段以外，资金费率为 `0`。


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