Overview
Welcome to the API documentation. We provide a complete REST and WebSocket API to meet your trading needs.
API Learning Resources and Technical Support
Create My API KEY
Please create it on the official website or app.
Live Trading
The live trading API address is as follows:
- REST:https://api-v2.uzx.com
- WebSocket Public Channel: wss://stream.uzx.com
- WebSocket Private Channel: wss://stream.uzx.com
Market Maker Application
REST API
Request Authentication
Generating API Keys
Before signing any requests, you must create an API key through the trading platform. Upon creation, you will receive three essential credentials that must be securely stored:
- API Key
- Secret Key
- Passphrase
The API Key and Secret Key are randomly generated by the platform, while the Passphrase is user-defined for enhanced API security. The platform stores only the hashed version of your Passphrase for authentication purposes. Please note:
- The Passphrase cannot be recovered if forgotten
- You must generate a new API key if the Passphrase is lost
- All three credentials are required for API authentication
Making Requests
Order Placement Code Examples
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()
}
All REST API private requests must include the following headers:
Header Parameters:
| Header Name | Type | Required | Description |
|---|---|---|---|
| UZX-ACCESS-KEY | string | Yes | Your API Key credential |
| UZX-ACCESS-SIGN | string | Yes | Base64-encoded HMAC SHA256 signature (see Signing section for details) |
| UZX-ACCESS-TIMESTAMP | string | Yes | Unix epoch timestamp in seconds (e.g., 1675665900) |
| UZX-ACCESS-PASSPHRASE | string | Yes | The passphrase you specified when creating the API key |
Request Signing
Signature Generation Examples
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
}
function generateSignature($timestamp, $method, $requestPath, $queryString, $body, $secret) {
$method = strtoupper($method);
$queryString = $queryString ? '?' . $queryString : '';
$body = $body ?: '';
$preHash = $timestamp . $method . $requestPath . $queryString . $body;
$hash = hash_hmac('sha256', $preHash, $secret, true);
return base64_encode($hash);
}
const crypto = require('crypto');
function generateSignature(timestamp, method, requestPath, queryString, body, secret) {
method = method.toUpperCase();
queryString = queryString ? '?' + queryString : '';
body = body || '';
const preHash = `${timestamp}${method}${requestPath}${queryString}${body}`;
const hmac = crypto.createHmac('sha256', secret);
hmac.update(preHash);
return hmac.digest('base64');
}
The UZX-ACCESS-SIGN header is generated by applying HMAC SHA256 encryption followed by Base64 encoding to the concatenated string of timestamp + method + requestPath + body and the SecretKey.
Example:
sign=CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(timestamp + 'GET' + '/v2/trade/history/positions?product_name=BTCUSDT&ins_type=SWAP', SecretKey))
Where:
- timestamp must match the value in the UZX-ACCESS-TIMESTAMP header (Unix timestamp format, e.g., 1675665900)
- method is the HTTP request method in uppercase (e.g., GET/POST)
- requestPath is the API endpoint path (e.g., /v2/trade/history/positions)
- body is the request payload string (omitted for GET requests). Example: {"instId":"BTC-USDT","lever":"5","mgnMode":"isolated"}
The SecretKey is generated when applying for an API key (e.g., 22582BD0CFF14C41EDBF1AB98506286D).
Enumerations
Order & Position Enums
Margin Mode (mgn_mode)
| Value | Type | Description |
|---|---|---|
| 1 | int | Isolated |
| 2 | int | Cross |
Order Mode (order_mode)
| Value | Type | Description |
|---|---|---|
| 1 | int | Normal order |
| 2 | int | Liquidation takeover order |
| 4 | int | ADL auto-reduction |
| 7 | int | One-click close order |
Order Direction (order_buy_or_sell)
| Value | Type | Description |
|---|---|---|
| 1 | int | Buy |
| 2 | int | Sell |
Position Side (pos_side)
| Value | Type | Description |
|---|---|---|
| LG | string | Long |
| ST | string | Short |
Order Type (order_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Market order |
| 2 | int | Limit GTC (normal limit) |
| 3 | int | Limit IOC (advanced) |
| 4 | int | Limit FOK (advanced) |
| 5 | int | LimitMaker (advanced) |
| 9 | int | One-click close |
Position Operation (pos_opt)
| Value | Type | Description |
|---|---|---|
| 1 | int | Open position |
| 2 | int | Close position |
| 3 | int | Liquidation takeover |
| 5 | int | ADL auto-reduction |
Order Status (status)
| Value | Type | Description |
|---|---|---|
| 0 | int | Pending |
| 1 | int | Partially filled |
| 2 | int | Partially canceled |
| 3 | int | Canceled |
| 4 | int | Fully filled |
Position Mode (pos_mode)
| Value | Type | Description |
|---|---|---|
| 1 | int | Dual-side |
| 2 | int | Single-side |
Role (role)
| Value | Type | Description |
|---|---|---|
| 1 | string | Taker |
| 2 | string | Maker |
Position Status (status)
| Value | Type | Description |
|---|---|---|
| 1 | int | Active |
| 2 | int | Closed |
| 3 | int | Liquidated |
Strategy Orders Enums
Stop Order Type (stop_pos_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Partial position |
| 2 | int | Full position |
Take Profit Type (tp_price_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Market |
| 2 | int | Limit |
Trigger Methods
tp_price_compare: Take-Profit Trigger Price Typesl_price_compare: Stop-Loss Trigger Price Typeplan_price_compare: Planned Order Trigger Price Typetrial_compare: Trailing Stop Activation Price Type
| Value | Type | Description |
|---|---|---|
| 1 | int | Index Price |
| 2 | int | Mark Price |
| 3 | int | Last Traded Price |
Trailing Stop-Loss and Take-Profit Callback Type (trial_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Percentage (for Trailing Stop-Loss and Take-Profit) / Market Order (for Planned Orders) |
| 2 | int | Distance (for Trailing Stop-Loss and Take-Profit) / Limit Order (for Planned Orders) |
Trigger Type (fin_trigger_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Take profit |
| 2 | int | Stop loss |
Strategy Order Status (status)
| Value | Type | Description |
|---|---|---|
| 3 | int | Canceled |
| 100 | int | Pending activation |
| 101 | int | Pending trigger |
| 102 | int | Triggered |
| 103 | int | Trigger failed |
Currency Configuration Enums
Currency Status (status)
| Value | Type | Description |
|---|---|---|
| 0 | int | Disabled |
| 1 | int | Enabled |
Spot Trading Pairs Enums
Spot Product Status (status)
| Value | Type | Description |
|---|---|---|
| 1 | int | Pre-open |
| 2 | int | Active |
| 3 | int | Trading suspended |
Perpetual Contract Pairs Enums
Contract Product Status (status)
| Value | Type | Description |
|---|---|---|
| 1 | int | Active |
| 2 | int | Trading suspended |
Funding Account Enums
Transfer Direction (trade_direction)
| Value | Type | Description |
|---|---|---|
| 1 | int | Income |
| 2 | int | Expense |
Bill Main Types (bill_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Deposit |
| 2 | int | Withdrawal |
| 3 | int | Transfer In |
| 4 | int | Transfer Out |
| 5 | int | Internal Transfer |
| 6 | int | Airdrop |
Trading Account Enums
Transfer Direction (trade_direction)
| Value | Type | Description |
|---|---|---|
| 1 | int | Income |
| 2 | int | Expense |
Bill Main Types (bill_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Trade |
| 2 | int | Liquidation |
| 3 | int | Margin Transfer |
| 4 | int | Funding Fee |
| 5 | int | ADL (Auto-Deleveraging) |
| 6 | int | Transfer |
| 7 | int | Rebate Expense |
| 8 | int | Rebate Refund |
| 9 | int | Trial Funds |
| 10 | int | Risk Fund |
| 11 | int | Funding Payment |
Bill Sub Types (sub_bill_type)
| Value | Type | Description |
|---|---|---|
| 1 | int | Freeze |
| 2 | int | Unfreeze |
| 3 | int | Buy |
| 4 | int | Sell |
| 5 | int | Fee |
| 6 | int | Open Long |
| 7 | int | Open Short |
| 8 | int | Close Long |
| 9 | int | Close Short |
| 10 | int | Reduce Long |
| 11 | int | Reduce Short |
| 12 | int | Manual Margin Increase |
| 13 | int | Manual Margin Decrease |
| 14 | int | Auto Margin Increase |
| 15 | int | Funding Fee Expense |
| 16 | int | Funding Fee Income |
| 17 | int | Transfer In |
| 18 | int | Transfer Out |
Market Data Enums
Event Type (event)
| Value | Type | Description |
|---|---|---|
| sub | string | Subscribe |
| unsub | string | Unsubscribe |
| req | string | Data request |
Business Type (params.biz)
| Value | Type | Description |
|---|---|---|
| spot | string | Spot |
| swap | string | Contract |
Channel Names (params.type)
- Spot Channels
| Value | Type | Description |
|---|---|---|
| spot.candles | string | Spot candlesticks |
| spot.orderbook | string | Spot order book |
| spot.percent10 | string | Spot order book (top 10%) |
| spot.ticker | string | Spot ticker |
| spot.fills | string | Spot trade details |
| spot.overview | string | Spot market overview |
- Contract Channels
| Value | Type | Description |
|---|---|---|
| swap.candles | string | Contract candlesticks |
| swap.index | string | Contract index candlesticks |
| swap.tag | string | Contract mark candlesticks |
| swap.orderbook | string | Contract order book |
| swap.percent10 | string | Contract order book (top 10%) |
| swap.ticker | string | Contract ticker |
| swap.fills | string | Contract trade details |
| swap.overview | string | Contract market overview |
Time Intervals (params.interval)
| Value | Type | Description |
|---|---|---|
| 1min | string | 1 minute |
| 5min | string | 5 minutes |
| 15min | string | 15 minutes |
| 30min | string | 30 minutes |
| 60min | string | 60 minutes |
| 1day | string | 1 day |
| 1week | string | 1 week |
| 1mon | string | 1 month |
Order Matching
APIs under the Order Matching module require authentication.
Place Spot Order
Rate Limit: 3 requests per second
HTTP Request
POST /v2/trade/spot/order
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Explanation | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » order_type | body | integer | Yes | Order type | See enumeration |
| » price | body | string | Yes | Price | |
| » amount | body | string | Yes | Order quantity | |
| » order_buy_or_sell | body | integer | Yes | Buy or sell direction | 1 for buy, 2 for sell |
| » trade_ccy | body | integer | Yes | Unit for market order | 1 for trading currency, 2 for quoted currency |
| » attach_algo | body | array[object] | No | Take-profit and stop-loss information | |
| »» tp_trigger_price | body | string | Yes | Take-profit trigger price | |
| »» tp_ord_price | body | string | Yes | Take-profit order price | -1 for market price, >0 for normal limit price |
| »» tp_ord_kind | body | string | Yes | Take-profit order type | 1 for trigger order/conditional order, 2 for limit order |
| »» sl_trigger_price | body | string | Yes | Stop-loss trigger price | |
| »» sl_ord_price | body | string | Yes | Stop-loss order price | -1 for market price, >0 for normal limit price |
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": {
"order_id": "2508810000100425939"
}
}
| Name | Type | Explanation | Description |
|---|---|---|---|
| » code | integer | Status code | |
| » msg | string | Description | |
| » data | object | Data | |
| »» order_id | string | Order identifier |
Spot Batch Order Placement
Rate Limit: 3 requests per second
HTTP Request
POST /v2/trade/spot/batch-orders
Request Parameters
Request Example
[
{
"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()
}
| Name | Location | Type | Required | Explanation | Description |
|---|---|---|---|---|---|
| body | body | array[object] | No | Array of orders | |
| » product_name | body | string | Yes | Product name | |
| » order_type | body | integer | Yes | Order type | See enumeration |
| » price | body | string | Yes | Price | |
| » amount | body | string | Yes | Order quantity | |
| » order_buy_or_sell | body | integer | Yes | Buy or sell direction | 1 for buy, 2 for sell |
| » trade_ccy | body | integer | Yes | Unit for market order | 1 for trading currency, 2 for quoted currency |
| » attach_algo | body | array[object] | No | Take-profit and stop-loss information | |
| »» tp_trigger_price | body | string | Yes | Take-profit trigger price | |
| »» tp_ord_price | body | string | Yes | Take-profit order price | -1 for market price, >0 for normal limit price |
| »» tp_ord_kind | body | string | Yes | Take-profit order type | 1 for trigger order/conditional order, 2 for limit order |
| »» sl_trigger_price | body | string | Yes | Stop-loss trigger price | |
| »» sl_ord_price | body | string | Yes | Stop-loss order price | -1 for market price, >0 for normal limit price |
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": [
{
"code": 200,
"order_id": "2509820413501205367"
}
]
}
| Name | Type | Description |
|---|---|---|
| » code | integer | Status code |
| » msg | string | Description message |
| » data | array[object] | Data array |
| »» code | integer | Status subcode |
| »» order_id | string | Order identifier |
Place Swap Order
Rate Limit: 3 requests per second
HTTP Request
POST /v2/trade/swap/order
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Explanation | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » order_type | body | integer | Yes | Order type | See enumeration |
| » number | body | integer | Yes | Contract quantity | |
| » price | body | string | Yes | Price | |
| » amount | body | string | No | Market order amount | |
| » trade_ccy | body | integer | No | Unit for market order | 1 for contract quantity, 2 for quoted currency |
| » pos_side | body | string | Yes | Position direction | LG for long, ST for short |
| » order_buy_or_sell | body | integer | Yes | Buy or sell direction | 1 for buy, 2 for sell |
| » attach_algo | body | array[object] | No | Take-profit and stop-loss information | |
| »» tp_trigger_price | body | string | Yes | Take-profit trigger price | |
| »» tp_ord_price | body | string | Yes | Take-profit order price | -1 for market order, >0 for normal limit price |
| »» tp_ord_kind | body | integer | Yes | Take-profit order type | 1 for trigger order/conditional order, 2 for limit order |
| »» tp_compare | body | integer | Yes | Take-profit trigger price comparison | 1: Index price, 2: Mark price, 3: Last traded price |
| »» sl_trigger_price | body | string | Yes | Stop-loss trigger price | |
| »» sl_ord_price | body | string | Yes | Stop-loss order price | -1 for market order, >0 for normal limit price |
| »» sl_compare | body | integer | Yes | Stop-loss trigger price comparison | 1: Index price, 2: Mark price, 3: Last traded price |
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": {
"order_id": "2517820683201827363"
}
}
| Name | Type | Explanation | Description |
|---|---|---|---|
| » code | integer | Status code | |
| » msg | string | Description | |
| » data | object | Data | |
| »» order_id | string | Order identifier |
Swap Batch Order Placement
Rate Limit: 3 requests per second
HTTP Request
POST /v2/trade/swap/batch-orders
Request Parameters
Request Example
[
{
"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()
}
| Name | Location | Type | Required | Explanation | Description |
|---|---|---|---|---|---|
| body | body | array[object] | No | Array of orders | |
| » product_name | body | string | Yes | Product name | |
| » order_type | body | integer | Yes | Order type | See enumeration |
| » number | body | integer | Yes | Contract quantity | |
| » price | body | string | Yes | Price | |
| » amount | body | string | No | Market order amount | |
| » trade_ccy | body | integer | No | Unit for market order | 1 for contract quantity, 2 for quoted currency |
| » pos_side | body | string | Yes | Position direction | LG for long, ST for short |
| » order_buy_or_sell | body | integer | Yes | Buy or sell direction | 1 for buy, 2 for sell |
| » attach_algo | body | array[object] | No | Take-profit and stop-loss information | |
| »» tp_trigger_price | body | string | Yes | Take-profit trigger price | |
| »» tp_ord_price | body | string | Yes | Take-profit order price | -1 for market order, >0 for normal limit price |
| »» tp_ord_kind | body | integer | Yes | Take-profit order type | 1 for trigger order/conditional order, 2 for limit order |
| »» tp_compare | body | integer | Yes | Take-profit trigger price comparison | 1: Index price, 2: Mark price, 3: Last traded price |
| »» sl_trigger_price | body | string | Yes | Stop-loss trigger price | |
| »» sl_ord_price | body | string | Yes | Stop-loss order price | -1 for market order, >0 for normal limit price |
| »» sl_compare | body | integer | Yes | Stop-loss trigger price comparison | 1: Index price, 2: Mark price, 3: Last traded price |
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": [
{
"order_id": "2517720561802636780"
},
{
"order_id": "2517720561802636781"
}
]
}
| Name | Type | Description |
|---|---|---|
| » code | integer | Status code |
| » msg | string | Description message |
| » data | array[object] | Data array |
| »» code | integer | Status subcode |
| »» order_id | string | Order identifier |
Close Swap Positions
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/close-position
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » pos_side | body | string | Yes | Position direction | LG for long, ST for short |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Constraints | Explanation | Description |
|---|---|---|---|---|---|
| code | integer | true | none | Status code | |
| msg | string | true | none | Description | |
| data | object | true | none | Data |
Adjust Swap Position Leverage
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/position/set-leverage
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » leverage | body | integer | Yes | New leverage | |
| » pos_side | body | string | Yes | Position direction | LG for long, ST for short |
| » mgn_mode | body | integer | Yes | Margin mode | 1 for isolated, 2 for cross |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Adjust Swap Position Margin
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/position/margin-balance
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » type | body | string | Yes | Type | add for increase, reduce for decrease |
| » amount | body | string | Yes | Margin amount | |
| » pos_side | body | string | Yes | Position direction | LG for long, ST for short |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Modify Swap User Leverage Configuration
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/config/set-leverage
Request Parameters
Note:
- If pos_mode is 1, both long_leverage and short_leverage must be provided.
- If pos_mode is 2, one_way_leverage must be provided.
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » long_leverage | body | integer | Yes | Long position leverage | Required if pos_mode is 1 |
| » short_leverage | body | integer | Yes | Short position leverage | Required if pos_mode is 1 |
| » one_way_leverage | body | integer | Yes | One-way position leverage | Required if pos_mode is 2 |
| » pos_mode | body | integer | Yes | Position mode | 1 for two-way, 2 for one-way |
| » mgn_mode | body | integer | Yes | Margin mode | 1 for isolated, 2 for cross |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Modify Swap User Margin Mode
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/config/set-mgn
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » product_name | body | string | Yes | Product name | |
| » mgn_mode | body | integer | Yes | Margin mode | 1 for isolated, 2 for cross |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Modify Swap User Position Mode
Rate Limit: 3 requests per second
HTTP Request
PUT /v2/trade/swap/config/set-pos-mod
Request Parameters
Request Example
{
"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()
}
| Name | Location | Type | Required | Description | Description |
|---|---|---|---|---|---|
| body | body | object | No | ||
| » pos_mode | body | integer | Yes | Position mode | 1 for two-way, 2 for one-way |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Cancel Order
Rate Limit: 3 times/second
HTTP Request
PUT /v2/trade/cancel-order
Request Parameters
Request Example
{
"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()
}
| Name | Position | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| body | body | object | No | None | None |
| » inst_type | body | integer | Yes | Business Type | 1: Spot, 2: Swap |
| » cancel_ord_type | body | integer | Yes | Order Cancellation Type | 1: Limit/Advanced Limit Order, 2: Take Profit/Stop Loss Order, 3: Scheduled Order, 4: Trailing Take Profit/Stop Loss Order |
| » order_id | body | string | Yes | Order ID | None |
Response Parameters
Response Example
{
"code": 200,
"msg": "string",
"data": {}
}
| Name | Type | Required | Explanation | Description |
|---|---|---|---|---|
| code | integer | true | Status code | |
| msg | string | true | Description | |
| data | object | false | Response payload |
Cancel Batch Orders
Rate Limit: 3 times/second
HTTP Request
PUT /v2/trade/cancel-batch-order
Request Parameters
Request Example
{
"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()
}
| Name | Position | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| body | body | object | No | None | None |
| » inst_type | body | integer | Yes | Business Type | 1: Spot, 2: Swap |
| » cancel_ord_type | body | integer | Yes | Order Cancellation Type | 1: Limit/Advanced Limit Order, 2: Take Profit/Stop Loss Order, 3: Scheduled Order, 4: Trailing Take Profit/Stop Loss Order |
| » order_ids | body | [string] | Yes | List of Order IDs | None |
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": [
{
"code": 200,
"order_id": "2509820413501205367"
},
{
"code": 200,
"order_id": "2509820413501205368"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | array[object] | Data | none |
| »» code | integer | none | |
| »» order_id | string | none |
Current Orders
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/orders
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| product_name | query | string | No | Product name |
Response Parameters
Response Example
{
"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
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | array[object] | Array of order data | |
| » product_name | string | Product name | |
| » order_id | string | Order identifier | |
| » mgn_mode | integer | Margin mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_side | string | Position side | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_mode | integer | Order mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_mode | integer | Position mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_type | integer | Order type | |
| » pos_opt | integer | Position option | Applicable only to contract business (USDT-margined & coin-margined) |
| » leverage | string | Leverage value | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_buy_or_sell | integer | Trade direction (buy/sell) | |
| » number | string | Contract quantity | Applicable only to contract business (USDT-margined & coin-margined) |
| » amount | string | Order amount | Applicable only to contract business (USDT-margined & coin-margined) |
| » deal_number | string | Filled quantity | Filled base currency amount |
| » lock_base_amount | string | Locked base currency amount | Applicable only to spot business |
| » lock_quote_amount | string | Locked quote currency amount | Applicable only to spot business |
| » filled_quote_amount | string | Filled quote currency amount | Applicable only to spot business |
| » price | string | Order price | |
| » status | integer | Order status | |
| » avg_price | string | Average filled price | |
| » deal_fee | string | Transaction fee | |
| » income | string | Profit/loss | Applicable only to contract business (USDT-margined & coin-margined) |
| » created_at | integer | Creation timestamp | |
| » finish_at | integer | Completion timestamp | |
| » ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| » algo_info | string | Algorithmic order details | |
| » coin | string | Quote coin name | |
| » un_filled_amount | string | Remaining quantity | Applicable only to contract business (USDT-margined & coin-margined) |
Historical Orders
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/history/orders
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| product_name | query | string | No | Product name | |
| begin | query | integer | No | Start timestamp | Millisecond |
| end | query | integer | No | End timestamp | Millisecond |
| limit | query | integer | No | Number of records | Default 20, max 20 |
Response Parameters
Response Example
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | array[object] | Array of order data | |
| » product_name | string | Product name | |
| » order_id | string | Order identifier | |
| » mgn_mode | integer | Margin mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_side | string | Position side | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_mode | integer | Order mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_mode | integer | Position mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_type | integer | Order type | |
| » pos_opt | integer | Position option | Applicable only to contract business (USDT-margined & coin-margined) |
| » leverage | string | Leverage value | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_buy_or_sell | integer | Trade direction (buy/sell) | |
| » number | string | Contract quantity | Applicable only to contract business (USDT-margined & coin-margined) |
| » amount | string | Order amount | |
| » deal_number | string | Filled quantity | Filled base currency amount |
| » lock_base_amount | string | Locked base currency amount | Applicable only to spot business |
| » lock_quote_amount | string | Locked quote currency amount | Applicable only to spot business |
| » filled_quote_amount | string | Filled quote currency amount | Applicable only to spot business |
| » price | string | Order price | |
| » status | integer | Order status | |
| » avg_price | string | Average filled price | |
| » deal_fee | string | Transaction fee | |
| » income | string | Profit/loss | Applicable only to contract business (USDT-margined & coin-margined) |
| » created_at | integer | Creation timestamp | |
| » finish_at | integer | Completion timestamp | |
| » ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| » algo_info | string | Algorithmic order details | |
| » coin | string | Quote coin name |
Current Positions
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/positions
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SWAP - USDT-margined, BASE - Coin-margined |
| product_name | query | string | No | Product name |
Response Parameters
Response Example
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | array[object] | Array of current positions | |
| » product_name | string | Product name | |
| » position_id | string | Position identifier | |
| » ins_type | string | Product type | SWAP - USDT-margined, BASE - Coin-margined |
| » mgn_mode | integer | Margin mode | |
| » pos_mode | integer | Position mode | |
| » leverage | integer | Leverage multiplier | |
| » side | string | Position direction (long/short) | |
| » hold_position_amount | integer | Current position size | |
| » margin | string | Collateral amount | Modifiable for isolated positions |
| » total_fee | string | Total fees paid | |
| » status | integer | Position state | 1: Open, 2: Closed, 3: Liquidated |
| » force_close_price | string | Liquidation price level | |
| » position_avg_price | string | Average entry price | |
| » deal_avg_price | string | Average exit price | |
| » income | string | Realized profit/loss | |
| » begin_order_id | string | Initial opening order ID | |
| » created_at | integer | Position creation timestamp | |
| » updated_at | integer | Last update timestamp | |
| » close_num | integer | Number of closed contracts | |
| » open_num | integer | Number of open contracts | |
| » bankrupt_price | string | Bankruptcy price level | |
| » force_trigger_price | string | Liquidation trigger threshold | |
| » adl_num | integer | ADL (Auto-Deleveraging) event count | |
| » adl_deal_price | string | Average ADL execution price | |
| » adl_income | string | P/L from ADL events | |
| » funding_fee | string | Accumulated funding payments |
Historical Positions
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/history/positions
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SWAP - USDT-margined, BASE - Coin-margined |
| product_name | query | string | No | Product name | |
| mgn_mode | query | integer | No | Margin mode | 1 for isolated, 2 for cross |
| begin | query | integer | No | Start timestamp | Millisecond |
| end | query | integer | No | End timestamp | Millisecond |
| limit | query | integer | No | Number of records | Default 20, max 20 |
Response Parameters
Response Example
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | array[object] | Array of current positions | |
| » product_name | string | Product name | |
| » position_id | string | Position identifier | |
| » ins_type | string | Product type | SWAP - USDT-margined, BASE - Coin-margined |
| » mgn_mode | integer | Margin mode | |
| » pos_mode | integer | Position mode | |
| » leverage | integer | Leverage multiplier | |
| » side | string | Position direction (long/short) | |
| » hold_position_amount | integer | Current position size | |
| » margin | string | Collateral amount | Modifiable for isolated positions |
| » total_fee | string | Total fees paid | |
| » status | integer | Position state | 1: Open, 2: Closed, 3: Liquidated |
| » force_close_price | string | Liquidation price level | |
| » position_avg_price | string | Average entry price | |
| » deal_avg_price | string | Average exit price | |
| » income | string | Realized profit/loss | |
| » begin_order_id | string | Initial opening order ID | |
| » created_at | integer | Position creation timestamp | |
| » updated_at | integer | Last update timestamp | |
| » close_num | integer | Number of closed contracts | |
| » open_num | integer | Number of open contracts | |
| » bankrupt_price | string | Bankruptcy price level | |
| » force_trigger_price | string | Liquidation trigger threshold | |
| » adl_num | integer | ADL (Auto-Deleveraging) event count | |
| » adl_deal_price | string | Average ADL execution price | |
| » adl_income | string | P/L from ADL events | |
| » funding_fee | string | Accumulated funding payments |
Get Order Details
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/order/details
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| order_id | query | string | Yes | Order ID |
Response Parameters
Response Example
{
"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
}
]
}
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | object | Order details | |
| » product_name | string | Trading pair/product name | |
| » order_id | string | Unique order identifier | |
| » mgn_mode | integer | Margin account type | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_side | string | Position direction (long/short) | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_mode | integer | Order execution type | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_mode | integer | Position holding mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_type | integer | Order type (limit/market/etc) | |
| » pos_opt | integer | Position operation type | Applicable only to contract business (USDT-margined & coin-margined) |
| » leverage | integer | Leverage multiplier | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_buy_or_sell | integer | Trade direction (buy=1/sell=2) | |
| » number | integer | Total contract quantity | Applicable only to contract business (USDT-margined & coin-margined) |
| » amount | string | Frozen collateral amount | |
| » deal_number | integer | Filled contract quantity | Filled base currency amount |
| » lock_base_amount | string | Locked base currency amount | Applicable only to spot business |
| » lock_quote_amount | string | Locked quote currency amount | Applicable only to spot business |
| » filled_quote_amount | string | Filled quote currency amount | Applicable only to spot business |
| » price | string | Order price | |
| » status | integer | Current order state | |
| » avg_price | string | Volume-weighted average fill price | |
| » deal_fee | string | Total fees paid | |
| » income | string | Realized profit/loss | Applicable only to contract business (USDT-margined & coin-margined) |
| » created_at | integer | Order creation timestamp | |
| » finish_at | integer | Order completion timestamp | |
| » ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| » algo_info | object | TP/SL order details | |
| » coin | string | Quote coin name | |
| » bills | array[object] | Array of trade executions | |
| »» bill_id | string | Unique trade ID | |
| »» product_name | string | Trading pair | |
| »» order_id | string | Parent order ID | |
| »» position_id | string | Associated position ID | Applicable only to contract business (USDT-margined & coin-margined) |
| »» mgn_mode | integer | Margin mode | Applicable only to contract business (USDT-margined & coin-margined) |
| »» role | string | Maker or taker | |
| »» order_mode | integer | Order execution mode | Applicable only to contract business (USDT-margined & coin-margined) |
| »» pos_side | string | Position direction | Applicable only to contract business (USDT-margined & coin-margined) |
| »» pos_opt | integer | Position operation | Applicable only to contract business (USDT-margined & coin-margined) |
| »» filled_amount | string | Filled quantity | |
| »» price | string | Execution price | |
| »» fee | string | Trade fee | |
| »» margin | string | Margin used | Applicable only to contract business (USDT-margined & coin-margined) |
| »» leverage | integer | Leverage at execution | Applicable only to contract business (USDT-margined & coin-margined) |
| »» income | string | PnL from this trade | Applicable only to contract business (USDT-margined & coin-margined) |
| »» taker_fee | string | Taker fee rate | |
| »» maker_fee | string | Maker fee rate | |
| »» order_buy_or_sell | integer | Trade direction | |
| »» created_at | integer | Trade timestamp | |
| »» ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| »» order_type | integer | Order type |
Get Historical Order Details
Rate Limit: 10 requests per second
HTTP Request
GET /v2/trade/history/order/details
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Product type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| order_id | query | string | Yes | Order ID |
Response Parameters
Response Example
{
"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
}
]
}
}
| Name | Type | Description | Notes |
|---|---|---|---|
| code | integer | Status code | |
| msg | string | Description message | |
| data | object | Order details | |
| » product_name | string | Trading pair/product name | |
| » order_id | string | Unique order identifier | |
| » mgn_mode | integer | Margin account type | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_side | string | Position direction (long/short) | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_mode | integer | Order execution type | Applicable only to contract business (USDT-margined & coin-margined) |
| » pos_mode | integer | Position holding mode | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_type | integer | Order type (limit/market/etc) | |
| » pos_opt | integer | Position operation type | Applicable only to contract business (USDT-margined & coin-margined) |
| » leverage | integer | Leverage multiplier | Applicable only to contract business (USDT-margined & coin-margined) |
| » order_buy_or_sell | integer | Trade direction (buy=1/sell=2) | |
| » number | integer | Total contract quantity | Applicable only to contract business (USDT-margined & coin-margined) |
| » amount | string | Frozen collateral amount | |
| » deal_number | integer | Filled contract quantity | Filled base currency amount |
| » lock_base_amount | string | Locked base currency amount | Applicable only to spot business |
| » lock_quote_amount | string | Locked quote currency amount | Applicable only to spot business |
| » filled_quote_amount | string | Filled quote currency amount | Applicable only to spot business |
| » price | string | Order price | |
| » status | integer | Current order state | |
| » avg_price | string | Volume-weighted average fill price | |
| » deal_fee | string | Total fees paid | |
| » income | string | Realized profit/loss | Applicable only to contract business (USDT-margined & coin-margined) |
| » created_at | integer | Order creation timestamp | |
| » finish_at | integer | Order completion timestamp | |
| » ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| » algo_info | object | TP/SL order details | |
| » coin | string | Quote coin name | |
| » bills | array[object] | Array of trade executions | |
| »» bill_id | string | Unique trade ID | |
| »» product_name | string | Trading pair | |
| »» order_id | string | Parent order ID | |
| »» position_id | string | Associated position ID | Applicable only to contract business (USDT-margined & coin-margined) |
| »» mgn_mode | integer | Margin mode | Applicable only to contract business (USDT-margined & coin-margined) |
| »» role | string | Maker or taker | |
| »» order_mode | integer | Order execution mode | Applicable only to contract business (USDT-margined & coin-margined) |
| »» pos_side | string | Position direction | Applicable only to contract business (USDT-margined & coin-margined) |
| »» pos_opt | integer | Position operation | Applicable only to contract business (USDT-margined & coin-margined) |
| »» filled_amount | string | Filled quantity | |
| »» price | string | Execution price | |
| »» fee | string | Trade fee | |
| »» margin | string | Margin used | Applicable only to contract business (USDT-margined & coin-margined) |
| »» leverage | integer | Leverage at execution | Applicable only to contract business (USDT-margined & coin-margined) |
| »» income | string | PnL from this trade | Applicable only to contract business (USDT-margined & coin-margined) |
| »» taker_fee | string | Taker fee rate | |
| »» maker_fee | string | Maker fee rate | |
| »» order_buy_or_sell | integer | Trade direction | |
| »» created_at | integer | Trade timestamp | |
| »» ins_type | string | Instrument type | SPOT - Spot, SWAP - USDT-margined, BASE - Coin-margined |
| »» order_type | integer | Order type |
Funding Account
The API interfaces under the Funding Account module require authentication.
Get Account Balance
Rate Limit: 10 requests/second
HTTP Request
GET /v2/asset/balances
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| coins | query | string | No | Currency names | BTC,USDT |
| omit_zero | query | boolean | No | Whether to hide zero balances |
Response Parameters
Example Response
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status code | |
| » msg | string | Message | |
| » data | array[object] | Balance data | |
| »» coin | string | Currency name | |
| »» balance | string | Total balance | |
| »» frozen_balance | string | Frozen balance | |
| »» available_balance | string | Available balance |
Get Account Transaction History (Last 7 Days)
Rate Limit: 10 requests/second
HTTP Request
GET /v2/asset/bills
Request Parameters
| Name | Location | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| bill_type | query | integer | No | Bill type | |
| begin | query | integer | No | Start timestamp (ms) | |
| end | query | integer | No | End timestamp (ms) | |
| limit | query | integer | No | Pagination limit (default: 20) |
Response Parameters
Example Response
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status code | |
| » msg | string | Message | |
| » data | array[object] | Transaction data | |
| »» coin_name | string | Currency name | |
| »» bill_type | integer | Transaction type | |
| »» trade_direction | integer | Flow direction | |
| »» amount | string | Transaction amount | |
| »» note | string | Remarks | |
| »» created_at | integer | Timestamp (ms) | |
| »» log_id | string | Transaction ID |
Trading Account
The API interfaces under the Trading Account module require authentication.
Get Trading Account Balances
Rate Limit: 10 times/second
HTTP Request
GET /v2/account/balances
Request Parameters
| Name | Position | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| coins | query | string | No | Coin Names | Example: BTC,USDT |
| omit_zero | query | boolean | No | Hide Zero Values | None |
Response Parameters
Response Example
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | array[object] | Data | none |
| »» coin | string | Coin Type | none |
| »» balance | string | Total Balance | none |
| »» available_balance | string | Available Balance | none |
| »» isolated_frozen_balance | string | Isolated Positions Frozen Balance | none |
| »» cross_frozen_balance | string | Cross Positions Frozen Balance | none |
| »» frozen_balance | string | Total Frozen Balance | none |
| »» order_frozen_balance | string | Order Frozen Balance | none |
Get Trading Account Statements (Last 7 Days)
Rate Limit: 10 times/second
HTTP Request
GET /v2/account/bills
Request Parameters
| Name | Position | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Instrument Type | SPOT - Spot, SWAP - USDt-denominated, OTHER_BILL - Other |
| coin | query | string | No | Coin Name | None |
| bill_type | query | integer | No | Main Bill Type | See Enumeration |
| sub_bill_type | query | integer | No | Sub Bill Type | See Enumeration |
| begin | query | integer | No | Start Timestamp | Millisecond |
| end | query | integer | No | End Timestamp | Millisecond |
| limit | query | integer | No | Number of Records | Default: 20, Max: 20 |
Response Parameters
Response Example
{
"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"
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | array[object] | Data | none |
| »» ins_type | string | Instrument Type | none |
| »» product_name | string | Product Name | none |
| »» coin_name | string | Coin Name | none |
| »» bill_type | integer | Main Bill Type | none |
| »» sub_bill_type | integer | Sub Bill Type | none |
| »» mgn_mode | integer | Margin Mode | none |
| »» role | string | Role | none |
| »» trade_direction | integer | Trade Direction | none |
| »» amount | string | Amount | none |
| »» experience_amount | string | Experience Amount | none |
| »» fee_amount | string | Fee Amount | none |
| »» price | string | Trade Price | none |
| »» income | string | Income | none |
| »» created_at | integer | Creation Time | none |
| »» log_id | string | Log ID | none |
Spot Market Data
API interfaces under the Spot Market Data module do not require authentication.
Spot Candlestick Data
Returns candlestick data. The candlestick intervals are calculated based on Shanghai time.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/{symbol}/candles
Request Parameters
Request Example
GET /notification/spot/BTC-USDT/candles?size=10&interval=1min
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| size | query | integer | Yes | Number of Records: Maximum 2000 |
| start | query | integer | Yes | Start Timestamp (seconds) |
| end | query | integer | Yes | End Timestamp (seconds) |
| interval | query | string | Yes | Time Interval: See enumeration |
Response Parameters
Response Example
{
"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"
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » symbol | string | Trading Pair Name | none |
| » interval | string | Candlestick Type | none |
| » msg | string | Description Message | none |
| » code | integer | Status Code | none |
| » ts | string | Timestamp in Milliseconds | none |
| » data | array[object] | Data | none |
| »» open | string | Open Price | none |
| »» close | string | Close Price | none |
| »» high | string | High Price | none |
| »» low | string | Low Price | none |
| »» turn_over | string | Turnover | none |
| »» vol | string | Volume | none |
| »» count | integer | Number of Trades | none |
Spot Order Book
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/{symbol}/orderbook
Request Parameters
Request Example
GET /notification/spot/BTC-USDT/orderbook?interval=step0
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair |
| interval | query | string | Yes | Depth Level (step0-step3) |
Response Parameters
Response Example
{
"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"
}
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » interval | string | Depth Level | none |
| » msg | string | Description Message | none |
| » status | string | Status | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » type | string | Type | none |
| » data | object | Data | none |
| »» bids | [array] | Buy Orders | Array of [price, quantity] |
| »» asks | [array] | Sell Orders | Array of [price, quantity] |
| »» ts | integer | Timestamp in Milliseconds | 13-digit timestamp |
| »» type | string | Request Method | none |
| »» product_name | string | Product Name | none |
| »» interval | string | Depth Level | none |
Spot Tickers
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/tickers
Request Parameters
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » data | array[object] | Data | none |
| »» market | object | Market Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »»» turn_over | string | Turnover | none |
| »»» count | integer | Trade Count | none |
| »»» vol | string | Volume | none |
| »»» change | string | 24-hour Change | none |
| »»» change_percent | string | 24-hour Change Percentage | none |
| »» symbol | string | Symbol | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
Spot Ticker
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/{symbol}/ticker
Request Parameters
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » data | object | Data | none |
| »» market | object | Market Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »»» turn_over | string | Turnover | none |
| »»» count | integer | Trade Count | none |
| »»» vol | string | Volume | none |
| »»» change | string | 24-hour Change | none |
| »»» change_percent | string | 24-hour Change Percentage | none |
| »» symbol | string | Symbol | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
Spot Trade Record
The most recent trade record.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/{symbol}/trade
Request Parameters
Request Example
GET /notification/spot/BTC-USDT/trade
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair |
Response Parameters
Response Example
{
"code": 200,
"data": {
"data": [
{
"direction": "sell",
"price": "102680.546869",
"ts": 1746759096603,
"vol": "0.04"
}
],
"ts": 1746759097067
},
"msg": "success",
"ts": 1746759097067,
"type": "swap.detail"
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » data | object | Data | none |
| »» data | array[object] | Trade Records | none |
| »»» direction | string | Trade Direction | sell, buy |
| »»» price | string | Trade Price | none |
| »»» ts | integer | Timestamp in Milliseconds | none |
| »»» vol | string | Trade Volume | none |
| »» ts | integer | Timestamp | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp | none |
Spot Batch Trade Records
Retrieve the most recent trade records up to a specified number.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/spot/{symbol}/trades
Request Parameters
Request Example
GET /notification/spot/BTC-USDT/trades?size=10
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair |
| size | query | int | Yes | Number of Records, Maximum 2000 |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » data | array[object] | Data | none |
| »» data | array[object] | Trade Records | none |
| »»» direction | string | Trade Direction | sell, buy |
| »»» price | string | Trade Price | none |
| »»» ts | integer | Timestamp in Milliseconds | none |
| »»» vol | string | Trade Volume | none |
| »» product_name | string | Product Name | none |
| »» ts | integer | Timestamp in Milliseconds | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
Spot Historical Trade Records
Retrieves historical trade information in the market; paginated data for the last 3 months is supported.
Rate Limit: 20 requests per 2 seconds
Limit Rule: IP-based
HTTP Request
GET /notification/spot/{symbol}/history-trades
Request Parameters
Request Example
GET /notification/spot/BTC-USDT/history-trades?size=10
| Name | Location | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading pair name |
| size | query | integer | No | Number of records (max 100). Default is 100 when omitted. |
| after | query | integer | No | Millisecond timestamp. Use the last record’s timestamp from the previous response to paginate backwards. |
Response Parameters
Response Example
{
"code": 200,
"data": [
{
"ts": 1752557507585,
"direction": "buy",
"price": "108640.42",
"vol": "0.0002",
"id": 184664390001
}
],
"msg": "success",
"ts": 1752725468921
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status code | |
| » data | array[object] | Trade data | |
| »» direction | string | Trade side | sell or buy |
| »» price | string | Trade price | |
| »» ts | integer | Millisecond timestamp | |
| »» vol | string | Trade volume | |
| »» id | integer | Trade ID | |
| » msg | string | Description | |
| » ts | integer | Response timestamp |
Swap Market Data
API interfaces under the Swap Market Data module do not require authentication.
Swap Candlestick Data
Returns candlestick data. The candlestick intervals are calculated based on Shanghai time.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/candles
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/candles?size=10&interval=1min
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| interval | query | string | Yes | Candlestick Type, See Enumeration |
| size | query | integer | Yes | Number of Records, Maximum 2000 |
| start | query | integer | Yes | Start Timestamp (seconds) |
| end | query | integer | Yes | End Timestamp (seconds) |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » data | array[object] | Data | none |
| »» open | string | Open Price | none |
| »» close | string | Close Price | none |
| »» high | string | High Price | none |
| »» low | string | Low Price | none |
| »» turn_over | string | Turnover | none |
| »» vol | string | Volume | none |
| »» count | integer | Number of Trades | none |
| » msg | string | Description Message | none |
| » symbol | string | Trading Pair Name | none |
| » interval | string | Candlestick Type | none |
| » ts | integer | Timestamp in Milliseconds | none |
Swap Order Book
Retrieve market depth information for a product.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/orderbook
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/orderbook?interval=step0
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| interval | query | string | No | depth step0-step3 |
Response Parameters
Response Example
{
"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"
}
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » interval | string | Depth Level | none |
| » msg | string | Description Message | none |
| » status | string | Status | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » type | string | Type | none |
| » data | object | Data | none |
| »» bids | [array] | Buy Orders | Array of [price, quantity] |
| »» asks | [array] | Sell Orders | Array of [price, quantity] |
| »» ts | integer | Timestamp in Milliseconds | 13-digit timestamp |
| »» type | string | Request Method | none |
| »» product_name | string | Product Name | none |
| »» interval | string | Depth Level | none |
Swap Ticker
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/ticker
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/ticker
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | object | Data | none |
| »» market | object | Market Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »»» turn_over | string | Turnover | none |
| »»» count | integer | Trade Count | none |
| »»» vol | string | Volume | none |
| »»» change | string | 24-hour Change | none |
| »»» change_percent | string | 24-hour Change Percentage | none |
| »» index | object | Index Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »» tag | object | Tag Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »» funding_rate | string | Funding Rate | none |
| »» funding_next_time | integer | Next Funding Time | Unix timestamp in seconds |
| »» pre_funding_rate | string | Predicted Funding Rate | none |
| »» symbol | string | Symbol | none |
| »» risk_fund | string | Risk Fund Balance | none |
Swap Tickers
Retrieve market data for multiple products, including the latest 24-hour aggregated trading information.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/tickers
Request Parameters
Request Example
GET /notification/swap/tickers
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | array[object] | Data | none |
| »» market | object | Market Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »»» turn_over | string | Turnover | none |
| »»» count | string | Trade Count | none |
| »»» vol | string | Volume | none |
| »»» change | string | 24-hour Change | none |
| »»» change_percent | string | 24-hour Change Percentage | none |
| »» index | object | Index Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »» tag | object | Tag Data | none |
| »»» open | string | Open Price | none |
| »»» close | string | Close Price | none |
| »»» low | string | Low Price | none |
| »»» high | string | High Price | none |
| »» funding_rate | string | Funding Rate | none |
| »» funding_next_time | integer | Next Funding Time | Unix timestamp in seconds |
| »» pre_funding_rate | string | Predicted Funding Rate | none |
| »» symbol | string | Symbol | none |
| »» risk_fund | string | Risk Fund Balance | none |
Swap Trade Record
Retrieve the most recent trade record for a specific contract.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/trade
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/trade
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
Response Parameters
Response Example
{
"code": 200,
"data": {
"data": [
{
"direction": "buy",
"price": "102736.9001",
"ts": 1746766999793,
"vol": "79300"
}
],
"ts": 1746766999982
},
"msg": "success",
"ts": 1746766999982,
"type": "swap.detail"
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | object | Data | none |
| »» data | array[object] | Trade Records | none |
| »»» direction | string | Trade Direction | sell, buy |
| »»» price | string | Trade Price | none |
| »»» ts | integer | Timestamp in Milliseconds | none |
| »»» vol | string | Trade Volume | none |
| »» ts | integer | Timestamp in Milliseconds | none |
Swap Batch Trade Records
Retrieve the most recent trade records for a specific contract, up to a specified number.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/trades
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/trades?size=10
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| size | query | int | Yes | Number of Records, Maximum 2000 |
Response Parameters
Response Example
{
"code": 200,
"data": {
"data": [
{
"direction": "sell",
"price": "102771.2",
"ts": 1746767096612,
"vol": "1"
}
],
"ts": 1746767097114
},
"msg": "success",
"ts": 1746767097114,
"type": "swap.detail"
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | object | Data | none |
| »» data | array[object] | Trade Records | none |
| »»» direction | string | Trade Direction | sell, buy |
| »»» price | string | Trade Price | none |
| »»» ts | integer | Timestamp in Milliseconds | none |
| »»» vol | string | Trade Volume | none |
| »» ts | integer | Timestamp in Milliseconds | none |
Swap Historical Trade Records
Retrieves historical trade information in the market; paginated data for the last 3 months is supported.
Rate Limit: 20 requests per 2 seconds
Limit Rule: IP-based
HTTP Request
GET /notification/swap/{symbol}/history-trades
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/history-trades?size=10
| Name | Location | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading pair name |
| size | query | integer | No | Number of records (max 100). Default is 100 when omitted. |
| after | query | integer | No | Millisecond timestamp. Use the last record’s timestamp from the previous response to paginate backwards. |
Response Parameters
Response Example
{
"code": 200,
"data": [
{
"ts": 1752557507585,
"direction": "buy",
"price": "108640.42",
"vol": "0.0002",
"id": 184664390001
}
],
"msg": "success",
"ts": 1752725468921
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status code | |
| » data | array[object] | Trade data | |
| »» direction | string | Trade side | sell or buy |
| »» price | string | Trade price | |
| »» ts | integer | Millisecond timestamp | |
| »» vol | string | Trade volume | |
| »» id | integer | Trade ID | |
| » msg | string | Description | |
| » ts | integer | Response timestamp |
Index Candlestick Data
Retrieve index candlestick data.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/index
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/index?size=10&interval=1min
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| interval | query | string | Yes | Candlestick Type, See Enumeration |
| size | query | integer | Yes | Number of Records, Maximum 2000 |
| start | query | integer | Yes | Start Timestamp (seconds) |
| end | query | integer | Yes | End Timestamp (seconds) |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » symbol | string | Trading Pair Name | none |
| » interval | string | Candlestick Type | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | array[object] | Data | none |
| »» open | string | Open Price | none |
| »» close | string | Close Price | none |
| »» high | string | High Price | none |
| »» low | string | Low Price | none |
| »» turn_over | string | Turnover | none |
| »» vol | string | Volume | none |
| »» count | integer | Trade Count | none |
Mark Price Candlestick Data
Retrieve mark price candlestick data.
Rate Limit: 20 times/2 seconds
Rate Limiting Rule: IP
HTTP Request
GET /notification/swap/{symbol}/tag
Request Parameters
Request Example
GET /notification/swap/BTCUSDT/tag?size=10&interval=1min
| Name | Position | Type | Required | Description |
|---|---|---|---|---|
| symbol | path | string | Yes | Trading Pair Name |
| interval | query | string | Yes | Candlestick Type, See Enumeration |
| size | query | integer | Yes | Number of Records, Maximum 2000 |
| start | query | integer | Yes | Start Timestamp (seconds) |
| end | query | integer | Yes | End Timestamp (seconds) |
Response Parameters
Response Example
{
"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
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » symbol | string | Trading Pair Name | none |
| » interval | string | Candlestick Type | none |
| » ts | integer | Timestamp in Milliseconds | none |
| » data | array[object] | Data | none |
| »» open | string | Open Price | none |
| »» close | string | Close Price | none |
| »» high | string | High Price | none |
| »» low | string | Low Price | none |
| »» turn_over | string | Turnover | none |
| »» vol | string | Volume | none |
| »» count | integer | Trade Count | none |
Public Data
The API interfaces under the Public Data feature module do not require authentication.
Get Server Time
Rate Limit: 10 times/second
HTTP Request
GET /v2/time
Response Parameters
Response Example
{
"code": 200,
"msg": "success",
"data": {
"server_time": 1746498430903
}
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | object | Data | none |
| »» server_time | integer | Server Time (ms) | none |
Get Coin List
Rate Limit: 10 times/second
HTTP Request
GET /v2/coins
Response Parameters
Response Example
{
"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
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | array[object] | Data | none |
| »» coin_name | string | Coin Name | none |
| »» icon | string | Icon URL | none |
| »» decimal | integer | Decimal Precision | none |
| »» can_deposit | boolean | Deposit Enabled | none |
| »» can_withdrawal | boolean | Withdrawal Enabled | none |
Get Product List
Rate Limit: 10 times/second
HTTP Request
GET /v2/products
Request Parameters
| Name | Position | Type | Required | Description | Notes |
|---|---|---|---|---|---|
| ins_type | query | string | No | Instrument Type | SPOT - Spot, SWAP - USDt-denominated, BASE - Coin-denominated |
| product_name | query | string | No | Product Name | None |
Response Parameters
Response Example
{
"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
}
]
}
| Name | Type | Description | Notes |
|---|---|---|---|
| » code | integer | Status Code | none |
| » msg | string | Description Message | none |
| » data | array[object] | Data | none |
| »» ins_type | string | Instrument Type | none |
| »» product_name | string | Product Name | none |
| »» base_coin_name | string | Base Coin Name | none |
| »» quote_coin_name | string | Quote Coin Name | none |
| »» price_precision | integer | Price Precision | Applicable for spot trading |
| »» num_precision | integer | Quantity Precision | Applicable for spot trading |
| »» max_once_vol | string | Maximum Single Trade Volume | Applicable for spot trading |
| »» max_once_amount | string | Maximum Single Trade Amount | Applicable for spot trading |
| »» min_once_vol | string | Minimum Single Trade Volume | Applicable for spot trading |
| »» min_once_amount | string | Minimum Single Trade Amount | Applicable for spot trading |
| »» swap_value | string | Contract Notional Value | Applicable for contract trading (U-based, Coin-based) |
| »» price_unit | string | Contract Price Increment | Applicable for contract trading (U-based, Coin-based) |
| »» max_leverage | integer | Maximum Leverage | Applicable for contract trading (U-based, Coin-based) |
| »» max_once_limit_num | integer | Maximum Limit Order Quantity per Trade | Applicable for contract trading (U-based, Coin-based) |
| »» max_once_market_num | integer | Maximum Market Order Quantity per Trade | Applicable for contract trading (U-based, Coin-based) |
| »» max_hold_num | integer | Maximum Position Quantity | Applicable for contract trading (U-based, Coin-based) |
| »» maintenance_margin_rate | string | Maintenance Margin Rate | Applicable for contract trading (U-based, Coin-based) |
| »» market_max_deeps | integer | Maximum Market Depth | none |
| »» max_book_num | integer | Maximum Open Orders | none |
WebSocket API
Overview
WebSocket is a new protocol introduced in HTML5. It enables full-duplex communication between the client and the server, allowing data to be transmitted bidirectionally in real-time. A simple handshake establishes the connection between the client and the server, and the server can proactively push information to the client based on business rules. Its advantages include:
- When transmitting data between the client and the server, the request header information is minimal, approximately 2 bytes.
- Both the client and the server can proactively send data to each other.
- There is no need to repeatedly create and destroy TCP connections, which saves bandwidth and server resources.
Connection
Connection Description:
Connection Limit: 1 time/second
When subscribing to public channels, use the public service address; when subscribing to private channels, use the private service address.
Subscription Limit: 240 times/hour
Subscription
Subscribe to the BTC-USDT spot candlestick chart.
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation sub |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Unsubscribe
Unsubscribe from the BTC-USDT spot candlestick chart.
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"unsub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation unsub |
| params | Yes | object | Subscription parameter information |
| >product | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "unsubbed",
"topic": "spot.BTC-USDT.kline.1min",
"status": "ok"
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| id | String | Ignore this field | |
| event | String | Event type | |
| topic | String | Topic name | |
| status | String | Status code |
Request Historical Data
Request historical 1-minute candlestick data for BTC-USDT.
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
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("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Event type req |
| params | Yes | Object | Request parameters |
| > symbol | Yes | String | Currency pair |
| > biz | Yes | String | Type market |
| > type | Yes | String | Channel type |
| > interval | Yes | String | Period |
| > size | Yes | Int | Number of records to query. Note that the interval between from and to should not exceed size, and size should not exceed 300. |
| > from | Yes | Integer | Start date for the query (in seconds) |
| > to | Yes | Integer | End date for the query (in seconds) |
| > id | Yes | String | Request Name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"data": [
{
"open": "109529.75",
"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"
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| data | Yes | Array | List of candlestick data |
| > close | Yes | String | Closing price of the period |
| > count | Yes | Integer | Number of trades |
| > high | Yes | String | Highest price of the period |
| > low | Yes | String | Lowest price of the period |
| > open | Yes | String | Opening price of the period |
| > turnOver | Yes | Integer | Total trade amount |
| > vol | Yes | String | Trade volume in the quoted currency |
| interval | Yes | String | Period |
| symbol | Yes | String | Currency pair |
| type | Yes | String | Channel type |
Swap Public Subscription
/notification/ws
Swap Candles
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.candles\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.kline.1min",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"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
}
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| >close | String | Closing price of the period |
| >count | Int | Number of trades |
| >high | String | Highest price of the period |
| >low | String | Lowest price of the period |
| >open | String | Opening price of the period |
| >turn_over | String | Total trade amount |
| >vol | String | Trade volume in the quoted currency |
| interval | String | Period |
| product_name | String | Product Name |
| type | String | Channel name |
Swap Overview
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.overview\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation |
| params | Yes | Object | Subscription parameter information |
| >biz | Yes | String | Type, market |
| >type | Yes | String | Channel name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.overview",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
Feed Example
{
"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"
}
]
}
| Parameter Name | Type | Description |
|---|---|---|
| code | Int | Success code |
| data | Array | Returned information |
| > market | Object | Market price changes |
| >> open | String | Opening price |
| >> close | String | Closing price |
| >> low | String | Lowest price |
| >> high | String | Highest price |
| >> turn_over | String | Total trade amount |
| >> count | Integer | Number of trades |
| >> vol | String | Trade volume in the quoted currency |
| >> change | String | Price change |
| >> change_percent | String | Price change percentage |
| > index | Object | Index price |
| >> open | String | Opening price |
| >> close | String | Closing price |
| >> low | String | Lowest price |
| >> high | String | Highest price |
| > tag | Object | Mark price |
| >> open | String | Opening price |
| >> close | String | Closing price |
| >> low | String | Lowest price |
| >> high | String | Highest price |
| > pre_funding_rate | String | Predicted funding rate |
| > funding_rate | String | Funding rate |
| > funding_next_time | Integer | Next funding time, Unix timestamp in seconds |
| > symbol | String | Product name |
| > risk_fund | String | risk reserve fund |
| msg | String | Return message |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| type | String | Channel name |
Swap Fills
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.fills\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.trade.detail",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"ts":1751362613567,
"type":"swap.BTCUSDT.fills",
"product_name":"BTCUSDT",
"data":[
{
"vol":"4",
"ts":1751362613567,
"price":"106521",
"direction":"buy"
}
]
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Array | Returned data |
| >direction | String | Trade direction: buy or sell |
| >price | String | Trade price in the quoted currency |
| >ts | Int | Trade time, in milliseconds since the Unix epoch, e.g., 1751362613567 |
| >vol | String | Trade volume in the quoted currency |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1751362613567 |
| type | String | Channel name |
Swap OrderBook
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.orderbook\",\"symbol\":\"BTCUSDT\",\"interval\":\"0\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation |
| params | Yes | Object | Subscription parameter information |
| >biz | Yes | String | Type, market |
| >type | Yes | String | Channel name |
| >symbol | Yes | String | Product Name |
| >interval | Yes | String | Depth level (0-3) |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.depth.step0",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"asks":[
[
19631.36,
0.2041
]
],
"bids":[
[
19602.5,
0.1
]
],
"ts":1751362801514,
"type":"swap.BTCUSDT.orderBook",
"product_name":"BTCUSDT",
"interval":"0"
}
Example values for
asksandbids:
asks:[19631.36, 0.2041]where19631.36is the best ask price and0.2041is the best ask volume.
bids:[19602.5, 0.1]where19602.5is the best bid price and0.1is the best bid volume.
| Parameter Name | Type | Description |
|---|---|---|
| asks | Array | Sell orders |
| bids | Array | Buy orders |
| interval | Int | Precision |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1751362801514 |
| type | String | Channel name |
Swap Percent10
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"type\":\"swap.percent10\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >type | Yes | string | Channel name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.depth.percent10",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"asks":[
[
"106486.85",
"5277"
]
],
"bids":[
[
"106486.65",
"5922"
]
],
"product_name":"BTCUSDT",
"ts":1751364759613,
"type":"swap.percent10"
}
Example values for asks and bids:
asks:[21573.475, 0.01]where21573.475is the best ask price and0.01is the best ask volume.
bids:[17651.025, 0.05]where17651.025is the best bid price and0.05is the best bid volume.
| Parameter Name | Type | Description |
|---|---|---|
| asks | Array | Sell orders |
| bids | Array | Buy orders |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1751364759613 |
| type | String | Channel name |
Swap Ticker
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.ticker\",\"symbol\":\"BTCUSDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation (sub) |
| params | Yes | Object | Subscription parameter information |
| > biz | Yes | String | Type, market |
| > type | Yes | String | Channel name |
| > symbol | Yes | String | Product ID (currency pair) |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "swap.BTCUSDT.ticker",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"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"
}
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| > ask_price | String | Ask price |
| > ask_vol | String | Ask volume |
| > bid_price | String | Bid price |
| > bid_vol | String | Bid volume |
| > change | String | Price change |
| > change_percent | String | Price change percentage |
| > close | String | Latest price |
| > high | String | Highest price |
| > low | String | Lowest price |
| > open | String | Opening price |
| > turn_over | String | Total trade amount |
| > vol | String | Trade volume in the quoted currency |
| symbol | String | Currency pair |
| type | String | Channel name |
Swap Index Candles
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.index\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "index.BTCUSDT.kline.1min",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"type":"swap.index.candles",
"symbol":"BTCUSDT",
"interval":"1min",
"data":{
"id":1751365320,
"open":"106521.7",
"close":"106519.1",
"high":"106521.7",
"low":"106514"
},
"id":1751365320
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| > close | String | Closing price of the period |
| > high | String | Highest price of the period |
| > id | Int | Time of the period, Unix timestamp (in seconds), e.g., 1751365320 |
| > low | String | Lowest price of the period |
| > open | String | Opening price of the period |
| interval | String | Period |
| symbol | String | Product Name (currency pair) |
| type | String | Channel name |
Swap Tag Candles
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"swap.tag\",\"symbol\":\"BTCUSDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "tag.BTCUSDT.kline.1min",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"type":"swap.tag.candles",
"symbol":"BTCUSDT",
"interval":"1min",
"data":{
"id":1751365740,
"open":"106441.7",
"close":"106433.5",
"high":"106441.7",
"low":"106432.1"
}
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| > close | String | Closing price of the period |
| > high | String | Highest price of the period |
| > id | Int | Time of the period, Unix timestamp (in seconds), e.g., 1751365740 |
| > low | String | Lowest price of the period |
| > open | String | Opening price of the period |
| interval | String | Period |
| symbol | String | Product Namw (currency pair) |
| type | String | Channel name |
Spot Public Subscription
/notification/ws
Spot Candles
Returns historical candlestick data. The candlestick period is calculated based on Shanghai time.
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.candles\",\"symbol\":\"BTC-USDT\",\"interval\":\"1min\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product name |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| >interval | No | string | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "spot.BTC-USDT.kline.1min",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"type": "spot.market.candles",
"product_name": "BTC-USDT",
"interval": "1min",
"data": {
"id": 1737078180,
"open": "101525.25",
"close": "101424",
"high": "101535.8",
"low": "101414.9",
"turn_over": "11871978.85186",
"vol": "117.024",
"count": 187
}
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| >close | String | Closing price of the period |
| >count | Int | Number of trades |
| >high | String | Highest price of the period |
| >id | Int | Time of the period, Unix timestamp (in seconds), e.g., 1737078180 |
| >low | String | Lowest price of the period |
| >open | String | Opening price of the period |
| >turn_over | String | Total trade amount |
| >vol | String | Trade volume in the quoted currency |
| interval | String | Period |
| product_name | String | Product Name |
| type | String | Channel name |
Spot Overview
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.overview\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation |
| params | Yes | Object | Subscription parameter information |
| >symbol | No | String | Product Name (currency pair) |
| >biz | Yes | String | Type, market |
| >type | Yes | String | Channel name |
| >interval | No | String | Period |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "spot.overview",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"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"
}
]
}
| Parameter Name | Type | Description |
|---|---|---|
| code | Int | Success code |
| data | Array | Returned information |
| > market | Object | Market price changes |
| >> open | String | Opening price |
| >> close | String | Closing price |
| >> low | String | Lowest price |
| >> high | String | Highest price |
| >> turn_over | String | Total trade amount |
| >> count | Integer | Number of trades |
| >> vol | String | Trade volume in the quoted currency |
| >> change | String | Price change |
| >> change_percent | String | Price change percentage |
| > symbol | String | Product name |
| msg | String | Return message |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| type | String | Channel name |
Spot Fills
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.fills\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >biz | Yes | string | Type, market |
| >type | Yes | string | Channel name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.trade.detail",
"status":"ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"ts":1751359932841,
"type":"spot.BTC-USDT.fills",
"product_name":"BTC-USDT",
"data":[
{
"vol":"0.09026",
"ts":1751359932841,
"price":"106738",
"direction":"sell"
}
]
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Array | Returned data |
| >direction | String | Trade direction: buy or sell |
| >price | String | Trade price in the quoted currency |
| >ts | Int | Trade time, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| >vol | String | Trade volume in the quoted currency |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| type | String | Channel name |
Spot OrderBook
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.orderbook\",\"symbol\":\"BTC-USDT\",\"interval\":\"0\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation |
| params | Yes | Object | Subscription parameter information |
| >biz | Yes | String | Type, market |
| >type | Yes | String | Channel name |
| >symbol | Yes | String | Product Name (currency pair) |
| >interval | Yes | String | Depth level (0-3) |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.depth.step0",
"status":"ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"bids": [
[
"107105.51",
"0.21529"
]
],
"asks": [
[
"107105.52",
"1.45346"
]
],
"ts": 1751018234502,
"type": "spot.orderBook",
"product_name": "BTC-USDT",
}
Example values for
asksandbids:
asks:[19631.36, 0.2041]where19631.36is the best ask price and0.2041is the best ask volume.
bids:[19602.5, 0.1]where19602.5is the best bid price and0.1is the best bid volume.
| Parameter Name | Type | Description |
|---|---|---|
| asks | Array | Sell orders |
| bids | Array | Buy orders |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| type | String | Channel name |
Spot Percent10
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
subMsg := map[string]interface{}{
"event": "sub",
"params": map[string]interface{}{
"type": "spot.percent10",
"symbol": "BTC-USDT",
},
"zip": true,
}
err = c.WriteJSON(subMsg)
if err != nil {
log.Fatal("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"type\":\"spot.percent10\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | string | Operation |
| params | Yes | object | Subscription parameter information |
| >symbol | Yes | string | Product Name (currency pair) |
| >type | Yes | string | Channel name |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id": "",
"event": "subscribe",
"topic": "spot.BTC-USDT.depth.percent10",
"status": "ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"asks":[
[
21573.475,
0.01
]
],
"bids":[
[
17651.025,
0.05
]
],
"product_name":"BTC-USDT",
"ts":1657868806752,
"type":"spot.percent10"
}
Example values for
asksandbids:
asks:[21573.475, 0.01]where21573.475is the best ask price and0.01is the best ask volume.
bids:[17651.025, 0.05]where17651.025is the best bid price and0.05is the best bid volume.
| Parameter Name | Type | Description |
|---|---|---|
| asks | Array | Sell orders |
| bids | Array | Buy orders |
| interval | String | Period |
| product_name | String | Product Name |
| ts | Int | Time of the response, in milliseconds since the Unix epoch, e.g., 1652974473071 |
| type | String | Channel name |
Spot Ticker
Request Parameters
Request Example
{
"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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
String subscribeMsg = "{\"event\":\"sub\",\"params\":{\"biz\":\"market\",\"type\":\"spot.ticker\",\"symbol\":\"BTC-USDT\"},\"zip\":true}";
webSocket.sendText(subscribeMsg, true);
System.out.println("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter Name | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation (sub) |
| params | Yes | Object | Subscription parameter information |
| > biz | Yes | String | Type, market |
| > type | Yes | String | Channel name |
| > symbol | Yes | String | Product Name (currency pair) |
| zip | Yes | Boolean | Whether to enable gzip |
Response Parameters
Response Example
{
"id":"",
"event":"subscribe",
"topic":"spot.BTC-USDT.ticker",
"status":"ok"
}
| Parameter Name | Type | Description |
|---|---|---|
| id | String | Ignore this field |
| event | String | Event type |
| topic | String | Topic name |
| status | String | Status code |
FEED Parameter Description
FEED Example
{
"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"
}
}
| Parameter Name | Type | Description |
|---|---|---|
| data | Object | Returned data |
| > ask_price | String | Ask price |
| > ask_vol | String | Ask volume |
| > bid_price | String | Bid price |
| > bid_vol | String | Bid volume |
| > change | String | Price change |
| > change_percent | String | Price change percentage |
| > close | String | Latest price |
| > high | String | Highest price |
| > low | String | Lowest price |
| > open | String | Opening price |
| > turn_over | String | Total trade amount |
| > vol | String | Trade volume in the quoted currency |
| product_name | String | Currency pair |
| seq_id | Int | Message sequence number |
| type | String | Channel name |
Private Subscriptions
/notification/pri/ws
API Login
Rate Limit: 1 time/1 second (for single account login)
Request Parameters
Request Example
{
"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/pri/notification/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"
// Custom dialer configuration
dialer := &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
NetDial: func(network, addr string) (net.Conn, error) {
// Force use of IPv4
return net.Dial("tcp4", addr)
},
HandshakeTimeout: 10 * time.Second,
}
// Establish WebSocket connection
c, _, err := dialer.Dial(url, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer c.Close()
// Subscribe to messages
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("Failed to send subscription:", err)
}
fmt.Println("Subscription request sent:", subMsg)
// Handle messages
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
return
}
var data map[string]interface{}
if err := json.Unmarshal(message, &data); err != nil {
log.Println("Failed to parse JSON:", err)
continue
}
// Handle ping message
if ping, ok := data["ping"].(float64); ok {
pong := map[string]interface{}{"pong": ping}
if err := c.WriteJSON(pong); err != nil {
log.Println("Failed to send pong:", err)
return
}
fmt.Println("Pong response sent")
continue
}
// Print other messages
pretty, _ := json.MarshalIndent(data, "", " ")
fmt.Printf("\nReceived message:\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("Connection established");
// Send subscription message
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("Subscription request sent: " + subscribeMsg);
WebSocket.Listener.super.onOpen(webSocket);
}
@Override
public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
String message = data.toString();
try {
// Handle ping message
if (message.contains("\"ping\"")) {
String pongMsg = message.replace("\"ping\"", "\"pong\"");
webSocket.sendText(pongMsg, true);
System.out.println("Pong response sent");
} else {
// Print other messages
System.out.println("\nReceived message:");
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("Connection closed: status code " + statusCode + ", reason: " + reason);
latch.countDown();
return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
}
@Override
public void onError(WebSocket webSocket, Throwable error) {
System.out.println("Error occurred:");
error.printStackTrace();
latch.countDown();
}
}).join();
try {
// Keep the connection alive
latch.await(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
| Parameter | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation type (login) |
| params | Yes | Object | Login information |
| > type | Yes | String | Login type (api) |
| > api_key | Yes | String | API Key |
| > api_timestamp | Yes | String | Timestamp in Unix time (Seconds) |
| > api_passphrase | Yes | String | API Key passphrase |
| > api_sign | Yes | String | Signature string |
| zip | Yes | Boolean | Whether to enable gzip compression |
Response Parameters
Successful Response Example
{
"event":"login",
"ts":1751373968447,
"status":"success"
}
| Parameter | Required | Type | Description |
|---|---|---|---|
| event | Yes | String | Operation |
| status | Yes | String | Status (success or error) |
| ts | Yes | Integer | Response time in Unix timestamp (milliseconds), e.g., 1751373968447 |
- API Key: The unique identifier for API access.
- API Passphrase: The password for the API Key.
- API Timestamp: Unix timestamp in seconds.
- API Sign: The signature string is generated as follows:
- Concatenate
api_timestamp,method, andrequestPath. - Use HMAC SHA256 to encrypt the concatenated string with the
SecretKey. - Encode the result using Base64.
- Concatenate
Example:
- 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: Always
GET - RequestPath: Always
/notification/pri/ws
SecretKey: The security key generated when applying for the API Key, e.g., 48f773feced21b2310bac1508a6259c4.
Spot Order Status Change Notification
Data Structure
Example Data
{
"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
}
}
}
| Parameter | Type | Description |
|---|---|---|
type |
String | Type (e.g., order.spot) |
name |
String | Trading Pair Name (e.g., BTC-USDT) |
data |
Object | Order Data Object |
└─ order_id |
Int64 | System-generated Order ID |
└─ order_type |
Int | Order Type |
└─ order_buy_or_sell |
Int | Buy/Sell Direction (1=Buy, 2=Sell) |
└─ lock_base_amount |
String | Locked Base Currency Amount |
└─ lock_quote_amount |
String | Locked Quote Currency Amount |
└─ filled_quote_amount |
String | Filled Quote Currency Amount |
└─ price |
String | Order Price |
└─ filled_amount |
String | Filled Amount |
└─ filled_fee |
String | Filled Fee |
└─ filled_avg |
String | Filled Average Price |
└─ created_at |
Int64 | Creation Timestamp |
└─ updated_at |
Int64 | Update Timestamp |
└─ finish_at |
Int64 | Completion Timestamp |
└─ state |
Int | Order State |
└─ un_filled_amount |
String | Unfilled Amount |
└─ taker |
String | Taker fee |
└─ maker |
String | Maker fee |
└─ order_state |
String | Order state |
└─ trade_ccy |
Int | Unit for market orders (1 for trading currency, 2 for quoted currency) |
└─ algo_info |
Object | Take Profit and Stop Loss Information |
└─ tp_trigger_price |
String | Take Profit Trigger Price |
└─ tp_price |
String | Take Profit Price (-1 for Market Order) |
└─ tp_price_compare |
Int | Take Profit Trigger Comparison Method |
└─ sl_trigger_price |
String | Stop Loss Trigger Price |
└─ sl_price |
String | Stop Loss Price (-1 for Market Order) |
└─ sl_price_compare |
Int | Stop Loss Trigger Comparison Method |
Spot Strategy Order Change Notification
Data Structure
Example Data
{
"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
}
}
| Parameter | Type | Description |
|---|---|---|
type |
String | Type (e.g., algo.spot) |
name |
String | Trading Pair Name (e.g., BTC-USDT) |
data |
Object | Strategy Order Data Object |
└─ algo_ord_id |
String | Strategy Order ID |
└─ link_ord_ids |
String | Linked Order IDs (comma-separated) |
└─ tp_ord_id |
String | Take Profit Order ID |
└─ ins_type |
String | Instrument Type (e.g., SPOT) |
└─ algo_ord_type |
Int | Strategy Order Type |
└─ trade_ccy |
Int | Trade Currency Type |
└─ number |
String | Contract Quantity |
└─ amount |
String | Spot Order Quantity |
└─ price |
String | Order Price |
└─ status |
Int | Strategy Status Code |
└─ order_buy_or_sell |
Int | Buy/Sell Direction (1=Buy, 2=Sell) |
└─ mgn_mode |
Int | Margin Mode |
└─ pos_mode |
Int | Position Mode |
└─ pos_opt |
Int | Position Option |
└─ stop_pos_type |
Int | Stop Position Type |
└─ taker_fee |
String | Taker Fee Rate |
└─ maker_fee |
String | Maker Fee Rate |
└─ created_at |
Int64 | Creation Timestamp |
└─ updated_at |
Int64 | Update Timestamp |
└─ finish_at |
Int64 | Completion Timestamp |
└─ position_id |
String | Position ID |
└─ fin_trigger_type |
Int | Final Trigger Type |
└─ fin_trigger_price |
String | Final Trigger Price |
└─ fin_trigger_ord_id |
Int64 | Final Trigger Order ID |
└─ from_ord_id |
String | Source Order ID |
└─ trial_his_price |
String | Trailing Stop Historical Price |
└─ trial_price |
String | Trailing Stop Price |
└─ trial_amount |
String | Trailing Stop Callback Amount/Percentage |
└─ trial_type |
Int | Trailing Stop Callback Type |
└─ trial_trigger_price |
String | Trailing Stop Trigger Price |
└─ plan_price_compare |
Int | Plan Order Price Comparison Method |
└─ plan_trigger_price |
String | Plan Order Trigger Price |
└─ plan_price |
String | Plan Order Price |
└─ attach_algo |
Array | Take Profit and Stop Loss Strategy Array |
└─ tp_trigger_price |
String | Take Profit Trigger Price |
└─ tp_price |
String | Take Profit Price (-1 for Market Order) |
└─ tp_price_compare |
Int | Take Profit Price Comparison Type |
└─ tp_ord_kind |
Int | Take Profit Order Type (1: Conditional, 2: Limit) |
└─ sl_trigger_price |
String | Stop Loss Trigger Price |
└─ sl_price |
String | Stop Loss Price (-1 for Market Order) |
└─ sl_price_compare |
Int | Stop Loss Price Comparison Type |
Swap Order Status Change Notification
Data Structure
Example Data
{
"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
}
}
}
| Parameter | Type | Description |
|---|---|---|
type |
String | Type (e.g., order.swap) |
name |
String | Trading Pair Name (e.g., BTCUSDT) |
data |
Object | Contract Order Object |
└─ order_id |
String | System Order ID |
└─ mgn_mode |
Int | Margin Mode |
└─ order_mode |
Int | Order Mode |
└─ pos_mode |
Int | Position Mode |
└─ number |
Int | Contract Quantity (for coin-based contracts) |
└─ amount |
String | Order Amount |
└─ un_filled_number |
Int | Unfilled Contract Quantity |
└─ deal_number |
Int | Filled Contract Quantity |
└─ price |
String | Order Price |
└─ status |
Int | Order Status |
└─ avg_price |
String | Average Fill Price |
└─ income |
String | Income (for backtesting) |
└─ order_buy_or_sell |
Int | Buy/Sell Direction (1=Buy, 2=Sell) |
└─ pos_side |
String | Position Side (long/short) |
└─ order_type |
Int | Order Type (limit, IOC, etc.) |
└─ pos_opt |
Int | Open/Close Position Flag |
└─ leverage |
Int | Leverage Ratio |
└─ freeze_amount |
String | Frozen Margin |
└─ taker_fee |
String | Taker Fee |
└─ maker_fee |
String | Maker Fee |
└─ created_at |
Int64 | Creation Timestamp |
└─ updated_at |
Int64 | Update Timestamp |
└─ finish_at |
Int64 | Completion Timestamp |
└─ deal_fee |
String | Total Transaction Fee |
└─ position_id |
Int | Position ID |
└─ bankrupt_price |
String | Bankruptcy Price |
└─ trade_ccy |
Int | Trade Currency Indicator |
└─ algo_info |
Object | Take Profit and Stop Loss Information |
└── tp_trigger_price |
String | Take Profit Trigger Price |
└── tp_price |
String | Take Profit Order Price (-1 for Market Order) |
└── tp_price_compare |
Int | Take Profit Trigger Price Comparison Type |
└── tp_ord_kind |
Int | Take Profit Order Type (1: Conditional, 2: Limit) |
└── sl_trigger_price |
String | Stop Loss Trigger Price |
└── sl_price |
String | Stop Loss Order Price (-1 for Market Order) |
└── sl_price_compare |
Int | Stop Loss Trigger Price Comparison Type |
Swap Maintenance Margin Ratio Change Notification
Data Structure
Example Data
{
"type": "margin.ration",
"name": "DOGEUSDT",
"data": {
"position_id": "208824000000000121",
"margin_ratio": "0.12"
}
}
| Parameter Name | Type | Description |
|---|---|---|
type |
String | Type (e.g., margin.ration) |
name |
String | Trading pair name (e.g., DOGEUSDT) |
data |
Object | Contract position object |
└─ position_id |
String | Position ID |
└─ margin_ratio |
String | Maintenance margin ratio |
Error Codes
REST
Order-related
| Error Code | Error Message |
|---|---|
| 1080001 | Invalid parameter |
| 1080002 | Trading pair cannot be empty |
| 1080003 | Invalid cancel order type |
| 1080004 | Invalid order type |
| 1080005 | Invalid quantity |
| 1080006 | Invalid take-profit or stop-loss quantity |
| 1080007 | Invalid position direction |
| 1080008 | Trade direction does not match position direction |
| 1080009 | Invalid position mode |
| 1080010 | Invalid leverage |
| 1080011 | Invalid take-profit or stop-loss parameters |
| 1080012 | Invalid margin quantity |
| 1080013 | Invalid price |
| 1080014 | Invalid take-profit or stop-loss type |
| 1080017 | Invalid order ID |
| 1080020 | Exceeded maximum bulk order quantity |
| 1080021 | Inconsistent products in bulk orders |
| 1080023 | Cannot modify margin mode while holding positions |
| 1080024 | Cannot modify margin mode while orders exist |
| 2080001 | Trading pair not found |
| 2080003 | Trading pair not enabled |
| 2080004 | Internal server error |
| 2080005 | Internal server error |
| 2080006 | Internal server error |
| 2080007 | Internal server error |
| 3080001 | Internal server error |
| 3080002 | Internal server error |
Asset-related
| Error Code | Error Message |
|---|---|
| 1010002 | Parameter validation failed |
| 1010003 | Parameter validation failed |
| 1010004 | Insufficient available assets |
| 1010005 | Existing positions or orders with different leverage |
| 1010006 | Order frequency too high |
| 1010007 | Existing positions or orders with different margin modes |
| 1010008 | Insufficient margin |
| 1010009 | Exceeded maximum order quantity |
| 1010010 | Exceeded maximum position size |
| 1010011 | Insufficient position to close |
| 1010012 | Price validation failed |
| 1010013 | Order rejected due to price being worse than liquidation price |
| 1010014 | Margin freeze failed |
| 1010015 | Order cancellation not allowed for this type |
| 1010016 | Position not found |
| 1010017 | Take-profit or stop-loss quantity exceeds position size |
| 1010018 | One-click close position timeout |
| 1010019 | Only one full-position take-profit or stop-loss allowed per position |
| 1010020 | Existing orders or take-profit/stop-loss orders with different leverage |
| 1010021 | Take-profit or stop-loss price validation failed |
| 1010022 | Margin unfreeze failed |
| 1010023 | Existing positions or orders with different margin modes |
| 1010024 | Limit order price cannot be higher than the highest bid |
| 1010025 | Limit order price cannot be lower than the lowest ask |
| 1010026 | Margin mode validation failed |
| 1010027 | Leverage validation failed |
| 1010028 | Order placement failed |
| 1010029 | Parameter validation failed |
| 1010030 | Order placement failed |
| 1010031 | Price comparison failed; please set a reasonable take-profit trigger price |
| 1010032 | Price comparison failed; please set a reasonable stop-loss trigger price |
| 1010033 | Parameter validation failed |
| 1010034 | Limit take-profit order price must be higher than the last traded price |
| 1010035 | Limit take-profit order price must be lower than the last traded price |
| 1010036 | Please set the order price for limit orders |
| 1010037 | Please set a take-profit or stop-loss trigger |
| 1010038 | Parameter validation failed |
| 1010039 | Parameter validation failed |
| 1010040 | Trailing stop-loss/take-profit callback range is 0.1-100 |
| 1010041 | Trailing stop-loss/take-profit price distance must be a positive integer |
| 1010042 | Trailing stop-loss/take-profit activation price must be a positive number |
| 1010043 | Parameter validation failed |
| 1010044 | Parameter validation failed |
| 1010045 | Internal server error |
| 1010046 | Parameter validation failed |
| 1010047 | Increase or decrease margin failed |
| 1010048 | Order not found |
| 1010049 | Internal server error |
| 1010050 | Operation on position not allowed in the current state |
| 1010051 | Account is in liquidation state and cannot perform operations |
| 1011001 | Trading pair is offline |
| 1011002 | Trading pair is not open for trading |
| 1011003 | Failed to take trading pair offline |
| 1011004 | Successfully took trading pair offline |
| 1011005 | Trading pair is suspended from trading |
| 1011006 | Only limit sell orders are allowed before the market opens |
| 1011007 | Parameter validation failed |
| 1011008 | Minimum trade amount not met |
| 1011009 | Maximum trade amount exceeded |
| 1011010 | Minimum trade quantity not met |
| 1011011 | Maximum trade quantity exceeded |
| 1011200 | Internal server error |
| 1011201 | Internal server error |
| 3010001 | Internal server error |
| 3010005 | Internal server error |
WebSocket
WebSocket