概览
欢迎查看 API文档。我们提供完整的REST和WebSocket API以满足您的交易需求。
API学习资源与技术支持
创建我的APIKEY
请在官网或APP进行创建。
实盘交易
实盘API交易地址如下:
- REST:https://api-v2.uzx.com
- WebSocket公共频道:wss://stream.uzx.com
- WebSocket私有频道:wss://stream.uzx.com
做市商申请
REST API
请求验证
生成Apikey
在对任何请求进行签名之前,您必须通过交易网站创建一个APIKey。创建APIKey后,您将获得3个必须记住的信息:
- APIKey
- SecretKey
- Passphrase APIKey和SecretKey将由平台随机生成和提供,Passphrase将由您提供以确保API访问的安全性。平台将存储Passphrase加密后的哈希值进行验证,但如果您忘记Passphrase,则无法恢复,请您通过交易网站重新生成新的APIKey。
发起请求
代码下单示例
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.rometools.utils.Strings;
import com.createsgin.HmacAlgorithmEnum;
public class TestCase {
public static String host="https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public static void testPostOrder(){
String timestamp = System.currentTimeMillis()/1000 +"";
String method = "POST";
String requestPath = "/v2/trade/spot/order";
String body = "{\"product_name\":\"BTC-USDT\",\"order_type\":2,\"price\":\"103000\",\"amount\":\"1000\",\"order_buy_or_sell\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = OpenAPiUtils.generate(timestamp,method,requestPath,null,body,UZXACCESSSECRET2,HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
HttpResponse resp = HttpUtil.createPost(host+requestPath ).body(body)
.header("UZX-ACCESS-KEY",UZXACCESSKEY2)
.header("UZX-ACCESS-SIGN",signature)
.header("UZX-ACCESS-TIMESTAMP",timestamp)
.header("UZX-ACCESS-PASSPHRASE",UZXACCESSPASSPHRASE2).execute();
System.out.println(resp.body());
}
public static void main(String[] args) {
testPostOrder();
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_post_order():
timestamp = str(int(time.time()))
method = "POST"
path = "/v2/trade/spot/order"
body = {
"product_name": "BTC-USDT",
"order_type": 2,
"price": "103000",
"amount": "1000",
"order_buy_or_sell": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.post(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_post_order()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPostOrder() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "POST"
path := "/v2/trade/spot/order"
body := `{"product_name":"BTC-USDT","order_type":2,"price":"103000","amount":"1000","order_buy_or_sell":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPostOrder()
}
所有REST私有请求头都必须包含以下内容:
Header参数:
| 参数名 | 类型 | 是否必须 | 描述 |
|---|---|---|---|
| UZX-ACCESS-KEY | string | 是 | APIKey |
| UZX-ACCESS-SIGN | string | 是 | 使用HMAC SHA256哈希函数获得哈希值,再使用Base-64编码(请参阅签名) |
| UZX-ACCESS-TIMESTAMP | string | 是 | 发起请求的时间,如:1675665900 |
| UZX-ACCESS-PASSPHRASE | string | 是 | 您在创建API密钥时指定的Passphrase |
签名
代码签名生成示例
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.io.UnsupportedEncodingException;
public class OpenAPiUtils {
public static final String GET = "GET";
public static final String POST = "POST";
public static final String DELETE = "DELETE";
public static String generate(final String timestamp, String method, final String requestPath,
String queryString, String body, final String secret, final HmacAlgorithmEnum alg) {
body = StringUtils.defaultIfBlank(body, StringUtils.EMPTY);
queryString = StringUtils.isEmpty(queryString) ? "" : "?" + queryString;
final String preHash = timestamp + method + requestPath + queryString + body;
return encodeBase64(alg, secret, preHash);
}
public static String encodeBase64(final HmacAlgorithmEnum alg, final String secret, final String data) {
Validate.notNull(alg, "SignatureAlgorithm cannot be null.");
Validate.notNull(data, "Signing Secret cannot be null.");
switch (alg) {
case HMAC_MD5:
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_MD5, secret).hmac(data));
case HMAC_SHA_1:
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secret).hmac(data));
case HMAC_SHA_224:
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_SHA_224, secret).hmac(data));
case HMAC_SHA_256:
try {
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_SHA_256,
secret.getBytes("UTF-8")).hmac(data.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
case HMAC_SHA_384:
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_SHA_384, secret).hmac(data));
case HMAC_SHA_512:
return Base64.encodeBase64String(new HmacUtils(HmacAlgorithms.HMAC_SHA_512, secret).hmac(data));
default:
throw new IllegalArgumentException("The '" + alg.name() + "' algorithm cannot be used for signing.");
}
}
}
import hmac
import hashlib
import base64
def generate_signature(timestamp, method, request_path, query_string, body, secret):
method = method.upper()
query_string = '?' + query_string if query_string else ''
body = body if body else ''
pre_hash = f"{timestamp}{method}{request_path}{query_string}{body}"
signature = hmac.new(
secret.encode('utf-8'),
pre_hash.encode('utf-8'),
hashlib.sha256
).digest()
return base64.b64encode(signature).decode('utf-8')
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
)
func GenerateSignature(timestamp, method, requestPath, queryString, body, secret string) string {
method = strings.ToUpper(method)
if queryString != "" {
queryString = "?" + queryString
}
preHash := timestamp + method + requestPath + queryString + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return signature
}
UZX-ACCESS-SIGN的请求头是对timestamp + method + requestPath + body字符串(+表示字符串连接),以及SecretKey,使用HMAC SHA256方法加密,通过Base-64编码输出而得到的。
如:sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp + 'GET' + '/v2/trade/history/positions?product_name=BTCUSDT&ins_type=SWAP', SecretKey))
其中,timestamp的值与UZX-ACCESS-TIMESTAMP请求头相同,为时间戳格式,如1675665900。
method是请求方法,字母全部大写:GET/POST。
requestPath是请求接口路径。如:/v2/trade/history/positions
body是指请求主体的字符串,如果请求没有主体(通常为GET请求)则body可省略。如:{"instId":"BTC-USDT","lever":"5","mgnMode":"isolated"}
SecretKey为用户申请APIKey时所生成。如:22582BD0CFF14C41EDBF1AB98506286D
枚举值
订单&仓位枚举
订单保证金模式 mgn_mode
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 逐仓 |
| 2 | int | 全仓 |
订单模式 order_mode
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 普通订单 |
| 2 | int | 强平代管委托 |
| 4 | int | adl自动减仓 |
| 7 | int | 一键平仓单 |
买卖方向 order_buy_or_sell
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 买 |
| 2 | int | 卖 |
仓位方向 pos_side
| 值 | 类型 | 说明 |
|---|---|---|
| LG | string | 多仓 |
| ST | string | 空仓 |
订单类型 order_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 市价单 |
| 2 | int | 限价GTC-普通限价单 |
| 3 | int | 限价IOC-高级限价 |
| 4 | int | 限价FOK-高级限价 |
| 5 | int | LimitMaker-高级限价 |
| 9 | int | 一键平仓 |
开仓方向 pos_opt
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 开仓 |
| 2 | int | 平仓 |
| 3 | int | 强平接管 |
| 5 | int | adl自动减仓 |
订单状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 0 | int | 挂单 |
| 1 | int | 部分成交 |
| 2 | int | 部分撤单 |
| 3 | int | 撤单 |
| 4 | int | 完全成交 |
仓位模式 pos_mode
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 双向持仓 |
| 2 | int | 单向持仓 |
角色 role
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | string | taker |
| 2 | string | maker |
仓位状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 持仓 |
| 2 | int | 已平仓 |
| 3 | int | 强平 |
策略单枚举
止盈止损委托类型 stop_pos_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 部分仓位 |
| 2 | int | 全量仓位 |
止盈方式 tp_price_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 市价 |
| 2 | int | 限价 |
触发方式
tp_price_compare止盈触发价格类型sl_price_compare止损触发价格类型plan_price_compare计划委托触发价格类型trial_compare移动止盈止损激活价格类型
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 指数价格 |
| 2 | int | 标记价格 |
| 3 | int | 最新价格 |
移动止盈止损回调类型 trial_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 比例(移动止盈止损)/市价(计划委托) |
| 2 | int | 间距(移动止盈止损)/限价(计划委托) |
触发方式 fin_trigger_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 止盈 |
| 2 | int | 止损 |
策略单状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 3 | int | 撤单 |
| 100 | int | 待激活 |
| 101 | int | 待触发 |
| 102 | int | 触发成功 |
| 103 | int | 触发失败 |
币种配置枚举
币种状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 0 | int | 禁用 |
| 1 | int | 启用 |
现货币对配置枚举
现货产品状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 待开盘 |
| 2 | int | 启用中 |
| 3 | int | 暂停交易 |
永续合约币对配置枚举
合约产品状态 status
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 启用中 |
| 2 | int | 暂停交易 |
资金账户枚举
转账方向 trade_direction
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 收入 |
| 2 | int | 支出 |
账单主类型 bill_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 充值 |
| 2 | int | 提现 |
| 3 | int | 转入 |
| 4 | int | 转出 |
| 5 | int | 划转 |
| 6 | int | 空投 |
交易账户枚举
转账方向 trade_direction
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 收入 |
| 2 | int | 支出 |
账单主类型 bill_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 交易 |
| 2 | int | 强平 |
| 3 | int | 保证金划转 |
| 4 | int | 资金费 |
| 5 | int | 自动减仓 |
| 6 | int | 划转 |
| 7 | int | 分润支出 |
| 8 | int | 分润退还 |
| 9 | int | 体验金 |
| 10 | int | 风险基金 |
| 11 | int | 资金费用 |
账单子类型 sub_bill_type
| 值 | 类型 | 说明 |
|---|---|---|
| 1 | int | 冻结 |
| 2 | int | 解冻 |
| 3 | int | 买入 |
| 4 | int | 卖出 |
| 5 | int | 手续费 |
| 6 | int | 开多 |
| 7 | int | 开空 |
| 8 | int | 平多 |
| 9 | int | 平空 |
| 10 | int | 减仓平多 |
| 11 | int | 减仓平空 |
| 12 | int | 手动追加保证金 |
| 13 | int | 手动减少保证金 |
| 14 | int | 自动追加保证金 |
| 15 | int | 资金费支出 |
| 16 | int | 资金费收入 |
| 17 | int | 转入 |
| 18 | int | 转出 |
行情枚举
事件类型 event
| 值 | 类型 | 说明 |
|---|---|---|
| sub | string | 订阅 |
| unsub | string | 取消订阅 |
| req | string | 请求数据 |
业务类型 biz
| 值 | 类型 | 说明 |
|---|---|---|
| spot | string | 现货 |
| swap | string | 合约 |
频道名 type
- 现货频道名
| 值 | 类型 | 说明 |
|---|---|---|
| spot.candles | string | 现货k线 |
| spot.orderbook | string | 现货订单簿 |
| spot.percent10 | string | 现货订单簿percent10 |
| spot.ticker | string | 现货ticker |
| spot.fills | string | 现货成交明细 |
| spot.overview | string | 现货overview |
- 合约频道名
| 值 | 类型 | 说明 |
|---|---|---|
| swap.candles | string | 合约k线 |
| swap.index | string | 合约指数k线 |
| swap.tag | string | 合约标记k线 |
| swap.orderbook | string | 合约订单簿 |
| swap.percent10 | string | 合约订单簿percent10 |
| swap.ticker | string | 合约ticker |
| swap.fills | string | 合约成交明细 |
| swap.overview | string | 合约overview |
周期 interval
| 值 | 类型 | 说明 |
|---|---|---|
| 1min | string | 1分钟 |
| 5min | string | 5分钟 |
| 15min | string | 15分钟 |
| 30min | string | 30分钟 |
| 60min | string | 60分钟 |
| 1day | string | 1天 |
| 1week | string | 1周 |
| 1mon | string | 1月 |
撮合交易
撮合交易功能模块下的API接口需要身份验证。
现货新增委托单
限速:3次/秒
HTTP请求
POST /v2/trade/spot/order
请求参数
请求示例
{
"product_name": "BTC-USDT",
"order_type": 2,
"price": "103000",
"amount": "1000",
"order_buy_or_sell": 1
}
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.rometools.utils.Strings;
import com.createsgin.HmacAlgorithmEnum;
public class TestCase {
public static String host="https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public static void testPostApi(){
String timestamp = System.currentTimeMillis()/1000 +"";
String method = "POST";
String requestPath = "/v2/trade/spot/order";
String body = "{\"product_name\":\"BTC-USDT\",\"order_type\":2,\"price\":\"103000\",\"amount\":\"1000\",\"order_buy_or_sell\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = OpenAPiUtils.generate(timestamp,method,requestPath,null,body,UZXACCESSSECRET2,HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
HttpResponse resp = HttpUtil.createPost(host+requestPath ).body(body)
.header("UZX-ACCESS-KEY",UZXACCESSKEY2)
.header("UZX-ACCESS-SIGN",signature)
.header("UZX-ACCESS-TIMESTAMP",timestamp)
.header("UZX-ACCESS-PASSPHRASE",UZXACCESSPASSPHRASE2).execute();
System.out.println(resp.body());
}
public static void main(String[] args) {
testPostApi();
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_post_api():
timestamp = str(int(time.time()))
method = "POST"
path = "/v2/trade/spot/order"
body = {
"product_name": "BTC-USDT",
"order_type": 2,
"price": "103000",
"amount": "1000",
"order_buy_or_sell": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.post(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_post_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPostApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "POST"
path := "/v2/trade/spot/order"
body := `{"product_name":"BTC-USDT","order_type":2,"price":"103000","amount":"1000","order_buy_or_sell":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPostApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » order_type | body | integer | 是 | 订单类型 | 见枚举 |
| » price | body | string | 是 | 价格 | none |
| » amount | body | string | 是 | 下单数量 | none |
| » order_buy_or_sell | body | integer | 是 | 买卖方向 | 1 买, 2 卖 |
| » trade_ccy | body | integer | 是 | 市价委托的单位 | 1 交易货币, 2计价货币 |
| » attach_algo | body | array[object] | 否 | 止盈止损信息 | none |
| »» tp_trigger_price | body | string | 是 | 止盈触发价 | none |
| »» tp_ord_price | body | string | 是 | 止盈委托价 | -1 代表市价,>0 为正常限价价格 |
| »» tp_ord_kind | body | string | 是 | 止盈委托类型 | 1.触发单/条件单(默认) 2 限价单 |
| »» sl_trigger_price | body | string | 是 | 止损触发价 | none |
| »» sl_ord_price | body | string | 是 | 止损委托价 | -1 代表市价,>0 为正常限价价格 |
返回参数
返回结果
{
"code": 200,
"msg": "success",
"data": {
"order_id": "2508810000100425939"
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | object | 数据 | none |
| »» order_id | string | 订单ID | none |
现货批量新增委托单
限速:3次/秒
HTTP请求
POST /v2/trade/spot/batch-orders
请求参数
请求示例
[
{
"product_name": "BTC-USDT",
"order_type": 2,
"price": "103000",
"amount": "1000",
"order_buy_or_sell": 1
}
]
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.rometools.utils.Strings;
import com.createsgin.HmacAlgorithmEnum;
public class TestCase {
public static String host="https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public static void testPostApi(){
String timestamp = System.currentTimeMillis()/1000 +"";
String method = "POST";
String requestPath = "/v2/trade/spot/batch-orders";
String body = "[{\"product_name\":\"BTC-USDT\",\"order_type\":2,\"price\":\"103000\",\"amount\":\"1000\",\"order_buy_or_sell\":1}]";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = OpenAPiUtils.generate(timestamp,method,requestPath,null,body,UZXACCESSSECRET2,HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
HttpResponse resp = HttpUtil.createPost(host+requestPath ).body(body)
.header("UZX-ACCESS-KEY",UZXACCESSKEY2)
.header("UZX-ACCESS-SIGN",signature)
.header("UZX-ACCESS-TIMESTAMP",timestamp)
.header("UZX-ACCESS-PASSPHRASE",UZXACCESSPASSPHRASE2).execute();
System.out.println(resp.body());
}
public static void main(String[] args) {
testPostApi();
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_post_api():
timestamp = str(int(time.time()))
method = "POST"
path = "/v2/trade/spot/batch-orders"
body = [
{
"product_name": "BTC-USDT",
"order_type": 2,
"price": "103000",
"amount": "1000",
"order_buy_or_sell": 1
}
]
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.post(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_post_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPostApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "POST"
path := "/v2/trade/spot/batch-orders"
body := `[{"product_name":"BTC-USDT","order_type":2,"price":"103000","amount":"1000","order_buy_or_sell":1}]`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPostApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | array[object] | 否 | 订单数组 | none |
| » product_name | body | string | 是 | 产品名 | none |
| » order_type | body | integer | 是 | 订单类型 | 见枚举 |
| » price | body | string | 是 | 价格 | none |
| » amount | body | string | 是 | 下单数量 | none |
| » order_buy_or_sell | body | integer | 是 | 买卖方向 | 1 买, 2 卖 |
| » trade_ccy | body | integer | 是 | 市价委托的单位 | 1 交易货币, 2计价货币 |
| » attach_algo | body | array[object] | 否 | 止盈止损信息 | none |
| »» tp_trigger_price | body | string | 是 | 止盈触发价 | none |
| »» tp_ord_price | body | string | 是 | 止盈委托价 | -1 代表市价,>0 为正常限价价格 |
| »» tp_ord_kind | body | string | 是 | 止盈委托类型 | 1.触发单/条件单(默认) 2 限价单 |
| »» sl_trigger_price | body | string | 是 | 止损触发价 | none |
| »» sl_ord_price | body | string | 是 | 止损委托价 | -1 代表市价,>0 为正常限价价格 |
返回参数
返回结果
{
"code": 200,
"msg": "success",
"data": [
{
"code": 200,
"order_id": "2509820413501205367"
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» code | integer | none | |
| »» order_id | string | none |
合约新增委托单
限速:3次/秒
HTTP请求
POST /v2/trade/swap/order
请求参数
Body 请求示例
{
"product_name": "BTCUSDT",
"order_type": 2,
"number": 1,
"price": "107000",
"amount": "1",
"trade_ccy": 1,
"pos_side": "LG",
"order_buy_or_sell": 1
}
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.rometools.utils.Strings;
import com.createsgin.HmacAlgorithmEnum;
public class TestCase {
public static String host="https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public static void testPostApi(){
String timestamp = System.currentTimeMillis()/1000 +"";
String method = "POST";
String requestPath = "/v2/trade/swap/order";
String body = "{\"product_name\":\"BTCUSDT\",\"order_type\":2,\"number\":1,\"price\":\"107000\",\"amount\":\"1\",\"trade_ccy\":1,\"pos_side\":\"LG\",\"order_buy_or_sell\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = OpenAPiUtils.generate(timestamp,method,requestPath,null,body,UZXACCESSSECRET2,HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
HttpResponse resp = HttpUtil.createPost(host+requestPath ).body(body)
.header("UZX-ACCESS-KEY",UZXACCESSKEY2)
.header("UZX-ACCESS-SIGN",signature)
.header("UZX-ACCESS-TIMESTAMP",timestamp)
.header("UZX-ACCESS-PASSPHRASE",UZXACCESSPASSPHRASE2).execute();
System.out.println(resp.body());
}
public static void main(String[] args) {
testPostApi();
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_post_api():
timestamp = str(int(time.time()))
method = "POST"
path = "/v2/trade/swap/order"
body = {
"product_name": "BTCUSDT",
"order_type": 2,
"number": 1,
"price": "107000",
"amount": "1",
"trade_ccy": 1,
"pos_side": "LG",
"order_buy_or_sell": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.post(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_post_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPostApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "POST"
path := "/v2/trade/swap/order"
body := `{"product_name":"BTCUSDT","order_type":2,"number":1,"price":"107000","amount":"1","trade_ccy":1,"pos_side":"LG","order_buy_or_sell":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPostApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » order_type | body | integer | 是 | 订单类型 | 见枚举 |
| » number | body | integer | 是 | 合约张数 | none |
| » price | body | string | 是 | 价格 | none |
| » amount | body | string | 否 | 市价下单计价币数量 | none |
| » trade_ccy | body | integer | 否 | 市价委托的单位 | 1 合约数量, 2 计价货币 |
| » pos_side | body | string | 是 | 仓位方向 | LG 多, ST 空 |
| » order_buy_or_sell | body | integer | 是 | 买卖方向 | 1 买, 2 卖 |
| » attach_algo | body | array[object] | 否 | 止盈止损信息 | none |
| »» tp_trigger_price | body | string | 是 | 止盈触发价 | none |
| »» tp_ord_price | body | string | 是 | 止盈委托价 | -1 代表市价委托 > 0 正常限价价格 |
| »» tp_ord_kind | body | integer | 是 | 止盈订单类型 | 1.触发单/条件单(默认) 2 限价单 |
| »» tp_compare | body | integer | 是 | 止盈触发价格对比 | 1:指数价格 2:标记价格 3:最新成交价 |
| »» sl_trigger_price | body | string | 是 | 止损触发价 | none |
| »» sl_ord_price | body | string | 是 | 止损委托价 | -1 代表市价委托 > 0 正常限价价格 |
| »» sl_compare | body | integer | 是 | 止损触发价格对比 | 1:指数价格 2:标记价格 3:最新成交价 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": {
"order_id": "2517820683201827363"
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | object | 数据 | none |
| »» order_id | string | 订单ID | none |
合约批量新增委托单
限速:3次/秒
HTTP请求
POST /v2/trade/swap/batch-orders
请求参数
Body 请求示例
[
{
"product_name": "BTCUSDT",
"order_type": 2,
"number": 1,
"price": "102001",
"amount": "316.89",
"pos_side": "LG",
"order_buy_or_sell": 1
}
]
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.rometools.utils.Strings;
import com.createsgin.HmacAlgorithmEnum;
public class TestCase {
public static String host="https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public static void testPostApi(){
String timestamp = System.currentTimeMillis()/1000 +"";
String method = "POST";
String requestPath = "/v2/trade/swap/batch-orders";
String body = "[{\"product_name\":\"BTCUSDT\",\"order_type\":2,\"number\":1,\"price\":\"102001\",\"amount\":\"316.89\",\"pos_side\":\"LG\",\"order_buy_or_sell\":1}]";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = OpenAPiUtils.generate(timestamp,method,requestPath,null,body,UZXACCESSSECRET2,HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
HttpResponse resp = HttpUtil.createPost(host+requestPath ).body(body)
.header("UZX-ACCESS-KEY",UZXACCESSKEY2)
.header("UZX-ACCESS-SIGN",signature)
.header("UZX-ACCESS-TIMESTAMP",timestamp)
.header("UZX-ACCESS-PASSPHRASE",UZXACCESSPASSPHRASE2).execute();
System.out.println(resp.body());
}
public static void main(String[] args) {
testPostApi();
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_post_api():
timestamp = str(int(time.time()))
method = "POST"
path = "/v2/trade/swap/batch-orders"
body = [
{
"product_name": "BTCUSDT",
"order_type": 2,
"number": 1,
"price": "102001",
"amount": "316.89",
"pos_side": "LG",
"order_buy_or_sell": 1
}
]
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.post(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_post_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPostApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "POST"
path := "/v2/trade/swap/batch-orders"
body := `[{"product_name":"BTCUSDT","order_type":2,"number":1,"price":"102001","amount":"316.89","pos_side":"LG","order_buy_or_sell":1}]`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPostApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | array[object] | 否 | 订单数组 | none |
| » product_name | body | string | 是 | 产品名 | none |
| » order_type | body | integer | 是 | 订单类型 | 见枚举 |
| » number | body | integer | 是 | 合约张数 | none |
| » price | body | string | 是 | 价格 | none |
| » amount | body | string | 否 | 市价下单计价币数量 | none |
| » trade_ccy | body | integer | 否 | 市价委托的单位 | 1 合约数量, 2 计价货币 |
| » pos_side | body | string | 是 | 仓位方向 | LG 多, ST 空 |
| » order_buy_or_sell | body | integer | 是 | 买卖方向 | 1 买, 2 卖 |
| » attach_algo | body | array[object] | 否 | 止盈止损信息 | none |
| »» tp_trigger_price | body | string | 是 | 止盈触发价 | none |
| »» tp_ord_price | body | string | 是 | 止盈委托价 | -1 代表市价委托 > 0 正常限价价格 |
| »» tp_ord_kind | body | integer | 是 | 止盈订单类型 | 1.触发单/条件单(默认) 2 限价单 |
| »» tp_compare | body | integer | 是 | 止盈触发价格对比 | 1:指数价格 2:标记价格 3:最新成交价 |
| »» sl_trigger_price | body | string | 是 | 止损触发价 | none |
| »» sl_ord_price | body | string | 是 | 止损委托价 | -1 代表市价委托 > 0 正常限价价格 |
| »» sl_compare | body | integer | 是 | 止损触发价格对比 | 1:指数价格 2:标记价格 3:最新成交价 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"order_id": "2517720561802636780"
},
{
"order_id": "2517720561802636781"
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» code | integer | 状态码 | none |
| »» order_id | string | 订单ID | none |
合约指定币对市价全平
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/close-position
请求参数
Body 请求示例
{
"product_name": "BTCUSDT",
"pos_side": "LG"
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/close-position";
String body = "{\"product_name\":\"BTCUSDT\",\"pos_side\":\"LG\"}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/close-position"
body = {
"product_name": "BTCUSDT",
"pos_side": "LG"
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/close-position"
body := `{"product_name":"BTCUSDT","pos_side":"LG"}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » pos_side | body | string | 是 | 仓位方向 | LG 多, ST 空 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
合约调整仓位杠杆倍数
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/position/set-leverage
请求参数
请求示例
{
"product_name": "BTCUSDT",
"leverage": 10,
"pos_side": "LG",
"mgn_mode": 1
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/position/set-leverage";
String body = "{\"product_name\":\"BTCUSDT\",\"leverage\":10,\"pos_side\":\"LG\",\"mgn_mode\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/position/set-leverage"
body = {
"product_name": "BTCUSDT",
"leverage": 10,
"pos_side": "LG",
"mgn_mode": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/position/set-leverage"
body := `{"product_name":"BTCUSDT","leverage":10,"pos_side":"LG","mgn_mode":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » leverage | body | integer | 是 | 修改后的杠杆倍数 | none |
| » pos_side | body | string | 是 | 仓位方向 | LG 多, ST 空 |
| » mgn_mode | body | integer | 是 | 保证金模式 | 1 逐仓, 2 全仓 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
合约调整仓位保证金
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/position/margin-balance
请求参数
请求示例
{
"product_name": "BTCUSDT",
"type": "add",
"pos_side": "LG",
"amount": "1"
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/position/margin-balance";
String body = "{\"product_name\":\"BTCUSDT\",\"type\":\"add\",\"pos_side\":\"LG\",\"amount\":\"1\"}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/position/margin-balance"
body = {
"product_name": "BTCUSDT",
"type": "add",
"pos_side": "LG",
"amount": "1"
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/position/margin-balance"
body := `{"product_name":"BTCUSDT","type":"add","pos_side":"LG","amount":"1"}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » type | body | string | 是 | 类型 | add 增加, reduce 减少 |
| » amount | body | string | 是 | 保证金数量 | none |
| » pos_side | body | string | 是 | 仓位方向 | LG 多, ST 空 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
合约修改用户币对杠杆配置
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/config/set-leverage
请求参数
注意:
pos_mode 是 1时, 需要传递:long_leverage 、short_leverage
pos_mode 是 2时, 需要传递:one_way_leverage请求示例
{
"product_name": "BTCUSDT",
"long_leverage": 5,
"short_leverage": 5,
"one_way_leverage": 5,
"pos_mode": 1,
"mgn_mode": 1
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/config/set-leverage";
String body = "{\"product_name\":\"BTCUSDT\",\"long_leverage\":5,\"short_leverage\":5,\"one_way_leverage\":5,\"pos_mode\":1,\"mgn_mode\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/config/set-leverage"
body = {
"product_name": "BTCUSDT",
"long_leverage": 5,
"short_leverage": 5,
"one_way_leverage": 5,
"pos_mode": 1,
"mgn_mode": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/config/set-leverage"
body := `{"product_name":"BTCUSDT","long_leverage":5,"short_leverage":5,"one_way_leverage":5,"pos_mode":1,"mgn_mode":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » long_leverage | body | integer | 是 | 多仓杠杆 | none |
| » short_leverage | body | integer | 是 | 空仓杠杆 | none |
| » one_way_leverage | body | integer | 是 | 单向持仓杠杆 | none |
| » pos_mode | body | integer | 是 | 仓位模式 | 1 双向, 2 单向 |
| » mgn_mode | body | integer | 是 | 保证金模式 | 1 逐仓, 2 全仓 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
合约修改用户仓位保证金模式
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/config/set-mgn
请求参数
请求示例
{
"product_name": "BTCUSDT",
"mgn_mode": 1
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/config/set-mgn";
String body = "{\"product_name\":\"BTCUSDT\",\"mgn_mode\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/config/set-mgn"
body = {
"product_name": "BTCUSDT",
"mgn_mode": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/config/set-mgn"
body := `{"product_name":"BTCUSDT","mgn_mode":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » product_name | body | string | 是 | 产品名 | none |
| » mgn_mode | body | integer | 是 | 保证金模式 | 1 逐仓, 2 全仓 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
合约修改用户持仓模式
限速:3次/秒
HTTP请求
PUT /v2/trade/swap/config/set-pos-mod
请求参数
请求示例
{
"pos_mode": 1
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/swap/config/set-pos-mod";
String body = "{\"pos_mode\":1}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/swap/config/set-pos-mod"
body = {
"pos_mode": 1
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/swap/config/set-pos-mod"
body := `{"pos_mode":1}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » pos_mode | body | integer | 是 | 持仓模式 | 1 双向持仓, 2 单向持仓 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
撤销委托单
限速:3次/秒
HTTP请求
PUT /v2/trade/cancel-order
请求参数
请求示例
{
"inst_type": 1,
"cancel_ord_type": 1,
"order_id": "2509820413501205367"
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/cancel-order";
String body = "{\"inst_type\":1,\"cancel_ord_type\":1,\"order_id\":\"2509820413501205367\"}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/cancel-order"
body = {
"inst_type": 1,
"cancel_ord_type": 1,
"order_id": "2509820413501205367"
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/cancel-order"
body := `{"inst_type":1,"cancel_ord_type":1,"order_id":"2509820413501205367"}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » inst_type | body | integer | 是 | 业务类型 | 1 现货 | 2 合约 |
| » cancel_ord_type | body | integer | 是 | 撤销订单类型 | 1.限价/高级限价单 2.止盈止损单 3.计划委托单 4.移动止盈止损单 |
| » order_id | body | string | 是 | 订单id |
返回参数
返回结果
{
"code": 200,
"msg": "string",
"data": {}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| code | integer | 状态码 | none |
| msg | string | 描述信息 | none |
| data | object | 数据 | none |
批量撤销委托单
限速:3次/秒
HTTP请求
PUT /v2/trade/cancel-batch-order
请求参数
请求示例
{
"inst_type": 1,
"cancel_ord_type": 1,
"order_ids": [
"2509820413501205367",
"2509820413501205368"
]
}
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TestCase {
public static String host = "https://api-v2.uzx.com";
public static String UZXACCESSKEY2 = "{APIKey}";
public static String UZXACCESSSECRET2 = "{SecretKey}";
public static String UZXACCESSPASSPHRASE2 = "{Passphrase}";
public enum HmacAlgorithmEnum {
HMAC_SHA_256("HmacSHA256"),
HMAC_SHA_512("HmacSHA512");
private final String algorithmName;
HmacAlgorithmEnum(String algorithmName) {
this.algorithmName = algorithmName;
}
public String getAlgorithmName() {
return algorithmName;
}
}
public static String generate(String timestamp, String method, String requestPath,
String queryString, String body, String secret,
HmacAlgorithmEnum algorithm) throws Exception {
String data = timestamp + method + requestPath + (queryString != null ? queryString : "") + body;
Mac mac = Mac.getInstance(algorithm.getAlgorithmName());
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algorithm.getAlgorithmName());
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
public static void testPutApi() throws Exception {
String timestamp = System.currentTimeMillis() / 1000 + "";
String method = "PUT";
String requestPath = "/v2/trade/cancel-batch-order";
String body = "{\"inst_type\":1,\"cancel_ord_type\":1,\"order_ids\":[\"2509820413501205367\",\"2509820413501205368\"]}";
String data = timestamp + method + requestPath + body;
System.out.println(data);
String signature = generate(timestamp, method, requestPath, null, body, UZXACCESSSECRET2, HmacAlgorithmEnum.HMAC_SHA_256);
System.out.println(signature);
URL url = new URL(host + requestPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("UZX-ACCESS-KEY", UZXACCESSKEY2);
conn.setRequestProperty("UZX-ACCESS-SIGN", signature);
conn.setRequestProperty("UZX-ACCESS-TIMESTAMP", timestamp);
conn.setRequestProperty("UZX-ACCESS-PASSPHRASE", UZXACCESSPASSPHRASE2);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = body.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}
public static void main(String[] args) {
try {
testPutApi();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import time
import hmac
import hashlib
import base64
import requests
import json
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
def generate_signature(timestamp, method, path, query, body, secret):
query = '?' + query if query else ''
body = body if body else ''
prehash = f"{timestamp}{method.upper()}{path}{query}{body}"
signature = hmac.new(secret.encode(), prehash.encode(), hashlib.sha256).digest()
return base64.b64encode(signature).decode()
def test_put_api():
timestamp = str(int(time.time()))
method = "PUT"
path = "/v2/trade/cancel-batch-order"
body = {
"inst_type": 1,
"cancel_ord_type": 1,
"order_ids": [
"2509820413501205367",
"2509820413501205368"
]
}
body_str = json.dumps(body, separators=(',', ':'))
signature = generate_signature(timestamp, method, path, None, body_str, SecretKey)
headers = {
"UZX-ACCESS-KEY": APIKey,
"UZX-ACCESS-SIGN": signature,
"UZX-ACCESS-TIMESTAMP": timestamp,
"UZX-ACCESS-PASSPHRASE": Passphrase,
"Content-Type": "application/json"
}
resp = requests.put(host + path, headers=headers, data=body_str)
print(resp.status_code, resp.text)
test_put_api()
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"time"
"strings"
"io/ioutil"
)
const (
host = "https://api-v2.uzx.com"
APIKey = "{APIKey}"
SecretKey = "{SecretKey}"
Passphrase = "{Passphrase}"
)
func generateSignature(timestamp, method, path, query, body, secret string) string {
if query != "" {
query = "?" + query
}
preHash := timestamp + strings.ToUpper(method) + path + query + body
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(preHash))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func testPutApi() {
timestamp := fmt.Sprintf("%d", time.Now().Unix())
method := "PUT"
path := "/v2/trade/cancel-batch-order"
body := `{"inst_type":1,"cancel_ord_type":1,"order_ids":["2509820413501205367","2509820413501205368"]}`
signature := generateSignature(timestamp, method, path, "", body, SecretKey)
req, err := http.NewRequest(method, host+path, bytes.NewBuffer([]byte(body)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("UZX-ACCESS-KEY", APIKey)
req.Header.Set("UZX-ACCESS-SIGN", signature)
req.Header.Set("UZX-ACCESS-TIMESTAMP", timestamp)
req.Header.Set("UZX-ACCESS-PASSPHRASE", Passphrase)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bodyResp, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(bodyResp))
}
func main() {
testPutApi()
}
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| body | body | object | 否 | none | |
| » inst_type | body | integer | 是 | 业务类型 | 1 现货 2 合约 |
| » cancel_ord_type | body | integer | 是 | 撤销订单类型 | 1.限价/高级限价单 2.止盈止损单 3.计划委托单 4.移动止盈止损单 |
| » order_ids | body | [string] | 是 | 订单id列表 | none |
返回参数
返回结果
{
"code": 200,
"msg": "success",
"data": [
{
"code": 200,
"order_id": "2509820413501205367"
},
{
"code": 200,
"order_id": "2509820413501205368"
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» code | integer | none | |
| »» order_id | string | none |
当前委托
限速:10次/秒
HTTP请求
GET /v2/trade/orders
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| product_name | query | string | 否 | 产品名 |
返回参数
返回结果
{
"code": 200,
"msg": "success",
"data": [
{
"product_name": "BTC-USDT",
"order_id": "2517910362100040465",
"mgn_mode": 0,
"pos_side": "",
"order_mode": 0,
"pos_mode": 0,
"order_type": 2,
"pos_opt": 0,
"leverage": 0,
"order_buy_or_sell": 1,
"number": 0,
"amount": "",
"deal_number": 0,
"lock_base_amount": "0.001",
"lock_quote_amount": "109.52972",
"filled_quote_amount": "0",
"price": "109529.72",
"status": 0,
"avg_price": "0",
"deal_fee": "0",
"income": "0",
"created_at": 1751100684192,
"finish_at": 1751100684208,
"ins_type": "SPOT",
"algo_info": null,
"coin": "USDT",
"un_filled_amount": 0
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» product_name | string | 产品名 | none |
| »» order_id | string | 订单id | none |
| »» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_side | string | 仓位方向 | 仅适用于合约业务(U本位,币本位) |
| »» order_mode | integer | 订单种类 | 仅适用于合约业务(U本位,币本位) |
| »» pos_mode | integer | 持仓模式 | 仅适用于合约业务(U本位,币本位) |
| »» order_type | integer | 订单类型 | none |
| »» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »» leverage | string | 杠杆 | 仅适用于合约业务(U本位,币本位) |
| »» order_buy_or_sell | integer | 买卖方向 | none |
| »» number | string | 合约张数 | 仅适用于合约业务(U本位,币本位) |
| »» amount | string | 冻结的数量 | 仅适用于合约业务(U本位,币本位) |
| »» deal_number | string | 成交数量 | 成交基础币量 |
| »» lock_base_amount | string | 委托基础币量 | 仅适用于现货业务 |
| »» lock_quote_amount | string | 委托价值币量 | 仅适用于现货业务 |
| »» filled_quote_amount | string | 成交价值币量 | 仅适用于现货业务 |
| »» price | string | 单价 | none |
| »» status | integer | 订单状态 | none |
| »» avg_price | string | 成交均价 | none |
| »» deal_fee | string | 已成交手续费 | none |
| »» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »» created_at | integer | 订单创建时间 | none |
| »» finish_at | integer | 最后更新时间 | none |
| »» ins_type | string | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »» algo_info | string | 止盈止损信息 | none |
| »» coin | string | 计价币种 | none |
| »» un_filled_amount | string | 未成交数量 | 仅适用于合约业务(U本位,币本位) |
历史委托
限速:10次/秒
HTTP请求
GET /v2/trade/history/orders
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| product_name | query | string | 否 | 产品名称 | |
| begin | query | integer | 否 | 开始时间戳 | 毫秒 |
| end | query | integer | 否 | 结束时间戳 | 毫秒 |
| limit | query | integer | 否 | 条数 | 默认20,最大20 |
返回参数
返回结果
{
"code": 200,
"msg": "success",
"data": [
{
"product_name": "BTCUSDT",
"order_id": "2518220520600100009",
"mgn_mode": 1,
"pos_side": "ST",
"order_mode": 1,
"pos_mode": 1,
"order_type": 14,
"pos_opt": 0,
"leverage": 5,
"order_buy_or_sell": 2,
"number": 2,
"amount": "0.00015734",
"deal_number": 0,
"lock_base_amount": "0",
"lock_quote_amount": "0",
"filled_quote_amount": "0",
"price": "107775",
"status": 4,
"avg_price": "0",
"deal_fee": "0",
"income": "0",
"created_at": 1751414400845,
"finish_at": 1751414400876,
"ins_type": "SWAP",
"algo_info": "[]",
"coin": "USDT"
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» product_name | string | 产品名 | none |
| »» order_id | string | 订单id | none |
| »» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_side | string | 仓位方向 | 仅适用于合约业务(U本位,币本位) |
| »» order_mode | integer | 订单种类 | 仅适用于合约业务(U本位,币本位) |
| »» pos_mode | integer | 持仓模式 | 仅适用于合约业务(U本位,币本位) |
| »» order_type | integer | 订单类型 | none |
| »» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »» leverage | string | 杠杆 | 仅适用于合约业务(U本位,币本位) |
| »» order_buy_or_sell | integer | 买卖方向 | none |
| »» number | string | 合约张数 | 仅适用于合约业务(U本位,币本位) |
| »» amount | string | 冻结的数量 | none |
| »» deal_number | string | 成交数量 | 成交基础币量 |
| »» lock_base_amount | string | 委托基础币量 | 仅适用于现货业务 |
| »» lock_quote_amount | string | 委托价值币量 | 仅适用于现货业务 |
| »» filled_quote_amount | string | 成交价值币量 | 仅适用于现货业务 |
| »» price | string | 单价 | none |
| »» status | integer | 订单状态 | 详见枚举类型 |
| »» avg_price | string | 成交均价 | none |
| »» deal_fee | string | 已成交手续费 | none |
| »» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »» created_at | integer | 订单创建时间 | none |
| »» finish_at | integer | 最后更新时间 | none |
| »» ins_type | string | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »» algo_info | string | 止盈止损信息 | none |
| »» coin | string | 计价币种 | none |
当前仓位
限速:10次/秒
HTTP请求
GET /v2/trade/positions
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SWAP - U本位,BASE - 币本位 |
| product_name | query | string | 否 | 产品名 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"product_name": "BTCUSDT",
"position_id": "205206000000000017",
"ins_type": "SWAP",
"mgn_mode": 1,
"pos_mode": 1,
"leverage": 5,
"side": "ST",
"hold_position_amount": 2,
"margin": "4.32523068",
"total_fee": "0.012933",
"status": 1,
"force_close_price": "129194.4422923322683706070287539936102236422",
"position_avg_price": "107775",
"deal_avg_price": "0",
"income": "0",
"begin_order_id": "2517920520600050556",
"created_at": 1751101108324,
"updated_at": 1751414400876,
"close_num": 0,
"open_num": 2,
"bankrupt_price": "129323.55926444133519888",
"force_trigger_price": "0",
"adl_num": 0,
"adl_deal_price": "0",
"adl_income": "0",
"funding_fee": "0.00129768"
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» product_name | string | 产品名 | none |
| »» position_id | string | 仓位id | none |
| »» ins_type | string | 产品类型 | SWAP - U本位,BASE - 币本位 |
| »» mgn_mode | integer | 保证金模式 | none |
| »» pos_mode | integer | 持仓模式 | none |
| »» leverage | integer | 杠杆 | none |
| »» side | string | 方向 | none |
| »» hold_position_amount | integer | 持仓数量 | none |
| »» margin | string | 保证金 | 可增减,仅适用于逐仓 |
| »» total_fee | string | 总成交手续费 | none |
| »» status | integer | 状态 | 1 未全平仓 2完全平仓 3 强平 |
| »» force_close_price | string | 强平价格 | none |
| »» position_avg_price | string | 开仓均价 | none |
| »» deal_avg_price | string | 平仓均价 | none |
| »» income | string | 平仓盈亏 | none |
| »» begin_order_id | string | 开仓订单号 | none |
| »» created_at | integer | 开仓时间 | none |
| »» updated_at | integer | 更新时间 | none |
| »» close_num | integer | 平仓张数 | none |
| »» open_num | integer | 开仓总数 | none |
| »» bankrupt_price | string | 破产价格 | none |
| »» force_trigger_price | string | 强平触发价格 | none |
| »» adl_num | integer | adl数量 | none |
| »» adl_deal_price | string | adl成交均价 | none |
| »» adl_income | string | adl收益 | none |
| »» funding_fee | string | 累计资金费用 | none |
历史仓位
限速:10次/秒
HTTP请求
GET /v2/trade/history/positions
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SWAP - U本位,BASE - 币本位 |
| product_name | query | string | 否 | 产品名 | |
| mgn_mode | query | integer | 否 | 保证金模式 | 1 逐仓, 2 全仓 |
| begin | query | integer | 否 | 开始时间戳 | 毫秒 |
| end | query | integer | 否 | 结束时间戳 | 毫秒 |
| limit | query | integer | 否 | 条数 | 默认20条 |
返回参数
返回示例
{
"code": 200,
"msg": "string",
"data": [
{
"product_name": "string",
"position_id": "string",
"ins_type": "string",
"mgn_mode": 0,
"pos_mode": 0,
"leverage": 0,
"side": "string",
"hold_position_amount": 0,
"margin": "string",
"total_fee": "string",
"status": 0,
"force_close_price": "string",
"position_avg_price": "string",
"deal_avg_price": "string",
"income": "string",
"begin_order_id": "string",
"created_at": 0,
"updated_at": 0,
"close_num": 0,
"open_num": 0,
"bankrupt_price": "string",
"force_trigger_price": "string",
"adl_num": 0,
"adl_deal_price": "string",
"adl_income": "string",
"funding_fee": "string"
}
]
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | array[object] | 数据 | none |
| »» product_name | string | 产品名 | none |
| »» position_id | string | 仓位ID | none |
| »» ins_type | string | 产品类型 | SWAP - U本位,BASE - 币本位 |
| »» mgn_mode | integer | 保证金模式 | none |
| »» pos_mode | integer | 持仓模式 | none |
| »» leverage | integer | 杠杆倍数 | none |
| »» side | string | 持仓方向 | none |
| »» hold_position_amount | integer | 持仓数量 | none |
| »» margin | string | 保证金金额 | 可增减,仅适用于逐仓 |
| »» total_fee | string | 总手续费 | none |
| »» status | integer | 持仓状态 | 1:未全平仓 2:完全平仓 3:强平 |
| »» force_close_price | string | 强平价格 | none |
| »» position_avg_price | string | 开仓均价 | none |
| »» deal_avg_price | string | 平仓均价 | none |
| »» income | string | 平仓盈亏 | none |
| »» begin_order_id | string | 开仓订单号 | none |
| »» created_at | integer | 开仓时间 | none |
| »» updated_at | integer | 最后更新时间 | none |
| »» close_num | integer | 已平仓数量 | none |
| »» open_num | integer | 开仓总数量 | none |
| »» bankrupt_price | string | 破产价格 | none |
| »» force_trigger_price | string | 强平触发价 | none |
| »» adl_num | integer | ADL数量 | none |
| »» adl_deal_price | string | ADL成交均价 | none |
| »» adl_income | string | ADL收益 | none |
| »» funding_fee | string | 累计资金费用 | none |
指定订单详情
限速:10次/秒
HTTP请求
GET /v2/trade/order/details
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 业务类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| order_id | query | string | 是 | 订单id |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": {
"product_name": "BTCUSDT",
"order_id": "2517920520600050556",
"mgn_mode": 1,
"pos_side": "ST",
"order_mode": 1,
"pos_mode": 1,
"order_type": 2,
"pos_opt": 1,
"leverage": 5,
"order_buy_or_sell": 2,
"number": 2,
"amount": "0",
"deal_number": 2,
"lock_base_amount": "0",
"lock_quote_amount": "0",
"filled_quote_amount": "0",
"price": "107775",
"status": 4,
"avg_price": "107775",
"deal_fee": "0.012933",
"income": "0",
"created_at": 1751101108310,
"finish_at": 1751101108340,
"ins_type": "SWAP",
"algo_info": "[]",
"coin": "USDT",
"bills": [
{
"bill_id": "43786-2517920520600050556-2517720520600573709",
"product_name": "",
"order_id": "2517920520600050556",
"position_id": "205206000000000017",
"mgn_mode": 1,
"role": "taker",
"order_mode": 1,
"pos_side": "ST",
"pos_opt": 1,
"filled_amount": "1",
"price": "107775",
"fee": "0.0064665",
"margin": "2.1619665",
"leverage": 5,
"income": "0",
"taker_fee": "0.0006",
"maker_fee": "0.0004",
"order_buy_or_sell": 2,
"created_at": 1751101108324,
"ins_type": "SWAP",
"order_type": 2
},
{
"bill_id": "43786-2517920520600050556-2517820520600110106",
"product_name": "",
"order_id": "2517920520600050556",
"position_id": "205206000000000017",
"mgn_mode": 1,
"role": "taker",
"order_mode": 1,
"pos_side": "ST",
"pos_opt": 1,
"filled_amount": "1",
"price": "107775",
"fee": "0.0064665",
"margin": "2.1619665",
"leverage": 5,
"income": "0",
"taker_fee": "0.0006",
"maker_fee": "0.0004",
"order_buy_or_sell": 2,
"created_at": 1751101108325,
"ins_type": "SWAP",
"order_type": 2
}
]
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | object | 数据 | none |
| »» product_name | string | 产品名称 | none |
| »» order_id | string | 订单ID | none |
| »» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_side | string | 持仓方向 | 仅适用于合约业务(U本位,币本位) |
| »» order_mode | integer | 订单模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_mode | integer | 持仓模式 | 仅适用于合约业务(U本位,币本位) |
| »» order_type | integer | 订单类型 | none |
| »» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »» leverage | integer | 杠杆倍数 | 仅适用于合约业务(U本位,币本位) |
| »» order_buy_or_sell | integer | 买卖方向 | none |
| »» number | integer | 合约张数 | 仅适用于合约业务(U本位,币本位) |
| »» amount | string | 冻结数量 | none |
| »» deal_number | integer | 成交数量 | 成交基础币量 |
| »» lock_base_amount | string | 委托基础币量 | 仅适用于现货业务 |
| »» lock_quote_amount | string | 委托计价币量 | 仅适用于现货业务 |
| »» filled_quote_amount | string | 成交计价币量 | 仅适用于现货业务 |
| »» price | string | 委托价格 | none |
| »» status | integer | 订单状态 | none |
| »» avg_price | string | 成交均价 | none |
| »» deal_fee | string | 已成交手续费 | none |
| »» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »» created_at | integer | 创建时间 | none |
| »» finish_at | integer | 完成时间 | none |
| »» ins_type | string | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »» algo_info | object | 条件单信息 | none |
| »» coin | string | 计价币种 | none |
| »» bills | array[object] | 成交明细 | none |
| »»» bill_id | string | 明细ID | none |
| »»» product_name | string | 产品名称 | none |
| »»» order_id | string | 订单ID | none |
| »»» position_id | string | 仓位ID | 仅适用于合约业务(U本位,币本位) |
| »»» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »»» role | string | 角色 | none |
| »»» order_mode | integer | 订单模式 | 仅适用于合约业务(U本位,币本位) |
| »»» pos_side | string | 持仓方向 | 仅适用于合约业务(U本位,币本位) |
| »»» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »»» filled_amount | string | 成交数量 | none |
| »»» price | string | 成交价格 | none |
| »»» fee | string | 手续费 | none |
| »»» margin | string | 保证金 | 仅适用于合约业务(U本位,币本位) |
| »»» leverage | integer | 杠杆倍数 | 仅适用于合约业务(U本位,币本位) |
| »»» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »»» taker_fee | string | Taker手续费 | none |
| »»» maker_fee | string | Maker手续费 | none |
| »»» order_buy_or_sell | integer | 买卖方向 | none |
| »»» created_at | integer | 创建时间 | none |
| »»» ins_type | string | 业务类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »»» order_type | integer | 订单类型 | none |
指定历史订单详情
限速:10次/秒
HTTP请求
GET /v2/trade/history/order/details
请求参数
| 名称 | 位置 | 类型 | 必选 | 描述 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 业务类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| order_id | query | string | 是 | 订单id |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": {
"product_name": "BTCUSDT",
"order_id": "2517920520600050556",
"mgn_mode": 1,
"pos_side": "ST",
"order_mode": 1,
"pos_mode": 1,
"order_type": 2,
"pos_opt": 1,
"leverage": 5,
"order_buy_or_sell": 2,
"number": 2,
"amount": "0",
"deal_number": 2,
"lock_base_amount": "0",
"lock_quote_amount": "0",
"filled_quote_amount": "0",
"price": "107775",
"status": 4,
"avg_price": "107775",
"deal_fee": "0.012933",
"income": "0",
"created_at": 1751101108310,
"finish_at": 1751101108340,
"ins_type": "SWAP",
"algo_info": "[]",
"coin": "USDT",
"bills": [
{
"bill_id": "43786-2517920520600050556-2517720520600573709",
"product_name": "",
"order_id": "2517920520600050556",
"position_id": "205206000000000017",
"mgn_mode": 1,
"role": "taker",
"order_mode": 1,
"pos_side": "ST",
"pos_opt": 1,
"filled_amount": "1",
"price": "107775",
"fee": "0.0064665",
"margin": "2.1619665",
"leverage": 5,
"income": "0",
"taker_fee": "0.0006",
"maker_fee": "0.0004",
"order_buy_or_sell": 2,
"created_at": 1751101108324,
"ins_type": "SWAP",
"order_type": 2
},
{
"bill_id": "43786-2517920520600050556-2517820520600110106",
"product_name": "",
"order_id": "2517920520600050556",
"position_id": "205206000000000017",
"mgn_mode": 1,
"role": "taker",
"order_mode": 1,
"pos_side": "ST",
"pos_opt": 1,
"filled_amount": "1",
"price": "107775",
"fee": "0.0064665",
"margin": "2.1619665",
"leverage": 5,
"income": "0",
"taker_fee": "0.0006",
"maker_fee": "0.0004",
"order_buy_or_sell": 2,
"created_at": 1751101108325,
"ins_type": "SWAP",
"order_type": 2
}
]
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » data | object | 数据 | none |
| »» product_name | string | 产品名称 | none |
| »» order_id | string | 订单ID | none |
| »» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_side | string | 持仓方向 | 仅适用于合约业务(U本位,币本位) |
| »» order_mode | integer | 订单模式 | 仅适用于合约业务(U本位,币本位) |
| »» pos_mode | integer | 持仓模式 | 仅适用于合约业务(U本位,币本位) |
| »» order_type | integer | 订单类型 | none |
| »» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »» leverage | integer | 杠杆倍数 | 仅适用于合约业务(U本位,币本位) |
| »» order_buy_or_sell | integer | 买卖方向 | none |
| »» number | integer | 合约张数 | 仅适用于合约业务(U本位,币本位) |
| »» amount | string | 冻结数量 | none |
| »» deal_number | integer | 成交数量 | 成交基础币量 |
| »» lock_base_amount | string | 委托基础币量 | 仅适用于现货业务 |
| »» lock_quote_amount | string | 委托计价币量 | 仅适用于现货业务 |
| »» filled_quote_amount | string | 成交计价币量 | 仅适用于现货业务 |
| »» price | string | 委托价格 | none |
| »» status | integer | 订单状态 | none |
| »» avg_price | string | 成交均价 | none |
| »» deal_fee | string | 已成交手续费 | none |
| »» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »» created_at | integer | 创建时间 | none |
| »» finish_at | integer | 完成时间 | none |
| »» ins_type | string | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »» algo_info | object | 条件单信息 | none |
| »» coin | string | 计价币种 | none |
| »» bills | array[object] | 成交明细 | none |
| »»» bill_id | string | 明细ID | none |
| »»» product_name | string | 产品名称 | none |
| »»» order_id | string | 订单ID | none |
| »»» position_id | string | 仓位ID | 仅适用于合约业务(U本位,币本位) |
| »»» mgn_mode | integer | 保证金模式 | 仅适用于合约业务(U本位,币本位) |
| »»» role | string | 角色 | none |
| »»» order_mode | integer | 订单模式 | 仅适用于合约业务(U本位,币本位) |
| »»» pos_side | string | 持仓方向 | 仅适用于合约业务(U本位,币本位) |
| »»» pos_opt | integer | 仓位操作 | 仅适用于合约业务(U本位,币本位) |
| »»» filled_amount | string | 成交数量 | none |
| »»» price | string | 成交价格 | none |
| »»» fee | string | 手续费 | none |
| »»» margin | string | 保证金 | 仅适用于合约业务(U本位,币本位) |
| »»» leverage | integer | 杠杆倍数 | 仅适用于合约业务(U本位,币本位) |
| »»» income | string | 平仓盈亏 | 仅适用于合约业务(U本位,币本位) |
| »»» taker_fee | string | Taker手续费 | none |
| »»» maker_fee | string | Maker手续费 | none |
| »»» order_buy_or_sell | integer | 买卖方向 | none |
| »»» created_at | integer | 创建时间 | none |
| »»» ins_type | string | 业务类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| »»» order_type | integer | 订单类型 | none |
资金账户
资金账户功能模块下的API接口需要身份验证。
获取资金账户余额
限速:10次/秒
HTTP请求
GET /v2/asset/balances
请求参数
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| coins | query | string | 否 | 币种名 | BTC,USDT |
| omit_zero | query | boolean | 否 | 是否隐藏0值 |
返回参数
返回示例
{
"msg": "success",
"data": [
{
"coin": "USDT",
"balance": "98990000",
"frozen_balance": "10",
"available_balance": "98989990"
},
{
"coin": "BTC",
"balance": "10",
"frozen_balance": "0",
"available_balance": "10"
}
],
"code": 200
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» coin | string | 币种名 | none |
| »» balance | string | 余额 | none |
| »» frozen_balance | string | 冻结 | none |
| »» available_balance | string | 可用余额 | none |
获取资金账单流水(近7天)
限速:10次/秒
HTTP请求
GET /v2/asset/bills
请求参数
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| bill_type | query | integer | 否 | 账单类型 | |
| begin | query | integer | 否 | 开始时间戳 | 13位毫秒时间戳 |
| end | query | integer | 否 | 结束时间戳 | 13位毫秒时间戳 |
| limit | query | integer | 否 | 条数 | 默认20 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"coin_name": "USDT",
"bill_type": 4,
"trade_direction": 2,
"amount": "1000000",
"note": "转出至交易账户",
"created_at": 1751423748815,
"log_id": "b2fa280e-2042-462e-9999-ed9e041026e9"
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» coin_name | string | 币种名 | none |
| »» bill_type | integer | 账单类型 | none |
| »» trade_direction | integer | 方向 | none |
| »» amount | string | 数量 | none |
| »» note | string | 备注信息 | none |
| »» created_at | integer | 创建时间(毫秒) | none |
| »» log_id | string | 流水id | none |
交易账户
交易账户功能模块下的API接口需要身份验证。
获取交易账户余额
限速:10次/秒
HTTP请求
GET /v2/account/balances
请求参数
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| coins | query | string | 否 | 币种名 | BTC,USDT |
| omit_zero | query | boolean | 否 | 是否隐藏0值 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"coin": "USDT",
"balance": "1009879.50566968",
"available_balance": "1009875.180439",
"isolated_frozen_balance": "4.32523068",
"cross_frozen_balance": "0",
"frozen_balance": "4.32523068",
"order_frozen_balance": "0"
},
{
"coin": "BTC",
"balance": "0.0000995",
"available_balance": "0.0000995",
"isolated_frozen_balance": "0",
"cross_frozen_balance": "0",
"frozen_balance": "0",
"order_frozen_balance": "0"
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» coin | string | 币种 | none |
| »» balance | string | 余额 | none |
| »» available_balance | string | 可用余额 | none |
| »» isolated_frozen_balance | string | 逐仓占用 | none |
| »» cross_frozen_balance | string | 全仓占用 | none |
| »» frozen_balance | string | 总占用 | none |
| »» order_frozen_balance | string | 挂单占用 | none |
获取交易账单流水(近7天)
限速:10次/秒
HTTP请求
GET /v2/account/bills
请求参数
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SPOT - 现货,SWAP - U本位,OTHER_BILL - 其他 |
| coin | query | string | 否 | 币种名 | |
| bill_type | query | integer | 否 | 主账单类型 | 见枚举值 |
| sub_bill_type | query | integer | 否 | 子账单类型 | 见枚举值 |
| begin | query | integer | 否 | 开始时间戳 | 13位毫秒时间戳 |
| end | query | integer | 否 | 结束时间戳 | 13位毫秒时间戳 |
| limit | query | integer | 否 | 数量,默认20,最大20 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"ins_type": "SWAP",
"product_name": "BTCUSDT",
"coin_name": "USDT",
"bill_type": 4,
"sub_bill_type": 16,
"mgn_mode": 1,
"role": "",
"trade_direction": 1,
"amount": "0.00023325",
"experience_amount": "0",
"fee_amount": "0",
"price": "0",
"income": "0",
"created_at": 1751443200823850,
"log_id": "c638cd39-9a37-4935-b119-2e394adc71e1"
},
{
"ins_type": "OTHER_BILL",
"product_name": "",
"coin_name": "USDT",
"bill_type": 6,
"sub_bill_type": 17,
"mgn_mode": 0,
"role": "",
"trade_direction": 1,
"amount": "1000000",
"experience_amount": "0",
"fee_amount": "0",
"price": "0",
"income": "0",
"created_at": 1751423749572423,
"log_id": "fc2cd6ff-d1f1-4ee9-a738-937591a2dca5"
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» ins_type | string | 产品类型 | none |
| »» product_name | string | 产品名 | none |
| »» coin_name | string | 币种名 | none |
| »» bill_type | integer | 主账单类型 | none |
| »» sub_bill_type | integer | 子账单类型 | none |
| »» mgn_mode | integer | 保证金模式 | none |
| »» role | string | 角色 | none |
| »» trade_direction | integer | 方向 | none |
| »» amount | string | 数量 | none |
| »» experience_amount | string | 体验金数量 | none |
| »» fee_amount | string | 手续费 | none |
| »» price | string | 成交价格 | none |
| »» income | string | 收益 | none |
| »» created_at | integer | 创建时间 | none |
| »» log_id | string | 流水id | none |
现货行情
现货行情功能模块下的API接口不需要身份验证。
现货烛图
返回K线数据。K线周期以上海时间为基准开始计算。
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/candles
请求参数
请求示例
GET /notification/spot/BTC-USDT/candles?size=10&interval=1min
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
| size | query | integer | 是 | 条数:最大2000 |
| start | query | integer | 是 | 开始时间戳(秒) |
| end | query | integer | 是 | 结束时间戳(秒) |
| interval | query | string | 是 | 时间间隔:见枚举 |
返回参数
返回结果
{
"code": 200,
"data": [
{
"open": "98955",
"close": "98955",
"high": "98955",
"low": "98955",
"turn_over": "0",
"vol": "0",
"count": 0
},
{
"open": "98955",
"close": "98955",
"high": "98955",
"low": "98955",
"turn_over": "0",
"vol": "0",
"count": 0
}
],
"interval": "1min",
"msg": "success",
"symbol": "BTC-USDT",
"ts": 1746754786392,
"type": "spot.candles"
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » symbol | string | 币对名 | none |
| » interval | string | k线类型 | none |
| » ts | string | 毫秒时间戳 | none |
| » data | array[object] | 数据 | none |
| »» open | string | 开盘价 | none |
| »» close | string | 收盘价 | none |
| »» high | string | 最高价 | none |
| »» low | string | 最低价 | none |
| »» turn_over | string | 成交额 | none |
| »» vol | string | 成交量 | none |
| »» count | integer | 交易次数 | none |
现货orderBook
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/orderbook
请求参数
请求示例
GET /notification/spot/BTC-USDT/candles?interval=step0
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对 |
| interval | query | string | 是 | 深度 step0-step3 |
返回参数
返回结果
{
"code": 200,
"interval": "step1",
"msg": "success",
"status": "ok",
"ts": 1746759469400,
"type": "spot.orderBook",
"data": {
"bids": [
[
"102551.64603",
"0.02"
]
],
"asks": [
[
"102551.65383",
"0.04"
]
],
"ts": 1746759469321,
"type": "spot.orderBook",
"product_name": "BTC-USDT",
"interval": "1"
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » interval | string | 深度 | none |
| » status | string | 状态 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | object | none | |
| »» bids | [array] | 买盘 | none |
| »» asks | [array] | 卖盘 | none |
| »» ts | integer | 毫秒时间戳 | |
| »» type | string | 请求方法 | |
| »» product_name | string | 产品名 | |
| »» interval | string | 深度档位 |
现货tickers
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/tickers
请求参数
返回参数
返回结果
{
"ch": "spot.tickers",
"code": 200,
"data": [
{
"market": {
"open": "100000",
"close": "100000",
"low": "100000",
"high": "100000",
"turn_over": "0",
"count": 0,
"vol": "0",
"change": "0",
"change_percent": "0"
},
"symbol": "BTC-USDT"
}
],
"msg": "success",
"ts": 1746727154821
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | array[object] | 数据 | none |
| »» market | object | none | |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »»» turn_over | string | 成交额 | none |
| »»» count | integer | 交易次数 | none |
| »»» vol | string | 成交量 | none |
| »»» change | string | 24小时变化值 | none |
| »»» change_percent | string | 24小时变化百分比 | none |
| »» symbol | string | 币对名 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
现货ticker
现货-ticker
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/ticker
请求参数
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
返回参数
返回结果
{
"ch": "spot.BTC-USDT.detail",
"code": 200,
"data": {
"market": {
"open": "89000",
"close": "89001",
"low": "89000",
"high": "89500",
"turn_over": "178089.9785",
"count": 0,
"vol": "2.000983",
"change": "0",
"change_percent": "0"
},
"symbol": "BTC-USDT"
},
"msg": "success",
"ts": 1744000114682
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | object | 数据 | none |
| »» market | object | none | |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »»» turn_over | string | 成交额 | none |
| »»» count | integer | 交易次数 | none |
| »»» vol | string | 成交量 | none |
| »»» change | string | 24小时变化值 | none |
| »»» change_percent | string | 24小时变化百分比 | none |
| »» symbol | string | 币对名 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
现货交易记录
最近一笔交易记录
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/trade
请求参数
请求示例
GET /notification/spot/BTC-USDT/trade
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对 |
返回参数
返回结果
{
"code": 200,
"data": {
"data": [
{
"direction": "sell",
"price": "102680.546869",
"ts": 1746759096603,
"vol": "0.04"
}
],
"ts": 1746759097067
},
"msg": "success",
"ts": 1746759097067,
"type": "swap.detail"
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | object | 数据 | none |
| »» data | array[object] | none | |
| »»» direction | string | 买卖方向 | sell, buy |
| »»» price | string | 成交价 | none |
| »»» ts | integer | 毫秒时间戳 | none |
| »»» vol | string | 成交量 | none |
| »» ts | integer | 毫秒时间戳 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
现货批量交易记录
最近指定数量的交易记录
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/trades
请求参数
请求示例
GET /notification/spot/BTC-USDT/trades?size=10
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名称 |
| size | query | int | 是 | 条数,最大2000 |
返回参数
返回结果
{
"code": 200,
"data": [
{
"data": [
{
"direction": "buy",
"price": "102599.946583",
"ts": 1746759371209,
"vol": "0.02"
}
],
"product_name": "BTC-USDT",
"ts": 1746759371209,
"type": "spot.BTC-USDT.fills"
},
{
"data": [
{
"direction": "sell",
"price": "102599.946583",
"ts": 1746759371725,
"vol": "0.02"
}
],
"product_name": "BTC-USDT",
"ts": 1746759371725,
"type": "spot.BTC-USDT.fills"
}
],
"msg": "success",
"ts": 1746759374498
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | array[object] | 数据 | none |
| »» data | array[object] | none | |
| »»» direction | string | 买卖方向 | sell, buy |
| »»» price | string | 成交价 | none |
| »»» ts | integer | 毫秒时间戳 | none |
| »»» vol | string | 成交量 | none |
| »» product_name | string | 币对名称 | none |
| »» ts | integer | 毫秒时间戳 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
现货历史交易记录
查询市场上的成交信息数据,可以分页获取最近3个月的数据。
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/spot/{symbol}/history-trades
请求参数
请求示例
GET /notification/spot/BTC-USDT/history-trades?size=10
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名称 |
| size | query | integer | 否 | 条数,最大 100,不填默认返回 100 条 |
| after | query | integer | 否 | 毫秒时间戳,请求此 ts 之前的分页内容,传的值为上一次请求的最后一条 ts |
返回参数
返回结果
{
"code": 200,
"data": [
{
"ts": 1752557507585,
"direction": "buy",
"price": "108640.42",
"vol": "0.0002",
"id": 184664390001
}
],
"msg": "success",
"ts": 1752725468921
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | array[object] | 数据 | none |
| »» direction | string | 买卖方向 | sell, buy |
| »» price | string | 成交价 | none |
| »» ts | integer | 毫秒时间戳 | none |
| »» vol | string | 成交量 | none |
| »» id | integer | id | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
合约行情
合约行情功能模块下的API接口不需要身份验证。
合约烛图
返回K线数据。K线周期以上海时间为基准开始计算。
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/candles
请求参数
请求示例
GET /notification/swap/BTCUSDT/candles?size=10&interval=1min
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
| interval | query | string | 是 | k线周期,见枚举值 |
| size | query | integer | 是 | 数量,最大2000 |
| start | query | integer | 是 | 开始时间戳(秒) |
| end | query | integer | 是 | 结束时间戳(秒) |
返回参数
返回结果
{
"code": 200,
"data": [
{
"open": "102380.8",
"close": "102380.3",
"high": "102380.8",
"low": "102379.2",
"turn_over": "",
"vol": "",
"count": 0
}
],
"interval": "1min",
"msg": "success",
"symbol": "BTCUSDT",
"ts": 1746763025575
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | array[object] | 数据 | none |
| »» open | string | 开盘价 | none |
| »» close | string | 收盘价 | none |
| »» high | string | 最高价 | none |
| »» low | string | 最低价 | none |
| »» turn_over | string | 成交额 | none |
| »» vol | string | 成交量 | none |
| »» count | integer | 交易次数 | none |
| » msg | string | 描述信息 | none |
| » symbol | string | 币对名 | none |
| » interval | string | 类型 | none |
| » ts | integer | 毫秒时间戳 | none |
合约orderBook
获取产品行情信息
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/orderbook
请求参数
请求示例
GET /notification/swap/BTCUSDT/orderbook?interval=step0
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
| interval | query | string | 否 | 深度 step0-step3 |
返回参数
返回结果
{
"code": 200,
"interval": "step1",
"msg": "success",
"status": "ok",
"ts": 1746782857053,
"type": "swap.orderBook",
"data": {
"bids": [
[
"102623",
"59494"
]
],
"asks": [
[
"102624",
"2143"
]
],
"ts": 1746782856804,
"type": "swap.BTCUSDT.orderBook",
"product_name": "BTCUSDT",
"interval": "1"
}
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » interval | string | 深度 | none |
| » status | string | 状态 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | object | none | |
| »» bids | [array] | 买盘 | none |
| »» asks | [array] | 卖盘 | none |
| »» ts | integer | 毫秒时间戳 | |
| »» type | string | 请求方法 | |
| »» product_name | string | 产品名 | |
| »» interval | string | 深度档位 |
合约ticker
合约ticker
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/ticker
请求参数
请求示例
GET /notification/swap/BTCUSDT/ticker
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
返回参数
返回结果
{
"ch": "swap.BTCUSDT.detail",
"code": 200,
"data": {
"market": {
"open": "10000",
"close": "102382.3557",
"low": "0.3538",
"high": "102938.655",
"turn_over": "411364424037.47854688",
"count": 0,
"vol": "4009858.7732",
"change": "92382.3557",
"change_percent": "9.23823557"
},
"index": {
"open": "103276.62",
"close": "102412.29",
"low": "102358.29",
"high": "103276.62"
},
"tag": {
"open": "103276.62",
"close": "102412.2",
"low": "102358.2",
"high": "103276.62"
},
"funding_rate": "0.00000001",
"funding_next_time": 1746777600,
"pre_funding_rate": "0.00000001",
"symbol": "BTCUSDT",
"risk_fund": "0"
},
"msg": "success",
"ts": 1746763088919
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | object | 数据 | none |
| »» market | object | 行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »»» turn_over | string | 成交额 | none |
| »»» count | integer | 交易次数 | none |
| »»» vol | string | 成交量 | none |
| »»» change | string | 24小时变化 | none |
| »»» change_percent | string | 24小时变化百分比 | none |
| »» index | object | 指数行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »» tag | object | 标记行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »» funding_rate | string | 资金费率 | none |
| »» funding_next_time | integer | 资金费下次收取时间 | 秒级时间戳 |
| »» pre_funding_rate | string | 预测资金费率 | none |
| »» symbol | string | 币对名 | none |
| »» risk_fund | string | 风险基金账户余额 | none |
合约tickers
获取产品行情信息同时提供最近24小时的交易聚合信息。
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/tickers
请求参数
请求示例
GET /notification/swap/tickers
返回参数
返回结果
{
"ch": "swap.tickers",
"code": 200,
"data": [
{
"market": {
"open": "10000",
"close": "102564.2999",
"low": "0.3538",
"high": "102938.655",
"turn_over": "554079954983.83727936",
"count": 0,
"vol": "5426486.2397",
"change": "92564.2999",
"change_percent": "9.25642999"
},
"index": {
"open": "103276.62",
"close": "102824.77",
"low": "102358.29",
"high": "103276.62"
},
"tag": {
"open": "103276.62",
"close": "102824.7",
"low": "102358.2",
"high": "103276.62"
},
"funding_rate": "0.00000001",
"funding_next_time": 1746777600,
"pre_funding_rate": "0.00000001",
"symbol": "BTCUSDT",
"risk_fund": "0"
}
],
"msg": "success",
"ts": 1746766867341
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | array[object] | 数据 | none |
| »» market | object | 行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »»» turn_over | string | 成交额 | none |
| »»» count | string | 交易次数 | none |
| »»» vol | string | 成交量 | none |
| »»» change | string | 24小时变化值 | none |
| »»» change_percent | string | 24小时变化百分比 | none |
| »» index | object | 指数行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »» tag | object | 标记行情 | none |
| »»» open | string | 开盘价 | none |
| »»» close | string | 收盘价 | none |
| »»» low | string | 最低价 | none |
| »»» high | string | 最高价 | none |
| »» funding_rate | string | 资金费率 | none |
| »» funding_next_time | integer | 下一次资金费率收取时间 | 秒级时间戳 |
| »» pre_funding_rate | string | 预测资金费率 | none |
| »» symbol | string | 币对名 | none |
| »» risk_fund | string | 风险基金余额 | none |
合约交易记录
最近一笔交易记录
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/trade
请求参数
请求示例
json GET /notification/swap/BTCUSDT/trade
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
返回参数
返回结果
{
"code": 200,
"data": {
"data": [
{
"direction": "buy",
"price": "102736.9001",
"ts": 1746766999793,
"vol": "79300"
}
],
"ts": 1746766999982
},
"msg": "success",
"ts": 1746766999982,
"type": "swap.detail"
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | object | 数据 | none |
| »» data | array[object] | none | |
| »»» direction | string | 买卖方向 | sell, buy |
| »»» price | string | 成交价 | none |
| »»» ts | integer | 毫秒时间戳 | none |
| »»» vol | string | 成交量 | none |
| »» ts | integer | 毫秒时间戳 | none |
合约批量交易记录
最近指定数量的交易记录
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/trades
请求参数
请求示例
GET /notification/swap/BTCUSDT/trades?size=10
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | none |
| size | query | int | 是 | 条数,最大2000 |
返回参数
返回结果
{
"code": 200,
"data": {
"data": [
{
"direction": "sell",
"price": "102771.2",
"ts": 1746767096612,
"vol": "1"
}
],
"ts": 1746767097114
},
"msg": "success",
"ts": 1746767097114,
"type": "swap.detail"
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | object | 数据 | none |
| »» data | array[object] | none | |
| »»» direction | string | 买卖方向 | sell, buy |
| »»» price | string | 成交价 | none |
| »»» ts | integer | 毫秒时间戳 | none |
| »»» vol | string | 成交量 | none |
| »» ts | integer | 毫秒时间戳 | none |
合约历史交易记录
查询市场上的成交信息数据,可以分页获取最近3个月的数据。
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/history-trades
请求参数
请求示例
GET /notification/swap/BTCUSDT/history-trades?size=10
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名称 |
| size | query | integer | 否 | 条数,最大 100,不填默认返回 100 条 |
| after | query | integer | 否 | 毫秒时间戳,请求此 ts 之前的分页内容,传的值为上一次请求的最后一条 ts |
返回参数
返回结果
{
"code": 200,
"data": [
{
"ts": 1752567144612,
"direction": "buy",
"price": "108640",
"vol": "605",
"id": 218251850000
}
],
"msg": "success",
"ts": 1752725604277
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » data | array[object] | 数据 | none |
| »» direction | string | 买卖方向 | sell, buy |
| »» price | string | 成交价 | none |
| »» ts | integer | 毫秒时间戳 | none |
| »» vol | string | 成交量 | none |
| »» id | integer | id | none |
| » msg | string | 描述信息 | none |
| » ts | integer | 毫秒时间戳 | none |
指数K线
获取指数K线
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/index
请求参数
请求示例
GET /notification/swap/BTCUSDT/index?size=10&interval=1min
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
| interval | query | string | 是 | k线周期,见枚举值 |
| size | query | integer | 是 | 条数,最大2000 |
| start | query | integer | 是 | 开始时间戳(秒) |
| end | query | integer | 是 | 结束时间戳(秒) |
返回参数
返回结果
{
"code": 200,
"data": [
{
"open": "102380.8",
"close": "102380.3",
"high": "102380.8",
"low": "102379.2",
"turn_over": "",
"vol": "",
"count": 0
}
],
"interval": "1min",
"msg": "success",
"symbol": "BTCUSDT",
"ts": 1746763025575
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » symbol | string | 币对名 | none |
| » interval | string | 类型 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | array[object] | 数据 | none |
| »» open | string | 开盘价 | none |
| »» close | string | 收盘价 | none |
| »» high | string | 最高价 | none |
| »» low | string | 最低价 | none |
| »» turn_over | string | 成交额 | none |
| »» vol | string | 成交量 | none |
| »» count | integer | 交易次数 | none |
标记K线
获取标记K线
限速: 20次/2s
限速规则:IP
HTTP请求
GET /notification/swap/{symbol}/tag
请求参数
请求示例
GET /notification/swap/BTCUSDT/tag?size=10&interval=1min
| 名称 | 位置 | 类型 | 必选 | 说明 |
|---|---|---|---|---|
| symbol | path | string | 是 | 币对名 |
| interval | query | string | 是 | k线周期,见枚举值 |
| size | query | integer | 是 | 条数,最大2000 |
| start | query | integer | 是 | 开始时间戳(秒) |
| end | query | integer | 是 | 结束时间戳(秒) |
返回参数
返回结果
{
"code": 200,
"data": [
{
"open": "102380.8",
"close": "102380.3",
"high": "102380.8",
"low": "102379.2",
"turn_over": "",
"vol": "",
"count": 0
}
],
"interval": "1min",
"msg": "success",
"symbol": "BTCUSDT",
"ts": 1746763025575
}
| 名称 | 类型 | 描述 | 说明 |
|---|---|---|---|
| » code | integer | 状态码 | none |
| » msg | string | 描述信息 | none |
| » symbol | string | 币对名 | none |
| » interval | string | 类型 | none |
| » ts | integer | 毫秒时间戳 | none |
| » data | array[object] | 数据 | none |
| »» open | string | 开盘价 | none |
| »» close | string | 收盘价 | none |
| »» high | string | 最高价 | none |
| »» low | string | 最低价 | none |
| »» turn_over | string | 成交额 | none |
| »» vol | string | 成交量 | none |
| »» count | integer | 交易次数 | none |
公共数据
公共数据功能模块下的API接口不需要身份验证。
获取服务器时间
限速:10次/秒
HTTP请求
GET /v2/time
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": {
"server_time": 1746498430903
}
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» server_time | integer | 服务器时间(毫秒) | none |
获取币种列表
限速:10次/秒
HTTP请求
GET /v2/coins
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"coin_name": "BTC",
"icon": "https://uzx-icon.oss-cn-hongkong.aliyuncs.com/coin/BTC.png",
"decimal": 8,
"can_deposit": true,
"can_withdrawal": true
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» coin_name | string | 币种名 | none |
| »» icon | string | 图标链接 | none |
| »» decimal | integer | 精度 | none |
| »» can_deposit | boolean | 是否允许充值 | none |
| »» can_withdrawal | boolean | 是否允许提现 | none |
获取币对列表
限速:10次/秒
HTTP请求
GET /v2/products
请求参数
| 名称 | 位置 | 类型 | 必选 | 中文名 | 说明 |
|---|---|---|---|---|---|
| ins_type | query | string | 否 | 产品类型 | SPOT - 现货,SWAP - U本位,BASE - 币本位 |
| product_name | query | string | 否 | 币种名 |
返回参数
返回示例
{
"code": 200,
"msg": "success",
"data": [
{
"ins_type": "SWAP",
"product_name": "BTCUSDT",
"base_coin_name": "BTC",
"quote_coin_name": "USDT",
"price_precision": 1,
"num_precision": 0,
"max_once_vol": "0",
"max_once_amount": "0",
"min_once_vol": "0",
"min_once_amount": "0",
"swap_value": "0.0001",
"price_unit": "0.1",
"max_leverage": 125,
"max_once_limit_num": 100000001,
"max_once_market_num": 100000000,
"max_hold_num": 100000000,
"maintenance_margin_rate": "0.001",
"market_max_deeps": 5,
"max_book_num": 500
}
]
}
| 名称 | 类型 | 中文名 | 说明 |
|---|---|---|---|
| » code | integer | none | |
| » msg | string | 描述信息 | none |
| » data | array[object] | none | |
| »» ins_type | string | 产品类型 | none |
| »» product_name | string | 产品名 | none |
| »» base_coin_name | string | 交易货币币种 | none |
| »» quote_coin_name | string | 计价货币币种 | none |
| »» price_precision | integer | 价格精度 | 适用现货交易 |
| »» num_precision | integer | 数量精度 | 适用于现货交易 |
| »» max_once_vol | string | 单次最大成交量 | 适用现货交易 |
| »» max_once_amount | string | 单次最大成交金额 | 适用现货交易 |
| »» min_once_vol | string | 单次最小成交量 | 适用现货交易 |
| »» min_once_amount | string | 单次最小成交金额 | 适用现货交易 |
| »» swap_value | string | 合约面值 | 适用合约交易(U本位、币本位) |
| »» price_unit | string | 合约价格最小步进 | 适用合约交易(U本位、币本位) |
| »» max_leverage | integer | 最大杠杆倍数 | 适用合约交易(U本位、币本位) |
| »» max_once_limit_num | integer | 单笔限价单最大数量 | 适用合约交易(U本位、币本位) |
| »» max_once_market_num | integer | 单笔市价单最大数量 | 适用合约交易(U本位、币本位) |
| »» max_hold_num | integer | 最大持仓数量 | 适用合约交易(U本位、币本位) |
| »» maintenance_margin_rate | string | 维持最大保证金率 | 适用合约交易(U本位、币本位) |
| »» market_max_deeps | integer | 市价最大吃单深度 | none |
| »» max_book_num | integer | 最大挂单数 | none |
WebSocket API
概述
WebSocket 是 HTML5 一种新的协议(Protocol)。它实现了用户端与服务器全双工通信, 使得数据可以快速地双向传播。通过一次简单的握手就可以建立用户端和服务器连接, 服务器根据业务规则可以主动推送信息给用户端。其优点如下:
- 用户端和服务器进行数据传输时,请求头信息比较小,大概 2 个字节。
- 用户端和服务器皆可以主动地发送数据给对方。
- 不需要多次创建 TCP 请求和销毁,节约宽带和服务器的资源。
连接
连接说明:
连接限制:1次/秒
当订阅公有频道时,使用公有服务的地址;当订阅私有频道时,使用私有服务的地址
订阅限制:240次/小时
订阅
订阅BTC-USDT现货k线
请求参数
请求示例
{
"event": "sub",
"params": {
"biz": "makert",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 sub |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称(币对) |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| >interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
取消订阅
取消订阅现货k线
请求参数
请求示例
{
"event": "unsub",
"params": {
"biz": "makert",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "unsub",
"params": {
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "unsub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"unsub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 unsub |
| params | 是 | object | 订阅参数信息 |
| > symbol | 是 | string | 产品名称(币对) |
| > biz | 是 | string | 类型 market |
| > type | 是 | string | 频道名 |
| > interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "unsubbed",
"topic": "spot.BTC-USDT.kline.1min",
"status": "ok"
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| id | 是 | String | 请忽略 |
| event | 是 | String | 事件 |
| topic | 是 | String | 主题 |
| status | 是 | String | 状态 |
请求历史数据
请求 BTC-USDT 1分钟历史k线数据
请求参数
请求示例
{
"event": "req",
"params": {
"symbol": "BTC-USDT",
"biz": "market",
"type": "spot.candles",
"interval": "1min",
"size": 300,
"from": 1751295600,
"to": 1751299200,
"id": "his"
},
"zip": true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "req",
"params": {
"symbol": "BTC-USDT",
"biz": "market",
"type": "spot.candles",
"interval": "1min",
"size": 300,
"from": 1751295600,
"to": 1751299200,
"id": "his"
},
"zip": true
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "req",
"params": map[string]interface{}{
"symbol": "BTC-USDT",
"biz": "market",
"type": "spot.candles",
"interval": "1min",
"size": 300,
"from": 1751295600,
"to": 1751299200,
"id": "his",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"req\",\"params\":{\"symbol\":\"BTC-USDT\",\"biz\":\"market\",\"type\":\"spot.candles\",\"interval\":\"1min\",\"size\":300,\"from\":1751295600,\"to\":1751299200,\"id\":\"his\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 事件 req |
| params | 是 | Object | 订阅参数信息 |
| > symbol | 是 | String | 币对 |
| > biz | 是 | String | 类型 market |
| > type | 是 | String | 频道类型 |
| > interval | 是 | String | 周期 |
| > size | 是 | Int | 查询记录大小 注意from和to的时间间隔不要超过size,size不超过300 |
| > from | 是 | Integer | 查询开始日期(秒级时间戳) |
| > to | 是 | Integer | 查询结束日期(秒级时间戳) |
| > id | 是 | String | 请求名 |
| zip | 是 | Boolean | 是否启用 gzip |
返回参数
返回示例
{
"data": [
{
"id": 1751295600,
"seq_id": 0,
"open": "109529.75",
"version": 0,
"close": "109529.75",
"high": "109529.75",
"low": "109529.75",
"turn_over": "0",
"vol": "0",
"count": 0
}
],
"id": "his",
"interval": "1min",
"status": "ok",
"symbol": "BTC-USDT",
"ts": 1751358326792,
"type": "spot.candles"
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| data | 是 | Array | |
| > close | 是 | String | 本阶段最新价 |
| > count | 是 | String | 交易次数 |
| > high | 是 | String | 本阶段最高价 |
| > low | 是 | String | 本阶段最低价 |
| > open | 是 | String | 本阶段开盘价 |
| > turn_over | 是 | String | 交易额 |
| > vol | 是 | String | 以报价币种计量的交易量 |
| interval | 是 | String | 周期 |
| symbol | 是 | String | 币种 |
| type | 是 | String | 频道类型 |
合约公共订阅
/notification/ws
合约Candles
请求参数
请求示例
{
"event": "sub",
"params": {
"biz": "market",
"type": "swap.candles",
"symbol": "BTCUSDT",
"interval": "1min"
},
"zip": true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.candles",
"symbol": "BTCUSDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.candles",
"symbol": "BTCUSDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.candles\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称 |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| >interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.kline.1min",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type":"swap.market.candles",
"product_name":"BTCUSDT",
"interval":"1min",
"data":{
"open":"106566.7",
"close":"106592.1",
"high":"106592.1",
"low":"106555.9",
"turn_over":"471445.0658",
"vol":"4.424",
"count":66
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >close | String | 本阶段最新价 |
| >count | Int | 交易次数 |
| >high | String | 本阶段最高价 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| >turn_over | String | 交易额度 |
| >vol | String | 以报价币种计量的交易量 |
| interval | String | 周期 |
| product_name | String | 产品名称 |
| type | String | 频道名 |
合约OverView
请求参数
请求示例
{
"event": "sub",
"params": {
"biz": "market",
"type": "swap.overview"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.overview",
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.overview",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.overview\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 |
| params | 是 | Object | 订阅参数信息 |
| >biz | 是 | String | 类型 market |
| >type | 是 | String | 频道名 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.overview",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
Feed示例
{
"type":"swap.overview",
"code":200,
"ts":1697034749887,
"msg":"success",
"data":[
{
"market":{
"open":"107575.2",
"close":"106660.1",
"low":"106538.5",
"high":"107916.6",
"turn_over":"1146662269.8977",
"count":0,
"vol":"10693.421",
"change":"-915.1",
"change_percent":"-0.0085066074708668912537462166001085752"
},
"index":{
"open":"107143.5",
"close":"106712.4",
"low":"106597.9",
"high":"107542.1"
},
"tag":{
"open":"107091.8",
"close":"106662.9",
"low":"106548.5",
"high":"107492.3"
},
"funding_rate":"0.0000511",
"funding_next_time":1751385600,
"pre_funding_rate":"0.0000511",
"symbol":"BTCUSDT",
"risk_fund":"0"
}
]
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| code | Int | 成功码 |
| data | Array | 返回信息 |
| > market | Object | 市场价格变化 |
| >> open | String | 开盘价 |
| >> close | String | 收盘价 |
| >> low | String | 最低价 |
| >> high | String | 最高价 |
| >> turn_over | String | 交易额 |
| >> count | Integer | 交易次数 |
| >> vol | String | 以报价币种计量的交易量 |
| >> change | String | 价格变化 |
| >> change_percent | String | 价格变化百分比 |
| > index | Object | 指数价格 |
| >> open | String | 开盘价 |
| >> close | String | 收盘价 |
| >> low | String | 最低价 |
| >> high | String | 最高价 |
| > tag | Object | 标记价格 |
| >> open | String | 开盘价 |
| >> close | String | 收盘价 |
| >> low | String | 最低价 |
| >> high | String | 最高价 |
| > pre_funding_rate | String | 预测资金费率 |
| > funding_rate | string | 资金费率 |
| > funding_next_time | Integer | 下次资金费用收取时间 秒级时间戳 |
| > symbol | String | 产品名称 |
| > risk_fund | String | 风险储备金 |
| msg | String | 返回信息 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1652974473071 |
| type | String | 频道名 |
合约Fills
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"swap.fills",
"symbol":"BTCUSDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.fills",
"symbol": "BTCUSDT"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.fills",
"symbol": "BTCUSDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.fills\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称 |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.trade.detail",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"ts":1751362613567,
"type":"swap.BTCUSDT.fills",
"product_name":"BTCUSDT",
"data":[
{
"vol":"4",
"ts":1751362613567,
"price":"106521",
"direction":"buy"
}
]
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Array | 返回数据 |
| >direction | String | 交易方向 buy sell |
| >price | String | 以报价币种为单位的成交价格 |
| >ts | Int | 成交时间,毫秒时间戳,如 1751362613567 |
| >vol | String | 以报价币种计量的交易量 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1751362613567 |
| type | String | 频道名 |
合约OrderBook
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"swap.orderbook",
"symbol":"BTCUSDT",
"interval":"0"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.orderbook",
"symbol": "BTCUSDT",
"interval": "0"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.orderbook",
"symbol": "BTCUSDT",
"interval": "0",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.orderbook\",\"symbol\":\"BTCUSDT\",\"interval\":\"0\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 |
| params | 是 | Object | 订阅参数信息 |
| >biz | 是 | String | 类型 market |
| >type | 是 | String | 频道名 |
| >symbol | 是 | String | 产品名称 |
| >interval | 是 | String | 深度0-3 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.depth.step0",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"asks":[
[
19631.36,
0.2041
]
],
"bids":[
[
19602.5,
0.1
]
],
"ts":1751362801514,
"type":"swap.BTCUSDT.orderBook",
"product_name":"BTCUSDT",
"interval":"0"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| asks | Array | 卖盘 |
| bids | Array | 买盘 |
| interval | Int | 精度 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1751362801514 |
| type | String | 频道名 |
asks和bids值数组举例说明:
asks: [19631.36,0.2041] 19631.36表示卖一价,0.2041表示卖一量
bids: [19602.5, 0.1] 19602.5 表示买一价,0.1表示买一量
合约Percent10
请求参数
请求示例
{
"event":"sub",
"params":{
"type":"swap.percent10",
"symbol":"BTCUSDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"type": "swap.percent10",
"symbol": "BTCUSDT"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"type": "swap.percent10",
"symbol": "BTCUSDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"type\":\"swap.percent10\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称(币对) |
| >type | 是 | string | 频道名 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.depth.percent10",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"asks":[
[
"106486.85",
"5277"
]
],
"bids":[
[
"106486.65",
"5922"
]
],
"product_name":"BTCUSDT",
"ts":1751364759613,
"type":"swap.percent10"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| asks | Array | 卖盘 |
| bids | Array | 买盘 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1751364759613 |
| type | String | 频道名 |
asks和bids值数组举例说明:
asks: [21573.475,0.01] 21573.475表示卖一价,0.01表示卖一量
bids: [17651.025, 0.05] 17651.025 表示买一价,0.05表示买一量
合约Ticker
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"swap.ticker",
"symbol":"BTCUSDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.ticker",
"symbol": "BTCUSDT"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.ticker",
"symbol": "BTCUSDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.ticker\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 sub |
| params | 是 | Object | 订阅参数信息 |
| > biz | 是 | String | 类型 |
| > type | 是 | String | 频道名 |
| > symbol | 是 | String | 产品名称(币对) |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.ticker",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type":"swap.BTCUSDT.ticker",
"product_name":"BTCUSDT",
"data":{
"open":"107399.9",
"close":"106460.1",
"high":"107916.6",
"low":"106444",
"vol":"10783.141",
"turn_over":"1155959567.4468",
"ask_price":"106454.3",
"ask_vol":"4237",
"bid_price":"106454.2",
"bid_vol":"2142",
"change":"-939.8",
"change_percent":"-0.0087504736969028835222379164226409894"
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >ask_price | String | 卖价 |
| >ask_vol | String | 卖量 |
| >bid_price | String | 买价 |
| >bid_vol | String | 买量 |
| >change | String | 价格变化 |
| >change_percent | String | 价格变化百分比 |
| >close | String | 本阶段最新价 |
| >high | String | 本阶段最高价 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| >turn_over | String | 交易额 |
| >vol | String | 以报价币种计量的交易量 |
| product_name | String | 产品名称 |
| type | String | 频道名 |
合约指数Candles
请求参数
请求示例
{
"event":"sub",
"params":{
"symbol":"BTCUSDT",
"biz":"market",
"type":"swap.index",
"interval":"1min"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.index",
"symbol": "BTCUSDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.index",
"symbol": "BTCUSDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.index\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称(币对) |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| >interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "index.BTCUSDT.kline.1min",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type":"swap.index.candles",
"symbol":"BTCUSDT",
"interval":"1min",
"data":{
"id":1751365320,
"open":"106521.7",
"close":"106519.1",
"high":"106521.7",
"low":"106514"
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >close | String | 本阶段最新价 |
| >high | String | 本阶段最高价 |
| >id | Int | 本阶段时间,秒级时间戳,例如:1751365320 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| interval | String | 周期 |
| symbol | String | 产品名称(币对) |
| type | String | 频道名 |
合约标记Candles
请求参数
请求示例
{
"event":"sub",
"params":{
"symbol":"BTCUSDT",
"biz":"market",
"type":"swap.tag",
"interval":"1min"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "swap.tag",
"symbol": "BTCUSDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "swap.tag",
"symbol": "BTCUSDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.tag\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品名称(币对) |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| >interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "tag.BTCUSDT.kline.1min",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type":"swap.tag.candles",
"symbol":"BTCUSDT",
"interval":"1min",
"data":{
"id":1751365740,
"open":"106441.7",
"close":"106433.5",
"high":"106441.7",
"low":"106432.1"
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >close | String | 本阶段最新价 |
| >high | String | 本阶段最高价 |
| >id | Int | 本阶段时间,秒级时间戳,例如:1751365740 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| interval | String | 周期 |
| symbol | String | 产品名称(币对) |
| type | String | 频道名 |
现货公共订阅
/notification/ws
现货Candles
返回历史K线数据。K线周期以上海时间为基准开始计算。
请求参数
请求示例
{
"event": "sub",
"params": {
"biz": "makert",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.candles",
"symbol": "BTC-USDT",
"interval": "1min",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| > symbol | 是 | string | 产品名称 |
| > biz | 是 | string | 类型 market |
| > type | 是 | string | 频道名 |
| > interval | 否 | string | 周期 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "spot.BTC-USDT.kline.1min",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type": "spot.market.candles",
"product_name": "BTC-USDT",
"interval": "1min",
"data": {
"id": 1751285220,
"open": "107685.73",
"close": "107685.71",
"high": "107685.73",
"low": "107685.7",
"turn_over": "109032.8693024",
"vol": "1.01251",
"count": 45
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >close | String | 本阶段最新价 |
| >count | Int | 交易次数 |
| >high | String | 本阶段最高价 |
| >id | Int | 本阶段时间,秒级时间戳,例如:1751285220 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| >turn_over | String | 交易额度 |
| >vol | String | 以报价币种计量的交易量 |
| interval | String | 周期 |
| product_name | String | 产品名称 |
| type | String | 频道名 |
现货OverView
请求参数
请求示例
{
"event": "sub",
"params": {
"biz": "market",
"type": "spot.overview"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "spot.overview"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.overview",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.overview\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 |
| params | 是 | Object | 订阅参数信息 |
| >symbol | 否 | String | 产品名称(币对) |
| >biz | 是 | String | 类型 market |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "spot.overview",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type": "spot.overview",
"code": 200,
"ts": 1751359457739,
"msg": "success",
"data": [
{
"market": {
"open": "10",
"close": "10",
"low": "10",
"high": "10",
"turn_over": "0",
"count": 0,
"vol": "0",
"change": "0",
"change_percent": "0"
},
"symbol": "YGG-USDT"
}
]
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| code | Int | 成功码 |
| data | Array | 返回信息 |
| > market | Object | 市场价格变化 |
| >> open | String | 开盘价 |
| >> close | String | 收盘价 |
| >> low | String | 最低价 |
| >> high | String | 最高价 |
| >> turn_over | String | 交易额 |
| >> count | Integer | 交易次数 |
| >> vol | String | 以报价币种计量的交易量 |
| >> change | String | 价格变化 |
| >> change_percent | String | 价格变化百分比 |
| > symbol | String | 产品名称 |
| msg | String | 返回信息 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1652974473071 |
| type | String | 频道名 |
现货Fills
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"spot.fills",
"symbol":"BTC-USDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "spot.fills",
"symbol": "BTC-USDT",
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.fills",
"symbol": "BTC-USDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.fills\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品ID(币对) |
| >biz | 是 | string | 类型 market |
| >type | 是 | string | 频道名 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.trade.detail",
"status":"ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"ts":1751359932841,
"type":"spot.BTC-USDT.fills",
"product_name":"BTC-USDT",
"data":[
{
"vol":"0.09026",
"ts":1751359932841,
"price":"106738",
"direction":"sell"
}
]
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Array | 返回数据 |
| >direction | String | 交易方向 buy, sell |
| >price | String | 以报价币种为单位的成交价格 |
| >ts | Int | 成交时间,毫秒时间戳,如 1652974473071 |
| >vol | String | 以报价币种计量的交易量 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1652974473071 |
| type | String | 频道名 |
现货OrderBook
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"spot.orderbook",
"symbol":"BTC-USDT",
"interval":"0"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz": "market",
"type": "spot.orderBook",
"symbol": "BTC-USDT",
"interval":"0"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.orderBook",
"symbol": "BTC-USDT",
"interval": "0",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.orderBook\",\"symbol\":\"BTC-USDT\",\"interval\":\"0\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 |
| params | 是 | Object | 订阅参数信息 |
| >biz | 是 | String | 类型 market |
| >type | 是 | String | 频道名 |
| >symbol | 是 | String | 产品ID(币对) |
| >interval | 是 | String | 深度0-3 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.depth.step0",
"status":"ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"bids": [
[
"107105.51",
"0.21529"
]
],
"asks": [
[
"107105.52",
"1.45346"
]
],
"ts": 1751018234502,
"type": "spot.orderBook",
"product_name": "BTC-USDT",
"interval": "0"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| asks | Array | 卖盘 |
| bids | Array | 买盘 |
| interval | Int | 精度 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1652974473071 |
| type | String | 频道名 |
asks和bids值数组举例说明:
asks: [19631.36,0.2041] 19631.36表示卖一价,0.2041表示卖一量
bids: [19602.5, 0.1] 19602.5 表示买一价,0.1表示买一量
现货Percent10
请求参数
请求示例
{
"event":"sub",
"params":{
"type":"spot.percent10",
"symbol":"BTC-USDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"type": "spot.percent10",
"symbol": "BTC-USDT"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"type": "spot.orderBook",
"symbol": "BTC-USDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"type\":\"spot.orderBook\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | string | 操作 |
| params | 是 | object | 订阅参数信息 |
| >symbol | 是 | string | 产品ID(币对) |
| >type | 是 | string | 频道名 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id": "",
"event": "subscribe",
"topic": "spot.BTC-USDT.depth.percent10",
"status": "ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"asks":[
[
21573.475,
0.01
]
],
"bids":[
[
17651.025,
0.05
]
],
"product_name":"BTC-USDT",
"ts":1657868806752,
"type":"spot.percent10"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| asks | Array | 卖盘 |
| bids | Array | 买盘 |
| product_name | String | 产品名称 |
| ts | Int | 信息返回时间,毫秒时间戳,如 1652974473071 |
| type | String | 频道名 |
asks和bids值数组举例说明:
asks: [21573.475,0.01] 21573.475表示卖一价,0.01表示卖一量
bids: [17651.025, 0.05] 17651.025 表示买一价,0.05表示买一量
现货Ticker
请求参数
请求示例
{
"event":"sub",
"params":{
"biz":"market",
"type":"spot.ticker",
"symbol":"BTC-USDT"
},
"zip":true
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/ws") as ws:
await ws.send(json.dumps({
"event": "sub",
"params": {
"biz":"market",
"type": "spot.ticker",
"symbol": "BTC-USDT"
},
"zip": True
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"biz": "market",
"type": "spot.ticker",
"symbol": "BTC-USDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.ticker\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 sub |
| params | 是 | Object | 订阅参数信息 |
| > biz | 是 | String | 类型 market |
| > type | 是 | String | 频道名 |
| > symbol | 是 | String | 产品ID(币对) |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
返回示例
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.ticker",
"status":"ok"
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| id | String | 请忽略 |
| event | String | 事件 |
| topic | String | Topic |
| status | String | 状态码 |
FEED参数说明
FEED示例
{
"type":"spot.BTC-USDT.ticker",
"product_name":"BTC-USDT",
"interval":"",
"data":{
"open":"107667.04",
"close":"106786.74",
"high":"107964.34",
"low":"106615.96",
"vol":"3538.46454",
"turn_over":"379681486.5679235",
"ask_price":"106786.74",
"ask_vol":"3.18435",
"bid_price":"106786.72",
"bid_vol":"0.00034",
"change":"-359.76",
"change_percent":"-0.0033576458400414385910879030112976159"
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
| data | Object | 返回数据 |
| >ask_price | String | 卖价 |
| >ask_vol | String | 卖量 |
| >bid_price | String | 买价 |
| >bid_vol | String | 买量 |
| >change | String | 价格变化 |
| >change_percent | String | 价格变化百分比 |
| >close | String | 本阶段最新价 |
| >high | String | 本阶段最高价 |
| >low | String | 本阶段最低价 |
| >open | String | 本阶段开盘价 |
| >turn_over | String | 交易额 |
| >vol | String | 以报价币种计量的交易量 |
| product_name | String | 币对 |
| type | String | 频道名 |
私有订阅
/notification/pri/ws
API登录
限速: 1次/1s 适用于单账户登录
请求参数
请求示例
{
"event":"login",
"params":{
"type":"api",
"api_key": "c881dd80201e4a1c8e2d0c25560cb871",
"api_timestamp": "1751371162",
"api_sign": "XvyvQW+H4fPgLcoC7AOJ6v4sJE2T5ajnM/NpQdtFzrE=",
"api_passphrase": "123.comA!"
}
}
import asyncio
import json
import websockets
async def handle_websocket():
async with websockets.connect("wss://stream.uzx.com/notification/pri/ws") as ws:
await ws.send(json.dumps({
"event":"login",
"params":{
"type":"api",
"api_key": "c881dd80201e4a1c8e2d0c25560cb871",
"api_timestamp": "1751371162",
"api_sign": "XvyvQW+H4fPgLcoC7AOJ6v4sJE2T5ajnM/NpQdtFzrE=",
"api_passphrase": "123.comA!"
}
}))
while True:
msg = await ws.recv()
data = json.loads(msg)
if "ping" in data:
await ws.send(json.dumps({"pong": data["ping"]}))
else:
print(json.dumps(data, indent=2))
asyncio.run(handle_websocket())
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net"
"net/http"
"time"
)
func main() {
url := "wss://stream.uzx.com/notification/pri/ws"
// 自定义Dialer配置
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// 强制使用IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// 建立WebSocket连接
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("连接失败:", err)
}
defer c.Close()
// 订阅消息
subMsg := map[string]interface{}{
"event": "login",
"params": map[string]interface{}{
"type":"api",
"api_key": "c881dd80201e4a1c8e2d0c25560cb871",
"api_timestamp": "1751371162",
"api_sign": "XvyvQW+H4fPgLcoC7AOJ6v4sJE2T5ajnM/NpQdtFzrE=",
"api_passphrase": "123.comA!",
},
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("发送订阅失败:", err)
}
fmt.Println("已发送订阅请求:", subMsg)
// 处理消息
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("读取消息错误:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("解析JSON错误:", err)
continue
}
// 处理ping消息
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("发送pong失败:", err)
return
}
fmt.Println("已发送pong响应")
continue
}
// 打印其他消息
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\n收到消息:\n%s\n", pretty)
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
String uri = "wss://stream.uzx.com/notification/pri/ws";
WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(uri), new WebSocket.Listener() {
@Override
public void onOpen(WebSocket webSocket) {
System.out.println("连接已建立");
// 发送订阅消息
String subscribeMsg = "{\"event\":\"login\",\"params\":{\"type\":\"api\",\"api_key\":\"c881dd80201e4a1c8e2d0c25560cb871\",\"api_timestamp\":\"1751371162\",\"api_sign\":\"XvyvQW+H4fPgLcoC7AOJ6v4sJE2T5ajnM/NpQdtFzrE=\",\"api_passphrase\":\"123.comA!\"}}";
webSocket.sendText(subscribeMsg, true);
System.out.println("已发送订阅请求: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// 处理 ping 消息
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("已发送 pong 响应");
} else {
// 打印其他消息
System.out.println("\n收到消息:");
System.out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
return WebSocket.Listener.super.onText(webSocket, data, last);
}
@Override
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
System.out.println("连接关闭: 状态码 " + statusCode + ", 原因 " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("发生错误:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// 保持连接
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 login |
| params | 是 | Object | 登录信息 |
| > type | 是 | String | 登录类型 api |
| > api_key | 是 | String | APIKey |
| > api_timestamp | 是 | String | 时间戳,Unix时间,单位是秒 |
| > api_passphrase | 是 | String | APIKey 的密码 |
| > api_sign | 是 | String | 签名字符串 |
| zip | 是 | Boolean | 是否启用gzip |
返回参数
全部成功返回示例
{
"id":"",
"event":"login",
"ts":1751373968447,
"status":"success"
}
| 参数名 | 必选 | 类型 | 说明 |
|---|---|---|---|
| event | 是 | String | 操作 |
| status | 是 | String | 状态码 success/error |
| ts | 是 | Int | 信息返回时间,毫秒时间戳,如 1748448006166 |
- api_key 调用API的唯一标识。需要用户手动设置一个
- api_passphrase APIKey的密码
- api_timestamp Unix 时间戳,单位为秒
api_sign 签名字符串,签名算法如下:
先将
api_timestamp、method、requestPath进行字符串拼接,再使用HMAC SHA256方法将拼接后的字符串和SecretKey加密,然后进行Base64编码SecretKey 用户申请APIKey时所生成的安全密钥,如:48f773feced21b2310bac1508a6259c4
其中 api_timestamp 示例 const api_timestamp = '' + Date.now() / 1000
其中 api_sign 示例 api_sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(api_timestamp +'GET'+ '/notification/pri/ws', secret))
method 总是 'GET'
requestPath 总是 '/notification/pri/ws'
现货订单状态变更通知
返回数据结构
数据示例
{
"type": "order.spot",
"name": "BTC-USDT",
"data": {
"order_id": 2509310000100964400,
"order_type": 1,
"order_buy_or_sell": 1,
"lock_base_amount": "0",
"lock_quote_amount": "0",
"filled_quote_amount": "0",
"price": "0",
"filled_amount": "0",
"filled_fee": "0",
"filled_avg": "0",
"created_at": 1743679202098,
"updated_at": 0,
"finish_at": 0,
"state": 0,
"un_filled_amount": "1",
"taker": "1",
"maker": "1",
"order_state": "",
"trade_ccy": 0,
"algo_info": {
"tp_trigger_price": "98000",
"tp_price": "-1",
"tp_price_compare": 3,
"sl_trigger_price": "72000",
"sl_price": "-1",
"sl_price_compare": 3
}
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
type |
String | 类型(如: order.spot) |
name |
String | 币对名(如: BTC-USDT) |
data |
Object | 订单数据对象 |
└─ order_id |
Int64 | 系统生成的订单 ID |
└─ order_type |
Int | 订单类型 |
└─ order_buy_or_sell |
Int | 买卖方向(1=买,2=卖) |
└─ lock_base_amount |
String | 冻结基础币数量 |
└─ lock_quote_amount |
String | 冻结计价币数量 |
└─ filled_quote_amount |
String | 已成交计价币金额 |
└─ price |
String | 委托价格 |
└─ filled_amount |
String | 已成交数量 |
└─ filled_fee |
String | 成交手续费 |
└─ filled_avg |
String | 成交均价 |
└─ created_at |
Int64 | 创建时间戳 |
└─ updated_at |
Int64 | 更新时间戳 |
└─ finish_at |
Int64 | 完成时间戳 |
└─ state |
Int | 订单状态 |
└─ un_filled_amount |
String | 未成交数量 |
└─ taker |
String | taker手续费 |
└─ maker |
String | maker手续费 |
└─ order_state |
String | 订单状态 |
└─ trade_ccy |
Int | 市价委托的单位, 1 交易货币, 2计价货币 |
└─ algo_info |
Object | 止盈止损信息 |
└─ tp_trigger_price |
String | 止盈触发价 |
└─ tp_price |
String | 止盈委托价 -1表示市价 |
└─ tp_price_compare |
Int | 止盈触发比较方式 |
└─ tp_ord_kind |
Int | 止盈委托类型 |
└─ sl_trigger_price |
String | 止损触发价 |
└─ sl_price |
String | 止损委托价 -1表示市价 |
└─ sl_price_compare |
Int | 止损触发比较方式 |
现货策略单变更通知
返回数据结构
数据示例
{
"type": "algo.spot",
"name": "BTC-USDT",
"data":{
"algo_ord_id": "2509310000101120674",
"link_ord_ids": "",
"tp_ord_id": "0",
"product_id": 100001,
"product_name": "",
"ins_type": "SPOT",
"algo_ord_type": 1,
"trade_ccy": 1,
"number": "0",
"amount": "1",
"user_id": 8378507354,
"account_id": "8378507354.001",
"price": "0",
"status": 101,
"order_buy_or_sell": 1,
"mgn_mode": 0,
"pos_mode": 0,
"pos_opt": 0,
"stop_pos_type": 0,
"taker_fee": "1",
"maker_fee": "1",
"created_at": 1743682997431,
"updated_at": 1743682997431,
"finish_at": 0,
"position_id": "0",
"source": 1,
"cancel_type": 0,
"fin_trigger_type": 0,
"fin_trigger_price": "0",
"fin_trigger_ord_id": 0,
"from_ord_id": "0",
"trial_his_price": "0",
"trial_price": "0",
"trial_amount": "0",
"trial_type": 0,
"trial_trigger_price": "0",
"plan_price_compare": 0,
"plan_trigger_price": "0",
"plan_price": "0",
"attach_algo": [
{
"tp_trigger_price": "89001",
"tp_price": "-1",
"tp_price_compare": 0,
"tp_ord_kind": 0,
"sl_trigger_price": "87001",
"sl_price": "-1",
"sl_price_compare": 0
}
],
"trade_role": 1
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
type |
String | 类型(如: algo.spot) |
name |
String | 币对名(如: BTC-USDT) |
data |
Object | 策略订单数据对象 |
└─ algo_ord_id |
String | 策略订单 ID |
└─ link_ord_ids |
String | 关联订单 ID(多个以逗号分隔) |
└─ tp_ord_id |
String | 止盈订单 ID |
└─ ins_type |
String | 交易类型(如 SPOT) |
└─ algo_ord_type |
Int | 策略订单类型 |
└─ trade_ccy |
Int | 交易币种类型 |
└─ number |
String | 合约委托张数 |
└─ amount |
String | 现货委托数量 |
└─ price |
String | 委托时候价格 |
└─ status |
Int | 策略状态码 |
└─ order_buy_or_sell |
Int | 买卖方向(1=买,2=卖) |
└─ mgn_mode |
Int | 保证金模式 |
└─ pos_mode |
Int | 持仓模式 |
└─ pos_opt |
Int | 持仓选项 |
└─ stop_pos_type |
Int | 止损仓位类型 |
└─ taker_fee |
String | 吃单手续费率 |
└─ maker_fee |
String | 挂单手续费率 |
└─ created_at |
Int64 | 创建时间戳 |
└─ updated_at |
Int64 | 更新时间戳 |
└─ finish_at |
Int64 | 完成时间戳 |
└─ position_id |
String | 仓位 ID |
└─ fin_trigger_type |
Int | 最终触发类型 |
└─ fin_trigger_price |
String | 最终触发价格 |
└─ fin_trigger_ord_id |
Int64 | 最终触发委托订单ID |
└─ from_ord_id |
String | 来源订单 ID |
└─ trial_his_price |
String | 移动止盈止损历史价格 |
└─ trial_price |
String | 移动止盈止损委托价格 |
└─ trial_amount |
String | 移动止盈止损回调数量/回调百分比 |
└─ trial_type |
Int | 移动止盈止损回调类型 |
└─ trial_trigger_price |
String | 移动止盈止损触发价格 |
└─ plan_price_compare |
Int | 计划委托价格触发方式 |
└─ plan_trigger_price |
String | 计划委托触发价 |
└─ plan_price |
String | 计划委托价格 |
└─ attach_algo |
Array | 止盈止损策略数组 |
└─ tp_trigger_price |
String | 止盈触发价 |
└─ tp_price |
String | 止盈委托价,-1表示市价 |
└─ tp_price_compare |
Int | 止盈价格比较类型 |
└─ tp_ord_kind |
Int | 止盈委托类型 1:条件单/2:限价单 |
└─ sl_trigger_price |
String | 止损触发价 |
└─ sl_price |
String | 止损委托价,-1表示市价 |
└─ sl_price_compare |
Int | 止损价格比较类型 |
合约订单状态变更通知
返回数据结构
数据示例
{
"type": "order.swap",
"name": "BTCUSDT",
"data": {
"seq_id": 0,
"product_id": 100001,
"order_id": "2509310000100502948",
"mgn_mode": 0,
"order_mode": 0,
"pos_mode": 0,
"number": 0,
"amount": "0",
"un_filled_number": 0,
"deal_number": 0,
"price": "88000",
"status": 0,
"avg_price": "0",
"income": "0",
"order_buy_or_sell": 1,
"pos_side": "",
"order_type": 2,
"pos_opt": 0,
"leverage": 0,
"freeze_amount": "0",
"taker_fee": "0",
"maker_fee": "0",
"created_at": 1743669339939,
"updated_at": 0,
"finish_at": 0,
"deal_fee": "0",
"position_id": 0,
"stp": 0,
"bankrupt_price": "0",
"trade_ccy": 0,
"LinkStopId": 0,
"algo_info": {
"tp_trigger_price": "89001",
"tp_price": "-1",
"tp_price_compare": 0,
"tp_ord_kind": 0,
"sl_trigger_price": "87001",
"sl_price": "-1",
"sl_price_compare": 0
}
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
type |
String | 类型(如: order.swap) |
name |
String | 币对名(如: BTCUSDT) |
data |
Object | 合约订单对象 |
└─ order_id |
String | 系统订单 ID |
└─ mgn_mode |
Int | 保证金模式 |
└─ order_mode |
Int | 下单模式 |
└─ pos_mode |
Int | 持仓模式 |
└─ number |
Int | 张数(币本位合约) |
└─ amount |
String | 委托金额 |
└─ un_filled_number |
Int | 未成交张数 |
└─ deal_number |
Int | 已成交张数 |
└─ price |
String | 委托价格 |
└─ status |
Int | 订单状态 |
└─ avg_price |
String | 成交均价 |
└─ income |
String | 收益(可用于回测) |
└─ order_buy_or_sell |
Int | 买卖方向(1=买,2=卖) |
└─ pos_side |
String | 仓位方向(long/short) |
└─ order_type |
Int | 委托类型(限价、IOC 等) |
└─ pos_opt |
Int | 开平仓标志 |
└─ leverage |
Int | 杠杆倍数 |
└─ freeze_amount |
String | 冻结保证金 |
└─ taker_fee |
String | 吃单手续费 |
└─ maker_fee |
String | 挂单手续费 |
└─ created_at |
Int64 | 创建时间戳 |
└─ updated_at |
Int64 | 更新时间戳 |
└─ finish_at |
Int64 | 完成时间戳 |
└─ deal_fee |
String | 成交总手续费 |
└─ position_id |
Int | 仓位 ID |
└─ bankrupt_price |
String | 破产价格 |
└─ trade_ccy |
Int | 交易币种标识 |
└─ algo_info |
Object | 止盈止损相关信息 |
└── tp_trigger_price |
String | 止盈触发价格 |
└── tp_price |
String | 止盈委托价格 -1代表市价 |
└── tp_price_compare |
Int | 止盈触发价格对比价格类型 |
└── tp_ord_kind |
Int | 止盈订单类型 1.条件单/2.限价单 |
└── sl_trigger_price |
String | 止损触发价格 |
└── sl_price |
String | 止损委托价格 -1代表市价 |
└── sl_price_compare |
Int | 止损触发价格对比价格类型 |
合约维持保证金率变更通知
返回数据结构
数据示例
{
"type": "margin.ration",
"name": "DOGEUSDT",
"data": {
"position_id": "208824000000000121",
"margin_ratio": "0.12"
}
}
| 参数名 | 类型 | 说明 |
|---|---|---|
type |
String | 类型(如: margin.ration) |
name |
String | 币对名(如: DOGEUSDT) |
data |
Object | 合约订单对象 |
└─ position_id |
String | 仓位 ID |
└─ margin_ratio |
Int | 维持保证金率模式 |
错误码
REST
订单类
| 错误码 | 错误提示 |
|---|---|
| 1080001 | 参数错误 |
| 1080002 | 交易对不允许为空 |
| 1080003 | 撤单类型错误 |
| 1080004 | 订单类型错误 |
| 1080005 | 数量错误 |
| 1080006 | 止盈止损数量错误 |
| 1080007 | 仓位方向错误 |
| 1080008 | 买卖方向与仓位方向不匹配 |
| 1080009 | 持仓模式错误 |
| 1080010 | 杠杆错误 |
| 1080011 | 止盈止损参数 |
| 1080012 | 保证金数量错误 |
| 1080013 | 价格错误 |
| 1080014 | 止盈止损类型错误 |
| 1080017 | 订单id错误 |
| 1080020 | 超过批量下单最大数量 |
| 1080021 | 批量订单产品不一致 |
| 1080023 | 当前存在仓位,不允许修改保证金模式 |
| 1080024 | 当前存在订单,不允许修改保证金模式 |
| 2080001 | 找不到交易对 |
| 2080003 | 交易对未启用 |
| 2080004 | 服务器内部错误 |
| 2080005 | 服务器内部错误 |
| 2080006 | 服务器内部错误 |
| 2080007 | 服务器内部错误 |
| 3080001 | 服务器内部错误 |
| 3080002 | 服务器内部错误 |
资产类
| 错误码 | 错误提示 |
|---|---|
| 1010002 | 参数校验失败 |
| 1010003 | 参数校验失败 |
| 1010004 | 资产可用不足 |
| 1010005 | 存在其他杠杆倍数的仓位,挂单或者止盈止损 |
| 1010006 | 下单太频繁 |
| 1010007 | 存在其他保证金模式的仓位,挂单或者止盈止损 |
| 1010008 | 保证金不足 |
| 1010009 | 超过最大订单数量 |
| 1010010 | 超过最大持仓 |
| 1010011 | 仓位可平数量不足 |
| 1010012 | 价格校验失败 |
| 1010013 | 委托失败,下单价格差于强平价格 |
| 1010014 | 资产冻结失败 |
| 1010015 | 该种类型的订单不允许进行撤单 |
| 1010016 | 没有查询到对应的仓位 |
| 1010017 | 止盈止损设置张数超过持仓张数 |
| 1010018 | 一键平仓超时 |
| 1010019 | 一个仓位只允许存在一个全量仓位止盈止损 |
| 1010020 | 存在其他杠杆倍数的订单或者止盈止损单 |
| 1010021 | 止盈止损价格校验失败 |
| 1010022 | 资产解冻失败 |
| 1010023 | 当前仓位模式下存在其他类型单仓位,订单或者止盈止损单 |
| 1010024 | 限价单不能高于最高买价 |
| 1010025 | 限价单的价格不能低于最低卖价 |
| 1010026 | 保证金模式校验失败 |
| 1010027 | 杠杆倍数校验失败 |
| 1010028 | 下单失败 |
| 1010029 | 参数校验失败 |
| 1010030 | 下单失败 |
| 1010031 | 价格对比失败,请设置合理的止盈触发价格 |
| 1010032 | 价格对比失败,请设置合理的止损触发价格 |
| 1010033 | 参数校验失败 |
| 1010034 | 限价止盈委托价格需要高于最新价 |
| 1010035 | 限价止盈委托价格需要低于最新价 |
| 1010036 | 限价委托策略请设置好委托价格 |
| 1010037 | 请设置止盈或者止损触发 |
| 1010038 | 参数校验失败 |
| 1010039 | 参数校验失败 |
| 1010040 | 移动止盈止损的回调幅度位0.1-100 |
| 1010041 | 移动止盈止损价距需要设置为正整数 |
| 1010042 | 移动止盈止损激活价格必须为正数 |
| 1010043 | 参数校验失败 |
| 1010044 | 参数校验失败 |
| 1010045 | 服务内部错误 |
| 1010046 | 参数校验失败 |
| 1010047 | 增加减少保证金失败 |
| 1010048 | 订单没有查询到 |
| 1010049 | 服务内部错误 |
| 1010050 | 当前状态下不允许对仓位进行操作 |
| 1010051 | 当前账户处于强平状态,不能进行操作 |
| 1011001 | 交易对已下线 |
| 1011002 | 交易对未开盘 |
| 1011003 | 交易对下线失败 |
| 1011004 | 交易对下线成功 |
| 1011005 | 交易对已暂停交易 |
| 1011006 | 开盘前仅允许挂卖出方向的限价单 |
| 1011007 | 参数校验失败 |
| 1011008 | 单笔交易额不能小于最小交易额 |
| 1011009 | 单笔交易额不能大于最大交易额 |
| 1011010 | 单笔交易量不能小于最小交易量 |
| 1011011 | 单笔交易量不能大于最大交易量 |
| 1011200 | 服务内部错误 |
| 1011201 | 服务内部错误 |
| 3010001 | 服务内部错误 |
| 3010005 | 服务内部错误 |
WebSocket
WebSocket