Update Log

entry-into-force timeInterfaceabstract
2022-03-28rest cancelAllOrdersAfter/getSpotBillsNew interface:rest cancelAllOrdersAfter/getSpotBills Cancel the delegation regularly/Get spot bill
2022-03-17rest cancelOrderModify interface:Rest cancelOrder The interface newly adds the data of order quantity, order price, total transaction volume and transaction quantity
2022-03-17ws kline/ws push_user_cross_assetNew interface:websocket Kline and Full bin lever push interface
2022-03-01setExpressState/setRepayStateNew interface:setExpressState/setRepayState
2021-09-18klineWebsocket API push_user_incr_record The interface newly adds four fields: the latest transaction ID, price, quantity and time
2021-07-16klineThe symbol field of the interface return value is changed to uppercase
2021-07-16all interfaceAll interfaces no longer support the old name of the currency, and use the new name uniformly, where the old name includes:bchabc,bchsv,hsr,nxwc. The new names correspond to:bch,bsv,hc,xwc
2021-03-16getFeeInfoDelete the API for 'createSubUserKey'
2021-03-16restMarketChange HTTP to HTTPS
2020-12-31push_user_incr_record,
push_user_incr_asset
Only push changed currency orders and assets

Get Started

ZB API Introduction

eg: https://api.zb.com/data/v1/ticker?market=btc_usdt

ZB provides APIs for fast access to its spot markets with the following features: market data, order book, depths of bids and asks, trade history, trade execution, order information, order history, Account information.

If you have any question, please contact email: [email protected] for support.

API Interface Description

ZB.com provides Rest API and Websocket API, you can use them to inquiry market data and trade as needed.

REST APIDescription

Rest is short for Representational State Transfer, which is one of the most popular internet software architectures. It's clear in structure, easy to understand and expand, making it get adopted by more and more websites. Its advantages are as follows::

In the architecture of RESTful, each URL represents one kind of resource;

Some representation layers of this resource are transferred between client and server;

The client uses four HTTP instructions to operate the server resources and realize the state transitions of the presentation layer

Developers are advised to use the REST API for operations such as trading or asset withdrawal.

WebSocket API

WebSocket is a new protocol of HTML5. It realizes the full-duplex communication between client and server, makes data being rapidly transferred in both directions. The connection between client and server can be established through a simple handshake, and the server can actively push information to the client according to business rules. Its advantages are as follows::

When data is transferred between client and server, request header information can be relatively small which is about 2 bytes.

Both client and server can actively send data to each other.

No need to create TCP requests and destroy them multiple times to save bandwidth and server resources.

It is strongly recommended that developers use WebSocket API to obtain information such as market data and depth.

Rest API

Please make sure to set user agent to 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'

Sample Code

Signature: Use sha to encrypt the secretkey first, then sign the requested parameters according to the encrypted secretkey, request the parameters to be sorted and encrypted according to the ascii value, and fill the 16-bit encryption with md5.

github Sample Code

Access Restriction

1.For Trade API and Margin API, a single IP is limited to 10,000 access per minute, while over 10,000 access will be locked for 1 hour and automatically unlocked after one hour.。

2.For Trade API and Margin API, a single API KEY is limited to 60 accesses per second, and requests that exceed 60 requests per second are considered invalid.。

3.K-Line data can only be requested once per second.。

Configuration

Get Market Configuration

Get the open market information, including the number of decimal places for prices

Request Sample


// request demo
GET https://api.zb.com/data/v1/markets



// java demo
public void getMarkets() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/markets").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getMarkets(self, market):
    url = 'https://api.zb.com/data/v1/markets'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "btc_usdt": {
        "amountScale": 4,
        "minAmount": 0.0001,
        "minSize": 50,
        "priceScale": 2
    }
}


Return ValueDescription
priceScaleDecimal Places of Price
minAmountMinimum transaction amount in transaction currency
minSizeMinimum transaction quantity in pricing currency
amountScaleDecimal Places of Amount

Market

Get allTicker data

Get all coin data

Request Sample


// request demo
GET https://api.zb.com/data/v1/allTicker



// java demo
public void getAllTicker() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/allTicker").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getAllTicker(self, market):
    url = 'https://api.zb.com/data/v1/allTicker'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "hpybtc":{
		"vol":"19800.6",
		"last":"0.00000237",
		"sell":"0.000002366",
		"buy":"0.00000236",
		"high":"0.0000026552",
		"low":"0.00000229"
       "open": "0.31"
       "riseRate": "4.81"
	},
	"tvqc":{
		"vol":"2201510.1",
		......
}


Return ValueDescription
highHigh Price
lowLow Price
buyBuy 1
sellSell 1
lastLast Price
openOpening price
riseRate24H change
vol24H Volume

Get ticker data

Get a single coin's market

Request Sample


// request demo
GET https://api.zb.com/data/v1/ticker?market=btc_usdt



// java demo
public void getTicker() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/ticker?market=btc_usdt").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getTicker(self, market):
    url = 'https://api.zb.com/data/v1/ticker?market=btc_usdt'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "ticker": {
        "vol": "40.463", 
        "last": "0.899999", 
        "sell": "0.5",
        "buy": "0.225", 
        "high": "0.899999", 
        "low": "0.081"
        "open": "0.31"
        "riseRate": "4.81"
    }, 
    "date": "1507875747359"
}


Parameter NameTypeValue Range
marketStringSample:btc_qc

Return ValueDescription
highHigh Price
lowLow Price
buyBuy 1
sellSell 1
lastLast Price
openOpening price
riseRate24H change
vol24H Volume

Get Market Depth

Request Sample


// request demo
GET https://api.zb.com/data/v1/depth?market=btc_usdt&size=3



// java demo
public void getDepth() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/depth?market=btc_usdt&size=3").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getDepth(self, market):
    url = 'https://api.zb.com/data/v1/depth?market=btc_usdt&size=3'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "asks": [
        [
            83.28,
            11.8
        ]...
    ],
    "bids": [
        [
            81.91,
            3.65
        ]...
    ],
    "timestamp" : Timestamp
}


Parameter NameTypeValue Range
marketStringSample:btc_qc
sizeintPosition range is from 1 to 50, if there is combine depth, it only return 5 positions.
mergefloatDefault Depth

Return ValueDescription
asksSell Order Depth
bidsBuy Order Depth
timestampThe timestamp generated by

Get Historical Orders

Request Sample


// request demo
GET https://api.zb.com/data/v1/trades?market=btc_usdt



// java demo
public void getTrades() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/trades?market=btc_usdt").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getTrades(self, market):
    url = 'https://api.zb.com/data/v1/trades?market=btc_usdt'
    return self.get(url)


Request Reply Sample


// Return Result
[
    {
        "amount": 0.541,
        "date": 1472711925,
        "price": 81.87,
        "tid": 16497097,
        "trade_type": "ask",
        "type": "sell"
    }...
]


Parameter NameTypeValue Range
marketStringSample:btc_qc
sincelong50 data after the specified transaction ID

Return ValueDescription
dateTransaction Time(stempel waktu)
pricePrice
amountAmount
tidGenerate transactionID
trade_typeOrder Type: ask and bidID
typeTrading Type: buy and sellID

GetKLine

Get K-line data up to the latest 1000 data

Request Sample


// request demo
GET https://api.zb.com/data/v1/kline?market=btc_usdt



// java demo
public void getKline() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/kline?market=btc_usdt").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getKline(self, market):
    url = 'https://api.zb.com/data/v1/kline?market=btc_usdt'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "data": [
        [
            1472107500000,
            3840.46,
            3843.56,
            3839.58,
            3843.3,
            492.456
        ]...
    ],
    "moneyType": "USDT",
    "symbol": "BTC"
}


Parameter NameTypeValue Range
marketStringSample:btc_qc
typeString1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
sincelongAfter this timestamp
sizeintLimit of returning data(default 1000, it only returns 1000 data if there are more than 1000 data)

Return ValueDescription
dataK-line Content
1472107500000Timestamp
3840.46Open
3843.56High
3839.58Low
3843.3Close
492.456Volume
moneyTypeBuy
symbolSell

Funds

Get User Info

Request Sample


// request demo
GET https://trade.zb.com/api/getAccountInfo?accesskey=youraccesskey&method=getAccountInfo&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getAccountInfo() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo";
	//sign encrypted by HmacMD5 and get:25d7c24e7a3640d7d82f834976053bc9
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getAccountInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo&reqTime=1539942325894&sign=25d7c24e7a3640d7d82f834976053bc9";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getAccountInfo(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getAccountInfo'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo'
        params = 'accesskey=' + self._access_key_ + '&method=getAccountInfo'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 25d7c24e7a3640d7d82f834976053bc9
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getAccountInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo&reqTime=1540295995373&sign=25d7c24e7a3640d7d82f834976053bc9
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "result": {
        "coins": [
            {
                "enName": "ZB", 
                "freez": "0.00000000", 
                "fundstype": 51, 
                "unitDecimal": 8, 
                "cnName": "ZB", 
                "isCanRecharge": true, 
                "unitTag": "ZB", 
                "isCanWithdraw": true, 
                "available": "0.00361064", 
                "canLoan": false, 
                "key": "zb"
            }, 
            ...
        ], 
        "base": {
            "username": "lianlianyi", 
            "trade_password_enabled": true, 
            "auth_google_enabled": true, 
            "auth_mobile_enabled": true
        }
    }, 
    "assetPerm": true, 
    "leverPerm": true, 
    "entrustPerm": true, 
    "moneyPerm": true
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetAccountInfo
accesskeyStringaccesskey
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
auth_google_enabledWhether or not enable Google Authentication
auth_mobile_enabledWhether or not enable Phone Authentication
trade_password_enabledWhether or not enable transaction password
usernameUsername
keyCoin
enameCoin's English Name
cnNameCoin's Chinese Name
showNameUse the new name if it is renamed,otherwise use ename
unitTagCoin Symbol
isCanRechargeIs it available to deposit
isCanWithdrawIs it available to withdraw
canLoanIs it available to invest
Permission
leverPermMargin:Investment Management、Lending Management
assetPermInquiry Assets:Inquiry account info and assets
entrustPermEntrust Trade:Entrust、Cancel、Inquiry Trade Orders
moneyPermDeposit and Withdrawal:Get Deposit、Deposit address and record,Send Withdrawal Request

Get spot bill

Request Sample


// request demo
GET https://trade.zb.com/api/getSpotBills?accesskey=youraccesskey&currency=zb&method=getSpotBills&startDate=2022-01-28 00:00:00&endDate=2022-03-28 00:00:00&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds

Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": "success",
    "result": [{,
       "balance": "1000 USDT",
       "changeAmount": "+10 USDT",
       "currencyName": "USDT",
       "date": 1641784657000,
       "id": 102300,
       "remark": "",
       "showDate": "2022-01-10 11:00:00",
       "total": "10 USDT",
       "typeDesc": "",
    "},...]"
}

Parameter NameTypeIs it necessaryValue Range
methodStringyesDirect Assignment getSpotBills
accesskeyStringyesaccesskey
currencyStringnoCoin Name
startDateStringnostart time
endDateStringnoend time
dataTypeStringno0: <= 48h; 1: > 48h
pageIndexStringnoDefault to 1
pageSizeStringnoDefault to 10,(10 ~ 50)

Return ValueDescription
codeReturn Code
messageHints
balanceBalance
changeAmountChangesCOINAmount
currencyNameCoin Name
datedate
idID
remarkRemark
showDatetime
totalBalance
typeDescType of Records

Get deposit address

You need to go to app or web to get the address first

Request Sample


// request demo
GET https://trade.zb.com/api/getUserAddress?accesskey=youraccesskey&currency=btc&method=getUserAddress&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getUserAddress() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getUserAddress";
	//sign encrypted by HmacMD5 and get:0eea9a3d1d1665d6727ca9b1286bef98
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getUserAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getUserAddress&reqTime=1539942326056&sign=0eea9a3d1d1665d6727ca9b1286bef98";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getUserAddress(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getUserAddress'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getUserAddress'
        params = 'accesskey=' + self._access_key_ + '&currency=bch&method=getUserAddress'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0eea9a3d1d1665d6727ca9b1286bef98
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getUserAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getUserAddress&reqTime=1540295995534&sign=0eea9a3d1d1665d6727ca9b1286bef98
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
        }
    }
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetUserAddress
accesskeyStringaccesskey
currencyStringCoin
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
keyAddress

Get multiple chain deposit address

Request Sample


// request demo
GET https://trade.zb.com/api/getPayinAddress?accesskey=youraccesskey&currency=usdt&method=getPayinAddress&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getPayinAddress() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=usdt&method=getPayinAddress";
	//sign encrypted by HmacMD5 and get:393e455ac4343996db43219a38253631
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getPayinAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=usdt&method=getPayinAddress&reqTime=1560956360295&sign=393e455ac4343996db43219a38253631
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getPayinAddress(self, market):
        MyUrl = 'https://trade.zb.com/api/getPayinAddress'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=usdt&method=getPayinAddress'
        params = 'accesskey=' + self._access_key_ + '&currency=usdt&method=getPayinAddress'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 393e455ac4343996db43219a38253631
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getPayinAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=usdt&method=getPayinAddress&reqTime=1560956360295&sign=393e455ac4343996db43219a38253631
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": [
        	{
        		"blockChain": "btc",
        		"isUseMemo": false,
        		"address": "1LL5ati6pXHZnTGzHSA3rWdqi4mGGXudwM",
        		"canWithdraw": true,
        		"canDeposit": true
        	},
        	{
        		"blockChain": "bts",
        		"isUseMemo": true,
        		"account": "btstest",
        		"memo": "123",
        		"canWithdraw": true,
        		"canDeposit": true
        	},
        ]
    }
}

Parameter NameTypeValue Range
methodStringDirect AssignmentgetPayinAddress
accesskeyStringaccesskey
currencyStringCoin
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
blockChainBlock
canDepositWhether to deposit
canWithdrawWhether to withdrawal
isUseMemoWhether to use memo or tag. When it is 'true', the deposit information uses 'account+memo', otherwise uses address
addressDeposit address, when isUseMemo=false
accountAccount, when isUseMemo=true
memomemo or tag, when isUseMemo=true

Get withdrawal address

Get user's verified withdrawal address

Request Sample


// request demo
GET https://trade.zb.com/api/getWithdrawAddress?accesskey=youraccesskey&currency=btc&method=getWithdrawAddress&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getWithdrawAddress() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getWithdrawAddress";
	//sign encrypted by HmacMD5 and get:a23945f53b24c404e51d6ced99fea633
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getWithdrawAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getWithdrawAddress&reqTime=1539942326058&sign=a23945f53b24c404e51d6ced99fea633";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getWithdrawAddress(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getWithdrawAddress'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getWithdrawAddress'
        params = 'accesskey=' + self._access_key_ + '&currency=btc&method=getWithdrawAddress'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a23945f53b24c404e51d6ced99fea633
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getWithdrawAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=btc&method=getWithdrawAddress&reqTime=1540295995538&sign=a23945f53b24c404e51d6ced99fea633
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
        }
    }
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetWithdrawAddress
accesskeyStringaccesskey
currencyStringCoin
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
keyAddress

Get withdrawal records

Request Sample


// request demo
GET https://trade.zb.com/api/getWithdrawRecord?accesskey=youraccesskey&currency=eth&method=getWithdrawRecord&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getWithdrawRecord() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:f5eb60290d3a0ce6e2e546e562f59aff
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getWithdrawRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10&reqTime=1539942326065&sign=f5eb60290d3a0ce6e2e546e562f59aff";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getWithdrawRecord(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getWithdrawRecord'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&currency=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = f5eb60290d3a0ce6e2e546e562f59aff
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getWithdrawRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10&reqTime=1540295995549&sign=f5eb60290d3a0ce6e2e546e562f59aff
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "list": [
                {
                    "amount": 0.01,
                    "fees": 0.001,
                    "id": 2016042556231,
                    "manageTime": 1461579340000,
                    "status": 3,
                    "submitTime": 1461579288000,
                    "toAddress": "14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp"
                    "merchantOrderNo": "2021051912283100022694489"
                    "hash": "eb40b5787eb32e7d685555c16ecbc85d1c476736e07daa6468715d737d1fc5bd"
                }...
            ],
            "pageIndex": 1,
            "pageSize": 10,
            "totalCount": 4,
            "totalPage": 1
        }
    }
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetWithdrawRecord
accesskeyStringaccesskey
currencyStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
amountWithdrawal Amount
feesNetwork Fee
idWithdrawal Recordid
manageTimeTimestamp for withdrawal processing time
statusWithdrawal Status(0Submit,1Fail,2Success,3Cancel,5Confirmed)
submitTimeTimestamp for withdrawal submit time
toAddressReceiving Address
merchantOrderNoMerchant order number
hash提现交易号

Get deposit records

Request Sample


// request demo
GET https://trade.zb.com/api/getChargeRecord?accesskey=youraccesskey&currency=btc&method=getChargeRecord&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getChargeRecord() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getChargeRecord&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:e871dcce5138334704165ee53efe5545
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getChargeRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getChargeRecord&pageIndex=1&pageSize=10&reqTime=1539942326084&sign=e871dcce5138334704165ee53efe5545";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getChargeRecord(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getChargeRecord'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getChargeRecord&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&currency=bch&method=getChargeRecord&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = e871dcce5138334704165ee53efe5545
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getChargeRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch&method=getChargeRecord&pageIndex=1&pageSize=10&reqTime=1540295995596&sign=e871dcce5138334704165ee53efe5545
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "list": [
                {
                    "address": "1FKN1DZqCm8HaTujDioRL2Aezdh7Qj7xxx",
                    "amount": "1.00000000",
                    "confirmTimes": 1,
                    "currency": "BTC",
                    "description": "Successfully Confirm",
                    "hash": "7ce842de187c379abafadd64a5fe66c5c61c8a21fb04edff9532234a1dae6xxx",
                    "id": 558,
                    "itransfer": 1,
                    "status": 2,
                    "submit_time": "2016-12-07 18:51:57"
                }...
            ],
            "pageIndex": 1,
            "pageSize": 10,
            "total": 8
        }
    }
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetChargeRecord
accesskeyStringaccesskey
currencyStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
amountDeposit Amount
confirmTimesDeposit Confirmations
currencyDeposit Coin Type(Upper case)
descriptionDescription of deposit record status
hashDeposit ID
idDeposit Recordsid
itransferWhether internal transfer,1Yes0No
statusStatus(0Pending Confirm,1Fail to deposit,2Deposit Success)
submit_timeDeposit Time
addressDeposit Address

Get withdrawal fees

Request Sample


// request demo
GET https://trade.zb.com/api/getFeeInfo?currency=btc


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": success
    "result": {
        "USDT": [
           {
               "chainName": "BTC"
               "fee": 0.001
               "mainChainName": "BTC"
               "canDeposit": true
               "canWithdraw": true
           }
           ...
        ]
    }
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetFeeInfo
currencyStringCoin
Return ValueDescription
chainNameBlockchain
feeWithdrawal fees
mainChainNamemainChainName
canDepositCan recharge
canWithdrawCan withdraw

Withdrawal

Request Sample


// request demo
GET https://trade.zb.com/api/withdraw?accesskey=youraccesskey&amount=0.0004&currency=etc&fees=0.0003⁢ransfer=0&method=withdraw&receiveAddr=14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp&safePwd=Transaction Password&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void withdraw() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=Addressstring&safePwd=123456bb";
	//sign encrypted by HmacMD5 and get:a2d96def2e570e2f0567fe2c0ee73d78
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/withdraw?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=%E5%9C%B0%E5%9D%80string&reqTime=1539942326067&safePwd=123456bb&sign=a2d96def2e570e2f0567fe2c0ee73d78";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def withdraw(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/withdraw'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=Addressstring&safePwd=123456bb'
        params = 'accesskey=' + self._access_key_ + '&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=Addressstring&safePwd=123456bb'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a2d96def2e570e2f0567fe2c0ee73d78
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/withdraw?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=%E5%9C%B0%E5%9D%80string&reqTime=1540295995554&safePwd=123456bb&sign=a2d96def2e570e2f0567fe2c0ee73d78
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": "success",
    "id": "Withdrawal Recordid"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
amountfloatWithdrawal Amount
currencyStringCoin
feesfloatNetwork Fee
itransferintAgree or not?bitbankInternal transfer(0Disagree,1Agree,Default Disagree)
methodStringDirect Assignmentwithdraw
receiveAddrStringReceiving Address(It needs to be the verified address,btsif it's,use"account_Remark"format)
safePwdStringTransaction Password
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idWithdrawal Recordid

Trade

Place Order

Spot trade and margin trade share this interface, which is distinguished by the parameter acctType

Request Sample


// request demo
GET https://trade.zb.com/api/order?accesskey=youraccesskey&acctType=0&amount=1.502&currency=qtum_usdt&method=order&price=1.9001&tradeType=1&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void order() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001&currency=zb_qc&method=order&price=1.0&tradeType=1";
	//signEncrypted by HmacMD5 and get:a0f18f0f1007433d905272c4c40560b2
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/order?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001&currency=zb_qc&method=order&price=1.0&reqTime=1539942326046&sign=a0f18f0f1007433d905272c4c40560b2&tradeType=1";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) &lt; 1:
            raise Exception("Get markets status failed")

    def order(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/order'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001&currency=zb_qc&method=order&price=1.0&tradeType=1'
        params = 'accesskey=' + self._access_key_ + '&acctType=0&amount=0.001&currency=zb_qc&method=order&price=1.0&tradeType=1'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a0f18f0f1007433d905272c4c40560b2
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/order?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001&currency=zb_qc&method=order&price=1.0&reqTime=1540295995514&sign=a0f18f0f1007433d905272c4c40560b2&tradeType=1
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。",
    "id": "20131228361867"
}


Parameter NameTypeValue Range
methodStringDirect Assignmentorder
accesskeyStringaccesskey
acctTypeintMargin 0/1/2[Spot/Isolated/Cross](Optional,Default to: 0 Spot)
enableExpressintAutomatic currency borrowing true/false(Optional,Default to: false)
enableRepayintAutomatically Repay true/false(Optional,Default to: false)
amountfloatAmount
currencyStringTransaction Coin/Pricing Coin
customerOrderIdStringCustom ID(Optional,4-36 characters, numbers or letters. Cancellation order can replace the order ID. If there is a duplicate, the order can only be canceled or the latest data can be found when canceling the order and querying the order.)
orderTypeintorder type1/2[PostOnly/IOC]Optional, empty or other limit orders
pricefloatPrice
tradeTypeintType1/0[buy/sell]
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idEntrusted order No.

Batch Entrust Order

Spot trade and margin trade share this interface, which is distinguished by the parameter acctType

Request Sample


// request demo
GET https://trade.zb.com/api/orderMoreV2?accesskey=youraccesskey&acctType=0&tradeParams=[[2,1],[2.2,1]]&market=zb_qc&method=orderMoreV2&tradeType=1&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void orderMoreV2() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=1&market=eth_usdt&method=orderMoreV2&tradeParams=[[2,1],[2.2,1]]&tradeType=1";
	//signEncrypted by HmacMD5 and get:6dde6176052204af2b2ea3df495c21b0
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/orderMoreV2&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=1&market=eth_usdt&method=orderMoreV2&reqTime=1560950545558&sign=6dde6176052204af2b2ea3df495c21b0&tradeParams=[[2,1],[2.2,1]]&tradeType=1";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) &lt; 1:
            raise Exception("Get markets status failed")

    def orderMoreV2(self, market, type, tradeParams):
        MyUrl = 'https://trade.zb.com/api/orderMoreV2'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=1&market=eth_usdt&method=orderMoreV2&tradeParams=[[2,1],[2.2,1]]&tradeType=1'
        params = 'accesskey=' + self._access_key_ + '&acctType=1&market=eth_usdt&method=orderMoreV2&tradeParams=[[2,1],[2.2,1]]&tradeType=1'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 6dde6176052204af2b2ea3df495c21b0
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/orderMoreV2&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=1&market=eth_usdt&method=orderMoreV2&reqTime=1560950545558&sign=6dde6176052204af2b2ea3df495c21b0&tradeParams=[[2,1],[2.2,1]]&tradeType=1
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。",
    "data": [201902281619801,201902281619802]
}


Parameter NameTypeValue Range
methodStringDirect AssignmentorderMoreV2
accesskeyStringaccesskey
marketStringTransaction Coin/Pricing Coin
tradeParamsStringTrade parameter, array format [[price, Amount],[price, Amount]], up to 20
tradeTypeintType1/0[buy/sell]
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds
acctTypeintMargin 0/1/2[Spot/Isolated/Cross](Optional,Default to: 0 Spot)

Return ValueDescription
codeReturn Code
messageHints
dataOrder Number id array

Cancel Order

Request Sample


// request demo
GET https://trade.zb.com/api/cancelOrder?accesskey=youraccesskey&currency=zb_qc&id=201710111625&method=cancelOrder&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void cancelOrder() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=cancelOrder";
	//sign encrypted by HmacMD5 and get:a435f4bddfedb50877587ae1acff1c35
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/cancelOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=cancelOrder&reqTime=1539942326052&sign=a435f4bddfedb50877587ae1acff1c35";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def cancelOrder(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/cancelOrder'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=cancelOrder'
        params = 'accesskey=' + self._access_key_ + '&currency=zb_qc&id=20180522105585216&method=cancelOrder'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a435f4bddfedb50877587ae1acff1c35
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/cancelOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=cancelOrder&reqTime=1540295995526&sign=a435f4bddfedb50877587ae1acff1c35
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": "{"
       "des": "Success",
       "isSuc": true,
       "datas": "{"
           "amount": 10.00,
           "price": 12.00,
           "completeMonty": 24.00,
           "completeAmount": 2.00,
       "}"
   "}"
}


Parameter NameTypeValue Range
methodStringDirect AssignmentcancelOrder
accesskeyStringaccesskey
currencyStringTransaction Coin/Pricing Coin
idlongEntrusted order No.
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds
customerOrderIdStringCustom ID(4-36 characters, numbers or letters, only one of customer OrderId and id can be filled in)

Return ValueDescription
codeReturn Code
messageHints
amountOrder Amount
pricePrice
completeMontyTrading Volume
completeAmountTrading Amount

Cancel the delegation regularly

Cancel the delegation after one minute and access the refresh time again

Request Sample


// request demo
GET https://trade.zb.com/api/cancelAllOrdersAfter?accesskey=youraccesskey&currency=zb_qc&method=cancelAllOrdersAfter&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds

Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": "Success"
}

Parameter NameTypeValue Range
methodStringDirect Assignment cancelAllOrdersAfter
accesskeyStringaccesskey
currencyStringTransaction Coin/Pricing Coin

Return ValueDescription
codeReturn Code
messageHints

Get Entrusted Order

Get single buy order or sell order

Request Sample


// request demo
GET https://trade.zb.com/api/getOrder?accesskey=youraccesskey&currency=zb_qc&id=201710122805&method=getOrder&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getOrder() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=getOrder";
	//sign encrypted by HmacMD5 and get:c25289ab4f1f7027b6aaf83b7bd5c50b
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=getOrder&reqTime=1539942326049&sign=c25289ab4f1f7027b6aaf83b7bd5c50b";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getOrder(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getOrder'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=getOrder'
        params = 'accesskey=' + self._access_key_ + '&currency=zb_qc&id=20180522105585216&method=getOrder'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = c25289ab4f1f7027b6aaf83b7bd5c50b
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&id=20180522105585216&method=getOrder&reqTime=1540295995519&sign=c25289ab4f1f7027b6aaf83b7bd5c50b
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "currency": "btc_usdt",
    "id": "20150928158614292",
    "price": 1560,
    "status": 3,
    "total_amount": 0.1,
    "trade_amount": 0,
    "trade_date": 1443410396717,
    "trade_money": 0,
    "type": 0,
    "fees": "0.03",
    "useZbFee": true
}


Parameter NameTypeValue Range
methodStringDirect AssignmentgetOrder
accesskeyStringaccesskey
idlongEntrusted order No.
currencyStringTransaction Coin/Pricing Coin
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds
customerOrderIdStringCustom ID(4-36 characters, numbers or letters, only one of customer OrderId and id can be filled in)

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee

Get Multiple Entrust Orders

Get multiple entrust buy orders or sell orders, every request returns 10 records

Request Sample


// request demo
GET https://trade.zb.com/api/getOrders?accesskey=youraccesskey&currency=zb_qc&method=getOrders&pageIndex=1&tradeType=1&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getOrders() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getOrders&pageIndex=1&tradeType=1";
	//sign encrypted by HmacMD5 and get:083d58360afd1da87c85ac2037aa0f4f
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getOrders?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getOrders&pageIndex=1&reqTime=1539942326060&sign=083d58360afd1da87c85ac2037aa0f4f&tradeType=1";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getOrders(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getOrders'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getOrders&pageIndex=1&tradeType=1'
        params = 'accesskey=' + self._access_key_ + '&currency=zb_qc&method=getOrders&pageIndex=1&tradeType=1'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 083d58360afd1da87c85ac2037aa0f4f
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getOrders?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getOrders&pageIndex=1&reqTime=1540295995542&sign=083d58360afd1da87c85ac2037aa0f4f&tradeType=1
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
[
    {
        "currency": "btc_usdt",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0,
        "fees": "0.03",
        "useZbFee": true
    }...
]


Parameter NameTypeValue Range
methodStringDirect AssignmentgetOrders
accesskeyStringaccesskey
tradeTypeintType1/0[buy/sell]
currencyStringTransaction Coin/Pricing Coin
pageIndexintCurrent Page(Such as: 1, page 1)
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee

Get entrust order ignore type

Cancel the field filter of tradeType to get both buy orders and sell orders, returning 10 pageSize records per request

Request Sample


// request demo
GET https://trade.zb.com/api/getOrdersIgnoreTradeType?accesskey=youraccesskey&currency=zb_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=1&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getOrdersIgnoreTradeType() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:035c3a682574790044dc7aa4cffa0259
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getOrdersIgnoreTradeType?method=getOrdersIgnoreTradeType&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&pageIndex=1&pageSize=10&sign=035c3a682574790044dc7aa4cffa0259&reqTime=1539942326054";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getOrdersIgnoreTradeType(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getOrdersIgnoreTradeType'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=bch_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&currency=bch_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 035c3a682574790044dc7aa4cffa0259
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getOrdersIgnoreTradeType?method=getOrdersIgnoreTradeType&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&pageIndex=1&pageSize=10&sign=035c3a682574790044dc7aa4cffa0259&amp;reqTime=1540295995530
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
[
    {
        "currency": "btc_usdt",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0,
        "fees": "0.03",
        "useZbFee": true
    }...
]


Parameter NameTypeValue Range
methodStringDirect AssignmentgetOrdersIgnoreTradeType
accesskeyStringaccesskey
currencyStringTransaction Coin/Pricing Coin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee

Undone or partial done orders

Get undone or partial done buy orders and sell orders, returning less than 10 pageSize records per request

Request Sample


// request demo
GET https://trade.zb.com/api/getUnfinishedOrdersIgnoreTradeType?accesskey=youraccesskey&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getUnfinishedOrdersIgnoreTradeType() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:8007befda9d8903ea5e17601ea78bd94
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getUnfinishedOrdersIgnoreTradeType?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10&reqTime=1539942326063&sign=8007befda9d8903ea5e17601ea78bd94";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getUnfinishedOrdersIgnoreTradeType(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getUnfinishedOrdersIgnoreTradeType'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 8007befda9d8903ea5e17601ea78bd94
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getUnfinishedOrdersIgnoreTradeType?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&currency=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10&reqTime=1540295995546&sign=8007befda9d8903ea5e17601ea78bd94
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
[
    {
        "currency": "btc_usdt",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0,
        "fees": "0.03",
        "useZbFee": true
    }...
]


Parameter NameTypeValue Range
methodStringDirect AssignmentgetUnfinishedOrdersIgnoreTradeType
accesskeyStringaccesskey
currencyStringTransaction Coin/Pricing Coin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ))
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee

Interface for querying completed or partial transactions

Request Sample


// request demo
GET https://trade.zb.com/api/getFinishedAndPartialOrders?accesskey=youraccesskey&currency=btc_usdt&method=getFinishedAndPartialOrders&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


Request Reply Sample


// Return Result
[
    {
        "currency": "btc_usdt",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0,
        "fees": "0.03",
        "useZbFee": true
    }...
]


Parameter NameTypeValue Range
methodStringDirect AssignmentgetFinishedAndPartialOrders
accesskeyStringaccesskey
currencyStringTransaction Coin/Pricing Coin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ))
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee

Sub-account

Create Sub-account

Request Sample


// request demo
GET https://trade.zb.com/api/addSubUser?accesskey=youraccesskey&memo=xxx&password=xxxx&method=addSubUser⊂UserName=xxxxx&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void addSubUser() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457⊂UserName=test33";
	//sign encrypted by HmacMD5 and get:9f8018b8ca1dd4fba833a1fc51b81768
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/addSubUser?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457&reqTime=1539942326088&sign=9f8018b8ca1dd4fba833a1fc51b81768⊂UserName=test33";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def addSubUser(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/addSubUser'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457⊂UserName=test33'
        params = 'accesskey=' + self._access_key_ + '&memo=hah&method=addSubUser&password=pass123457⊂UserName=test33'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 9f8018b8ca1dd4fba833a1fc51b81768
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/addSubUser?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457&reqTime=1540295995605&sign=9f8018b8ca1dd4fba833a1fc51b81768⊂UserName=test33
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {}
    }
}


Parameter NameTypeValue Range
memoStringRemark
passwordStringPassword
subUserNameStringSub-account Username(not more than6 digits or letters)
accesskeyStringaccesskey
reqTimeLongCurrent time in milliseconds
signStringSignature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not

Get Sub-account List

Request Sample


// request demo
GET https://trade.zb.com/api/getSubUserList?accesskey=youraccesskey&method=getSubUserList&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getSubUserList() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList";
	//sign encrypted by HmacMD5 and get:2abacfab6ecb27144b798f36e1d8443c
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getSubUserList?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList&reqTime=1539942326091&sign=2abacfab6ecb27144b798f36e1d8443c";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getSubUserList(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getSubUserList'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList'
        params = 'accesskey=' + self._access_key_ + '&method=getSubUserList'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 2abacfab6ecb27144b798f36e1d8443c
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getSubUserList?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList&reqTime=1540295995611&sign=2abacfab6ecb27144b798f36e1d8443c
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
  "code": 1000,
  "message": "Success",
  "result": [
    {
      "isOpenApi": false,
      "memo": "1",
      "userName": "xxxx@1",
      "userId": 123456,
      "isFreez": false
    },
    {
      "isOpenApi": false,
      "memo": "2",
      "userName": "xxxx@2",
      "userId": 132456,
      "isFreez": false
    }
  ]
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
reqTimeLongCurrent time in milliseconds
signStringSignature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not
isOpenApiEnable or notAPI
userNameUsername
isFreezFreeze or not
memoRemark

Internal transfer between main account and sub-account

Request Sample


// request demo
https://trade.zb.com/api/doTransferFunds?accesskey=youraccesskey&method=doTransferFunds&amount=1&currency=xx&fromUserName=xx&toUserName=xxxx&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void doTransferFunds() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&[email protected]&method=doTransferFunds&toUserName=lianlianyi@test12";
	//sign encrypted by HmacMD5 and get:0d109b7d008c924041d10cf5706b2fce
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/doTransferFunds?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&fromUserName=lianlianyi%40vip.qq.com&method=doTransferFunds&reqTime=1539942326092&sign=0d109b7d008c924041d10cf5706b2fce&toUserName=lianlianyi%40test12";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def doTransferFunds(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/doTransferFunds'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&[email protected]&method=doTransferFunds&toUserName=lianlianyi@test12'
        params = 'accesskey=' + self._access_key_ + '&amount=1&currency=doge&[email protected]&method=doTransferFunds&toUserName=lianlianyi@test12'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0d109b7d008c924041d10cf5706b2fce
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/doTransferFunds?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&fromUserName=lianlianyi%40vip.qq.com&method=doTransferFunds&reqTime=1540295995614&sign=0d109b7d008c924041d10cf5706b2fce&toUserName=lianlianyi%40test12
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
  "code": 1000,
  "message": "Success",
  "result": []
}


Parameter NameTypeValue Range
amountDoubleAmount
currencyStringCoin
fromUserNameStringTransferor Username
toUserNameStringReceiver Username
accesskeyStringaccesskey
reqTimeLongCurrent time in milliseconds
signStringSignature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not

Isolated

Obtain isolated information

Request Sample


// request demo
GET https://trade.zb.com/api/getLeverAssetsInfo?accesskey=youraccesskey&method=getLeverAssetsInfo&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getLeverAssetsInfo() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo";
	//sign encrypted by HmacMD5 and get:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getLeverAssetsInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo&reqTime=1539942326068&sign=0cc8a3b79dabfac0c28229dd3871862d";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getLeverAssetsInfo(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getLeverAssetsInfo'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo'
        params = 'accesskey=' + self._access_key_ + '&method=getLeverAssetsInfo'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0cc8a3b79dabfac0c28229dd3871862d
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getLeverAssetsInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo&reqTime=1540295995557&sign=0cc8a3b79dabfac0c28229dd3871862d
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000, 
    "message": {
        "des": "success", 
        "isSuc": true, 
        "datas": {
            "levers": [
                {
                    "fLoanIn": 0, 
                    "repayLevel": 0, 
                    "cUnitTag": "XRP", 
                    "unwindPrice": 0, 
                    "fUnitDecimal": 8, 
                    "repayLock": false, 
                    "cLoanIn": 0, 
                    "cEnName": "XRP", 
                    "cAvailable": 0, 
                    "fAvailable": 0, 
                    "cLoanOut": 0, 
                    "cCanLoanIn": 0, 
                    "fLoanOut": 0, 
                    "level": 0, 
                    "fFreeze": 0, 
                    "fEnName": "BTC", 
                    "cFreeze": 0, 
                    "fCanLoanIn": 0, 
                    "cUnitDecimal": 8, 
                    "cOverdraft": 0, 
                    "key": "xrpbtc", 
                    "repayLeverShow": "-"
                }
            ]
        }
    }
}


Parameter NameTypeValue Range
methodStringDirect Assignment getLeverAssetsInfo
accesskeyStringaccesskey
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not
keyMarket Name
fshowNameUse the new name if it is renamed,otherwise use fname
cshowNameUse the new name if it is renamed,otherwise use cname
showNameUse the new trading pair name if it is renamed,otherwise use key
fLoanInBorrowing amount of French currency
repayLevelLiquidation Level
unwindPriceLiquidation Price
fUnitDecimalDecimal Point
repayLockWhether is locked for the outstanding payment
cLoanInBorrow Amount
cAvailableAvailable Coin
fAvailableAvailable Fiat Currency
cLoanOutLend Amount
cCanLoanInAvailable for borrowing
fLoanOutAvailable for lending
levelMargin Level
fFreezeFrozen Fiat Currency
cFreezeFrozen Coin
fCanLoanInAvailable fiat currency for borrowing
cUnitDecimalCoin's decimal point
cOverdraftOverdue Interest
repayLeverShowLiquidation Risk

Get isolated bills

Request Sample


// request demo
GET https://trade.zb.com/api/getLeverBills?accesskey=youraccesskey&coin=qc&method=getLeverBills&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getLeverBills() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:2473a00d93feed72583365e3cb90f391
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getLeverBills?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10&reqTime=1539942326070&sign=2473a00d93feed72583365e3cb90f391";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getLeverBills(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getLeverBills'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 2473a00d93feed72583365e3cb90f391
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getLeverBills?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10&reqTime=1540295995560&sign=2473a00d93feed72583365e3cb90f391
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success。",
	"result"            : [
		{
			"changeCoin"    : 500.00000000,
			"showCoin"      : "+500.000=500.000LTC",
			"type"          : 1,
			"date"          : 1522668146000,
			"database"      : "default",
			"dataName"      : "baseBean",
			"fundsType"     : 3,
			"billTypeValue" : "LTCDeposit",
			"id"            : 609,
			"downTableDate" : 1520092800000,
			"marketName"    : "ltcusdt",
			"avgPrice"      : 0,
			"userId"        : 110803,
			"coinBalance"   : 500.00000000,
			"entrustId"     : 0
		}
	]
}


Parameter NameTypeValue Range
methodStringDirect Assignment getLeverBills
accesskeyStringaccesskey
coinStringCoin
dataTypeintData Type[0/1](Data in 30 days/Data over 30 days)
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idRecordsID
userIdUserID
dateRecords generate time
typeType of Records
billTypeValueRecords Type in Chinese
changeCoinChangesCOINAmount
coinBalanceChangedCOINBalance
changeFiatThe changed fiat currency amount
fiatBalanceFiat currency balance
fundsTypeCOINType
marketNameMarket Name
showCoinShowCOINChange
showFiatShow the change of fiat currency

Assets transferred into isolated

Request Sample


// request demo
GET https://trade.zb.com/api/transferInLever?accesskey=youraccesskey&amount=100&coin=qc&marketName=btsqc&method=transferInLever&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void transferInLever() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever";
	//sign encrypted by HmacMD5 and get:a8fe8d3e01143e83491e5df69f288fd4
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/transferInLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever&reqTime=1539942326071&sign=a8fe8d3e01143e83491e5df69f288fd4";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def transferInLever(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/transferInLever'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever'
        params = 'accesskey=' + self._access_key_ + '&amount=1&coin=qc&marketName=btsqc&method=transferInLever'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a8fe8d3e01143e83491e5df69f288fd4
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/transferInLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever&reqTime=1540295995563&sign=a8fe8d3e01143e83491e5df69f288fd4
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment transferInLever
accesskeyStringaccesskey
coinStringCoin
marketNameStringMarket Name
amountdoubleTransfer-in Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Assets transferred out of isolated

Request Sample


// request demo
GET https://trade.zb.com/api/transferOutLever?accesskey=youraccesskey&amount=100&coin=qc&marketName=btsqc&method=transferOutLever&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void transferOutLever() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever";
	//sign encrypted by HmacMD5 and get:d7dcb17e6271232862812c339611d17e
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/transferOutLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever&reqTime=1539942326073&sign=d7dcb17e6271232862812c339611d17e";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def transferOutLever(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/transferOutLever'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever'
        params = 'accesskey=' + self._access_key_ + '&amount=1&coin=qc&marketName=btsqc&method=transferOutLever'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = d7dcb17e6271232862812c339611d17e
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/transferOutLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever&reqTime=1540295995566&sign=d7dcb17e6271232862812c339611d17e
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment transferOutLever
accesskeyStringaccesskey
coinStringCoin
marketNameStringMarket Name
amountdoubleTransfer-out Amount,The decimal places cannot exceed8,Exceed the system automatically intercepts8Bit
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Release Investment

Request Sample


// request demo
GET https://trade.zb.com/api/loan?accesskey=youraccesskey&amount=100&coin=qc&interestRateOfDay=0.1&isLoop=1&method=loan&repaymentDay=20&safePwd=Transaction Password&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void loan() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10";
	//sign encrypted by HmacMD5 and get:0237aa2fd02b155142a1915c8589b2b1
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/loan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10&reqTime=1539942326074&sign=0237aa2fd02b155142a1915c8589b2b1";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def loan(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/loan'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10'
        params = 'accesskey=' + self._access_key_ + '&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0237aa2fd02b155142a1915c8589b2b1
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/loan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10&reqTime=1540295995569&sign=0237aa2fd02b155142a1915c8589b2b1
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。",
    "id": "97"
}


Parameter NameTypeValue Range
methodStringDirect Assignment loan
accesskeyStringaccesskey
coinStringCoin
amountdoubleInvestment Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDaydoubleDaily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDayintLending Days [10/20/30]
isLoopbooleanAutomatic lending or not [1/0]
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idInvestmentID

Cancel investment

Request Sample


// request demo
GET https://trade.zb.com/api/cancelLoan?accesskey=youraccesskey&loanId=100&method=cancelLoan&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void cancelLoan() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan";
	//sign encrypted by HmacMD5 and get:0def7152ff2f6d4a8cab5f684d825a4a
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/cancelLoan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan&reqTime=1539942326076&sign=0def7152ff2f6d4a8cab5f684d825a4a";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def cancelLoan(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/cancelLoan'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan'
        params = 'accesskey=' + self._access_key_ + '&loanId=1454545445&method=cancelLoan'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0def7152ff2f6d4a8cab5f684d825a4a
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/cancelLoan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan&reqTime=1540295995572&sign=0def7152ff2f6d4a8cab5f684d825a4a
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment cancelLoan
accesskeyStringaccesskey
loanIdStringInvestmentID
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Get the available borrowing list

Request Sample


// request demo
GET https://trade.zb.com/api/getLoans?accesskey=youraccesskey&coin=qc&method=getLoans&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getLoans() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getLoans&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:9ed81061104f5b87703861ba77806eba
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getLoans?method=getLoans&cesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&pageIndex=1&pageSize=10&sign=9ed81061104f5b87703861ba77806eba&reqTime=1539942326077";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getLoans(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getLoans'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getLoans&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&coin=qc&method=getLoans&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 9ed81061104f5b87703861ba77806eba
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getLoans?method=getLoans&cesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&pageIndex=1&pageSize=10&sign=9ed81061104f5b87703861ba77806eba&reqTime=1540295995575
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success。",
	"result"            : [
		{
			"amount"            : "0.1",
			"balance"           : "0.00008001",
			"coinName"          : "qc",
			"repaymentDay"      : 10,
			"interestRateOfDay" : "0.0005"
		}
	]
}


Parameter NameTypeValue Range
methodStringDirect Assignment getLoans
accesskeyStringaccesskey
coinStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
amountAmount
balanceAvailable borrowing amount
coinNameCoin
repaymentDayBorrowing Period
interestRateOfDayDaily Interest Rate

Get Lending Records

Request Sample


// request demo
GET https://trade.zb.com/api/getLoanRecords?accesskey=youraccesskey&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=2&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getLoanRecords() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=1";
	//sign encrypted by HmacMD5 and get:08891e23a060aa0f979332939e7e845d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getLoanRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&reqTime=1539942326078&sign=08891e23a060aa0f979332939e7e845d&status=1";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getLoanRecords(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getLoanRecords'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=1'
        params = 'accesskey=' + self._access_key_ + '&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=1'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 08891e23a060aa0f979332939e7e845d
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getLoanRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&reqTime=1540295995578&sign=08891e23a060aa0f979332939e7e845d&status=1
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"                 : 1000,
	"message"              : "Success",
	"result"               : [
		{
			"createTime"           : 1522473159000,
			"statusShow"           : "Under Repayment",
			"freezId"              : "0",
			"tstatus"              : 0,
			"withoutLxAmount"      : "0",
			"investMark"           : false,
			"withoutLxDays"        : 0,
			"hasRepay"             : "0",
			"amount"               : "0.10008001",
			"id"                   : 290,
			"fwfScale"             : "0.2",
			"rate"                 : "0.0005",
			"marketName"           : "btsqc",
			"hasLx"                : "0",
			"isIn"                 : false,
			"balanceAmount"        : "0",
			"fundType"             : 15,
			"outUserId"            : 110797,
			"inUserId"             : 110797,
			"repayDate"            : 1523337159000,
			"zheLx"                : "0",
			"outUserFees"          : "",
			"dikouLx"              : "0",
			"sourceType"           : 8,
			"coinName"             : "QC",
			"reward"               : "0",
			"status"               : 1,
			"arrearsLx"            : "0.00005004",
			"balanceWithoutLxDays" : 0,
			"riskManage"           : 1,
			"rateAddVal"           : "0",
			"outUserName"          : "18022121179",
			"inUserName"           : "18022121179",
			"inUserLock"           : false,
			"rateForm"             : 1,
			"loanId"               : 94,
			"nextRepayDate"        : 1522559559000
		}
		...
	]
}


Parameter NameTypeValue Range
methodStringDirect Assignment getLoanRecords
accesskeyStringaccesskey
loanIdStringInvestmentid(Transfer if lending Do not transfer if borrowing)
marketNameStringMarket
statusintStatus(1Under Repayment 2Repaid 3 Need to be Liquidated 4 Liquidation repayment 5Automatically Repaying 6Automatically Repay)
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idLending RecordsID
loanIdInvestmentID
inUserIdBorrowerID
inUserNameBorrower's username
outUserIdLenderID
outUserNameLender's username
fundTypeCoin
amountBorrow Amount
statusStatus 1Under Repayment 2Repaid 3Need to be Liquidated 4 Liquidation repayment 5Automatically Repay
createTimeBorrow Time
rewardReward Amount
balanceAmountAvailable Amount
rateInterest Rate
hasRepayRepaid Capital Amount
hasLxRepaid Interest
dikouLxThe deducted interest
zheLxConverted price
arrearsLxOverdue Interest
nextRepayDateNext Repayment Time
riskManageRisk Control
inUserLockWhether the borrower is locked
withoutLxAmountInterest-free Amount
withoutLxDaysInterest-free Days
balanceWithoutLxDaysThe remaining interest-free days
rateFormInterest Type
rateAddValIncrease Range
repayDateRepayment Time
marketNameMarket
fwfScaleService Fee
investMarkAutomatically Renew
sourceTypeSource Type: 8”Web”,5”PhoneAPP”,6”InterfaceAPI”

Borrowing

Request Sample


// request demo
GET https://trade.zb.com/api/borrow?accesskey=youraccesskey&amount=100&coin=qc&interestRateOfDay=0.1&isLoop=1&marketName=btcqc&method=borrow&repaymentDay=20&safePwd=Transaction Password&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void borrow() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=0.5&coin=qc&interestRateOfDay=0.05&isLoop=0&marketName=aeqc&method=borrow&repaymentDay=10&safePwd=152433";
	//sign encrypted by HmacMD5 and get:0018e23184496b1fd5b7eadfaab2cc99
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/borrow?method=borrow&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=aeqc&coin=qc&amount=0.5&interestRateOfDay=0.05&repaymentDay=10&isLoop=0&safePwd=152433&sign=0018e23184496b1fd5b7eadfaab2cc99&reqTime=1539942326079";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def borrow(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/borrow'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=0.5&coin=qc&interestRateOfDay=0.05&isLoop=0&marketName=aeqc&method=borrow&repaymentDay=10&safePwd=152433'
        params = 'accesskey=' + self._access_key_ + '&amount=0.5&coin=qc&interestRateOfDay=0.05&isLoop=0&marketName=aeqc&method=borrow&repaymentDay=10&safePwd=152433'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0018e23184496b1fd5b7eadfaab2cc99
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/borrow?method=borrow&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=aeqc&coin=qc&amount=0.5&interestRateOfDay=0.05&repaymentDay=10&isLoop=0&safePwd=152433&sign=0018e23184496b1fd5b7eadfaab2cc99&reqTime=1540295995582
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment borrow
accesskeyStringaccesskey
marketNameStringMargin Market
coinStringCoin
amountdoubleBorrow Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDaydoubleDaily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDayintBorrowing Period [10/20/30]Day
isLoopintWhether to renew automatically [1/0](Automatic renewal at maturity/Automatic repay at maturity)
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Fast Borrow

Priority to borrow the funds start from those with the lowest interest rate

Request Sample


// request demo
GET https://trade.zb.com/api/autoBorrow?accesskey=youraccesskey&amount=100&coin=qc&interestRateOfDay=0.1&marketName=btsqc&method=autoBorrow&repaymentDay=20&safePwd=Transaction Password&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void borrow() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=100&coin=qc&interestRateOfDay=0.2&marketName=btsqc&method=autoBorrow&repaymentDay=20&safePwd=152433";
	//sign encrypted by HmacMD5 and get:09c5fe77bfd19ce4c636cb9ef0543d44
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/autoBorrow?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=100&coin=qc&interestRateOfDay=0.2&marketName=btsqc&method=autoBorrow&repaymentDay=20&reqTime=1566290460905&safePwd=152433&sign=09c5fe77bfd19ce4c636cb9ef0543d44";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def autoBorrow(self):
        MyUrl = 'https://trade.zb.com/api/autoBorrow'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=100&coin=qc&interestRateOfDay=0.2&marketName=btsqc&method=autoBorrow&repaymentDay=20&safePwd=152433'
        params = 'accesskey=' + self._access_key_ + '&amount=100&coin=qc&interestRateOfDay=0.2&marketName=btsqc&method=autoBorrow&repaymentDay=20&safePwd=152433'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 09c5fe77bfd19ce4c636cb9ef0543d44
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/autoBorrow?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=100&coin=qc&interestRateOfDay=0.2&marketName=btsqc&method=autoBorrow&repaymentDay=20&reqTime=1566290460905&safePwd=152433&sign=09c5fe77bfd19ce4c636cb9ef0543d44
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment autoBorrow
accesskeyStringaccesskey
marketNameStringMargin Market
coinStringCoin
amountdoubleBorrow Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDaydoubleDaily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDayintBorrowing Period [10/20/30]Day
safePwdStringTransaction Password
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Repayment

Request Sample


// request demo
GET https://trade.zb.com/api/repay?accesskey=youraccesskey&loanRecordId=289&method=repay&repayAmount=100&repayType=0&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void repay() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1";
	//sign encrypted by HmacMD5 and get:90fb3aacda467ffb95ce36c054173fff
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/repay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1&reqTime=1539942326080&sign=90fb3aacda467ffb95ce36c054173fff";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def repay(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/repay'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1'
        params = 'accesskey=' + self._access_key_ + '&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 90fb3aacda467ffb95ce36c054173fff
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/repay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1&reqTime=1540295995586&sign=90fb3aacda467ffb95ce36c054173fff
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment repay
accesskeyStringaccesskey
loanRecordIdStringLending Recordsid
repayAmountdoubleRepayment Amount
repayTypeintRepayment Mode [0/1](All/Part)
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Fast Repayment

Repay all outstanding borrowing

Request Sample


// request demo
GET https://trade.zb.com/api/doAllRepay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=btsqc&method=doAllRepay&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void doAllRepay() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=btsqc&method=doAllRepay";
	//sign encrypted by HmacMD5 and get:ce749e942171b8123a98c0eb0e097543
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/doAllRepay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=btsqc&method=doAllRepay&reqTime=1566315002580&sign=ce749e942171b8123a98c0eb0e097543";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def doAllRepay(self):
        MyUrl = 'https://trade.zb.com/api/doAllRepay'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=btsqc&method=doAllRepay'
        params = 'accesskey=' + self._access_key_ + '&marketName=btsqc&method=doAllRepay'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = ce749e942171b8123a98c0eb0e097543
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/doAllRepay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&marketName=btsqc&method=doAllRepay&reqTime=1566315002580&sign=ce749e942171b8123a98c0eb0e097543
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}


Parameter NameTypeValue Range
methodStringDirect Assignment doAllRepay
accesskeyStringaccesskey
marketNameStringMargin market, sample:btcqc
coinStringCurrency (optional when repayAmount is not filled)
repayAmountStringRepayment amount (optional, default full repayment)
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Get repayment records

Request Sample


// request demo
GET https://trade.zb.com/api/getRepayments?accesskey=youraccesskey&loanRecordId=50&method=getRepayments&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getRepayments() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:3a8808fa43fac898bb7e6bb32713f7bb
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getRepayments?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10&reqTime=1539942326082&sign=3a8808fa43fac898bb7e6bb32713f7bb";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getRepayments(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getRepayments'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 3a8808fa43fac898bb7e6bb32713f7bb
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getRepayments?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10&reqTime=1540295995590&sign=3a8808fa43fac898bb7e6bb32713f7bb
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"       : 1000,
	"message"    : "Success",
	"result"     : [
		{
			"benJin"     : "29",
			"id"         : 42,
			"statusShow" : "Repaid",
			"status"     : 1,
			"liXi"       : "0.0145",
			"actureDate" : 1522031604000
		}
	]
}


Parameter NameTypeValue Range
methodStringDirect Assignment getRepayments
accesskeyStringaccesskey
loanRecordIdStringLending Recordsid
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idRepayment RecordsID
benJinPrincipal
liXiInterest
statusStatus
statusShowStatus Value in Chinese
actureDateActual Repayment Date

Get Investment Records

Request Sample


// request demo
GET https://trade.zb.com/api/getFinanceRecords?accesskey=youraccesskey&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getFinanceRecords() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:c448737856caa08575d83f26e33cdde0
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getFinanceRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10&reqTime=1539943777351&sign=c448737856caa08575d83f26e33cdde0";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getFinanceRecords(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/getFinanceRecords'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = c448737856caa08575d83f26e33cdde0
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getFinanceRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10&reqTime=1540295995593&sign=c448737856caa08575d83f26e33cdde0
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success。",
	"result"            : [
		{
			"id"                : 156,
			"userId"            : 110803,
			"userName"          : "13427002684",
			"fundType"          : 15,
			"coinName"          : "QC",
			"amount"            : "10",
			"hasAmount"         : "0",
			"status"            : 0,
			"statusShow"        : "No Borrowing",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
	]
}


Parameter NameTypeValue Range
methodStringDirect Assignment getFinanceRecords
accesskeyStringaccesskey
coinStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idInvestmentID
userIdUserID
userNameUsername
fundTypeCoin
coinNameCoin Name
amountInvestment Amount
hasAmountLent Amount
statusStatus Value
statusShowStatus Value in Chinese
createTimeRelease Time
interestRateOfDayDaily Interest Rate
repaymentDayLending Days
isLoopAutomatic lending or not
inTimesThe investment being borrowed
sourceTypeSource Type: 8”Web”,5”PhoneAPP”,6”InterfaceAPI”

Change to automatical renewing or not

Request Sample


// request demo
GET https://trade.zb.com/api/changeInvestMark?accesskey=youraccesskey&investMark=1&loanRecordId=Lendingid&method=changeInvestMark&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


// java demo
public void changeInvestMark() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1&loanRecordId=154545,457457574&method=changeInvestMark";
	//sign encrypted by HmacMD5 and get:904182d4286992037130fbcbdabbe5cb
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/changeInvestMark?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1&loanRecordId=154545%2C457457574&method=changeInvestMark&reqTime=1539942326086&sign=904182d4286992037130fbcbdabbe5cb";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def changeInvestMark(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/changeInvestMark'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1&loanRecordId=154545,457457574&method=changeInvestMark'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 904182d4286992037130fbcbdabbe5cb
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/changeInvestMark?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1;loanRecordId=154545%2C457457574&method=changeInvestMark&ime=1540295995599&sign=904182d4286992037130fbcbdabbe5cb
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success。",
}


Parameter NameTypeValue Range
methodStringDirect Assignment changeInvestMark
accesskeyStringaccesskey
investMarkintRenew Type[0/1](Non-automated/Automatically Renew)
loanRecordIdStringLendingId,Multiple by English‘,’divided
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Change to automatical lending or not

Request Sample


// request demo
GET https://trade.zb.com/api/changeLoop?accesskey=youraccesskey&isLoop=1&loanId=Lendid&method=changeLoop&sign=Request Encrypted Signature String&reqTime=current time milliseconds



// java demo
public void changeLoop() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop";
	//sign encrypted by HmacMD5 and get:cfa39cb7fc939b2f4fd4dd3d788bf842
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/changeLoop?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop&reqTime=1539942326087&sign=cfa39cb7fc939b2f4fd4dd3d788bf842";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def changeLoop(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.com/api/changeLoop'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop'
        params = 'accesskey=' + self._access_key_ + '&isLoop=0&loanId=1154545&method=changeLoop'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = cfa39cb7fc939b2f4fd4dd3d788bf842
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/changeLoop?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop&reqTime=1540295995602&sign=cfa39cb7fc939b2f4fd4dd3d788bf842
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000,
    "message": "success",
}


Parameter NameTypeValue Range
methodStringDirect Assignment changeLoop
accesskeyStringaccesskey
isLoopintLend Type[0/1](Non-automated/Automatically Lend)
loanIdStringLendid
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Cross

Obtain cross information

Request Sample


// request demo
GET https://trade.zb.com/api/getCrossAssets?accesskey=youraccesskey&method=getCrossAssets&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


// java demo
public void getCrossAssets() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getCrossAssets";
	//sign encrypted by HmacMD5 and get:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getCrossAssets?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getCrossAssets&reqTime=1539942326068&sign=0cc8a3b79dabfac0c28229dd3871862d";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getCrossAssets(self):
        MyUrl = 'https://trade.zb.com/api/getCrossAssets'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo'
        params = 'accesskey=' + self._access_key_ + '&method=getCrossAssets'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0cc8a3b79dabfac0c28229dd3871862d
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getCrossAssets?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getCrossAssets&reqTime=1540295995557&sign=0cc8a3b79dabfac0c28229dd3871862d
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": 1000, 
    "message": Success, 
    "result": {
        "loanIn": 100, 
        "total": 1000, 
        "list": [
                {
                    "fundType": 15, 
                    "loanIn": 33, 
                    "amount": 44, 
                    "freeze": 0, 
                    "overdraft": 13, 
                    "key": "QC", 
                    "canTransferOut": 0
                },
                ...
            ],
            "net": 1000 
        }
    }
}

Parameter NameTypeValue Range
methodStringDirect Assignment getCrossAssets
accesskeyStringaccesskey
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
loanInBorrow
totalTotal assets
riskRaterisk rate
fundTypeCoin ID
amountAvailable Coin
freezeFrozen Coin
overdraftInterest
keyCoin Name
canTransferOutTransferable amount

Get cross bills

Request Sample


// request demo
GET https://trade.zb.com/api/getCrossBills?accesskey=youraccesskey&coin=qc&dataType=0&method=getCrossBills&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void getCrossBills() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:2473a00d93feed72583365e3cb90f391
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getCrossBills?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getCrossBills&pageIndex=1&pageSize=10&reqTime=1539942326070&sign=2473a00d93feed72583365e3cb90f391";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getCrossBills(self, amount, coin, dataType):
        MyUrl = 'https://trade.zb.com/api/getCrossBills'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getCrossBills&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&coin=qc&dataType=0&method=getCrossBills&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 2473a00d93feed72583365e3cb90f391
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getCrossBills?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getCrossBills&pageIndex=1&pageSize=10&reqTime=1540295995560&sign=2473a00d93feed72583365e3cb90f391
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success",
	"result"            : [
		{
			"balance"       : +1.000=1.000QC,
			"showFiat"      : "...",
			"createTime"    : 1605784831000,
			"typeName"      : "QC转入",
			"showCoin"      : "+1.000=1.000QC",
			"id"            : 609,
			"type"          : 1,
			"changed"       : 1
		}
	],
}

Parameter NameTypeValue Range
methodStringDirect Assignment getCrossBills
accesskeyStringaccesskey
coinStringCoin
dataTypeintData Type[0/1](Data in 30 days/Data over 30 days)
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
balanceBalance
showFiat...
createTimeRecords generate time
typeNameRecords Type in Chinese
showCoinShowCOINChange
idRecordsID
typeType of Records
changedChangesCOINAmount

Assets transferred into cross

Request Sample


// request demo
GET https://trade.zb.com/api/transferInCross?accesskey=youraccesskey&amount=100&coin=qc&method=transferInCross&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void transferInCross() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferInCross";
	//sign encrypted by HmacMD5 and get:a8fe8d3e01143e83491e5df69f288fd4
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/transferInCross?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferInCross&reqTime=1539942326071&sign=a8fe8d3e01143e83491e5df69f288fd4";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}


// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def transferInLever(self, coin, amount):
        MyUrl = 'https://trade.zb.com/api/transferInCross'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferInCross'
        params = 'accesskey=' + self._access_key_ + '&amount=1&coin=qc&marketName=btsqc&method=transferInLever'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = a8fe8d3e01143e83491e5df69f288fd4
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/transferInCross?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferInCross&reqTime=1540295995563&sign=a8fe8d3e01143e83491e5df69f288fd4
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment transferInCross
accesskeyStringaccesskey
coinStringCoin
amountdoubleTransfer-in Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Assets transferred out of cross

Request Sample


// request demo
GET https://trade.zb.com/api/transferOutCross?accesskey=youraccesskey&amount=100&coin=qc&method=transferOutCross&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void transferOutCross() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferOutCross";
	//sign encrypted by HmacMD5 and get:d7dcb17e6271232862812c339611d17e
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/transferOutCross?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferOutLever&reqTime=1539942326073&sign=d7dcb17e6271232862812c339611d17e";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}



// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def transferOutLever(self, amount, coin):
        MyUrl = 'https://trade.zb.com/api/transferOutCross'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&method=transferOutCross'
        params = 'accesskey=' + self._access_key_ + '&amount=1&coin=qc&method=transferOutCross'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = d7dcb17e6271232862812c339611d17e
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/transferOutCross?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&&method=transferOutLever&reqTime=1540295995566&sign=d7dcb17e6271232862812c339611d17e
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment transferOutCross
accesskeyStringaccesskey
coinStringCoin
amountdoubleTransfer-out Amount,The decimal places cannot exceed8,Exceed the system automatically intercepts8Bit
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Borrowing

Request Sample


// request demo
GET https://trade.zb.com/api/doCrossLoan?accesskey=youraccesskey&amount=100&coin=qc&method=doCrossLoan&safePwd=Transaction Password&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


// java demo
public void doCrossLoan() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=0.5&coin=qc&method=doCrossLoan&safePwd=152433";
	//sign encrypted by HmacMD5 and get:0018e23184496b1fd5b7eadfaab2cc99
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/doCrossLoan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706ecoin=qc&amount=0.5&method=doCrossLoan&safePwd=152433&sign=0018e23184496b1fd5b7eadfaab2cc99&reqTime=1539942326079";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}


// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def borrow(self, amount, coin, safePwd):
        MyUrl = 'https://trade.zb.com/api/doCrossLoan'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=doCrossLoan&safePwd=152433'
        params = 'accesskey=' + self._access_key_ + '&amount=0.5&coin=qc&method=doCrossLoan&safePwd=152433'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0018e23184496b1fd5b7eadfaab2cc99
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/doCrossLoan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&amount=0.5&method=doCrossLoan&safePwd=152433&sign=0018e23184496b1fd5b7eadfaab2cc99&reqTime=1540295995582
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment doCrossLoan
accesskeyStringaccesskey
coinStringCoin
amountdoubleBorrow Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
safePwdStringTransaction password
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Repayment

Request Sample


// request demo
GET https://trade.zb.com/api/doCrossRepay?accesskey=youraccesskey&coins=qc,usdt&method=doCrossRepay&repayAmount=100,200&&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


// java demo
public void doCrossRepay() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=doCrossRepay&repayAmount=1.5";
	//sign encrypted by HmacMD5 and get:90fb3aacda467ffb95ce36c054173fff
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/doCrossRepay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=doCrossRepay&reqTime=1539942326080&sign=90fb3aacda467ffb95ce36c054173fff";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}


// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def repay(self, coins, amount, price):
        MyUrl = 'https://trade.zb.com/api/doCrossRepay'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=repay&repayAmount=1.5'
        params = 'accesskey=' + self._access_key_ + '&method=repay&repayAmount=1.5'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 90fb3aacda467ffb95ce36c054173fff
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/doCrossRepay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=repay&repayAmount=1.5&reqTime=1540295995586&sign=90fb3aacda467ffb95ce36c054173fff
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment doCrossRepay
accesskeyStringaccesskey
coinsStringCurrency (optional when repayAmount is not filled)
repayAmountdoubleRepayment amount (optional, default full repayment)
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Automatic currency borrowing

Request Sample


// request demo
GET https://trade.zb.com/api/setExpressState?accesskey=youraccesskey&enableExpress=true&method=setExpressState&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds

Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment setExpressState
accesskeyStringaccesskey
enableExpressStringtrue/false
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Automatically Repay

Request Sample


// request demo
GET https://trade.zb.com/api/setRepayState?accesskey=youraccesskey&enableRepay=true&method=setRepayState&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds

Request Reply Sample


// Return Result
{
    "code": "1000",
    "message": "Success。"
}

Parameter NameTypeValue Range
methodStringDirect Assignment setRepayState
accesskeyStringaccesskey
enableRepayStringtrue/false
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Get a list of repayments

Request Sample


// request demo
GET https://trade.zb.com/api/getCrossRepayRecords?accesskey=youraccesskey&coin=qc&method=getCrossRepayRecords&pageIndex=1&pageSize=10&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds


// java demo
public void getCrossRepayRecords() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getCrossRepayRecords&pageIndex=1&pageSize=10";
	//sign encrypted by HmacMD5 and get:9ed81061104f5b87703861ba77806eba
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.com/api/getCrossRepayRecords?method=getCrossRepayRecords&cesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&pageIndex=1&pageSize=10&sign=9ed81061104f5b87703861ba77806eba&reqTime=1539942326077";
	//Get return resultjson
	String resultJson = HttpRequest.get(finalUrl).send().bodyText();
}


// python demo
import hashlib
import struct
import time
import requests

class ZApi:
    def __init__(self, access_key, secret_key):
        self._access_key_ = access_key
        self._secret_key_ = secret_key
        self._markets_ = self.markets()
        if len(self._markets_) < 1:
            raise Exception("Get markets status failed")

    def getCrossRepayRecords(self, coin, pageIndex, pageSize):
        MyUrl = 'https://trade.zb.com/api/getCrossRepayRecords'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getLoans&pageIndex=1&pageSize=10'
        params = 'accesskey=' + self._access_key_ + '&coin=qc&method=getCrossRepayRecords&pageIndex=1&pageSize=10'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 9ed81061104f5b87703861ba77806eba
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.com/api/getCrossRepayRecords?method=getCrossRepayRecords&cesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&pageIndex=1&pageSize=10&sign=9ed81061104f5b87703861ba77806eba&reqTime=1540295995575
            full_url += '?' + params
        result = {}
        while True:
            try:
                r = requests.get(full_url, timeout=2)
            except Exception:
                time.sleep(0.5)
                continue
            if r.status_code != 200:
                time.sleep(0.5)
                r.close()
                continue
            else:
                result = r.json()
                r.close()
                break
        return result

    @staticmethod
    def fill(value, length, fill_byte):
        if len(value) >= length:
            return value
        else:
            fill_size = length - len(value)
        return value + chr(fill_byte) * fill_size

    @staticmethod
    def xor(s, value):
        slist = list(s.decode('utf-8'))
        for index in range(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)

    def hmac_sign(self, arg_value, arg_key):
        keyb = struct.pack("%ds" % len(arg_key), arg_key.encode('utf-8'))
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        k_ipad = self.xor(keyb, 0x36)
        k_opad = self.xor(keyb, 0x5c)
        k_ipad = self.fill(k_ipad, 64, 54)
        k_opad = self.fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad.encode('utf-8'))
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad.encode('utf-8'))
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    def digest(self, arg_value):
        value = struct.pack("%ds" % len(arg_value), arg_value.encode('utf-8'))
        h = hashlib.sha1()
        h.update(value)
        dg = h.hexdigest()
        return dg


Request Reply Sample


// Return Result
{
	"code"              : 1000,
	"message"           : "Success。",
	"result"            : [
		{
			"fundType"            : 13,
			"newStatus"           : 2,
			"oldStatus"           : 1,
			"sourceType"          : 6,
			"benJin"              : 0.1
			"crossLoanrecordId"   : 1480
			"repayDate"           : 1605792527000
			"id"                  : 698
			"userName"            : 18712342222
			"liXi"                : 0.1
			"userId"              : 32231
		}
	]
}

Parameter NameTypeValue Range
methodStringDirect Assignment getCrossRepayRecords
accesskeyStringaccesskey
coinStringqc
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
accesskeyStringaccesskey
signStringRequest Encrypted Signature String
reqTimelongCurrent time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
fundTypeStringCoinID
newStatusintStatus before repayment,1 Under Repayment,2 Repaid,3 Forced liquidation,4 Liquidation repayment
oldStatusintStatus after repayment
sourceTypeSource Type: 8”Web”,5”PhoneAPP”,6”InterfaceAPI”
benJinintPrincipal
crossLoanrecordIdStringWhole warehouse loan record ID
repayDateintRepayment Time
idintid
userNameintUsername
liXiintInterest
userIdintuser id

WebSocket API

ZB provides the strong APIs for fast access to its spot markets with the following features: market data, order book, depths of bids and asks, trade history, trade execution, order information, order history, account information.。

Heartbeat setting, send ping, return pong

WebSocketService Address

ZB WebSocketService Connection Address :wss://api.zb.com/websocket

Sample Code

Signature: Use sha to encrypt the secretkey first, then sign the requested parameters according to the encrypted secretkey, request the parameters to be sorted and encrypted according to the ascii value, and fill the 16-bit encryption with md5.

github Sample Code

Access Restriction

1.For Trade API and Margin API, a single API KEY is limited to 60 accesses per second, and requests that exceed 60 requests per second are considered invalid.。

WSConfiguration

Get Market Configuration

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"markets"
}



// java demo
public void markets() {
	val data = new TreeMap();
	data.put("event", "addChannel");
	data.put("channel", "markets");
	ws.sendText(JSONObject.toJSONString(data));
}

    

// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'markets'}"
        self.ws_sub_spot.send(req)


Request Reply Sample


// Return Result
{
    "code":1000,
    "data":{
        "btc_usdt":{
            "amountScale":4,
            "minAmount":0.0001,
            "minSize":50,
            "priceScale":2
        },
        ...
    },
    "success":true,
    "channel":"markets",
    "message":"Success。"
}


Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringmarkets

Return ValueDescription
priceScaleDecimal Places of Price
minAmountMinimum transaction amount in transaction currency
minSizeMinimum transaction quantity in pricing currency
amountScaleDecimal Places of Amount

WSMarket

GettickerData

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"ltcbtc_ticker",
}



// java demo
public void ticker() {
	val data = new TreeMap();
	data.put("event", "addChannel");
	data.put("channel", "ltcbtc_ticker");
	ws.sendText(JSONObject.toJSONString(data));
}

    

// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_ticker'}"
        self.ws_sub_spot.send(req)


Request Reply Sample


// Return Result
{
    "channel": "ltcbtc_ticker",
    "date": "1472800466093",
    "no": 245539,
    "ticker": {
        "buy": "3826.94",
        "high": "3838.22",
        "last": "3826.94",
        "low": "3802.0",
        "sell": "3828.25",
        "open": "0.31"
        "riseRate": "4.81"
        "vol": "90151.83"
    }
}


Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringzbqc_ticker

Return ValueDescription
dateServer time of returning data
highHigh Price
lowLow Price
buyBuy 1
sellSell 1
lastLast Price
openOpening price
riseRate24H change
volTrading Volume(Latest 24Hour)
channelCurrent requestchannel

Get Market Depth

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"ltcbtc_depth",
}



// java demo
public void depth() {
	val data = new TreeMap();
	data.put("event", "addChannel");
	data.put("channel", "ltcqc_depth");
	ws.sendText(JSONObject.toJSONString(data));
}

    

// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_depth'}"
        self.ws_sub_spot.send(req)


Request Reply Sample


// Return Result
{
    "asks": [
        [
            3846.94,
            0.659
        ]...
    ],
    "bids": [
        [
            3826.94,
            4.843
        ]...
    ],
    "channel": "ltcbtc_depth",
    "no": 245539
}


Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringltcbtc_depth

Return ValueDescription
asksSell Order Depth
bidsBuy Order Depth
channelCurrent requestchannel

Get Historical Orders

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"ltcbtc_trades",
}



// java demo
public void trades() {
	val data = new TreeMap();
	data.put("event", "addChannel");
	data.put("channel", "ltcbtc_trades");
	ws.sendText(JSONObject.toJSONString(data));
}

    

// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_trades'}"
        self.ws_sub_spot.send(req)


Request Reply Sample


// Return Result
{
	"data": [
		{
			"date":"1443428902",
			"price":"1565.91",
			"amount":"0.553",
			"tid":"37594617",
			"type":"sell",
			"trade_type":"ask"
		}...
	],
	"no": 1031995,
	"channel": "ltcbtc_trades"
}
	


Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringltcbtc_trades

Return ValueDescription
dateTransaction Time
pricePrice
amountAmount
tidGenerate transactionID
channelCurrent requestchannel

Obtain K-line data

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"btcusdt_kline_15min",
}


Request Reply Sample


// Return Result
{
	"datas": 
		{
			"date":[[1647446400000(time),40605.46(open),41435.92(high),39339.33(low),40796.16(collect),9248.8589()]]",
		}
   "channel":"btcusdt_kline_1day",
	"isSuc":true,
}
	


Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringbtcusdt_kline_1day (1week, 3day, 1day, 12hour, 6hour, 4hour, 2hour, 1hour, 30min, 15min, 5min, 3min, 1min)

Return ValueDescription
channelCurrent requestchannel

WSTrade

Place Order

Request Sample


// request demo
{
    "accesskey": your key,
    "amount": 0.01,
    "channel": "ltcbtc_order",
    "event": "addChannel",
    "no": "14728151154382111746154",
    "price": 100,
    "sign": Signature,
    "tradeType": 1,
    "acctType" : 1
}



// java demo
public void usdtqc_order() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","tradeType":"1"}";
	//sign encrypted by HmacMD5 and get:6b9cd4aaee79a6b74fffa49146ae8879
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","sign":"6b9cd4aaee79a6b74fffa49146ae8879","tradeType":"1"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","tradeType":"1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 6b9cd4aaee79a6b74fffa49146ae8879
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def usdtqc_order(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","sign":"6b9cd4aaee79a6b74fffa49146ae8879","tradeType":"1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "message":"Success。",
    "no":"0",
    "data":"{
        "entrustId":201711133673
        }",
    "code":1000,
    "channel":"ltcbtc_order",
    "success":true
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
amountfloatAmount
channelStringTransaction Coin/Pricing Coin_order(btcusdt_order)
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
pricefloatPrice
tradeTypeintType1/0[buy/sell]
acctTypeintMargin 0/1/2[Spot/Isolated/Cross](Optional,Default to: 0 Spot)
signStringRequest Encrypted Signature String

Return ValueDescription
codeReturn Code
messageHints
entrustIdEntrusted order No.
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Cancel Order

Request Sample


// request demo
{
    "accesskey": your key,
    "channel": "ltcbtc_cancelorder",
    "event": "addChannel",
    "id": 20160902387645980,
    "no": "1472814987517496849777",
    "sign": Signature,
}



// java demo
public void usdtqc_cancelorder() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001"}";
	//sign encrypted by HmacMD5 and get:100d377228931b1147895f9d9785b2a3
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001","sign":"100d377228931b1147895f9d9785b2a3"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 100d377228931b1147895f9d9785b2a3
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def usdtqc_cancelorder(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001","sign":"100d377228931b1147895f9d9785b2a3"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "success": true,
    "code": 1000,
    "channel": "ltcbtc_cancelorder",
    "message": "Success。",
    "no": "1472814987517496849777"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringTransaction Coin/Pricing Coin_cancelorder(btcusdt_cancelorder)
eventStringDirect AssignmentaddChannel
idlongOrderid
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringRequest Encrypted Signature String

Return ValueDescription
codeReturn Code
messageHints
entrustIdEntrusted order No.
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get Entrusted Order

Request Sample


// request demo
{
    "accesskey": your key,
    "channel": "ltcbtc_getorder",
    "event": "addChannel",
    "id": 20160902387645980,
    "no": "14728149875431230591268",
    "sign": Signature,
}



// java demo
public void usdtqc_getorder() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001"}";
	//sign encrypted by HmacMD5 and get:aa67749256db23191458fea8970f1b6e
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001","sign":"aa67749256db23191458fea8970f1b6e"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: aa67749256db23191458fea8970f1b6e
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def usdtqc_getorder(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001","sign":"aa67749256db23191458fea8970f1b6e"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "success": true,
    "code": 1000,
    "data": {
        "currency": "ltc_btc",
        "id": "20160902387645980",
        "price": 100,
        "status": 0,
        "total_amount": 0.01,
        "trade_amount": 0,
        "trade_date": 1472814905567,
        "trade_money": 0,
        "type": 1
    },
    "channel": "ltcbtc_getorder",
    "message": "Success。",
    "no": "14728149875431230591268"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringTransaction Coin/Pricing Coin_getorder(btcusdt_getorder)
eventStringDirect AssignmentaddChannel
idlongEntrusted order No.
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringRequest Encrypted Signature String

Return ValueDescription
idEntrusted order No.
currencyType
trade_amountTrading Amount
trade_moneyTrading Volume
total_amountOrder Amount
trade_dateEntrust Time
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get Multiple Entrust Orders

Request Sample


// request demo
{
    "accesskey": "your key",
    "channel": "ltcbtc_getorders",
    "event": "addChannel",
    "no": "14728004752031866329548",
    "pageIndex": 1,
    "sign": Signature,
    "tradeType": 1
}



// java demo
public void usdtqc_getorders() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","tradeType":"1"}";
	//sign encrypted by HmacMD5 and get:027cf41d1f761e5ab8fc61b7e3efda54
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","sign":"027cf41d1f761e5ab8fc61b7e3efda54","tradeType":"1"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","tradeType":"1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 027cf41d1f761e5ab8fc61b7e3efda54
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def usdtqc_getorders(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","sign":"027cf41d1f761e5ab8fc61b7e3efda54","tradeType":"1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "success": true,
    "code": 1000,
    "data": [
        {
           "currency": "ltc_btc",
           "id": "20160901385862136",
           "price": 3700,
           "status": 0,
           "total_amount": 1.845,
           "trade_amount": 0,
           "trade_date": 1472706387742,
           "trade_money": 0,
           "type": 1
        }...
    ],
    "channel": "ltcbtc_getorders",
    "message": "Success。",
    "no": "14728004752031866329548"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringTransaction Coin/Pricing Coin_getorders(btcusdt_getorders)
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
pageIndexintCurrent Page(Such as: 1, page 1)
tradeTypeintType1/0[buy/sell]

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
typeOrder Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy
feesfees
useZbFeeWhether ZB deducts the handling fee
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get the ignore type of the orders

Request Sample


// request demo
{
    "accesskey": "your key",
    "channel": "ltcbtc_getordersignoretradetype",
    "event": "addChannel",
    "no": "1472800475206-1927246702",
    "pageIndex": 1,
    "pageSize": 10,
    "sign": Signature,
}



// java demo
public void usdtqc_getordersignoretradetype() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign encrypted by HmacMD5 and get:71ea0655343e47e6359de635b9ffe312
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"71ea0655343e47e6359de635b9ffe312"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 71ea0655343e47e6359de635b9ffe312
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def usdtqc_getordersignoretradetype(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"71ea0655343e47e6359de635b9ffe312"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "success": true,
    "code": 1000,
    "data": [
        {
            "currency": "ltc_btc",
            "id": "20160901385862136",
            "price": 3700,
            "status": 0,
            "total_amount": 1.845,
            "trade_amount": 0,
            "trade_date": 1472706387742,
            "trade_money": 0,
            "type": 1
        }...
    ],
    "channel": "ltcbtc_getordersignoretradetype",
    "message": "Success。",
    "no": "1472800475205-217627433"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringTransaction Coin/Pricing Coin_getordersignoretradetype(btcusdt_getordersignoretradetype)
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount

Return ValueDescription
currencyType
idEntrusted order No.
pricePrice
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateEntrust Time
trade_moneyTrading Volume
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get User Info

Request Sample


// request demo
{
	"accesskey":"your key",
	"channel":"getaccountinfo",
	"event":"addChannel",
	"no" : The unique identity of the request is used to distinguish content when it is returned,
	"sign":Signature
}



// java demo
public void getaccountinfo() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001"}";
	//sign encrypted by HmacMD5 and get:c2683870eaade9be66e46747520ca95f
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001","sign":"c2683870eaade9be66e46747520ca95f"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: c2683870eaade9be66e46747520ca95f
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getaccountinfo(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001","sign":"c2683870eaade9be66e46747520ca95f"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "message": "Success",
    "no": "15207605119",
    "data": {
        "coins": [
            {
                "freez": "1.35828369",
                "enName": "BTC",
                "unitDecimal": 8,
                "cnName": "BTC",
                "unitTag": "฿",
                "available": "0.72771906",
                "key": "btc"
            },
            {
                "freez": "0.011",
                "enName": "LTC",
                "unitDecimal": 8,
                "cnName": "LTC",
                "unitTag": "Ł",
                "available": "3.51859814",
                "key": "ltc"
            },
            ...
        ],
        "base": {
            "username": "15207605119",
            "trade_password_enabled": true,
            "auth_google_enabled": true,
            "auth_mobile_enabled": true
        }
    },
    "code": 1000,
    "channel": "getaccountinfo",
    "success": true
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetaccountinfo
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
auth_google_enabledWhether or not enable Google Authentication
auth_mobile_enabledWhether or not enable Phone Authentication
trade_password_enabledWhether or not enable transaction password
usernameUsername
enameCoin's English Name
cnNameCoin's Chinese Name
unitTagCoin Symbol
keyCoin
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

WSSub-accounts

Create Sub-account

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "addSubUser",
    "event": "addChannel",
    "memo": "memo",
    "password": "123456",
    "subUserName": "1",
	"sign":"Signature"
}



// java demo
public void addSubUser() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}";
	//sign encrypted by HmacMD5 and get:475fdd83600e42140d2d0336b8d57ce4
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","sign":"475fdd83600e42140d2d0336b8d57ce4","subUserName":"test1"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","sign":"475fdd83600e42140d2d0336b8d57ce4","subUserName":"test1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
	"success": true,
	"code": 1000,
	"channel": "addSubUser",
	"message": "Success",
	"no": "0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringaddSubUser
eventStringDirect AssignmentaddChannel
memoStringRemark
passwordStringPassword
subUserNameStringSub-account Username(not more than6 digits or letters)
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get Sub-account List

Request Sample


// request demo
{
	"accesskey": "ceb1569d-7c17-487a-b4a1-10bf2a8d925d",
	"channel": "getSubUserList",
	"event": "addChannel",
	"sign":"Signature"
}



// java demo
public void getSubUserList() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001"}";
	//sign encrypted by HmacMD5 and get:5fe82bf1864091af1120b184f773d1f9
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001","sign":"5fe82bf1864091af1120b184f773d1f9"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 5fe82bf1864091af1120b184f773d1f9
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getSubUserList(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001","sign":"5fe82bf1864091af1120b184f773d1f9"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
	"success": true,
	"code": 1000,
	"channel": "getSubUserList",
	"message": " [{
		"isOpenApi": false,
		"memo": "1",
		"userName": "15914665280@1",
		"userId": 110980,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "2",
		"userName": "15914665280@2",
		"userId": 110984,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "test3",
		"userName": "15914665280@3",
		"userId": 111014,
		"isFreez": false
	}]",
	"no": "0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetSubUserList
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
isOpenApiEnable or notAPI
userNameUsername
isFreezFreeze or not
memoRemark

Internal transfer between sub-accounts

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-487a-b4a1-10bf2a8d925d",
    "amount": "1",
    "channel": "doTransferFunds",
    "currency": "zb",
    "event": "addChannel",
    "fromUserName": "xxxxxx",
    "toUserName":"xxxx",
	"sign":"Signature"
}



// java demo
public void doTransferFunds() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","toUserName":"xxxx"}";
	//sign encrypted by HmacMD5 and get:3c1ab8f0b974e022ef8a151ff620062d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","sign":"3c1ab8f0b974e022ef8a151ff620062d","toUserName":"xxxx"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","toUserName":"xxxx"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 3c1ab8f0b974e022ef8a151ff620062d
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def doTransferFunds(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","sign":"3c1ab8f0b974e022ef8a151ff620062d","toUserName":"xxxx"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
	"success": true,
	"code": 1000,
	"channel": "doTransferFunds",
	"message": "Success",
	"no": "0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringdoTransferFunds
eventStringDirect AssignmentaddChannel
amountStringAmount
currencyStringCoin
fromUserNameStringTransferor Username
toUserNameStringReceiver Username
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

WSMargin

Get User's Margin Info

Request Sample


// request demo
{
	"accesskey":"your key",
	"channel":"getuserLeverAsset",
	"event":"addChannel",
	"no" : The unique identity of the request is used to distinguish content when it is returned,
	"sign":Signature
}



// java demo
public void getuserLeverAsset() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001"}";
	//sign encrypted by HmacMD5 and get:f060147b2f8a276291c7da4bf1f1d420
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001","sign":"f060147b2f8a276291c7da4bf1f1d420"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: f060147b2f8a276291c7da4bf1f1d420
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getuserLeverAsset(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001","sign":"f060147b2f8a276291c7da4bf1f1d420"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
    "message": "Success", 
    "no": "0", 
    "data": "
    {
        "levers": [
            {
                "fLoanIn": "0", 
                "repayLevel": "0", 
                "cUnitTag": "BTC", 
                "unwindPrice": "0", 
                "fUnitDecimal": "8", 
                "repayLock": "false", 
                "cLoanIn": "0", 
                "cEnName": "BTC", 
                "cAvailable": "0", 
                "fAvailable": "0", 
                "cLoanOut": "0", 
                "cCanLoanIn": "0", 
                "fLoanOut": "0", 
                "level": "0", 
                "fFreeze": "0", 
                "fEnName": "QC", 
                "cFreeze": "0", 
                "fCanLoanIn": "0", 
                "cUnitDecimal": "8", 
                "cOverdraft": "0", 
                "key": "btcqc", 
                "repayLeverShow": "-"
            }, 
           ...
        ]
    }
    ", 
    "code": 1000, 
    "channel": "getuserLeverAsset", 
    "success": true
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetuserLeverAsset
eventStringDirect AssignmentaddChannel
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not
fLoanInBorrowing amount of French currency
repayLevelLiquidation Level
unwindPriceLiquidation Price
fUnitDecimalDecimal Point
repayLockWhether is locked for the outstanding payment
cLoanInBorrow Amount
cAvailableAvailable Coin
fAvailableAvailable Fiat Currency
cLoanOutLend Amount
cCanLoanInAvailable for borrowing
fLoanOutAvailable for lending
levelMargin Level
fFreezeFrozen Fiat Currency
cFreezeFrozen Coin
fCanLoanInAvailable fiat currency for borrowing
cUnitDecimalCoin's decimal point
cOverdraftOverdue Interest
repayLeverShowLiquidation Risk

Get Margin Records

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLeverBills",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":Signature
}



// java demo
public void getLeverBills() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign encrypted by HmacMD5 and get:e92666397d9b03a47edfafd8cb4e759a
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"e92666397d9b03a47edfafd8cb4e759a"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e92666397d9b03a47edfafd8cb4e759a
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getLeverBills(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"e92666397d9b03a47edfafd8cb4e759a"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
    {
      "changeCoin":10,
      "showFiat":"…",
      "showCoin":"-10.000=2200.000QC",
      "type":12,
      "date":1523001559000,
      "database":"default",
      "dataName":"baseBean",
      "fundsType":15,
      "billTypeValue":"LendQC",
      "id":898,
      "downTableDate":1520697600000,
      "marketName":"btsqc",
      "avgPrice":0,
      "userId":110803,
      "coinBalance":2200,
      "entrustId":0
    },
    ...
  ],
  "channel":"getLeverBills",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetLeverBills
eventStringDirect AssignmentaddChannel
coinStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
idRecordsID
userIdUserID
dateRecords generate time
typeType of Records
billTypeValueRecords Type in Chinese
changeCoinChangesCOINAmount
coinBalanceChangedCOINBalance
changeFiatThe changed fiat currency amount
fiatBalanceFiat currency balance
fundsTypeCOINType
marketNameMarket Name
showCoinShowCOINChange
showFiatShow the change of fiat currency

Transfer funds to Margin Account

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"transferInLever",
  "coin":"qc",
  "event":"addChannel",
  "marketName":"btsqc",
  "sign":Signature
}



// java demo
public void transferInLever() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}";
	//sign encrypted by HmacMD5 and get:c9ef0030df66980464ccc47675900832
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001","sign":"c9ef0030df66980464ccc47675900832"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: c9ef0030df66980464ccc47675900832
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def transferInLever(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001","sign":"c9ef0030df66980464ccc47675900832"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"transferInLever",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringtransferInLever
eventStringDirect AssignmentaddChannel
coinStringCoin
marketNameStringMarket
amountDoubleTransfer-in Amount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Transfer funds out from Margin Account

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"transferOutLever",
  "coin":"qc",
  "event":"addChannel",
  "marketName":"btsqc",
  "sign":Signature
}



// java demo
public void transferOutLever() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}";
	//sign encrypted by HmacMD5 and get:da3b000acb6fb245a1ba2f661f2fd398
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001","sign":"da3b000acb6fb245a1ba2f661f2fd398"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: da3b000acb6fb245a1ba2f661f2fd398
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def transferOutLever(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001","sign":"da3b000acb6fb245a1ba2f661f2fd398"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"transferOutLever",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringtransferOutLever
eventStringDirect AssignmentaddChannel
coinStringCoin
marketNameStringMarket
amountDoubleTransfer-out Amount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Release Investment

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"loan",
  "coin":"qc",
  "event":"addChannel",
  "interestRateOfDay":0.15
  "isLoop":1
  "repaymentDay":20
  "safePwd":Transaction Password
  "sign":Signature
}



// java demo
public void loan() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"loan","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456"}";
	//sign encrypted by HmacMD5 and get:4ca79117822a780511307e55eb176d6b
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"loan","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456","sign":"4ca79117822a780511307e55eb176d6b"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"loan","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 4ca79117822a780511307e55eb176d6b
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def loan(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"loan","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456","sign":"4ca79117822a780511307e55eb176d6b"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"loan",
  "message":"Success",
  "no":"0",
  "data":{
      "loanId":121
  }
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringloan
eventStringDirect AssignmentaddChannel
coinStringCoin
amountDoubleInvestment Amount
interestRateOfDayDoubleDaily Interest Rate [0.05-0.2]%
repaymentDayintLending Days [10/20/30]
isLoopintAutomatic lending or not [1/0]
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
data
loanIdInvestmentID

Cancel investment

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"cancelLoan",
  "event":"addChannel",
  "loanId":121,
  "sign":Signature
}



// java demo
public void cancelLoan() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001"}";
	//sign encrypted by HmacMD5 and get:c19662ffe48ff586d5f5fa3ba8fcf2e1
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001","sign":"c19662ffe48ff586d5f5fa3ba8fcf2e1"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: c19662ffe48ff586d5f5fa3ba8fcf2e1
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def cancelLoan(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001","sign":"c19662ffe48ff586d5f5fa3ba8fcf2e1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"cancelLoan",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringcancelLoan
eventStringDirect AssignmentaddChannel
loanIdLongInvestmentID
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get the available borrowing list

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLoans",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":Signature
}



// java demo
public void getLoans() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign encrypted by HmacMD5 and get:357e94bcc5b2544f71364c6e05914f2e
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"357e94bcc5b2544f71364c6e05914f2e"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 357e94bcc5b2544f71364c6e05914f2e
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getLoans(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"357e94bcc5b2544f71364c6e05914f2e"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
    {
      "amount":"1400",
      "balance":"1300",
      "coinName":"qc",
      "repaymentDay":30,
      "lowestAmount":0.1,
      "interestRateOfDay":"0.0011"
    },
    {
      "amount":"2551.58399997",
      "balance":"901.58399997",
      "coinName":"qc",
      "repaymentDay":20,
      "lowestAmount":0.1,
      "interestRateOfDay":"0.0012"
    },
    ...
  ],
  "channel":"getLoans",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetLoans
eventStringDirect AssignmentaddChannel
coinStringCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
amountAmount
balanceAvailable borrowing amount
coinNameCoin
repaymentDayBorrowing Period
interestRateOfDayDaily Interest Rate

Get Lending Records

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLoanRecords",
  "loanId":58,
  "marketName":"btsqc",
  "pageIndex":1,
  "pageSize":10,
  "sign":Signature,
  "status":""
}



// java demo
public void getLoanRecords() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign encrypted by HmacMD5 and get:a728271842900000f82a046d06f5ceee
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10","sign":"a728271842900000f82a046d06f5ceee"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: a728271842900000f82a046d06f5ceee
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getLoanRecords(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10","sign":"a728271842900000f82a046d06f5ceee"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
    {
      "createTime":1521789778000,
      "statusShow":"Under Repayment",
      "freezId":"0",
      "tstatus":0,
      "withoutLxAmount":"0",
      "investMark":false,
      "withoutLxDays":0,
      "hasRepay":"0",
      "amount":"600",
      "id":59,
      "fwfScale":"0.2",
      "rate":"0.0015",
      "marketName":"btsqc",
      "hasLx":"0",
      "isIn":false,
      "balanceAmount":"0",
      "fundType":15,
      "outUserId":110652,
      "inUserId":110652,
      "repayDate":1524381778000,
      "zheLx":"0",
      "outUserFees":"",
      "dikouLx":"0",
      "sourceType":8,
      "coinName":"QC",
      "reward":"0",
      "status":1,
      "arrearsLx":"0.9",
      "statusColor":"orange",
      "balanceWithoutLxDays":0,
      "riskManage":1,
      "rateAddVal":"0",
      "outUserName":"13800138000",
      "inUserName":"13800138000",
      "inUserLock":false,
      "rateForm":1,
      "loanId":58,
      "nextRepayDate":1521876178000
    }
  ],
  "channel":"getLoanRecords",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetLoanRecords
eventStringDirect AssignmentaddChannel
loanIdLongInvestmentid(Transfer if lending Do not transfer if borrowing)
marketNameStringMarket
statusintStatus(1Under Repayment 2Repaid 3 Need to be Liquidated 4 Liquidation repayment 5Automatically Repaying 6Automatically Repay)
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
idLending RecordsID
loanIdInvestmentID
inUserIdBorrowerID
inUserNameBorrower's username
outUserIdLenderID
outUserNameLender's username
fundTypeCoin
amountBorrow Amount
statusStatus 1Under Repayment 2Repaid 3Need to be Liquidated 4 Liquidation repayment 5Automatically Repay
createTimeBorrow Time
rewardReward Amount
balanceAmountAvailable Amount
rateInterest Rate
hasRepayRepaid Capital Amount
hasLxRepaid Interest
dikouLxThe deducted interest
zheLxConverted price
arrearsLxOverdue Interest
nextRepayDateNext Repayment Time
riskManageRisk Control
inUserLockWhether the borrower is locked
withoutLxAmountInterest-free Amount
withoutLxDaysInterest-free Days
balanceWithoutLxDaysThe remaining interest-free days
rateFormInterest Type
rateAddValIncrease Range
repayDateRepayment Time
marketNameMarket
fwfScaleService Fee
investMarkAutomatically Renew
sourceTypeSource Type: 8”Web”,5”PhoneAPP”,6”InterfaceAPI”

Borrowing

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"borrow",
  "coin":"qc",
  "event":"addChannel",
  "interestRateOfDay":0.15
  "isLoop":1
  "repaymentDay":20
  "safePwd":Transaction Password
  "sign":Signature
}



// java demo
public void borrow() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"borrow","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456"}";
	//sign encrypted by HmacMD5 and get:378348551685d6d5ddbdf02a4df71f43
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"borrow","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456","sign":"378348551685d6d5ddbdf02a4df71f43"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"borrow","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 378348551685d6d5ddbdf02a4df71f43
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def borrow(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"borrow","coin":"qc","event":"addChannel","interestRateOfDay":"0.15","isLoop":"1","no":"test001","repaymentDay":"20","safePwd":"123456","sign":"378348551685d6d5ddbdf02a4df71f43"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"borrow",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringborrow
eventStringDirect AssignmentaddChannel
marketNameStringMargin Market
coinStringCoin
amountDoubleBorrow Amount
interestRateOfDayDoubleDaily Interest Rate [0.05-0.2]%
repaymentDayintBorrowing Period [10/20/30]Day
isLoopintWhether to renew automatically [1/0](Automatic renewal at maturity/Automatic repay at maturity)
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Repayment

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"repay",
  "event":"addChannel",
  "loanRecordId":296,
  "repayAmount":50,
  "repayType":0,
  "sign":Signature
}



// java demo
public void repay() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0"}";
	//sign encrypted by HmacMD5 and get:e8f84ef851933cee9c26417d26ae2122
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0","sign":"e8f84ef851933cee9c26417d26ae2122"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e8f84ef851933cee9c26417d26ae2122
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def repay(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0","sign":"e8f84ef851933cee9c26417d26ae2122"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"repay",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringrepay
eventStringDirect AssignmentaddChannel
loanRecordIdLongLending Recordsid
repayAmountDoubleRepayment Amount
repayTypeintRepayment Mode [0/1](All/Part)
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned

Get repayment records

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getRepayments",
  "loanRecordId":296,
  "pageIndex":1,
  "pageSize":10,
  "sign":Signature
}



// java demo
public void getRepayments() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign encrypted by HmacMD5 and get:5be5380faa9ee8010f43bafabbae5e3d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10","sign":"5be5380faa9ee8010f43bafabbae5e3d"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 5be5380faa9ee8010f43bafabbae5e3d
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getRepayments(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10","sign":"5be5380faa9ee8010f43bafabbae5e3d"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
    {
      "benJin":"50",
      "id":78,
      "statusShow":"Repaid",
      "status":1,
      "liXi":"0.06",
      "actureDate":1522982889000
    }
  ],
  "channel":"getLeverBills",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetRepayments
eventStringDirect AssignmentaddChannel
loanRecordIdLongLending Recordsid
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
idRepayment RecordsID
benJinPrincipal
liXiInterest
statusStatus
statusShowStatus Value in Chinese
actureDateActual Repayment Date

Get Investment Records

Request Sample


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getFinanceRecords",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":Signature
}



// java demo
public void getFinanceRecords() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//signEncrypted by HmacMD5 and get:e950df0cff23a392fb738c8eeb2ef9dc
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"e950df0cff23a392fb738c8eeb2ef9dc"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e950df0cff23a392fb738c8eeb2ef9dc
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def getFinanceRecords(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10","sign":"e950df0cff23a392fb738c8eeb2ef9dc"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
		{
			"id"                : 156,
			"userId"            : 110803,
			"userName"          : "13427002684",
			"fundType"          : 15,
			"coinName"          : "QC",
			"amount"            : "10",
			"hasAmount"         : "0",
			"status"            : 0,
			"statusShow"        : "No Borrowing",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
  ],
  "channel":"getFinanceRecords",
  "message":"Success",
  "no":"0"
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringgetFinanceRecords
eventStringDirect AssignmentaddChannel
coinSTirngCoin
pageIndexintCurrent Page(Such as: 1, page 1)
pageSizeintAmount
noStringThe unique identity of the request is used to distinguish content when it is returned
signStringSignature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request is used to distinguish content when it is returned
idInvestmentID
userIdUserID
userNameUsername
fundTypeCoin
coinNameCoin Name
amountInvestment Amount
hasAmountLent Amount
statusStatus Value
statusShowStatus Value in Chinese
createTimeRelease Time
interestRateOfDayDaily Interest Rate
repaymentDayLending Days
isLoopAutomatic lending or not
inTimesThe investment being borrowed
sourceTypeSource Type: 8”Web”,5”PhoneAPP”,6”InterfaceAPI”

WebSocket API V2

Fast Market

Request Sample


// request demo
{
	"event":"addChannel",
	"channel":"usdtqc_quick_depth",
}


// java demo
public void depth() {
	val data = new TreeMap();
	data.put("event", "addChannel");
	data.put("channel", "usdtqc_quick_depth");
	ws.sendText(JSONObject.toJSONString(data));
}
    

// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread
import websocket
import urllib2, hashlib,struct,sha,time
zb_usd_url = "wss://api.zb.com/websocket/usdt"
class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'usdtqc_quick_depth'}"
        self.ws_sub_spot.send(req)


Request Reply Sample


// Return Result
{
    "lastTime": 1592277547320,
    "dataType": quickDepth,
    "channel": usdtqc_quick_depth,
    "currentPrice": 7.0885,
    "transction":[],
    "listDown": [
        [
            7.0885,
            12589.6168
        ]...
    ],
    "listUp": [
        [
            7.0893,
            64.843
        ]...
    ],
    "market": usdtqc,
    "high": 7.1477,
    "rate": 1,
    "low": 7.0851,
    "currentIsBuy": false,
    "dayNumber": 22236861.8995,
    "totalBtc": 22236861.8995
}

Parameter NameTypeValue Range
eventStringDirect AssignmentaddChannel
channelStringusdtqc_quick_depth
lengthStringGear5 10 20(Optional, default is 5 files)

Return ValueDescription
lastTimeTime
dataTypeData Type
channelCurrent requestchannel
currentPriceLast Price
transction
listDownBuy Order Depth
listUpSell Order Depth
marketMarket
highHigh Price
rateBuy Order Depth
lowLow Price
currentIsBuyType
dayNumberTrading Volume
totalBtcTrading Volume

Quick market grouping

同一组内的多个市场可以用一个WS链接进行订阅,在此场景下,WS访问地址是wss://api.zb.com/websocket/XXX,XXX是该组内任意一个币种名

eg.ETH, LTC, EOS, qtum and other currencies belong to group 3, then access the address wss://api.zb.com/websocket/eth

It can be used to subscribe to the Quick Quotation interface of all currency transaction pairs in the group, eg.ltc_qc,qtum_usdt,eos_btc...

Request Sample


// request demo
GET https://api.zb.com/data/v1/getGroupMarkets



// java demo
public void getGroupMarkets() {
	//Get return result
	String returnJson = HttpRequest.get("https://api.zb.com/data/v1/getGroupMarkets").send().bodyText();
}



// python demo
def get(self, url):
    while True:
        try:
            r = requests.get(url)
        except Exception:
            time.sleep(0.5)
            continue
        if r.status_code != 200:
            time.sleep(0.5)
            continue
        r_info = r.json()
        r.close()
        return r_info

def getGroupMarkets(self, market):
    url = 'https://api.zb.com/data/v1/getGroupMarkets'
    return self.get(url)

Request Reply Sample


// Return Result
{
    "wsgroup1": [
        "usdtqc"
        ],
    "wsgroup2": [
        "btcusdt",
        "btcqc",
        "zbqc"
        ...
    ],
    ...
}

Order Changes (push the last 10 pending and completed orders records)

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "push_user_record",
    "event": "addChannel",
    "market": "zbqcdefault",
    "sign":"Signature"
}



// java demo
public void push_user_record() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_record","event":"addChannel","isZip":false,"market":"zbqcdefault"}";
	//sign encrypted by HmacMD5 and get:6c9157032c96795a411a3b8628f543f5
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"market":"zbqcdefault","accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_record","sign":"6c9157032c96795a411a3b8628f543f5","isZip":false,"event":"addChannel"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","sign":"475fdd83600e42140d2d0336b8d57ce4","subUserName":"test1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
	"record": [],
	"hrecord": [
		[
			"id",
			entrust price,
			entrust amount,
			Trading Amount,
			Trading Volume,
			Order Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy,
			Entrust Time,
			Order status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ),
			fees,
			ignore,
			Source Type: 8Web,5PhoneAPP,6InterfaceAPI,
			account type 0 spot 1 lever
		]...
	],
	"precord": [
		[
			"id",
			entrust price,
			entrust amount,
			Trading Amount,
			Trading Volume,
			Order Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy,
			Entrust Time,
			Order status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ),
			fees,
			Trigger price of chasing high and stop loss,
			Source Type: 8Web,5PhoneAPP,6InterfaceAPI,
			Trigger price for bottom reading and profit stopping,
			entrust price,
			entrust money,
			Official delegation ID,
			true,
			True trigger price, 0 is unknown
		]...
	],
	"dataType": "userRecord",
	"count": 0,
	"channel": "push_user_record"
	"lastTime": 1590806778504
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringpush_user_record
eventStringDirect AssignmentaddChannel
marketStringzbqcdefault
signStringSignature

Return ValueDescription
precordPlan commission
recordCurrent entrust
hrecordHistorical commission
dataTypeData Type
channelRequested Channel
lastTimetime

Incremental Order Changes (only push changed commission records)

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "push_user_incr_record",
    "event": "addChannel",
    "market": "zbqcdefault",
    "sign":"Signature"
}



// java demo
public void push_user_incr_record() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_record","event":"addChannel","market":"zbqcdefault"}";
	//sign encrypted by HmacMD5 and get:6c9157032c96795a411a3b8628f543f5
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"market":"zbqcdefault","accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_record","sign":"6c9157032c96795a411a3b8628f543f5","event":"addChannel"}";
	ws.sendText(json);
}



// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_record","event":"addChannel"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_record","event":"addChannel","sign":"475fdd83600e42140d2d0336b8d57ce4"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass


Request Reply Sample


// Return Result
{
	"market": "usdtqcdefault",
	"record": [
		"id",
		entrust price,
		entrust amount,
		Trading Amount,
		Trading Volume,
		Order Type0-limit sell,1-limit buy,2-PostOnly sell,3-PostOnly buy,4-IOC sell,5-IOC buy,
		Entrust Time,
		Order status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ),
		fees,
		ignore,
		Source Type: 8Web,5PhoneAPP,6InterfaceAPI,
		account type 0 spot 1 lever,
		订单详情ID,
		Latest transaction price,
		Latest transaction volume,
		Latest transaction time
	],
   "dataType": "userIncrRecord",
	"count": 0,
	"channel": "push_user_incr_record"
	"lastTime": 1590806778504
}


Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringpush_user_incr_record
eventStringDirect AssignmentaddChannel
marketStringzbqcdefault
signStringSignature

Return ValueDescription
recordCurrent entrust
dataTypeData Type
channelRequested Channel
lastTimetime

Main Account Changes (push full currency assets)

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "push_user_asset",
    "event": "addChannel",
    "sign":"Signature"
}


// java demo
public void push_user_record() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_asset","event":"addChannel","isZip":false}";
	//sign encrypted by HmacMD5 and get:6c9157032c96795a411a3b8628f543f5
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_asset","sign":"6c9157032c96795a411a3b8628f543f5","isZip":false,"event":"addChannel"}";
	ws.sendText(json);
}


// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","sign":"475fdd83600e42140d2d0336b8d57ce4","subUserName":"test1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass

Request Reply Sample


// Return Result
{
"coins": [
    {
        "isCanWithdraw": true,
        "canLoan": false,
        "fundstype": 51,
        "showName": "ZB",
        "isCanRecharge": true,
        "cnName": "ZB",
        "enName": "ZB",
        "available": 6011.29619163,
        "freez": 20,
        "unitTag": "ZB",
        "key": "ZB",
        "unitDecimal": 8
    }
],
	"dataType": "userAsset",
	"channel": "push_user_asset",
	"version": 1590806778504
}

Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringpush_user_asset
eventStringDirect AssignmentaddChannel
signStringSignature

Return ValueDescription
coinscoin information
dataTypeData Type
channelRequested Channel
versionPush the number once and add 1

Main Account Incremental Changes (push changed currency assets)

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "push_user_incr_asset",
    "event": "addChannel",
    "sign":"Signature"
}


// java demo
public void push_user_incr_asset() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_asset","event":"addChannel"}";
	//sign encrypted by HmacMD5 and get:6c9157032c96795a411a3b8628f543f5
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_asset","sign":"6c9157032c96795a411a3b8628f543f5","event":"addChannel"}";
	ws.sendText(json);
}


// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread

import websocket
import urllib2, hashlib,struct,sha,time


zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey

        websocket.enableTrace(trace)

        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()

        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_asset","event":"addChannel"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"push_user_incr_asset","event":"addChannel","sign":"475fdd83600e42140d2d0336b8d57ce4"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass

Request Reply Sample


// Return Result
{
"coins": [
{
    "isCanWithdraw": true,
    "canLoan": false,
    "fundstype": 51,
    "showName": "ZB",
    "isCanRecharge": true,
    "cnName": "ZB",
    "enName": "ZB",
    "available": 6011.29619163,
    "freez": 20,
    "unitTag": "ZB",
    "key": "ZB",
    "unitDecimal": 8
}],
	"dataType": "userIncrAsset",
	"channel": "push_user_incr_asset",
	"version": 1590806778504
}

Parameter NameTypeValue Range
accesskeyStringaccesskey
channelStringpush_user_incr_asset
eventStringDirect AssignmentaddChannel
signStringSignature

Return ValueDescription
coinscoin information
dataTypeData Type
channelRequested Channel
versionPush the number once and add 1

Lever Account Change

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "binary": "false",
    "channel": "push_user_lever_asset",
    "event": "addChannel",
    "isZip": "false",
    "sign":"Signature"
}


// java demo
public void push_user_lever_asset() {
	//TestapiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//TestsecretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//Cryptography Classes:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKeyEncrypted by sha1:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//Parameters are sorted by ASCII value
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_lever_asset","event":"addChannel","isZip":false}";
	//sign encrypted by HmacMD5 and get:6c9157032c96795a411a3b8628f543f5
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","binary":false,"channel":"push_user_lever_asset","sign":"6c9157032c96795a411a3b8628f543f5","isZip":false,"event":"addChannel"}";
	ws.sendText(json);
}


// python demo
import hashlib
import zlib
import json
from time import sleep
from threading import Thread
import websocket
import urllib2, hashlib,struct,sha,time
zb_usd_url = "wss://api.zb.com/websocket"

class ZB_Sub_Spot_Api(object):
    """Websocket-based API Object"""
    def __init__(self):
        """Constructor"""
        self.apiKey = 'ce2a18e0-dshs-4c44-4515-9aca67dd706e'
        self.secretKey = 'c11a122s-dshs-shsa-4515-954a67dd706e'

        self.ws_sub_spot = None          # websocketApplication Object  Spot Object

    #----------------------------------------------------------------------
    def reconnect(self):
        """Reconnect"""
        # Close the previous connection first
        self.close()

        # and reconnect
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                         on_message=self.onMessage,
                                         on_error=self.onError,
                                         on_close=self.onClose,
                                         on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()

    #----------------------------------------------------------------------
    def connect_Subpot(self, apiKey , secretKey , trace = False):
        self.host = zb_usd_url
        self.apiKey = apiKey
        self.secretKey = secretKey
        websocket.enableTrace(trace)
        self.ws_sub_spot = websocket.WebSocketApp(self.host,
                                             on_message=self.onMessage,
                                             on_error=self.onError,
                                             on_close=self.onClose,
                                             on_open=self.onOpen)

        self.thread = Thread(target=self.ws_sub_spot.run_forever)
        self.thread.start()
    #----------------------------------------------------------------------
    def readData(self, evt):
        """Extract and push the received data"""
        # # Extract and push the received data
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)

        # # Decompress the original data into string
        # inflated = decompress.decompress(evt) + decompress.flush()

        # Parse strings via json
        data = json.loads(evt)

        return data

    #----------------------------------------------------------------------
    def close(self):
        """Close Interface"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """Information Push"""
        print evt

    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """Wrong Push"""
        print 'onError'
        print evt

    #----------------------------------------------------------------------
    def onClose(self, ws):
        """Disconnect Interface"""
        print 'onClose'

    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """Open Interface"""
        print 'onOpen'

    #----------------------------------------------------------------------
    def __fill(self, value, length, fillByte):
        if len(value) >= length:
            return value
        else:
            fillSize = length - len(value)
        return value + chr(fillByte) * fillSize
    #----------------------------------------------------------------------
    def __doXOr(self, s, value):
        slist = list(s)
        for index in xrange(len(slist)):
            slist[index] = chr(ord(slist[index]) ^ value)
        return "".join(slist)
    #----------------------------------------------------------------------
    def __hmacSign(self, aValue, aKey):
        keyb   = struct.pack("%ds" % len(aKey), aKey)
        value  = struct.pack("%ds" % len(aValue), aValue)
        k_ipad = self.__doXOr(keyb, 0x36)
        k_opad = self.__doXOr(keyb, 0x5c)
        k_ipad = self.__fill(k_ipad, 64, 54)
        k_opad = self.__fill(k_opad, 64, 92)
        m = hashlib.md5()
        m.update(k_ipad)
        m.update(value)
        dg = m.digest()
        m = hashlib.md5()
        m.update(k_opad)
        subStr = dg[0:16]
        m.update(subStr)
        dg = m.hexdigest()
        return dg
    #----------------------------------------------------------------------
    def __digest(self, aValue):
        value  = struct.pack("%ds" % len(aValue), aValue)
        h = sha.new()
        h.update(value)
        dg = h.hexdigest()
        return dg

    #----------------------------------------------------------------------
    def generateSign(self, params):
        #Parameters are sorted by ASCII value: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: 475fdd83600e42140d2d0336b8d57ce4
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def addSubUser(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","sign":"475fdd83600e42140d2d0336b8d57ce4","subUserName":"test1"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass

Request Reply Sample


// Return Result
{
	"levers": [],
	"dataType": "userLeverAsset",
	"channel": "push_user_lever_asset"
	"usdtcny": 7.0835
}

Parameter NameTypeValue Range
accesskeyStringaccesskey
binarybooleanWhether binary transmission
channelStringpush_user_lever_asset
eventStringDirect AssignmentaddChannel
isZipbooleanWhether to compress transmission
signStringSignature

Return ValueDescription
leverschange information
dataTypeData Type
channelRequested Channel
usdtcnyUS dollar exchange rate

Full position leveraged assets

Request Sample


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "binary": "false",
    "channel": "push_user_cross_asset",
    "event": "addChannel",
    "isZip": "false",
    "sign":"Signature"
}

Request Reply Sample


// Return Result
{
	"coins": [
	    {
	        "loanIn": 11.1,
	        "fundType": 3,
	        "amount": 10,
	        "freeze": 0,
	        "overdrafr": 0,
	        "userId": 1124,
	        "key": "ltc",
	        "status": 0
	    }
	    ......
   ]
	"dataType": "userAsset",
	"channel": "push_user_cross_asset"
	"usdtcny": 7.0835
}

Parameter NameTypeValue Range
accesskeyStringaccesskey
binarybooleanWhether binary transmission
channelStringpush_user_cross_asset
eventStringDirect AssignmentaddChannel
isZipbooleanWhether to compress transmission
signStringSignature

Return ValueDescription
coins
loanInBorrow
fundTypeCoin
amountchange information
freezeFrozen Coin
overdraftInterest
keyCoin Name
dataTypeData Type
channelRequested Channel
usdtcnyUS dollar exchange rate

Encryption Method

  • accesskey=08b38d11-445f-447f-9372-d255e10b91bd
  • secretKey=ad030fda-86c1-4d9e-b333-fefbc1fb89e8

Online encryption tool: http://tool.oschina.net/encrypt?type=2

First: Usesha1 encryption secretKey get 5b1f87b2375ad8e46abf5e8ac4577c50dcee7989

Enter description for the picture

Second: Calculatesign

  • demoGet user information, and splice corresponding parameters to get the final result:
  • rest:accesskey=08b38d11-445f-447f-9372-d255e10b91bd&method=getAccountInfo;
  • ws:{"accesskey":"08b38d11-445f-447f-9372-d255e10b91bd","channel":"getaccountinfo","event":"addChannel","no":"1231231233431"}
  • For each interface example, all parameters (except sign and reqTime) after the interface '?' Need to be calculated as clear text.
  • Encrypted strings cannot have spaces
  • UsesecretKeyPasssha1Encrypted String:5b1f87b2375ad8e46abf5e8ac4577c50dcee7989 as hash
  • Calculate and get to the finalsign, rest:48a1af2ea626dde38134ff8a51d8d0c3;ws:9ee1b7201261fd530630cc9bc384a3b1 Enter description for the picture

FAQ

  1. How to enable API?API?

    • Log in and access this link for API Settingshttps://vip.zb.com/u/safe/api
    • Press API Setting---->Press to enable API---->Enter SMS Verification Code---->Enable
    • If you bind API Trade IP, you will just be able to use the bound IP for trading, if not, there is no limit.
  2. What is the utility of the generated private key??

    • The private key is the key used for API operation, which is required when calling API interface. The private key is only showed once when it is generated, and it needs to be regenerated if you forget it.
  3. Why does 1003 error occur?

    • Check whether encryption is sorted by ASCII value and whether encryption parameters are missing or have rebundant character concatenation, etc
  4. It prompts 1002 error invalid parameter
    • Invalid transfer parameter
  5. Can K-line chart obtain the data of months or a year ago?
    • The system only provides up to 1000 K-line data. If you want to obtain data of a longer time, you can use the unit of hour or day.
  6. Does the API need to be bound with the IP??

    • Binding IP will effectively prevent the server other than this IP from calling its permissions for trading.
    • The binding IP must be the static IP of the public network and the personal developed PC client does not need to bind IP. After binding the IP, only the binding IP can access the API, otherwise there is no restriction.
    • API transaction stays empty will have no restriction
  7. Does API support random withdrawal??

    • Not supported, the withdrawal must be verified on the zb official website before the API withdrawal can be carried out
    • It is required to provide transaction password when withdraw via API
  8. Can I provide public key or private key to others?

    • Please do not leak out your public key or secret key to others, otherwise it will result in your loss of asset.
  9. qcDoes QC is CNY

    • No, it isn't. QC is 1:1 to CNY in value
  10. Why '1002, internal error' occurs
    • Sometimes, excessive request volume may cause these errors, please recall it for normal use.

Error Code

restReturn Code

Return CodeDescription
1000The call is successful.
1001General error prompt
1002Internal Error
1003Fail to verify
1004The transaction password is locked
1005Wrong transaction password, please check it and re-enter。
1006Real-name authentication is pending approval or unapproved
1009This interface is under maintenance
1010Not available now
1012Insufficient permissions
1013Cannot trade, please contact email: [email protected] for support.
1014Cannot sell during the pre-sale period
2001Insufficient CNY account balance
2002Insufficient BTC account balance
2003Insufficient LTC account balance
2005Insufficient ETH account balance
2006ETCInsufficient account balance
2007BTSInsufficient account balance
2008EOSInsufficient account balance
2009BCCInsufficient account balance
3001Order not found or is completed
3002Invalid amount
3003Invalid quantity
3004User does not exist
3005Invalid parameter
3006Invalid IP or not consistent with the bound IP
3007The request time has expired
3008Transaction not found
3009The price exceeds the limit
3010It fails to place an order, due to you have set up to prohibit trading of this market.
3011The entrusted price is abnormal, please modify it and place order again
3012Duplicate custom customerOrderId
4001APIThe interface is locked for one hour
4002Request too frequently

websocketReturn Code

Return CodeDescription
1000The call is successful.
1001General error prompt
1002Internal Error
1003Fail to verify
1004The transaction password is locked
1005Wrong transaction password, please check it and re-enter。
1006Real-name authentication is pending approval or unapproved
1007Channel does not exist
1009This interface is under maintenance
1010Not available now
1012Insufficient permissions
1013Cannot trade, please contact email: [email protected] for support.
1014Cannot sell during the pre-sale period
2001Insufficient CNY account balance
2002Insufficient BTC account balance
2003Insufficient LTC account balance
2005Insufficient ETH account balance
2006ETCInsufficient account balance
2007BTSInsufficient account balance
2008EOSInsufficient account balance
2009BCCInsufficient account balance
3001Order not found or is completed
3002Invalid amount
3003Invalid quantity
3004User does not exist
3005Invalid parameter
3006Invalid IP or not consistent with the bound IP
3007The request time has expired
3008Transaction not found
3009The price exceeds the limit
3010It fails to place an order, due to you have set up to prohibit trading of this market.
3011The entrusted price is abnormal, please modify it and place order again
3012Duplicate custom customerOrderId
4001APIThe interface is locked for one hour
4002Request too frequently

Contact us

ZB is now soliciting market makers from all over the world. Market makers enjoy maker rebate and ultra-low rate of taker. If you are interested in the market maker plan, please contact us [email protected] Or your key account manager. Please send the following information to [email protected] :

  1. Effective contact information (wechat or telephone)

  2. Briefly introduce the team and past market making (trading volume within 30 days, market making strategy, etc.)