beta

用户API-HTTP接口

Rest API(http)

HTTPAPI

ZBX provides users with a simple and powerful API, which aims to help users integrate ZBX transaction functions into their own applications quickly and efficiently.

API Address Domain Name Address

Domain name address:https://www.zbx.com/

Instructions

Before using these APIs, two parameters should be obtained. After login, the API function should be turned on and then the parameters of Api Id and Api Secret should be obtained. Through these two parameters, we have high privileges to place orders, withdraw money and so on. Please keep them confidential. All HTTP interfaces need to be signed, and the signature rules are explained later.

1 Configuration and Basic Function API

1.1 Get Market List

path:/exchange/config/controller/website/marketcontroller/getByWebId
Request method:get/post
Request message

nothing

Return successful message


{
  { "datas": [
    {
      "amountDecimal": 8,//Quantitative accuracy
      "minAmount": "0.0001000000",//Minimum quantity
      "buyerCurrencyId": "2",//Buyer's currency
      "priceDecimal": 8,//Price accuracy
      "serverId": "entrust-server-001",//Service ID
      "marketId": "70",//Market ID
      "webId": "100", //Site ID
      "modifyTime": 0,
      "sellerCurrencyId": "19", //Seller's currency
      "createTime": 1522400906009,
      "defaultFee": "0.00050000",   //Default rate
      "name": "eth_btc",    //Market name
      "leverType": "1",     //Leverage Type: 1 Spot 2 Leverage
      "state": 1, //Status: 1 runs, 2 stop(Cannot place an order) 0 stops - 1 deletes
      "isMining":0,    //Whether mining: 1 is 0 is not
      "openTime": 1,//Time,Timestamp in milliseconds
    },
    ....
  ],
  "resMsg": {
    "code": "1",
    "method": null,
    "message": "success !"
  }
}

1.2 Get the currency list

path:/exchange/config/controller/website/currencycontroller/getCurrencyList
Request method:get/post
Request message

nothing

Return successful message

{
  "datas": [
    {
      "totalNumber": "230000000.00000000",//Total
      "tradeSearchUrl": null,//Transaction query address
      "tokenCoinsId": 0,//If greater than 0 is the token of another currency, otherwise it is equal to 0.
      "minCash": null,
      "tokenName": null,//
      "description": "BTC",//describe
      "arithmetic": null,   //Consensus algorithm
      "dailyDrawLimit": 10000,
      "remark": null,   //
      "isLegalCoin": 0, //Is it a French currency, such as US dollar 1, 0, not it?
      "outConfigTimes": 0,//
      "timesFreetrial": "0",//
      "hourFreetrial": "0",//
      "inConfigTimes": 6,//
      "alias": "b",//alias
      "logo": "market-btc.png",//Icon
      "needBlockUrl": 0,//Do you need a block address? 0 does not need 1.
      "currencyId": "2",//Currency ID
      "drawFlag": 1,
      "rechargeFlag": 1,
      "onceDrawLimit": 100,
      "founder": null,
      "drawFee": "0.00100000",
      "blockChainUrl": "https://blockchain.info/tx/", //blockChainQuery address (block query address)
      "dayFreetrial": "0",
      "marketValue": null,//Total market value
      "minFee": null,
      "teamAddress": null,
      "defaultDecimal": 2,//Currency decimal (precision) - Priority lower than market configuration
      "publishNumber": "14500000.00000000",//issued
      "isMining": "0",//Is it mineable?
      "name": "btc",//Name
      "limitAmount": null,
      "websiteCurrencyId": "223f4d23232",
      "state": 1,    //Status -1 Delete 0 Disable 1 Enable Default 1
      "descriptionEnglish": "<p>The BTC is ...</p>",//English description
      "mark": null//Symbol
    },
    .....
  ],
  "resMsg": {
    "code": "1",
    "method": null,
    "message": "success !"
  }
}

2 Getting User Information Interface

2.1 Getting User Information Interface

path:/exchange/user/controller/website/usercontroller/getuserinfo
Request method:get/post
Request message

nothing

Return successful message

{
"datas":{
"loginMobileAuth":0,//Whether Mobile Authentication: 0: No, 1: Yes
"googleStatus":0,//Audit status: 0: no audit, 1: revision audit
"isAlipay":"",//Whether bind Alipay 1 binding 0 unbound
"loginPwd":"1",//Whether to set login password: 0: no, 1: yes
"externalUidType":null,//Extended userid source types, such as: zb, BW
"isWechat":"",//Whether Binding Wechat 1 Binding 0 Unbound
"loginAuth":3,//Login authentication (1-login password 2-remote login authentication 4-Google authentication, can be any combination of the three, default 3
"merchantName":"",//Merchant name
"countryCode":"+86",//Country code
"loginName":"130***17",//Login name
"loginGoogleAuth":1,//Whether Google Certification: 0: No, 1: Yes
"email":null,//email
"nickName":"130***17",//nickname
"isBank":"",//Whether to bind banks
"mobileAuth":1,//Whether mobile phone authentication: 0: no, 1: yes, [2: modification failed, failed, -1: modification audit]
"mobile":"+86 130***17",//Phone Number
"userId":"test6",//User ID
"recommendCode":"dGVzdDY=\u000a",//Recommendation code
"realName":"",//User real name
"withdrawAuth":3,//Cash withdrawal verification (1 - Fund password 2 - short message / mailbox verification 4 - Google verification code default fund password + short message / mailbox = 3)
"recommendCount":null,//Referrals
"externalUserId":null,//Extended userid, such as ZB one-click login saved ZB userid
"mobileStatus":0,//Audit status: 0: no audit, 1: revision audit
"safePwdAuth":0,//Whether to set a security password: 0: No, 1: Yes
"googleAuth":1,//Whether Google Certification: 0: No, 1: Yes
"loginEmailAuth":0,//Whether Mailbox Authentication: 0:No, 1:Yes
"tradeAuth":1,//Transaction Verification (1 - Never enter the capital password for 2 - 6 hours, no capital password for 3 - Verify the capital password for each transaction)
"status":1//0 (000-initial state) 1 (001-authenticated by real name), 2 (010-authenticated by bank) 3 (011 authenticated by real name and bank)
},
"resMsg":{
"code":"1",
"method":null,
"message":"success !"
}
}

3 Rest API

3.1 New entrustment:

path:/exchange/entrust/controller/website/EntrustController/addEntrust
Request method:post
Request message format:application/json
Request message


{
  "amount": 0,                          //Order quantity
  "type": 0,                            //Sale Type: 0 Sell 1 Purchase
  "rangeType": 0,                       //The constant is 0.
  "marketId": "90",                     //Market ID
  "price": 0                            //Price
}

Return message:

{
  "datas":{
    “entrustId”:"E6419466484531482624"  //OrdersID
  },
  "resMsg":{
    "code":"1",                        //1Representative success, other explanations for error codes
    "method":null,
    "message":"success !"
  }
}

3.2 Cancellation of delegation

path: /exchange/entrust/controller/website/EntrustController/cancelEntrust
Request method:post
Request message format: application/json
Request message:

{
  "entrustId": "E6419466484531482624",  //Delegate ID to cancel
  "marketId": "90"                     //Market ID
}

Return message:

{
  "datas":null,
  "resMsg":{
    "code":"1",                        //1Representative success, other explanations for error codes
    "method":null,
    "message":"success !"
  }
}

3.3 Enquiry on on-going entrustment

This interface only returns orders with status (status) as part of the start and transaction, and supports paging.
path: /exchange/entrust/controller/website/EntrustController/getUserEntrustRecordFromCache
Request method:post
Request message:key-value

marketId: 90                    //Market ID
pageSize: 4 //PageSize
pageIndex: 1 //PageNo,Starting from 1

Return message:

json
            {
                "datas": {
                    "entrustList":[
                        {
                          "amount":"7",                     //Amount
                          "availabelAmount": "3.02",      //The number of remaining transactions
                          "completeAmount": "1.99",       //Number of transactions completed
                          "completeTotalMoney":"15.92",     //Total amount completed
                          "totalMoney":"56.003",                //Total sum
                          "rangeType":0,                        //Interval Type 0 Current Order 1 Interval Order
                          "rangeLowPrice":null,             //Minimum Price of Interval Delegation
                          "rangeHighPrice":null,                //Maximum Price of Interval Delegation
                          "entrustId":"E6437955999037923328",   //OrdersID
                          "type":0,                         //0 Sell 1 Buy - 1 Cancel
                          "userId":"test6",                 //User ID
                          "dealTimes":1,                    //Number of transactions processed
                          "createTime":1534928321609,       //order time
                          "price":"8.00005",                //Unit Price
                          "entrustType":0,              //Entrustment Type 0 General Entrustment Order 1 Leverage Entrustment Order
                          "status":0     //Status : -2 funds unfrozen failed -1 user funds are insufficient 0 start 1 cancel 2 transaction success 3 transaction part 4 cancel
                        }
                    ],
                        "totalRow":1,  //Total number of banks
                        "pageNum":1,   //PageNo,Starting from 1
                        "pageSize":4,  //PageSize
                        "totalPage":1  //PageCount
                },
                "resMsg": {
                "code": "1",            //1 represents success, others are error codes.
                "method": null,
                "message": "success !"
                }
            }
            

3.4 Paging queries for historical delegation (queries only for completed and cancelled delegation records)

This interface only returns orders with status (status) as part of the start and transaction, and supports paging.
paht: /exchange/entrust/controller/website/EntrustController/getUserEntrustList
Request method:get
Request message:body json

marketId:   90                      //Market ID
pageIndex:  1               //Page number
pageSize:   20              //Number of display items per page
type=0                      //(optional) delegate type, 0 sell 1 purchase -1 cancel
status=0                    //(optional) status: -2 funds unfreeze failed -1 user insufficient funds 0 start 1 cancel 2 trade success 3 trade one 4 cancel
startDateTime=1533204010299    //(Optional) The start time of the order placed, 13-bit time stamp
endDateTime= 1534204030299     //(Optional) The end time of the order placed, 13-bit time stamp

Return message:

json
{
    "datas": {
        "entrustList": [{
            "amount": "43.730000000000000000”,                //Amount
            "rangeType": 0,                                    //Interval Type: 0 Present Price Delegation 1 Interval Delegation
            "rangeLowPrice": null,                              //Minimum Price of Interval Delegation
            "customerOrderId": null,                            //Internal delegate ID of the site
            "rangeHighPrice": null,                             //Maximum Price of Interval Delegation
            "totalMoney": "31.603671000000000000”,            //Total sum
            "entrustId": "E6434001988198871040”,              //Delegate ID
            "type": 1,                           				//0 Sell 1 Buy - 1 Cancel
            "userId": "7eiiEs6gmlE”,            				 //User ID of site
            "freezeId": "Z6434001988224442368”, 			 //Freeze Id and store cancelled ID when cancelled
            "completeAmount": "43.730000000000000000”,	//Number of transactions completed
            "marketId": "302”,                   			//Market ID
            "dealTimes": 1,                      			//Number of transactions processed
            "webId": "102”,                      				//Website ID
            "createTime": 1533985611963,        				 //Sending time
            "price": "0.722700000”,             			 //Unit Price
            "completeTotalMoney": "31.603671000000000000”,   //Total amount completed
            "entrustType": 0,                               //Entrustment Type 0 General Entrustment Order 1 Leverage Entrustment Order
            "sumToWeb": 1,                      				 //Whether to merge into the main project': default is 1
            "status": 2                                        //Status : -2 funds unfrozen failed -1 user funds are insufficient 0 start 1 cancel 2 transaction success 3 transaction part 4 cancel
    }],
        "totalPage": 1,
        "currentPage": 1
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

3.5 Query the delegation record according to the delegation ID

path: /exchange/entrust/controller/website/EntrustController/getEntrustById
Request method:get
Request message:key-value

marketId:   90                      //Market ID
entrustId:  E6419443135315070976    //Delegate ID to query

Return message:

json
            {
                "datas":
                {
                        "amount": "43.730000000000000000”,                //Amount
                        "rangeType": 0,                                    //Interval Type: 0 Present Price Delegation 1 Interval Delegation
                        "rangeLowPrice": null,                              //Minimum Price of Interval Delegation
                        "customerOrderId": null,                            //Internal delegate ID of the site
                        "rangeHighPrice": null,                             //Maximum Price of Interval Delegation
                        "totalMoney": "31.603671000000000000”,            //Total sum
                        "entrustId": "E6434001988198871040”,              //Delegate ID
                        "type": 1,                           				//0 Sell 1 Buy - 1 Cancel
                        "userId": "7eiiEs6gmlE”,            				 //User ID of site
                        "freezeId": "Z6434001988224442368”, 			 //Freeze Id and store cancelled ID when cancelled
                        "completeAmount": "43.730000000000000000”,	//Number of transactions completed
                        "dealTimes": 1,                      			//Number of transactions processed
                        "webId": "102”,                      				//Website ID
                        "createTime": 1533985611963,        				 //Sending time
                        "price": "0.722700000”,             			 //Unit Price
                        "completeTotalMoney": "31.603671000000000000”,   //Total amount completed
                        "entrustType": 0,                               //Entrustment Type 0 General Entrustment Order 1 Leverage Entrustment Order
                        "sumToWeb": 1,                      				 //Whether to merge into the main project': default is 1
                        "status": 2                                        //Status: - 2 Failure of fund thawing - 1 User's fund is insufficient 0 Initiation 1 Cancellation 2 Transaction Success 3 Transaction Part 4 Matching Completion Waiting for fund change
                                                                                //13 Parts Completed Waiting for Change of Funds 12 Parts Completed Waiting for Change of Funds

            },
                "resMsg": {
                "code": "1",            //1 represents success, others are error codes.
                "method": null,
                "message": "success !"
                }
            }

4 Financial Funds API

4.1 Get the currency address

path:exchange/fund/controller/website/fundcontroller/getPayinAddress
Request method:post
Request message format:application/json
Request message:body json

{
    “currencyTypeName”:"btc" //Currency Type Name (Bizhuan)
}

Return message


{
    "datas": {
        "address": "19cdJwd3j6ArHNhiYoWpN8cJq9ash7WDDC",//Coin address
        "isMemo": false,
        "memo": ""
        "account": ""
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

4.2 Search for Filling Records

path:exchange/fund/controller/website/fundcontroller/getPayinCoinRecord
Request method:post
Request message format:application/json
Request message:body json

{
    “currencyTypeName”:“qtum”, //Currency type
    “sort”:1 //No passes are arranged in reverse order according to filling time, and passes are arranged in ascending order.,
    "pageNum":1
    "pageSize":20
}

Return message

{
    "datas": {
        "totalRow": 1,  //Total number of banks
        "totalPage": 1, //PageCount
        "pageSize": 20, //Transactions per page
        "list": [
            {
                "currencyTypeId": 1,//Currency type ID
                "depositId": “f3342424”,//Recharge the primary key
                "amount": "10.0",//Amount of money charged
                "confirmTimes": "4",//Confirmation times
                "createTime": "2018-03-10 10:22:09.0",//Charging time
                "depositAddress": "1BKd2sSPYzxC2XHurR6oQWc2wzSx2rZzck",//Coin address
                "txId": "6378183001917882368",//Transaction ID
                "userId": "1",//User ID
                "status": 1,//& #39; 0: Not yet in the accounts 1: Has been in the accounts & #39;

            }
        ],
        "pageNum": 1
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

4.3 Inquiry for withdrawal records

path:/exchange/fund/controller/website/fundwebsitecontroller/getpayoutcoinrecord
Request method:get
Request message:key-value

currencyId=1    //Currency ID
tab=all         //(required) | all (all), wait (submitted, not audited), success (audited), fail (audited failure), cancel (user cancels voluntarily)
pageIndex=1     //Bizhuan, default 1
pageSize=10     //Bizhuan, default 10

Return message

{
    "datas": {
        "totalRow": 34,                                          //Total number of banks
        "totalPage": 4,                                          //PageCount
        "pageSize": 10,                                          //Transactions per page
        "list": [
            {
                "modifyUid": null,                               //Amendment ID
                "withdrawalId": "W6419027628808093696",          //Cash withdrawal ID
                "fees": "0.001000000000000000",                  //Transaction fee
                "amount": "10.000000000000000000",               //Quantity of withdrawals
                "userApplyWithdrawId": "7eBDJ5PKbSK",            //Withdrawal record ID
                "verifyRemark": null,                            //Audit opinion
                "remark": null,                                  //Remarks
                "verifyTime": 0,                                 //Audit time
                "userName": "[email protected]",                  //User name
                "userId": "7e9ioSoVXcW",                         //User ID
                "actuallyAmount": "10.000000000000000000",       //Actual Achievement Quantity
                "modifyTime": 0,                                 //Modification time
                "verifyStatus": 0,                               //Audit status (0 to be audited, 1 to pass - 1 to fail)
                "createTime": 1530415446577,                    //Money raising time
                "state": 1,                                                             //Status (- 1 deleted, 1 normal)
                "currencyId": "2",                                                          //Currency ID
                "withdrawalAddress": "1JimMZks39eVqU6T3v6wvz1m4LtJ3tPjGL",                  //Money withdrawal address
                "verifyUid": null                                                           //Auditor ID
            }
        ],
        "pageNum": 1
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

4.4 Obtain all funds information from users

path:/exchange/fund/controller/website/fundcontroller/findbypage
Request method:post
Request message format:application/json
Request message:body json


{
    "pageSize":30,       # Number of lines per page (must pass)
    "pageNum":1          # Page number (must pass)
}

Return message


{
    "datas": {
        "totalRow": null,
        "totalPage": null,
        "pageSize": 30,
        "list": [
            {
                "currencyTypeId": 1,                      //Currency type ID
                "amount": "0",                           //Current amount of funds available to users
                "fundId": "F3785385345384r84337",
                "freeze": "122.000000000000000000",      //The amount of funds frozen by users
                "saved": "122.000000000000000000",      //Deposit freezing (this parameter is not displayed when the number is 0)
                "modifyTime": "2018-02-19 10:02:33",
                "webId":"102",                           //Site Id
                "createTime": "2018-02-19 10:02:33",
                "depositAddress": null,                    //Coin address
                "userId": "7sefsudf3fr1"                   //User Id
            },
            {
                "currencyTypeId": 81,
                "amount": "0",
                "freeze": "122.000000000000000000",
                "modifyTime": "2018-02-19 10:02:33",
                "webId":"102",
                "createTime": "2018-02-19 10:02:33",
                "depositAddress": null,
                "userId": "7sefsudf3fr1"
            }
        ],
        "pageNum": 1
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}
        

4.5 Inquire the address of withdrawal money

path:/exchange/fund/controller/website/fundwebsitecontroller/getwithdrawaddress
Request method:get
Request message formdata key-value to submit

currencyId=2          //(Biography)
pageIndex=1           //(Bizhuan, default 1)
pageSize=10           //(Bizhuan, default 10)

Return message

{
    "datas": {
        "totalRow": 2,
        "totalPage": 1,
        "pageSize": 10,
        "list": [
            {
                "address": "1DkwrD4bMtjd6kcZw8CxM9r3z4AGVFfSRz",    //address
                "modifyTime": 1524217688882,                        //Modification time
                "currencyName": "btc",                              //Currency name
                "createTime": 1523185357488,                        //Money raising time
                "userFundAddressId": "7bwK95B7jTk",                 //Address ID
                "remark": "correct",                                //Remarks
                "currencyId": "2",                                  //Currency ID
                "type": 1,                                          //(1-Telling address, 2-Telling address)
                "userName": "Mr.牛",                                //User name
                "userId": "7e8fMkzTlL6",                            //userId
                "status": "1"                                       //Status (- 1 deleted, 1 normal)
            }
        ],
        "pageNum": 1
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

5 Signature and Cryptographic Encryption Rules

5.1 Signature rule

Signature string sign = MD5 (Apiid + Timestamp + parameter content concatenation + signature secret key), signature secret key is Api Secret, and Apiid is obtained when Api function is opened on the website. There are three kinds of parameter concatenation rules, only empty string of header parameter & quot; & quot;, body JSON parameter JSON string format, key-value and get parameter content concatenation for all parameters. Sort by the first letter of the key value and then spell in the form of key1 + value1 + key2 + Value2.. After signing, put Apiid, Timestamp, Sign in the request header, pay attention to the capitalization of the initials, followed by all lowercase.
For example, after opening the API function on the website, you get the following two parameters Apiid=7eESLc0x69I7eESLc0x69J,Apisecret = 87ceba599b6d39a39deb01cf71eacd57,Timestamp=1533179478000,
a、Body json Format parameter

The parameter content json string is:{"userId":"u111","name":"zhangsan"}
Parameter content is as follows:{"userId":"u111","name":"zhangsan"}
Sign = md5(7eESLc0x69I7eESLc0x69J1533179478000{"userId":"u111","name":"zhangsan"}87ceba599b6d39a39deb01cf71eacd57)
= 9bd4ef5f834add851badb0bbd5bb0f2c   

b、No body or get parameters

Parameter content string is empty
Sign = md5(7eESLc0x69I7eESLc0x69J153317947800087ceba599b6d39a39deb01cf71eacd57)
= 935b6a59860cc12e802e5dee30c6a614 

c、formdata key-value,Or get parameters

The parameter content is:userid=10,status=1,acount = 10
Parameter content is as follows:account10status1userid10
Sign = md5(7eESLc0x69I7eESLc0x69J1533179478000account10status1userid1087ceba599b6d39a39deb01cf71eacd57)
= 6f732b47933684dd11a770d6575f43fa   

Provide the Java version of the signature code as follows, other languages please refer to the code to achieve their own

import com.alibaba.fastjson.JSON;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:
 * @Description:
 * @Date: Created in 2018/6/26
 * @Modified By:
 */
public class SignUtils {
    private static Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    /**
     * Set it up according to your needs, generally think that only one is used in a service.
     */
    public static String ID_NAME = "Apiid";

    /**
     * cannot null
     *
     * @param source
     * @return
     */
    public static boolean isEmpty(String source) {
        return source == null || source.isEmpty() || source.equals("\"\"") || source.trim().equals("{}");
    }

    /**
     *
     * @param parameters
     * @return
     */
    public static Map getHeaderOfKeyValue(String id, String secret,Map parameters) {
        long time = System.currentTimeMillis();
        Map header = new HashMap();
        StringBuffer contentSb = new StringBuffer();
        parameters = new TreeMap<>(parameters);
        Iterator it = parameters.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            contentSb.append(entry.getKey()).append(entry.getValue());
        }

        header.put(ID_NAME,id);
        header.put("Timestamp", String.valueOf(time));
        header.put("Sign", encryptMD5(id + time + contentSb.toString() + secret));
        return header;
    }

    /**
     *
     * @return
     */
    public static Map getHeaderOfNoParams(String id, String secret) {
        Map header = new HashMap();
        long time = System.currentTimeMillis();
        header.put(ID_NAME, id);
        header.put("Timestamp", String.valueOf(time));
        header.put("Sign", encryptMD5(id + time + secret));
        return header;

    }

    /**
     *
     * @param object
     * @return
     */
    public static Map getHeaderOfBodyJson(String id, String secret, Object object) {
        Map header = new HashMap();
        long time = System.currentTimeMillis();
        String params = JSON.toJSONString(object);
        header.put(ID_NAME, id);
        header.put("Timestamp", String.valueOf(time));
        header.put("Sign", encryptMD5(id + time + params + secret));
        return header;
    }

    public static String encryptMD5(String str) {
        return digest("MD5", str);
    }

    public static String digest(String code, String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(code);
            messageDigest.reset();
            messageDigest.update(str.getBytes(DEFAULT_CHARSET));
            byte[] byteArray = messageDigest.digest();
            StringBuffer md5StrBuff = new StringBuffer();

            for(int i = 0; i < byteArray.length; ++i) {
                if (Integer.toHexString(255 & byteArray[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(255 & byteArray[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(255 & byteArray[i]));
                }
            }

            return md5StrBuff.toString();
        } catch (NoSuchAlgorithmException var6) {
            var6.printStackTrace();
            return null;
        }
    }
}

6Market class interface

Note that the market quotation class interface does not require signature, and the header does not need to pass several parameters of the signature. This part of the interface can only access 1000 times in one minute, please pay attention to the control frequency.

6.1 All market 24H market prices

This data server update speed is 10 seconds, not too frequent
path:/api/data/v1/tickers
Request method:get
Request message

isUseMarketName=true          //Bizhuan, choose true and return the results with market names such as BTC_USDT instead of market Id, while false uses market Id.

Return message in two formats
isUseMarketName = fasle

{
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    },
    "datas": [
        [
            99,
            "0.0",
            "0",
            "0",
            "0",
            "0.0",
            "[]",
            "9.396",
            "9.08",
            "21469873.428"
        ],
        [
            90,
            "8249994.968",
            "8257720.9458",
            "8207608.58",
            "1080294.9779",
            "0.51",
            "[[1, 8219706.597], [2, 8249994.998]]",
            "7418805.42381067",
            "7418805.425",
            "21469873.428"
        ]
    ]
}

isUseMarketName = true

{
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    },
    "datas": {
        "ETC_USDT": [
            99,
            "0.0",
            "0",
            "0",
            "0",
            "0.0",
            "[]",
            "9.296",
            "9.708",
            "21469873.428"
        ],
        "BTC_KRW": [
            90,
            "8245004.195",
            "8257720.93",
            "8207608.57",
            "1187226.0187",
            "0.45",
            "[[1, 8219706.597], [2, 8245004.125]]",
            "7418805.413",
            "7418805.47",
            "21469873.408"
        ]
    }
}

Data description

[ Market ID, latest transaction price, highest price, lowest price, 24-hour volume, 24-hour price increase, recent 6H closing price list, buy one price, sell one price, 24-hour turnover (unit is buyer's currency)]

The list of recent 6H closing prices is sorted in chronological order, data description:

[[Serial number, Closing price], [Serial number, Closing price], [Serial number, Closing price]]

6.2 Single market 24H market

This data server update speed is 10 seconds, not too frequent
path:/api/data/v1/ticker
Request method:get
Request message

marketId=99          //Market id, and market name can be passed on one.
marketName=ETC_USDT          //Market name, and market ID can be passed on one.

Return message format

{
    "datas": [
        99,
        "826.4023",
        "826.4023",
        "820.5862",
        "172.1401",
        "0.73",
        "[[1, 821.597], [2, 826.7998], [3, 826.4023]]",
        "741.4126",
        "741.4237",
        "2143.408"
    ],
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

Data description

[ Market ID, latest transaction price, highest price, lowest price, 24-hour volume, 24-hour price increase, recent 6H closing price list, buy one price, sell one price, 24-hour turnover (unit is buyer's currency)]

The list of recent 6H closing prices is sorted in chronological order, data description:

[[Serial number, Closing price], [Serial number, Closing price], [Serial number, Closing price]]

6.3 Kline WebSocket

path:/api/data/v1/klines
Request method:get
Request message

marketId=99                     //Market id, and market name can be passed on one.
marketName=ETC_USDT             //Market name, and market ID can be passed on one.
type=1M                         //K-line type, support 1M, 5M, 15M, 30M, 1H, 1D, 1W seven types, respectively, representing 1-30 minutes, 1 hour, 1 day, 1 week
dataSize=5                      //Data volume, up to 500

Return message format

{
    "datas": [
        [
            "K",
            "99",
            "etc_usdt",
            "1532181600",
            "826.7",
            "827.68",
            "826.68",
            "826.07",
            "492261",
            "0.04",
            "6.8",
            "1H",
            "false",
            "407073731.01"
        ],
        ..........
    ],
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

Data description

[Data type, market ID, market name, time stamp, opening data, highest price, lowest price, closing price, volume, price range, dollar exchange rate, K line period, whether converted]

6.4 Transaction Records

path:/api/data/v1/trades
Request method:get
Request message

marketId=99                     //Market id, and market name can be passed on one.
marketName=ETC_USDT             //Market name, and market ID can be passed on one.
dataSize=10                     //Data volume, up to 500

Return message format

{
    "datas": [
        [
            "T",
            "99",
            "1532183063",
            "ETC_USDT",
            "bid",
            "827.90",
            "515.50"
        ],
        ..........
    ],
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

Data description

[data type, market ID, timestamp, market Name, buy and sell type (asks sell bids buy), price, volume]

6.5 Handicap data (The depth of market)

This interface returns the market data of up to 50 files.
path:/api/data/v1/entrusts
Request method:get
Request message

marketId=99                     //Market id, and market name can be passed on one.
marketName=ETC_USDT             //Market name, and market ID can be passed on one.
dataSize=5                      //The number of stalls, which means 5 stalls for sale and 50 stalls for sale.

Return message format

{
    "datas": {
        "asks": [
            [
                "824.898",
                "5.95"
            ],
            [
                "741.435",
                "4.88"
            ],
            [
                "741.47",
                "0.01"
            ]
        ],
        "bids": [
            [
                "294",
                "24.32"
            ],
            [
                "247",
                "2.064"
            ],
            [
                "216",
                "17.043"
            ]
        ],
        "timestamp": "1532183394"
    },
    "resMsg": {
        "code": "1",
        "method": null,
        "message": "success !"
    }
}

Data description

asks:(sell)[[Price,  Volume]]
bids:(buy)[[Price,  Volume]]

7 Complete Demo

JavaPython
                        
# ! /usr/bin/env python
# -*- coding:utf-8 -*-
from ws4py.client.threadedclient import WebSocketClient
import time
import hashlib
import requests
import json
"""
简单刷单demo
订阅行情,在买1卖1平均价自买自卖(未处理不成交的情况)
更多复杂功能轻自行修改实现
"""


class Bw:
def __init__(self, key, secret):
    self.base_url = 'https://www.zbx.com'  # Trading address
    self.key = key
    self.secret = secret

def public_request(self, method, api_url, **payload):
    """request public url"""
    r_url = 'https://www.zbx.com/' + api_url
    try:
        r = requests.request(method, r_url, params=payload)
        r.raise_for_status()
        if r.status_code == 200:
            return True, r.json()
        else:
            return False, {'error': 'E10000', 'data': r.status_code}
    except requests.exceptions.HTTPError as err:
        return False, {'error': 'E10001', 'data': r.text}
    except Exception as err:
        return False, {'error': 'E10002', 'data': err}

def get_trades(self, symbol):
    """get detail trade"""
    return self.public_request('GET', 'market/trades/{symbol}'.format(symbol=symbol))

def signed_request(self, method, api_url, **payload):
    """request a signed url"""
    timestamp = str(int(time.time() * 1000))
    full_url = self.base_url + api_url

    param = ''
    if method == 'GET' and payload:
        param = json.dumps(''.join([key + '=' + str(payload[key]) for key in sorted(payload.keys())]))
    elif method == 'POST' and payload:
        # param = json.dumps({key: payload[key] for key in sorted(payload.keys())})
        param = json.dumps(payload)
    elif not payload:
        payload = ''

    sig_str = self.key + timestamp + param + self.secret
    signature = hashlib.md5(sig_str.encode('utf-8')).hexdigest()

    headers = {
        'Apiid': self.key,
        'Timestamp': timestamp,
        'Sign': signature
    }
    # print(self.key, timestamp, param, self.secret)
    # print(sig_str)
    # print(headers)

    try:
        r = requests.request(method, full_url, headers=headers, json=payload)
        r.raise_for_status()
        if r.status_code == 200:
            return True, r.json()
        else:
            return False, {'error': 'E10000', 'data': r.status_code}
    except requests.exceptions.HTTPError as err:
        return False, {'error': 'E10001', 'data': r.text}
    except Exception as err:
        return False, {'error': 'E10002', 'data': err}

def get_balance(self):
    a = {"pageSize": "30", "pageNum": "1"}
    return self.signed_request('POST', '/exchange/fund/controller/website/fundcontroller/findbypage', **a)

def get_info(self):
    return self.signed_request('POST', '/exchange/user/controller/website/usercontroller/getuserinfo')

def get_PayinAddress(self, name="btc"):
    a = {"currencyTypeName": name}
    return self.signed_request('POST', '/exchange/fund/controller/website/fundwebsitecontroller/getwithdrawaddress', **a)

def get_market(self):
    return self.signed_request('POST', '/exchange/config/controller/website/marketcontroller/getByWebId')

def create_order(self, **payload):
    """create order"""
    return self.signed_request('POST', '/exchange/entrust/controller/website/EntrustController/addEntrust', **payload)

def buy(self, marketId, price, amount):
    """buy someting"""
    return self.create_order(marketId=marketId, type=1, rangeType=0, price=price, amount=amount)

def sell(self, marketId, price, amount):
    """sell someting"""
    return self.create_order(marketId=marketId, type=0, rangeType=0, price=price, amount=amount)

def cancel_order(self, entrustId, marketId):
    payload = {'entrustId': entrustId, 'marketId': marketId}
    return self.signed_request('POST', '/exchange/entrust/controller/website/EntrustController/cancelEntrust', **payload)

def get_unfinish_order(self, marketId):
    return self.signed_request('GET', '/exchange/entrust/controller/website/EntrustController/getUserEntrustRecordFromCache', marketId = marketId)


class DummyClient(WebSocketClient):
def __init__(self, url):
    super(DummyClient, self).__init__(url)
    self.b = Bw(key='xxxxxx', secret='xxx')  # 填写自己的key和secret
    self.symbol = 'eth_usdt'  # 必须同时持有这两个币种,刷其他币对请修改symbol
    self.vol = 0.001  # 单次刷单量,最好先用小量试一下

    market = self.b.get_market()  # 获取基本市场信息
    if market[0]:
        for cur in market[1]['datas']:
            if cur['name'] == self.symbol:
                self.marketId = cur['marketId']  # 市场id
                self.price_decimal = cur['priceDecimal']  # 报价精度
                self.amount_decimal = cur['amountDecimal']  # 委托精度
                self.buy_id = int(cur['buyerCurrencyId'])  # 买方币种id
                self.sell_id = int(cur['sellerCurrencyId'])  # 买方币种id
                self.min_amount = float(cur['minAmount'])  # 最小委托量

    self.price_tick = 10 ** (-self.price_decimal)  # 最小价格变动单位
    self.data = {'asks': [], 'bids': []}

def opened(self):  # 订阅行情
    self.send('{"dataType": "' + self.marketId + '_ENTRUST_ADD_' + self.symbol.upper() + '","dataSize":1000,"action":"ADD"}')

def closed(self, code, reason=None):
    print("Closed down", code, reason)

def received_message(self, m):  # 接收行情
    data = eval(str(m))
    if data[0] != 'E' and data[0][0] == 'AE':
        self.data['asks'] = data[0][4]['asks']
        self.data['bids'] = data[0][5]['bids']
        self.data['ts'] = data[0][3]
    elif data[0] == 'E':
        self.data['ts'] = data[2]
        self.update_data(data)

    self.update_trade()  # 来一个行情刷一次

def update_data(self, data):  # 将行情格式规范好
    side = data[4].lower() + 's'
    for i in range(len(self.data[side])):
        if self.data[side][i][0] == data[5]:
            if data[6] != '0':
                self.data[side][i][1] = data[6]
            else:
                self.data[side].pop(i)
            return
        elif float(data[5]) > float(self.data[side][i][0]) and data[6] != '0':
            self.data[side].insert(i, [data[5], data[6]])
            return

    if data[6] != '0':
        self.data[side].append([data[5], data[6]])

def update_trade(self):  # 刷单逻辑部分
    ask1 = float(self.data['asks'][-1][0])
    bid1 = float(self.data['bids'][0][0])
    print('time:{}\task1:{}\tbid1:{}'.format(self.data['ts'], ask1, bid1))
    if ask1 - bid1 < self.price_tick * 1.5:  # 买1卖1至少相差两个档位才能刷单,不然会和别人成交
        print('价差太小,无法刷单!')
        return

    price = round((ask1 + bid1) / 2, self.price_decimal)  # 在买1卖2平均价位刷单
    buy_order = self.b.buy(self.marketId, price, self.vol)
    sell_order = self.b.sell(self.marketId, price, self.vol)
    print('{}\t{}\t{}\t{:.2f}\t{:.4f}'.format(self.data['ts'], self.marketId, self.symbol, price, self.vol))

    if buy_order[0] and 'datas' in buy_order[1] and buy_order[1]['datas']:
        a = self.b.cancel_order(buy_order[1]['datas']['entrustId'], self.marketId)
    if sell_order[0] and 'datas' in sell_order[1] and sell_order[1]['datas']:
        a = self.b.cancel_order(sell_order[1]['datas']['entrustId'], self.marketId)


if __name__ == '__main__':
ws = DummyClient('wss://kline.zbx.com/websocket')  # Websocket market subscription address
if hasattr(ws, 'marketId'):
    ws.connect()
    ws.run_forever()
else:
    print('信息获取失败!')  # 如果获取不到市场信息,检查网络是否有问题,是否要翻墙
                        
                    
                        
package io.test;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/*
    * note: The code adapts to the official website https server interface
    * jar  Version :httpclient-4.5.3.jar 、httpcore-4.4.6.jar
    *  Please refer to the official website for the error code.
    * */
public class BwApiDemos {
        private static final String zbxdomain name = "https://www.zbx.com";
        private static final String Get Market ListURL = "/exchange/config/controller/website/marketcontroller/getByWebId";
        private static final String Get the currency listURL = "/exchange/config/controller/website/currencycontroller/getCurrencyList";
        private static final String Acquire user informationURL ="/exchange/user/controller/website/usercontroller/getuserinfo";//
        private static final String New delegateURL = "/exchange/entrust/controller/website/entrustController/addEntrust";
        private static final String Cancellation of delegationURL = "/exchange/entrust/controller/website/EntrustController/cancelEntrust";
        private static final String Enquiry on on-going entrustment URL = "/exchange/entrust/controller/website/entrustController/getUserEntrustRecordFromCache";
        private static final String Paging query history delegation record URL="/exchange/entrust/controller/website/EntrustController/getUserEntrustList";
        private static final String Query the delegation record according to the delegation ID ="/exchange/entrust/controller/website/EntrustController/getEntrustById";
        private static final String Get the currency address URL="/exchange/fund/controller/website/fundcontroller/getPayinAddress";
        private static final String Search for Filling Records URL="/exchange/fund/controller/website/fundcontroller/getPayinCoinRecord";
        private static final String Inquiry for withdrawal records URL="/exchange/fund/controller/website/fundwebsitecontroller/getPayoutCoinRecord";
        private static final String Obtain all funds information from users URL="/exchange/fund/controller/website/fundcontroller/findbypage";
        private static final String Inquire the address of withdrawal money URL="/exchange/fund/controller/website/fundwebsitecontroller/getwithdrawaddress";
    private static final String Abolish consignment in batches URL = "/exchange/entrust/controller/website/EntrustController/batchCancelEntrustByMarketId";
        private static String API Access key  = "7fMCs1GQe7fMCsw1GQeP";//"7fMBgZfWzOC7fMBgZfWzOD";//[0-9a-zA-Z]//7fHskt6xdPk7fHskt6xdPl//7f6K9CGG4qO7f6K9CGG4qP
        private static String API Private key  ="f43e8280d994724db633241d3c1502";//"eed02fcdc4ecb7711b19ed0a29cb0550";//HexString//499b0780fa25007af59e9e9417e38912 //我的c7dc6c2e766bcd2a9499885c94f3e928
        public static Map Market transaction vs cache  = new HashMap<>();
        private static SSLConnectionSocketFactory sslsf = null;
        private static PoolingHttpClientConnectionManager cm = null;
        private static SSLContextBuilder builder = null;
        //SSL certificate verification correlation
        static {
            try {
                builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
                });
                sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
                Registry registry = RegistryBuilder. create().register("http", new PlainConnectionSocketFactory()) .register("https", sslsf) .build();
                cm = new PoolingHttpClientConnectionManager(registry);
                cm.setMaxTotal(200);//max connection
            } catch (Exception e) {
                e.printStackTrace();
                }
        }
        //HTTPS supported by wrapping HttpClient
        public static CloseableHttpClient getHttpClient() throws Exception {
            CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .setConnectionManager(cm)
            .setConnectionManagerShared(true)
            .build();
            return httpClient;
            }


        public static void   Initialization key (String Apiid,String Apisecret){
            BwApiDemos.API Access key  = Apiid;
            BwApiDemos.API Private key  = Apisecret;
        }

        public static void main(String[] args) throws Exception {
                //Basic API - ----------------------------------------------------------------------------------------------------------------
                  Market transaction vs cache  =   Get Market List ();
                  Get the currency list ();
                  Acquire user information ();
                //Transaction API
                String  Deliver successful order number  =  New delegate ("290",0,0.5,60);//Trading pair, trading direction (0 sell 1 buy), quantity, price
                String  Deliver successful order number 2=  New delegate ("290",1,0.5,50);
                Cancellation of delegation ("290","E6433935901914578944");//JSON request refers to this
                Enquiry on on-going entrustment ("290");//Key1: value1 requests to refer to this
                Paging query history delegation record ("302",1,20);
                Query the delegation record according to the delegation ID ("302","E6435033358698295296");
                Abolish consignment in batches ("302");
                //Financial Capital API
                Get the currency address ("btc");
                Search for Filling Records ("eth",1,1,20);
                Inquiry for withdrawal records (1,"all",1,10);
                Obtain all funds information from users (30,1);
                Inquire the address of withdrawal money (5,1,10);

        }


            /*Get the information you need based on the returned list */
            public static Map   Get Market List () throws Exception{
            System.out.println("Get the market list to start .....");
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name+  Get Market List URL);
            Md5 sign (httpPost, null,false);
            HttpResponse rsp=client.execute(httpPost);
            int status = rsp.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(rsp.getEntity());
                JSONArray json  = (JSONArray)  General analytical response ( Response message );
                if(json.size()>0){
                    System.out.println(" Get the market list successfully .....");
                    List mapListJson = (List)json;
                    Map marketsMapping = new HashMap();
                    //Return the corresponding transaction pair as needed
                    if(mapListJson.size()>0){
                        marketsMapping = mapListJson.get(0);
                    }
                    //Here only one transaction pair is returned as an example
                    return marketsMapping;
                }else return null;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*Get the information you need based on the returned list  */
        public static List   Get the currency list () throws Exception{
                System.out.println(" Get the currency list to start .....");
                    CloseableHttpClient client=getHttpClient();
                HttpPost httpPost=new HttpPost(zbxdomain name+  Get the currency list URL);
                Md5 sign (httpPost, null,false);
                HttpResponse rsp=client.execute(httpPost);
                int status = rsp.getStatusLine().getStatusCode();
                if(status==200){
                    String  Response message  = EntityUtils.toString(rsp.getEntity());
                        JSONArray json  = (JSONArray)  General analytical response ( Response message );
                    if(json.size()>0){
                        System.out.println(" Get the currency list successfully .....");
                        //Asset List
                        List mapListJson = (List)json;
                        System.out.println(" Get currency list results ------->"+JSONArray.toJSONString(mapListJson));
                        return mapListJson;
                    }else return null;
                }else throw new HttpException(" Return code exception :"+status);
        }

        /* Getting User Information Interface */
        public static String   Acquire user information () throws Exception{
                System.out.println(" Get user information to start .....");
                    CloseableHttpClient client=getHttpClient();
                HttpPost httpPost=new HttpPost(zbxdomain name+  Acquire user information URL);
                Md5 sign (httpPost, null,false);
                HttpResponse rsp=client.execute(httpPost);
                int status = rsp.getStatusLine().getStatusCode();
                if(status==200){
                    String  Response message  = EntityUtils.toString(rsp.getEntity());
                    JSONObject json  = (JSONObject)  General analytical response ( Response message );
                        System.out.println(" Merchant name ="+json.getString("merchantName"));
                        System.out.println(" email="+json.getString("email"));
                        System.out.println(" nickname ="+json.getString("nickName"));
                        System.out.println(" User real name ="+json.getString("realName"));
                    return json.toJSONString();
                }else throw new HttpException(" Return code exception :"+status);
        }
        public static String  New delegate (final String marketId,final Integer type,final double amount,final double price) throws Exception{
            if(  Market transaction vs cache .get(marketId)!=null){
                    System.out.println(" New delegate : "+(type==0?" Sell ":" Buy ")+" ["+  Market transaction vs cache .get(marketId).toString()+"] "
                            +amount+"个, Unit Price :["+price+"]");
            }else{
                System.out.println(" New delegate : "+(type==0?" Sell ":" Buy ")+" ["+marketId+"] "+amount+"个, Unit Price :["+price+"]");
            }
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name+ New delegate URL);
            Map parameters = new HashMap(){{
                put("amount", amount);
                put("type", type);
                put("rangeType", 0);
                put("marketId", marketId);
                put("price", price);
            }};
            StringEntity httpParams=new StringEntity(JSON.toJSONString(parameters));
            //Setting Request Body
            httpPost.setEntity(httpParams);
            //Setting Signature, Request Header
            Md5 sign (httpPost, parameters,true);
            HttpResponse httpResponse = client.execute(httpPost);
            int status=httpResponse.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                JSONObject json  = (JSONObject)  General analytical response ( Response message );
                String entrustId = (String) json.get("entrustId");
                System.out.println(" The commission is newly added, and the order number is :======>>["+entrustId+"]");
                return entrustId;
            }else throw new HttpException(" Return code exception :"+status);
        }

        public static String  Cancellation of delegation (final String marketId,final String entrustId) throws Exception{
                System.out.println(" Cancellation of delegation :["+entrustId+"]");
                CloseableHttpClient client=getHttpClient();
                HttpPost httpPost=new HttpPost(zbxdomain name+ Cancellation of delegation URL);
                Map parameters = new HashMap(){{
                    put("marketId", marketId);
                    put("entrustId", entrustId);
                }};
                StringEntity httpParams=new StringEntity(JSON.toJSONString(parameters));
                //Setting Request Body
                httpPost.setEntity(httpParams);
                //Setting Signature, Request Header
                Md5 sign (httpPost, parameters,true);
                HttpResponse rsp=client.execute(httpPost);
                int status = rsp.getStatusLine().getStatusCode();
                if(status==200){
                    String  Response message  = EntityUtils.toString(rsp.getEntity());
                    JSONObject json  = (JSONObject)  General analytical response ( Response message );
                    System.out.println(" Delegate successful cancellation ");
                    return entrustId;
                }else throw new HttpException(" Return code exception :"+status);
        }

        public static JSONArray  Enquiry on on-going entrustment (final String marketId) throws Exception{
            System.out.println(" check ["+marketId+"] All pending orders ");
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name+ Enquiry on on-going entrustment URL);
            Map parameters = new HashMap(){{
                put("marketId", marketId);
            }};
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //Note: For key-value request data format, both Entity and Param in HttpPost need to pass in corresponding attributes
                httpPost.setEntity(new StringEntity("marketId="+marketId));
            httpPost.getParams().setParameter("marketId", marketId);
            //Setting Signature, Request Header
            Md5 sign (httpPost, parameters,false);
                HttpResponse rsp=client.execute(httpPost);
            int status = rsp.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(rsp.getEntity());
                JSONArray json  = (JSONArray)  General analytical response ( Response message );
                if(json==null||json.size()==0){
                    System.out.println(" No ongoing commission ");
                    return null;
                }
                System.out.println(" Successful entrustment query ---->"+json);//Invite the caller to parse JSON to get the required data format reference footer
                    return json;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*Paging query history delegation record */
        public static String Paging query history delegation record (final String marketId,int pageIndex,int pageSize) throws Exception{
                    System.out.println("marketId="+marketId+",pageIndex="+pageIndex+",pageSiz="+pageSize);
                    CloseableHttpClient client=getHttpClient();
                    //Get request mode: parameters are spliced behind the URL
                HttpGet httpGet=new HttpGet(zbxdomain name+Paging query history delegation record URL+"?marketId="+marketId+"&pageIndex="+String.valueOf(pageIndex)+"&pageSize="+String.valueOf(pageSize));
                Map parameters = new HashMap(){{
                        put("marketId", marketId);
                        put("pageIndex",pageIndex);
                        put("pageSize",pageSize);
                    }};
                Md5 sign (httpGet, parameters,true);
                HttpResponse httpResponse = client.execute(httpGet);
                int status=httpResponse.getStatusLine().getStatusCode();
                if(status==200){
                    String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                    JSONObject json  = (JSONObject)  General analytical response ( Response message );
                    String entrustRecordsList=json.getJSONArray("entrustList").toJSONString();
                    System.out.println(" Historical commission record is :======>>["+entrustRecordsList+"]");
                    return json.toJSONString();
                }else throw new HttpException(" Return code exception :"+status);
        }

        /*Query the delegation record according to the delegation ID */
        public static String Query the delegation record according to the delegation ID (final String marketId,final String entrustId) throws Exception{
                    System.out.println("marketId="+marketId+",entrustID="+entrustId);
                    CloseableHttpClient client=getHttpClient();
                    //Get request mode: parameters are spliced behind the URL
                    HttpGet httpGet=new HttpGet(zbxdomain name + Query the delegation record according to the delegation ID +"?marketId="+marketId+"&entrustId="+entrustId);
                    Map parameters = new HashMap(){{
                            put("marketId", marketId);
                            put("entrustId",entrustId);
                    }};
                    Md5 sign (httpGet, parameters,false);
                    HttpResponse httpResponse = client.execute(httpGet);
                    int status=httpResponse.getStatusLine().getStatusCode();
                    if(status==200){
                        String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                        JSONObject json  = (JSONObject)  General analytical response ( Response message );
//				        String entrustRecordsList=json.getJSONArray("entrustList").toJSONString();
                        System.out.println(" The commission record is :======>>["+json+"]");
                        return json.toJSONString();
                    }else throw new HttpException(" Return code exception :"+status);
        }

    public static String Abolish consignment in batches (final String marketId) throws Exception {
            System.out.println("Abolish consignment in batches :["+marketId+"]");
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name + Abolish consignment in batches URL);
            Map parameters = new HashMap(){{
                put("marketId", marketId);
            }};
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //Note: For key-value request data format, both Entity and Param in HttpPost need to pass in corresponding attributes
                httpPost.setEntity(new StringEntity("marketId="+marketId));
            httpPost.getParams().setParameter("marketId", marketId);
            Md5 sign (httpPost, parameters,false);
            HttpResponse rsp=client.execute(httpPost);
            int status = rsp.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  =  EntityUtils.toString(rsp.getEntity());
                JSONObject respsone = JSONObject.parseObject( Response message );
                Object resMsg = respsone.get("resMsg");
                JSONArray json = null;
                if(resMsg!=null&&resMsg instanceof JSONObject){
                    if("1".equals(((JSONObject)resMsg).get("code"))){//Return Code Successful
                        json = (JSONArray) respsone.get("datas");
                        if(json==null||json.size()==0){
                            System.out.println(" No ongoing commission ");
                            return null;
                        }else {
                            System.out.println(" Delegate successful cancellation ");
                            //Return all cancelled delegates
                            return json.toJSONString();
                        }
                    }
                }
                System.err.println("respsone----------------"+respsone);
                return respsone.toJSONString();
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*-------------------------------- Financial funds API-------------------------------------*/
        public static String Get the currency address (final String currencyTypeName) throws Exception{
            System.out.println("币种="+currencyTypeName);
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name + Get the currency address URL);
            Map parameters = new HashMap(){{
                put("currencyTypeName", currencyTypeName);
            }};
            StringEntity httpParams=new StringEntity(JSON.toJSONString(parameters));
            //Setting Request Body
            httpPost.setEntity(httpParams);
            //Setting Signature, Request Header
            Md5 sign (httpPost, parameters,true);
                HttpResponse rsp=client.execute(httpPost);
            int status = rsp.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(rsp.getEntity());
                JSONObject json  = (JSONObject)  General analytical response ( Response message );
                String chargingAddress=json.get("address").toString();
                System.out.println(" Coin address ---->"+chargingAddress);//Invite the caller to parse JSON to get the required data format reference footer
                return chargingAddress;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*Search for Filling Records */
        public static String Search for Filling Records (final String currencyTypeName,int sort,int pageNum,int pageIndex) throws Exception{
            System.out.println("currencyTypeName="+currencyTypeName+",sort="+sort+",pageNum="+pageNum+",pageIndex="+pageIndex);
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name + Search for Filling Records URL);
            Map parameters = new HashMap(){{
                put("currencyTypeName", currencyTypeName);
                put("sort", sort);
                put("pageNum", pageNum);//
                put("pageIndex", pageIndex);//
            }};
            StringEntity httpParams=new StringEntity(JSON.toJSONString(parameters));
            //Setting Request Body
            httpPost.setEntity(httpParams);
            Md5 sign (httpPost, parameters,true);
                HttpResponse rsp=client.execute(httpPost);
            int status = rsp.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(rsp.getEntity());
                JSONObject json  = (JSONObject)  General analytical response ( Response message );
                String chargingCoinRecord=json.getJSONArray("list").toJSONString();
                System.out.println(" Currency record ---->"+chargingCoinRecord);//Invite the caller to parse JSON to get the required data format reference footer
                return chargingCoinRecord;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*Inquiry for withdrawal records */
        public static String Inquiry for withdrawal records (int currencyId,final String tab,int pageIndex,int pageNum) throws Exception{
                    System.out.println("currencyId="+currencyId+",tab="+tab+",pageIndex="+pageIndex+",pageNum="+pageNum);
                    CloseableHttpClient client=getHttpClient();
                    //Get request mode: parameters are spliced behind the URL
                HttpGet httpGet=new HttpGet(zbxdomain name + Inquiry for withdrawal records URL+"?currencyId="+currencyId+"&tab="+tab+"&pageIndex="+pageIndex+"&pageNum="+pageNum);
                    Map parameters = new HashMap(){{
                            put("currencyId", currencyId);
                            put("tab",tab);
                            put("pageIndex",pageIndex);
                            put("pageNum",pageNum);
                    }};
                    Md5 sign (httpGet, parameters,false);
                    HttpResponse httpResponse = client.execute(httpGet);
                    int status=httpResponse.getStatusLine().getStatusCode();
                    if(status==200){
                        String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                        JSONObject json  = (JSONObject)  General analytical response ( Response message );
                        String getCoinRecordsList=json.getJSONArray("list").toJSONString();
                        System.out.println(" Money record :======>>["+getCoinRecordsList+"]");
                        return getCoinRecordsList;
                    }else throw new HttpException(" Return code exception :"+status);
        }

        /*Obtain all funds information from users */
            public static String Obtain all funds information from users (final Integer pageSize,final Integer pageNum) throws Exception{
            CloseableHttpClient client=getHttpClient();
            HttpPost httpPost=new HttpPost(zbxdomain name + Obtain all funds information from users URL);
            Map parameters = new HashMap(){{
                put("pageSize", pageSize);
                put("pageNum", pageNum);
            }};
            StringEntity httpParams=new StringEntity(JSON.toJSONString(parameters));
            //Setting Request Body
            httpPost.setEntity(httpParams);
            //Setting Signature, Request Header
            Md5 sign (httpPost, parameters,true);
            HttpResponse httpResponse = client.execute(httpPost);
            int status=httpResponse.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                JSONObject json  = (JSONObject)  General analytical response ( Response message );
                String  List of funds information =json.get("list").toString();
                System.out.println(" List of funds information :======>>["+ List of funds information +"]");
                return  List of funds information ;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*Inquire the address of withdrawal money */
        public static String Inquire the address of withdrawal money (int currencyId,int pageIndex,int pageNum) throws Exception{
            System.out.println("currencyId="+currencyId+",pageIndex="+pageIndex+",pageNum="+pageNum);
            CloseableHttpClient client=getHttpClient();
            //Get request mode: parameters are spliced behind the URL
        HttpGet httpGet=new HttpGet(zbxdomain name + Inquire the address of withdrawal money URL+"?currencyId="+currencyId+"&pageIndex="+pageIndex+"&pageNum="+pageNum);
            Map parameters = new HashMap(){{
                    put("currencyId", currencyId);
                    put("pageIndex",pageIndex);
                    put("pageNum",pageNum);
            }};
            Md5 sign (httpGet, parameters,false);
            HttpResponse httpResponse = client.execute(httpGet);
            int status=httpResponse.getStatusLine().getStatusCode();
            if(status==200){
                String  Response message  = EntityUtils.toString(httpResponse.getEntity());
                JSONObject json  = (JSONObject)  General analytical response ( Response message );
                String getCoinRecordsList=json.getJSONArray("list").toJSONString();
                System.out.println(" Money withdrawal address :======>>["+getCoinRecordsList+"]");
                return getCoinRecordsList;
            }else throw new HttpException(" Return code exception :"+status);
        }

        /*-------------------------------------------- Basic function method -----------------------------------------*/
        /*  Parsing the response packet to obtain the data parameter  */
        private static JSON  General analytical response (String responseStr){
            JSONObject respsone = JSONObject.parseObject(responseStr);
            Object resMsg = respsone.get("resMsg");
            if(resMsg!=null&&resMsg instanceof JSONObject){
                if("1".equals(((JSONObject)resMsg).get("code"))){//Return Code Successful
                    return (JSON) respsone.get("datas");
                }
            }
            System.err.println("responseStr------------------------------------->"+responseStr);
            throw new RuntimeException(" API call failed : Packet parsing failed !");
        }


        /**
        * @param parameters  			 param MAP
        * @param isJson				 Is it a JSON string true when the request format is JSON, false when key1:value1
        */
        protected static void Md5 sign (HttpPost post,Map parameters,boolean isJson){

            StringBuffer sb = new StringBuffer(APIAccess key );
            String timestamp = String.valueOf(System.currentTimeMillis());
            sb.append(timestamp);
            if(parameters!=null&&!parameters.isEmpty()){
                if(isJson){
                    String params = JSON.toJSONString(parameters);
                    sb.append(params);
                }else{
                    parameters = new TreeMap<>(parameters);
                    Iterator it = parameters.entrySet().iterator();
                    while(it.hasNext()){
                        Entry entry = (Entry)it.next();
                        sb.append(entry.getKey()).append(entry.getValue());
                    }
                }
            }
            sb.append(API Private key );
            String sign = digest(sb.toString());
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
            post.addHeader("Apiid", API Access key );
            post.addHeader("Timestamp", timestamp);
            post.addHeader("Sign", sign);
        }

        protected static void Md5 sign (HttpGet get,Map parameters,boolean isJson){

            StringBuffer sb = new StringBuffer(API Access key );
            String timestamp = String.valueOf(System.currentTimeMillis());
            sb.append(timestamp);
            if(parameters!=null&&!parameters.isEmpty()){
                if(isJson){
                    String params = JSON.toJSONString(parameters);
                    sb.append(params);
                }else{
                    parameters = new TreeMap<>(parameters);
                    Iterator it = parameters.entrySet().iterator();
                    while(it.hasNext()){
                        Entry entry = (Entry)it.next();
                        sb.append(entry.getKey()).append(entry.getValue());
                    }
                }
            }
            sb.append(API Private key );
            String sign = digest(sb.toString());
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
            get.addHeader("Apiid", API Access key );
            get.addHeader("Timestamp", timestamp);
            get.addHeader("Sign", sign);
        }


        public static String digest(String str) {
                try {
                        //Implementation of digest of MD5 encryption algorithm
                    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                    messageDigest.reset();
                    messageDigest.update(str.getBytes());
                    byte[] byteArray = messageDigest.digest();
                    StringBuffer md5StrBuff = new StringBuffer();
                    for(int i = 0; i < byteArray.length; ++i) {
                        if (Integer.toHexString(255 & byteArray[i]).length() == 1) {
                            md5StrBuff.append("0").append(Integer.toHexString(255 & byteArray[i]));
                        } else {
                            md5StrBuff.append(Integer.toHexString(255 & byteArray[i]));
                        }
                    }
                    return md5StrBuff.toString();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                    return null;
                }
            }
}



                        
                    

8 Error code

When failing, the return message is as follows

{
    "datas": null,
    "resMsg": {
        "code": "1000",
        "method": null,
        "message": "param invalid"
    }
}

Error code list:

Error code Explain English explanation
999 签名错误 sign is invalid!
1000 系统错误 system error
1001 下单频率超过限制 request limit
1003 无效的参数 param invalid
2000 参数错误 parameter error
2001 委托价格类型为空 entrust price range type null
2002 委托类型错误 rangeType [ 0,1] error
2003 委托价格异常 entrust price abnormal
2004 市场ID不能为空 market id null
2008 买卖类型不能为空 type[ buy :type=1 or sell: type=0] null
2009 买卖类型错误 type[ buy :type=1 or sell: type=0] error
2012 委托信息不存在或状态异常 entrust not exists or status abnormal
2014 缓存中无该该委托单 entrust not exists in cache
2015 委托单已取消或数据库中不存在 entrust already canceled or not exists in database
2016 分页index,pageSize参数有误 paging:index or pageSize invalid
2017 交易货币量为空 entrust amount null
2018 交易货币量异常 entrust amount abnormal
2019 委托单ID不能为空 entrustId null
2020 委托类型不能为空 entrustType null
2021 委托类型错误 entrustType [ 0,1] error
2022 交易货币量小于最小值 entrust amount low min limit
2023 委托正在处理 entrust still on dealing, cancel it later
2024 价格过大或过小 entrust price too big or too small
2026 用户委托单数超过最大值 user entrust amount exceed maxnum
2027 市场暂停 this market is suspended
2999 内部错误 system error
6000 参数缺失 Param Missing
6002 授权失效,需要重新登录 Authorization invalid, please sign in again.
6021 限制提币操作 Limit the withdraw operation
6040 该账户已冻结,暂时不能操作 The account has been frozen and can not be operated for the time being
6074 该用户未实名认证 The user is not identified
6075 该用户未银行认证 This user has not bank identified
6076 安全密码错误,请重新输入 Security password error, please enter again!
6095 用户不存在 User does not exist
6096 无效的参数 Invalid parameter
6098 用户已经被列入交易黑名单不能进行交易 The user has been listed on the transaction blacklist and cannot transaction
6114 提币地址为空 Please select a currency address!
6115 提交提币申请失败 Submit a withdrawal application failure!
6124 审核失败 Audit failure!
6125 无效的货币类型 An invalid currency type!
6126 审核通过 Audit Approve!
6130 没有选取币种 No selection of currency, Please try again!
6400 当前市场未到开盘时间 This market is not open!
6894 时间过长,API签名已失效 The time is too long,sign for api is invalid now!
6895 校验API权限失败,接口不属于授权API Failed to verify the API permission. This interface is not a authorize API!
6896 校验API权限失败,Userid和Apiid不匹配 Failed to verify the API permission. The Userid is not matching with Apiid!
6897 校验API权限失败,请确认是否开启Api权限 Failed to verify the API permission. Please confirm whether to enable API permission!
6898 多次校验API权限失败,请确认是否开启Api权限 Failed to verify the API permission for multiple times. Please confirm whether to enable API permission!
6899 该市场现暂不对外开放api交易 The market is temporarily not open to API trading!
6900 交易所现暂不对外开放api交易 The exchange server temporarily not open to API trading!
10012 未知异常 unknown error

行情、盘口数据(市场深度)、k线、交易记录四类API的错误码说明

错误码 说明 英文说明
1000 系统错误 system error
5010 参数错误 param is invalid
5016 数据不存在 data not exist
5017 该市场不存在 market not exist
5019 你的IP一分钟内访问次数过多 your ip has too many visits per minute

9.API访问限制

Create new order via web - max 3 times per second

Cancel order via web - max 3 times per second

Create new order via API - max 3 times per second

Cancel order via API - max 3 times per second

API signature is valid for 5 minutes

For marketing data, order book data, K line data and transaction data, each IP can access maximum 1000 time per minute

24H market data is refreshed every 10 second