Get Started

ZB API Introduction

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.。

ZB API interface is the basis of API services and it is divided into four categories: trading, market data, margin and sub-accounts. After creating a ZB account, developers can create APIs with different permissions according to their own needs, and use the API to perform automatic transactions or withdrawals.。

Trade, Market Data, Margin and Sub-account need to verify the signatures.

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. Clear in structure, easy to understand and expand, making it is 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, saving 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'

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. It currently supports C, JAVA, Python versions, and more language versions will be supported in succession. If you have any question, please contact at [email protected] for support.

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.KLine 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 http://api.zb.live/data/v1/markets



// java demo
public void getMarkets() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/data/v1/markets'
    return self.get(url)


Request Reply Sample


// Return Result
{
    "btc_usdt": {
        "amountScale": 4,
        "priceScale": 2
    }
}


Return ValueDescription
priceScaleDecimal Places of Price
amountScaleDecimal Places of Amount

Markets

Get allTicker data

Get all coin data

Request Sample


// request demo
GET http://api.zb.live/data/v1/allTicker



// java demo
public void getAllTicker() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/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"
	},
	"tvqc":{
		"vol":"2201510.1",
		......
}


Return ValueDescription
high24h High
low24h Low
buyBuy 1
sellSell 1
lastLatest Price
vol24H Volume

Get ticker data

Get a single coin's market

Request Sample


// request demo
GET http://api.zb.live/data/v1/ticker?market=btc_usdt



// java demo
public void getTicker() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/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"
    }, 
    "date": "1507875747359"
}


Parameter Name Type Value Range
market String Sample:btc_qc

Return ValueDescription
high24h High
low24h Low
buyBuy 1
sellSell 1
lastLatest Price
vol24H Volume

Get Market Depth

Request Sample


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



// java demo
public void getDepth() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/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 Name Type Value Range
market String Sample:btc_qc
size int Position range is from 1 to 50, if there is combine depth, it only return 5 positions.
merge float Depth

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

Get Historical Orders

Request Sample


// request demo
GET http://api.zb.live/data/v1/trades?market=btc_usdt



// java demo
public void getTrades() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/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 Name Type Value Range
market String Sample:btc_qc
since long 50 data after the specified transaction ID

Return ValueDescription
dateTransaction Time(Timestamp)
pricePrice
amountTransaction Amount
tidGenerate TransactionID
trade_typeOrder Type: ask and bidID
typeTrading Type: buy and sellID

ObtainKLine

Get K line data, up to the latest 1000 data

Request Sample


// request demo
GET http://api.zb.live/data/v1/kline?market=btc_usdt



// java demo
public void getKline() {
	//Get return result
	String returnJson = HttpRequest.get("http://api.zb.live/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 = 'http://api.zb.live/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 Name Type Value Range
market String Sample:btc_qc
type String 1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
since long After this timestamp
size int Limit of returning data(default 1000, it only returns 1000 data if there are more than 1000 data)

Return ValueDescription
dataKline Content
1472107500000Timestamp
3840.46Open
3843.56high
3839.58low
3843.3Close
492.456Volume
moneyTypeBuy
symbolSell

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.live/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.live/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_) < 1:
            raise Exception("Get markets status failed")

    def order(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignmentorder
accesskey String accesskey
amount float Transaction Amount
currency String Transaction Coin/Pricing Coin
price float unit price
tradeType int Trade Types 1/0[buy/sell]
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds
acctType int Margin 1/0[Margin /Spot](Optional,Default to: 0 Spot)
customerOrderId String Custom 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.)

Return ValueDescription
codeReturn Code
messageHints
idEntrusted Oder 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.live/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 = "http://trade.zb.live/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_) < 1:
            raise Exception("Get markets status failed")

    def orderMoreV2(self, market, type, tradeParams):
        MyUrl = 'https://trade.zb.live/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 = http://trade.zb.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentorderMoreV2
accesskey String accesskey
market String Transaction Coin/Pricing Coin
tradeParams String Trade parameter, array format [[price, Amount],[price, Amount]], Up to 20
tradeType int Trade Types 1/0[buy/sell]
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds
acctType int Margin 1/0[Margin /Spot](Optional Parameters,Default to: 0 Spot)

Return ValueDescription
codeReturn Code
messageHints
dataOrder Number id array

Cancel Order

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentcancelOrder
accesskey String accesskey
currency String Transaction Coin/Pricing Coin
id long Entrusted Oder No.
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds
customerOrderId String Custom ID(4-36 characters, numbers or letters, only one of customerOrderId and id can be filled in)

Return ValueDescription
codeReturn Code
messageHints
idEntrusted Oder No.

Get Entrusted Order

Get single buy order or sell order

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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,
}


Parameter Name Type Value Range
method String Direct AssignmentgetOrder
accesskey String accesskey
id long Entrusted Oder No.
currency String Transaction Coin/Pricing Coin
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds
customerOrderId String Custom ID(4-36 characters, numbers or letters, only one of customerOrderId and id can be filled in)

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
typeOrder Type1/0[buy/sell]

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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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
    }...
]


Parameter Name Type Value Range
method String Direct AssignmentgetOrders
accesskey String accesskey
tradeType int Trade Types 1/0[buy/sell]
currency String Transaction Coin/Pricing Coin
pageIndex int Current Page
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
typeOrder Type1/0[buy/sell]

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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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
    }...
]


Parameter Name Type Value Range
method String Direct AssignmentgetOrdersIgnoreTradeType
accesskey String accesskey
currency String Transaction Coin/Pricing Coin
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
typeOrder Type1/0[buy/sell]

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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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
    }...
]


Parameter Name Type Value Range
method String Direct AssignmentgetUnfinishedOrdersIgnoreTradeType
accesskey String accesskey
currency String Transaction Coin/Pricing Coin
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un ))
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
typeOrder Type1/0[buy/sell]

Get User Info

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentgetAccountInfo
accesskey String accesskey
sign String Request Encrypted Signature String
reqTime long Current 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
keyCoinType
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 withdrawal
canLoanIs it available to invest
Privilege
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 deposit address

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentgetUserAddress
accesskey String accesskey
currency String CoinType
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
key Address

Get multiple chain deposit address

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentgetPayinAddress
accesskey String accesskey
currency String CoinType
sign String Request Encrypted Signature String
reqTime long Current 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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentgetWithdrawAddress
accesskey String accesskey
currency String CoinType
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
key Address

Get withdrawal records

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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"
                }...
            ],
            "pageIndex": 1,
            "pageSize": 10,
            "totalCount": 4,
            "totalPage": 1
        }
    }
}


Parameter Name Type Value Range
method String Direct AssignmentgetWithdrawRecord
accesskey String accesskey
currency String CoinType
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
amountWithdrawal Amount
feesNetwork Fee
idWithdrawal Recordid
manageTimeTimestamp for withdrawal processing time
statusWithdrawal Status(0SUMBIT ,1Failed ,2Successful ,3Cancel ,5Confirmed)
submitTimeTimestamp for withdrawal submit time
toAddressReceiving Address

Get deposit records

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct AssignmentgetChargeRecord
accesskey String accesskey
currency String CoinType
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current 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,1Yes 0No
statusStatus (0Pending Confirm,1Fail to deposit,2Deposit Success)
submit_timeDeposit Time
addressWallet Address

Withdrawal

Request Sample


// request demo
GET https://trade.zb.live/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= Address
string&safePwd=123456bb";
	//sign encrypted by HmacMD5 and get:a2d96def2e570e2f0567fe2c0ee73d78
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/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.live/api/withdraw'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr= Address
string&safePwd=123456bb'
        params = 'accesskey=' + self._access_key_ + '&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr= Address
string&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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
accesskey String accesskey
amount float Withdrawal Amount
currency String CoinType
fees float Network Fee
itransfer int Agree or not?bitbankInternal transfer(0Disagree,1Agree,Default Disagree)
method String Direct Assignmentwithdraw
receiveAddr String Receive Address (It needs to be the verified address,btsif it's,use"Account _Remark "format)
safePwd String Transaction Password
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idWithdrawal Recordid

Sub-account

Create Sub-account

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
memo String Remark
password String Password
subUserName String Sub-account Username(not more than6 digits or letters)
accesskey String accesskey
reqTime Long Current time in milliseconds
sign String Signature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not

Get Sub-account List

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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": "[email protected]",
      "userId": 123456,
      "isFreez": false
    },
    {
      "isOpenApi": false,
      "memo": "2",
      "userName": "[email protected]",
      "userId": 132456,
      "isFreez": false
    }
  ]
}


Parameter Name Type Value Range
accesskey String accesskey
reqTime Long Current time in milliseconds
sign String Signature

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.live/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&[email protected]";
	//sign encrypted by HmacMD5 and get:0d109b7d008c924041d10cf5706b2fce
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/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.live/api/doTransferFunds'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&[email protected]&method=doTransferFunds&[email protected]'
        params = 'accesskey=' + self._access_key_ + '&amount=1&currency=doge&[email protected]&method=doTransferFunds&[email protected]'
        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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
amount Double Amount
currency String CoinType
fromUserName String Transferor Username
toUserName String Receiver Username
accesskey String accesskey
reqTime Long Current time in milliseconds
sign String Signature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not

Create Sub-account API

Request Sample


// request demo
https://trade.zb.live/api/createSubUserKey?accesskey=youraccesskey&assetPerm=true&entrustPerm=true&method=createSubUserKey&keyName=xxx≤verPerm=true&moneyPerm=true&toUserId=xxx&sign=Request Encrypted Signature String&reqTime=Current time in milliseconds



// java demo
public void createSubUserKey() {
	//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&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&toUserId=1325607";
	//sign encrypted by HmacMD5 and get:b49ea1f5b9930bffc60d3f0dba0163e1
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/api/createSubUserKey?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&reqTime=1539942326089&sign=b49ea1f5b9930bffc60d3f0dba0163e1&toUserId=1325607";
	//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 createSubUserKey(self, market, type, amount, price):
        MyUrl = 'https://trade.zb.live/api/createSubUserKey'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&toUserId=1325607'
        params = 'accesskey=' + self._access_key_ + '&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&toUserId=1325607'
        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 = b49ea1f5b9930bffc60d3f0dba0163e1
            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.live/api/createSubUserKey?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&reqTime=1540295995608&sign=b49ea1f5b9930bffc60d3f0dba0163e1&toUserId=1325607
            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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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": {
    "apiKey": "xxxx",
    "apiSecret": "xxxxx"
  }
}


Parameter Name Type Value Range
assetPerm Boolean Inquiry Assets Permission(Boolean Value)true or false
entrustPerm Boolean Permission of entrusted transaction(Boolean Value)true or false
keyName String Name
toUserId Long Sub-accountId
leverPerm Boolean Margin Permission(Boolean Value)true or false
moneyPerm Boolean Deposit and Withdrawal Permission(Boolean Value)true or false
accesskey String accesskey
reqTime Long Current time in milliseconds
sign String Signature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not
apiKeyapiKey
apiSecretapiSecret

Margin

Get User's Margin Info

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment getLeverAssetsInfo
accesskey String accesskey
sign String Request Encrypted Signature String
reqTime long Current 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
fLoanInPending Borrow
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
repayLeverShowRisk Rate

Get Margin Records

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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" : "LTCAmount
",
			"id"            : 609,
			"downTableDate" : 1520092800000,
			"marketName"    : "ltcusdt",
			"avgPrice"      : 0,
			"userId"        : 110803,
			"coinBalance"   : 500.00000000,
			"entrustId"     : 0
		}
	]
}


Parameter Name Type Value Range
method String Direct Assignment getLeverBills
accesskey String accesskey
coin String CoinType
dataType int Data Type[0/1](Data in 30 days/Data over 30 days)
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idHistory ID
userId User ID
dateRecords generate time
typeType of Records
billTypeValueRecords Type in Chinese
changeCoinChangesCOINQuantity
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
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment transferInLever
accesskey String accesskey
coin String CoinType
marketName String Market Name
amount double Transfer-in Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Transfer funds out from Margin Account

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment transferOutLever
accesskey String accesskey
coin String CoinType
marketName String Market Name
amount double Transfer-out Amount,The decimal places cannot exceed8,Exceed the system automatically intercepts8Bit
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Release Investment

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment loan
accesskey String accesskey
coin String CoinType
amount double Investment Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDay double Daily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDay int Lending Days [10/20/30]
isLoop boolean Auto Invest(On/Off) [1/0]
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idInvestment ID

Cancel investment

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment cancelLoan
accesskey String accesskey
loanId String Investment ID
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Get the available borrowing list

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment getLoans
accesskey String accesskey
coin String CoinType
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
amountQuantity
balanceAvailable
coinNameCoinType
repaymentDayBorrow Period
interestRateOfDayDaily Interest Rate

Get Lending Records

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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"           : "Pending Repay",
			"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 Name Type Value Range
method String Direct Assignment getLoanRecords
accesskey String accesskey
loanId String Investment id(Transfer if lending Do not transfer if borrowing)
marketName String Market
status int Status (1Pending Repay 2Repaid 3 Need to Liquidate 4 Liquidate Repay 5Automatically repaying 6Auto Repay)
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idLending RecordsID
loanIdInvestment ID
inUserIdBorrowerID
inUserNameBorrower's username
outUserIdLenderID
outUserNameLender's username
fundTypeCoin Type
amountBorrowed Amount
statusStatus 1Pending Repay 2Repaid 3Need to Liquidate 4 Liquidate Repay 5Auto Repay
createTimeBorrow Time
rewardReward Amount
balanceAmountAvailable Amount
rateInterest Rate
hasRepayRepaid Capital Amount
hasLxReoaid 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
repayDateRepay Deadline
marketNameMarket
fwfScaleService Fee
investMarkAutomatically Renew
sourceTypeSource Type: 8”Website”,5”Phone NumberAPP”,6”InterfaceAPI”

Borrow

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment borrow
accesskey String accesskey
marketName String Margin Market
coin String CoinType
amount double Borrowed Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDay double Daily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDay int Borrow Period [10/20/30]Days
isLoop int Borrowers Automatic Renew [1/0](Automatic renewal at maturity/Automatic repay at maturity)
sign String Request Encrypted Signature String
reqTime long Current 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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment autoBorrow
accesskey String accesskey
marketName String Margin Market
coin String CoinType
amount double Borrowed Amount,The decimal places cannot exceed4,Exceed the system automatically intercepts4Bit
interestRateOfDay double Daily Interest Rate [0.05-0.2] Percentage,The decimal places cannot exceed3,Exceed the system automatically intercepts3Bit
repaymentDay int Borrow Period [10/20/30]Days
safePwd String Transaction Password
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Repay

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment repay
accesskey String accesskey
loanRecordId String Lending Recordsid
repayAmount double Repayment Amount
repayType int Repayment Mode [0/1](All /Part)
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Fast Repayment

Repay all outstanding borrowing

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment doAllRepay
accesskey String accesskey
marketName String Margin Market, Sample:btcqc
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Get repayment records

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment getRepayments
accesskey String accesskey
loanRecordId String Lending Recordsid
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current 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.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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"        : "Invest Balance",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
	]
}


Parameter Name Type Value Range
method String Direct Assignment getFinanceRecords
accesskey String accesskey
coin String CoinType
pageIndex int Current Page
pageSize int Amount
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
idInvestment ID
userId User ID
userNameUsername
fundTypeCoin Type
coinNameCoin Name
amountInvestment Amount
hasAmountLended Amount
statusStatus Value
statusShowStatus Value in Chinese
createTimePublish Time
interestRateOfDayDaily Interest Rate
repaymentDayLending Days
isLoopAuto Invest(On/Off)
inTimesThe investment being borrowed
sourceTypeSource Type: 8”Website”,5”Phone NumberAPP”,6”InterfaceAPI”

Change to automatically renew or not

Request Sample


// request demo
GET https://trade.zb.live/api/changeInvestMark?accesskey=youraccesskey&investMark=1&loanRecordId=Loanid&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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment changeInvestMark
accesskey String accesskey
investMark int Renew Type[0/1](Non-automated/Automatically Renew)
loanRecordId String LoanId,Multiple by English‘,’divided
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Change to automatically lend or not

Request Sample


// request demo
GET https://trade.zb.live/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.live/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.live/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.live/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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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 Name Type Value Range
method String Direct Assignment changeLoop
accesskey String accesskey
isLoop int Lend Type[0/1](Non-automated/Automatically Lend)
loanId String Lendid
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Event

Get users‘ asset of Advanced Account

Request Sample


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


// java demo
public void getAsset() {
	//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=getAsset";
	//sign encrypted by HmacMD5 and get:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/api/getAsset?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAsset&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 getAsset(self):
        MyUrl = 'https://trade.zb.live/api/getAsset'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAsset'
        params = 'accesskey=' + self._access_key_ + '&method=getAsset'
        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.live/api/getAsset?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAsset&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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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": "Successful."
    "data": {
    	"coins": [
    		{
    			"esAmount": null, 
    			"fundstype": 15, 
    			"freez": "10.184", 
    			"esFreeze": null, 
    			"available": 136.92738, 
    			"key": "qc", 
    			"cnName": "QC", 
    			"enName": "QC", 
    			"showName": "QC", 
    			"unitTag": "QC", 
    			"unitDecimal": 8, 
    			"isCanRecharge": true, 
    			"isCanWithdraw": true, 
    			"canLoan": false, 
       	}
    	]
    }
}


Parameter Name Type Value Range
method String Direct Assignment getAsset
accesskey String accesskey
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints
fundstypeCoin ID
availableAvailable balance
keyCoin Name
cnNameChinese Name
enNameEnglish Name
showNameThe displayed Name
unitTagUnit symbol
unitDecimalThe displayed decimals
isCanRechargeWhether open deposit
isCanWithdrawWhether open withdrawal
canLoanIs it available to invest

Transfer-in funds to Advanced Market

Request Sample


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


// java demo
public void transferInActArea() {
	//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=transferInActArea";
	//sign encrypted by HmacMD5 and get:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/api/transferInActArea?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=transferInActArea&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 transferInActArea(self):
        MyUrl = 'https://trade.zb.live/api/transferInActArea'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAsset'
        params = 'accesskey=' + self._access_key_ + '&method=getAsset'
        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.live/api/transferInActArea?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=transferInActArea&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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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": "Successful."
}


Parameter Name Type Value Range
method String Direct Assignment transferInActArea
accesskey String accesskey
amount String Transfer-in Amount
currency String Name of transfer-in currency
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

Transfer-out funds from Advanced Market

Request Sample


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


// java demo
public void transferOutActArea() {
	//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=transferOutActArea";
	//sign encrypted by HmacMD5 and get:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//the final sent requesturl
	String finalUrl = "https://trade.zb.live/api/getAsset?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=transferOutActArea&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 transferOutActArea(self):
        MyUrl = 'https://trade.zb.live/api/transferOutActArea'
        #params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=transferOutActArea'
        params = 'accesskey=' + self._access_key_ + '&method=transferOutActArea'
        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.live/api/getAsset?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAsset&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, lenght, fill_byte):
        if len(value) >= lenght:
            return value
        else:
            fill_size = lenght - 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": "Successful."
}


Parameter Name Type Value Range
method String Direct Assignment transferOutActArea
accesskey String accesskey
amount BigDecimal Transfer-in Amount
currency String Name of transfer-in currency
sign String Request Encrypted Signature String
reqTime long Current time in milliseconds

Return ValueDescription
codeReturn Code
messageHints

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.。

WebSocketService Address

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

Sample Code

It currently supports C, JAVA, Python versions, and more language versions will be supported in succession. If you have any question, please contact at [email protected] for support.。

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.live/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,
            "priceScale":2
            },
        "bcc_usdt":{
            "amountScale":3
            ,"priceScale":2
            }
        }
        ...
    },
    "success":true,
    "channel":"markets",
    "message":"Success。"
}


Parameter Name Type Value Range
event String Direct AssignmentaddChannel
channel String markets

Return ValueDescription
priceScaleDecimal Places of Price
amountScaleDecimal Places of Amount

WSMarkets

ObtaintickerData

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.live/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",
        "vol": "90151.83"
    }
}


Parameter Name Type Value Range
event String Direct AssignmentaddChannel
channel String zbqc_ticker

Return ValueDescription
dateServer time of returning data
high24h High
low24h Low
buyBuy 1
sellSell 1
lastLatest Price
volVolume (Latest 24Hours)
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.live/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 Name Type Value Range
event String Direct AssignmentaddChannel
channel String ltcbtc_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.live/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 Name Type Value Range
event String Direct AssignmentaddChannel
channel String ltcbtc_trades

Return ValueDescription
dateTransaction Time
pricePrice
amountTransaction Amount
tidGenerate TransactionID
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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
amount float Transaction Amount
channel String Transaction Coin/Pricing Coin_order(btcusdt_order)
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
price float unit price
tradeType int Trade Types 1/0[buy/sell]
acctType int Whether margin 1.Margin /0.Spot,Default to0.Spot
sign String Request Encrypted Signature String

Return ValueDescription
codeReturn Code
messageHints
entrustIdEntrusted Oder No.
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String Transaction Coin/Pricing Coin_cancelorder(btcusdt_cancelorder)
event String Direct AssignmentaddChannel
id long Orderid
no String The unique identity of the request used to distinguish content when it is returned
sign String Request Encrypted Signature String

Return ValueDescription
codeReturn Code
messageHints
entrustIdEntrusted Oder No.
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String Transaction Coin/Pricing Coin_getorder(btcusdt_getorder)
event String Direct AssignmentaddChannel
id long Entrusted Oder No.
no String The unique identity of the request used to distinguish content when it is returned
sign String Request Encrypted Signature String

Return ValueDescription
idEntrusted Oder No.
currencyTrade Types
trade_amountTrading Amount
trade_moneyTrading Volume
total_amountOrder Amount
trade_dateDate
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String Transaction Coin/Pricing Coin_getorders(btcusdt_getorders)
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
pageIndex int Current Page
tradeType int Trade Types 1/0[buy/sell]

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
typeOrder Type 1/0[buy/sell]
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String Transaction Coin/Pricing Coin_getordersignoretradetype(btcusdt_getordersignoretradetype)
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
pageIndex int Current Page
pageSize int Amount

Return ValueDescription
currencyTrade Types
idEntrusted Oder No.
priceunit price
statusOrder status:(1. Cancel, 2. Finish/Cancel the order after partial finish, 3. Pending orders/Un )
total_amountOrder Amount
trade_amountTrading Amount
trade_dateDate
trade_moneyTrading Volume
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String getaccountinfo
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

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
keyCoinType
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String addSubUser
event String Direct AssignmentaddChannel
memo String Remark
password String Password
subUserName String Sub-account Username(not more than6 digits or letters)
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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": "[email protected]",
		"userId": 110980,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "2",
		"userName": "[email protected]",
		"userId": 110984,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "test3",
		"userName": "[email protected]",
		"userId": 111014,
		"isFreez": false
	}]",
	"no": "0"
}


Parameter Name Type Value Range
accesskey String accesskey
channel String getSubUserList
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String doTransferFunds
event String Direct AssignmentaddChannel
amount String Amount
currency String CoinType
fromUserName String Transferor Username
toUserName String Receiver Username
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned

Create Sub-account API

Request Sample


// request demo
{
	"accesskey": "ceb1569d-7c17-487a-b4a1-10bf2a8d925d",
	"assetPerm": "true",
	"channel": "createSubUserKey",
	"entrustPerm": "true",
	"event": "addChannel",
	"keyName": "xxxx",
	"leverPerm": "true",
	"moneyPerm": "true",
	"toUserId": "xxx",
	"sign": "Signature"
}



// java demo
public void createSubUserKey() {
	//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","assetPerm":"true","channel":"createSubUserKey","entrustPerm":"true","event":"addChannel","keyName":"xxxxx","leverPerm":"xxx","moneyPerm":"true","no":"test001","toUserId":"xxx"}";
	//sign encrypted by HmacMD5 and get:e961b173f88acf4676b57f065374a65d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//Finally send request to the serve parameter json
	String json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","assetPerm":"true","channel":"createSubUserKey","entrustPerm":"true","event":"addChannel","keyName":"xxxxx","leverPerm":"xxx","moneyPerm":"true","no":"test001","sign":"e961b173f88acf4676b57f065374a65d","toUserId":"xxx"}";
	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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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","assetPerm":"true","channel":"createSubUserKey","entrustPerm":"true","event":"addChannel","keyName":"xxxxx","leverPerm":"xxx","moneyPerm":"true","no":"test001","toUserId":"xxx"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e961b173f88acf4676b57f065374a65d
        return self.__hmacSign( paramsStr, SHA_secret)

    #----------------------------------------------------------------------
    def createSubUserKey(self, symbol_pair, type_, price, amount):
        json = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","assetPerm":"true","channel":"createSubUserKey","entrustPerm":"true","event":"addChannel","keyName":"xxxxx","leverPerm":"xxx","moneyPerm":"true","no":"test001","sign":"e961b173f88acf4676b57f065374a65d","toUserId":"xxx"}";
        try:
            self.ws_sub_spot.send(json)
        except websocket.WebSocketConnectionClosedException:
            pass 


Request Reply Sample


// Return Result
{
	"success": true,
	"code": 1000,
	"channel": "createSubUserKey",
	"message": "{"apiKey ":"41 bf75f9 - 525e-4876 - 8257 - b880a938d4d2 ","apiSecret ":"046 b4706fe88b5728991274962d7fc46b4779c0c"}",
	"no": "0"
}


Parameter Name Type Value Range
accesskey String accesskey
channel String createSubUserKey
event String Direct AssignmentaddChannel
assetPerm Boolean Inquiry Assets Permission(Boolean Value)true or false
entrustPerm Boolean Permission of entrusted transaction(Boolean Value)true or false
keyName String Name
leverPerm Boolean Margin Permission(Boolean Value)true or false
moneyPerm String Deposit and Withdrawal Permission(Boolean Value)true or false
toUserId String Sub-Account ID
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
apiKeyapiKey
apiSecretapiSecret

WSMargin

Get User's Margin Info

Request Sample


// request demo
{
	'accesskey':'your key',
	'channel':'getuserLeverAsset',
	'event':'addChannel',
	'no' : The unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String getuserLeverAsset
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
codeReturn Code
desHints
isSucSuccess or not
fLoanInPending Borrow
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
repayLeverShowRisk Rate

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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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":"lend
QC",
      "id":898,
      "downTableDate":1520697600000,
      "marketName":"btsqc",
      "avgPrice":0,
      "userId":110803,
      "coinBalance":2200,
      "entrustId":0
    },
    ...
  ],
  "channel":"getLeverBills",
  "message":"Success",
  "no":"0"
}


Parameter Name Type Value Range
accesskey String accesskey
channel String getLeverBills
event String Direct AssignmentaddChannel
coin String CoinType
pageIndex int Current Page
pageSize int Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
idHistory ID
userId User ID
dateRecords generate time
typeType of Records
billTypeValueRecords Type in Chinese
changeCoinChangesCOINQuantity
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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String transferInLever
event String Direct AssignmentaddChannel
coin String CoinType
marketName String Market
amount Double Transfer-in Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String transferOutLever
event String Direct AssignmentaddChannel
coin String CoinType
marketName String Market
amount Double Transfer-out Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String loan
event String Direct AssignmentaddChannel
coin String CoinType
amount Double Investment Amount
interestRateOfDay Double Daily Interest Rate [0.05-0.2]%
repaymentDay int Lending Days [10/20/30]
isLoop int Auto Invest(On/Off) [1/0]
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
data
loanIdInvestment ID

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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String cancelLoan
event String Direct AssignmentaddChannel
loanId Long Investment ID
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String getLoans
event String Direct AssignmentaddChannel
coin String CoinType
pageIndex int Current Page
pageSize int Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
amountQuantity
balanceAvailable
coinNameCoinType
repaymentDayBorrow 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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":"Pending Repay",
      "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 Name Type Value Range
accesskey String accesskey
channel String getLoanRecords
event String Direct AssignmentaddChannel
loanId Long Investment id(Transfer if lending Do not transfer if borrowing)
marketName String Market
status int Status (1Pending Repay 2Repaid 3 Need to Liquidate 4 Liquidate Repay 5Automatically repaying 6Auto Repay)
pageIndex int Current Page
pageSize int Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
idLending RecordsID
loanIdInvestment ID
inUserIdBorrowerID
inUserNameBorrower's username
outUserIdLenderID
outUserNameLender's username
fundTypeCoin Type
amountBorrowed Amount
statusStatus 1Pending Repay 2Repaid 3Need to Liquidate 4 Liquidate Repay 5Auto Repay
createTimeBorrow Time
rewardReward Amount
balanceAmountAvailable Amount
rateInterest Rate
hasRepayRepaid Capital Amount
hasLxReoaid 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
repayDateRepay Deadline
marketNameMarket
fwfScaleService Fee
investMarkAutomatically Renew
sourceTypeSource Type: 8”Website”,5”Phone NumberAPP”,6”InterfaceAPI”

Borrow

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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String borrow
event String Direct AssignmentaddChannel
marketName String Margin Market
coin String CoinType
amount Double Borrowed Amount
interestRateOfDay Double Daily Interest Rate [0.05-0.2]%
repaymentDay int Borrow Period [10/20/30]Days
isLoop int Borrowers Automatic Renew [1/0](Automatic renewal at maturity/Automatic repay at maturity)
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned

Repay

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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String repay
event String Direct AssignmentaddChannel
loanRecordId Long Lending Recordsid
repayAmount Double Repayment Amount
repayType int Repayment Mode [0/1](All /Part)
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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 Name Type Value Range
accesskey String accesskey
channel String getRepayments
event String Direct AssignmentaddChannel
loanRecordId Long Lending Recordsid
pageIndex int Current Page
pageSize int Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request 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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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"        : "Invest Balance",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
  ],
  "channel":"getFinanceRecords",
  "message":"Success",
  "no":"0"
}


Parameter Name Type Value Range
accesskey String accesskey
channel String getFinanceRecords
event String Direct AssignmentaddChannel
coin STirng CoinType
pageIndex int Current Page
pageSize int Amount
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
idInvestment ID
userId User ID
userNameUsername
fundTypeCoin Type
coinNameCoin Name
amountInvestment Amount
hasAmountLended Amount
statusStatus Value
statusShowStatus Value in Chinese
createTimePublish Time
interestRateOfDayDaily Interest Rate
repaymentDayLending Days
isLoopAuto Invest(On/Off)
inTimesThe investment being borrowed
sourceTypeSource Type: 8”Website”,5”Phone NumberAPP”,6”InterfaceAPI”

WSEvent

Get users‘ asset of Advanced Account

Request Sample


// request demo
{
    "accesskey": "your accesskey",
    "channel": "getSparkUserAsset",
    "event": "addChannel",
    "no": "The unique identity of the request used to distinguish content when it is returned",
    "sign":Signature
}



// java demo
public void getSparkUserAsset() {
	//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":"getSparkUserAsset","event":"addChannel","no":"test001"}";
	//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":"getSparkUserAsset","event":"addChannel","no":"test001","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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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":"getSparkUserAsset","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e950df0cff23a392fb738c8eeb2ef9dc
        return self.__hmacSign( paramsStr, SHA_secret)

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


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "data":[
		{
			"fundstype": 15,
			"freez": 10.184,
			"available": 136.92738,
			"key": qc,
			"cnName": "QC",
			"enName": "QC",
			"showName": "QC",
			"unitTag": "QC",
			"unitDecimal": 8,
			"isCanRecharge": true,
			"isCanWithdraw": true,
			"canLoan": false,
		}
  ],
  "channel":"getSparkUserAsset",
  "message":"Success",
  "no":"0test001"
}


Parameter Name Type Value Range
accesskey String accesskey
channel String getSparkUserAsset
event String Direct AssignmentaddChannel
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned
fundstypeCoinType ID
availableAvailable balance
keyCoin Name
cnNameChinese Name
enNameEnglish Name
showNameThe displayed Name
unitTagUnit symbol
unitDecimalThe displayed decimals
isCanRechargeWhether open deposit
isCanWithdrawWhether open withdrawal
canLoanIs it available to invest

Transfer-in funds to Advanced Account

Request Sample


// request demo
{
    "accesskey": "your accesskey",
    "amount": "Transfer-in Amount",
    "channel": "transferInSpark",
    "currency": "Name of transfer-in currency",
    "event": "addChannel",
    "no": "The unique identity of the request used to distinguish content when it is returned",
    "sign":Signature
}



// java demo
public void transferInSpark() {
	//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":"10.5","channel":"transferInSpark","currency":"qc","event":"addChannel","no":"test001"}";
	//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","amount":"10.5","channel":"transferInSpark","currency":"qc","event":"addChannel","no":"test001","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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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":"10.5","channel":"transferInSpark","currency":"qc","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e950df0cff23a392fb738c8eeb2ef9dc
        return self.__hmacSign( paramsStr, SHA_secret)

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


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"transferInSpark",
  "message":"Success",
  "no":"0"
}


Parameter Name Type Value Range
accesskey String accesskey
amount STirng Transfer-in Amount
channel String transferInSpark
event String Direct AssignmentaddChannel
currency STirng Name of transfer-in currency
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned

Transfer-out funds from Advanced Account

Request Sample


{
    "accesskey": "your accesskey",
    "amount": "Transfer-out Amount",
    "channel": "transferInSpark",
    "currency": "Name of transfer-out currency",
    "event": "addChannel",
    "no": "The unique identity of the request used to distinguish content when it is returned",
    "sign":Signature
}



// java demo
public void transferOutSpark() {
	//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":"10.5","channel":"transferOutSpark","currency":"qc","event":"addChannel","no":"test001"}";
	//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","amount":"10.5","channel":"transferOutSpark","currency":"qc","event":"addChannel","no":"test001","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.live/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, lenght, fillByte):
        if len(value) >= lenght:
            return value
        else:
            fillSize = lenght - 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":"10.5","channel":"transferOutSpark","currency":"qc","event":"addChannel","no":"test001"}
        #secretKey After encrypting:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #Work out sign: e950df0cff23a392fb738c8eeb2ef9dc
        return self.__hmacSign( paramsStr, SHA_secret)

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


Request Reply Sample


// Return Result
{
  "success":true,
  "code":1000,
  "channel":"transferOutSpark",
  "message":"Success",
  "no":"test001"
}


Parameter Name Type Value Range
accesskey String accesskey
amount STirng Transfer-out Amount
channel String transferOutSpark
event String Direct AssignmentaddChannel
currency STirng Name of transfer-out currency
no String The unique identity of the request used to distinguish content when it is returned
sign String Signature

Return ValueDescription
successSuccess or not
codeReturn Code
messageHints
channelRequested Channel
noThe unique identity of the request used to distinguish content when it is returned

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:accesskey=08b38d11-445f-447f-9372-d255e10b91bd&method=getAccountInfo
  • For each interface example, all parameters (except sign and reqTime) after the interface '?' Need to be calculated as clear text.
  • UsesecretKeyPasssha1Encrypted String:5b1f87b2375ad8e46abf5e8ac4577c50dcee7989 as hash
  • Calculate and get to the finalsign: 48a1af2ea626dde38134ff8a51d8d0c3 Enter description for the picture

FAQ

  1. OpenAPI?

    • 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. How to deal with the API common error access timeout?

    • Bind hosts file, please bind as shown in API binding file or manually bind. If it is timeout after bingding with the domestic server, please use VPN.
    • 47.91.169.147 api.zb.com
    • 52.55.212 trade.zb.com
    • windowsSystemC:\Windows\System32\drivers\etc\hosts
    • mac/linuxSystem /etc/hosts
  4. Why 1003 error?

    • Check whether encryption is sorted by ASCII value and whether encryption parameters are missing or have redundant character concatenation, etc。
  5. It prompts 1002 error invalid parameter
    • Invalid transfer parameter
  6. Can K Line chart obtain the data of months or a year ago?
    • The system only provides up to 1000 Kline data. If you want to obtain data of a longer time, you can use the unit of hour or day.
  7. Does the API need to binding 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 that 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
  8. Does API support random withdrawal?

    • No, only the verified withdrawal address can withdrawal via API.
    • It is required to provide transaction password when withdrawal via API
  9. 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
  10. qcDoes QC is CNY

    • No, it isn't. QC is 1:1 to CNY in value
  11. 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
1000 The call is successful.
1001 General error prompt
1002 Internal Error
1003 Fail to verify
1004 The transaction password is locked
1005 Wrong transaction password, please check it and re-enter。
1006 Real-name authentication is pending approval or unapproved
1009 This interface is under maintenance
1010 Not available now
1012 Insufficient permissions
1013 Cannot trade, please contact at [email protected] for support.
1014 Cannot sell during the pre-sale period
2001 Insufficient CNY account balance
2002 Insufficient BTC account balance
2003 Insufficient LTC account balance
2005 Insufficient ETH account balance
2006 ETCInsufficient account balance
2007 BTSInsufficient account balance
2008 EOSInsufficient account balance
2009 BCCInsufficient account balance
3001 Order not found or is completed
3002 Invalid amount
3003 Invalid quantity
3004 User does not exist
3005 Invalid parameter
3006 Invalid IP or not consistent with the bound IP
3007 The request time has expired
3008 Transaction not found
3009 The price exceeds the limit
3010 It fails to place an order, due to you have set up to prohibit trading of this market
3011 The entrustment price exceeds the limit, please reset a price!
4001 APIInterface is locked or not enable
4002 Request too frequently

websocketReturn Code

Return CodeDescription
1000 The call is successful.
1001 General error prompt
1002 Internal Error
1003 Fail to verify
1004 The transaction password is locked
1005 Wrong transaction password, please check it and re-enter。
1006 Real-name authentication is pending approval or unapproved
1009 This interface is under maintenance
1010 Not available now
1012 Insufficient permissions
1013 Cannot trade, please contact at [email protected] for support.
1014 Cannot sell during the pre-sale period
2001 Insufficient CNY account balance
2002 Insufficient BTC account balance
2003 Insufficient LTC account balance
2005 Insufficient ETH account balance
2006 ETCInsufficient account balance
2007 BTSInsufficient account balance
2008 EOSInsufficient account balance
2009 BCCInsufficient account balance
3001 Order not found or is completed
3002 Invalid amount
3003 Invalid quantity
3004 User does not exist
3005 Invalid parameter
3006 Invalid IP or not consistent with the bound IP
3007 The request time has expired
3008 Transaction not found
3009 The price exceeds the limit
3010 It fails to place an order, due to you have set up to prohibit trading of this market
3011 The entrustment price exceeds the limit, please reset a price!
4001 APIInterface is locked or not enable
4002 Request too frequently