入门

API介绍

欢迎使用ZB开发者文档。此文档为用户提供了一套简单而又强大的开发工具,皆在帮助用户快速、高效的将ZB交易功能整合到自己的应用当中。

ZBAPI接口是提供服务的基础,API分为四大类、交易、行情、杠杆,子账号。开发者在ZB网站创建账号后,可根据自身需求建立不同权限的API,并利用API进行自动交易或提现。

其中交易、行情、杠杆、子账号均需要验签

API接口说明

ZB为用户提供了两种调用接口的方式,分别为:Rest和websocket,开发者可根据自身需求来选择适合自己的方式查询行情,进行交易等

REST API说明

REST,即Representational State Transfer的缩写,是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,正得到越来越多网站的采用。其优点如下:

在RESTful架构中,每一个URL代表一种资源;

客户端和服务器之间,传递这种资源的某种表现层;

客户端通过四个HTTP指令,对服务器端资源进行操作,实现"表现层状态转化"。

建议开发者使用REST API进行币币交易或者资产提现等操作。

WebSocket API

WebSocket是HTML5一种新的协议Protocol。它实现了客户端与服务器全双工通信,使得数据可以快速地双向传播。通过一次简单的握手就可以建立客户端和服务器连接,服务器根据业务规则可以主动推送信息给客户端。其优点如下:

客户端和服务器进行数据传输时,请求头信息比较小,大概2个字节;

客户端和服务器皆可以主动地发送数据给对方;

不需要多次创建TCP请求和销毁,节约宽带和服务器的资源。

强烈建议开发者使用WebSocket API获取市场行情和买卖深度等信息。

Rest API

请务必设置user agent为 '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为用户提供了一个简单的而又强大的API,旨在帮助用户快速高效的将ZB交易功能整合到自己应用当中。 目前支持C、JAVA、Python版本。其他语言版本会相继支持。如果在使用过程中有任何问题请联系我们API技术QQ群:764113552,我们将在第一时间帮您解决技术问题。

示例代码

签名方式:先用sha加密secretkey,然后根据加密过的secretkey把请求的参数签名,请求参数按照ascii值排序加密,通过md5填充16位加密

github 示例代码

访问限制

1.针对交易API和杠杆API,单个IP限制每分钟1000次访问,超过1000次将被锁定1小时,一小时后自动解锁。

2.针对交易API和杠杆API,单个用户限制每秒钟30次访问,一秒钟内30次以上的请求,将会视作无效。

3.K线接口每秒只能请求一次数据。

配置

获取市场配置

获取已开启的市场信息,包括价格、数量小数点位数

请求示例


// request demo
GET http://api.zb.cn/data/v1/markets



// java demo
public void getMarkets() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/markets'
    return self.get(url)


响应示例


// 返回结果
{
    "btc_usdt": {
        "amountScale": 4,
        "priceScale": 2
    }
}


返回值描述
priceScale价格小数位数
amountScale数量小数位数

行情

获取allTicker数据

获取全币种行情

请求示例


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



// java demo
public void getAllTicker() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/allTicker'
    return self.get(url)


响应示例


// 返回结果
{
    "hpybtc":{
		"vol":"19800.6",
		"last":"0.00000237",
		"sell":"0.000002366",
		"buy":"0.00000236",
		"high":"0.0000026552",
		"low":"0.00000229"
	},
	"tvqc":{
		"vol":"2201510.1",
		......
}


返回值描述
high最高价
low最低价
buy买一价
sell卖一价
last最新成交价
vol成交量(最近的24小时)

获取ticker数据

获取单个币种行情

请求示例


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



// java demo
public void getTicker() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/ticker?market=btc_usdt'
    return self.get(url)


响应示例


// 返回结果
{
    "ticker": {
        "vol": "40.463", 
        "last": "0.899999", 
        "sell": "0.5",
        "buy": "0.225", 
        "high": "0.899999", 
        "low": "0.081"
    }, 
    "date": "1507875747359"
}


参数名称 类型 取值范围
market String 例:btc_qc

返回值描述
high最高价
low最低价
buy买一价
sell卖一价
last最新成交价
vol成交量(最近的24小时)

获取市场深度

请求示例


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



// java demo
public void getDepth() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/depth?market=btc_usdt&size=3'
    return self.get(url)


响应示例


// 返回结果
{
    "asks": [
        [
            83.28,
            11.8
        ]...
    ],
    "bids": [
        [
            81.91,
            3.65
        ]...
    ],
    "timestamp" : 时间戳
}


参数名称 类型 取值范围
market String 例:btc_qc
size int 档位1-50,如果有合并深度,只能返回5档深度
merge float 默认深度

返回值描述
asks卖方深度
bids买方深度
timestamp此次深度的产生时间戳

获取历史成交

请求示例


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



// java demo
public void getTrades() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/trades?market=btc_usdt'
    return self.get(url)


响应示例


// 返回结果
[
    {
        "amount": 0.541,
        "date": 1472711925,
        "price": 81.87,
        "tid": 16497097,
        "trade_type": "ask",
        "type": "sell"
    }...
]


参数名称 类型 取值范围
market String 例:btc_qc
since long 从指定交易ID后50条数据

返回值描述
date交易时间(时间戳)
price交易价格
amount交易数量
tid交易生成ID

获取K线

获取K线数据,最多获取最新的1000条

请求示例


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



// java demo
public void getKline() {
	//得到返回结果
	String returnJson = HttpRequest.get("http://api.zb.cn/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.cn/data/v1/kline?market=btc_usdt'
    return self.get(url)


响应示例


// 返回结果
{
    "data": [
        [
            1472107500000,
            3840.46,
            3843.56,
            3839.58,
            3843.3,
            492.456
        ]...
    ],
    "moneyType": "usdt",
    "symbol": "btc"
}


参数名称 类型 取值范围
market String 例:btc_qc
type String 1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
since long 从这个时间戳之后的
size int 返回数据的条数限制(默认为1000,如果返回数据多于1000条,那么只返回1000条)

返回值描述
dataK线内容
1472107500000时间戳
3840.46
3843.56
3839.58
3843.3
492.456交易量
moneyType买入货币
symbol卖出货币

交易

委托下单

现货与杠杆共用此接口,已参数acctType区分

请求示例


// request demo
GET https://trade.zb.cn/api/order?accesskey=youraccesskey&acctType=0&amount=1.502¤cy=qtum_usdt&method=order&price=1.9001&tradeType=1&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void order() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001¤cy=zb_qc&method=order&price=1.0&tradeType=1";
	//sign通过HmacMD5加密得到:a0f18f0f1007433d905272c4c40560b2
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/order?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001¤cy=zb_qc&method=order&price=1.0&reqTime=1539942326046&sign=a0f18f0f1007433d905272c4c40560b2&tradeType=1";
	//取得返回结果json
	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.cn/api/order'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001¤cy=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.cn/api/order?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&acctType=0&amount=0.001¤cy=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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。",
    "id": "20131228361867"
}


参数名称 类型 取值范围
method String 直接赋值order
accesskey String accesskey
price float 单价
amount float 交易数量
tradeType int 交易类型1/0[buy/sell]
currency String 交易币种_计价币种
sign String 请求加密签名串
reqTime long 当前时间毫秒数
acctType int 杠杆 1/0[杠杆/现货](可选参数,默认为: 0 现货)

返回值描述
code返回代码
message提示信息
id委托挂单号

取消委托

请求示例


// request demo
GET https://trade.zb.cn/api/cancelOrder?accesskey=youraccesskey¤cy=zb_qc&id=201710111625&method=cancelOrder&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void cancelOrder() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&id=20180522105585216&method=cancelOrder";
	//sign通过HmacMD5加密得到:a435f4bddfedb50877587ae1acff1c35
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/cancelOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&id=20180522105585216&method=cancelOrder&reqTime=1539942326052&sign=a435f4bddfedb50877587ae1acff1c35";
	//取得返回结果json
	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.cn/api/cancelOrder'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/cancelOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值cancelOrder
accesskey String accesskey
id long 委托挂单号
currency String 交易币种_计价币种
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id委托挂单号

获取委托单

获取单个委托买单或卖单

请求示例


// request demo
GET https://trade.zb.cn/api/getOrder?accesskey=youraccesskey¤cy=zb_qc&id=201710122805&method=getOrder&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getOrder() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&id=20180522105585216&method=getOrder";
	//sign通过HmacMD5加密得到:c25289ab4f1f7027b6aaf83b7bd5c50b
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&id=20180522105585216&method=getOrder&reqTime=1539942326049&sign=c25289ab4f1f7027b6aaf83b7bd5c50b";
	//取得返回结果json
	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.cn/api/getOrder'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getOrder?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
{
    "currency": "btc",
    "id": "20150928158614292",
    "price": 1560,
    "status": 3,
    "total_amount": 0.1,
    "trade_amount": 0,
    "trade_price" : 6000,
    "trade_date": 1443410396717,
    "trade_money": 0,
    "type": 0,
}


参数名称 类型 取值范围
method String 直接赋值getOrder
accesskey String accesskey
id long 委托挂单号
currency String 交易币种_计价币种
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
currency交易类型
id委托挂单号
price单价
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额

获取多个委托单

获取多个委托买单或卖单,每次请求返回10条记录

请求示例


// request demo
GET https://trade.zb.cn/api/getOrders?accesskey=youraccesskey¤cy=zb_qc&method=getOrders&pageIndex=1&tradeType=1&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getOrders() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&method=getOrders&pageIndex=1&tradeType=1";
	//sign通过HmacMD5加密得到:083d58360afd1da87c85ac2037aa0f4f
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getOrders?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&method=getOrders&pageIndex=1&reqTime=1539942326060&sign=083d58360afd1da87c85ac2037aa0f4f&tradeType=1";
	//取得返回结果json
	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.cn/api/getOrders'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getOrders?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
[
    {
        "currency": "btc",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
    	"trade_price" : 6000,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0
    }...
]


参数名称 类型 取值范围
method String 直接赋值getOrders
accesskey String accesskey
tradeType int 交易类型1/0[buy/sell]
currency String 交易币种_计价币种
pageIndex int 当前页数
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
currency交易类型
id委托挂单号
price单价
status挂单状态(1:取消,2:交易完成,0/3:待成交/待成交未交易部份))
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额

获取委托单忽略类型

取消tradeType字段过滤,可同时获取买单和卖单,每次请求返回pageSize10条记录

请求示例


// request demo
GET https://trade.zb.cn/api/getOrdersIgnoreTradeType?accesskey=youraccesskey¤cy=zb_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=1&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getOrdersIgnoreTradeType() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&method=getOrdersIgnoreTradeType&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:035c3a682574790044dc7aa4cffa0259
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getOrdersIgnoreTradeType?method=getOrdersIgnoreTradeType&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&pageIndex=1&pageSize=10&sign=035c3a682574790044dc7aa4cffa0259&reqTime=1539942326054";
	//取得返回结果json
	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.cn/api/getOrdersIgnoreTradeType'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getOrdersIgnoreTradeType?method=getOrdersIgnoreTradeType&accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&pageIndex=1&pageSize=10&sign=035c3a682574790044dc7aa4cffa0259&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


响应示例


// 返回结果
[
    {
        "currency": "btc",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
    	"trade_price" : 6000,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0
    }...
]


参数名称 类型 取值范围
method String 直接赋值getOrdersIgnoreTradeType
accesskey String accesskey
currency String 交易币种_计价币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
currency交易类型
id委托挂单号
price单价
status挂单状态(1:取消,2:交易完成,0/3:待成交/待成交未交易部份))
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额

未成交或部份成交挂单

获取未成交或部份成交的买单和卖单,每次请求返回pageSize<=10条记录

请求示例


// request demo
GET https://trade.zb.cn/api/getUnfinishedOrdersIgnoreTradeType?accesskey=youraccesskey¤cy=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getUnfinishedOrdersIgnoreTradeType() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:8007befda9d8903ea5e17601ea78bd94
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getUnfinishedOrdersIgnoreTradeType?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=zb_qc&method=getUnfinishedOrdersIgnoreTradeType&pageIndex=1&pageSize=10&reqTime=1539942326063&sign=8007befda9d8903ea5e17601ea78bd94";
	//取得返回结果json
	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.cn/api/getUnfinishedOrdersIgnoreTradeType'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getUnfinishedOrdersIgnoreTradeType?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
[
    {
        "currency": "btc",
        "id": "20150928158614292",
        "price": 1560,
        "status": 3,
        "total_amount": 0.1,
        "trade_amount": 0,
    	"trade_price" : 6000,
        "trade_date": 1443410396717,
        "trade_money": 0,
        "type": 0
    }...
]


参数名称 类型 取值范围
method String 直接赋值order
accesskey String accesskey
currency String 交易币种_计价币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
currency交易类型
id委托挂单号
price单价
status挂单状态(1:取消,2:交易完成,0/3:待成交/待成交未交易部份))
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额

获取用户信息

请求示例


// request demo
GET https://trade.zb.cn/api/getAccountInfo?accesskey=youraccesskey&method=getAccountInfo&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getAccountInfo() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo";
	//sign通过HmacMD5加密得到:25d7c24e7a3640d7d82f834976053bc9
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getAccountInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getAccountInfo&reqTime=1539942325894&sign=25d7c24e7a3640d7d82f834976053bc9";
	//取得返回结果json
	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.cn/api/getAccountInfo'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "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
}


参数名称 类型 取值范围
method String 直接赋值getAccountInfo
accesskey String accesskey
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
auth_google_enabled是否开通谷歌验证
auth_mobile_enabled是否开通手机验证
trade_password_enabled是否开通交易密码
username用户名
key币种
ename币种英文名
cnName币种中文名
showName若有改名则为新币名称,否则同ename
unitTag币种符号
isCanRecharge是否可充值
isCanWithdraw是否可提现
canLoan是否可理财
权限
leverPerm杠杆理财:理财管理、借贷管理
assetPerm查询资产:查询账号信息及资产情况
entrustPerm委托交易:委托、取消、查询交易订单
moneyPerm充值提币:获取充值、提币地址和记录,发起提币业务

获取充值地址

请求示例


// request demo
GET https://trade.zb.cn/api/getUserAddress?accesskey=youraccesskey¤cy=btc&method=getUserAddress&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getUserAddress() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=btc&method=getUserAddress";
	//sign通过HmacMD5加密得到:0eea9a3d1d1665d6727ca9b1286bef98
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getUserAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=btc&method=getUserAddress&reqTime=1539942326056&sign=0eea9a3d1d1665d6727ca9b1286bef98";
	//取得返回结果json
	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.cn/api/getUserAddress'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getUserAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
        }
    }
}


参数名称 类型 取值范围
method String 直接赋值getUserAddress
accesskey String accesskey
currency String 币种
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
key地址

获取提现地址

获取用户认证的提现地址

请求示例


// request demo
GET https://trade.zb.cn/api/getWithdrawAddress?accesskey=youraccesskey¤cy=btc&method=getWithdrawAddress&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getWithdrawAddress() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=btc&method=getWithdrawAddress";
	//sign通过HmacMD5加密得到:a23945f53b24c404e51d6ced99fea633
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getWithdrawAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=btc&method=getWithdrawAddress&reqTime=1539942326058&sign=a23945f53b24c404e51d6ced99fea633";
	//取得返回结果json
	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.cn/api/getWithdrawAddress'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getWithdrawAddress?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {
            "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
        }
    }
}


参数名称 类型 取值范围
method String 直接赋值getWithdrawAddress
accesskey String accesskey
currency String 币种
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
key地址

获取提现记录

请求示例


// request demo
GET https://trade.zb.cn/api/getWithdrawRecord?accesskey=youraccesskey¤cy=eth&method=getWithdrawRecord&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getWithdrawRecord() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:f5eb60290d3a0ce6e2e546e562f59aff
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getWithdrawRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=bch&method=getWithdrawRecord&pageIndex=1&pageSize=10&reqTime=1539942326065&sign=f5eb60290d3a0ce6e2e546e562f59aff";
	//取得返回结果json
	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.cn/api/getWithdrawRecord'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getWithdrawRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


// 返回结果
{
    "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
        }
    }
}


参数名称 类型 取值范围
method String 直接赋值getWithdrawRecord
accesskey String accesskey
currency String 币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
amount提现金额
fees提现手续费
id提现记录id
manageTime提现处理的时间的时间戳
status提币状态(0提交,1失败,2成功,3取消,5已确认)
submitTime提现发起的时间的时间戳
toAddress提现的接收地址

获取充值记录

请求示例


// request demo
GET https://trade.zb.cn/api/getChargeRecord?accesskey=youraccesskey¤cy=btc&method=getChargeRecord&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getChargeRecord() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=bch&method=getChargeRecord&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:e871dcce5138334704165ee53efe5545
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getChargeRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=bch&method=getChargeRecord&pageIndex=1&pageSize=10&reqTime=1539942326084&sign=e871dcce5138334704165ee53efe5545";
	//取得返回结果json
	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.cn/api/getChargeRecord'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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.cn/api/getChargeRecord?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e¤cy=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


响应示例


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


参数名称 类型 取值范围
method String 直接赋值getChargeRecord
accesskey String accesskey
currency String 币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
amount充值金额
confirmTimes充值确认次数
currency充值货币类型(大写)
description充值记录状态描述
hash充值交易号
id充值记录id
itransfer是否内部转账,1是0否
status状态(0等待确认,1充值失败,2充值成功)
submit_time充值时间
address充值地址

提现

请求示例


// request demo
GET https://trade.zb.cn/api/withdraw?accesskey=youraccesskey&amount=0.0004¤cy=etc&fees=0.0003⁢ransfer=0&method=withdraw&receiveAddr=14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp&safePwd=资金安全密码&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void withdraw() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5¤cy=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=地址string&safePwd=123456bb";
	//sign通过HmacMD5加密得到:a2d96def2e570e2f0567fe2c0ee73d78
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/withdraw?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5¤cy=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=%E5%9C%B0%E5%9D%80string&reqTime=1539942326067&safePwd=123456bb&sign=a2d96def2e570e2f0567fe2c0ee73d78";
	//取得返回结果json
	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.cn/api/withdraw'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1.5&currency=ada&fees=0.05⁢ransfer=0&method=withdraw&receiveAddr=地址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.cn/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


响应示例


// 返回结果
{
    "code": 1000,
    "message": "success",
    "id": "提现记录id"
}


参数名称 类型 取值范围
accesskey String accesskey
amount float 提现金额
currency String 币种
fees float 提现矿工费
itransfer int 是否同意bitbank系内部转账(0不同意,1同意,默认不同意)
method String 直接赋值withdraw
receiveAddr String 接收地址(必须是认证了的地址,bts的话,以"账户_备注"这样的格式)
safePwd String 资金安全密码
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id提现记录id

子帐号

创建子账号

请求示例


// request demo
GET https://trade.zb.cn/api/addSubUser?accesskey=youraccesskey&memo=xxx&password=xxxx&method=addSubUser⊂UserName=xxxxx&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void addSubUser() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457⊂UserName=test33";
	//sign通过HmacMD5加密得到:9f8018b8ca1dd4fba833a1fc51b81768
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/addSubUser?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&memo=hah&method=addSubUser&password=pass123457&reqTime=1539942326088&sign=9f8018b8ca1dd4fba833a1fc51b81768⊂UserName=test33";
	//取得返回结果json
	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.cn/api/addSubUser'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": 1000,
    "message": {
        "des": "success",
        "isSuc": true,
        "datas": {}
    }
}


参数名称 类型 取值范围
memo String 备注
password String 密码
subUserName String 子账号用户名(不超过6位数字或字母)
accesskey String accesskey
reqTime Long 当前时间毫秒数
sign String 签名

返回值描述
code返回代码
des提示信息
isSuc是否成功

获取子账号列表

请求示例


// request demo
GET https://trade.zb.cn/api/getSubUserList?accesskey=youraccesskey&method=getSubUserList&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getSubUserList() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList";
	//sign通过HmacMD5加密得到:2abacfab6ecb27144b798f36e1d8443c
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getSubUserList?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getSubUserList&reqTime=1539942326091&sign=2abacfab6ecb27144b798f36e1d8443c";
	//取得返回结果json
	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.cn/api/getSubUserList'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
  "code": 1000,
  "message": "操作成功",
  "result": [
    {
      "isOpenApi": false,
      "memo": "1",
      "userName": "xxxx@1",
      "userId": 123456,
      "isFreez": false
    },
    {
      "isOpenApi": false,
      "memo": "2",
      "userName": "xxxx@2",
      "userId": 132456,
      "isFreez": false
    }
  ]
}


参数名称 类型 取值范围
accesskey String accesskey
reqTime Long 当前时间毫秒数
sign String 签名

返回值描述
code返回代码
des提示信息
isSuc是否成功
isOpenApi是否开启API
userName用户名
isFreez是否冻结
memo备注

主子账号内部转账

请求示例


// request demo
https://trade.zb.cn/api/doTransferFunds?accesskey=youraccesskey&method=doTransferFunds&amount=1&currency=xx&fromUserName=xx&toUserName=xxxx&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void doTransferFunds() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&fromUserName=lianlianyi@vip.qq.com&method=doTransferFunds&toUserName=lianlianyi@test12";
	//sign通过HmacMD5加密得到:0d109b7d008c924041d10cf5706b2fce
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/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";
	//取得返回结果json
	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.cn/api/doTransferFunds'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&currency=doge&fromUserName=lianlianyi@vip.qq.com&method=doTransferFunds&toUserName=lianlianyi@test12'
        return self.call_api(url=MyUrl, params=params)

    def call_api(self, url, params=''):
        full_url = url
        if params:
            #sha_secret=86429c69799d3d6ac5da5c2c514baa874d75a4ba
            sha_secret = self.digest(self._secret_key_)
            #sign = 0d109b7d008c924041d10cf5706b2fce
            sign = self.hmac_sign(params, sha_secret)
            req_time = int(round(time.time() * 1000))
            params += '&sign=%s&reqTime=%d' % (sign, req_time)
            #full_url = https://trade.zb.cn/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


响应示例


// 返回结果
{
  "code": 1000,
  "message": "操作成功",
  "result": []
}


参数名称 类型 取值范围
amount Double 金额
currency String 币种
fromUserName String 转出方用户名
toUserName String 转入方用户名
accesskey String accesskey
reqTime Long 当前时间毫秒数
sign String 签名

返回值描述
code返回代码
des提示信息
isSuc是否成功

创建子账号API

请求示例


// request demo
https://trade.zb.cn/api/createSubUserKey?accesskey=youraccesskey&assetPerm=true&entrustPerm=true&method=createSubUserKey&keyName=xxx≤verPerm=true&moneyPerm=true&toUserId=xxx&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void createSubUserKey() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&assetPerm=true&entrustPerm=true&keyName=myKey11≤verPerm=true&method=createSubUserKey&moneyPerm=true&toUserId=1325607";
	//sign通过HmacMD5加密得到:b49ea1f5b9930bffc60d3f0dba0163e1
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/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";
	//取得返回结果json
	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.cn/api/createSubUserKey'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
  "code": 1000,
  "message": "操作成功",
  "result": {
    "apiKey": "xxxx",
    "apiSecret": "xxxxx"
  }
}


参数名称 类型 取值范围
assetPerm Boolean 查询资产权限(布尔值)true or false
entrustPerm Boolean 委托交易权限(布尔值)true or false
keyName String 名称
toUserId Long 子帐号Id
leverPerm Boolean 杠杆权限(布尔值)true or false
moneyPerm Boolean 充值提币权限(布尔值)true or false
accesskey String accesskey
reqTime Long 当前时间毫秒数
sign String 签名

返回值描述
code返回代码
des提示信息
isSuc是否成功
apiKeyapiKey
apiSecretapiSecret

杠杆

获取用户杠杆信息

请求示例


// request demo
GET https://trade.zb.cn/api/getLeverAssetsInfo?accesskey=youraccesskey&method=getLeverAssetsInfo&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getLeverAssetsInfo() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo";
	//sign通过HmacMD5加密得到:0cc8a3b79dabfac0c28229dd3871862d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getLeverAssetsInfo?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&method=getLeverAssetsInfo&reqTime=1539942326068&sign=0cc8a3b79dabfac0c28229dd3871862d";
	//取得返回结果json
	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.cn/api/getLeverAssetsInfo'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "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": "-"
                }
            ]
        }
    }
}


参数名称 类型 取值范围
method String 直接赋值 getLeverAssetsInfo
accesskey String accesskey
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
des提示信息
isSuc是否成功
key市场名称
fshowName若有改名则为新币名称,否则同fname
cshowName若有改名则为新币名称,否则同cname
showName若有改名则为新交易对名称,否则同key
fLoanIn法币待借入
repayLevel平仓级别
unwindPrice平仓价格
fUnitDecimal法币小数点
repayLock是否未还款锁定
cLoanIn币借入金额
cAvailable币可用
fAvailable法币可用
cLoanOut币借出金额
cCanLoanIn币可借入
fLoanOut法币可借出
level杠杆级别
fFreeze法币冻结
cFreeze币冻结
fCanLoanIn法币可借入
cUnitDecimal币小数点
cOverdraft币欠息
repayLeverShow平仓风险

获取杠杆账单

请求示例


// request demo
GET https://trade.zb.cn/api/getLeverBills?accesskey=youraccesskey&coin=qc&method=getLeverBills&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getLeverBills() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:2473a00d93feed72583365e3cb90f391
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getLeverBills?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&dataType=0&method=getLeverBills&pageIndex=1&pageSize=10&reqTime=1539942326070&sign=2473a00d93feed72583365e3cb90f391";
	//取得返回结果json
	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.cn/api/getLeverBills'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
	"code"              : 1000,
	"message"           : "操作成功。",
	"result"            : [
		{
			"changeCoin"    : 500.00000000,
			"showCoin"      : "+500.000=500.000LTC",
			"type"          : 1,
			"date"          : 1522668146000,
			"database"      : "default",
			"dataName"      : "baseBean",
			"fundsType"     : 3,
			"billTypeValue" : "LTC转入",
			"id"            : 609,
			"downTableDate" : 1520092800000,
			"marketName"    : "ltcusdt",
			"avgPrice"      : 0,
			"userId"        : 110803,
			"coinBalance"   : 500.00000000,
			"entrustId"     : 0
		}
	]
}


参数名称 类型 取值范围
method String 直接赋值 getLeverBills
accesskey String accesskey
coin String 币种
dataType int 数据类型[0/1](30天内数据/30天前数据)
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id账单ID
userId用户ID
date账单生成时间
type账单类型
billTypeValue账单类型对应中文
changeCoin本次变化的COIN数量
coinBalance变化后的COIN余额
changeFiat本次变化的法币数量
fiatBalance变化后的法币余额
fundsTypeCOIN类型
marketName市场名称
showCoin显示COIN变化
showFiat显示法币变化

资产转入杠杆区

请求示例


// request demo
GET https://trade.zb.cn/api/transferInLever?accesskey=youraccesskey&amount=100&coin=qc&marketName=btsqc&method=transferInLever&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void transferInLever() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever";
	//sign通过HmacMD5加密得到:a8fe8d3e01143e83491e5df69f288fd4
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/transferInLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferInLever&reqTime=1539942326071&sign=a8fe8d3e01143e83491e5df69f288fd4";
	//取得返回结果json
	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.cn/api/transferInLever'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值 transferInLever
accesskey String accesskey
coin String 币种
marketName String 市场名称
amount double 转入数量,小数位数不能超过4,超过系统自动截取前4位
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

资产转出杠杆区

请求示例


// request demo
GET https://trade.zb.cn/api/transferOutLever?accesskey=youraccesskey&amount=100&coin=qc&marketName=btsqc&method=transferOutLever&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void transferOutLever() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever";
	//sign通过HmacMD5加密得到:d7dcb17e6271232862812c339611d17e
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/transferOutLever?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&marketName=btsqc&method=transferOutLever&reqTime=1539942326073&sign=d7dcb17e6271232862812c339611d17e";
	//取得返回结果json
	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.cn/api/transferOutLever'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值 transferOutLever
accesskey String accesskey
coin String 币种
marketName String 市场名称
amount double 转出数量,小数位数不能超过8,超过系统自动截取前8位
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

发布理财

请求示例


// request demo
GET https://trade.zb.cn/api/loan?accesskey=youraccesskey&amount=100&coin=qc&interestRateOfDay=0.1&isLoop=1&method=loan&repaymentDay=20&safePwd=资金安全密码&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void loan() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&amount=1&coin=qc&interestRateOfDay=0.05&isLoop=0&method=loan&repaymentDay=10";
	//sign通过HmacMD5加密得到:0237aa2fd02b155142a1915c8589b2b1
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/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";
	//取得返回结果json
	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.cn/api/loan'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。",
    "id": "97"
}


参数名称 类型 取值范围
method String 直接赋值 loan
accesskey String accesskey
coin String 币种
amount double 理财金额,小数位数不能超过4,超过系统自动截取前4位
interestRateOfDay double 日利率 [0.05-0.2] 百分比,小数位数不能超过3,超过系统自动截取前3位
repaymentDay int 放款天数 [10/20/30]
isLoop boolean 是否自动放贷 [1/0]
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id理财ID

取消理财

请求示例


// request demo
GET https://trade.zb.cn/api/cancelLoan?accesskey=youraccesskey&loanId=100&method=cancelLoan&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void cancelLoan() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan";
	//sign通过HmacMD5加密得到:0def7152ff2f6d4a8cab5f684d825a4a
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/cancelLoan?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1454545445&method=cancelLoan&reqTime=1539942326076&sign=0def7152ff2f6d4a8cab5f684d825a4a";
	//取得返回结果json
	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.cn/api/cancelLoan'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值 cancelLoan
accesskey String accesskey
loanId String 理财ID
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

获取可借贷列表

请求示例


// request demo
GET https://trade.zb.cn/api/getLoans?accesskey=youraccesskey&coin=qc&method=getLoans&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getLoans() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getLoans&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:9ed81061104f5b87703861ba77806eba
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getLoans?method=getLoans&cesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&pageIndex=1&pageSize=10&sign=9ed81061104f5b87703861ba77806eba&reqTime=1539942326077";
	//取得返回结果json
	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.cn/api/getLoans'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
	"code"              : 1000,
	"message"           : "操作成功。",
	"result"            : [
		{
			"amount"            : "0.1",
			"balance"           : "0.00008001",
			"coinName"          : "qc",
			"repaymentDay"      : 10,
			"interestRateOfDay" : "0.0005"
		}
	]
}


参数名称 类型 取值范围
method String 直接赋值 getLoans
accesskey String accesskey
coin String 币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
amount数量
balance剩余可借
coinName币种
repaymentDay借款期限
interestRateOfDay日利率

获取借贷记录

请求示例


// request demo
GET https://trade.zb.cn/api/getLoanRecords?accesskey=youraccesskey&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=2&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getLoanRecords() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&status=1";
	//sign通过HmacMD5加密得到:08891e23a060aa0f979332939e7e845d
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getLoanRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanId=1545454415&marketName=btsqc&method=getLoanRecords&pageIndex=1&pageSize=10&reqTime=1539942326078&sign=08891e23a060aa0f979332939e7e845d&status=1";
	//取得返回结果json
	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.cn/api/getLoanRecords'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
	"code"                 : 1000,
	"message"              : "操作成功",
	"result"               : [
		{
			"createTime"           : 1522473159000,
			"statusShow"           : "还款中",
			"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
		}
		...
	]
}


参数名称 类型 取值范围
method String 直接赋值 getLoanRecords
accesskey String accesskey
loanId String 理财id(借出就传 借入不用传)
marketName String 市场
status int 状态(1还款中 2已还款 3 需要平仓 4 平仓还款 5自动还款中 6自动还款)
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id借贷记录ID
loanId理财ID
inUserId借入者ID
inUserName借入者用户名
outUserId借出者ID
outUserName借出者用户名
fundType币种类型
amount借入金额
status状态 1还款中 2已还款 3需要平仓 4 平仓还款 5自动还款
createTime借贷成功时间
reward奖励金额
balanceAmount投标后借款剩余金额
rate利率
hasRepay已还本金金额
hasLx已还利息
dikouLx已抵扣利息
zheLx折算线上价
arrearsLx拖欠利息
nextRepayDate下次还款时间
riskManage风险控制
inUserLock借入者是否被锁定
withoutLxAmount免息额度
withoutLxDays免息天数
balanceWithoutLxDays剩余的免息天数
rateForm利率形式
rateAddVal增长幅度
repayDate还款时间
marketName市场
fwfScale服务费费率
investMark自动续借
sourceType来源类型: 8”网页”,5”手机APP”,6”接口API”

借款

请求示例


// request demo
GET https://trade.zb.cn/api/borrow?accesskey=youraccesskey&amount=100&coin=qc&interestRateOfDay=0.1&isLoop=1&marketName=btcqc&method=borrow&repaymentDay=20&safePwd=资金安全密码&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void borrow() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	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通过HmacMD5加密得到:0018e23184496b1fd5b7eadfaab2cc99
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/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";
	//取得返回结果json
	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.cn/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'
        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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值 borrow
accesskey String accesskey
marketName String 杠杆市场
coin String 币种
amount double 借入金额,小数位数不能超过4,超过系统自动截取前4位
interestRateOfDay double 日利率 [0.05-0.2] 百分比,小数位数不能超过3,超过系统自动截取前3位
repaymentDay int 借款期限 [10/20/30]天
isLoop int 是否自动续借 [1/0](到期自动续借/到期自动还款)
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

还款

请求示例


// request demo
GET https://trade.zb.cn/api/repay?accesskey=youraccesskey&loanRecordId=289&method=repay&repayAmount=100&repayType=0&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void repay() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1";
	//sign通过HmacMD5加密得到:90fb3aacda467ffb95ce36c054173fff
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/repay?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=repay&repayAmount=1.5&repayType=1&reqTime=1539942326080&sign=90fb3aacda467ffb95ce36c054173fff";
	//取得返回结果json
	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.cn/api/repay'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": "1000",
    "message": "操作成功。"
}


参数名称 类型 取值范围
method String 直接赋值 repay
accesskey String accesskey
loanRecordId String 借贷记录id
repayAmount double 还款金额
repayType int 还款方式 [0/1](全部/部分)
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

获取还款记录

请求示例


// request demo
GET https://trade.zb.cn/api/getRepayments?accesskey=youraccesskey&loanRecordId=50&method=getRepayments&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getRepayments() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:3a8808fa43fac898bb7e6bb32713f7bb
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getRepayments?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&loanRecordId=1454545415&method=getRepayments&pageIndex=1&pageSize=10&reqTime=1539942326082&sign=3a8808fa43fac898bb7e6bb32713f7bb";
	//取得返回结果json
	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.cn/api/getRepayments'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
	"code"       : 1000,
	"message"    : "操作成功",
	"result"     : [
		{
			"benJin"     : "29",
			"id"         : 42,
			"statusShow" : "已还",
			"status"     : 1,
			"liXi"       : "0.0145",
			"actureDate" : 1522031604000
		}
	]
}


参数名称 类型 取值范围
method String 直接赋值 getRepayments
accesskey String accesskey
loanRecordId String 借贷记录id
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id还款记录ID
benJin本金
liXi利息
status状态
statusShow状态值对应中文
actureDate实际还款日期

获取理财记录

请求示例


// request demo
GET https://trade.zb.cn/api/getFinanceRecords?accesskey=youraccesskey&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10&sign=请求加密签名串&reqTime=当前时间毫秒数



// java demo
public void getFinanceRecords() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10";
	//sign通过HmacMD5加密得到:c448737856caa08575d83f26e33cdde0
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/getFinanceRecords?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&coin=qc&method=getFinanceRecords&pageIndex=1&pageSize=10&reqTime=1539943777351&sign=c448737856caa08575d83f26e33cdde0";
	//取得返回结果json
	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.cn/api/getFinanceRecords'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
	"code"              : 1000,
	"message"           : "操作成功。",
	"result"            : [
		{
			"id"                : 156,
			"userId"            : 110803,
			"userName"          : "13427002684",
			"fundType"          : 15,
			"coinName"          : "QC",
			"amount"            : "10",
			"hasAmount"         : "0",
			"status"            : 0,
			"statusShow"        : "未有借入",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
	]
}


参数名称 类型 取值范围
method String 直接赋值 getFinanceRecords
accesskey String accesskey
coin String 币种
pageIndex int 当前页数
pageSize int 每页数量
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息
id理财ID
userId用户ID
userName用户名
fundType币种类型
coinName币种名称
amount理财金额
hasAmount已借出金额
status状态值
statusShow状态值对应中文
createTime发布时间
interestRateOfDay日利率
repaymentDay放贷天数
isLoop是否自动放贷
inTimes理财被借入次数
sourceType来源类型: 8”网页”,5”手机APP”,6”接口API”

变更是否自动续借

请求示例


// request demo
GET https://trade.zb.cn/api/changeInvestMark?accesskey=youraccesskey&investMark=1&loanRecordId=借贷id&method=changeInvestMark&sign=请求加密签名串&reqTime=当前时间毫秒数


// java demo
public void changeInvestMark() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1&loanRecordId=154545,457457574&method=changeInvestMark";
	//sign通过HmacMD5加密得到:904182d4286992037130fbcbdabbe5cb
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/changeInvestMark?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706&investMark=1&loanRecordId=154545%2C457457574&method=changeInvestMark&reqTime=1539942326086&sign=904182d4286992037130fbcbdabbe5cb";
	//取得返回结果json
	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.cn/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.cn/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


响应示例


// 返回结果
{
	"code"              : 1000,
	"message"           : "操作成功。",
}


参数名称 类型 取值范围
method String 直接赋值 changeInvestMark
accesskey String accesskey
investMark int 续借类型[0/1](非自动/自动续借)
loanRecordId String 借贷Id,多个以英文‘,’分割
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

变更是否自动放贷

请求示例


// request demo
GET https://trade.zb.cn/api/changeLoop?accesskey=youraccesskey&isLoop=1&loanId=放贷id&method=changeLoop&sign=请求加密签名串&reqTime=当前时间毫秒



// java demo
public void changeLoop() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String digest = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String paramStr = "accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop";
	//sign通过HmacMD5加密得到:cfa39cb7fc939b2f4fd4dd3d788bf842
	String sign = EncryDigestUtil.hmacSign(paramStr, digest);
	//组装最终发送的请求url
	String finalUrl = "https://trade.zb.cn/api/changeLoop?accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&isLoop=0&loanId=1154545&method=changeLoop&reqTime=1539942326087&sign=cfa39cb7fc939b2f4fd4dd3d788bf842";
	//取得返回结果json
	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.cn/api/changeLoop'
        params = 'accesskey=ce2a18e0-dshs-4c44-4515-9aca67dd706e&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.cn/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


响应示例


// 返回结果
{
    "code": 1000,
    "message": "success",
}


参数名称 类型 取值范围
method String 直接赋值 changeLoop
accesskey String accesskey
isLoop int 放贷类型[0/1](非自动/自动放贷)
loanId String 放贷id
sign String 请求加密签名串
reqTime long 当前时间毫秒数

返回值描述
code返回代码
message提示信息

WebSocket API

ZB为用户提供了一个简单的而又强大的API,旨在帮助用户快速高效的将ZB交易功能整合到自己应用当中。

WebSocket服务地址

ZB WebSocket服务连接地址:wss://api.zb.cn/websocket

示例代码

目前支持C、JAVA、Python版本。其他语言版本会相继支持。如果在使用过程中有任何问题请联系我们API技术QQ群:764113552,我们将在第一时间帮您解决技术问题。

签名方式:先用sha加密secretkey,然后根据加密过的secretkey把请求的参数签名,请求参数按照ascii值排序加密,通过md5填充16位加密

github 示例代码

访问限制

1.针对交易API和杠杆API,单个用户限制每秒钟30次访问,一秒钟内30次以上的请求,将会视作无效。

WS配置

获取市场配置

请求示例


// 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.cn/websocket"

class ZB_Sub_Spot_Api(object):
    """基于Websocket的API对象"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        print 'onOpen'
    
    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'markets'}"
        self.ws_sub_spot.send(req)


响应示例


// 返回结果
{
    "code":1000,
    "data":{
        "btc_usdt":{
            "amountScale":4,
            "priceScale":2
            },
        "bcc_usdt":{
            "amountScale":3
            ,"priceScale":2
            }
        }
        ...
    },
    "success":true,
    "channel":"markets",
    "message":"操作成功。"
}


返回值描述
priceScale价格小数位数
amountScale数量小数位数

WS行情

获取ticker数据

请求示例


// 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.cn/websocket"

class ZB_Sub_Spot_Api(object):
    """基于Websocket的API对象"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        print 'onOpen'
    
    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_ticker'}"
        self.ws_sub_spot.send(req)


响应示例


// 返回结果
{
    "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"
    }
}


参数名称 类型 取值范围
event String 直接赋值addChannel
channel String zbqc_ticker

返回值描述
date返回数据时服务器时间
high最高价
low最低价
buy买一价
sell卖一价
last最新成交价
vol成交量(最近的24小时)
channel当前请求的channel

获取市场深度

请求示例


// 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.cn/websocket"

class ZB_Sub_Spot_Api(object):
    """基于Websocket的API对象"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        print 'onOpen'
    
    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_depth'}"
        self.ws_sub_spot.send(req)


响应示例


// 返回结果
{
    "asks": [
        [
            3846.94,
            0.659
        ]...
    ],
    "bids": [
        [
            3826.94,
            4.843
        ]...
    ],
    "channel": "ltcbtc_depth",
    "no": 245539
}


参数名称 类型 取值范围
event String 直接赋值addChannel
channel String ltcbtc_depth

返回值描述
asks卖方深度
bids买方深度
channel当前请求的channel

获取历史成交

请求示例


// 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.cn/websocket"

class ZB_Sub_Spot_Api(object):
    """基于Websocket的API对象"""
    def __init__(self):
        """Constructor"""
        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        print 'onOpen'
    
    #----------------------------------------------------------------------
    def sendJson(self):
        req = "{'event':'addChannel','channel':'ltcbtc_trades'}"
        self.ws_sub_spot.send(req)


响应示例


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


参数名称 类型 取值范围
event String 直接赋值addChannel
channel String ltcbtc_trades

返回值描述
date交易时间
price交易价格
amount交易数量
tid交易生成ID
channel当前请求的channel

WS交易

委托下单

请求示例


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



// java demo
public void usdtqc_order() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","tradeType":"1"}";
	//sign通过HmacMD5加密得到:6b9cd4aaee79a6b74fffa49146ae8879
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"0.001","channel":"usdtqc_order","event":"addChannel","no":"test001","price":"1.0","tradeType":"1"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "message":"操作成功。",
    "no":"0",
    "data":"{
        "entrustId":201711133673
        }",
    "code":1000,
    "channel":"ltcbtc_order",
    "success":true
}


参数名称 类型 取值范围
event String 直接赋值addChannel
accesskey String accesskey
amount float 交易数量
channel String 交易币种_购买币种_order
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
price float 单价
tradeType int 交易类型1/0[buy/sell]
acctType int 是否杠杆 1.杠杆/0.现货,默认为0.现货
sign String 请求加密签名串

返回值描述
code返回代码
message提示信息
entrustId委托挂单号
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

取消委托

请求示例


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



// java demo
public void usdtqc_cancelorder() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001"}";
	//sign通过HmacMD5加密得到:100d377228931b1147895f9d9785b2a3
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_cancelorder","event":"addChannel","id":"20180522105585216","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "success": true,
    "code": 1000,
    "channel": "ltcbtc_cancelorder",
    "message": "操作成功。",
    "no": "1472814987517496849777"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String 交易币种购买币种_cancelorder
event String 直接赋值addChannel
id long 委托单id
no String 请求的唯一标识,用于在返回内容时区分
sign String 请求加密签名串

返回值描述
code返回代码
message提示信息
entrustId委托挂单号
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取委托单

请求示例


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



// java demo
public void usdtqc_getorder() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001"}";
	//sign通过HmacMD5加密得到:aa67749256db23191458fea8970f1b6e
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getorder","event":"addChannel","id":"20180522105585216","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "success": true,
    "code": 1000,
    "data": {
        "currency": "ltc_btc",
        "fees": 0,
        "id": "20160902387645980",
        "price": 100,
        "status": 0,
        "total_amount": 0.01,
        "trade_amount": 0,
    	"trade_price" : 6000,
        "trade_date": 1472814905567,
        "trade_money": 0,
        "type": 1
    },
    "channel": "ltcbtc_getorder",
    "message": "操作成功。",
    "no": "14728149875431230591268"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String 交易币种_购买币种_getorder
event String 直接赋值addChannel
id long 委托挂单号
no String 请求的唯一标识,用于在返回内容时区分
sign String 请求加密签名串

返回值描述
id委托挂单号
currency交易类型
trade_amount已成交数量
trade_money已成交总金额
trade_price成交均价
total_amount挂单总数量
trade_date委托时间
fees交易手续费,卖单的话,显示的是收入货币;买单的话,显示的是买入货币
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取多个委托单

请求示例


// request demo
{
    "accesskey": "your key",
    "channel": "ltcbtc_getorders",
    "event": "addChannel",
    "no": "14728004752031866329548",
    "pageIndex": 1,
    "sign": 签名,
    "tradeType": 1
}



// java demo
public void usdtqc_getorders() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","tradeType":"1"}";
	//sign通过HmacMD5加密得到:027cf41d1f761e5ab8fc61b7e3efda54
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","acctType":"0","channel":"usdtqc_getorders","event":"addChannel","no":"test001","pageIndex":"1","tradeType":"1"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "success": true,
    "code": 1000,
    "data": [
        {
            "currency": "ltc_btc",
            "fees": 0,
            "id": "20160901385862136",
            "price": 3700,
            "status": 0,
            "total_amount": 1.845,
            "trade_amount": 0,
    		"trade_price" : 6000,
            "trade_date": 1472706387742,
            "trade_money": 0,
            "type": 1
        }...
    ],
    "channel": "ltcbtc_getorders",
    "message": "操作成功。",
    "no": "14728004752031866329548"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String 交易币种购买币种_getorders
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
pageIndex int 当前页数
tradeType int 交易类型1/0[buy/sell]

返回值描述
currency交易类型()
id委托挂单号
price单价
status挂单状态(1:取消,2:交易完成,0/3:待成交/待成交未交易部份))
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额
trade_price成交均价
fees交易手续费,卖单的话,显示的是收入货币;买单的话,显示的是买入货币
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取委托买卖单忽略类型

请求示例


// request demo
{
    "accesskey": "your key",
    "channel": "ltcbtc_getordersignoretradetype",
    "event": "addChannel",
    "no": "1472800475206-1927246702",
    "pageIndex": 1,
    "pageSize": 10,
    "sign": 签名,
    "tradeType": 1
}



// java demo
public void usdtqc_getordersignoretradetype() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:71ea0655343e47e6359de635b9ffe312
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"usdtqc_getordersignoretradetype","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "success": true,
    "code": 1000,
    "data": [
        {
            "currency": "ltc_btc",
            "fees": 0,
            "id": "20160901385862136",
            "price": 3700,
            "status": 0,
            "total_amount": 1.845,
            "trade_amount": 0,
    		"trade_price" : 6000,
            "trade_date": 1472706387742,
            "trade_money": 0,
            "type": 1
        }...
    ],
    "channel": "ltcbtc_getordersignoretradetype",
    "message": "操作成功。",
    "no": "1472800475205-217627433"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String 交易币种购买币种_getorders
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
pageIndex int 当前页数
pageSize int 每页数量

返回值描述
currency交易类型
id委托挂单号
price单价
status挂单状态(1:取消,2:交易完成,0/3:待成交/待成交未交易部份))
total_amount挂单总数量
trade_amount已成交数量
trade_date委托时间
trade_money已成交总金额
trade_price成交均价
fees交易手续费,卖单的话,显示的是收入货币;买单的话,显示的是买入货币
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取用户信息

请求示例


// request demo
{
	'accesskey':'your key',
	'channel':'getaccountinfo',
	'event':'addChannel',
	'no' : 请求的唯一标识,用于在返回内容时区分,
	'sign':签名
}



// java demo
public void getaccountinfo() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001"}";
	//sign通过HmacMD5加密得到:c2683870eaade9be66e46747520ca95f
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getaccountinfo","event":"addChannel","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "message": "操作成功",
    "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
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getaccountinfo
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
auth_google_enabled是否开通谷歌验证
auth_mobile_enabled是否开通手机验证
trade_password_enabled是否开通交易密码
username用户名
ename币种英文名
cnName币种中文名
unitTag币种符号
key币种
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

WS子账户

创建子账号

请求示例


// request demo
{
    "accesskey": "ceb1569d-7c17-xxxx-b4a1-xxxxxxxxx",
    "channel": "addSubUser",
    "event": "addChannel",
    "memo": "memo",
    "password": "123456",
    "subUserName": "1",
	"sign":"签名"
}



// java demo
public void addSubUser() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}";
	//sign通过HmacMD5加密得到:475fdd83600e42140d2d0336b8d57ce4
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"addSubUser","event":"addChannel","memo":"memo","no":"test001","password":"123456","subUserName":"test1"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
	"success": true,
	"code": 1000,
	"channel": "addSubUser",
	"message": "操作成功",
	"no": "0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String addSubUser
event String 直接赋值addChannel
memo String 备注
password String 密码
subUserName String 子账号用户名(不超过6位数字或字母)
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取子账号列表

请求示例


// request demo
{
	"accesskey": "ceb1569d-7c17-487a-b4a1-10bf2a8d925d",
	"channel": "getSubUserList",
	"event": "addChannel",
	"sign":"签名"
}



// java demo
public void getSubUserList() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001"}";
	//sign通过HmacMD5加密得到:5fe82bf1864091af1120b184f773d1f9
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getSubUserList","event":"addChannel","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
	"success": true,
	"code": 1000,
	"channel": "getSubUserList",
	"message": " [{
		"isOpenApi": false,
		"memo": "1",
		"userName": "15914665280@1",
		"userId": 110980,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "2",
		"userName": "15914665280@2",
		"userId": 110984,
		"isFreez": false
	}, {
		"isOpenApi": false,
		"memo": "test3",
		"userName": "15914665280@3",
		"userId": 111014,
		"isFreez": false
	}]",
	"no": "0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getSubUserList
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
isOpenApi是否开启API
userName用户名
isFreez是否冻结
memo备注

子账号内部转账

请求示例


// request demo
{
    "accesskey": "ceb1569d-7c17-487a-b4a1-10bf2a8d925d",
    "amount": "1",
    "channel": "doTransferFunds",
    "currency": "zb",
    "event": "addChannel",
    "fromUserName": "xxxxxx",
    "toUserName":"xxxx",
	"sign":"签名"
}



// java demo
public void doTransferFunds() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","toUserName":"xxxx"}";
	//sign通过HmacMD5加密得到:3c1ab8f0b974e022ef8a151ff620062d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"1","channel":"doTransferFunds","currency":"zb","event":"addChannel","fromUserName":"xxxx","no":"test001","toUserName":"xxxx"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
	"success": true,
	"code": 1000,
	"channel": "doTransferFunds",
	"message": "操作成功",
	"no": "0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String doTransferFunds
event String 直接赋值addChannel
amount String 金额
currency String 币种
fromUserName String 转出方用户名
toUserName String 转入方用户名
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

创建子账号API

请求示例


// 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": "签名"
}



// java demo
public void createSubUserKey() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	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通过HmacMD5加密得到:e961b173f88acf4676b57f065374a65d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"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 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


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


参数名称 类型 取值范围
accesskey String accesskey
channel String createSubUserKey
event String 直接赋值addChannel
assetPerm Boolean 查询资产权限(布尔值)true or false
entrustPerm Boolean 委托交易权限(布尔值)true or false
keyName String 名称
leverPerm Boolean 杠杆权限(布尔值)true or false
moneyPerm String 充值提币权限(布尔值)true or false
toUserId String 子账号ID
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
apiKeyapiKey
apiSecretapiSecret

WS杠杆

获取用户杠杆信息

请求示例


// request demo
{
	'accesskey':'your key',
	'channel':'getuserLeverAsset',
	'event':'addChannel',
	'no' : 请求的唯一标识,用于在返回内容时区分,
	'sign':签名
}



// java demo
public void getuserLeverAsset() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001"}";
	//sign通过HmacMD5加密得到:f060147b2f8a276291c7da4bf1f1d420
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getuserLeverAsset","event":"addChannel","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
    "message": "操作成功", 
    "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
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getuserLeverAsset
event String 直接赋值addChannel
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
code返回代码
des提示信息
isSuc是否成功
fLoanIn法币待借入
repayLevel平仓级别
unwindPrice平仓价格
fUnitDecimal法币小数点
repayLock是否未还款锁定
cLoanIn币借入金额
cAvailable币可用
fAvailable法币可用
cLoanOut币借出金额
cCanLoanIn币可借入
fLoanOut法币可借出
level杠杆级别
fFreeze法币冻结
cFreeze币冻结
fCanLoanIn法币可借入
cUnitDecimal币小数点
cOverdraft币欠息
repayLeverShow平仓风险

获取杠杆账单

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLeverBills",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":签名
}



// java demo
public void getLeverBills() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:e92666397d9b03a47edfafd8cb4e759a
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLeverBills","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "data":[
    {
      "changeCoin":10,
      "showFiat":"…",
      "showCoin":"-10.000=2200.000QC",
      "type":12,
      "date":1523001559000,
      "database":"default",
      "dataName":"baseBean",
      "fundsType":15,
      "billTypeValue":"借出QC",
      "id":898,
      "downTableDate":1520697600000,
      "marketName":"btsqc",
      "avgPrice":0,
      "userId":110803,
      "coinBalance":2200,
      "entrustId":0
    },
    ...
  ],
  "channel":"getLeverBills",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getLeverBills
event String 直接赋值addChannel
coin String 币种
pageIndex int 当前页数
pageSize int 每页数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
id账单ID
userId用户ID
date账单生成时间
type账单类型
billTypeValue账单类型对应中文
changeCoin本次变化的COIN数量
coinBalance变化后的COIN余额
changeFiat本次变化的法币数量
fiatBalance变化后的法币余额
fundsTypeCOIN类型
marketName市场名称
showCoin显示COIN变化
showFiat显示法币变化

资产转入杠杆区

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"transferInLever",
  "coin":"qc",
  "event":"addChannel",
  "marketName":"btsqc",
  "sign":签名
}



// java demo
public void transferInLever() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}";
	//sign通过HmacMD5加密得到:c9ef0030df66980464ccc47675900832
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferInLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"transferInLever",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String transferInLever
event String 直接赋值addChannel
coin String 币种
marketName String 市场
amount Double 转入数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

资产转出杠杆区

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"transferOutLever",
  "coin":"qc",
  "event":"addChannel",
  "marketName":"btsqc",
  "sign":签名
}



// java demo
public void transferOutLever() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}";
	//sign通过HmacMD5加密得到:da3b000acb6fb245a1ba2f661f2fd398
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"transferOutLever","coin":"qc","event":"addChannel","marketName":"btsqc","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"transferOutLever",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String transferOutLever
event String 直接赋值addChannel
coin String 币种
marketName String 市场
amount Double 转出数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

发布理财

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"loan",
  "coin":"qc",
  "event":"addChannel",
  "interestRateOfDay":0.15
  "isLoop":1
  "repaymentDay":20
  "safePwd":资金安全密码
  "sign":签名
}



// java demo
public void loan() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	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通过HmacMD5加密得到:4ca79117822a780511307e55eb176d6b
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"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 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"loan",
  "message":"操作成功",
  "no":"0",
  "data":{
      "loanId":121
  }
}


参数名称 类型 取值范围
accesskey String accesskey
channel String loan
event String 直接赋值addChannel
coin String 币种
amount Double 理财金额
interestRateOfDay Double 日利率 [0.05-0.2]%
repaymentDay int 放款天数 [10/20/30]
isLoop int 是否自动放贷 [1/0]
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
data
loanId理财ID

取消理财

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"cancelLoan",
  "event":"addChannel",
  "loanId":121,
  "sign":签名
}



// java demo
public void cancelLoan() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001"}";
	//sign通过HmacMD5加密得到:c19662ffe48ff586d5f5fa3ba8fcf2e1
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"cancelLoan","event":"addChannel","loanId":"121","no":"test001"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"cancelLoan",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String cancelLoan
event String 直接赋值addChannel
loanId Long 理财ID
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取可借贷列表

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLoans",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":签名
}



// java demo
public void getLoans() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:357e94bcc5b2544f71364c6e05914f2e
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoans","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "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":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getLoans
event String 直接赋值addChannel
coin String 币种
pageIndex int 当前页数
pageSize int 每页数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
amount数量
balance剩余可借
coinName币种
repaymentDay借款期限
interestRateOfDay日利率

获取借贷记录

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getLoanRecords",
  "loanId":58,
  "marketName":"btsqc",
  "pageIndex":1,
  "pageSize":10,
  "sign":签名,
  "status":""
}



// java demo
public void getLoanRecords() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:a728271842900000f82a046d06f5ceee
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getLoanRecords","event":"addChannel","loanId":"58","marketName":"btsqc","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "data":[
    {
      "createTime":1521789778000,
      "statusShow":"还款中",
      "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":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getLoanRecords
event String 直接赋值addChannel
loanId Long 理财id(借出就传 借入不用传)
marketName String 市场
status int 状态(1还款中 2已还款 3 需要平仓 4 平仓还款 5自动还款中 6自动还款)
pageIndex int 当前页数
pageSize int 每页数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
id借贷记录ID
loanId理财ID
inUserId借入者ID
inUserName借入者用户名
outUserId借出者ID
outUserName借出者用户名
fundType币种类型
amount借入金额
status状态 1还款中 2已还款 3需要平仓 4 平仓还款 5自动还款
createTime借贷成功时间
reward奖励金额
balanceAmount投标后借款剩余金额
rate利率
hasRepay已还本金金额
hasLx已还利息
dikouLx已抵扣利息
zheLx折算线上价
arrearsLx拖欠利息
nextRepayDate下次还款时间
riskManage风险控制
inUserLock借入者是否被锁定
withoutLxAmount免息额度
withoutLxDays免息天数
balanceWithoutLxDays剩余的免息天数
rateForm利率形式
rateAddVal增长幅度
repayDate还款时间
marketName市场
fwfScale服务费费率
investMark自动续借
sourceType来源类型: 8”网页”,5”手机APP”,6”接口API”

借款

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"borrow",
  "coin":"qc",
  "event":"addChannel",
  "interestRateOfDay":0.15
  "isLoop":1
  "repaymentDay":20
  "safePwd":资金安全密码
  "sign":签名
}



// java demo
public void borrow() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	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通过HmacMD5加密得到:378348551685d6d5ddbdf02a4df71f43
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"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 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"borrow",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String borrow
event String 直接赋值addChannel
marketName String 杠杆市场
coin String 币种
amount Double 借入金额
interestRateOfDay Double 日利率 [0.05-0.2]%
repaymentDay int 借款期限 [10/20/30]天
isLoop int 是否自动续借 [1/0](到期自动续借/到期自动还款)
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

还款

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "amount":100,
  "channel":"repay",
  "event":"addChannel",
  "loanRecordId":296,
  "repayAmount":50,
  "repayType":0,
  "sign":签名
}



// java demo
public void repay() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0"}";
	//sign通过HmacMD5加密得到:e8f84ef851933cee9c26417d26ae2122
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","amount":"100","channel":"repay","event":"addChannel","loanRecordId":"292","no":"test001","repayAmount":"50","repayType":"0"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "channel":"repay",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String repay
event String 直接赋值addChannel
loanRecordId Long 借贷记录id
repayAmount Double 还款金额
repayType int 还款方式 [0/1](全部/部分)
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分

获取还款记录

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getRepayments",
  "loanRecordId":296,
  "pageIndex":1,
  "pageSize":10,
  "sign":签名
}



// java demo
public void getRepayments() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:5be5380faa9ee8010f43bafabbae5e3d
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getRepayments","event":"addChannel","loanRecordId":"292","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "data":[
    {
      "benJin":"50",
      "id":78,
      "statusShow":"已还",
      "status":1,
      "liXi":"0.06",
      "actureDate":1522982889000
    }
  ],
  "channel":"getLeverBills",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getRepayments
event String 直接赋值addChannel
loanRecordId Long 借贷记录id
pageIndex int 当前页数
pageSize int 每页数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
id还款记录ID
benJin本金
liXi利息
status状态
statusShow状态值对应中文
actureDate实际还款日期

获取理财记录

请求示例


// request demo
{
  "accesskey":"your accesskey",
  "channel":"getFinanceRecords",
  "coin":"qc",
  "event":"addChannel",
  "pageIndex":1,
  "pageSize":10,
  "sign":签名
}



// java demo
public void getFinanceRecords() {
	//测试apiKey:ce2a18e0-dshs-4c44-4515-9aca67dd706e
	//测试secretKey:c11a122s-dshs-shsa-4515-954a67dd706e
	//加密类:https://github.com/zb2017/api/blob/master/zb_netty_client_java/src/main/java/websocketx/client/EncryDigestUtil.java
	//secretKey通过sha1加密得到:86429c69799d3d6ac5da5c2c514baa874d75a4ba
	String secret = EncryDigestUtil.digest("c11a122s-dshs-shsa-4515-954a67dd706e");
	//参数按照ASCII值排序
	String params = "{"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}";
	//sign通过HmacMD5加密得到:e950df0cff23a392fb738c8eeb2ef9dc
	String sign = EncryDigestUtil.hmacSign(params, secret);
	//最终发送到服务器参数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.cn/websocket"

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

        self.ws_sub_spot = None          # websocket应用对象  现货对象

    #----------------------------------------------------------------------
    def reconnect(self):
        """重新连接"""
        # 首先关闭之前的连接
        self.close()
        
        # 再执行重连任务
        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):
        """解压缩推送收到的数据"""
        # # 创建解压器
        # decompress = zlib.decompressobj(-zlib.MAX_WBITS)
        
        # # 将原始数据解压成字符串
        # inflated = decompress.decompress(evt) + decompress.flush()
        
        # 通过json解析字符串
        data = json.loads(evt)
        
        return data

    #----------------------------------------------------------------------
    def close(self):
        """关闭接口"""
        if self.thread and self.thread.isAlive():
            self.ws_sub_spot.close()
            self.thread.join()

    #----------------------------------------------------------------------
    def onMessage(self, ws, evt):
        """信息推送""" 
        print evt
        
    #----------------------------------------------------------------------
    def onError(self, ws, evt):
        """错误推送"""
        print 'onError'
        print evt
        
    #----------------------------------------------------------------------
    def onClose(self, ws):
        """接口断开"""
        print 'onClose'
        
    #----------------------------------------------------------------------
    def onOpen(self, ws):
        """接口打开"""
        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):
        #参数按照ASCII值排序: {"accesskey":"ce2a18e0-dshs-4c44-4515-9aca67dd706e","channel":"getFinanceRecords","coin":"qc","event":"addChannel","no":"test001","pageIndex":"1","pageSize":"10"}
        #secretKey 加密后:86429c69799d3d6ac5da5c2c514baa874d75a4ba
        SHA_secret = self.__digest(self.secretKey)
        #计算出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 


响应示例


// 返回结果
{
  "success":true,
  "code":1000,
  "data":[
		{
			"id"                : 156,
			"userId"            : 110803,
			"userName"          : "13427002684",
			"fundType"          : 15,
			"coinName"          : "QC",
			"amount"            : "10",
			"hasAmount"         : "0",
			"status"            : 0,
			"statusShow"        : "未有借入",
			"createTime"        : 1524541195000,
			"interestRateOfDay" : "0.0012",
			"repaymentDay"      : 10,
			"isLoop"            : true,
			"inTimes"           : 0,
			"sourceType"        : 6
		},
		...
  ],
  "channel":"getFinanceRecords",
  "message":"操作成功",
  "no":"0"
}


参数名称 类型 取值范围
accesskey String accesskey
channel String getFinanceRecords
event String 直接赋值addChannel
coin STirng 币种
pageIndex int 当前页数
pageSize int 每页数量
no String 请求的唯一标识,用于在返回内容时区分
sign String 签名

返回值描述
success是否成功
code返回代码
message提示信息
channel请求的频道
no请求的唯一标识,用于在返回内容时区分
id理财ID
userId用户ID
userName用户名
fundType币种类型
coinName币种名称
amount理财金额
hasAmount已借出金额
status状态值
statusShow状态值对应中文
createTime发布时间
interestRateOfDay日利率
repaymentDay放贷天数
isLoop是否自动放贷
inTimes理财被借入次数
sourceType来源类型: 8”网页”,5”手机APP”,6”接口API”

加密方式

  • accesskey=08b38d11-445f-447f-9372-d255e10b91bd
  • secretKey=ad030fda-86c1-4d9e-b333-fefbc1fb89e8

在线加密工具: http://tool.oschina.net/encrypt?type=2

第一步: 使用sha1 加密 secretKey 得到 5b1f87b2375ad8e46abf5e8ac4577c50dcee7989

输入图片说明

第二步: 计算sign

  • demo获取用户信息,将相应的参数进行拼接得到最终结果:accesskey=08b38d11-445f-447f-9372-d255e10b91bd&method=getAccountInfo
  • 使用secretKey通过sha1加密的字符串:5b1f87b2375ad8e46abf5e8ac4577c50dcee7989 作为哈希值
  • 计算得到最终sign: 48a1af2ea626dde38134ff8a51d8d0c3 输入图片说明

常见问题

  1. 开通API?

    • 登录后进入此链接进行API设置https://vip.zb.com/u/safe/api
    • 点击API设置---->点击开启API---->填入短信验证码---->开启
    • 绑定API交易IP则限制用API交易的IP只能为绑定IP,不绑定则不限制
  2. 生成的密钥有什么用处?

    • 密钥是用来操作API的钥匙,在调用API接口时需要,私有密钥只在刚生成时显示一次,遗忘需重新生成。
  3. API时常见错误time-out访问超时?

    • 绑定hosts文件,API群文件有绑定方式,或者手动绑定,境内服务器绑定后仍超时需翻墙
    • 47.91.169.147 api.zb.com
    • 52.55.212 trade.zb.com
    • windows系统C:\Windows\System32\drivers\etc\hosts
    • mac/linux系统 /etc/hosts
  4. 为什么报1003等错

    • 检查加密是否按照ASCII值排序加密、参数是否有漏掉或多余字符连接符等。
  5. 提示1002错误无效参数
    • 传参参数无效
  6. k线图是否可以获取几个月或者一年前的数据
    • 系统k线图最多只提供1000条数据,如果要获取比较久的数据需要使用小时或者天的单位获取
  7. api的ip是否需要绑定?

    • api的ip绑定有效的防止除了这个ip之外的服务器进行调用自己的权限进行交易操作
    • api绑定必须是公网的静态ip如果个人开发的pc端是不需要绑定的,api交易api此时可以为空
    • api交易留空就是不限制ip
  8. api是否支持随意提币?

    • 不支持,提币必须现在zb官网认证提币地址后才能进行api提币
    • api提币必须提供交易密码
  9. 公钥私钥可以提供给别人吗?

    • 不建议,会导致资产损失
  10. qc是否是人民币

    • 不是,qc和人民币是1:1换算的
  11. 为什么会有1002内部错误
    • 服务器压力或者请求量过大导致偶尔出现的,重新调用就可以

错误代码

rest返回码

返回码描述
1000 调用成功
1001 一般错误提示
1002 内部错误
1003 验证不通过
1004 资金安全密码锁定
1005 资金安全密码错误,请确认后重新输入。
1006 实名认证等待审核或审核不通过
1009 此接口维护中
1010 暂不开放
1012 权限不足
1013 不能交易,若有疑问请联系在线客服
1014 预售期间不能卖出
2001 人民币账户余额不足
2002 比特币账户余额不足
2003 莱特币账户余额不足
2005 以太币账户余额不足
2006 ETC币账户余额不足
2007 BTS币账户余额不足
2008 EOS币账户余额不足
2009 BCC币账户余额不足
3001 挂单没有找到或已完成
3002 无效的金额
3003 无效的数量
3004 用户不存在
3005 无效的参数
3006 无效的IP或与绑定的IP不一致
3007 请求时间已失效
3008 交易记录没有找到
4001 API接口被锁定或未启用
4002 请求过于频繁

websocket返回码

返回码描述
1000 调用成功
1001 一般错误提示
1002 内部错误
1003 验证不通过
1004 资金安全密码锁定
1005 资金安全密码错误,请确认后重新输入。
1006 实名认证等待审核或审核不通过
1009 此接口维护中
1010 暂不开放
1012 权限不足
1013 不能交易,若有疑问请联系在线客服
1014 预售期间不能卖出
2001 人民币账户余额不足
2002 比特币账户余额不足
2003 莱特币账户余额不足
2005 以太币账户余额不足
2006 ETC币账户余额不足
2007 BTS币账户余额不足
2008 EOS币账户余额不足
2009 BCC币账户余额不足
3001 挂单没有找到或已完成
3002 无效的金额
3003 无效的数量
3004 用户不存在
3005 无效的参数
3006 无效的IP或与绑定的IP不一致
3007 请求时间已失效
3008 交易记录没有找到
4001 API接口被锁定或未启用
4002 请求过于频繁