跳到主要内容

快速入门 — 5 分钟完成您的第一笔交易

本指南将引导您完成完整的集成流程:获取公开市场数据、身份验证、在测试网下单,以及通过 WebSocket 订阅实时更新。


前提条件

请先使用测试网

以下所有示例均针对测试网,这样您可以在不承担真实资金风险的情况下进行实验。准备好后再切换到生产环境 URL。

ProductProductionTestnet
Spot RESThttps://api.btse.com/spothttps://testapi.btse.io/spot
Spot WebSocketwss://ws.btse.com/ws/spotwss://testws.btse.io/ws/spot

第 1 步 — 获取公开市场数据(无需身份验证)

获取所有可交易的现货市场列表,找到您想交易的交易对。

接口: GET /public-api/market/v1/markets

无需请求头。返回每个市场的价格、成交量和交易对配置信息。

参见市场信息了解完整的字段说明。

example
GET/public-api/market/v1/markets

Python

import requests

resp = requests.get("https://testapi.btse.io/public-api/market/v1/markets")
symbols = resp.json()["data"]["symbols"]

# Find BTC-USDT
btc = next(s for s in symbols if s["symbol"] == "BTC-USDT")
print(f"BTC-USDT minOrderSize: {btc['minOrderSize']}, active: {btc['active']}")

Node.js

const resp = await fetch(
"https://testapi.btse.io/public-api/market/v1/markets"
);
const { data } = await resp.json();

const btc = data.symbols.find((s) => s.symbol === "BTC-USDT");
console.log(`BTC-USDT minOrderSize: ${btc.minOrderSize}, active: ${btc.active}`);

curl

curl https://testapi.btse.io/public-api/market/v1/markets?symbol=BTC-USDT

第 2 步 — 签署已认证的请求

私有接口需要三个请求头。签名算法为 HMAC-SHA384(secret, path + nonce + body)

参见身份验证了解完整规范。

每个私有请求所需的请求头:

请求头
request-api您的 API key
request-nonce当前 UTC 时间戳(毫秒)
request-signHMAC-SHA384 签名

签名输入 = urlPath + nonce + bodyString

  • 对于 GET 请求,bodyString 为空字符串 ""
  • 对于 POST/PUT/DELETE 请求,bodyString 为原始 JSON 请求体
example

Python — 签名辅助函数

import hmac, hashlib, time, json, requests

API_KEY = "your-api-key"
API_SECRET = "your-api-secret"
BASE_URL = "https://testapi.btse.io/spot"

def signed_request(method, path, body=None):
nonce = str(int(time.time() * 1000))
body_str = json.dumps(body) if body else ""
message = path + nonce + body_str
signature = hmac.new(
API_SECRET.encode(), message.encode(), hashlib.sha384
).hexdigest()

headers = {
"request-api": API_KEY,
"request-nonce": nonce,
"request-sign": signature,
"Content-Type": "application/json",
}
url = BASE_URL + path
if method == "GET":
return requests.get(url, headers=headers)
elif method == "POST":
return requests.post(url, headers=headers, json=body)
elif method == "DELETE":
return requests.delete(url, headers=headers)

Node.js — 签名辅助函数

import crypto from "crypto";

const API_KEY = "your-api-key";
const API_SECRET = "your-api-secret";
const BASE_URL = "https://testapi.btse.io/spot";

async function signedRequest(method, path, body) {
const nonce = Date.now().toString();
const bodyStr = body ? JSON.stringify(body) : "";
const message = path + nonce + bodyStr;
const signature = crypto
.createHmac("sha384", API_SECRET)
.update(message)
.digest("hex");

const headers = {
"request-api": API_KEY,
"request-nonce": nonce,
"request-sign": signature,
"Content-Type": "application/json",
};

const resp = await fetch(BASE_URL + path, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
return resp.json();
}

第 3 步 — 下一笔测试订单

在测试网上下一笔 BTC-USD 的限价买单。

接口: POST /api/v3.3/order

所需权限: 交易

成功时响应中包含 status: 2(ORDER_INSERTED)。参见错误代码 → API 状态枚举了解所有状态码。

参见创建新订单了解完整的字段说明。

example
POST/api/v3.3/order

Python

order = {
"symbol": "BTC-USD",
"side": "BUY",
"type": "LIMIT",
"price": 20000,
"size": 0.001,
"time_in_force": "GTC",
}

resp = signed_request("POST", "/api/v3.3/order", order)
result = resp.json()
print(f"Order ID: {result[0]['orderID']}, status: {result[0]['status']}")

Node.js

const order = {
symbol: "BTC-USD",
side: "BUY",
type: "LIMIT",
price: 20000,
size: 0.001,
time_in_force: "GTC",
};

const result = await signedRequest("POST", "/api/v3.3/order", order);
console.log(`Order ID: ${result[0].orderID}, status: ${result[0].status}`);

Response

[
{
"status": 2,
"symbol": "BTC-USD",
"orderType": 76,
"price": 20000.0,
"side": "BUY",
"size": 0.001,
"orderID": "990db9b6-2ed4-4c68-b46e-827c88cc3884",
"timestamp": 1660208800123,
"triggerPrice": 0.0,
"trigger": false,
"averageFillPrice": 0.0,
"fillSize": 0.0,
"postOnly": false,
"remainingSize": 0.001,
"time_in_force": "GTC"
}
]

第 4 步 — 通过 WebSocket 订阅实时更新

打开 WebSocket 连接以接收实时订单更新和成交通知。

连接流程:

  1. 连接到 wss://testws.btse.io/ws/spot
  2. 每 15 秒发送 ping 以保持连接(服务器响应 pong
  3. 使用 authKeyExpires 进行身份验证以访问私有主题
  4. 订阅主题:notificationApiV3(订单更新)、fills(成交通知)

WebSocket 身份验证签名:

HMAC-SHA384(secret, "/ws/spot" + nonce)

参见 WebSocket 身份验证了解详情。

example

Python(使用 websockets 库)

import asyncio, websockets, json, hmac, hashlib, time

WS_URL = "wss://testws.btse.io/ws/spot"
API_KEY = "your-api-key"
API_SECRET = "your-api-secret"

async def main():
async with websockets.connect(WS_URL) as ws:
# 1. Authenticate
nonce = str(int(time.time() * 1000))
sig = hmac.new(
API_SECRET.encode(),
f"/ws/spot{nonce}".encode(),
hashlib.sha384,
).hexdigest()

await ws.send(json.dumps({
"op": "authKeyExpires",
"args": [API_KEY, nonce, sig],
}))

# 2. Subscribe to order notifications
await ws.send(json.dumps({
"op": "subscribe",
"args": ["notificationApiV3"],
}))

# 3. Listen for messages
async for msg in ws:
if msg == "pong":
continue
data = json.loads(msg)
print(json.dumps(data, indent=2))

asyncio.run(main())

Node.js(使用 ws 库)

import WebSocket from "ws";
import crypto from "crypto";

const WS_URL = "wss://testws.btse.io/ws/spot";
const API_KEY = "your-api-key";
const API_SECRET = "your-api-secret";

const ws = new WebSocket(WS_URL);

ws.on("open", () => {
// 1. Authenticate
const nonce = Date.now().toString();
const sig = crypto
.createHmac("sha384", API_SECRET)
.update("/ws/spot" + nonce)
.digest("hex");

ws.send(JSON.stringify({
op: "authKeyExpires",
args: [API_KEY, nonce, sig],
}));

// 2. Subscribe to order notifications
ws.send(JSON.stringify({
op: "subscribe",
args: ["notificationApiV3"],
}));

// 3. Keep alive
setInterval(() => ws.send("ping"), 15000);
});

ws.on("message", (msg) => {
const str = msg.toString();
if (str === "pong") return;
console.log(JSON.parse(str));
});

第 5 步 — 取消测试订单

取消您在第 3 步中下的订单以完成清理。

接口: DELETE /api/v3.3/order

传入第 3 步中的 orderID。参见取消订单了解完整说明。

example
DELETE/api/v3.3/order

Python

resp = signed_request(
"DELETE",
"/api/v3.3/order?symbol=BTC-USD&orderID=990db9b6-2ed4-4c68-b46e-827c88cc3884",
)
print(resp.json())

Node.js

const result = await signedRequest(
"DELETE",
"/api/v3.3/order?symbol=BTC-USD&orderID=990db9b6-2ed4-4c68-b46e-827c88cc3884"
);
console.log(result);

下一步

目标资源
浏览所有现货接口现货 API 概览
交互式测试接口API 浏览器
交易期货期货 API 概览
管理钱包和提现钱包 API 概览
构建实时订单簿订单簿增量更新
了解错误响应错误代码