NAV
python javascript

REST Basic Information


Basic Parameter Passing Rules for APIs

Example (curl):

curl --location --request GET 'BASE_URL/v2/balance/list' \ --header 'X_ACCESS_KEY: CEm6kiOLFUurrC72afj8W7r9RLsqdjQKOGARAv080gkgWXgkikfvRhvtGiyUnebP' \ --header 'X_SIGNATURE: 5d9e9d4ad1515802dc3fa3c695bca0776f6d82c52793a0625193db088d4978dd'


Access Frequency Limits

Explanation of authentication and rate limiting policies.

Authentication

Weight and Quota Rules

Reset Points (Time Base)

Handling Excessive Requests (Recommendation)

Example (Pseudo Flow)

  1. Receive request → Verify X_ACCESS_KEY and X_SIGNATURE.
  2. Query the user's remaining minute weight and remaining day weight.
  3. If both are >= this interface's weight, deduct the corresponding weights and allow the request.
  4. If either is insufficient, return a rate limit error (439) and inform of retry time or remaining quota.

Trading Pair Whitelist Restrictions

Restrictions on trading pair permissions for trading interfaces. These restrictions only take effect when users have set trading permissions and submitted a trading pair whitelist.

Method Interface Description
POST /v2/order/create Create order
POST /v2/order/create-batch Batch create orders
POST /v2/entrust/create-plan Create planned entrust
POST /v2/entrust/create-profit Create take profit/stop loss
POST /v2/position/adjust-leverage Adjust leverage
POST /v2/position/margin Adjust margin
POST /v2/position/change-type Change position type

Restriction Rules

Rule Item Description
Whitelist Quantity Limit Maximum of 30 trading pairs can be set
Trading Permission Restriction Only trading pairs in the whitelist are allowed for trading
Error Code 467
Error Message symbol-not-in-allowed

Usage Instructions

  1. Whitelist Setup: Users can set the trading pair whitelist through the API management interface
  2. Scope of Effect: Only takes effect for API Keys that have trading permissions set
  3. Validation Timing: Validation occurs during trading operations such as order creation and entrust placement
  4. Default Behavior: If no whitelist is set, no trading pair restrictions apply

API Key Usage Guidelines

Overview

API Keys are used to identify the caller and control permissions. If a service requires an API Key, follow the guidelines below for passing and managing it.

Passing Method

Sensitivity

Permissions and Management

Key Rotation and Revocation

Errors and Responses

Example Response (Illustrative)

Signature Algorithm

When calling these APIs, in addition to the required parameters, the request header must include X_SIGNATURE, the signature parameter.

Request Parameter Concatenation Method for Signatures

When calling an API, you need to generate a signature value using the HMAC SHA256 algorithm with the request parameters and the API Secret Key.


Market Data Interface

Get Server Time

import time
import hmac
import hashlib
import requests

url = "BASE_URL/v2/public/time"
access_key = "your_api_accessKey"
secret_key = "your_api_secretKey"

timestamp = str(int(time.time() * 1000))
signature = hmac.new(secret_key.encode('utf-8'), timestamp.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": access_key,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
data = resp.json()
print("HTTP status:", resp.status_code)
print("Response:", data)
if data.get("code") == 0 and "data" in data:
    print("serverTime:", data["data"].get("serverTime"))
else:
    print("Error:", data.get("message"))
import crypto from "crypto";
import fetch from "node-fetch";

const url = "BASE_URL/v2/public/time";
const accessKey = "your_api_accessKey";
const secretKey = "your_api_secretKey";

const timestamp = Date.now().toString();
const signature = crypto.createHmac("sha256", secretKey).update(timestamp).digest("hex");

const headers = {
  "X_ACCESS_KEY": accessKey,
  "X_SIGNATURE": signature,
  "Content-Type": "application/x-www-form-urlencoded"
};

async function getServerTime() {
  const resp = await fetch(url, { method: "GET", headers });
  const data = await resp.json();
  console.log("HTTP status:", resp.status);
  console.log("Response:", data);
  if (data.code === 0 && data.data) {
    console.log("serverTime:", data.data.serverTime);
  } else {
    console.error("Error:", data.message);
  }
}

getServerTime().catch(console.error);

Description: Get the server's current timestamp for synchronizing client time.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/time

Authentication Required: API Key authentication required

Request Headers:

Response Fields

Field Type Description Example
data Long Server current timestamp (milliseconds) 1769582710262

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": 1769582710262,
    "bizCode": null
}

Field Description:


Get Trading Pair List

import requests

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

base_url = "BASE_URL"
path = "/v2/public/symbol/list"
params = {"status": "TRADING"}

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(base_url + path, headers=headers, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
print(data)
const axios = require("axios");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const baseUrl = "BASE_URL";
const path = "/v2/public/symbol/list";
const params = { status: "TRADING" };

axios.get(baseUrl + path, {
  headers: {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
  },
  params,
  timeout: 10000,
})
.then(res => {
  console.log(res.data);
})
.catch(err => {
  console.error(err.response ? err.response.data : err.message);
});

Description: Get basic information list of all trading pairs supported by the platform.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/symbol/list

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (body):

Parameter Required Description Example
status No Trading pair status: TRADING (Trading) TRADING

Response Field Description

Field Type Description Example
id Long Trading pair ID 1
symbol String Trading pair name btc_usdt
contractType String Contract type PERPETUAL (Perpetual)
underlyingType String Underlying type U_BASED (U-margin), COIN (Coin-margin)
contractSize BigDecimal Contract multiplier (face value) 0.001
tradeSwitch Boolean Trading switch true
state Integer Status 1 (Normal)
initLeverage Integer Initial leverage multiple 20
initPositionType String Initial position type ISOLATED (Isolated)
baseCoin String Base asset BTC
quoteCoin String Quote asset USDT
baseCoinPrecision Integer Base coin precision 8
baseCoinDisplayPrecision Integer Base coin display precision 8
quoteCoinPrecision Integer Quote coin precision 2
quoteCoinDisplayPrecision Integer Quote coin display precision 2
quantityPrecision Integer Quantity precision 3
pricePrecision Integer Price precision 2
supportOrderType String Supported order types LIMIT,MARKET
supportTimeInForce String Supported time in force GTC,IOC,FOK
supportEntrustType String Supported conditional order types STOP_MARKET,STOP_LIMIT,TAKE_PROFIT_MARKET,TAKE_PROFIT_LIMIT
supportPositionType String Supported position types ISOLATED,CROSS
minPrice BigDecimal Minimum price 0.01
minQty BigDecimal Minimum quantity 0.001
minNotional BigDecimal Minimum notional value 10.00
maxNotional BigDecimal Maximum notional value 1000000.00
multiplierDown BigDecimal Limit sell order lower bound percentage 0.95
multiplierUp BigDecimal Limit buy order price upper bound percentage 1.05
maxOpenOrders Integer Maximum open orders 100
maxEntrusts Integer Maximum open conditional orders 100
makerFee BigDecimal Maker fee rate 0.0002
takerFee BigDecimal Taker fee rate 0.0005
liquidationFee BigDecimal Liquidation fee rate 0.0005
marketTakeBound BigDecimal Maximum price deviation for market orders 0.005
depthPrecisionMerge Integer Depth precision merge 4
labels List Labels ["HOT", "NEW"]
onboardDate Long Listing time (millisecond timestamp) 1651500001000
enName String Contract English name btc_usdt Perpetual
cnName String Contract Chinese name btc_usdt 永续
minStepPrice BigDecimal Minimum price change unit 0.1
robotRate BigDecimal Market maker fund ratio (%) 10
pfRatio BigDecimal Hedging pool fund ratio (%) 0
tfRatio BigDecimal Treasury fund ratio (%) 0
plate String Partition configuration (JSON string) "[\"22\",\"23\",\"24\",\"86\"]"
baseCoinName String Base coin name btc
quoteCoinName String Quote coin name usdt

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "id": 1,
            "symbol": "btc_usdt",
            "contractType": "PERPETUAL",
            "underlyingType": "U_BASED",
            "contractSize": "0.0001",
            "tradeSwitch": true,
            "state": 0,
            "initLeverage": 25,
            "initPositionType": "CROSSED",
            "baseCoin": "btc",
            "quoteCoin": "usdt",
            "baseCoinPrecision": 8,
            "baseCoinDisplayPrecision": 4,
            "quoteCoinPrecision": 4,
            "quoteCoinDisplayPrecision": 8,
            "quantityPrecision": 0,
            "pricePrecision": 1,
            "supportOrderType": "LIMIT,MARKET",
            "supportTimeInForce": "GTC,FOK,IOC,GTX",
            "supportEntrustType": "TAKE_PROFIT,STOP,TAKE_PROFIT_MARKET,STOP_MARKET,TRAILING_STOP_MARKET",
            "supportPositionType": "CROSSED,ISOLATED",
            "minPrice": null,
            "minQty": "1",
            "minNotional": "1",
            "maxNotional": "100000000",
            "multiplierDown": "0.1",
            "multiplierUp": "0.1",
            "maxOpenOrders": 100,
            "maxEntrusts": 100,
            "makerFee": "0.0002",
            "takerFee": "0.0005",
            "liquidationFee": "0.0005",
            "marketTakeBound": "0.005",
            "depthPrecisionMerge": 4,
            "labels": [
                "HOT"
            ],
            "onboardDate": 1651500001000,
            "enName": "btc_usdt Perpetual",
            "cnName": "btc_usdt 永续",
            "minStepPrice": "0.1",
            "robotRate": "10",
            "pfRatio": "0",
            "tfRatio": "0",
            "plate": "[\"22\",\"23\",\"24\",\"86\"]",
            "baseCoinName": "btc",
            "quoteCoinName": "usdt"
        },
        {
            "id": 2,
            "symbol": "eth_usdt",
            "contractType": "PERPETUAL",
            "underlyingType": "U_BASED",
            "contractSize": "0.001",
            "tradeSwitch": true,
            "state": 0,
            "initLeverage": 10,
            "initPositionType": "CROSSED",
            "baseCoin": "eth",
            "quoteCoin": "usdt",
            "baseCoinPrecision": 8,
            "baseCoinDisplayPrecision": 4,
            "quoteCoinPrecision": 8,
            "quoteCoinDisplayPrecision": 8,
            "quantityPrecision": 0,
            "pricePrecision": 2,
            "supportOrderType": "LIMIT,MARKET",
            "supportTimeInForce": "GTC,FOK,IOC,GTX",
            "supportEntrustType": "TAKE_PROFIT,STOP,TAKE_PROFIT_MARKET,STOP_MARKET,TRAILING_STOP_MARKET",
            "supportPositionType": "CROSSED,ISOLATED",
            "minPrice": null,
            "minQty": "1",
            "minNotional": "1",
            "maxNotional": "100000000",
            "multiplierDown": "0.1",
            "multiplierUp": "0.1",
            "maxOpenOrders": 100,
            "maxEntrusts": 100,
            "makerFee": "0.0002",
            "takerFee": "0.0005",
            "liquidationFee": "0.0005",
            "marketTakeBound": "0.005",
            "depthPrecisionMerge": 4,
            "labels": [
                "HOT"
            ],
            "onboardDate": 1651298519000,
            "enName": "eth_usdt Perpetual",
            "cnName": "eth_usdt 永续",
            "minStepPrice": "0.01",
            "robotRate": "10",
            "pfRatio": "0",
            "tfRatio": "0",
            "plate": "[\"24\",\"86\"]",
            "baseCoinName": "eth",
            "quoteCoinName": "usdt"
        }
    ],
    "bizCode": null
}

Trading Pair Details

import requests

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

base_url = "BASE_URL"
path = "/v2/public/symbol/detail"
params = {"symbol": "btc_usdt"}

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(base_url + path, headers=headers, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
print(data)
if data.get("code") == 0:
    detail = data.get("data", {})
    print("pricePrecision:", detail.get("pricePrecision"))
    print("quantityPrecision:", detail.get("quantityPrecision"))
const axios = require("axios");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const baseUrl = "BASE_URL";
const path = "/v2/public/symbol/detail";
const params = { symbol: "btc_usdt" };

axios.get(baseUrl + path, {
  headers: {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
  },
  params,
  timeout: 10000,
})
.then(res => {
  console.log(res.data);
  if (res.data.code === 0) {
    const d = res.data.data;
    console.log("pricePrecision:", d.pricePrecision);
    console.log("quantityPrecision:", d.quantityPrecision);
  }
})
.catch(err => {
  console.error(err.response ? err.response.data : err.message);
});

Description: Get detailed information for a specified trading pair, including precision, minimum trading volume, fees, etc.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/symbol/detail

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt

Response Field Description

Field Type Description Example
id Long Trading pair ID 1
symbol String Trading pair name btc_usdt
contractType String Contract type PERPETUAL (Perpetual)
underlyingType String Underlying type USDT (U-margin), COIN (Coin-margin)
contractSize BigDecimal Contract multiplier (face value) 0.001
tradeSwitch Boolean Trading switch true
state Integer Status 1 (Normal)
initLeverage Integer Initial leverage multiple 20
initPositionType String Initial position type ISOLATED (Isolated)
baseCoin String Base asset BTC
quoteCoin String Quote asset USDT
baseCoinPrecision Integer Base coin precision 8
baseCoinDisplayPrecision Integer Base coin display precision 8
quoteCoinPrecision Integer Quote coin precision 2
quoteCoinDisplayPrecision Integer Quote coin display precision 2
quantityPrecision Integer Quantity precision 3
pricePrecision Integer Price precision 2
supportOrderType String Supported order types LIMIT,MARKET
supportTimeInForce String Supported time in force GTC,IOC,FOK
supportEntrustType String Supported conditional order types STOP_MARKET,STOP_LIMIT,TAKE_PROFIT_MARKET,TAKE_PROFIT_LIMIT
supportPositionType String Supported position types ISOLATED,CROSS
minPrice BigDecimal Minimum price 0.01
minQty BigDecimal Minimum quantity 0.001
minNotional BigDecimal Minimum notional value 10.00
maxNotional BigDecimal Maximum notional value 1000000.00
multiplierDown BigDecimal Limit sell order lower bound percentage 0.95
multiplierUp BigDecimal Limit buy order price upper bound percentage 1.05
maxOpenOrders Integer Maximum open orders 200
maxEntrusts Integer Maximum open conditional orders 20
makerFee BigDecimal Maker fee rate 0.0002
takerFee BigDecimal Taker fee rate 0.0005
liquidationFee BigDecimal Liquidation fee rate 0.0002
marketTakeBound BigDecimal Maximum price deviation for market orders 0.10
depthPrecisionMerge Integer Depth precision merge 8
labels List Labels ["HOT", "NEW"]
onboardDate Long Listing time (millisecond timestamp) 1640995200000
enName String Contract English name Bitcoin Perpetual
cnName String Contract Chinese name 比特币永续合约
minStepPrice BigDecimal Minimum price change unit 0.01
robotRate BigDecimal Market maker fund ratio (%) 30.00
pfRatio BigDecimal Hedging pool fund ratio (%) 50.00
tfRatio BigDecimal Treasury fund ratio (%) 20.00
plate String Partition configuration (JSON string) "[1,10]"
baseCoinName String Base coin name Bitcoin
quoteCoinName String Quote coin name Tether

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "id": 1,
        "symbol": "btc_usdt",
        "contractType": "PERPETUAL",
        "underlyingType": "U_BASED",
        "contractSize": "0.0001",
        "tradeSwitch": true,
        "state": 0,
        "initLeverage": 25,
        "initPositionType": "CROSSED",
        "baseCoin": "btc",
        "quoteCoin": "usdt",
        "baseCoinPrecision": 8,
        "baseCoinDisplayPrecision": 4,
        "quoteCoinPrecision": 4,
        "quoteCoinDisplayPrecision": 8,
        "quantityPrecision": 0,
        "pricePrecision": 1,
        "supportOrderType": "LIMIT,MARKET",
        "supportTimeInForce": "GTC,FOK,IOC,GTX",
        "supportEntrustType": "TAKE_PROFIT,STOP,TAKE_PROFIT_MARKET,STOP_MARKET,TRAILING_STOP_MARKET",
        "supportPositionType": "CROSSED,ISOLATED",
        "minPrice": null,
        "minQty": "1",
        "minNotional": "1",
        "maxNotional": "100000000",
        "multiplierDown": "0.1",
        "multiplierUp": "0.1",
        "maxOpenOrders": 100,
        "maxEntrusts": 100,
        "makerFee": "0.0002",
        "takerFee": "0.0005",
        "liquidationFee": "0.0005",
        "marketTakeBound": "0.005",
        "depthPrecisionMerge": 4,
        "labels": [
            "HOT"
        ],
        "onboardDate": 1651500001000,
        "enName": "btc_usdt Perpetual",
        "cnName": "btc_usdt 永续",
        "minStepPrice": "0.1",
        "robotRate": "10",
        "pfRatio": "0",
        "tfRatio": "0",
        "plate": "[\"22\",\"23\",\"24\",\"86\"]",
        "baseCoinName": "btc",
        "quoteCoinName": "usdt"
    },
    "bizCode": null
}

Get Contract Currency List

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/symbol/all"
params = {}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params or None, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

async function fetchAllSymbols() {
  try {
    const res = await axios.get("BASE_URL/v2/public/symbol/all", {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": API_SECRET,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchAllSymbols();

Description: Get complete configuration information for all trading pairs, including contract specifications, risk limits, etc.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/symbol/all

Authentication Required: API Key authentication required

Request Headers:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        "btc_usdt",
        "eth_usdt",
        "sol_usdt",
        "atom_usdt",
        "doge_usdt",
        "bnb_usdt",
        "hype_usdt",
        "xrp_usdt",
        "aster_usdt",
        "link_usdt",
        "pump_usdt",
        "trx_usdt",
        "sui_usdt",
        "1000pepe_usdt",
        "1000shib_usdt",
        "aevo_usdt",
        "wlfi_usdt"
    ],
    "bizCode": null
}

Market Tickers

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/ticker"
params = {"symbol": "btc_usdt", "timeRangeType": "D"}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/ticker";
const params = { symbol: "btc_usdt", timeRangeType: "D" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchTickerSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchTickerSigned();

Description: Get the latest market data for a single trading pair, including latest price, 24-hour trading volume, price change percentage, etc.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/ticker

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example Enum Values
symbol Yes Trading pair btc_usdt -
timeRangeType Yes Time range type H24 See detailed enumeration below

timeRangeType Enumeration:

Enum Value Description UTC Timezone Offset Explanation
H24 24-hour rolling data UTC Rolling data for the past 24 hours
UTC_P_12 UTC+12 timezone +12:00 Trading day data based on UTC+12 timezone
UTC_P_11 UTC+11 timezone +11:00 Trading day data based on UTC+11 timezone
UTC_P_10 UTC+10 timezone +10:00 Trading day data based on UTC+10 timezone
UTC_P_9 UTC+9 timezone +09:00 Trading day data based on UTC+9 timezone
UTC_P_8 UTC+8 timezone +08:00 Trading day data based on UTC+8 timezone
UTC_P_7 UTC+7 timezone +07:00 Trading day data based on UTC+7 timezone
UTC_P_6 UTC+6 timezone +06:00 Trading day data based on UTC+6 timezone
UTC_P_5 UTC+5 timezone +05:00 Trading day data based on UTC+5 timezone
UTC_P_4 UTC+4 timezone +04:00 Trading day data based on UTC+4 timezone
UTC_P_3 UTC+3 timezone +03:00 Trading day data based on UTC+3 timezone
UTC_P_2 UTC+2 timezone +02:00 Trading day data based on UTC+2 timezone
UTC_P_1 UTC+1 timezone +01:00 Trading day data based on UTC+1 timezone
UTC_P_0 UTC+0 timezone +00:00 Trading day data based on UTC+0 timezone
UTC_N_1 UTC-1 timezone -01:00 Trading day data based on UTC-1 timezone
UTC_N_2 UTC-2 timezone -02:00 Trading day data based on UTC-2 timezone
UTC_N_3 UTC-3 timezone -03:00 Trading day data based on UTC-3 timezone
UTC_N_4 UTC-4 timezone -04:00 Trading day data based on UTC-4 timezone
UTC_N_5 UTC-5 timezone -05:00 Trading day data based on UTC-5 timezone
UTC_N_6 UTC-6 timezone -06:00 Trading day data based on UTC-6 timezone
UTC_N_7 UTC-7 timezone -07:00 Trading day data based on UTC-7 timezone
UTC_N_8 UTC-8 timezone -08:00 Trading day data based on UTC-8 timezone
UTC_N_9 UTC-9 timezone -09:00 Trading day data based on UTC-9 timezone
UTC_N_10 UTC-10 timezone -10:00 Trading day data based on UTC-10 timezone
UTC_N_11 UTC-11 timezone -11:00 Trading day data based on UTC-11 timezone
UTC_N_12 UTC-12 timezone -12:00 Trading day data based on UTC-12 timezone

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
c String Latest price "89192.3"
h String Highest price within the statistical period "89493.3"
l String Lowest price within the statistical period "87255.6"
a String Trading volume (base currency) within the statistical period "7216921.4"
v String Trading amount (quote currency) within the statistical period "63836031.32165"
o String First trade price at the start of the statistical period "88289.9"
r String Price change percentage within the statistical period (percentage, e.g., "0.0102" represents 1.02%) "0.0102"

Explanation:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "t": 1769584725803,
        "s": "btc_usdt",
        "c": "89192.3",
        "h": "89493.3",
        "l": "87255.6",
        "a": "7216921.4",
        "v": "63836031.32165",
        "o": "88289.9",
        "r": "0.0102"
    },
    "bizCode": null
}

Market List

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/tickers"
params = {"timeRangeType": "D"}

qs = urlencode(sorted(params.items()))

signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/tickers";
const params = { timeRangeType: "D" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchTickersSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchTickersSigned();

Description: Get 24-hour market data summary for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/tickers

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example Enum Values
timeRangeType Yes Time range type H24 H24 (24 hours)

timeRangeType Enumeration:

Enum Value Description UTC Timezone Offset Explanation
H24 24-hour rolling data UTC Rolling data for the past 24 hours
UTC_P_12 UTC+12 timezone +12:00 Trading day data based on UTC+12 timezone
UTC_P_11 UTC+11 timezone +11:00 Trading day data based on UTC+11 timezone
UTC_P_10 UTC+10 timezone +10:00 Trading day data based on UTC+10 timezone
UTC_P_9 UTC+9 timezone +09:00 Trading day data based on UTC+9 timezone
UTC_P_8 UTC+8 timezone +08:00 Trading day data based on UTC+8 timezone
UTC_P_7 UTC+7 timezone +07:00 Trading day data based on UTC+7 timezone
UTC_P_6 UTC+6 timezone +06:00 Trading day data based on UTC+6 timezone
UTC_P_5 UTC+5 timezone +05:00 Trading day data based on UTC+5 timezone
UTC_P_4 UTC+4 timezone +04:00 Trading day data based on UTC+4 timezone
UTC_P_3 UTC+3 timezone +03:00 Trading day data based on UTC+3 timezone
UTC_P_2 UTC+2 timezone +02:00 Trading day data based on UTC+2 timezone
UTC_P_1 UTC+1 timezone +01:00 Trading day data based on UTC+1 timezone
UTC_P_0 UTC+0 timezone +00:00 Trading day data based on UTC+0 timezone
UTC_N_1 UTC-1 timezone -01:00 Trading day data based on UTC-1 timezone
UTC_N_2 UTC-2 timezone -02:00 Trading day data based on UTC-2 timezone
UTC_N_3 UTC-3 timezone -03:00 Trading day data based on UTC-3 timezone
UTC_N_4 UTC-4 timezone -04:00 Trading day data based on UTC-4 timezone
UTC_N_5 UTC-5 timezone -05:00 Trading day data based on UTC-5 timezone
UTC_N_6 UTC-6 timezone -06:00 Trading day data based on UTC-6 timezone
UTC_N_7 UTC-7 timezone -07:00 Trading day data based on UTC-7 timezone
UTC_N_8 UTC-8 timezone -08:00 Trading day data based on UTC-8 timezone
UTC_N_9 UTC-9 timezone -09:00 Trading day data based on UTC-9 timezone
UTC_N_10 UTC-10 timezone -10:00 Trading day data based on UTC-10 timezone
UTC_N_11 UTC-11 timezone -11:00 Trading day data based on UTC-11 timezone
UTC_N_12 UTC-12 timezone -12:00 Trading day data based on UTC-12 timezone

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
c String Latest price "89192.3"
h String Highest price within the statistical period "89493.3"
l String Lowest price within the statistical period "87255.6"
a String Trading volume (base currency) within the statistical period "7216921.4"
v String Trading amount (quote currency) within the statistical period "63836031.32165"
o String First trade price at the start of the statistical period "88289.9"
r String Price change percentage within the statistical period (percentage, e.g., "0.0102" represents 1.02%) "0.0102"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "t": 1769597269001,
            "s": "btc_usdt",
            "c": "89452.1",
            "h": "89650.4",
            "l": "87255.6",
            "a": "7469238.6",
            "v": "66159976.89515",
            "o": "87735.3",
            "r": "0.0195"
        },
        {
            "t": 1769597267407,
            "s": "eth_usdt",
            "c": "3027.95",
            "h": "3035.20",
            "l": "2900.31",
            "a": "5151240",
            "v": "15335904.01611",
            "o": "2902.23",
            "r": "0.0433"
        }
    ],
    "bizCode": null
}

Aggregate Market Data

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/agg-ticker"
params = {"symbol": "btc_usdt", "timeRangeType": "D"}

qs = urlencode(sorted(params.items()))

signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/agg-ticker";
const params = { symbol: "btc_usdt", timeRangeType: "D" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchAggTickerSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchAggTickerSigned();

Description: Get aggregated market data for a single trading pair, containing more statistical indicators.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/agg-ticker

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair btc_usdt
timeRangeType Yes Time range type H24

timeRangeType Enumeration:

Enum Value Description UTC Timezone Offset Explanation
H24 24-hour rolling data UTC Rolling data for the past 24 hours
UTC_P_12 UTC+12 timezone +12:00 Trading day data based on UTC+12 timezone
UTC_P_11 UTC+11 timezone +11:00 Trading day data based on UTC+11 timezone
UTC_P_10 UTC+10 timezone +10:00 Trading day data based on UTC+10 timezone
UTC_P_9 UTC+9 timezone +09:00 Trading day data based on UTC+9 timezone
UTC_P_8 UTC+8 timezone +08:00 Trading day data based on UTC+8 timezone
UTC_P_7 UTC+7 timezone +07:00 Trading day data based on UTC+7 timezone
UTC_P_6 UTC+6 timezone +06:00 Trading day data based on UTC+6 timezone
UTC_P_5 UTC+5 timezone +05:00 Trading day data based on UTC+5 timezone
UTC_P_4 UTC+4 timezone +04:00 Trading day data based on UTC+4 timezone
UTC_P_3 UTC+3 timezone +03:00 Trading day data based on UTC+3 timezone
UTC_P_2 UTC+2 timezone +02:00 Trading day data based on UTC+2 timezone
UTC_P_1 UTC+1 timezone +01:00 Trading day data based on UTC+1 timezone
UTC_P_0 UTC+0 timezone +00:00 Trading day data based on UTC+0 timezone
UTC_N_1 UTC-1 timezone -01:00 Trading day data based on UTC-1 timezone
UTC_N_2 UTC-2 timezone -02:00 Trading day data based on UTC-2 timezone
UTC_N_3 UTC-3 timezone -03:00 Trading day data based on UTC-3 timezone
UTC_N_4 UTC-4 timezone -04:00 Trading day data based on UTC-4 timezone
UTC_N_5 UTC-5 timezone -05:00 Trading day data based on UTC-5 timezone
UTC_N_6 UTC-6 timezone -06:00 Trading day data based on UTC-6 timezone
UTC_N_7 UTC-7 timezone -07:00 Trading day data based on UTC-7 timezone
UTC_N_8 UTC-8 timezone -08:00 Trading day data based on UTC-8 timezone
UTC_N_9 UTC-9 timezone -09:00 Trading day data based on UTC-9 timezone
UTC_N_10 UTC-10 timezone -10:00 Trading day data based on UTC-10 timezone
UTC_N_11 UTC-11 timezone -11:00 Trading day data based on UTC-11 timezone
UTC_N_12 UTC-12 timezone -12:00 Trading day data based on UTC-12 timezone

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
c String Latest price "89192.3"
h String Highest price within the statistical period "89493.3"
l String Lowest price within the statistical period "87255.6"
a String Trading volume (base currency) within the statistical period "7216921.4"
v String Trading amount (quote currency) within the statistical period "63836031.32165"
o String First trade price at the start of the statistical period "88289.9"
r String Price change percentage within the statistical period (percentage, e.g., "0.0102" represents 1.02%) "0.0102"
i String Index price "89423.4"
m String Mark price "89429.2"
bp String Best bid price "89422.8"
ap String Best ask price "89424.1"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "t": 1769597496859,
        "s": "btc_usdt",
        "c": "89423.3",
        "h": "89650.4",
        "l": "87255.6",
        "a": "7475284.7",
        "v": "66214057.48860",
        "o": "87735.3",
        "r": "0.0192",
        "i": "89423.4",
        "m": "89429.2",
        "bp": "89422.8",
        "ap": "89424.1"
    },
    "bizCode": null
}

Aggregate Market List

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/agg-tickers"
params = {"timeRangeType": "D"}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/agg-tickers";
const params = { timeRangeType: "D" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchAggTickersSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchAggTickersSigned();

Description: Get aggregated market data list for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/agg-tickers

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example Enum Values
timeRangeType Yes Time range type H24 H24 (24 hours)

timeRangeType Enumeration:

Enum Value Description UTC Timezone Offset Explanation
H24 24-hour rolling data UTC Rolling data for the past 24 hours
UTC_P_12 UTC+12 timezone +12:00 Trading day data based on UTC+12 timezone
UTC_P_11 UTC+11 timezone +11:00 Trading day data based on UTC+11 timezone
UTC_P_10 UTC+10 timezone +10:00 Trading day data based on UTC+10 timezone
UTC_P_9 UTC+9 timezone +09:00 Trading day data based on UTC+9 timezone
UTC_P_8 UTC+8 timezone +08:00 Trading day data based on UTC+8 timezone
UTC_P_7 UTC+7 timezone +07:00 Trading day data based on UTC+7 timezone
UTC_P_6 UTC+6 timezone +06:00 Trading day data based on UTC+6 timezone
UTC_P_5 UTC+5 timezone +05:00 Trading day data based on UTC+5 timezone
UTC_P_4 UTC+4 timezone +04:00 Trading day data based on UTC+4 timezone
UTC_P_3 UTC+3 timezone +03:00 Trading day data based on UTC+3 timezone
UTC_P_2 UTC+2 timezone +02:00 Trading day data based on UTC+2 timezone
UTC_P_1 UTC+1 timezone +01:00 Trading day data based on UTC+1 timezone
UTC_P_0 UTC+0 timezone +00:00 Trading day data based on UTC+0 timezone
UTC_N_1 UTC-1 timezone -01:00 Trading day data based on UTC-1 timezone
UTC_N_2 UTC-2 timezone -02:00 Trading day data based on UTC-2 timezone
UTC_N_3 UTC-3 timezone -03:00 Trading day data based on UTC-3 timezone
UTC_N_4 UTC-4 timezone -04:00 Trading day data based on UTC-4 timezone
UTC_N_5 UTC-5 timezone -05:00 Trading day data based on UTC-5 timezone
UTC_N_6 UTC-6 timezone -06:00 Trading day data based on UTC-6 timezone
UTC_N_7 UTC-7 timezone -07:00 Trading day data based on UTC-7 timezone
UTC_N_8 UTC-8 timezone -08:00 Trading day data based on UTC-8 timezone
UTC_N_9 UTC-9 timezone -09:00 Trading day data based on UTC-9 timezone
UTC_N_10 UTC-10 timezone -10:00 Trading day data based on UTC-10 timezone
UTC_N_11 UTC-11 timezone -11:00 Trading day data based on UTC-11 timezone
UTC_N_12 UTC-12 timezone -12:00 Trading day data based on UTC-12 timezone

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
c String Latest price "89192.3"
h String Highest price within the statistical period "89493.3"
l String Lowest price within the statistical period "87255.6"
a String Trading volume (base currency) within the statistical period "7216921.4"
v String Trading amount (quote currency) within the statistical period "63836031.32165"
o String First trade price at the start of the statistical period "88289.9"
r String Price change percentage within the statistical period (percentage, e.g., "0.0102" represents 1.02%) "0.0102"
i String Index price "89423.4"
m String Mark price "89429.2"
bp String Best bid price "89422.8"
ap String Best ask price "89424.1"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "t": 1769597753585,
            "s": "btc_usdt",
            "c": "89402.7",
            "h": "89650.4",
            "l": "87255.6",
            "a": "7482855.7",
            "v": "66281760.94256",
            "o": "87735.3",
            "r": "0.0190",
            "i": "89402.3",
            "m": "89408.0",
            "bp": "89401.8",
            "ap": "89403.1"
        },
        {
            "t": 1769597753488,
            "s": "eth_usdt",
            "c": "3025.00",
            "h": "3035.20",
            "l": "2900.31",
            "a": "5173701",
            "v": "15403913.82645",
            "o": "2902.23",
            "r": "0.0423",
            "i": "3025.14",
            "m": "3025.42",
            "bp": "3024.34",
            "ap": "3025.13"
        }
    ],
    "bizCode": null
}

Depth Data

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/depth"
params = {"symbol": "btc_usdt", "level": 10}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/depth";
const params = { symbol: "btc_usdt", level: 10 };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchDepthSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error("Error:", err.response ? err.response.data : err.message);
  }
}

fetchDepthSigned();

Description: Get order book depth information for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/depth

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example Constraint
symbol Yes Trading pair btc_usdt -
level Yes Number of levels 2 1-50

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
u String updateId "586765918776852548"
b String Buy orders "[price, quantity]"
a String Sell orders "[price, quantity]"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "t": 1769597897116,
        "s": "btc_usdt",
        "u": 586765918776852548,
        "b": [
            [
                "89390.8",
                "11630"
            ],
            [
                "89390.3",
                "10970"
            ]
        ],
        "a": [
            [
                "89392",
                "2240"
            ],
            [
                "89392.3",
                "2990"
            ]
        ]
    },
    "bizCode": null
}

Field Description:


Trade Data

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/deal"
params = {"symbol": "btc_usdt", "num": 50}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/deal";
const params = { symbol: "btc_usdt", num: 50 };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchDealsSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchDealsSigned();

Description: Get the latest trade records for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/deal

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example Default Value Constraint
symbol Yes Trading pair btc_usdt - -
num No Number of returns 2 50 ≥1

Field Description:

Field Name Field Type Description Example
t Long Data timestamp (milliseconds) 1769584725803
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
p String Trade price "89300.7"
a String Trade volume "21"
m String Trade direction "ASK" or "BID"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "t": 1769598709094,
            "s": "btc_usdt",
            "p": "89300.7",
            "a": "3",
            "m": "ASK"
        },
        {
            "t": 1769598708455,
            "s": "btc_usdt",
            "p": "89300.8",
            "a": "21",
            "m": "BID"
        }
    ],
    "bizCode": null
}

Field Description:


K-line Data

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

def fetch_kline_signed(symbol="btc_usdt", interval="1h", startTime=None, endTime=None, limit=500):
    url = "BASE_URL/v2/public/q/kline"
    params = {"symbol": symbol, "interval": interval, "limit": limit}
    if startTime is not None:
        params["startTime"] = int(startTime)
    if endTime is not None:
        params["endTime"] = int(endTime)

    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }

    resp = requests.get(url, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    data = fetch_kline_signed("btc_usdt", "1h")
    print(data)
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

async function fetchKlineSigned(symbol = "btc_usdt", interval = "1h", startTime, endTime, limit = 500) {
  const url = "BASE_URL/v2/public/q/kline";
  const params = { symbol, interval, limit };
  if (startTime !== undefined) params.startTime = Number(startTime);
  if (endTime !== undefined) params.endTime = Number(endTime);

  const sortedKeys = Object.keys(params).sort();
  const entries = sortedKeys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();

  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    return res.data;
  } catch (err) {
    throw err.response ? err.response.data : err;
  }
}

fetchKlineSigned("btc_usdt", "1h").then(console.log).catch(console.error);

Description: Get K-line data for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/kline

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt
interval Yes K-line interval: 1m,5m,15m,30m,1h,4h,1d,1w,1M,3M,6M 1h
startTime No Start timestamp (milliseconds) 1672444800000
endTime No End timestamp (milliseconds) 1672531200000
limit No Number of K-lines to return (default 500, maximum 1000) 500

interval Enumeration:

Enum Value Description Code Value Period Minutes Collection Name
1m 1-minute K-line 0 1 kline_1m
5m 5-minute K-line 1 5 kline_5m
15m 15-minute K-line 2 15 kline_15m
30m 30-minute K-line 3 30 kline_30m
1h 1-hour K-line 4 60 kline_1h
4h 4-hour K-line 5 240 kline_4h
1d Daily K-line 9 1440 kline_1d
1w Weekly K-line 11 10080 kline_1w
1M Monthly K-line 12 43200 kline_1mth
3M Quarterly K-line (3 months) 13 129600 kline_3mth
6M Semi-annual K-line (6 months) 14 259200 kline_6mth

Parameter Description:

Parameter Type Description Notes
symbol String Trading pair identifier Format is lowercase, separated by underscore (e.g., "btc_usdt")
interval String K-line period Must use one of the above enumeration values
startTime Long Query start time (millisecond timestamp) When not passed, defaults to calculating forward from current time for limit number of K-lines
endTime Long Query end time (millisecond timestamp) When not passed, defaults to current time; if startTime is passed but endTime is not, endTime defaults to current time
limit Integer Number of K-lines to return Range 1-1000, default 500; if both startTime and endTime are passed, this parameter may be ignored

Time Range Description:

Field Description:

Field Name Field Type Description Example
s String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
t Long K-line start timestamp (milliseconds) 1769598000000
o String Opening price (first trade price of this K-line period) "89362.3"
c String Closing price (last trade price of this K-line period) "89308.7"
h String Highest price (highest trade price within this K-line period) "89440.7"
l String Lowest price (lowest trade price within this K-line period) "89275.7"
a String Trading volume (base currency, e.g., BTC quantity) "63036.05"
v String Trading amount (quote currency, e.g., USDT amount) "563190.2239020"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "s": "btc_usdt",
            "t": 1769598000000,
            "o": "89362.3",
            "c": "89308.7",
            "h": "89440.7",
            "l": "89275.7",
            "a": "63036.05",
            "v": "563190.2239020"
        },
        {
            "s": "btc_usdt",
            "t": 1769594400000,
            "o": "89434.0",
            "c": "89362.3",
            "h": "89650.4",
            "l": "89291.2",
            "a": "297423.10",
            "v": "2660580.4022515"
        }
    ],
    "bizCode": null
}

Notes:

Mark Price

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/mark-price"
params = {}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=None, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

async function fetchMarkPricesSigned() {
  try {
    const params = {};
    const qs = new URLSearchParams(Object.keys(params).sort().reduce((acc, k) => {
      acc[k] = params[k];
      return acc;
    }, {})).toString();

    const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

    const res = await axios.get("BASE_URL/v2/public/q/mark-price", {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });

    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchMarkPricesSigned();

Description: Get mark prices for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/mark-price

Authentication Required: API Key authentication required

Request Headers:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "s": "eth_usdt",
            "p": "3017.12",
            "t": 1769599670589
        },
        {
            "s": "btc_usdt",
            "p": "89367.3",
            "t": 1769599670589
        }
    ],
    "bizCode": null
}

Trading Pair Mark Price

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/symbol-mark-price"
params = {"symbol": "btc_usdt"}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/symbol-mark-price";
const params = { symbol: "btc_usdt" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchSymbolMarkPriceSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchSymbolMarkPriceSigned();

Description: Get mark price details for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/symbol-mark-price

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "s": "btc_usdt",
        "p": "89434.7",
        "t": 1769599787498
    },
    "bizCode": null
}

Index Price

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/index-price"
params = {}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const url = "BASE_URL/v2/public/q/index-price";

async function fetchIndexPriceSigned() {
  try {
    const params = {};
    const qs = new URLSearchParams(Object.keys(params).sort().reduce((acc, k) => {
      acc[k] = params[k];
      return acc;
    }, {})).toString();

    const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchIndexPriceSigned();

Description: Get index prices for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/index-price

Authentication Required: API Key authentication required

Request Headers:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "s": "eth_usdt",
            "p": "3020.4",
            "t": 1769599966917
        },
        {
            "s": "btc_usdt",
            "p": "89410.4",
            "t": 1769599966917
        }
    ],
    "bizCode": null
}

Trading Pair Index Price

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/q/symbol-index-price"
params = {"symbol": "btc_usdt"}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

const url = "BASE_URL/v2/public/q/symbol-index-price";
const params = { symbol: "btc_usdt" };

const sortedKeys = Object.keys(params).sort();
const entries = sortedKeys.map(k => [k, params[k]]);
const qs = new URLSearchParams(entries).toString();

const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

async function fetchSymbolIndexPriceSigned() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchSymbolIndexPriceSigned();

Description: Get index price details for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/symbol-index-price

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "s": "btc_usdt",
        "p": "89410.4",
        "t": 1769599966917
    },
    "bizCode": null
}

Funding Rate

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

def fetch_funding_rate_signed(symbol="btc_usdt"):
    url = "BASE_URL/v2/public/q/funding-rate"
    params = {"symbol": symbol}

    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(url, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(fetch_funding_rate_signed("btc_usdt"))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";

async function fetchFundingRateSigned(symbol = "btc_usdt") {
  const url = "BASE_URL/v2/public/q/funding-rate";
  const params = { symbol };

  const sortedKeys = Object.keys(params).sort();
  const entries = sortedKeys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();

  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    return res.data;
  } catch (err) {
    throw err.response ? err.response.data : err;
  }
}

fetchFundingRateSigned("btc_usdt").then(console.log).catch(console.error);

Description: Get current funding rates for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/funding-rate

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair btc_usdt

Field Description:

Field Name Field Type Description Example
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
fundingRate BigDecimal Funding rate "0.000102"
nextCollectionTime Long Next collection time 1769616000000

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "symbol": "btc_usdt",
        "fundingRate": "0.000102",
        "nextCollectionTime": 1769616000000
    },
    "bizCode": null
}

Funding Rate Records

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
BASE_URL = "BASE_URL"
PATH = "/v2/public/q/funding-rate-record"
URL = BASE_URL + PATH

def fetch_funding_rate_records_simple(symbol, id=None, direction="NEXT", limit=10):
    params = {"symbol": symbol, "limit": limit}
    if id is not None:
        params["id"] = id
        params["direction"] = direction
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": API_SECRET,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

def fetch_funding_rate_records_signed(symbol, id=None, direction="NEXT", limit=10):
    params = {"symbol": symbol, "limit": limit}
    if id is not None:
        params["id"] = id
        params["direction"] = direction

    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    symbol = "btc_usdt"

    r = fetch_funding_rate_records_signed(symbol, limit=10)
    print("First page:", r)
    items = r.get("data", {}).get("items", [])
    if items:
        last_id = items[-1].get("id")
        r2 = fetch_funding_rate_records_signed(symbol, id=last_id, direction="NEXT", limit=10)
        print("Next page:", r2)

        first_id = items[0].get("id")
        r_prev = fetch_funding_rate_records_signed(symbol, id=first_id, direction="PREV", limit=10)
        print("Prev page:", r_prev)
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const BASE_URL = "BASE_URL";
const PATH = "/v2/public/q/funding-rate-record";
const URL = BASE_URL + PATH;

async function fetchFundingRateRecordsSimple(symbol, id = undefined, direction = "NEXT", limit = 10) {
  const params = { symbol, limit };
  if (id !== undefined) {
    params.id = id;
    params.direction = direction;
  }
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(URL, { headers, params, timeout: 10000 });
  return res.data;
}

async function fetchFundingRateRecordsSigned(symbol, id = undefined, direction = "NEXT", limit = 10) {
  const params = { symbol, limit };
  if (id !== undefined) {
    params.id = id;
    params.direction = direction;
  }

  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };

  const res = await axios.get(URL, { headers, params, timeout: 10000 });
  return res.data;
}

(async () => {
  try {
    const symbol = "btc_usdt";
    const first = await fetchFundingRateRecordsSigned(symbol, undefined, "NEXT", 10);
    console.log("First page:", first);

    const items = first.data && first.data.items ? first.data.items : [];
    if (items.length) {
      const lastId = items[items.length - 1].id;
      const nextPage = await fetchFundingRateRecordsSigned(symbol, lastId, "NEXT", 10);
      console.log("Next page:", nextPage);

      const firstId = items[0].id;
      const prevPage = await fetchFundingRateRecordsSigned(symbol, firstId, "PREV", 10);
      console.log("Prev page:", prevPage);
    }
  } catch (err) {
    console.error("Error:", err.response ? err.response.data : err.message);
  }
})();

Description: Get historical funding rate records for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/q/funding-rate-record

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example Default Value Enum Values
symbol Yes Trading pair btc_usdt - -
id No Cursor ID 1234567890 - -
direction No Pagination direction NEXT NEXT NEXT, PREV
limit No Number of records 10 10 1-100

Field Description:

Field Name Field Type Description Example
id Long id id
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
fundingRate BigDecimal Latest funding rate "0.000097"
createdTime Long Time 1769587200000
collectionInternal Long Collection interval (seconds) 28800

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "hasPrev": false,
        "hasNext": true,
        "items": [
            {
                "id": "586721053934975552",
                "symbol": "btc_usdt",
                "fundingRate": "0.000097",
                "createdTime": 1769587200000,
                "collectionInternal": 28800
            },
            {
                "id": "586600257988164160",
                "symbol": "btc_usdt",
                "fundingRate": "0.00017",
                "createdTime": 1769558400000,
                "collectionInternal": 28800
            }
        ]
    },
    "bizCode": null
}

Pagination Instructions:

This interface uses a cursor-based pagination mechanism:


Leverage Tier List

import requests
import hmac
import hashlib

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/leverage/bracket/list"

qs = ""  
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const url = "BASE_URL/v2/public/leverage/bracket/list";

(async () => {
  try {
    const qs = "";
    const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
})();

Description: Get leverage tier configurations for all trading pairs.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/leverage/bracket/list

Authentication Required: API Key authentication required

Request Headers:

Field Description:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": [
    {
      "symbol": "btc_usdt",
      "leverageBrackets": [
        {
          "symbolId": 1,
          "bracket": 1,
          "maxPosition": "1000.00000000",
          "maxLeverage": "125",
          "maintenanceMargin": "0.0040",
          "maintenanceAmount": "0.00000000"
        },
        {
          "symbolId": 1,
          "bracket": 2,
          "maxPosition": "5000.00000000",
          "maxLeverage": "100",
          "maintenanceMargin": "0.0050",
          "maintenanceAmount": "0.00000000"
        }
      ]
    },
    {
      "symbol": "eth_usdt",
      "leverageBrackets": [
        {
          "symbolId": 2,
          "bracket": 1,
          "maxPosition": "10000.00000000",
          "maxLeverage": "125",
          "maintenanceMargin": "0.0040",
          "maintenanceAmount": "0.00000000"
        }
      ]
    }
  ]
}

Leverage Tier Details

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

url = "BASE_URL/v2/public/leverage/bracket/detail"
params = {"symbol": "btc_usdt"}

qs = urlencode(sorted(params.items()))
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const url = "BASE_URL/v2/public/leverage/bracket/detail";
const params = { symbol: "btc_usdt" };

async function fetchBracketDetailSimple() {
  try {
    const res = await axios.get(url, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": API_SECRET,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
    if (res.data.code === 0) {
      const d = res.data.data;
      console.log("symbol:", d.symbol);
      d.leverageBrackets.forEach(b => {
        console.log(" bracket:", b.bracket, "maxLeverage:", b.maxLeverage, "maxPosition:", b.maxPosition);
      });
    }
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchBracketDetailSimple();

Description: Get leverage tier details for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/leverage/bracket/detail

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt

Field Description:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "symbol": "btc_usdt",
    "leverageBrackets": [
      {
        "symbolId": 1,
        "bracket": 1,
        "maxPosition": "1000.00000000",
        "maxLeverage": "125",
        "maintenanceMargin": "0.0040",
        "maintenanceAmount": "0.00000000",
        "symbol": "btc_usdt"
      },
      {
        "symbolId": 1,
        "bracket": 2,
        "maxPosition": "5000.00000000",
        "maxLeverage": "100",
        "maintenanceMargin": "0.0050",
        "maintenanceAmount": "0.00000000",
        "symbol": "btc_usdt"
      }
    ]
  }
}

Get Trading Pair Risk Fund Balance

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/v2/public/contract/risk-balance"

def build_signature(params):
    if not params:
        qs = ""
    else:
        qs = urlencode(sorted(params.items()))
    return hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

def fetch_risk_balance_signed(symbol, id=None, direction="NEXT", limit=10):
    params = {"symbol": symbol, "limit": limit}
    if id is not None:
        params["id"] = id
        params["direction"] = direction

    signature = build_signature(params)
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }

    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    first = fetch_risk_balance_signed("btc_usdt", limit=10)
    print("first page:", first)
    items = first.get("data", {}).get("items", []) or []
    if items:
        last_id = items[-1]["id"]
        next_page = fetch_risk_balance_signed("btc_usdt", id=last_id, direction="NEXT", limit=10)
        print("next page:", next_page)
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/v2/public/contract/risk-balance";

function buildSignature(params) {
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  return crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
}

async function fetchRiskBalanceSigned(symbol, id = undefined, direction = "NEXT", limit = 10) {
  const params = { symbol, limit };
  if (id !== undefined) {
    params.id = id;
    params.direction = direction;
  }

  const signature = buildSignature(params);
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };

  const res = await axios.get(URL, { headers, params, timeout: 10000 });
  return res.data;
}

(async () => {
  try {
    const first = await fetchRiskBalanceSigned("btc_usdt", undefined, "NEXT", 10);
    console.log("first page:", first);
    const items = (first.data && first.data.items) || [];
    if (items.length) {
      const lastId = items[items.length - 1].id;
      const next = await fetchRiskBalanceSigned("btc_usdt", lastId, "NEXT", 10);
      console.log("next page:", next);
    }
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
})();

Description: Get historical risk fund balance records for a specified trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/contract/risk-balance

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt
id No Cursor ID (for pagination, query backward or forward based on this ID) 1234567890
direction No Pagination direction: NEXT (backward) or PREV (forward) NEXT
limit No Number of records per page (default 10, minimum 1) 10

Field Description:

Field Name Field Type Description Example
id Long id id
coin String Currency "usdt"
amount BigDecimal Balance "0.000097"
createdTime Long Time 1769587200000

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "hasPrev": false,
        "hasNext": true,
        "items": [
            {
                "id": "587004485520343296",
                "coin": "usdt",
                "amount": "940677.25916082",
                "createdTime": 1769654775364
            },
            {
                "id": "586962652094284032",
                "coin": "usdt",
                "amount": "940676.44076082",
                "createdTime": 1769644801498
            }
        ]
    },
    "bizCode": null
}

Field Description:


Get Trading Pair Open Interest

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/v2/public/contract/open-interest"

def fetch_open_interest_signed(symbol="btc_usdt"):
    params = {"symbol": symbol}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(fetch_open_interest_signed("btc_usdt"))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/v2/public/contract/open-interest";

async function fetchOpenInterestSigned(symbol = "btc_usdt") {
  const params = { symbol };
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

  try {
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    return res.data;
  } catch (err) {
    throw err.response ? err.response.data : err;
  }
}

fetchOpenInterestSigned("btc_usdt").then(console.log).catch(console.error);

Description: Get open interest data for a trading pair.

Interface Weight: 1

Request Method: GET
Request URL: /v2/public/contract/open-interest

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Description Example
symbol Yes Trading pair identifier btc_usdt

Field Description

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "symbol": "btc_usdt",
        "openInterest": "95.2852",
        "openInterestUsd": "9153000.787852",
        "time": 1769668629274
    },
    "bizCode": null
}

DeFi Contract List

import time
import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/common/v2/perpetual/contracts"

def fetch_contracts_signed(timestamp_ms=None):
    if timestamp_ms is None:
        timestamp_ms = int(time.time() * 1000)
    params = {"timestamp": timestamp_ms}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    data = fetch_contracts_signed(1672531200000)
    print(data)
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/common/v2/perpetual/contracts";

async function fetchContractsSigned(timestampMs = Date.now()) {
  const params = { timestamp: timestampMs };
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

  try {
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    console.log(res.data);
    return res.data;
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
}

fetchContractsSigned(1672531200000);

Description: Get DeFi-related perpetual contract information (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /common/v2/perpetual/contracts

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
timestamp Yes Timestamp (milliseconds), used to determine K-line date, this time is based on server time 1769126400000

Field Description:

Note:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "symbol": "ETH_USDT",
            "baseAsset": "ETH",
            "quoteAsset": "USDT",
            "open": 2950.79,
            "close": 2954.81,
            "hign": 3016.57,
            "low": 2889.92,
            "Amount": 5864.8700,
            "volume": 17305605.20324
        },
        {
            "symbol": "BTC_USDT",
            "baseAsset": "BTC",
            "quoteAsset": "USDT",
            "open": 89511.8,
            "close": 89552.0,
            "hign": 91180.0,
            "low": 88507.4,
            "Amount": 744.7113,
            "volume": 66833951.2478195
        }
    ],
    "bizCode": null
}

DeFi Trading Fees

import time
import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/common/v2/perpetual/fee"

def fetch_defi_fee_signed(timestamp_ms=None):
    if timestamp_ms is None:
        timestamp_ms = int(time.time() * 1000)
    params = {"timestamp": timestamp_ms}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(fetch_defi_fee_signed(1672531200000))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/common/v2/perpetual/fee";

async function fetchDefiFeeSigned(timestampMs = Date.now()) {
  const params = { timestamp: timestampMs };
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(URL, { headers, params, timeout: 10000 });
  return res.data;
}

fetchDefiFeeSigned(1672531200000).then(console.log).catch(err => console.error(err.response ? err.response.data : err.message));

Description: Get DeFi-related trading fee information (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /common/v2/perpetual/fee

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
timestamp Yes Timestamp (milliseconds), used to determine calculation date 1769126400000

Calculation Logic:

  1. Get total trading volume (USDT) for all trading pairs on the specified date
  2. Use different fee rates based on the day of the week (0-6 corresponding to Sunday to Saturday)
  3. Fee rate table: ["0.00041", "0.00047", "0.00026", "0.00031", "0.00044", "0.0004", "0.00037"]
  4. Total fee = Total trading volume × Corresponding fee rate

Fee Rate Corresponding Table:

Day of Week Index Fee Rate
Sunday 0 0.00041
Monday 1 0.00047
Tuesday 2 0.00026
Wednesday 3 0.00031
Thursday 4 0.00044
Friday 5 0.00040
Saturday 6 0.00037

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "totalFee": 56660.7559
    },
    "bizCode": null
}

CMC Contract List

import requests
import hmac
import hashlib

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/cmc/v2/perpetual/contracts"

qs = ""
signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.get(URL, headers=headers, timeout=10)
resp.raise_for_status()
print(resp.json())
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/cmc/v2/perpetual/contracts";

const qs = "";
const signature = crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");

(async () => {
  try {
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
})();

Description: Get CoinMarketCap format perpetual contract list (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cmc/v2/perpetual/contracts

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

This interface does not require query parameters.

Field Description:

Field Type Description Example
ticker_id string Trading pair identifier "BTC_USDT"
base_currency string Base currency "BTC"
target_currency string Quote currency "USDT"
last_price string Latest price "45000.00"
base_volume string 24-hour trading volume in base currency "1250.5"
usd_volume string 24-hour trading volume in USD "56272500.00"
target_volume string 24-hour trading volume in quote currency "56272500.00"
bid string Current best bid price "44999.50"
ask string Current best ask price "45000.50"
high string 24-hour highest price "45500.00"
low string 24-hour lowest price "44500.00"
product_type string Product type
Perpetual: Perpetual contract
Fixed: Fixed-term contract
"Perpetual"
open_interest string Open interest (base currency) "12500.00"
open_interest_usd string Open interest (USD denominated) "562500000.00"
index_price string Index price "44950.00"
creation_timestamp integer Creation timestamp (fixed-term contracts)
Fixed-term contracts: has value
Perpetual contracts: null
1638316800000
expiry_timestamp integer Expiry timestamp (fixed-term contracts)
Fixed-term contracts: has value
Perpetual contracts: null
1640995200000
funding_rate string Current funding rate "0.0001"
next_funding_rate_timestamp integer Next funding rate collection timestamp 1672617600000
maker_fee string Maker fee rate "0.0002"
taker_fee string Taker fee rate "0.0004"

Response Example:

[
  {
    "ticker_id": "BTC_USDT",
    "base_currency": "BTC",
    "target_currency": "USDT",
    "last_price": "45000.00",
    "base_volume": "1250.5",
    "usd_volume": "56272500.00",
    "target_volume": "56272500.00",
    "bid": "44999.50",
    "ask": "45000.50",
    "high": "45500.00",
    "low": "44500.00",
    "product_type": "Perpetual",
    "open_interest": "12500.00",
    "open_interest_usd": "562500000.00",
    "index_price": "44950.00",
    "creation_timestamp": 1638316800000,
    "expiry_timestamp": 1640995200000,
    "funding_rate": "0.0001",
    "next_funding_rate_timestamp": 1672617600000,
    "maker_fee": "0.0002",
    "taker_fee": "0.0004"
  },
  {
    "ticker_id": "ETH_USDT",
    "base_currency": "ETH",
    "target_currency": "USDT",
    "last_price": "3000.00",
    "base_volume": "50000.0",
    "usd_volume": "150000000.00",
    "target_volume": "150000000.00",
    "bid": "2999.50",
    "ask": "3000.50",
    "high": "3100.00",
    "low": "2950.00",
    "product_type": "Perpetual",
    "open_interest": "250000.00",
    "open_interest_usd": "750000000.00",
    "index_price": "2995.00",
    "creation_timestamp": null,
    "expiry_timestamp": null,
    "funding_rate": "0.00015",
    "next_funding_rate_timestamp": 1672617600000,
    "maker_fee": "0.0002",
    "taker_fee": "0.0004"
  }
]

CMC Contract Specifications

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/cmc/v2/perpetual/contract_specs"

def contract_specs_signed(symbol: str):
    params = {"symbol": symbol}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(contract_specs_signed("btc_usdt"))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/cmc/v2/perpetual/contract_specs";

function signParams(params = {}) {
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  return crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
}

async function contractSpecsSigned(symbol = "btc_usdt") {
  const params = { symbol };
  const signature = signParams(params);
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(URL, { headers, params, timeout: 10000 });
  return res.data;
}

contractSpecsSigned("btc_usdt").then(console.log).catch(err => console.error(err.response ? err.response.data : err.message));

Description: Get CoinMarketCap format contract specification information (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cmc/v2/perpetual/contract_specs

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
symbol Yes Trading pair identifier BTC_USDT

Field Description:

Response Example:

{
    "contract_type": "Vanilla",
    "contract_price": 88264.1,
    "contract_price_currency": "USDT"
}

CMC Depth

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
BASE = "BASE_URL"

def sign_params(params: dict) -> str:
    qs = urlencode(sorted(params.items())) if params else ""
    return hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

def contract_specs_simple(symbol):
    url = f"{BASE}/cmc/v2/perpetual/contract_specs"
    params = {"symbol": symbol}
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": API_SECRET,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    r = requests.get(url, headers=headers, params=params, timeout=10)
    r.raise_for_status()
    return r.json()

def contract_specs_signed(symbol):
    url = f"{BASE}/cmc/v2/perpetual/contract_specs"
    params = {"symbol": symbol}
    signature = sign_params(params)
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    r = requests.get(url, headers=headers, params=params, timeout=10)
    r.raise_for_status()
    return r.json()

def depth_simple(symbol):
    url = f"{BASE}/cmc/v2/perpetual/depth"
    params = {"symbol": symbol}
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": API_SECRET,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    r = requests.get(url, headers=headers, params=params, timeout=10)
    r.raise_for_status()
    return r.json()

def depth_signed(symbol):
    url = f"{BASE}/cmc/v2/perpetual/depth"
    params = {"symbol": symbol}
    signature = sign_params(params)
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    r = requests.get(url, headers=headers, params=params, timeout=10)
    r.raise_for_status()
    return r.json()

if __name__ == "__main__":
    s = "btc_usdt"
    print("contract_specs (simple):", contract_specs_simple(s))
    print("contract_specs (signed):", contract_specs_signed(s))
    print("depth (simple):", depth_simple(s))
    print("depth (signed):", depth_signed(s))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const BASE = "BASE_URL";

function signParams(params = {}) {
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  return crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
}

async function contractSpecsSimple(symbol) {
  const url = `${BASE}/cmc/v2/perpetual/contract_specs`;
  const params = { symbol };
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(url, { headers, params, timeout: 10000 });
  return res.data;
}

async function contractSpecsSigned(symbol) {
  const url = `${BASE}/cmc/v2/perpetual/contract_specs`;
  const params = { symbol };
  const signature = signParams(params);
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(url, { headers, params, timeout: 10000 });
  return res.data;
}

async function depthSimple(symbol) {
  const url = `${BASE}/cmc/v2/perpetual/depth`;
  const params = { symbol };
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": API_SECRET,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(url, { headers, params, timeout: 10000 });
  return res.data;
}

async function depthSigned(symbol) {
  const url = `${BASE}/cmc/v2/perpetual/depth`;
  const params = { symbol };
  const signature = signParams(params);
  const headers = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
  };
  const res = await axios.get(url, { headers, params, timeout: 10000 });
  return res.data;
}

(async () => {
  try {
    const s = "btc_usdt";
    console.log("contractSpecsSimple:", await contractSpecsSimple(s));
    console.log("contractSpecsSigned:", await contractSpecsSigned(s));
    console.log("depthSimple:", await depthSimple(s));
    console.log("depthSigned:", await depthSigned(s));
  } catch (err) {
    console.error(err.response ? err.response.data : err.message);
  }
})();

Description: Get CoinMarketCap format depth data (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cmc/v2/perpetual/depth

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
symbol Yes Trading pair identifier BTC_USDT

Field Description:

Response Example:

{
  "ticker_id": "btc_usdt",
  "asks": [
    ["45001.00", "1.5"],
    ["45002.00", "2.3"],
    ["45003.00", "3.1"]
  ],
  "bids": [
    ["44999.00", "2.1"],
    ["44998.00", "1.8"],
    ["44997.00", "0.9"]
  ],
  "timestamp": 1672531200000
}

CG Contract List

import requests
import hmac
import hashlib

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/cg/v2/perpetual/contracts"

def fetch_cg_contracts_signed():
    sig = hmac.new(API_SECRET.encode(), b"", hashlib.sha256).hexdigest()
    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": sig,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    try:
        print(fetch_cg_contracts_signed())
    except Exception as e:
        print("Error:", e)
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/cg/v2/perpetual/contracts";

async function fetchCgContractsSigned() {
  try {
    const signature = crypto.createHmac("sha256", API_SECRET).update("").digest("hex");
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      timeout: 10000,
    });
    console.log(res.data);
  } catch (err) {
    console.error("Error:", err.response ? err.response.data : err.message);
  }
}

fetchCgContractsSigned();

Description: Get CoinGecko format perpetual contract list (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cg/v2/perpetual/contracts

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

This interface does not require query parameters.

Field Description:

Field Type Description Example
ticker_id string Trading pair identifier "ETH_USDT"
base_currency string Base currency "ETH"
target_currency string Quote currency "USDT"
last_price number Latest price 2953.89
base_volume number 24-hour trading volume in base currency 4581.96385226
usd_volume number 24-hour trading volume in USD 13534617.20354
target_volume number 24-hour trading volume in quote currency 13534617.20354
bid number Current best bid price 2953.48
ask number Current best ask price 2954.92
high number 24-hour highest price 3044.35
low number 24-hour lowest price 2935.93
product_type string Product type
Perpetual: Perpetual contract
Fixed: Fixed-term contract
"Perpetual"
open_interest number Open interest (base currency) 12932.388206500004760000
open_interest_usd number Open interest (USD denominated) 38210682.318490364060564000000
index_price number Index price 2954.01
index_currency string Index quote currency "USDT"
funding_rate number Current funding rate 0.000094
next_funding_rate number Next funding rate 0.000094
next_funding_rate_timestamp integer Next funding rate collection timestamp 1769673600000
start_timestamp integer Start timestamp 0
end_timestamp integer End timestamp 0
maker_fee number Maker fee rate 0.000200000000000000
taker_fee number Taker fee rate 0.000500000000000000

Response Example:

[
    {
        "ticker_id": "ETH_USDT",
        "base_currency": "ETH",
        "target_currency": "USDT",
        "last_price": 2953.89,
        "base_volume": 4581.96385226,
        "usd_volume": 13534617.20354,
        "target_volume": 13534617.20354,
        "bid": 2953.48,
        "ask": 2954.92,
        "high": 3044.35,
        "low": 2935.93,
        "product_type": "Perpetual",
        "open_interest": 12932.388206500004760000,
        "open_interest_usd": 38210682.318490364060564000000,
        "index_price": 2954.01,
        "index_currency": "USDT",
        "funding_rate": 0.000094,
        "next_funding_rate": 0.000094,
        "next_funding_rate_timestamp": 1769673600000,
        "start_timestamp": 0,
        "end_timestamp": 0,
        "maker_fee": 0.000200000000000000,
        "taker_fee": 0.000500000000000000
    },
    {
        "ticker_id": "BTC_USDT",
        "base_currency": "BTC",
        "target_currency": "USDT",
        "last_price": 88277.4,
        "base_volume": 890.30512045,
        "usd_volume": 78593821.24044,
        "target_volume": 78593821.24044,
        "bid": 88276.9,
        "ask": 88278.1,
        "high": 90554.3,
        "low": 87666.2,
        "product_type": "Perpetual",
        "open_interest": 813.704894400000045850,
        "open_interest_usd": 72965740.53700200404752337500,
        "index_price": 88277.4,
        "index_currency": "USDT",
        "funding_rate": 0.000084,
        "next_funding_rate": 0.000084,
        "next_funding_rate_timestamp": 1769673600000,
        "start_timestamp": 0,
        "end_timestamp": 0,
        "maker_fee": 0.000200000000000000,
        "taker_fee": 0.000500000000000000
    }
]

CG Contract Specifications

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/cg/v2/perpetual/contract_specs"

def contract_specs_signed(ticker_id: str):
    params = {"ticker_id": ticker_id}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(contract_specs_signed("btc_usdt"))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/cg/v2/perpetual/contract_specs";

function signParams(params = {}) {
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  return crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
}

async function contractSpecsSigned(tickerId = "btc_usdt") {
  const params = { ticker_id: tickerId };
  const signature = signParams(params);
  try {
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    return res.data;
  } catch (err) {
    throw err.response ? err.response.data : err;
  }
}

contractSpecsSigned("btc_usdt").then(console.log).catch(console.error);

Description: Get CoinGecko format contract specification information (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cg/v2/perpetual/contract_specs

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
ticker_id Yes Trading pair identifier BTC_USDT

Field Description:

Response Example:

{
  "contract_type": "Vanilla",
  "contract_price": "45000.00",
  "contract_price_currency": "USDT"
}

CG Depth

import requests
import hmac
import hashlib
from urllib.parse import urlencode

API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
URL = "BASE_URL/cg/v2/perpetual/depth"

def fetch_depth_signed(ticker_id: str, depth: int = 50):
    params = {"ticker_id": ticker_id, "depth": depth}
    qs = urlencode(sorted(params.items()))
    signature = hmac.new(API_SECRET.encode(), qs.encode(), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
    }
    resp = requests.get(URL, headers=headers, params=params, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(fetch_depth_signed("btc_usdt", 50))
const axios = require("axios");
const crypto = require("crypto");

const API_KEY = "YOUR_API_KEY";
const API_SECRET = "YOUR_API_SECRET";
const URL = "BASE_URL/cg/v2/perpetual/depth";

function signParams(params = {}) {
  const keys = Object.keys(params).sort();
  const entries = keys.map(k => [k, params[k]]);
  const qs = new URLSearchParams(entries).toString();
  return crypto.createHmac("sha256", API_SECRET).update(qs).digest("hex");
}

async function fetchDepthSigned(tickerId = "btc_usdt", depth = 50) {
  const params = { ticker_id: tickerId, depth };
  const signature = signParams(params);

  try {
    const res = await axios.get(URL, {
      headers: {
        "X_ACCESS_KEY": API_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      params,
      timeout: 10000,
    });
    return res.data;
  } catch (err) {
    throw err.response ? err.response.data : err;
  }
}

fetchDepthSigned("btc_usdt", 50).then(console.log).catch(console.error);

Description: Get CoinGecko format depth data (third-party data interface).

Interface Weight: 1

Request Method: GET
Request URL: /cg/v2/perpetual/depth

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Description Example
ticker_id Yes Trading pair identifier BTC_USDT
depth No Depth count (default 50) 50

Field Description:

Response Example:

{
  "ticker_id": "btc_usdt",
  "asks": [
    ["45001.00", "1.5"],
    ["45002.00", "2.3"],
    ["45003.00", "3.1"]
  ],
  "bids": [
    ["44999.00", "2.1"],
    ["44998.00", "1.8"],
    ["44997.00", "0.9"]
  ],
  "timestamp": 1672531200000
}

Trading and Account Interface

Create Order

import requests
import json

BASE_URL = "BASE_URL"
API_KEY = "your_api_accessKey"
X_SIGNATURE = "your_api_query_secretKey"
HEADERS = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": X_SIGNATURE,
    "Content-Type": "application/x-www-form-urlencoded"
}

payload = {
    "symbol": "btc_usdt",
    "orderType": "LIMIT",
    "orderSide": "BUY",
    "positionSide": "LONG",
    "price": "45000.00",
    "origQty": "1.0",
    "timeInForce": "GTC",
    "reduceOnly": False
}

try:
    response = requests.post(f"{BASE_URL}/v2/order/create", 
                            headers=HEADERS, json=payload)
    data = response.json()

    if response.status_code == 200 and data.get("code") == 0:
        print("Order created successfully")
        print(f"Symbol: {payload['symbol']}, Type: {payload['orderType']}, "
              f"Side: {payload['orderSide']}, Price: {payload['price']}, "
              f"Quantity: {payload['origQty']}")
    else:
        print(f"Error: {data.get('message', 'Unknown error')}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
const axios = require('axios');

const BASE_URL = 'BASE_URL';
const API_KEY = 'your_api_accessKey';
const X_SIGNATURE = 'your_api_query_secretKey';

const headers = {
  'X_ACCESS_KEY': API_KEY,
  'X_SIGNATURE': X_SIGNATURE,
  'Content-Type': 'application/x-www-form-urlencoded'
};

async function createOrder(orderOptions) {
  try {
    const payload = {
      symbol: orderOptions.symbol,
      orderType: orderOptions.orderType || 'LIMIT',
      orderSide: orderOptions.orderSide,
      positionSide: orderOptions.positionSide,
      price: orderOptions.price,
      origQty: orderOptions.origQty,
      timeInForce: orderOptions.timeInForce || 'GTC',
      reduceOnly: orderOptions.reduceOnly || false,
      clientOrderId: orderOptions.clientOrderId,
      leverage: orderOptions.leverage,
      positionId: orderOptions.positionId,
      triggerProfitPrice: orderOptions.triggerProfitPrice,
      triggerStopPrice: orderOptions.triggerStopPrice,
      marketOrderLevel: orderOptions.marketOrderLevel,
      profitOrderType: orderOptions.profitOrderType,
      stopOrderType: orderOptions.stopOrderType,
      profitOrderPrice: orderOptions.profitOrderPrice,
      stopOrderPrice: orderOptions.stopOrderPrice
    };

    Object.keys(payload).forEach(key => payload[key] === undefined && delete payload[key]);

    const response = await axios.post(`${BASE_URL}/v2/order/create`, 
                                     payload, { headers });

    if (response.data.code === 0) {
      console.log('Order created successfully');
      console.log(`Symbol: ${payload.symbol}, Type: ${payload.orderType}, ` +
                 `Side: ${payload.orderSide}, Price: ${payload.price}, ` +
                 `Quantity: ${payload.origQty}`);
      return response.data;
    } else {
      throw new Error(response.data.message || 'Unknown error');
    }
  } catch (error) {
    console.error('Error creating order:', error.message);
    throw error;
  }
}

createOrder({
  symbol: 'btc_usdt',
  orderType: 'LIMIT',
  orderSide: 'BUY',
  positionSide: 'LONG',
  price: '45000.00',
  origQty: '1.0',
  timeInForce: 'GTC',
  reduceOnly: false
})
  .then(result => {
  })
  .catch(error => {
  });

Description: Create a new trading order (limit or market order, take profit/stop loss order).

Interface Weight: 20

Request Method: POST
Request URL: (TRADE)/v2/order/create

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters (body):

Parameter Required Description Example Enum Values
symbol Yes Trading pair btc_usdt -
orderType Yes Order type: LIMIT (limit), MARKET (market) LIMIT LIMIT, MARKET
orderSide Yes Trade direction: BUY (buy), SELL (sell) BUY BUY, SELL
positionSide Yes Position direction: LONG (long), SHORT (short), BOTH (both) LONG LONG, SHORT, BOTH
price No Price (required for limit orders, optional for market orders) 45000.00 -
origQty Yes Quantity (contracts) 1.0 -
timeInForce No Time in force: GTC (good till canceled), IOC (immediate or cancel), FOK (fill or kill), GTX GTC GTC, IOC, FOK, GTX
reduceOnly No Reduce only (default false) false true, false
clientOrderId No Custom order ID (1-32 alphanumeric characters) myOrder123 -
leverage Yes Leverage multiple 20 -
positionId No Position ID (required when closing positions) 123456 -
triggerProfitPrice No Take profit trigger price 46000.00 -
triggerStopPrice No Stop loss trigger price 44000.00 -
marketOrderLevel No Market order best level: 1 (counter price), 5, 10, 15 levels 1 1, 5, 10, 15
profitOrderType No Take profit order type: MARKET/LIMIT MARKET MARKET, LIMIT
stopOrderType No Stop loss order type: MARKET/LIMIT MARKET MARKET, LIMIT
profitOrderPrice No LIMIT take profit order price (required when profitOrderType is LIMIT) 45900.00 -
stopOrderPrice No LIMIT stop loss order price (required when stopOrderType is LIMIT) 44100.00 -

Notes

  1. Limit Orders: Must provide price parameter
  2. Market Orders: price parameter is optional, if provided will be used as reference price
  3. Closing Orders: When closing positions, must provide positionId and reduceOnly=true
  4. Conditional Orders: When setting take profit/stop loss, need to set both trigger price and order type
  5. Reduce Only: When reduceOnly=true, the order can only reduce existing positions, not increase them

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": "587077935051136448",
    "bizCode": null
}
error:
{
    "code": -1,
    "msg": "order_leverage_not_match_position_leverage",
    "data": null,
    "bizCode": "1000"
}

Batch Create Orders

import requests
import json
import hashlib
import time

class FutureExchangeAPI:
    def __init__(self, api_key, secret_key, base_url="BASE_URL"):
        self.api_key = api_key
        self.secret_key = secret_key
        self.base_url = base_url

    def _generate_signature(self, params_str):
        return hashlib.md5((params_str + self.secret_key).encode()).hexdigest()

    def create_batch_orders(self, orders_list):

        endpoint = "/v2/order/create-batch"
        url = self.base_url + endpoint

        list_json = json.dumps(orders_list, separators=(',', ':'))

        params = {
            "list": list_json
        }

        sorted_params = "&".join([f"{k}={v}" for k, v in sorted(params.items())])

        signature = self._generate_signature(sorted_params)

        headers = {
            "X_ACCESS_KEY": self.api_key,
            "X_SIGNATURE": signature,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        response = requests.post(url, headers=headers, data=params)

        return response.json()

if __name__ == "__main__":
    API_KEY = "your_api_accessKey"
    SECRET_KEY = "your_api_query_secretKey"

    client = FutureExchangeAPI(API_KEY, SECRET_KEY)

    orders = [
        {
            "isCreate": True,
            "symbol": "btc_usdt",
            "price": 45000.00,
            "origQty": 1.0,
            "orderType": "LIMIT",
            "orderSide": "BUY",
            "positionSide": "LONG",
            "timeInForce": "GTC",
            "positionId": 0,
            "clientOrderId": "myOrder_123456789"
        },
        {
            "isCreate": True,
            "symbol": "eth_usdt",
            "price": 2220.00,
            "origQty": 2.0,
            "orderType": "LIMIT",
            "orderSide": "BUY",
            "positionSide": "LONG",
            "timeInForce": "GTC",
            "positionId": 0,
            "clientOrderId": "myOrder_987654321"
        },
        {
            "isCreate": False,
            "orderId": 1234567890,
            "symbol": "btc_usdt",
            "price": 0,
            "origQty": 0,
            "orderType": "LIMIT",
            "orderSide": "BUY",
            "positionSide": "LONG",
            "timeInForce": "GTC",
            "positionId": 0,
            "clientOrderId": ""
        }
    ]

    try:
        result = client.create_batch_orders(orders)
        print("response result:", json.dumps(result, indent=2))

        if result.get("code") == 0:
            print("Batch order creation successful!")
        else:
            print(f"Failed to create batch orders: {result.get('msg')}")

    except Exception as e:
        print(f"Request exception: {str(e)}")
const crypto = require('crypto');
const axios = require('axios');

class FutureExchangeAPI {
  constructor(apiKey, secretKey, baseUrl = 'BASE_URL') {
    this.apiKey = apiKey;
    this.secretKey = secretKey;
    this.baseUrl = baseUrl;
  }

  _generateSignature(paramsStr) {
    return crypto
            .createHash('md5')
            .update(paramsStr + this.secretKey)
            .digest('hex');
  }

  async createBatchOrders(ordersList) {

    const endpoint = '/v2/order/create-batch';
    const url = this.baseUrl + endpoint;

    const listJson = JSON.stringify(ordersList);

    const params = {
      list: listJson
    };

    const sortedParams = Object.keys(params)
            .sort()
            .map(key => `${key}=${params[key]}`)
            .join('&');

    const signature = this._generateSignature(sortedParams);

    const headers = {
      'X_ACCESS_KEY': this.apiKey,
      'X_SIGNATURE': signature,
      'Content-Type': 'application/x-www-form-urlencoded'
    };

    try {
      const response = await axios.post(url, new URLSearchParams(params).toString(), { headers });
      return response.data;
    } catch (error) {
      console.error('Request failed:', error.message);
      if (error.response) {
        console.error('response data:', error.response.data);
      }
      throw error;
    }
  }
}

(async () => {
  const API_KEY = 'your_api_accessKey';
  const SECRET_KEY = 'your_api_query_secretKey';

  const client = new FutureExchangeAPI(API_KEY, SECRET_KEY);

  const orders = [
    {
      isCreate: true,
      symbol: 'btc_usdt',
      price: 45000.00,
      origQty: 1.0,
      orderType: 'LIMIT',
      orderSide: 'BUY',
      positionSide: 'LONG',
      timeInForce: 'GTC',
      positionId: 0,
      clientOrderId: 'myOrder_123456789'
    },
    {
      isCreate: true,
      symbol: 'eth_usdt',
      price: 2220.00,
      origQty: 2.0,
      orderType: 'LIMIT',
      orderSide: 'BUY',
      positionSide: 'LONG',
      timeInForce: 'GTC',
      positionId: 0,
      clientOrderId: 'myOrder_987654321'
    },
    {
      isCreate: false,
      orderId: 1234567890,
      symbol: 'btc_usdt',
      price: 0,
      origQty: 0,
      orderType: 'LIMIT',
      orderSide: 'BUY',
      positionSide: 'LONG',
      timeInForce: 'GTC',
      positionId: 0,
      clientOrderId: ''
    }
  ];

  try {
    const result = await client.createBatchOrders(orders);
    console.log('response result:', JSON.stringify(result, null, 2));

    if (result.code === 0) {
      console.log('Batch order creation successful!');
    } else {
      console.log(`Failed to create batch orders: ${result.msg}`);
    }
  } catch (error) {
    console.error('Request exception:', error.message);
  }
})();

Description: Batch create multiple orders.

Interface Weight: 15

Request Method: POST
Request URL: (TRADE)/v2/order/create-batch

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters (body):

Parameter Required Description Example Explanation
list Yes Array parameter converted to JSON format "[ { "isCreate": true, "symbol": "btc_usdt", "price": 45000.00, "origQty": 1.0, "orderType": "LIMIT", "orderSide": "BUY", "positionSide": "LONG", "timeInForce": "GTC", "positionId": 0, "clientOrderId": "myOrder_123456789" }, { "isCreate": false, "orderId": 1234567890, "symbol": "btc_usdt" } ]" -

Parameter list Explanation

Parameter Required Description Example Explanation
isCreate Yes Operation type: true (create order), false (cancel order) true -
orderId Yes Order ID (required when isCreate=false) 123456 -
symbol Yes Trading pair btc_usdt -
price Yes Price (required when isCreate=true) 45000.00 -
origQty Yes Quantity (contracts) (required when isCreate=true) 1.0 -
orderType Yes Order type: LIMIT, MARKET (required when isCreate=true) LIMIT -
orderSide Yes Trade direction: BUY, SELL (required when isCreate=true) BUY -
positionSide Yes Position direction: LONG, SHORT (required when isCreate=true) LONG -
timeInForce Yes Time in force: GTC, IOC, FOK, GTX (required when isCreate=true) GTC -
positionId No Position ID 123456 -
clientOrderId No Custom order ID myOrder123 -

Request Body Example: json [ { "isCreate": true, "symbol": "btc_usdt", "price": 45000.00, "origQty": 1.0, "orderType": "LIMIT", "orderSide": "BUY", "positionSide": "LONG", "timeInForce": "GTC", "positionId": 0, "clientOrderId": "myOrder_123456789" }, { "isCreate": false, "orderId": 1234567890, "symbol": "btc_usdt", "price": 0, "origQty": 0, "orderType": "LIMIT", "orderSide": "BUY", "positionSide": "LONG", "timeInForce": "GTC", "positionId": 0, "clientOrderId": "" } ]

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": true,
    "bizCode": null
}

Cancel Order

import requests
import json

BASE_URL = "BASE_URL"
API_KEY = "your_api_accessKey"
X_SIGNATURE = "your_api_query_secretKey"
HEADERS = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": X_SIGNATURE,
    "Content-Type": "application/x-www-form-urlencoded"
}

order_id = 1234567890
payload = {"orderId": order_id}

try:
    response = requests.post(f"{BASE_URL}/v2/order/cancel", 
                            headers=HEADERS, json=payload)
    data = response.json()

    if response.status_code == 200 and data.get("code") == 0:
        print(f"Order {order_id} cancelled successfully")
    else:
        print(f"Error cancelling order {order_id}: {data.get('message', 'Unknown error')}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
const axios = require('axios');

const BASE_URL = 'BASE_URL';
const API_KEY = 'your_api_accessKey';
const X_SIGNATURE = 'your_api_query_secretKey';

const headers = {
  'X_ACCESS_KEY': API_KEY,
  'X_SIGNATURE': X_SIGNATURE,
  'Content-Type': 'application/x-www-form-urlencoded'
};

async function cancelOrder(orderId) {
  try {
    const payload = { orderId };

    const response = await axios.post(`${BASE_URL}/v2/order/cancel`, 
                                     payload, { headers });

    if (response.data.code === 0) {
      console.log(`Order ${orderId} cancelled successfully`);
      return response.data;
    } else {
      throw new Error(response.data.message || 'Unknown error');
    }
  } catch (error) {
    console.error(`Error cancelling order ${orderId}:`, error.message);
    throw error;
  }
}

cancelOrder(1234567890)
  .then(result => {
  })
  .catch(error => {
  });

Description: Cancel a specified order.

Interface Weight: 5

Request Method: POST
Request URL: (TRADE)/v2/order/cancel

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters (body):

Parameter Required Type Description Example
orderId Yes string Order ID 1234567890
symbol No string Trading pair identifier btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Batch Cancel Orders

import json
import hmac
import hashlib
from urllib.parse import urlencode
import requests

url = "BASE_URL/v2/order/cancel-batch"
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"

orders = ["1234567890", "1234567891"]

body_dict = {"orders": json.dumps(orders)}
body_str = urlencode(body_dict)

signature = hmac.new(secret_key.encode("utf-8"), body_str.encode("utf-8"), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": access_key,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.post(url, data=body_str, headers=headers)
print(resp.status_code)
print(resp.text)
const crypto = require('crypto');

const url = "BASE_URL/v2/order/cancel-batch";
const accessKey = "YOUR_ACCESS_KEY";
const secretKey = "YOUR_SECRET_KEY";

const orders = ["1234567890", "1234567891"];

const params = new URLSearchParams();
params.append("orders", JSON.stringify(orders));
const bodyStr = params.toString();

const signature = crypto.createHmac('sha256', secretKey).update(bodyStr).digest('hex');

const headers = {
  "X_ACCESS_KEY": accessKey,
  "X_SIGNATURE": signature,
  "Content-Type": "application/x-www-form-urlencoded"
};

(async () => {
  const resp = await fetch(url, {
    method: "POST",
    headers,
    body: bodyStr
  });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
})();

Description: Batch cancel multiple orders.

Interface Weight: 8

Request Method: POST
Request URL: (TRADE)/v2/order/cancel-batch

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters (array format): json ["1234567890", "1234567891"]

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Cancel All Orders

import json
import hmac
import hashlib
from urllib.parse import urlencode
import requests

url = "BASE_URL/v2/order/cancel-all"
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"

body_dict = {"symbol": "btc_usdt"} 
body_str = urlencode(body_dict)

signature = hmac.new(secret_key.encode("utf-8"), body_str.encode("utf-8"), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": access_key,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

resp = requests.post(url, data=body_str, headers=headers)
print(resp.status_code)
print(resp.text)

body_str_empty = ""
signature_empty = hmac.new(secret_key.encode("utf-8"), body_str_empty.encode("utf-8"), hashlib.sha256).hexdigest()
headers["X_SIGNATURE"] = signature_empty
resp_all = requests.post(url, data=body_str_empty, headers=headers)
print(resp_all.status_code)
print(resp_all.text)
const crypto = require('crypto');
const fetch = global.fetch || require('node-fetch');

const url = "BASE_URL/v2/order/cancel-all";
const accessKey = "YOUR_ACCESS_KEY";
const secretKey = "YOUR_SECRET_KEY";

async function cancelBySymbol(symbol) {
  const params = new URLSearchParams();
  params.append("symbol", symbol);
  const bodyStr = params.toString();

  const signature = crypto.createHmac('sha256', secretKey).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": accessKey,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(url, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelBySymbol("btc_usdt");

async function cancelAll() {
  const bodyStr = "";
  const signature = crypto.createHmac('sha256', secretKey).update(bodyStr).digest('hex');
  const headers = {
    "X_ACCESS_KEY": accessKey,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };
  const resp = await fetch(url, { method: "POST", headers, body: bodyStr });
  const result = await resp.json().catch(() => await resp.text());
  console.log(resp.status, result);
}
cancelAll();

Description: Cancel all orders for the current user or all orders for a specified trading pair.

Interface Weight: 10

Request Method: POST
Request URL: (TRADE)/v2/order/cancel-all

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier (cancel all if not provided) btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Query Order List

import hashlib
import hmac
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order/list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "symbol": "btc_usdt",
    "state": "UNFINISHED",
    "page": 1,
    "size": 10,
    # "startTime": 1672444800000,
    # "endTime": 1672531200000,
}

params = {k: v for k, v in params.items() if v is not None}

sorted_items = sorted(params.items())
query_str = urlencode(sorted_items)  # e.g. "page=1&size=10&state=UNFINISHED&symbol=btc_usdt"

signature = hmac.new(SECRET_KEY.encode('utf-8'), query_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded",
}

url = BASE + ("?" + query_str if query_str else "")
resp = requests.get(url, headers=headers)
print(resp.status_code)
print(resp.text)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order/list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

const params = {
  symbol: "btc_usdt",
  state: "UNFINISHED",
  page: 1,
  size: 10,
  // startTime: 1672444800000,
  // endTime: 1672531200000
};

const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
entries.sort((a, b) => a[0].localeCompare(b[0]));

const usp = new URLSearchParams();
for (const [k, v] of entries) {
  usp.append(k, String(v));
}
const queryStr = usp.toString(); // "page=1&size=10&state=UNFINISHED&symbol=btc_usdt"

const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

const headers = {
  "X_ACCESS_KEY": ACCESS_KEY,
  "X_SIGNATURE": signature,
  "Content-Type": "application/x-www-form-urlencoded"
};

const url = BASE + (queryStr ? `?${queryStr}` : "");

(async () => {
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
})();

Description: Query order list with support for pagination and filtering.

Interface Weight: 2

Request Method: GET
Request URL: /v2/order/list

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt
state No string Order status: NEW/PARTIALLY_FILLED/FILLED etc. UNFINISHED
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000
page No integer Page number (default 1) 1
size No integer Number of items per page (default 10) 10

Field Description:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be null) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Trade direction: BUY, SELL "BUY"
positionSide String Position direction: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full closing order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (contracts) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Filled quantity (contracts) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take profit trigger price (can be null) null
triggerStopPrice String (serialized) Stop loss trigger price (can be null) null
sourceId Long Conditional trigger ID (can be null) null
forceClose Boolean Whether it's a full closing order false
closeProfit String (serialized) Closing profit/loss (can be null) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

  1. Serialization Note: Fields like orderId, price, origQty are converted to string type via JsonSerialize annotation in the response to prevent precision loss when handling large numbers on the frontend.
  2. Time Unit: createdTime is a millisecond Unix timestamp.
  3. Numerical Fields: All BigDecimal type fields (such as price, quantity, margin) are returned as strings to preserve full precision.

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "page": 1,
        "ps": 10,
        "total": 1,
        "items": [
            {
                "orderId": "587077935051136448",
                "clientOrderId": null,
                "symbol": "btc_usdt",
                "orderType": "MARKET",
                "orderSide": "BUY",
                "positionSide": "LONG",
                "timeInForce": "IOC",
                "closePosition": false,
                "price": "0",
                "origQty": "1",
                "avgPrice": "88256.7",
                "executedQty": "1",
                "marginFrozen": "0.4524",
                "triggerProfitPrice": null,
                "triggerStopPrice": null,
                "sourceId": null,
                "forceClose": false,
                "closeProfit": null,
                "state": "FILLED",
                "createdTime": 1769672287213
            }
        ]
    },
    "bizCode": null
}

Query Historical Orders

import hashlib
import hmac
import time
import requests
from typing import Dict, List, Optional, Any
from urllib.parse import urlencode


class HistoryOrderAPI:

    def __init__(self, base_url: str, access_key: str, secret_key: str):

        self.base_url = base_url.rstrip('/')
        self.access_key = access_key
        self.secret_key = secret_key
        self.session = requests.Session()

    def _generate_signature(self, params: Dict[str, Any]) -> str:

        sorted_params = sorted(params.items(), key=lambda x: x[0])

        query_string = '&'.join(
            [f"{key}={value}" for key, value in sorted_params]
        )

        signature = hmac.new(
            self.secret_key.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()

        return signature

    def query_history_orders(
        self,
        symbol: Optional[str] = None,
        order_id: Optional[str] = None,
        direction: str = "NEXT",
        limit: int = 10,
        start_time: Optional[int] = None,
        end_time: Optional[int] = None
    ) -> Dict[str, Any]:

        try:
            params = {
                'timestamp': int(time.time() * 1000)
            }

            if symbol:
                params['symbol'] = symbol
            if order_id:
                params['id'] = order_id
            if direction in ['NEXT', 'PREV']:
                params['direction'] = direction
            if limit:
                params['limit'] = limit
            if start_time:
                params['startTime'] = start_time
            if end_time:
                params['endTime'] = end_time

            signature = self._generate_signature(params)

            url = f"{self.base_url}/v2/order/list-history"

            headers = {
                'X_ACCESS_KEY': self.access_key,
                'X_SIGNATURE': signature,
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }

            response = self.session.get(
                url,
                params=params,
                headers=headers,
                timeout=30
            )

            response.raise_for_status()

            data = response.json()

            if data.get('code') != 0:
                error_msg = data.get('msg', 'Unknown error')
                raise Exception(f"API error: {error_msg}")

            return data.get('data', {})

        except requests.exceptions.RequestException as e:
            raise Exception(f"Request failed: {str(e)}")
        except ValueError as e:
            raise Exception(f"Invalid response format: {str(e)}")

    def get_all_history_orders(
        self,
        symbol: str,
        batch_size: int = 50,
        max_orders: Optional[int] = None
    ) -> List[Dict[str, Any]]:

        all_orders = []
        last_order_id = None
        has_more = True

        try:
            while has_more:
                query_params = {
                    'symbol': symbol,
                    'limit': batch_size,
                    'direction': 'NEXT'
                }

                if last_order_id:
                    query_params['id'] = last_order_id

                response = self.query_history_orders(**query_params)

                if response.get('items'):
                    items = response['items']

                    all_orders.extend(items)

                    last_order_id = items[-1]['orderId']

                    has_more = len(items) == batch_size

                    if max_orders and len(all_orders) >= max_orders:
                        all_orders = all_orders[:max_orders]
                        break
                else:
                    has_more = False

                time.sleep(0.1)

            return all_orders

        except Exception as e:
            raise

    def get_orders_by_time_range(
        self,
        symbol: str,
        start_time: int,
        end_time: int,
        limit: int = 100
    ) -> List[Dict[str, Any]]:

        try:
            response = self.query_history_orders(
                symbol=symbol,
                start_time=start_time,
                end_time=end_time,
                limit=limit,
                direction='NEXT'
            )

            return response.get('items', [])

        except Exception as e:
            raise

    def get_order_statistics(
        self,
        symbol: str,
        days: int = 7
    ) -> Dict[str, Any]:

        try:
            end_time = int(time.time() * 1000)
            start_time = end_time - (days * 24 * 60 * 60 * 1000)

            orders = self.get_all_history_orders(
                symbol=symbol,
                max_orders=1000
            )

            if not orders:
                return {
                    'total_orders': 0,
                    'buy_orders': 0,
                    'sell_orders': 0,
                    'filled_orders': 0,
                    'canceled_orders': 0,
                    'total_volume': 0,
                    'avg_trade_size': 0
                }

            stats = {
                'total_orders': len(orders),
                'buy_orders': 0,
                'sell_orders': 0,
                'filled_orders': 0,
                'canceled_orders': 0,
                'total_volume': 0,
                'avg_trade_size': 0
            }

            for order in orders:
                if order.get('orderSide') == 'BUY':
                    stats['buy_orders'] += 1
                elif order.get('orderSide') == 'SELL':
                    stats['sell_orders'] += 1

                if order.get('state') == 'FILLED':
                    stats['filled_orders'] += 1
                    if order.get('executedQty'):
                        try:
                            qty = float(order['executedQty'])
                            stats['total_volume'] += qty
                        except (ValueError, TypeError):
                            pass
                elif order.get('state') == 'CANCELED':
                    stats['canceled_orders'] += 1

            if stats['filled_orders'] > 0:
                stats['avg_trade_size'] = stats['total_volume'] / stats['filled_orders']

            return stats

        except Exception as e:
            raise


def example_usage():

    BASE_URL = "https://api.example.com"
    ACCESS_KEY = "your_api_accessKey"
    SECRET_KEY = "your_api_secretKey"

    api_client = HistoryOrderAPI(BASE_URL, ACCESS_KEY, SECRET_KEY)

    try:
        recent_orders = api_client.query_history_orders(
            symbol="btc_usdt",
            limit=10
        )

        import datetime

        yesterday = datetime.datetime.now() - datetime.timedelta(days=1)
        start_ts = int(yesterday.timestamp() * 1000)
        end_ts = int(time.time() * 1000)

        time_range_orders = api_client.get_orders_by_time_range(
            symbol="btc_usdt",
            start_time=start_ts,
            end_time=end_ts,
            limit=20
        )

        all_orders = api_client.get_all_history_orders(
            symbol="btc_usdt",
            batch_size=20
        )

        stats = api_client.get_order_statistics(
            symbol="btc_usdt",
            days=7
        )

        first_page = api_client.query_history_orders(
            symbol="btc_usdt",
            limit=5,
            direction="NEXT"
        )

        if first_page.get('items'):
            last_order = first_page['items'][-1]
            second_page = api_client.query_history_orders(
                symbol="btc_usdt",
                order_id=last_order['orderId'],
                limit=5,
                direction="NEXT"
            )
            print(f"Order quantity on page 2: {len(second_page.get('items', []))}")

    except Exception as e:
        print(f"Example execution failed: {str(e)}")


if __name__ == "__main__":
    example_usage()
const API_CONFIG = {
    BASE_URL: 'https://api.example.com',
    ACCESS_KEY: 'your_api_accessKey', 
    SECRET_KEY: 'your_api_secretKey'
};

function generateSignature(params, secretKey) {
    const sortedKeys = Object.keys(params).sort();

    const queryString = sortedKeys
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&');

    const CryptoJS = require('crypto-js');
    const signature = CryptoJS.HmacSHA256(queryString, secretKey).toString();

    return signature;
}

async function queryHistoryOrders(options = {}) {
    try {
        const queryParams = {
            ...options,
            timestamp: Date.now()
        };

        Object.keys(queryParams).forEach(key => {
            if (queryParams[key] === null || queryParams[key] === undefined || queryParams[key] === '') {
                delete queryParams[key];
            }
        });

        const signature = generateSignature(queryParams, API_CONFIG.SECRET_KEY);

        const queryString = Object.keys(queryParams)
            .map(key => `${key}=${encodeURIComponent(queryParams[key])}`)
            .join('&');

        const url = `${API_CONFIG.BASE_URL}/v2/order/list-history?${queryString}`;

        const headers = {
            'X_ACCESS_KEY': API_CONFIG.ACCESS_KEY,
            'X_SIGNATURE': signature,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        };

        const response = await fetch(url, {
            method: 'GET',
            headers: headers
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.code !== 0) {
            throw new Error(`API error: ${data.msg || 'Unknown error'}`);
        }

        return data.data;

    } catch (error) {
        console.error('Failed to query historical orders:', error);
        throw error;
    }
}

async function exampleUsage() {
    try {
        const recentOrders = await queryHistoryOrders({
            symbol: 'btc_usdt',
            limit: 10
        });
        console.log('The last 10 orders:', recentOrders);

        const timeRangeOrders = await queryHistoryOrders({
            symbol: 'btc_usdt',
            startTime: 1672444800000, // 2023-01-01 00:00:00
            endTime: 1672531200000,   // 2023-01-02 00:00:00
            limit: 20
        });
        console.log('Time range order:', timeRangeOrders);

        const firstPage = await queryHistoryOrders({
            symbol: 'btc_usdt',
            limit: 5,
            direction: 'NEXT'
        });
        console.log('Page One:', firstPage);

        if (firstPage.items && firstPage.items.length > 0) {
            const lastOrderId = firstPage.items[firstPage.items.length - 1].orderId;
            const secondPage = await queryHistoryOrders({
                symbol: 'btc_usdt',
                id: lastOrderId,
                direction: 'NEXT',
                limit: 5
            });
            console.log('Page Two:', secondPage);
        }

    } catch (error) {
        console.error('Example execution failed:', error);
    }
}


async function getAllHistoryOrders(options) {
    const { symbol, batchSize = 50 } = options;
    let allOrders = [];
    let lastOrderId = null;
    let hasMore = true;

    try {
        while (hasMore) {
            const queryOptions = {
                symbol: symbol,
                limit: batchSize,
                direction: 'NEXT'
            };

            if (lastOrderId) {
                queryOptions.id = lastOrderId;
            }

            const response = await queryHistoryOrders(queryOptions);

            if (response.items && response.items.length > 0) {
                allOrders = allOrders.concat(response.items);

                lastOrderId = response.items[response.items.length - 1].orderId;

                hasMore = response.items.length === batchSize;
            } else {
                hasMore = false;
            }

            await new Promise(resolve => setTimeout(resolve, 100));
        }

        return allOrders;

    } catch (error) {
        console.error('Batch query of historical orders failed:', error);
        throw error;
    }
}

module.exports = {
    queryHistoryOrders,
    getAllHistoryOrders,
    exampleUsage
};

if (typeof window !== 'undefined') {
    window.TradeAPI = {
        queryHistoryOrders,
        getAllHistoryOrders
    };
}

Description: Query historical orders using cursor-based pagination mechanism.

Interface Weight: 2

Request Method: GET
Request URL: /v2/order/list-history

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt
id No string Cursor ID 1234567890
direction No string Pagination direction: NEXT/PREV NEXT
limit No integer Number of items per page (default 10) 10
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000

Field Description:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be null) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Trade direction: BUY, SELL "BUY"
positionSide String Position direction: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full closing order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (contracts) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Filled quantity (contracts) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take profit trigger price (can be null) null
triggerStopPrice String (serialized) Stop loss trigger price (can be null) null
sourceId Long Conditional trigger ID (can be null) null
forceClose Boolean Whether it's a full closing order false
closeProfit String (serialized) Closing profit/loss (can be null) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

  1. Serialization Note: Fields like orderId, price, origQty are converted to string type via JsonSerialize annotation in the response to prevent precision loss when handling large numbers on the frontend.
  2. Time Unit: createdTime is a millisecond Unix timestamp.
  3. Numerical Fields: All BigDecimal type fields (such as price, quantity, margin) are returned as strings to preserve full precision.

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "page": 1,
        "ps": 10,
        "total": 1,
        "items": [
            {
                "orderId": "587077935051136448",
                "clientOrderId": null,
                "symbol": "btc_usdt",
                "orderType": "MARKET",
                "orderSide": "BUY",
                "positionSide": "LONG",
                "timeInForce": "IOC",
                "closePosition": false,
                "price": "0",
                "origQty": "1",
                "avgPrice": "88256.7",
                "executedQty": "1",
                "marginFrozen": "0.4524",
                "triggerProfitPrice": null,
                "triggerStopPrice": null,
                "sourceId": null,
                "forceClose": false,
                "closeProfit": null,
                "state": "FILLED",
                "createdTime": 1769672287213
            }
        ]
    },
    "bizCode": null
}

Query Order Details

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order/detail"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "orderId": "587077935051136448"
}

params = {k: v for k, v in params.items() if v is not None}

sorted_items = sorted(params.items())
query_str = urlencode(sorted_items)

signature = hmac.new(SECRET_KEY.encode('utf-8'), query_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

url = BASE + ("?" + query_str if query_str else "")

resp = requests.get(url, headers=headers, timeout=10)
print(resp.status_code)
try:
    print(resp.json())
except ValueError:
    print(resp.text)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order/detail";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getOrderDetail(orderId) {
  const params = { orderId };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) {
    usp.append(k, String(v));
  }
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

getOrderDetail("587077935051136448").catch(console.error);

Description: Query order details by order ID.

Interface Weight: 1

Request Method: GET
Request URL: /v2/order/detail

Authentication Required: API Key authentication required

Request Headers:

Query Parameters (query):

Parameter Required Type Description Example
orderId Yes string Order ID 587077935051136448

Field Description:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be null) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Trade direction: BUY, SELL "BUY"
positionSide String Position direction: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full closing order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (contracts) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Filled quantity (contracts) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take profit trigger price (can be null) null
triggerStopPrice String (serialized) Stop loss trigger price (can be null) null
sourceId Long Conditional trigger ID (can be null) null
forceClose Boolean Whether it's a full closing order false
closeProfit String (serialized) Closing profit/loss (can be null) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

  1. Serialization Note: Fields like orderId, price, origQty are converted to string type via JsonSerialize annotation in the response to prevent precision loss when handling large numbers on the frontend.
  2. Time Unit: createdTime is a millisecond Unix timestamp.
  3. Numerical Fields: All BigDecimal type fields (such as price, quantity, margin) are returned as strings to preserve full precision.

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
          "orderId": "587077935051136448",
          "clientOrderId": null,
          "symbol": "btc_usdt",
          "orderType": "MARKET",
          "orderSide": "BUY",
          "positionSide": "LONG",
          "timeInForce": "IOC",
          "closePosition": false,
          "price": "0",
          "origQty": "1",
          "avgPrice": "88256.7",
          "executedQty": "1",
          "marginFrozen": "0.4524",
          "triggerProfitPrice": null,
          "triggerStopPrice": null,
          "sourceId": null,
          "forceClose": false,
          "closeProfit": null,
          "state": "FILLED",
          "createdTime": 1769672287213
    },
    "bizCode": null
}

Query Trade Records

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order/trade-list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "orderId": "587077935051136448",
    "symbol": "btc_usdt",
    "startTime": None,
    "endTime": None,
    "page": 1,
    "size": 10
}

params = {k: v for k, v in params.items() if v is not None}

sorted_items = sorted(params.items())
query_str = urlencode(sorted_items)

signature = hmac.new(SECRET_KEY.encode('utf-8'), query_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

url = BASE + ("?" + query_str if query_str else "")
resp = requests.get(url, headers=headers, timeout=10)
print(resp.status_code)
try:
    print(resp.json())
except ValueError:
    print(resp.text)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order/trade-list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getTradeList(params) {

  const entries = Object.entries(params || {}).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, String(v));
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

getTradeList({
  orderId: "587077935051136448",
  symbol: "btc_usdt",
  page: 1,
  size: 10
}).catch(console.error);

Description: Query trade detail records for an order.

Interface Weight: 2

Request Method: GET
Request URL: /v2/order/trade-list

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Type Description Example
orderId No string Order ID 587077935051136448
symbol No string Trading pair identifier btc_usdt
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000
page No integer Page number (default 1) 1
size No integer Number of items per page (default 10) 10

Field Description:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
execId String (serialized) Trade record ID (unique identifier) "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
quantity String (serialized) Trade quantity (contracts) "0.5"
price String (serialized) Trade price "88256.7"
fee String (serialized) Fee amount "0.0005"
feeCoin String Fee currency "USDT"
timestamp Long Trade time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

  1. Serialization Note: Fields like orderId, execId, quantity, price, fee are converted to string type via JsonSerialize annotation in the response to prevent precision loss when handling large numbers on the frontend.
  2. Trade Identifier: execId is the unique identifier for each trade record. A single order may have multiple trade records.
  3. Fee: Negative fee indicates deduction of fee, positive indicates fee rebate (e.g., Maker rebate).
  4. Time Unit: timestamp is a millisecond Unix timestamp.

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "page": 1,
        "ps": 10,
        "total": 8734,
        "items": [
            {
                "orderId": "587077935051136448",
                "execId": "587077935538634818",
                "symbol": "btc_usdt",
                "quantity": "1",
                "price": "88256.7",
                "fee": "0.0044",
                "feeCoin": "usdt",
                "timestamp": 1769672287213
            },
            {
                "orderId": "584291373785223168",
                "execId": "584291374195540034",
                "symbol": "btc_usdt",
                "quantity": "88",
                "price": "89751.62",
                "fee": "0.3949",
                "feeCoin": "usdt",
                "timestamp": 1769007919217
            }
        ]
    },
    "bizCode": null
}

Query Position List

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/position/list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "symbol": "btc_usdt"
}

params = {k: v for k, v in params.items() if v is not None}
sorted_items = sorted(params.items())
query_str = urlencode(sorted_items)

signature = hmac.new(SECRET_KEY.encode('utf-8'), query_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

url = BASE + ("?" + query_str if query_str else "")
resp = requests.get(url, headers=headers, timeout=10)
print(resp.status_code)
try:
    print(resp.json())
except ValueError:
    print(resp.text)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/position/list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getPositionList(params = {}) {
  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, String(v));
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

getPositionList({ symbol: "btc_usdt" }).catch(console.error);
getPositionList({}).catch(console.error);

Description: Get user's position information, can specify trading pair or get all positions.

Interface Weight: 2

Request Method: GET
Request URL: /v2/position/list

Authentication Required: API Key authentication required

Request Headers:

Query Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt

Field Description:

Field Name Field Type Description Example
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
positionId String (serialized) Position ID "1234567890123456789"
positionType String Position type: CROSSED (cross margin), ISOLATED (isolated margin) "ISOLATED"
positionSide String Position direction: LONG (long position), SHORT (short position) "LONG"
positionSize String (serialized) Position size (contracts) "10.5"
closeOrderSize String (serialized) Closing order size (contracts) "2.0"
availableCloseSize String (serialized) Available closing size (contracts) "8.5"
entryPrice String (serialized) Average entry price "45000.00"
isolatedMargin String (serialized) Isolated margin (only valid for isolated mode) "500.00"
openOrderMarginFrozen String (serialized) Frozen margin for opening orders "100.00"
realizedProfit String (serialized) Realized profit/loss (can be positive or negative) "125.50"
autoMargin Boolean Whether auto margin addition is enabled true
leverage Integer Leverage multiple 20
contractSize String (serialized) Contract multiplier (quantity per contract) "0.001"

Calculation Formulas (for reference):

  1. Position Value = positionSize × entryPrice × contractSize
  2. Available Margin = isolatedMargin - openOrderMarginFrozen (isolated only)
  3. Unrealized P&L = (current price - entryPrice) × positionSize × contractSize × (+1 for LONG, -1 for SHORT)

Field Relationship Explanation:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "symbol": "btc_usdt",
            "positionId": "587077935156970752",
            "positionType": "CROSSED",
            "positionSide": "LONG",
            "positionSize": "1",
            "closeOrderSize": "0",
            "availableCloseSize": "1",
            "entryPrice": "88256.7",
            "isolatedMargin": "0.4413",
            "openOrderMarginFrozen": "0",
            "realizedProfit": "-0.0008",
            "autoMargin": false,
            "leverage": 20,
            "contractSize": "0.0001"
        }
    ],
    "bizCode": null
}

Adjust Leverage

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/position/adjust-leverage"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "symbol": "btc_usdt",
    "leverage": 20
}

items = sorted((k, v) for k, v in params.items() if v is not None)
body_str = urlencode(items)

signature = hmac.new(SECRET_KEY.encode('utf-8'), body_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
print(resp.status_code)
try:
    print(resp.json())
except ValueError:
    print(resp.text)
const crypto = require('crypto');

const URL = "BASE_URL/v2/position/adjust-leverage";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function adjustLeverage(symbol, leverage) {
  const params = { symbol, leverage };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, String(v));
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

adjustLeverage("btc_usdt", 20).catch(console.error);

Description: Adjust leverage multiple for specified trading pair. Cannot modify when positions exist.

Interface Weight: 8

Request Method: POST
Request URL: (TRADE)/v2/position/adjust-leverage

Authentication Required: API Key authentication required

Request Headers:

Request Parameters (query):

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
leverage Yes integer Leverage multiple (minimum 1) 20

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Adjust Margin

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/position/margin"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

params = {
    "symbol": "btc_usdt",
    "positionSide": "LONG",
    "positionId": "1234567890",
    "margin": "100.00",
    "type": "ADD"  # "SUB"
}

items = sorted((k, v) for k, v in params.items() if v is not None)
body_str = urlencode(items)

signature = hmac.new(SECRET_KEY.encode('utf-8'), body_str.encode('utf-8'), hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
print(resp.status_code)
try:
    print(resp.json())
except ValueError:
    print(resp.text)
const crypto = require('crypto');

const URL = "BASE_URL/v2/position/margin";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function adjustMargin(params) {

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, String(v));
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

adjustMargin({
  symbol: "btc_usdt",
  positionSide: "LONG",
  positionId: "1234567890",
  margin: "100.00",
  type: "ADD"
}).catch(console.error);

Description: Adjust margin for isolated margin positions.

Interface Weight: 5

Request Method: POST
Request URL: (TRADE)/v2/position/margin

Authentication Required: API Key authentication required

Request Headers:

Request Parameters (query):

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
positionSide Yes string Position direction: LONG/SHORT LONG
positionId Yes string Position ID 1234567890
margin Yes string Margin amount to adjust (positive number) 100.00
type Yes string Adjustment direction: ADD/SUB ADD

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Close All Positions

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/position/close-all"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def close_positions(symbol=None):
    params = {}
    if symbol is not None:
        params["symbol"] = symbol

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'), body_str.encode('utf-8'), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

close_positions("btc_usdt")

close_positions()
const crypto = require('crypto');

const URL = "BASE_URL/v2/position/close-all";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function closePositions(symbol) {
  const params = {};
  if (symbol !== undefined && symbol !== null) params.symbol = String(symbol);

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

closePositions("btc_usdt").catch(console.error);

closePositions().catch(console.error);

Description: Close all user positions or positions for a specified trading pair with one click.

Interface Weight: 10

Request Method: POST
Request URL: (TRADE)/v2/position/close-all

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier (close all if not provided) btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Modify Position Type

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/position/change-type"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def change_position_type(symbol, positionType, positionModel):
    params = {
        "symbol": symbol,
        "positionType": positionType,
        "positionModel": positionModel
    }

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'), body_str.encode('utf-8'), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

change_position_type("btc_usdt", "CROSSED", "AGGREGATION")
const crypto = require('crypto');

const URL = "BASE_URL/v2/position/change-type";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function changePositionType(symbol, positionType, positionModel) {
  const params = {
    symbol,
    positionType,
    positionModel
  };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, String(v));
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

changePositionType("btc_usdt", "CROSSED", "AGGREGATION").catch(console.error);

Description: Modify position mode and type (cross/isolated margin, aggregated/disaggregated).

Interface Weight: 3

Request Method: POST
Request URL: (TRADE)/v2/position/change-type

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
positionType Yes string Position type: CROSSED/ISOLATED CROSSED
positionModel Yes string Position model: AGGREGATION/DISAGGREGATION AGGREGATION

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Create Conditional Order

import requests
import json

BASE_URL = "BASE_URL"
API_KEY = "your_api_accessKey"
X_SIGNATURE = "your_api_query_secretKey"
HEADERS = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": X_SIGNATURE,
    "Content-Type": "application/x-www-form-urlencoded"
}

payload = {
    "symbol": "btc_usdt",
    "entrustType": "STOP",
    "orderSide": "BUY",
    "positionSide": "LONG",
    "timeInForce": "GTC",
    "price": "45000.00",
    "origQty": "1.0",
    "stopPrice": "44500.00",
    "triggerPriceType": "MARK_PRICE",
    "positionId": "1234567890",
    "marketOrderLevel": 1,
    "expireTime": "1769759999000"
}

try:
    response = requests.post(f"{BASE_URL}/v2/entrust/create-plan", 
                            data=payload, headers=HEADERS)
    data = response.json()

    if response.status_code == 200 and data.get("code") == 0:
        print("Plan entrust created successfully")
        print(f"Entrust ID: {data.get('data', {}).get('entrustId')}")
    else:
        print(f"Error: {data.get('message', 'Unknown error')}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
const axios = require('axios');

const BASE_URL = 'BASE_URL';
const API_KEY = 'your_api_accessKey';
const X_SIGNATURE = 'your_api_query_secretKey';

const headers = {
  'X_ACCESS_KEY': API_KEY,
  'X_SIGNATURE': X_SIGNATURE,
  'Content-Type': 'application/x-www-form-urlencoded'
};

async function createPlanEntrust(params) {
  try {
    const payload = {
      symbol: params.symbol,
      entrustType: params.entrustType,
      orderSide: params.orderSide,
      positionSide: params.positionSide,
      timeInForce: params.timeInForce || 'GTC',
      price: params.price?.toString(),
      origQty: params.origQty.toString(),
      stopPrice: params.stopPrice.toString(),
      triggerPriceType: params.triggerPriceType || 'LATEST_PRICE',
      positionId: params.positionId,
      marketOrderLevel: params.marketOrderLevel,
      expireTime: params.expireTime
    };

    const response = await axios.post(`${BASE_URL}/v2/entrust/create-plan`, 
                                     payload, { headers });

    if (response.data.code === 0) {
      console.log('Plan entrust created successfully');
      return response.data;
    } else {
      throw new Error(response.data.message || 'Unknown error');
    }
  } catch (error) {
    console.error('Error creating plan entrust:', error.message);
    throw error;
  }
}

createPlanEntrust({
  symbol: 'btc_usdt',
  entrustType: 'STOP',
  orderSide: 'BUY',
  positionSide: 'LONG',
  timeInForce: 'GTC',
  price: '45000.00',
  origQty: 1.0,
  stopPrice: '44500.00',
  triggerPriceType: 'MARK_PRICE'
})
  .then(result => {
    console.log('Created plan entrust:', result.data.entrustId);
  })
  .catch(error => {
    console.error('Failed:', error.message);
  });

Description: Create conditional order (plan entrust). When market price reaches trigger condition, system automatically creates corresponding limit or market order.

Interface Weight: 10

Request Method: POST
Request URL: (TRADE)/v2/entrust/create-plan

Authentication Required: API Key authentication required

Request Headers:

Request Body Parameters:

1. Basic Parameters

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
entrustType Yes string Entrust type: STOP(limit), TAKE_PROFIT_MARKET(take profit market) STOP
orderSide Yes string Trade direction: BUY/SELL BUY
positionSide Yes string Position direction: LONG/SHORT LONG
timeInForce Yes string Time in force: GTC/IOC/FOK/GTX GTC
origQty Yes string Quantity (contracts) must be integer 1.0

2. Price Parameters

Parameter Required Type Description Example
price Yes string Order price 45000.00
stopPrice Yes string Trigger price 44500.00

3. Trigger Condition Parameters

Parameter Required Type Description Example
triggerPriceType Yes string Trigger price type: MARK_PRICE(mark price)/LATEST_PRICE(latest price) MARK_PRICE

4. Market Order Parameters

Parameter Required Type Description Example
marketOrderLevel No integer Market order best level: 1(counter price), 2(current price), 5, 10, 15 levels, effective for market orders 1

5. Closing Related Parameters

Parameter Required Type Description Example
positionId Conditionally Required string Position ID, required for closing conditional orders 1234567890

6. Other Parameters

Parameter Required Type Description Example
expireTime No long Expiry time (timestamp) 1769759999000

Trigger Logic Explanation:

  1. Limit Trigger Order (STOP)
  1. Market Trigger Order (STOP_MARKET)
  1. Closing Judgment Rules

In open/close mode, the following conditions are closing orders, must provide positionId: - orderSide=BUY and positionSide=SHORT (buy to close short) - orderSide=SELL and positionSide=LONG (sell to close long)

  1. Price Limit Rules

Precision Requirements:

  1. Quantity Precision: origQty must be integer (scale=0)
  2. Price Precision: price and stopPrice must comply with trading pair's minimum price step
  3. Trigger Price: stopPrice must be divisible by minimum price step

Trading Mode Explanation:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "entrustId": "1234567890123456789",
    "symbol": "btc_usdt",
    "entrustType": "STOP",
    "state": "NOT_TRIGGERED"
  }
}

Error Code Explanation:


Create Take Profit/Stop Loss

import requests
import json

BASE_URL = "BASE_URL"
API_KEY = "your_api_accessKey"
X_SIGNATURE = "your_api_query_secretKey"
HEADERS = {
    "X_ACCESS_KEY": API_KEY,
    "X_SIGNATURE": X_SIGNATURE,
    "Content-Type": "application/x-www-form-urlencoded"
}

payload = {
    "symbol": "btc_usdt",
    "positionSide": "LONG",
    "origQty": "1.0",
    "triggerPriceType": "MARK_PRICE",
    "triggerProfitPrice": "46000.00",
    "triggerStopPrice": "44000.00",
    "positionId": "1234567890",
    "profitOrderType": "MARKET",
    "stopOrderType": "MARKET",
    "profitFlag": 1,
    "reduceOnly": True
}

try:
    response = requests.post(f"{BASE_URL}/v2/entrust/create-profit",
                            data=payload, headers=HEADERS)
    data = response.json()

    if response.status_code == 200 and data.get("code") == 0:
        print("Profit stop order created successfully")
        print(f"Profit ID: {data.get('data', {}).get('profitId')}")
    else:
        print(f"Error: {data.get('message', 'Unknown error')}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
const axios = require('axios');

const BASE_URL = 'BASE_URL';
const API_KEY = 'your_api_accessKey';
const X_SIGNATURE = 'your_api_query_secretKey';

const headers = {
  'X_ACCESS_KEY': API_KEY,
  'X_SIGNATURE': X_SIGNATURE,
  'Content-Type': 'application/x-www-form-urlencoded'
};

async function createProfitEntrust(params) {
  try {
    const payload = {
      symbol: params.symbol,
      positionSide: params.positionSide,
      origQty: params.origQty.toString(),
      triggerPriceType: params.triggerPriceType || 'LATEST_PRICE',
      triggerProfitPrice: params.triggerProfitPrice?.toString(),
      triggerStopPrice: params.triggerStopPrice?.toString(),
      positionId: params.positionId,
      profitOrderType: params.profitOrderType || 'MARKET',
      stopOrderType: params.stopOrderType || 'MARKET',
      profitFlag: params.profitFlag || 1,
      reduceOnly: params.reduceOnly !== false
    };

    const response = await axios.post(`${BASE_URL}/v2/entrust/create-profit`,
                                     payload, { headers });

    if (response.data.code === 0) {
      console.log('Profit stop order created successfully');
      return response.data;
    } else {
      throw new Error(response.data.message || 'Unknown error');
    }
  } catch (error) {
    console.error('Error creating profit stop order:', error.message);
    throw error;
  }
}

createProfitEntrust({
  symbol: 'btc_usdt',
  positionSide: 'LONG',
  origQty: 1.0,
  triggerPriceType: 'MARK_PRICE',
  triggerProfitPrice: 46000.00,
  triggerStopPrice: 44000.00,
  positionId: '1234567890',
  profitFlag: 1
})
  .then(result => {
    console.log('Created profit stop order:', result.data.profitId);
  })
  .catch(error => {
    console.error('Failed:', error.message);
  });

Description: Create a Take Profit/Stop Loss order. Supports two modes: 1) Open position Take Profit/Stop Loss (no positionId) 2) Close position Take Profit/Stop Loss (with positionId).

Rate Limit Weight: 8

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/create-profit

Authentication: API Key required

Headers:

Request Body Parameters:

1. Basic Parameters

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
origQty Yes string Quantity (in lots). A value of 0 means close all position. 1.0

2. Trigger Condition Parameters

Parameter Required Type Description Example
triggerPriceType No string Trigger price type: MARK_PRICE(Mark Price)/LATEST_PRICE(Last Price). Default is LATEST_PRICE. MARK_PRICE
triggerProfitPrice No string Take Profit trigger price 46000.00
triggerStopPrice No string Stop Loss trigger price 44000.00

3. Order Type Parameters

Parameter Required Type Description Example
profitOrderType No string Take Profit order type: MARKET/LIMIT. Default MARKET. MARKET
stopOrderType No string Stop Loss order type: MARKET/LIMIT. Default MARKET. MARKET
profitOrderPrice No string LIMIT Take Profit order's price 45950.00
stopOrderPrice No string LIMIT Stop Loss order's price 44050.00

4. Mode Selection Parameters Mode One: Open Position Take Profit/Stop Loss (positionId is empty)

Parameter Required Type Description Example
orderSide Yes string Order side: BUY/SELL BUY
positionSide Yes string Position side: LONG/SHORT/BOTH LONG

Mode Two: Close Position Take Profit/Stop Loss (positionId is not empty)

Parameter Required Type Description Example
positionId No string Position ID. If empty, it's for opening a position with TP/SL. 1234567890
orderSide No string Order side. Calculated automatically when closing a position. BUY

5. Other Parameters

Parameter Required Type Description Example
reduceOnly No boolean Whether Reduce Only. Default true. true
profitFlag No integer 1: Full TP/SL, 2: Partial TP/SL. Default 1. 1
expireTime No long Expiration time (timestamp) 1769759999000

Note:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "profitId": "1234567890123456789",
    "symbol": "btc_usdt",
    "positionSide": "LONG",
    "state": "NOT_TRIGGERED"
  }
}

Error Code Explanation:


Cancel Plan Order

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/entrust/cancel-plan"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_plan(entrust_id):
    params = {"entrustId": str(entrust_id)}

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_plan("1234567890")
const crypto = require('crypto');

const URL = "BASE_URL/v2/entrust/cancel-plan";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelPlan(entrustId) {
  const params = { entrustId: String(entrustId) };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelPlan("1234567890").catch(console.error);

Description: Cancel the specified plan order.

Rate Limit Weight: 5

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/cancel-plan

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
entrustId Yes string Plan Order ID 1234567890

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Cancel Take Profit/Stop Loss

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/entrust/cancel-profit-stop"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_profit(profit_id):
    params = {"profitId": str(profit_id)}

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_profit("1234567890")
const crypto = require('crypto');

const URL = "BASE_URL/v2/entrust/cancel-profit-stop";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelProfit(profitId) {
  const params = { profitId: String(profitId) };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelProfit("1234567890").catch(console.error);

Description: Cancel the specified Take Profit/Stop Loss order.

Rate Limit Weight: 5

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/cancel-profit-stop

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
profitId Yes string Take Profit/Stop Loss order ID 1234567890

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Update Take Profit/Stop Loss

import hmac
import hashlib
from urllib.parse import urlencode
import requests
import json
from decimal import Decimal, getcontext

getcontext().prec = 10

URL = "BASE_URL/v2/entrust/update-profit-stop"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

class ProfitEntrustAPI:
    def __init__(self, access_key, secret_key):
        self.access_key = access_key
        self.secret_key = secret_key

    def _generate_signature(self, body_str):
        return hmac.new(
            self.secret_key.encode('utf-8'),
            body_str.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()

    def _validate_params(self, params):
        errors = []

        if "profitId" not in params:
            errors.append("profitId is a required parameter")

        if ("triggerProfitPrice" not in params or params["triggerProfitPrice"] is None) and \
           ("triggerStopPrice" not in params or params["triggerStopPrice"] is None):
            errors.append("At least one of triggerProfitPrice or triggerStopPrice needs to be provided")

        profit_order_type = params.get("profitOrderType")
        stop_order_type = params.get("stopOrderType")

        if profit_order_type == "LIMIT":
            trigger_profit = params.get("triggerProfitPrice")
            profit_price = params.get("profitOrderPrice")
            has_trigger = trigger_profit is not None and str(trigger_profit).strip() != ""
            has_price = profit_price is not None and str(profit_price).strip() != ""
            if has_trigger != has_price:
                errors.append("For a LIMIT take-profit order: Both triggerProfitPrice and profitOrderPrice must be provided simultaneously or neither should be provided")

        if stop_order_type == "LIMIT":
            trigger_stop = params.get("triggerStopPrice")
            stop_price = params.get("stopOrderPrice")
            has_trigger = trigger_stop is not None and str(trigger_stop).strip() != ""
            has_price = stop_price is not None and str(stop_price).strip() != ""
            if has_trigger != has_price:
                errors.append("For a LIMIT stop-loss order: Both triggerStopPrice and stopOrderPrice must be provided simultaneously or neither must be provided")

        orig_qty = params.get("origQty")
        if orig_qty is not None:
            try:
                qty = Decimal(str(orig_qty))
                if qty < 0:
                    errors.append("The quantity cannot be less than 0")
            except:
                errors.append("The quantity format is incorrect")

        profit_flag = params.get("profitFlag")
        if profit_flag is not None:
            try:
                flag = int(profit_flag)
                if flag not in [0, 1, 2]:
                    errors.append("profitFlag must be 0, 1, or 2")
            except:
                errors.append("profitFlag must be an integer")

        return errors

    def update_profit_stop(self, params):

        errors = self._validate_params(params)
        if errors:
            raise ValueError(f"Parameter verification failed: {', '.join(errors)}")

        if "profitFlag" in params:
            profit_flag = params["profitFlag"]
            if profit_flag in ["0", "1"]:
                params["profitFlag"] = "1"
            else:
                params["profitFlag"] = "2"

        cleaned_params = {}
        for k, v in params.items():
            if v is not None:
                if isinstance(v, bool):
                    cleaned_params[k] = "true" if v else "false"
                else:
                    cleaned_params[k] = str(v).strip()

        items = sorted(cleaned_params.items())
        body_str = urlencode(items)

        signature = self._generate_signature(body_str)

        headers = {
            "X_ACCESS_KEY": self.access_key,
            "X_SIGNATURE": signature,
            "Content-Type": "application/x-www-form-urlencoded"
        }

        resp = requests.post(URL, data=body_str, headers=headers, timeout=10)

        try:
            result = resp.json()
            return result
        except ValueError:
            return {"error": resp.text, "raw_response": resp.text}

if __name__ == "__main__":
    api = ProfitEntrustAPI(ACCESS_KEY, SECRET_KEY)

    try:
        params1 = {
            "profitId": "1234567890",
            "triggerProfitPrice": "46500.00",
            "triggerPriceType": "LATEST_PRICE",
            "profitOrderType": "MARKET",
            "profitFlag": "1"
        }
        result1 = api.update_profit_stop(params1)

        params2 = {
            "profitId": "1234567890",
            "triggerProfitPrice": "47000.00",
            "triggerStopPrice": "43000.00",
            "profitOrderType": "LIMIT",
            "stopOrderType": "LIMIT",
            "profitOrderPrice": "47100.00",
            "stopOrderPrice": "42900.00",
            "triggerPriceType": "MARK_PRICE",
            "origQty": "2.5",
            "profitFlag": "1"
        }
        result2 = api.update_profit_stop(params2)

        params3 = {
            "profitId": "1234567890",
            "origQty": "3.0",
            "profitFlag": "2"
        }
        result3 = api.update_profit_stop(params3)

        try:
            params4 = {
                "profitId": "1234567890",
                "triggerProfitPrice": "47000.00",
                "profitOrderType": "LIMIT",
                "profitFlag": "1"
            }
            result4 = api.update_profit_stop(params4)
        except ValueError as e:
            print(f"expected error: {e}")

    except Exception as e:
        print(f"error: {e}")
const crypto = require('crypto');

const URL = "BASE_URL/v2/entrust/update-profit-stop";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

class ProfitEntrustAPI {
    constructor(accessKey, secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    _generateSignature(bodyStr) {
        return crypto.createHmac('sha256', this.secretKey)
            .update(bodyStr)
            .digest('hex');
    }

    _validateParams(params) {
        const errors = [];

        if (!params.profitId) {
            errors.push("profitId is a required parameter");
        }

        const hasTriggerProfit = params.triggerProfitPrice != null && String(params.triggerProfitPrice).trim() !== '';
        const hasTriggerStop = params.triggerStopPrice != null && String(params.triggerStopPrice).trim() !== '';

        if (!hasTriggerProfit && !hasTriggerStop) {
            errors.push("At least one of triggerProfitPrice or triggerStopPrice needs to be provided");
        }

        const profitOrderType = params.profitOrderType;
        const stopOrderType = params.stopOrderType;

        if (profitOrderType === 'LIMIT') {
            const hasTriggerProfitPrice = hasTriggerProfit;
            const hasProfitOrderPrice = params.profitOrderPrice != null && String(params.profitOrderPrice).trim() !== '';

            if (hasTriggerProfitPrice !== hasProfitOrderPrice) {
                errors.push("For a LIMIT take-profit order: Both triggerProfitPrice and profitOrderPrice must be provided simultaneously or neither should be provided");
            }
        }

        if (stopOrderType === 'LIMIT') {
            const hasTriggerStopPrice = hasTriggerStop;
            const hasStopOrderPrice = params.stopOrderPrice != null && String(params.stopOrderPrice).trim() !== '';

            if (hasTriggerStopPrice !== hasStopOrderPrice) {
                errors.push("For a LIMIT stop-loss order: Both triggerStopPrice and stopOrderPrice must be provided simultaneously or neither should be provided");
            }
        }

        if (params.origQty != null) {
            const qty = parseFloat(params.origQty);
            if (isNaN(qty) || qty < 0) {
                errors.push("The quantity cannot be less than 0");
            }
        }

        if (params.profitFlag != null) {
            const flag = parseInt(params.profitFlag);
            if (isNaN(flag) || ![0, 1, 2].includes(flag)) {
                errors.push("profitFlag must be 0, 1, or 2");
            }
        }

        return errors;
    }

    async updateProfitStop(params) {
        const errors = this._validateParams(params);
        if (errors.length > 0) {
            throw new Error(`Parameter verification failed: ${errors.join(', ')}`);
        }

        const processedParams = { ...params };
        if (processedParams.profitFlag != null) {
            const flag = parseInt(processedParams.profitFlag);
            if (flag === 0 || flag === 1) {
                processedParams.profitFlag = '1';
            } else {
                processedParams.profitFlag = '2';
            }
        }

        const cleanedParams = {};
        for (const [key, value] of Object.entries(processedParams)) {
            if (value != null) {
                if (typeof value === 'boolean') {
                    cleanedParams[key] = value ? 'true' : 'false';
                } else {
                    cleanedParams[key] = String(value).trim();
                }
            }
        }

        const entries = Object.entries(cleanedParams);
        entries.sort((a, b) => a[0].localeCompare(b[0]));

        const usp = new URLSearchParams();
        for (const [k, v] of entries) usp.append(k, v);
        const bodyStr = usp.toString();

        const signature = this._generateSignature(bodyStr);

        const headers = {
            "X_ACCESS_KEY": this.accessKey,
            "X_SIGNATURE": signature,
            "Content-Type": "application/x-www-form-urlencoded"
        };

        const resp = await fetch(URL, { 
            method: "POST", 
            headers, 
            body: bodyStr 
        });

        const contentType = resp.headers.get("content-type") || "";
        if (contentType.includes("application/json")) {
            return await resp.json();
        } else {
            const text = await resp.text();
            console.log(`Non-JSON response: ${text}`);
            return { error: text, rawResponse: text };
        }
    }
}

(async () => {
    const api = new ProfitEntrustAPI(ACCESS_KEY, SECRET_KEY);

    try {
        const params1 = {
            profitId: "1234567890",
            triggerProfitPrice: "46500.00",
            triggerPriceType: "LATEST_PRICE",
            profitOrderType: "MARKET",
            profitFlag: "1"
        };
        const result1 = await api.updateProfitStop(params1);

        const params2 = {
            profitId: "1234567890",
            triggerProfitPrice: "47000.00",
            triggerStopPrice: "43000.00",
            profitOrderType: "LIMIT",
            stopOrderType: "LIMIT",
            profitOrderPrice: "47100.00",
            stopOrderPrice: "42900.00",
            triggerPriceType: "MARK_PRICE",
            origQty: "2.5",
            profitFlag: "1"
        };
        const result2 = await api.updateProfitStop(params2);
        console.log("Result 2:", JSON.stringify(result2, null, 2));

        try {
            const params3 = {
                profitId: "1234567890",
                triggerProfitPrice: "47000.00",
                profitOrderType: "LIMIT",
                profitFlag: "1"
            };
            const result3 = await api.updateProfitStop(params3);
        } catch (error) {
            console.log("expected error:", error.message);
        }

    } catch (error) {
        console.error("error:", error.message);
    }
})();

Description: Modify various parameters of an existing Take Profit/Stop Loss order.

Rate Limit Weight: 3

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/update-profit-stop

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
profitId Yes string Take Profit/Stop Loss record ID 1234567890
triggerProfitPrice No string Take Profit trigger price 46500.00
triggerStopPrice No string Stop Loss trigger price 43500.00
triggerPriceType No string Trigger price type: MARK_PRICE/LATEST_PRICE LATEST_PRICE
profitOrderType No string Take Profit order type: MARKET/LIMIT (default MARKET) MARKET
stopOrderType No string Stop Loss order type: MARKET/LIMIT (default MARKET) MARKET
origQty No string Quantity (in lots), must be ≥ 0 2.5
profitOrderPrice No string Take Profit order price for LIMIT orders 47000.00
stopOrderPrice No string Stop Loss order price for LIMIT orders 43000.00
profitFlag No string Take Profit/Stop Loss flag: 0/1/2 (0 and 1 will be converted to 1) 1

Important Validation Rules:

Successful Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "adjustId": 9876543210,
    "status": "PROCESSING"
  }
}

Cancel All Plan Orders

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/entrust/cancel-all-plan"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_all_plans(symbol=None):
    params = {}
    if symbol is not None:
        params["symbol"] = symbol

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_all_plans("btc_usdt")

cancel_all_plans()
const crypto = require('crypto');

const URL = "BASE_URL/v2/entrust/cancel-all-plan";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelAllPlans(symbol) {
  const params = {};
  if (symbol !== undefined && symbol !== null) params.symbol = String(symbol);

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelAllPlans("btc_usdt").catch(console.error);

cancelAllPlans().catch(console.error);

Description: Cancel all plan orders for the user (optionally for a specific trading pair).

Rate Limit Weight: 8

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/cancel-all-plan

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier (cancel all if not provided) btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Cancel All Take Profit/Stop Loss

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "/v2/entrust/cancel-all-profit-stop"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_all_profit_stop(symbol=None):
    params = {}
    if symbol is not None:
        params["symbol"] = symbol

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_all_profit_stop("btc_usdt")

cancel_all_profit_stop()
const crypto = require('crypto');

const URL = "BASE_URL/v2/entrust/cancel-all-profit-stop";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelAllProfitStop(symbol) {
  const params = {};
  if (symbol !== undefined && symbol !== null) params.symbol = String(symbol);

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelAllProfitStop("btc_usdt").catch(console.error);

cancelAllProfitStop().catch(console.error);

Description: Cancel all Take Profit/Stop Loss orders for the user (optionally for a specific trading pair).

Rate Limit Weight: 8

HTTP Method: POST
Endpoint: (TRADE)/v2/entrust/cancel-all-profit-stop

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier (cancel all if not provided) btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Query Plan Order List

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/entrust/plan-list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def plan_list(symbol=None, state=None, id=None, limit=None, direction=None):
    params = {}
    if symbol is not None: params["symbol"] = str(symbol)
    if state is not None: params["state"] = str(state)
    if id is not None: params["id"] = str(id)
    if limit is not None: params["limit"] = str(limit)
    if direction is not None: params["direction"] = str(direction)  # "NEXT" or "PREV"

    items = sorted(params.items())
    query_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    res = plan_list(symbol="btc_usdt", state="NOT_TRIGGERED", limit=10, direction="NEXT")
    print(res)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/entrust/plan-list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function planList(options = {}) {
  const paramsObj = {};
  for (const k of ["symbol", "state", "id", "limit", "direction"]) {
    if (options[k] !== undefined && options[k] !== null) paramsObj[k] = String(options[k]);
  }

  const keys = Object.keys(paramsObj).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, paramsObj[k]);
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  return resp.json();
}

(async () => {
  try {
    const data = await planList({ symbol: "btc_usdt", state: "NOT_TRIGGERED", limit: 10, direction: "NEXT" });
    console.log(data);
  } catch (err) {
    console.error(err);
  }
})();

Description: Query the current user's plan order list.

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/entrust/plan-list

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt
state No string Order status: NOT_TRIGGERED/TRIGGERING, etc. NOT_TRIGGERED
id No string Pagination ID 1234567890
limit No integer Number of items per page (default 10) 10
direction No string Pagination direction: NEXT/PREV NEXT

Field Descriptions:

Field Name Field Type Description Example
entrustId String (serialized) Plan Order ID "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
entrustType String Order type (conditional order type) "STOP"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "GTC"
closePosition Boolean Whether it triggers full position close false
price String (serialized) Order price (the order price after trigger) "45000.00"
origQty String (serialized) Order quantity (in lots) "10"
stopPrice String (serialized) Trigger price "45500.00"
triggerPriceType String Trigger price type: MARK_PRICE, LATEST_PRICE, etc. "LATEST_PRICE"
isOrdinary Boolean Whether it's an ordinary plan order true
state String Order status:
NOT_TRIGGERED: Not triggered
TRIGGERING: Triggering
TRIGGERED: Triggered
USER_REVOCATION: User canceled
PLATFORM_REVOCATION: Platform canceled
EXPIRED: Expired
"NOT_TRIGGERED"
marketOrderLevel Integer Market order optimal level (effective for market orders after trigger) 1
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "page": 1,
    "size": 10,
    "total": 5,
    "items": [
      {
        "entrustId": "1234567890",
        "symbol": "btc_usdt",
        "entrustType": "LIMIT",
        "orderSide": "BUY",
        "positionSide": "LONG",
        "timeInForce": "GTC",
        "price": "45000.00",
        "origQty": "1.0",
        "stopPrice": "44500.00",
        "triggerPriceType": "MARK_PRICE",
        "state": "NOT_TRIGGERED",
        "createdTime": 1672531200000
      }
    ]
  }
}

Query Plan Order History

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/entrust/plan-list-history"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def plan_list_history(symbol=None, id=None, direction=None, limit=None, startTime=None, endTime=None):
    params = {}
    if symbol is not None: params["symbol"] = str(symbol)
    if id is not None: params["id"] = str(id)
    if direction is not None: params["direction"] = str(direction)  # "NEXT" or "PREV"
    if limit is not None: params["limit"] = str(limit)
    if startTime is not None: params["startTime"] = str(startTime)  # milliseconds
    if endTime is not None: params["endTime"] = str(endTime)

    # sort & urlencode
    items = sorted(params.items())
    query_str = urlencode(items)  # "" if no params

    # signature: HMAC-SHA256(hex) over the query string (or empty string)
    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    result = plan_list_history(symbol="btc_usdt", limit=10, direction="NEXT")
    print(result)
// Node 18+ has global fetch. For older Node, install node-fetch.
const crypto = require('crypto');

const BASE = "BASE_URL/v2/entrust/plan-list-history";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function planListHistory(options = {}) {
  // options: { symbol, id, direction, limit, startTime, endTime }
  const params = {};
  for (const k of ["symbol", "id", "direction", "limit", "startTime", "endTime"]) {
    if (options[k] !== undefined && options[k] !== null) params[k] = String(options[k]);
  }

  const keys = Object.keys(params).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, params[k]);
  const queryStr = usp.toString(); // "" if no params

  // signature: HMAC-SHA256(hex) over the query string (or empty string)
  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  return resp.json();
}

(async () => {
  try {
    const res = await planListHistory({ symbol: "btc_usdt", limit: 10, direction: "NEXT" });
    console.log(res);
  } catch (err) {
    console.error(err);
  }
})();

Description: Query historical plan order records (excluding orders that are not triggered and are triggering).

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/entrust/plan-list-history

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt
id No string Cursor ID 1234567890
direction No string Pagination direction: NEXT/PREV NEXT
limit No integer Number of items per page (default 10) 10
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000

Field Descriptions:

Field Name Field Type Description Example
entrustId String (serialized) Plan Order ID "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
entrustType String Order type (conditional order type) "STOP"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "GTC"
closePosition Boolean Whether it triggers full position close false
price String (serialized) Order price (the order price after trigger) "45000.00"
origQty String (serialized) Order quantity (in lots) "10"
stopPrice String (serialized) Trigger price "45500.00"
triggerPriceType String Trigger price type: MARK_PRICE, LATEST_PRICE, etc. "LATEST_PRICE"
isOrdinary Boolean Whether it's an ordinary plan order true
state String Order status:
NOT_TRIGGERED: Not triggered
TRIGGERING: Triggering
TRIGGERED: Triggered
USER_REVOCATION: User canceled
PLATFORM_REVOCATION: Platform canceled
EXPIRED: Expired
"NOT_TRIGGERED"
marketOrderLevel Integer Market order optimal level (effective for market orders after trigger) 1
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "page": 1,
    "size": 10,
    "total": 150,
    "items": [
      {
        "entrustId": "1234567890",
        "symbol": "btc_usdt",
        "entrustType": "LIMIT",
        "orderSide": "BUY",
        "positionSide": "LONG",
        "price": "45000.00",
        "origQty": "1.0",
        "stopPrice": "44500.00",
        "triggerPriceType": "MARK_PRICE",
        "state": "TRIGGERED",
        "createdTime": 1672444800000
      }
    ]
  }
}

Query Take Profit/Stop Loss List

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/entrust/profit-list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def profit_list(symbol=None, state=None, id=None, limit=None, direction=None):
    params = {}
    if symbol is not None: params["symbol"] = str(symbol)
    if state is not None: params["state"] = str(state)
    if id is not None: params["id"] = str(id)
    if limit is not None: params["limit"] = str(limit)
    if direction is not None: params["direction"] = str(direction)  # "NEXT" or "PREV"

    items = sorted(params.items())
    query_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(profit_list(symbol="btc_usdt", state="NOT_TRIGGERED", limit=10))
const crypto = require('crypto');

const BASE = "BASE_URL/v2/entrust/profit-list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function profitList(options = {}) {
  const paramsObj = {};
  for (const k of ["symbol", "state", "id", "limit", "direction"]) {
    if (options[k] !== undefined && options[k] !== null) paramsObj[k] = String(options[k]);
  }

  const keys = Object.keys(paramsObj).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, paramsObj[k]);
  const queryStr = usp.toString(); 

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  return resp.json();
}

(async () => {
  try {
    const data = await profitList({ symbol: "btc_usdt", state: "NOT_TRIGGERED", limit: 10 });
    console.log(data);
  } catch (err) {
    console.error(err);
  }
})();

Description: Query the current user's Take Profit/Stop Loss list.

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/entrust/profit-list

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier btc_usdt
state No string Order status NOT_TRIGGERED
id No string Pagination ID 1234567890
limit No integer Number of items per page (default 10) 10
direction No string Pagination direction: NEXT/PREV NEXT

Field Descriptions:

Field Name Field Type Description Example
profitId String (serialized) Take Profit/Stop Loss order ID "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
positionSide String Position side: LONG, SHORT "LONG"
origQty String (serialized) Order quantity (in lots) "10"
triggerPriceType String Trigger price type: MARK_PRICE (Mark Price), LATEST_PRICE (Last Price) "MARK_PRICE"
triggerProfitPrice String (serialized) Take Profit trigger price "46000.00"
triggerStopPrice String (serialized) Stop Loss trigger price "44000.00"
entryPrice String (serialized) Entry price (average opening price) "45000.00"
positionSize String (serialized) Position size (in lots) "10"
isolatedMargin String (serialized) Isolated margin "225.00"
executedQty String (serialized) Executed quantity (in lots) "0"
state String Order status:
NOT_TRIGGERED: Not triggered
TRIGGERING: Triggering
TRIGGERED: Triggered
USER_REVOCATION: User canceled
PLATFORM_REVOCATION: Platform canceled
EXPIRED: Expired
"NOT_TRIGGERED"
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "page": 1,
    "size": 10,
    "total": 3,
    "items": [
      {
        "profitId": "1234567890",
        "symbol": "btc_usdt",
        "positionSide": "LONG",
        "origQty": "1.0",
        "triggerPriceType": "MARK_PRICE",
        "triggerProfitPrice": "46000.00",
        "triggerStopPrice": "44000.00",
        "entryPrice": "45000.00",
        "positionSize": "1.0",
        "isolatedMargin": "450.00",
        "executedQty": "0.0",
        "state": "NOT_TRIGGERED",
        "createdTime": 1672531200000
      }
    ]
  }
}

Query Plan Order Details

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/entrust/plan-detail"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_plan_detail(entrust_id):
    if not entrust_id:
        raise ValueError("entrustId is required")

    params = {"entrustId": str(entrust_id)}
    sorted_items = sorted(params.items())
    query_str = urlencode(sorted_items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + "?" + query_str
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(get_plan_detail("1234567890"))
const crypto = require('crypto');

const BASE = "BASE_URL/v2/entrust/plan-detail";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getPlanDetail(entrustId) {
  if (!entrustId) throw new Error("entrustId is required");

  const params = { entrustId: String(entrustId) };
  const keys = Object.keys(params).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, params[k]);
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  return resp.json();
}

getPlanDetail("1234567890").then(console.log).catch(console.error);

Description: Query plan order details based on the order ID.

Rate Limit Weight: 1

HTTP Method: GET
Endpoint: /v2/entrust/plan-detail

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
entrustId Yes string Plan Order ID 1234567890

Field Descriptions:

Field Name Field Type Description Example
entrustId String (serialized) Plan Order ID "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
entrustType String Order type (conditional order type) "STOP"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "GTC"
closePosition Boolean Whether it triggers full position close false
price String (serialized) Order price (the order price after trigger) "45000.00"
origQty String (serialized) Order quantity (in lots) "10"
stopPrice String (serialized) Trigger price "45500.00"
triggerPriceType String Trigger price type: MARK_PRICE, LATEST_PRICE, etc. "LATEST_PRICE"
isOrdinary Boolean Whether it's an ordinary plan order true
state String Order status:
NOT_TRIGGERED: Not triggered
TRIGGERING: Triggering
TRIGGERED: Triggered
USER_REVOCATION: User canceled
PLATFORM_REVOCATION: Platform canceled
EXPIRED: Expired
"NOT_TRIGGERED"
marketOrderLevel Integer Market order optimal level (effective for market orders after trigger) 1
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213

Plan Order Type Explanation:

Common entrustType Values:

Trigger Logic (using BUY as an example):

Special Field Explanations:

Status Flow:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "entrustId": "1234567890",
    "symbol": "btc_usdt",
    "entrustType": "LIMIT",
    "orderSide": "BUY",
    "positionSide": "LONG",
    "timeInForce": "GTC",
    "closePosition": false,
    "price": "45000.00",
    "origQty": "1.0",
    "stopPrice": "44500.00",
    "triggerPriceType": "MARK_PRICE",
    "isOrdinary": true,
    "state": "NOT_TRIGGERED",
    "marketOrderLevel": null,
    "createdTime": 1672531200000
  }
}

Query Take Profit/Stop Loss Details

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/entrust/profit-detail"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_profit_detail(profit_id):
    if not profit_id:
        raise ValueError("profitId is required")

    params = {"profitId": str(profit_id)}
    sorted_items = sorted(params.items())
    query_str = urlencode(sorted_items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + "?" + query_str
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    print(get_profit_detail("1234567890"))
const crypto = require('crypto');

const BASE = "BASE_URL/v2/entrust/profit-detail";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getProfitDetail(profitId) {
  if (!profitId) throw new Error("profitId is required");

  const params = { profitId: String(profitId) };
  const keys = Object.keys(params).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, params[k]);
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  return resp.json();
}

getProfitDetail("1234567890")
  .then(console.log)
  .catch(console.error);

Description: Query Take Profit/Stop Loss details based on ID.

Rate Limit Weight: 1

HTTP Method: GET
Endpoint: /v2/entrust/profit-detail

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
profitId Yes string Take Profit/Stop Loss ID 1234567890

Field Descriptions:

Field Name Field Type Description Example
profitId String (serialized) Take Profit/Stop Loss order ID "1234567890123456789"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
positionSide String Position side: LONG, SHORT "LONG"
origQty String (serialized) Order quantity (in lots) "10"
triggerPriceType String Trigger price type: MARK_PRICE (Mark Price), LATEST_PRICE (Last Price) "MARK_PRICE"
triggerProfitPrice String (serialized) Take Profit trigger price "46000.00"
triggerStopPrice String (serialized) Stop Loss trigger price "44000.00"
entryPrice String (serialized) Entry price (average opening price) "45000.00"
positionSize String (serialized) Position size (in lots) "10"
isolatedMargin String (serialized) Isolated margin "225.00"
executedQty String (serialized) Executed quantity (in lots) "0"
state String Order status:
NOT_TRIGGERED: Not triggered
TRIGGERING: Triggering
TRIGGERED: Triggered
USER_REVOCATION: User canceled
PLATFORM_REVOCATION: Platform canceled
EXPIRED: Expired
"NOT_TRIGGERED"
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213

Detailed Field Explanations:

Calculation Example:

Assume LONG position:

Expected Profit = (46000 - 45000) × 10 × 0.001 = 100 USDT
Expected Loss = (44000 - 45000) × 10 × 0.001 = -100 USDT

Response Example:

{
  "code": 0,
  "message": "success",
  "data": {
    "profitId": "1234567890",
    "symbol": "btc_usdt",
    "positionSide": "LONG",
    "origQty": "1.0",
    "triggerPriceType": "MARK_PRICE",
    "triggerProfitPrice": "46000.00",
    "triggerStopPrice": "44000.00",
    "entryPrice": "45000.00",
    "positionSize": "1.0",
    "isolatedMargin": "450.00",
    "executedQty": "0.0",
    "state": "NOT_TRIGGERED",
    "createdTime": 1672531200000
  }
}

Query Order Entrust List

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order-entrust/list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_order_entrust_list(type=None, symbol=None, state=None,
                           startTime=None, endTime=None, forceClose=None,
                           page=None, size=None):
    params = {}
    if type is not None: params["type"] = str(type)
    if symbol is not None: params["symbol"] = str(symbol)
    if state is not None: params["state"] = str(state)
    if startTime is not None: params["startTime"] = str(startTime)
    if endTime is not None: params["endTime"] = str(endTime)
    if forceClose is not None:
        # send boolean as lowercase string to be explicit
        params["forceClose"] = "true" if forceClose else "false"
    if page is not None: params["page"] = str(page)
    if size is not None: params["size"] = str(size)

    # sort and encode
    sorted_items = sorted(params.items())
    query_str = urlencode(sorted_items)  # empty string if no params

    # signature (HMAC-SHA256 hex)
    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    res = get_order_entrust_list(type="ORDER", symbol="btc_usdt", page=1, size=10)
    print(res)
// Node 18+ has global fetch. For older Node, install node-fetch.
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order-entrust/list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getOrderEntrustList(options = {}) {
  // options: { type, symbol, state, startTime, endTime, forceClose, page, size }
  const params = {};
  if (options.type !== undefined) params.type = String(options.type);
  if (options.symbol !== undefined) params.symbol = String(options.symbol);
  if (options.state !== undefined) params.state = String(options.state);
  if (options.startTime !== undefined) params.startTime = String(options.startTime);
  if (options.endTime !== undefined) params.endTime = String(options.endTime);
  if (options.forceClose !== undefined) params.forceClose = options.forceClose ? "true" : "false";
  if (options.page !== undefined) params.page = String(options.page);
  if (options.size !== undefined) params.size = String(options.size);

  // build sorted query string
  const keys = Object.keys(params).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, params[k]);
  const queryStr = usp.toString(); // "" if no params

  // signature: HMAC-SHA256 hex
  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  if (!resp.ok) throw new Error(`HTTP ${resp.status} ${await resp.text()}`);
  const ct = resp.headers.get("content-type") || "";
  return ct.includes("application/json") ? await resp.json() : await resp.text();
}

(async () => {
  try {
    const result = await getOrderEntrustList({ type: "ORDER", symbol: "btc_usdt", page: 1, size: 10 });
    console.log(result);
  } catch (err) {
    console.error(err);
  }
})();

Description: Query all orders (including limit/market orders and plan orders).

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/order-entrust/list

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
type No string Type: ORDER/ENTRUST ORDER
symbol No string Trading pair identifier btc_usdt
state No string Order status NEW
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000
forceClose No boolean Whether it's a forced close false
page No integer Page number (default 1) 1
size No integer Items per page (default 10) 10

Field Descriptions:

Field Name Field Type Description Example
id String (serialized) Order record ID "1234567890123456789"
type String Type: ORDER (limit/market order), ENTRUST (plan order) "ORDER"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "LIMIT"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "GTC"
closePosition Boolean Whether it's a conditional full close order false
price String (serialized) Order price (effective for limit orders) "45000.00"
origQty String (serialized) Original order quantity (in lots) "10"
avgPrice String (serialized) Average fill price "44980.50"
executedQty String (serialized) Executed quantity (in lots) "5"
marginFrozen String (serialized) Frozen margin "250.50"
triggerProfitPrice String (serialized) Take Profit trigger price (conditional orders) "46000.00"
triggerStopPrice String (serialized) Stop Loss trigger price (conditional orders) "44000.00"
leverage Integer Leverage multiplier 20
entrustOrderId Long Associated order ID for conditional trigger (conditional orders) 987654321
closeProfit String (serialized) Close profit/loss (effective for closing orders) "125.50"
state String Order status:
NEW: New
PARTIALLY_FILLED: Partially filled
FILLED: Fully filled
CANCELED: User canceled
REJECTED: Order failed
EXPIRED: Expired
"PARTIALLY_FILLED"
createdTime Long Creation time (Unix timestamp, milliseconds) 1769672287213
entrustType String Order type (conditional order type) "TAKE_PROFIT_STOP"
stopPrice String (serialized) Trigger price (conditional orders) "45500.00"
triggerPriceType String Trigger price type (e.g., LAST, INDEX, etc.) "LAST"
isOrdinary Boolean Whether it's an ordinary plan order true
marketOrderLevel Integer Market order optimal level (effective for market orders) 1
forceClose Boolean Whether it's a forced close order false

Field Group Explanations:

Common Status Flow:

Conditional Order Type Reference:

Response Example (type=ORDER): { "code": 0, "msg": "success", "data": { "page": 1, "ps": 10, "total": 1, "items": [ { "id": "587077935051136448", "type": "ORDER", "symbol": "btc_usdt", "orderType": "MARKET", "orderSide": "BUY", "positionSide": "LONG", "timeInForce": "IOC", "closePosition": false, "price": "0", "origQty": "1", "avgPrice": "88256.7", "executedQty": "1", "marginFrozen": "0.4524", "triggerProfitPrice": null, "triggerStopPrice": null, "leverage": null, "entrustOrderId": null, "closeProfit": null, "state": "FILLED", "createdTime": 1769672287213, "entrustType": null, "stopPrice": null, "triggerPriceType": null, "isOrdinary": null, "marketOrderLevel": null, "forceClose": false } ] }, "bizCode": null }


Cancel Order Entrust

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/order-entrust/cancel"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_order_entrust(type_, id_):
    params = {
        "type": type_,
        "id": str(id_)
    }

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_order_entrust("ORDER", "1234567890")
const crypto = require('crypto');

const URL = "BASE_URL/v2/order-entrust/cancel";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelOrderEntrust(type, id) {
  const params = { type: String(type), id: String(id) };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelOrderEntrust("ORDER", "1234567890").catch(console.error);

Description: Cancel the specified order entrust (order or plan order).

Rate Limit Weight: 5

HTTP Method: POST
Endpoint: (TRADE)/v2/order-entrust/cancel

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
type Yes string Type: ORDER/ENTRUST ORDER
id Yes string Order Entrust ID 1234567890

Response Example:

{
  "code": 0,
  "message": "success",
  "data": null
}

Cancel All Order Entrusts

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/order-entrust/cancel-all"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def cancel_all_entrusts(symbol=None):
    params = {}
    if symbol is not None:
        params["symbol"] = symbol

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

cancel_all_entrusts("btc_usdt")

cancel_all_entrusts()
const crypto = require('crypto');

const URL = "BASE_URL/v2/order-entrust/cancel-all";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function cancelAllEntrusts(symbol) {
  const params = {};
  if (symbol !== undefined && symbol !== null) params.symbol = String(symbol);

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

cancelAllEntrusts("btc_usdt").catch(console.error);

cancelAllEntrusts().catch(console.error);

Description: Cancel all order entrusts for the user (including orders and plan orders). Optionally specify a trading pair.

Rate Limit Weight: 8

HTTP Method: POST
Endpoint: (TRADE)/v2/order-entrust/cancel-all

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
symbol No string Trading pair identifier (cancel all if not provided) btc_usdt

Response Example:

{
  "code": 0,
  "message": "success",
  "data": true
}

Query Balance List

import hmac
import hashlib
import requests

URL = "BASE_URL/v2/balance/list"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_balance_list():
    payload = ""
    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         payload.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.get(URL, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        data = resp.json()
        print(data)
    except ValueError:
        print(resp.text)

if __name__ == "__main__":
    get_balance_list()
const crypto = require('crypto');

const URL = "BASE_URL/v2/balance/list";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

(async () => {
  try {
    const payload = ""; 
    const signature = crypto.createHmac('sha256', SECRET_KEY).update(payload).digest('hex');

    const headers = {
      "X_ACCESS_KEY": ACCESS_KEY,
      "X_SIGNATURE": signature,
      "Content-Type": "application/x-www-form-urlencoded"
    };

    const resp = await fetch(URL, { method: "GET", headers });
    const text = await resp.text();
    console.log(resp.status);
    const ct = resp.headers.get("content-type") || "";
    if (ct.includes("application/json")) {
      console.log(JSON.parse(text));
    } else {
      console.log(text);
    }
  } catch (err) {
    console.error(err);
  }
})();

Description: Get funding information for all currencies for the user.

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/balance/list

Authentication: API Key required

Headers:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "coin": "usdt",
            "walletBalance": "93164.5884631",
            "openOrderMarginFrozen": "0",
            "isolatedMargin": "0",
            "crossedMargin": "0.4413",
            "availableBalance": "93164.1471631",
            "bonus": "0"
        }
    ],
    "bizCode": null
}

Field Descriptions:


Get User Single Currency Funds

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/balance/detail"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_balance_detail(coin):
    if not coin:
        raise ValueError("coin is required")

    params = {"coin": coin}

    items = sorted(params.items())
    query_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + "?" + query_str
    resp = requests.get(url, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

get_balance_detail("btc")
const crypto = require('crypto');

const BASE = "BASE_URL/v2/balance/detail";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getBalanceDetail(coin) {
  if (!coin) throw new Error("coin is required");

  const params = { coin: String(coin) };

  const keys = Object.keys(params).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, params[k]);
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const ct = resp.headers.get("content-type") || "";
  const result = ct.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

getBalanceDetail("btc").catch(console.error);

Description: Get detailed funding information for a specified currency for the user.

Rate Limit Weight: 1

HTTP Method: GET
Endpoint: /v2/balance/detail

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
coin Yes string Currency code btc

Field Descriptions:

Field Name Field Type Description Example
coin String Currency identifier "USDT"
walletBalance String (serialized) Total wallet balance "5000.75"
openOrderMarginFrozen String (serialized) Margin frozen by orders (occupied by open orders) "250.50"
isolatedMargin String (serialized) Isolated margin (occupied by opened positions) "1200.00"
crossedMargin String (serialized) Cross starting margin (occupied in cross margin mode) "0.00"
availableBalance String (serialized) Available balance (can be used for opening positions/withdrawals) "3549.25"
bonus String (serialized) Bonus balance (if any) "100.00"

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "coin": "btc",
        "walletBalance": "0",
        "openOrderMarginFrozen": "0",
        "isolatedMargin": "0",
        "crossedMargin": "0",
        "availableBalance": "0",
        "bonus": "0"
    },
    "bizCode": null
}

Query Bill Records

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/balance/bills"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def get_bills(id=None, direction=None, limit=None, coin=None, symbol=None,
              type_=None, startTime=None, endTime=None):
    params = {
        "id": id,
        "direction": direction,
        "limit": limit,
        "coin": coin,
        "symbol": symbol,
        "type": type_,          
        "startTime": startTime, 
        "endTime": endTime      
    }

    items = sorted((k, str(v)) for k, v in params.items() if v is not None)
    query_str = urlencode(items) 

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

get_bills(limit=10, coin="USDT", symbol="btc_usdt", startTime=1672444800000, endTime=1672531200000)
const crypto = require('crypto');

const BASE = "BASE_URL/v2/balance/bills";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function getBills(options = {}) {
  const paramsObj = {};
  for (const k of ["id", "direction", "limit", "coin", "symbol", "type", "startTime", "endTime"]) {
    if (options[k] !== undefined && options[k] !== null) {
      paramsObj[k] = String(options[k]);
    }
  }

  const keys = Object.keys(paramsObj).sort();
  const usp = new URLSearchParams();
  for (const k of keys) usp.append(k, paramsObj[k]);
  const queryStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const ct = resp.headers.get("content-type") || "";
  const result = ct.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

getBills({
  limit: 10,
  coin: "USDT",
  symbol: "btc_usdt",
  startTime: 1672444800000,
  endTime: 1672531200000
}).catch(console.error);

Description: Query the user's account transaction records, supporting pagination and filtering.

Rate Limit Weight: 2

HTTP Method: GET
Endpoint: /v2/balance/bills

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
id No string Cursor ID (for pagination) 1234567890
direction No string Pagination direction: NEXT/PREV NEXT
limit No integer Records per page (default 10) 10
coin No string Filter by currency BTC
symbol No string Trading pair btc_usdt
type No string Bill type FEE
startTime No integer Start timestamp (milliseconds) 1672444800000
endTime No integer End timestamp (milliseconds) 1672531200000

Bill Type Explanations:

Field Descriptions:

Field Name Field Type Description Example
id String (serialized) Transaction record ID "9876543210123456789"
coin String Currency identifier "USDT"
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
type String Transaction type:
EXCHANGE: Transfer
CLOSE_POSITION: Close position profit/loss
TAKE_OVER: Position takeover
QIANG_PING_MANAGER: Forced liquidation fee
FUND: Funding fee
FEE: Transaction fee (open, close, forced liquidation)
ADL: Auto-Deleveraging
MERGE: Position merge
"FEE"
amount String (serialized) Change amount (can be positive or negative) "-0.5000"
side String Fund direction:
ADD: Increase/transfer in
SUB: Decrease/transfer out
"SUB"
afterAmount String (serialized) Balance after the change "1250.7500"
createdTime Long Record creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

  1. Relationship between type and side:
  1. Value Sign Rules:
  1. Common Scenario Examples:
  1. afterAmount:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": {
        "hasPrev": false,
        "hasNext": true,
        "items": [
            {
                "id": "587083445113472257",
                "coin": "usdt",
                "symbol": "btc_usdt",
                "type": "FUND",
                "amount": "-0.00080000",
                "side": "SUB",
                "afterAmount": null,
                "createdTime": 1769673600798
            },
            {
                "id": "587077936180380928",
                "coin": "usdt",
                "symbol": "btc_usdt",
                "type": "FEE",
                "amount": "-0.00440000",
                "side": "SUB",
                "afterAmount": null,
                "createdTime": 1769672287366
            }
        ]
    },
    "bizCode": null
}

Get Listen Key

import hmac
import hashlib
import requests

URL = "BASE_URL/v2/user/listen-key"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

payload = ""

signature = hmac.new(SECRET_KEY.encode('utf-8'),
                     payload.encode('utf-8'),
                     hashlib.sha256).hexdigest()

headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
}

resp = requests.get(URL, headers=headers, timeout=10)
print(resp.status_code)
print(resp.text)

try:
    resp_json = resp.json()
    listen_key = resp_json.get("data")
    print("listenKey:", listen_key)
except Exception:
    pass
const crypto = require('crypto');

const URL = "BASE_URL/v2/user/listen-key";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

(async () => {
  const payload = "";
  const signature = crypto.createHmac('sha256', SECRET_KEY).update(payload).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "GET", headers });
  const result = await resp.text();
  console.log(resp.status, result);

  try {
    const json = JSON.parse(result);
    console.log("listenKey:", json.data);
  } catch (e) { /* ignore parse error */ }
})();

Description: Get the WebSocket user data stream Listen Key, used to establish private data stream connections.

Rate Limit Weight: 5

HTTP Method: GET
Endpoint: /v2/user/listen-key

Authentication: API Key required

Headers:

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": "FAD5A97BA1BD77BAF64F9770AD05ABFF",
    "bizCode": null
}

Field Descriptions:

FAD5A97BA1BD77BAF64F9770AD05ABFF: WebSocket Listen Key, used to connect to private data streams. The key is typically valid for 1 hour.

Important Notes:


Query Current Orders

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order/listUnfinished"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def list_unfinished(symbol, direction):
    params = {
        "symbol": symbol,
        "direction": direction
    }

    items = sorted(params.items())
    query_str = urlencode(items)

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         query_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + "?" + query_str
    resp = requests.get(url, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

list_unfinished("btc_usdt", "BUY")
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order/listUnfinished";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function listUnfinished(symbol, direction) {
  const params = { symbol: String(symbol), direction: String(direction) };

  const entries = Object.entries(params).sort((a, b) => a[0].localeCompare(b[0]));
  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const queryStr = usp.toString(); 

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

listUnfinished("btc_usdt", "BUY").catch(console.error);

Description: Query current valid orders (unfilled orders) for a specified trading pair and direction.

Rate Limit Weight: 1

HTTP Method: GET
Endpoint: /v2/order/listUnfinished

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
symbol Yes string Trading pair identifier btc_usdt
direction Yes string Order side: BUY/SELL BUY

Field Descriptions:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be empty) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full close order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (in lots) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Executed quantity (in lots) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take Profit trigger price (can be empty) null
triggerStopPrice String (serialized) Stop Loss trigger price (can be empty) null
sourceId Long Conditional trigger ID (can be empty) null
forceClose Boolean Whether it's a full close order false
closeProfit String (serialized) Close profit/loss (can be empty) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": [
    {
      "orderId": "587077935051136448",
      "clientOrderId": null,
      "symbol": "btc_usdt",
      "orderType": "MARKET",
      "orderSide": "BUY",
      "positionSide": "LONG",
      "timeInForce": "IOC",
      "closePosition": false,
      "price": "0",
      "origQty": "1",
      "avgPrice": "88256.7",
      "executedQty": "1",
      "marginFrozen": "0.4524",
      "triggerProfitPrice": null,
      "triggerStopPrice": null,
      "sourceId": null,
      "forceClose": false,
      "closeProfit": null,
      "state": "FILLED",
      "createdTime": 1769672287213
    }
  ]
}

Query All Current Orders

import hmac
import hashlib
from urllib.parse import urlencode
import requests

BASE = "BASE_URL/v2/order/all/listUnfinished"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def list_unfinished(symbols):
    """
    symbols: list of symbol strings or a single comma-separated string, e.g. ["btc_usdt","eth_usdt"] or "btc_usdt,eth_usdt"
    """
    if isinstance(symbols, (list, tuple)):
        list_str = ",".join(symbols)
    else:
        list_str = str(symbols)

    params = {"list": list_str}

    sorted_items = sorted(params.items())
    query_str = urlencode(sorted_items) 

    signature = hmac.new(SECRET_KEY.encode('utf-8'), query_str.encode('utf-8'), hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    url = BASE + ("?" + query_str if query_str else "")
    resp = requests.get(url, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

list_unfinished(["btc_usdt", "eth_usdt"])
const crypto = require('crypto');

const BASE = "BASE_URL/v2/order/all/listUnfinished";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function listUnfinished(symbols) {
  const listStr = Array.isArray(symbols) ? symbols.map(String).join(',') : String(symbols);

  const params = { list: listStr };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));

  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const queryStr = usp.toString(); 

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(queryStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const url = BASE + (queryStr ? `?${queryStr}` : "");
  const resp = await fetch(url, { method: "GET", headers });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

listUnfinished(["btc_usdt","eth_usdt"]).catch(console.error);

Description: Query current valid orders for multiple trading pairs.

Rate Limit Weight: 1

HTTP Method: GET
Endpoint: /v2/order/all/listUnfinished

Authentication: API Key required

Headers:

Query Parameters:

Parameter Required Type Description Example
list Yes string Trading pair list (comma separated) btc_usdt,eth_usdt

Field Descriptions:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be empty) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full close order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (in lots) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Executed quantity (in lots) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take Profit trigger price (can be empty) null
triggerStopPrice String (serialized) Stop Loss trigger price (can be empty) null
sourceId Long Conditional trigger ID (can be empty) null
forceClose Boolean Whether it's a full close order false
closeProfit String (serialized) Close profit/loss (can be empty) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": [
    {
      "orderId": "587077935051136448",
      "clientOrderId": null,
      "symbol": "btc_usdt",
      "orderType": "MARKET",
      "orderSide": "BUY",
      "positionSide": "LONG",
      "timeInForce": "IOC",
      "closePosition": false,
      "price": "0",
      "origQty": "1",
      "avgPrice": "88256.7",
      "executedQty": "1",
      "marginFrozen": "0.4524",
      "triggerProfitPrice": null,
      "triggerStopPrice": null,
      "sourceId": null,
      "forceClose": false,
      "closeProfit": null,
      "state": "FILLED",
      "createdTime": 1769672287213
    }
  ]
}

Query Orders by ID List

import hmac
import hashlib
from urllib.parse import urlencode
import requests

URL = "BASE_URL/v2/order/list-by-ids"
ACCESS_KEY = "YOUR_ACCESS_KEY"
SECRET_KEY = "YOUR_SECRET_KEY"

def list_by_ids(ids):
    """
    ids: list of id strings OR a single comma-separated string
    """
    if isinstance(ids, (list, tuple)):
        ids_str = ",".join(map(str, ids))
    else:
        ids_str = str(ids)

    params = {"ids": ids_str}

    items = sorted((k, v) for k, v in params.items() if v is not None)
    body_str = urlencode(items) 

    signature = hmac.new(SECRET_KEY.encode('utf-8'),
                         body_str.encode('utf-8'),
                         hashlib.sha256).hexdigest()

    headers = {
        "X_ACCESS_KEY": ACCESS_KEY,
        "X_SIGNATURE": signature,
        "Content-Type": "application/x-www-form-urlencoded"
    }

    resp = requests.post(URL, data=body_str, headers=headers, timeout=10)
    print(resp.status_code)
    try:
        print(resp.json())
    except ValueError:
        print(resp.text)

list_by_ids("587077935051136448")

list_by_ids(["587077935051136448", "587077935051136449"])
const crypto = require('crypto');

const URL = "BASE_URL/v2/order/list-by-ids";
const ACCESS_KEY = "YOUR_ACCESS_KEY";
const SECRET_KEY = "YOUR_SECRET_KEY";

async function listByIds(ids) {

  const idsStr = Array.isArray(ids) ? ids.map(String).join(',') : String(ids);

  const params = { ids: idsStr };

  const entries = Object.entries(params).filter(([k, v]) => v !== undefined && v !== null);
  entries.sort((a, b) => a[0].localeCompare(b[0]));
  const usp = new URLSearchParams();
  for (const [k, v] of entries) usp.append(k, v);
  const bodyStr = usp.toString();

  const signature = crypto.createHmac('sha256', SECRET_KEY).update(bodyStr).digest('hex');

  const headers = {
    "X_ACCESS_KEY": ACCESS_KEY,
    "X_SIGNATURE": signature,
    "Content-Type": "application/x-www-form-urlencoded"
  };

  const resp = await fetch(URL, { method: "POST", headers, body: bodyStr });
  const contentType = resp.headers.get("content-type") || "";
  const result = contentType.includes("application/json") ? await resp.json() : await resp.text();
  console.log(resp.status, result);
}

listByIds("587077935051136448").catch(console.error);

listByIds(["587077935051136448", "587077935051136449"]).catch(console.error);

Description: Query order details based on a list of order IDs.

Rate Limit Weight: 1

HTTP Method: POST
Endpoint: /v2/order/list-by-ids

Authentication: API Key required

Headers:

Request Body Parameters:

Parameter Required Type Description Example
ids Yes string Order ID list (multiple order IDs separated by commas) 587077935051136448

Field Descriptions:

Field Name Field Type Description Example
orderId String (serialized) Order ID "587077935051136448"
clientOrderId String Custom order ID (can be empty) null
symbol String Trading pair identifier (lowercase, underscore separated) "btc_usdt"
orderType String Order type: LIMIT, MARKET, etc. "MARKET"
orderSide String Order side: BUY, SELL "BUY"
positionSide String Position side: LONG, SHORT "LONG"
timeInForce String Time in force: GTC, IOC, FOK, GTX "IOC"
closePosition Boolean Whether it's a conditional full close order false
price String (serialized) Order price "0"
origQty String (serialized) Original order quantity (in lots) "1"
avgPrice String (serialized) Average fill price "88256.7"
executedQty String (serialized) Executed quantity (in lots) "1"
marginFrozen String (serialized) Frozen margin "0.4524"
triggerProfitPrice String (serialized) Take Profit trigger price (can be empty) null
triggerStopPrice String (serialized) Stop Loss trigger price (can be empty) null
sourceId Long Conditional trigger ID (can be empty) null
forceClose Boolean Whether it's a full close order false
closeProfit String (serialized) Close profit/loss (can be empty) null
state String Order status: NEW, PARTIALLY_FILLED, PARTIALLY_CANCELED, FILLED, CANCELED, REJECTED, EXPIRED "FILLED"
createdTime Long Order creation time (Unix timestamp, milliseconds) 1769672287213

Additional Notes:

Response Example:

{
  "code": 0,
  "message": "success",
  "data": [
    {
      "orderId": "587077935051136448",
      "clientOrderId": null,
      "symbol": "btc_usdt",
      "orderType": "MARKET",
      "orderSide": "BUY",
      "positionSide": "LONG",
      "timeInForce": "IOC",
      "closePosition": false,
      "price": "0",
      "origQty": "1",
      "avgPrice": "88256.7",
      "executedQty": "1",
      "marginFrozen": "0.4524",
      "triggerProfitPrice": null,
      "triggerStopPrice": null,
      "sourceId": null,
      "forceClose": false,
      "closeProfit": null,
      "state": "FILLED",
      "createdTime": 1769672287213
    }
  ]
}

Partner Rebate Details

import requests
import time
import hmac
import hashlib
import urllib.parse

# Configuration
BASE_URL = "https://api.example.com"
API_KEY = "your_api_accessKey"
SECRET_KEY = "your_api_query_secretKey"

def generate_signature(params, secret_key):
    """
    Generate signature
    :param params: Request parameters dictionary
    :param secret_key: API secret key
    :return: Signature string
    """
    # Sort parameters by key
    sorted_params = sorted(params.items())
    # Build query string
    query_string = '&'.join([f"{k}={v}" for k, v in sorted_params])
    # Generate signature using HMAC-SHA256
    signature = hmac.new(
        secret_key.encode('utf-8'),
        query_string.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    return signature

def get_rebate_detail(rebate_start_date=None, rebate_end_date=None, symbol_id=None):
    """
    Get partner rebate details
    :param rebate_start_date: Query start time (millisecond timestamp)
    :param rebate_end_date: Query end time (millisecond timestamp)
    :param symbol_id: Trading pair ID
    :return: Rebate detail data
    """
    # Request path
    path = "/v2/channel/rebateDetail"
    url = BASE_URL + path

    # Build request parameters
    params = {}
    if rebate_start_date:
        params['rebateStartDate'] = str(rebate_start_date)
    if rebate_end_date:
        params['rebateEndDate'] = str(rebate_end_date)
    if symbol_id:
        params['symbolId'] = str(symbol_id)

    # Generate signature
    signature = generate_signature(params, SECRET_KEY)

    # Set request headers
    headers = {
        'X_ACCESS_KEY': API_KEY,
        'X_SIGNATURE': signature,
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    try:
        # Send GET request
        response = requests.get(url, params=params, headers=headers)
        response.raise_for_status()

        # Parse response data
        data = response.json()

        if data.get('code') == 0:
            print("Request successful!")
            return data.get('data', [])
        else:
            print(f"Request failed: {data.get('msg')}")
            return None

    except requests.exceptions.RequestException as e:
        print(f"Request exception: {e}")
        return None

# Usage examples
if __name__ == "__main__":
    # Example 1: Query all rebate details
    print("Example 1: Query all rebate details")
    result = get_rebate_detail()
    if result:
        for item in result:
            print(f"User: {item['uid']}, Trading Pair: {item['symbol']}, Rebate Amount: {item['totalRebateAmount']}")
    print("-" * 50)

    # Example 2: Query by time range
    print("Example 2: Query by time range")
    start_time = 1769919603517  # Start timestamp
    end_time = 1772511603517     # End timestamp
    result = get_rebate_detail(rebate_start_date=start_time, rebate_end_date=end_time)
    if result:
        for item in result:
            print(f"User: {item['uid']}, Trading Pair: {item['symbol']}, Rebate Amount: {item['totalRebateAmount']}")
    print("-" * 50)

    # Example 3: Query by trading pair ID
    print("Example 3: Query by trading pair ID")
    result = get_rebate_detail(symbol_id=1)
    if result:
        for item in result:
            print(f"User: {item['uid']}, Trading Pair: {item['symbol']}, Rebate Amount: {item['totalRebateAmount']}")
    print("-" * 50)

    # Example 4: Combined condition query
    print("Example 4: Combined condition query (time range + trading pair ID)")
    result = get_rebate_detail(
        rebate_start_date=1769919603517,
        rebate_end_date=1772511603517,
        symbol_id=2
    )
    if result:
        for item in result:
            print(f"User: {item['uid']}, Trading Pair: {item['symbol']}, Rebate Amount: {item['totalRebateAmount']}")
// Using axios library, need to install first: npm install axios
const axios = require('axios');
const crypto = require('crypto');

// Configuration
const BASE_URL = 'https://api.example.com';
const API_KEY = 'your_api_accessKey';
const SECRET_KEY = 'your_api_query_secretKey';

/**
 * Generate signature
 * @param {Object} params - Request parameters object
 * @param {string} secretKey - API secret key
 * @returns {string} Signature string
 */
function generateSignature(params, secretKey) {
    // Sort parameters by key
    const sortedParams = Object.keys(params)
        .sort()
        .reduce((acc, key) => {
            acc[key] = params[key];
            return acc;
        }, {});

    // Build query string
    const queryString = Object.entries(sortedParams)
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&');

    // Generate signature using HMAC-SHA256
    return crypto
        .createHmac('sha256', secretKey)
        .update(queryString)
        .digest('hex');
}

/**
 * Get partner rebate details
 * @param {Object} options - Query parameters
 * @param {string} options.rebateStartDate - Query start time (millisecond timestamp)
 * @param {string} options.rebateEndDate - Query end time (millisecond timestamp)
 * @param {string} options.symbolId - Trading pair ID
 * @returns {Promise<Array>} Rebate detail data
 */
async function getRebateDetail({ rebateStartDate, rebateEndDate, symbolId } = {}) {
    // Request path
    const path = '/v2/channel/rebateDetail';
    const url = BASE_URL + path;

    // Build request parameters (only add parameters with values)
    const params = {};
    if (rebateStartDate) params.rebateStartDate = String(rebateStartDate);
    if (rebateEndDate) params.rebateEndDate = String(rebateEndDate);
    if (symbolId) params.symbolId = String(symbolId);

    // Generate signature
    const signature = generateSignature(params, SECRET_KEY);

    // Set request headers
    const headers = {
        'X_ACCESS_KEY': API_KEY,
        'X_SIGNATURE': signature,
        'Content-Type': 'application/x-www-form-urlencoded'
    };

    try {
        // Send GET request
        const response = await axios.get(url, { params, headers });

        // Parse response data
        const { code, msg, data } = response.data;

        if (code === 0) {
            console.log('Request successful!');
            return data;
        } else {
            console.log(`Request failed: ${msg}`);
            return null;
        }

    } catch (error) {
        console.error('Request exception:', error.message);
        if (error.response) {
            console.error('Response data:', error.response.data);
        }
        return null;
    }
}

// Usage examples
async function main() {
    // Example 1: Query all rebate details
    console.log('Example 1: Query all rebate details');
    const result1 = await getRebateDetail();
    if (result1) {
        result1.forEach(item => {
            console.log(`User: ${item.uid}, Trading Pair: ${item.symbol}, Rebate Amount: ${item.totalRebateAmount}`);
        });
    }
    console.log('-'.repeat(50));

    // Example 2: Query by time range
    console.log('Example 2: Query by time range');
    const result2 = await getRebateDetail({
        rebateStartDate: '1769919603517',
        rebateEndDate: '1772511603517'
    });
    if (result2) {
        result2.forEach(item => {
            console.log(`User: ${item.uid}, Trading Pair: ${item.symbol}, Rebate Amount: ${item.totalRebateAmount}`);
        });
    }
    console.log('-'.repeat(50));

    // Example 3: Query by trading pair ID
    console.log('Example 3: Query by trading pair ID');
    const result3 = await getRebateDetail({
        symbolId: '1'
    });
    if (result3) {
        result3.forEach(item => {
            console.log(`User: ${item.uid}, Trading Pair: ${item.symbol}, Rebate Amount: ${item.totalRebateAmount}`);
        });
    }
    console.log('-'.repeat(50));

    // Example 4: Combined condition query
    console.log('Example 4: Combined condition query (time range + trading pair ID)');
    const result4 = await getRebateDetail({
        rebateStartDate: '1769919603517',
        rebateEndDate: '1772511603517',
        symbolId: '2'
    });
    if (result4) {
        result4.forEach(item => {
            console.log(`User: ${item.uid}, Trading Pair: ${item.symbol}, Rebate Amount: ${item.totalRebateAmount}`);
        });
    }
}

// Browser environment example (using fetch)
/*
async function getRebateDetailBrowser(params = {}) {
    const url = new URL('https://api.example.com/v2/channel/rebateDetail');

    // Add query parameters
    Object.keys(params).forEach(key => {
        if (params[key]) {
            url.searchParams.append(key, params[key]);
        }
    });

    // Generate signature (in production, signature should be generated on the backend)
    const signature = generateSignature(params, SECRET_KEY);

    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'X_ACCESS_KEY': API_KEY,
            'X_SIGNATURE': signature,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });

    const data = await response.json();
    return data;
}
*/

// Execute examples
main().catch(console.error);

Description: Get partner rebate details by time range and trading pair ID.

Interface Weight: 1

Request Method: GET
Request URL: /v2/channel/rebateDetail

Authentication Requirements: API key authentication required

Request Headers:

Request Body Parameters:

Parameter Required Type Description Example
rebateStartDate No string Query start time (UTC+8) 1769919603517
rebateEndDate No string Query end time (UTC+8) 1772511603517
symbolId No string Trading pair ID 1

Field Description:

Field Type Description Example
uid String User UID "10000591"
pumpkinUid String pumpkin UID "10132346"
walletAddress String Wallet address null
totalTradeAmount BigDecimal Total trading amount 19993.5193
totalFee BigDecimal Total fee 9.9967
totalRebateAmount BigDecimal Total rebate amount 3.9987
rebateDate Long Rebate statistics time (Unix timestamp, milliseconds) 1769039700000
symbol String Trading pair identifier (lowercase, underscore separated) "eth_usdt"
rebateType Integer Rebate type: 1-self rebate, 2-direct customer, 3-price difference 2
rate BigDecimal Rebate rate 0.4
userType Integer User type: 1-partner, 2-retail 2
symbolId Integer Trading pair ID 2

Response Example:

{
    "code": 0,
    "msg": "success",
    "data": [
        {
            "uid": "10000585",
            "pumpkinsUid": "10132346",
            "walletAddress": "0xa90e27355aad0edfae161c5ba42002c8b2cd2738",
            "totalTradeAmount": 50616.55316,
            "totalFee": 25.3079,
            "totalRebateAmount": 12.65395,
            "rebateDate": 1772610900000,
            "symbol": "btc_usdt",
            "rebateType": 3,
            "rate": 0.5,
            "userType": 1,
            "symbolId": 1
        },
        {
            "uid": "10000585",
            "pumpkinsUid": "10132346",
            "walletAddress": "0xa90e27355aad0edfae161c5ba42002c8b2cd2738",
            "totalTradeAmount": 21081.90828,
            "totalFee": 10.54095413,
            "totalRebateAmount": 5.270476,
            "rebateDate": 1772610900000,
            "symbol": "eth_usdt",
            "rebateType": 3,
            "rate": 0.5,
            "userType": 1,
            "symbolId": 2
        }
    ],
    "bizCode": null
}

API Error Codes & Handling Guidance

The table below includes not only the meaning of each code, but also the recommended client-side action, so integrators can implement sensible retry and alerting strategies.

Status code Meaning Recommended client action
1 Invalid auth content / behavior / format Verify the request signature and parameter format; fix and retry (otherwise it will continue to fail)
-1 Invalid API key, account info, or identity details Verify and rotate the API key / check account status; if the issue persists, contact ops/support
403 WAF restriction triggered (Web Application Firewall), resulting in a 1-hour IP ban Pause requests and investigate request patterns (rate, payload); if false positive, contact support for unban
418 IP restricted (not in allowlist) Use an allowlisted IP or add the IP to the allowlist
429 High IP request rate; IP has been banned Back off per rate-limit policy (exponential backoff + throttling); reduce frequency and retry
439 Rate limit exceeded (more fine-grained) Similar to 429; prefer degradation/throttling first and review request patterns
5XX Server-side error (Pumpkin service issue) Log and alert; retry short-term (exponential backoff); if persistent, contact the service provider
503 Request reached backend but no response (unknown state) Success/failure is unknown: avoid blind retries that may cause duplicate submissions; check idempotency and query order status before deciding whether to retry

Interface Error Codes

Any endpoint may return an exception. The error response format is:

{
  "code": 1,
  "msg": "sign-error"
}

{
  "code": 429,
  "msg": "ip_high_frequency",
  "data": {
    "type": "ip",
    "current": 120,
    "limit": 100,
    "reset": 3600
  }
}

WebSocket API Documentation

WebSocket API Basics

Base URL:

Connection:

Heartbeat:

Subscribe/Unsubscribe format:

Error codes:

Code Description
0 Success
40001 Invalid topic format
40002 Topic not found
40003 Subscription limit exceeded
40004 Invalid parameters
40005 Insufficient permissions
40006 Rate limit exceeded
50001 Internal server error
50002 Service temporarily unavailable

WebSocket Market Data

Candlestick data (Kline):

1、Topic format:

2、Request example:

json:{"events": ["kline@trx_usdt,1m"],"method": "sub"}

  {
      "events": ["kline@trx_usdt,1m"],
      "method": "sub"
  }

3、Success response:

json:{"code": 0,"msg": "success"}

  {
    "code": 0,
    "msg": "success"
  }

4、Push payload (JSON):

json:{ "e": "kline", "s": "trx_usdt", "k": { "s": "trx_usdt", "i": "1m", "t": 1646382900000, "o": "0.31865", "c": "0.31862", "h": "0.31865", "l": "0.31862", "v": "369", "a": "117.57114" } }

  {
    "e": "kline",
    "s": "trx_usdt",
    "k": {
      "s": "trx_usdt",
      "i": "1m",
      "t": 1646382900000,
      "o": "0.31865",
      "c": "0.31862",
      "h": "0.31865",
      "l": "0.31862",
      "v": "369",
      "a": "117.57114"
    }
  }

message KlineVO {
    string s = 1;      // (trx_usdt)
    string o = 2;      // (0.31865)
    string c = 3;      // (0.31862)
    string h = 4;      // (0.31865)
    string l = 5;      // (0.31862)
    string a = 6;      // (117.57114)
    string v = 7;      // (369)
    string i = 8;      // (1m)
    int64 t = 9;       // (1646382900000)
}

5、Field reference:

Field Type Description
e String Event type, always "kline"
s String Trading pair
k.s String Trading pair
k.i String Candlestick interval
k.t Long Candlestick open time (ms)
k.o String Open price
k.c String Close price
k.h String High price
k.l String Low price
k.v String Volume
k.a String Turnover

Latest trades (Trade):

1、Topic format:

2、Request example:

json:{"events": ["trade@btc_usdt"],"method": "sub"}

{
    "events": ["trade@btc_usdt"],
    "method": "sub"
}

3、Success response:

json:{"code": 0,"msg": "success"}

{
    "code": 0,
    "msg": "success"
}

4、Push payload (JSON):

json:{ "e": "trade", "s": "btc_usdt", "t": 1234567890123456, "p": "95150.62", "a": "7", "m": "BID" }

{
    "e": "trade",
    "s": "btc_usdt",
    "t": 1234567890123456,
    "p": "95150.62",
    "a": "7",
    "m": "BID"
}
message DealVO {
    int64 t = 1;        // 成交时间
    string s = 2;       // 交易对
    string p = 3;       // 成交价
    string a = 4;       // 成交量
    string m = 5;       // 买卖方向 (BID/ASK)
    int64 id = 6;       // 交易ID
}

5、Field reference:

Field Type Description
e String Event type, always "trade"
s String Trading pair
t Long Trade ID
p String Trade price
a String Trade size
m String Side: "BID"(buy) / "ASK"(sell)

Order book (Depth):

1、Topic format:

2、Request example:

json:{"events": ["depth@btc_usdt,10"],"method": "sub"}

{
    "events": ["depth@btc_usdt,10"],
    "method": "sub"
}

3、Success response:

json:{"code": 0,"msg": "success"}

{
    "code": 0,
    "msg": "success"
}

4、Push payload (JSON): json { "e": "depth", "s": "btc_usdt", "U": 1234567890, "u": 1234567891, "b": [ ["45000.00", "1.2345"], ["44999.50", "0.9876"], ["44999.00", "2.3456"] ], "a": [ ["45001.00", "0.5432"], ["45001.50", "1.2345"], ["45002.00", "0.8765"] ] }

5、Push payload (Protobuf):

6、Incremental updates:

{
    "e": "depth.update",
    "s": "btc_usdt",
    "U": 1234567890,
    "u": 1234567891,
    "b": [
        ["45000.00", "1.2345"]
    ],
    "a": [
        ["45001.00", "0.5432"]
    ]
}

message DepthVO {
    string s = 1;        
    int64 U = 2;         
    int64 u = 3;         
    repeated PriceLevel bids = 4;
    repeated PriceLevel asks = 5;
}

message PriceLevel {
    string price = 1;
    string quantity = 2;
}

7、Field reference:

Field Type Description
e String Event type: "depth" or "depth.update"
s String Trading pair
U Long First update ID
u Long Last update ID
b Array Bid levels [[price, quantity], ...]
a Array Ask levels [[price, quantity], ...]

Usage Example

class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.ws = null;
        this.pingInterval = null;
    }

    connect() {
        this.ws = new WebSocket(this.url);

        this.ws.onopen = () => {
            console.log('WebSocket connected');
            this.startHeartbeat();
        };

        this.ws.onmessage = (event) => {

            if (typeof event.data === 'string') {
                if (event.data === 'pong') {
                    console.log('Received heartbeat response');
                    return;
                }

                try {
                    const data = JSON.parse(event.data);
                    this.handleMessage(data);
                } catch (error) {
                    console.log('Received text message:', event.data);
                }
            } 
            // Handling binary messages (protobuf)
            else if (event.data instanceof ArrayBuffer || event.data instanceof Blob) {
                this.handleBinaryMessage(event.data);
            }
        };
    }

    startHeartbeat() {
        // Send a heartbeat every 3 seconds
        this.pingInterval = setInterval(() => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send('ping');
            }
        }, 3000);
    }

    subscribe(topics) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            console.error('WebSocket is not connected');
            return;
        }

        const message = {
            events: Array.isArray(topics) ? topics : [topics],
            method: "sub"
        };

        this.ws.send(JSON.stringify(message));
    }

    unsubscribe(topics) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            console.error('WebSocket is not connected');
            return;
        }

        const message = {
            events: Array.isArray(topics) ? topics : [topics],
            method: "unsub"
        };

        this.ws.send(JSON.stringify(message));
    }

    handleMessage(data) {
        // 处理订阅响应
        if (data.code !== undefined) {
            if (data.code === 0) {
                console.log('Operation successful:', data.msg);
            } else {
                console.error('Operation failed:', data.code, data.msg);
            }
            return;
        }

        // 处理数据推送
        switch (data.e) {
            case 'kline':
                console.log('K-line data:', data);
                break;
            case 'trade':
                console.log('trade data:', data);
                break;
            case 'depth':
            case 'depth.update':
                console.log('depth data:', data);
                break;
            default:
                console.log('Unknown message type:', data);
        }
    }

    handleBinaryMessage(binaryData) {
        console.log('Received binary data, size:', binaryData.byteLength || binaryData.size);
        // Here, it is necessary to parse the Protobuf according to the specific format
    }
}

Quick start:

Notes

  1. Rate limits:avoid frequent subscribe/unsubscribe; prefer batching
  2. Data validation:always validate inbound payloads
  3. Error handling:implement robust error handling and reconnect logic
  4. Memory management:clean up unused data to prevent memory leaks
  5. Network security:use WSS (WebSocket Secure) in production
  6. Logging:log connection status and key events for troubleshooting
  7. Compatibility:account for WebSocket implementation differences across browsers

Best Practices

1. Connection management: Reconnect


let reconnectTimer = null;

function reconnect() {
    if (reconnectTimer) clearTimeout(reconnectTimer);

    reconnectTimer = setTimeout(() => {
        console.log('Try to reconnect...');
        connectWebSocket();
    }, 3000);
}

ws.onclose = function() {
    console.log('Connection lost, preparing to reconnect');
    reconnect();
};

2. Caching:


const dataCache = {
    kline: new Map(),
    trade: new Map(),
    depth: new Map()
};

function updateCache(type, symbol, data) {
    const key = `${type}_${symbol}`;
    dataCache[type].set(key, {
        data: data,
        timestamp: Date.now()
    });

    const now = Date.now();
    for (let [key, value] of dataCache[type].entries()) {
        if (now - value.timestamp > 30000) {
            dataCache[type].delete(key);
        }
    }
}

3. Batch operations: Multiple symbols and multiple intervals

function batchSubscribe(topics) {
    if (topics.length === 0) return;

    const message = {
        events: topics,
        method: "sub"
    };

    ws.send(JSON.stringify(message));
}

batchSubscribe([
    'kline@btc_usdt,1m',
    'kline@eth_usdt,1m',
    'trade@btc_usdt',
    'depth@btc_usdt,10'
]);