English
javascript python csharp

币本位合约

SDK与代码示例

console.log('币本位合约 javascript 代码示例');

# -*- coding:utf-8 -*-


if __name__ == '__main__':
    print_hi('币本位合约 python 代码示例')

Console.WriteLine("币本位合约 c# 代码示例");

Bibox为开发人员提供了多种语言版本的合约SDK。 这些SDK基于Bibox合约API开发,并自动完成以下功能:

因此,使用SDK开发访问Bibox的程序比使用API更便捷,开发周期更短。

如果需要下载或者阅读更多信息,请点击以下链接:

1.签名接口请求方式

完整例子

let CryptoJS = require("crypto-js");
let request = require("request");

let timestamp = Date.now(); // 1.当前时间戳

let param = { // 2.请求的参数
    "amount":"0.01",
    "symbol":"BTC",
    "type":0
};

let strParam = JSON.stringify(param); // 2.格式化参数

let strToSign = '' + timestamp + strParam; // 3.这就是需要签名的字符串

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //你的 apikey 密码
let sign = CryptoJS.HmacMD5(strToSign, secret).toString();//4.签名后的结果

let url = "https://api.bibox.com/v3/assets/transfer/cbc";

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//5.设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: strParam // 6.格式化参数
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }
        console.log(body) // 7.返回值

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def transfer(inout, amount):
    path = '/v3/assets/transfer/cbc'
    body = {
        'symbol': 'BTC',
        'type': inout,
        'amount': amount,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    transfer(0, 1)  # transfer in contract
    transfer(1, 1)  # transfer out contract

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/assets/transfer/cbc";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                symbol = "BTC",
                type = 0,
                amount = "0.001",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

字段名 类型 描述 取值
content-type string 'application/json'
bibox-api-key string 你的apikey
bibox-timestamp long 当前时间戳,用毫秒表示 timestamp
bibox-api-sign string 签名结果 sign

2.资金划转

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let timestamp = Date.now(); // 1.当前时间戳

let param = { // 2.请求的参数
    "amount":"0.01",
    "symbol":"BTC",
    "type":0
};

let strParam = JSON.stringify(param); // 2.格式化参数

let strToSign = '' + timestamp + strParam; // 3.这就是需要签名的字符串

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //你的 apikey 密码
let sign = CryptoJS.HmacMD5(strToSign, secret).toString();//4.签名后的结果

let url = "https://api.bibox.com/v3/assets/transfer/cbc";

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//5.设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: strParam // 6.格式化参数
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }
        console.log(body) // 7.返回值

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def transfer(inout, amount):
    path = '/v3/assets/transfer/cbc'
    body = {
        'symbol': 'BTC',
        'type': inout,
        'amount': amount,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    transfer(0, 1)  # transfer in contract
    transfer(1, 1)  # transfer out contract

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/assets/transfer/cbc";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                symbol = "BTC",
                type = 0,
                amount = "0.001",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/assets/transfer/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
amount true string 数量转字符串
symbol true string 币种 BTC,ETH, ...
type true integer 0转入,1转出 0,1

Response

{
    "state":0, // 成功
    "result":"352559634189422592"  // 忽略
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

3.下单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/open";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "pair":"5BTC_USD",
    "order_side":1,
    "order_type":2,
    "price":"11500",
    "amount":1,
    "order_from":6,
    "client_oid": "1234567890",
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/open'
    body = {
        "pair": "5BTC_USD",
        "order_side": 1,
        "order_type": 2,
        "price": "11500",
        "amount": 1,
        "order_from": 6,
        "client_oid": "1234567890",
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/open";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
                order_side = 1,
                order_type = 2,
                price = "11500",
                amount = 1,
                order_from = 6,
                client_oid = "1234567890",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/open

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 5BTC_USD,5ETH_USD, ...
amount true string 数量转字符串
order_side true integer 下单类型,1开多,2开空,3平多,4平空 1,2,3,4
order_type true integer 下单方式,1市价单,2限价单 1,2
price true string 下单价格
order_from true integer 下单来源 6
client_oid false string 自定义id

Response

{
    "state":0,
    "order_id":"425510999949316", // 订单id
    "client_oid":"1234567890", // 自定义id
    "status":1, // 订单状态 1等待成交,2部分成交,3全部成交,4部分撤销,5全部撤销,100下单失败
    "cmd":"open" // 忽略
}

名称 描述
state 0代表成功,否则代表失败
order_id 订单id
client_oid 自定义id
status 订单状态 1等待成交,2部分成交,3全部成交,4部分撤销,5全部撤销,100下单失败
其它字段 忽略

4.撤单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/close";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "order_id":"425510999949316"
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/close'
    body = {
        "order_id": "425510999949316"
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/close";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                order_id = "425510999949316",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/close

参数名称 是否必须 类型 描述 默认值 取值范围
order_id true string 订单id

Response

{
    "state":0, // 成功
    "result":"success", 
    "cmd":"close"
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

5.批量撤单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/closeBatch";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "order_ids":["2234567890","2234567891"]
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/closeBatch'
    body = {
        "order_ids": ["2234567890", "2234567891"]
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/closeBatch";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                order_ids = new [] {"2234567890", "2234567891"},
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/closeBatch

参数名称 是否必须 类型 描述 默认值 取值范围
order_ids true 数组 订单id数组

Response

{
    "state":0,// 成功
    "result":"success",
    "cmd":"close"
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

6.全部撤单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/closeAll";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "pair":"5BTC_USD"
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/closeAll'
    body = {
        "pair": "5BTC_USD"
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/closeAll";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/closeAll

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 5BTC_USD,5ETH_USD, ...

Response

{
    "state":0,// 成功
    "result":"success",
    "cmd":"closeAll"
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

7.逐仓调整保证金

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/changeMargin";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "pair":"5BTC_USD",
    "margin":"0.01",
    "side":1
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/changeMargin'
    body = {
        "pair": "5BTC_USD",
        "margin": "0.01",
        "side": 1
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/changeMargin";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
                margin = "0.01",
                side = 1
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/changeMargin

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 5BTC_USD,5ETH_USD, ...
margin true string 保证金数量
side true integer 仓位方向,1多仓, 2空仓 1,2

Response

{
    "state":3103, // 失败
    "msg":"没有持仓不支持该操作",
    "cmd":"changeMargin"
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

8.调整持仓模式及杠杆

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/changeMode";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "pair":"5BTC_USD",
    "mode":2,
    "leverage_long":10,
    "leverage_short":20
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/changeMode'
    body = {
        "pair": "5BTC_USD",
        "mode": 2,
        "leverage_long": 10,
        "leverage_short": 20
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/changeMode";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
                mode = 2,
                leverage_long = 10,
                leverage_short = 20,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/changeMode

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 5BTC_USD,5ETH_USD, ...
mode true integer 仓位模式,1全仓, 2逐仓 1,2
leverage_long true integer 多仓杠杆倍数 1~100
leverage_short true integer 空仓杠杆倍数 1~100

Response

{
    "state":0,
    "result":"success",
    "cmd":"changeMode"
}

名称 描述
state 0代表成功,否则代表失败
其它字段 忽略

9.查询资产

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/assets";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    // "coin":"BTC",
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/assets'
    body = {
        "coin": "BTC",
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/assets";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                coin = "BTC",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/assets

参数名称 是否必须 类型 描述 默认值 取值范围
coin false string 币种符号 BTC,ETH,...

Response

{
    "state":0,
    "result":[
        {
            "b":"1", // 可用余额
            "c":"BTC", // 币种
            "u":100006, // 用户id
            "f":"0", // 冻结资金
            "m":"0" // 保证金资金
        },
        {
            "b":"1",
            "c":"ETH",
            "u":100006,
            "f":"0",
            "m":"0"
        }
    ],
    "cmd":"assets"
}

名称 描述
state 0代表成功,否则代表失败
b 可用余额
c 币种
u 用户id
f 冻结资金
m 保证金资金
其它字段 忽略

10.查询仓位

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/position";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    // "pair":"5BTC_USD",
    // "side":1
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/position'
    body = {
        "pair": "5BTC_USD",
        "side": 1
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/position";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
                side = 1,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/position

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 5BTC_USD,5ETH_USD, ...
side false integer 仓位方向,1多仓, 2空仓 1,2

Response

{
    "state":0,
    "result":[
        {
            "pt":"0",//忽略
            "f":"0",//忽略
            "l":"10", // 杠杆
            "sd":1, // 仓位方向: 1, 多仓 2 , 空仓
            "pa":"0", //告警价格
            "ui":100006,//用户id
            "fb0":"0",//忽略
            "pf":"0",//爆仓价格
            "md":2,//仓位模式: 1, 全仓 2 , 逐仓
            "lc":"0",// 可平仓位价值
            "pi":"5BTC_USD", // 交易对
            "mg":"0", //保证金
            "hc":"0",// 仓位价值 = 合约张数X合约面值
            "fb":"0",//忽略
            "po":"0" //开仓价格
        },
        ...
    ],
    "cmd":"position"
}

名称 描述
state 0代表成功,否则代表失败
l 杠杆
sd 仓位方向: 1, 多仓 2 , 空仓
pa 告警价格
ui 用户id
pf 爆仓价格
md 仓位模式: 1全仓, 2逐仓
lc 可平仓位价值
pi 交易对
mg 保证金
hc 仓位价值 = 合约张数X合约面值
po 开仓价格
其它字段 忽略

11.查询订单列表

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/list";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    // "pair":"5BTC_USD",
    // "order_side":1
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/list'
    body = {
        "pair": "5BTC_USD",
        "order_side": 1
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/list";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "5BTC_USD",
                order_side = 1,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/list

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 5BTC_USD,5ETH_USD, ...
order_side true integer 下单类型,1开多,2开空,3平多,4平空 1,2,3,4

Response

{
    "state":0,
    "result":{
        "p":1,
        "t":1,
        "o":[
            {
                "f":"0", //手续费
                "dp":"0", //成交价格
                "eq":"0", //成交数量
                "p":"11092", //下单价格
                "tif":0, // 忽略
                "q":"1", //下单数量
                "sd":1, //下单方向
                "r":0, //reason
                "s":1, // status
                "t":1602679944815, //下单时间
                "ui":100006, //用户id
                "fz":"0.0000091417", //挂单冻结
                "fb0":"0", //优惠券抵扣
                "of":4, //order from
                "pi":"5BTC_USD", //交易对
                "oi":"426610511577093", // order id
                "coi":"1602679943911", //clientoid
                "fb":"0", //bix抵扣
                "po":false //忽略
            },
            ...
        ]
    },
    "cmd":"orderList"
}

名称 描述
state 0代表成功,否则代表失败
f 手续费
dp 成交价格
eq 成交数量
p 下单价格
q 下单数量
sd 下单方向
r 失败原因
s 订单状态
t 下单时间
ui 用户id
fz 挂单冻结
fb0 优惠券抵扣
of 订单来源
pi 交易对
oi 订单id
coi 用户自定义订单id
fb bix抵扣
其它字段 忽略

12.查询订单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/detail";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "order_id":"426610511577093",
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/detail'
    body = {
        "order_id": "426610511577093",
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/detail";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                order_id = "426610511577093",
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/detail

参数名称 是否必须 类型 描述 默认值 取值范围
order_id true string 订单id

Response

{
    "state":0,
    "result":{
        "f":"0", //手续费
        "dp":"0", //成交价格
        "eq":"0", //成交数量
        "p":"11092", //下单价格
        "tif":0, // 忽略
        "q":"1", //下单数量
        "sd":1, //下单方向
        "r":0, //reason
        "s":1, // status
        "t":1602679944815, //下单时间
        "ui":100006, //用户id
        "fz":"0.0000091417", //挂单冻结
        "fb0":"0", //优惠券抵扣
        "of":4, //order from
        "pi":"5BTC_USD", //交易对
        "oi":"426610511577093", // order id
        "coi":"1602679943911", //clientoid
        "fb":"0", //bix抵扣
        "po":false //忽略
    },
    "cmd":"orderDetail"
}

名称 描述
state 0代表成功,否则代表失败
f 手续费
dp 成交价格
eq 成交数量
p 下单价格
q 下单数量
sd 下单方向
r 失败原因
s 订单状态
t 下单时间
ui 用户id
fz 挂单冻结
fb0 优惠券抵扣
of 订单来源
pi 交易对
oi 订单id
coi 用户自定义订单id
fb bix抵扣
其它字段 忽略

13.批量查询订单列表

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/listBatch";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "order_ids":["426610511577093"],
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/listBatch'
    body = {
        "order_ids": ["426610511577093"],
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/listBatch";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                order_ids = new [] {"426610511577093"},
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/listBatch

参数名称 是否必须 类型 描述 默认值 取值范围
order_ids true 数组 订单id数组

Response

{
    "state":0,
    "result":[
        {
             "f":"0", //手续费
            "dp":"0", //成交价格
            "eq":"0", //成交数量
            "p":"11092", //下单价格
            "tif":0, // 忽略
            "q":"1", //下单数量
            "sd":1, //下单方向
            "r":0, //reason
            "s":1, // status
            "t":1602679944815, //下单时间
            "ui":100006, //用户id
            "fz":"0.0000091417", //挂单冻结
            "fb0":"0", //优惠券抵扣
            "of":4, //order from
            "pi":"5BTC_USD", //交易对
            "oi":"426610511577093", // order id
            "coi":"1602679943911", //clientoid
            "fb":"0", //bix抵扣
            "po":false //忽略
        }
    ],
    "cmd":"orderListBatch"
}

名称 描述
state 0代表成功,否则代表失败
f 手续费
dp 成交价格
eq 成交数量
p 下单价格
q 下单数量
sd 下单方向
r 失败原因
s 订单状态
t 下单时间
ui 用户id
fz 挂单冻结
fb0 优惠券抵扣
of 订单来源
pi 交易对
oi 订单id
coi 用户自定义订单id
fb bix抵扣
其它字段 忽略

14.根据clientoid批量查询订单列表

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3/cbc/order/listBatchByClientOid";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "order_ids":["1602679943911"],
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3/cbc/order/listBatchByClientOid'
    body = {
        "order_ids": ["1602679943911"],
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
       {
           HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
           byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
           StringBuilder sb = new StringBuilder();

           for (int i = 0; i < inArray.Length; i++)
           {
               sb.Append(inArray[i].ToString("X2"));
           }

           hmacmd.Clear();

           return sb.ToString().ToLower();
       }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3/cbc/order/listBatchByClientOid";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                order_ids = new [] {"1602679943911"},
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3/cbc/order/listBatchByClientOid

参数名称 是否必须 类型 描述 默认值 取值范围
order_ids true 数组 自定义订单id数组

Response

{
    "state":0,
    "result":[
        {
             "f":"0", //手续费
            "dp":"0", //成交价格
            "eq":"0", //成交数量
            "p":"11092", //下单价格
            "tif":0, // 忽略
            "q":"1", //下单数量
            "sd":1, //下单方向
            "r":0, //reason
            "s":1, // status
            "t":1602679944815, //下单时间
            "ui":100006, //用户id
            "fz":"0.0000091417", //挂单冻结
            "fb0":"0", //优惠券抵扣
            "of":4, //order from
            "pi":"5BTC_USD", //交易对
            "oi":"426610511577093", // order id
            "coi":"1602679943911", //clientoid
            "fb":"0", //bix抵扣
            "po":false //忽略
        }
    ],
    "cmd":"orderListBatchByCLientOid"
}

名称 描述
state 0代表成功,否则代表失败
f 手续费
dp 成交价格
eq 成交数量
p 下单价格
q 下单数量
sd 下单方向
r 失败原因
s 订单状态
t 下单时间
ui 用户id
fz 挂单冻结
fb0 优惠券抵扣
of 订单来源
pi 交易对
oi 订单id
coi 用户自定义订单id
fb bix抵扣
其它字段 忽略

15.获取服务器时间

GET https://api.bibox.com/v3/cbc/timestamp

Response

{
    "time":"1602680518605"
}

名称 描述
time 服务器时间

16.查询持仓变化记录

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/dealLog";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "pair": "5BTC_USD",
    "page": 1,
    "size": 10,
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/dealLog'
    body = {
        "pair": "5BTC_USD",
        "page": 1,
        "size": 10,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/dealLog";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 pair = "5BTC_USD",
                 page = 1,
                 size = 10,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/dealLog

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 5BTC_USD,5ETH_USD, ...
page true integer 第几页 1,2, ...
size true integer 条数 10,20, ...

Response

{
    "result":{
        "count":3,
        "page":1,
        "items":[
            {
                "id":"1125899906842635654", // 仓位变化id
                "user_id":100006, // 用户id
                "coin_symbol":"BTC",// 币种
                "pair":"5BTC_USD",// 交易对
                "side":1,// 仓位方向 1多仓,2空仓
                "model":1,// 仓位模式,1全仓,2逐仓
                "log_type":1,// 变化类型 1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
                "hold_coin_dx":"1.0000000000",// 仓位持仓变化量
                "hold_coin":"1.0000000000",// 仓位持仓
                "price_log":"11692.0000000000",// 参考价格
                "price_open":"11692.0000000000",// 开仓均价
                "profit":"0.0000000000",// 收益
                "fee":"0.0000000599",// 手续费
                "fee_bix":"0.0000000000",// bix抵扣
                "fee_bix0":"0.0000000000", // 优惠券抵扣
                "createdAt":"2020-10-14T03:00:08.000Z",// 变化时间
                "updatedAt":"2020-10-14T03:00:08.000Z"
            },
            ...
        ]
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
id 仓位变化id
user_id 用户id
coin_symbol 币种
pair 交易对
side 仓位方向 1多仓,2空仓
model 仓位模式,1全仓,2逐仓
log_type 变化类型 1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
hold_coin_dx 仓位持仓变化量
hold_coin 仓位持仓
price_log 参考价格
price_open 开仓均价
profit 收益
fee 手续费
fee_bix bix抵扣
fee_bix0 优惠券抵扣
createdAt 变化时间
其它字段 忽略

17.查询订单成交明细

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderDetail";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "orderId":"421112953438213",
    "page":1,
    "size":10
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/orderDetail'
    body = {
        "orderId": "421112953438213",
        "page": 1,
        "size": 10
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderDetail";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 orderId = "421112953438213",
                 page = 1,
                 size = 10,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/orderDetail

参数名称 是否必须 类型 描述 默认值 取值范围
orderId true long 订单id
page true integer 第几页 1,2, ...
size true integer 条数 10,20, ...

Response

{
    "result":{
        "count":1,
        "page":1,
        "items":[
            {
                "id":"1125899906842635651",// 明细id
                "coin_symbol":"BTC",// 币种
                "pair":"5BTC_USD",// 交易对
                "side":2,// 挂单方向 1开多,2开空,3平多,4平空
                "order_from":4,// 订单来源
                "price":"10692.0000000000",// 挂单价格
                "deal_price":"11510.0000000000",// 成交价格
                "deal_coin":"1.0000000000",// 成交价值
                "fee":"0.0000000608",// 手续费
                "fee_bix":"0.0000000000",// bix抵扣
                "fee_bix0":"0.0000000000",// 优惠券抵扣
                "is_maker":0,// 是否是maker
                "createdAt":"2020-10-14T02:58:59.000Z"// 成交时间
            }
        ]
    }
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
id 明细id
coin_symbol 币种
pair 交易对
side 挂单方向 1开多,2开空,3平多,4平空
order_from 订单来源
price 挂单价格
deal_price 成交价格
deal_coin 成交价值
fee 手续费
fee_bix bix抵扣
fee_bix0 优惠券抵扣
createdAt 变化时间
is_maker 是否是maker
其它字段 忽略

18.查询历史委托

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderHistory";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "page": 1,
    "size": 10,
    "pair": "5BTC_USD",
    "side": 1,
    "status": [3, 4, 5, 100],
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/orderHistory'
    body = {
        "page": 1,
        "size": 10,
        "pair": "5BTC_USD",
        "side": 1,
        "status": [3, 4, 5, 100],
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderHistory";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 page = 1,
                 size = 10,
                 pair = "5BTC_USD",
                 side = 1,
                 status = new [] {3, 4, 5, 100},
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/orderHistory

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 5BTC_USD,5ETH_USD, ...
page true integer 第几页 1,2, ...
size true integer 条数 10,20, ...
side false integer 1开多 2开空 3平多 4平空
status false 数组 状态,3:全部成交,4:部分撤单, 5:全部撤单, 100:下单失败

Response

{
    "result":{
        "count":1,
        "page":1,
        "items":[
            {
                "id":421112953438215,// 订单id
                "user_id":100006,// 用户id
                "coin_symbol":"BTC",// 币种
                "pair":"5BTC_USD",// 交易对
                "side":1,// 挂单方向
                "order_type":2,// 挂单类型 1市价,2限价
                "price":"11692.0000000000",// 挂单价格
                "amount_coin":"1.0000000000",// 挂单数量
                "freeze":"0.0000000000",// 冻结资金
                "price_deal":"11692.0000000000",// 成交均价
                "deal_coin":"1.0000000000",// 成交价值
                "deal_num":1,// 成交笔数
                "fee":"0.0000000599",// 手续费
                "fee_bix":"0.0000000000",// bix抵扣
                "fee_bix0":"0.0000000000",// 优惠券抵扣
                "status":3,// 订单状态,1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
                "reason":0,// 失败原因
                "fee_rate_maker":"0.0007000000",// maker手续费费率
                "fee_rate_taker":"0.0007000000",// taker手续费费率
                "client_oid":1602644402806,// 自定义id
                "order_from":4, // 忽略
                "createdAt":"2020-10-14T03:00:08.000Z",// 挂单时间
                "updatedAt":"2020-10-14T03:00:08.000Z"// 最新变化时间
            }
        ]
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
id 订单id
user_id 用户id
coin_symbol 币种
pair 交易对
side 挂单方向 1开多,2开空,3平多,4平空
order_type 挂单类型 1市价,2限价
price 挂单价格
amount_coin 挂单数量
freeze 冻结资金
price_deal 成交均价
deal_coin 成交价值
deal_num 成交笔数
fee 手续费
fee_bix bix抵扣
fee_bix0 优惠券抵扣
status 订单状态,1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
reason 失败原因
fee_rate_maker maker手续费费率
fee_rate_taker taker手续费费率
client_oid 自定义id
order_from 订单来源
createdAt 挂单时间
其它字段 忽略

19.查询订单

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderById";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    "orderIds": ["421112953438213", "421112953438214"],
    "clientOids": ["1602644402806", "1602644402811"],
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/orderById'
    body = {
        "orderIds": ["421112953438213", "421112953438214"],
        "clientOids": ["1602644402806", "1602644402811"],
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderById";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 orderIds = new [] {"421112953438213", "421112953438214"},
                 clientOids = new [] {"1602644402806", "1602644402811"},
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/orderById

参数名称 是否必须 类型 描述 默认值 取值范围
orderIds true 数组 订单id数组
clientOids true 数组 订单自定义di数组

Response

{
    "result":[
        {
            "id":421112953438214,// 订单id
            "user_id":100006,// 用户id
            "coin_symbol":"BTC",// 币种
            "pair":"5BTC_USD",// 交易对
            "side":1,// 挂单方向
            "order_type":2,// 挂单类型 1市价,2限价
            "price":"11692.0000000000",// 挂单价格
            "amount_coin":"1.0000000000",// 挂单数量
            "freeze":"0.0000000000",// 冻结资金
            "price_deal":"11692.0000000000",// 成交均价
            "deal_coin":"1.0000000000",// 成交价值
            "deal_num":1,// 成交笔数
            "fee":"0.0000000599",// 手续费
            "fee_bix":"0.0000000000",// bix抵扣
            "fee_bix0":"0.0000000000",// 优惠券抵扣
            "status":3,// 订单状态,1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
            "reason":0,// 失败原因
            "fee_rate_maker":"0.0007000000",// maker手续费费率
            "fee_rate_taker":"0.0007000000",// taker手续费费率
            "client_oid":1602644402806,// 自定义id
            "order_from":4, // 忽略
            "createdAt":"2020-10-14T03:00:08.000Z",// 挂单时间
            "updatedAt":"2020-10-14T03:00:08.000Z"// 最新变化时间
        },
        ...
    ],
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
id 订单id
user_id 用户id
coin_symbol 币种
pair 交易对
side 挂单方向 1开多,2开空,3平多,4平空
order_type 挂单类型 1市价,2限价
price 挂单价格
amount_coin 挂单数量
freeze 冻结资金
price_deal 成交均价
deal_coin 成交价值
deal_num 成交笔数
fee 手续费
fee_bix bix抵扣
fee_bix0 优惠券抵扣
status 订单状态,1未成交,2部分成交,3完全成交,4部分撤销,5全部撤销,100下单失败
reason 失败原因
fee_rate_maker maker手续费费率
fee_rate_taker taker手续费费率
client_oid 自定义id
order_from 订单来源
createdAt 挂单时间
其它字段 忽略

19.1.查询划转记录

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/transferLog";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {
    coin_symbol: 'BTC', 
    from: Date.now() - 1000 * 60 * 60 * 24,
    to: Date.now() - 1000 * 60 * 60 * 24, 
    page: 1, 
    size: 10,
};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/transferLog'
    timestamp = int(time.time()) * 1000
    body = {
        'coin_symbol': 'BTC',
        'from': timestamp - 1000 * 60 * 60 * 24,
        'to': timestamp,
        'page': 1,
        'size': 10,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/transferLog";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 coin_symbol = "BTC",
                 from = timestamp - 1000 * 60 * 60 * 24,
                 to = timestamp,
                 page = 1,
                 size = 10,
             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/transferLog

参数名称 是否必须 类型 描述 默认值 取值范围
coin_symbol false string 币种符号 BTC,ETH, ...
page true integer 第几页 1,2, ...
size true integer 条数 10,20, ...
from false integer 起始时间
to false integer 结束时间

Response

{
    "result":{
        "count":5,
        "page":1,
        "items":[
            {
                "id":"1125899906862835742",
                "user_id":100006,
                "coin_symbol":"BTC",
                "pair":"",
                "change_amount":"0.0010000000",
                "change_result":"2.0230606258",
                "bill_type":1,
                "comment":"划转",
                "createdAt":"2020-11-26T03:59:09.000Z",
                "updatedAt":"2020-11-26T03:59:09.000Z"
            },
            ...
        ]
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
id 账单id
user_id 用户id
coin_symbol 币种
pair 交易对
change_amount 划转数量
createdAt 时间
其它字段 忽略

19.2.查询资产估值

Request

let CryptoJS = require("crypto-js");
let request = require("request");

let url = "https://api.bibox.com/v3.1/cquery/base_coin/bassets";

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret

let param = {

};

let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds

request.post({
        url: url,//请求路径
        method: "POST",//请求方式
        headers: {//设置请求头
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//post参数字符串
    },

    function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }

        console.log(body)

    });

# -*- coding:utf-8 -*-
import hashlib
import hmac
import json
import time
import requests
import sys, getopt

API_KEY = '900625568558820892a8c833c33ebc8fd2701efe'
SECRET_KEY = 'c708ac3e70d115ec29efbee197330627d7edf842'
BASE_URL = 'https://api.bibox.com'  # 'https://api.bibox.tel' #


def do_sign(body):
    timestamp = int(time.time()) * 1000
    # to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
    to_sign = str(timestamp) + json.dumps(body)
    sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
    print(to_sign)

    headers = {
        'bibox-api-key': API_KEY,
        'bibox-api-sign': sign,
        'bibox-timestamp': str(timestamp)
    }
    return headers


def do_request():
    path = '/v3.1/cquery/base_coin/bassets'
    body = {

    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    do_request()

using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ConsoleProgram
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

    public class Class1
    {

        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        static string HmacMD5(string source, string key)
               {
                   HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
                   byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
                   StringBuilder sb = new StringBuilder();

                   for (int i = 0; i < inArray.Length; i++)
                   {
                       sb.Append(inArray[i].ToString("X2"));
                   }

                   hmacmd.Clear();

                   return sb.ToString().ToLower();
               }

        static async Task Main()
        {
          // Call asynchronous network methods in a try/catch block to handle exceptions.
          try
          {
             string uri = "https://api.bibox.com/v3.1/cquery/base_coin/bassets";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {

             };

             string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

             string source = timestamp + payload;
             string sign = HmacMD5(source, secret);

             Console.WriteLine(source);
             Console.WriteLine(sign);

             client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
             client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
             client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);

             HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");

             HttpResponseMessage response = await client.PostAsync(uri, content);
             response.EnsureSuccessStatusCode();
             string responseBody = await response.Content.ReadAsStringAsync();

             Console.WriteLine(responseBody);
          }
          catch(HttpRequestException e)
          {
             Console.WriteLine("\nException Caught!");
             Console.WriteLine("Message :{0} ",e.Message);
          }
        }

    }
}

POST https://api.bibox.com/v3.1/cquery/base_coin/bassets

Response

{
    "result":{
        "coinAssets":[
            {
                "coin_symbol":"BTC",
                "balance":"2.0230867132",
                "freeze":"0.0000685393",
                "profit":"-0.0000004735",
                "unprofit":"-0.0008529014",
                "can_transfer":"2.0222338118",
                "total_balance":"2.0223023511",
                "total_balance_usd":"20223.0235110000",
                "total_balance_cny":"131550.6837466242",
                "total_balance_btc":"2.0223023511",
                "order_freeze":"0.0000035218",
                "margin":"0.0000650175"
            },
            ...
        ],
        "total_balance_btc":"11897.1202764313",
        "total_balance_cny":"773907178.6813000767",
        "total_balance_usd":"118971202.7643127656"
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
coin_symbol 币种
balance 可用余额
order_freeze 挂单冻结
margin 保证金冻结
unprofit 未实现盈亏
total_balance 账户权益
其它字段 忽略

20.查询资金费率

GET https://api.bibox.com/v3.1/cquery/bcFundRate

Response

{
    "result":{
        "5BTC_USD":{
            "pair":"5BTC_USD",
            "close":"0.0000000000",
            "fund_rate":"0.0001000000",
            "createdAt":"2020-10-14T00:00:00.000Z"
        },
        "5ETH_USD":{
            "pair":"5ETH_USD",
            "close":"0.0000000000",
            "fund_rate":"0.0001000000",
            "createdAt":"2020-10-14T00:00:00.000Z"
        }
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
pair 交易对
fund_rate 即将收取的资金费率
其它字段 忽略

21.查询标记价格

GET https://api.bibox.com/v3.1/cquery/bcTagPrice

Response

{
    "result":{
        "5BTC_USD":{//交易对
            "close":"11453.7224909000",// 指数价格
            "priceTag":"11454.2951770245",// 标记价格
            "createdAt":"2020-10-14T03:41:08.000Z" // 时间
        },
        "5ETH_USD":{
            "close":"383.1999999600",
            "priceTag":"383.2191599600",
            "createdAt":"2020-10-14T03:41:08.000Z"
        }
    },
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
result 关键字是交易对
close 指数价格
priceTag 标记价格
createdAt 时间
其它字段 忽略

22.查询合约基本信息

GET https://api.bibox.com/v3.1/cquery/bcValue

Response

{
    "result":[
        {
            "id":465, // 忽略
            "pair":"5BTC_USD",//交易对
            "coin_symbol":"BTC", // 忽略
            "leverage_init":"10.0000000000", // 忽略
            "leverage_min":"0.0100000000",//最小杠杆倍数
            "leverage_max":"100.0000000000",//最大杠杆倍数
            "value":"1.0000000000",//合约面值
            "risk_level_base":"1000000.0000000000",//忽略
            "risk_level_dx":"50000.0000000000",//忽略
            "maker_fee":"0.0006000000",//默认maker手续费费率
            "taker_fee":"0.0006000000",//默认taker手续费费率
            "open_max_per":"10000000.0000000000",//单笔挂单最大数量
            "pending_max":100,//最大挂单个数
            "hold_max":"100000000.0000000000",//最大持仓价值
            "price_precision":1 // 忽略 
        },
        ...
    ],
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
pair 交易对
leverage_min 最小杠杆倍数
leverage_max 最大杠杆倍数
value 合约面值
maker_fee 默认maker手续费费率
taker_fee 默认taker手续费费率
open_max_per 单笔挂单最大数量
pending_max 最大挂单个数
hold_max 最大持仓价值
其它字段 忽略

23.查询精度配置

GET https://api.bibox.com/v3.1/cquery/bcUnit

Response

{
    "result":[
        {
            "pair":"5BTC_USD",//交易对
            "price_unit":1,//下单小数点数
            "vol_unit":6, // 忽略
            "value_unit":0 // 忽略
        },
        ...
    ],
    "state":0
}

名称 描述
state 0代表成功,否则代表失败
pair 交易对
price_unit 下单小数点数
其它字段 忽略

24.查询k线

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD, ...
period true string k线周期 '1min', '3min', '5min', '15min', '30min', '1hour', '2hour', '4hour', '6hour', '12hour', 'day', 'week'
size false integer 数量 1000 1-1000

Response

{
    "result":[
        {
            "time":1602680580000,// 时间戳
            "open":"10666.00000000",// 开盘价
            "high":"10666.00000000",// 最高价
            "low":"10666.00000000", // 最低价
            "close":"10666.00000000",// 收盘价
            "vol":"0.00000000"// 成交量
        },
        ...
    ],
    "cmd":"kline",
    "ver":"2.0"
}

名称 描述
result 有数据代表成功,否则代表失败
time 时间戳
open 开盘价
high 最高价
low 最低价
close 收盘价
vol 成交量
其它字段 忽略

25.查询合约市场深度

GET https://api.bibox.com/v2/mdata/depth?pair=5BTC_USD&size=10

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 4BTC_USDT, 4ETH_USDT, ...
size false integer 数量 200 1-200

Response

{
    "result":{
        "pair":"5BTC_USD",
        "update_time":1602669350668,
        "asks":[//卖方深度

        ],
        "bids":[//买方深度
            {
                "volume":"54054",//挂单数量
                "price":"10666"//挂单价格
            },
            ...
        ]
    },
    "cmd":"depth",
    "ver":"2.0"
}

名称 描述
result 有数据代表成功,否则代表失败
pair 交易对
update_time 时间
asks 卖方深度
bids 买方深度
volume 挂单数量
price 挂单价格
其它字段 忽略

26.订阅 Kline 数据

完整例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');

const biboxws = 'wss://npush.bibox360.com/cbc';


let wsClass = function () {

};

wsClass.prototype._decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log(err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log(new Date(), buffer.toString());
            } catch (e) {
                console.log(e);
            }
        }
    });
};

wsClass.prototype._initWs = async function () {
    let that = this;
    console.log(biboxws)
    let ws = new WebSocket(biboxws);
    that.ws = ws;

    ws.on('open', function open() {
        console.log(new Date(), 'open')
        ws.send(JSON.stringify({
            sub: '5BTC_USD_kline_1min',
            // unsub: '5BTC_USD_kline_1min',
        }));
    });

    ws.on('close', err => {
        console.log('close, ', err);
    });

    ws.on('error', err => {
        console.log('error', err);
    });

    ws.on('ping', err => {
        console.log('ping ', err.toString('utf8'));
    });

    ws.on('pong', err => {
        console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', data => {
        if (data[0] == '1') {
            that._decodeMsg(data);
        } else if (data[0] == '0') {
            console.log(1, new Date(), JSON.parse(data.slice(1)));
        } else {
            console.log(2, new Date(), JSON.parse(data));
        }

    });
};

let instance = new wsClass();

instance._initWs().catch(err => {
    console.log(err);
});

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib

ws_url = 'wss://npush.bibox360.com/cbc'


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sub_str():
    subdata = {
        'sub': '5BTC_USD_kline_1min',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': '5BTC_USD_kline_1min',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    elif message[0] == '\x00' or message[0] == 0:
        message = message[1:]
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    public static void Main (string[] args)
    {
      string wsuri = "wss://npush.bibox360.com/cbc";
      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");
            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);
                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);
                }
            }

        };

        ws.Connect ();

        var myobj = new {
            sub = "5BTC_USD_kline_1min",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD
period true string K线周期 1min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 12hour, day, week
sub true string '${pair} + '_kline_' + ${period}

Response

{
  topic: '5BTC_USD_kline_1min',
  t: 1,
  d: [
    [
      '1646464740000',
      '39113.6',
      '39135.2',
      '39111.8',
      '39111.8',
      '576699'
    ],
    [
      '1646464800000',
      '39111.8',
      '39129.6',
      '39081.2',
      '39129.6',
      '1348253'
    ]
  ]
}

[ k线某周期开始时间, 开盘价, 最高价, 最低价, 收盘价, 成交量(合约价值) ]

27.订阅标记价格

完整例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');

const biboxws = 'wss://npush.bibox360.com/cbc';


let wsClass = function () {

};

wsClass.prototype._decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log(err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log(new Date(), buffer.toString());
            } catch (e) {
                console.log(e);
            }
        }
    });
};

wsClass.prototype._initWs = async function () {
    let that = this;
    console.log(biboxws)
    let ws = new WebSocket(biboxws);
    that.ws = ws;

    ws.on('open', function open() {
        console.log(new Date(), 'open')
        ws.send(JSON.stringify({
            sub: '5BTC_USDTAGPRICE_kline_1min',
            // unsub: '5BTC_USDTAGPRICE_kline_1min',
        }));
    });

    ws.on('close', err => {
        console.log('close, ', err);
    });

    ws.on('error', err => {
        console.log('error', err);
    });

    ws.on('ping', err => {
        console.log('ping ', err.toString('utf8'));
    });

    ws.on('pong', err => {
        console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', data => {
        if (data[0] == '1') {
            that._decodeMsg(data);
        } else if (data[0] == '0') {
            console.log(1, new Date(), JSON.parse(data.slice(1)));
        } else {
            console.log(2, new Date(), JSON.parse(data));
        }

    });
};

let instance = new wsClass();

instance._initWs().catch(err => {
    console.log(err);
});

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib

ws_url = 'wss://npush.bibox360.com/cbc'


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sub_str():
    subdata = {
        'sub': '5BTC_USDTAGPRICE_kline_1min',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': '5BTC_USDTAGPRICE_kline_1min',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    elif message[0] == '\x00' or message[0] == 0:
        message = message[1:]
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    public static void Main (string[] args)
    {
      string wsuri = "wss://npush.bibox360.com/cbc";
      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");
            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);
                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);
                }
            }

        };

        ws.Connect ();

        var myobj = new {
            sub = "5BTC_USDTAGPRICE_kline_1min",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD
sub true string ${pair} + 'TAGPRICE_kline_1min'

Response

{
  topic: '5BTC_USDTAGPRICE_kline_1min',
  t: 1,
  d: [
    [
      '1646464680000',
      '39106.67632734',
      '39143.47178728',
      '39106.67632734',
      '39133.04415693',
      '30'
    ],
    [
      '1646464740000',
      '39132.729153',
      '39146.25432206',
      '39132.57415106',
      '39138.78672871',
      '16'
    ]
  ]
}

[ k线某周期开始时间, 开盘价, 最高价, 最低价, 收盘价, 成交量(忽略) ]

28.订阅深度

完整例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');

const biboxws = 'wss://npush.bibox360.com/cbc';


let wsClass = function () {

};

wsClass.prototype._decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log(err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log(new Date(), buffer.toString());
            } catch (e) {
                console.log(e);
            }
        }
    });
};

wsClass.prototype._initWs = async function () {
    let that = this;
    console.log(biboxws)
    let ws = new WebSocket(biboxws);
    that.ws = ws;

    ws.on('open', function open() {
        console.log(new Date(), 'open')
        ws.send(JSON.stringify({
            sub: '5BTC_USD_depth',
            // unsub: '5BTC_USD_depth',
        }));
    });

    ws.on('close', err => {
        console.log('close, ', err);
    });

    ws.on('error', err => {
        console.log('error', err);
    });

    ws.on('ping', err => {
        console.log('ping ', err.toString('utf8'));
    });

    ws.on('pong', err => {
        console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', data => {
        if (data[0] == '1') {
            that._decodeMsg(data);
        } else if (data[0] == '0') {
            console.log(1, new Date(), JSON.parse(data.slice(1)));
        } else {
            console.log(2, new Date(), JSON.parse(data));
        }

    });
};

let instance = new wsClass();

instance._initWs().catch(err => {
    console.log(err);
});

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib

ws_url = 'wss://npush.bibox360.com/cbc'


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sub_str():
    subdata = {
        'sub': '5BTC_USD_depth',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': '5BTC_USD_depth',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    elif message[0] == '\x00' or message[0] == 0:
        message = message[1:]
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    public static void Main (string[] args)
    {
      string wsuri = "wss://npush.bibox360.com/cbc";
      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");
            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);
                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);
                }
            }

        };

        ws.Connect ();

        var myobj = new {
            sub = "5BTC_USD_depth",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD
sub true string ${pair} + '_depth'

Response

{
    "topic":"5BTC_USD_depth",
    "t":1,
    "d":{
        "pair":"5BTC_USD",
        "ut":1646465078003,
        "seq":2078286,
        "add":{
            "asks":[
                [
                    "18438",
                    "39092.2"
                ]
            ],
            "bids":[
                [
                    "7314",
                    "39075.2"
                ]
            ]
        },
        "del":{
            "asks":[
                [
                    "25",
                    "44840"
                ]
            ],
            "bids":[
                [
                    "422685",
                    "39040.9"
                ]
            ]
        }
    }
}

名称 描述
pair 交易对
ut 时间
t 0代表全量数据,1代表增量数据
seq 序列号
add 新增的深度
del 删除的深度
mod 修改的深度
asks 卖单,第一字段是挂单数量,第二字段是深度价格
bids 买单
其它字段 忽略

29.订阅成交记录

完整例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');

const biboxws = 'wss://npush.bibox360.com/cbc';


let wsClass = function () {

};

wsClass.prototype._decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log(err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log(new Date(), buffer.toString());
            } catch (e) {
                console.log(e);
            }
        }
    });
};

wsClass.prototype._initWs = async function () {
    let that = this;
    console.log(biboxws)
    let ws = new WebSocket(biboxws);
    that.ws = ws;

    ws.on('open', function open() {
        console.log(new Date(), 'open')
        ws.send(JSON.stringify({
            sub: '5BTC_USD_deals',
            // unsub: '5BTC_USD_deals',
        }));
    });

    ws.on('close', err => {
        console.log('close, ', err);
    });

    ws.on('error', err => {
        console.log('error', err);
    });

    ws.on('ping', err => {
        console.log('ping ', err.toString('utf8'));
    });

    ws.on('pong', err => {
        console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', data => {
        if (data[0] == '1') {
            that._decodeMsg(data);
        } else if (data[0] == '0') {
            console.log(1, new Date(), JSON.parse(data.slice(1)));
        } else {
            console.log(2, new Date(), JSON.parse(data));
        }

    });
};

let instance = new wsClass();

instance._initWs().catch(err => {
    console.log(err);
});

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib

ws_url = 'wss://npush.bibox360.com/cbc'


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sub_str():
    subdata = {
        'sub': '5BTC_USD_deals',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': '5BTC_USD_deals',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    elif message[0] == '\x00' or message[0] == 0:
        message = message[1:]
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    public static void Main (string[] args)
    {
      string wsuri = "wss://npush.bibox360.com/cbc";
      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");
            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);
                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);
                }
            }

        };

        ws.Connect ();

        var myobj = new {
            sub = "5BTC_USD_deals",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD
sub true string ${pair} + '_deals'

Response

{
    "topic":"5BTC_USD_deals",
    "t":0,
    "d":{
        "pair":"5BTC_USD",
        "d":[
            [
                "39087.2",
                "47001",
                "2",
                "1646465389633",
                ""
            ],
            [
                "39111.8",
                "1281",
                "2",
                "1646464813823",
                ""
            ]
        ]
    }
}

{
  topic: '5BTC_USD_deals',
  t: 1,
  d: [ '5BTC_USD', '39086.6', '50', '1', '1646465418417', '' ]
}

名称 描述
t 0代表全量数据,1代表增量数据
d 数组定义:交易对,成交价格,成交价值,成交方向(1-开多,2-开空),成交时间戳

30.订阅最新成交价

完整例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');

const biboxws = 'wss://npush.bibox360.com/cbc';


let wsClass = function () {

};

wsClass.prototype._decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log(err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log(new Date(), buffer.toString());
            } catch (e) {
                console.log(e);
            }
        }
    });
};

wsClass.prototype._initWs = async function () {
    let that = this;
    console.log(biboxws)
    let ws = new WebSocket(biboxws);
    that.ws = ws;

    ws.on('open', function open() {
        console.log(new Date(), 'open')
        ws.send(JSON.stringify({
            sub: '5BTC_USD_ticker',
            // unsub: '5BTC_USD_ticker',
        }));
    });

    ws.on('close', err => {
        console.log('close, ', err);
    });

    ws.on('error', err => {
        console.log('error', err);
    });

    ws.on('ping', err => {
        console.log('ping ', err.toString('utf8'));
    });

    ws.on('pong', err => {
        console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', data => {
        if (data[0] == '1') {
            that._decodeMsg(data);
        } else if (data[0] == '0') {
            console.log(1, new Date(), JSON.parse(data.slice(1)));
        } else {
            console.log(2, new Date(), JSON.parse(data));
        }

    });
};

let instance = new wsClass();

instance._initWs().catch(err => {
    console.log(err);
});

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib

ws_url = 'wss://npush.bibox360.com/cbc'


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sub_str():
    subdata = {
        'sub': '5BTC_USD_ticker',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': '5BTC_USD_ticker',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    elif message[0] == '\x00' or message[0] == 0:
        message = message[1:]
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    public static void Main (string[] args)
    {
      string wsuri = "wss://npush.bibox360.com/cbc";
      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");
            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);
                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);
                }
            }

        };

        ws.Connect ();

        var myobj = new {
            sub = "5BTC_USD_ticker",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 5BTC_USD, 5ETH_USD
sub true string '${pair} + '_ticker'

Response

{
    "topic":"5BTC_USD_ticker",
    "t":0,
    "d":[
        "5BTC_USD",
        "39043.5",
        "39043.50",
        "248316.10",
        "41890.7",
        "38540",
        "39043.4",
        "7009",
        "39043.5",
        "1500",
        "1750950839",
        "-5.55%",
        "1646465730385",
        "248316.10000000"
    ]
}

[ 交易对, 最新成交价, 最新成交价(usd计价), 最新成交价(cny计价), 24h最高价, 24h最低价, 最新买一价, 买一价值, 最新卖一价, 卖一价值, 24h成交价值, 24h涨跌幅, 时间戳, 最新成交价(cny计价) ]

31.订阅用户数据方法

实际例子


'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');
let CryptoJS = require("crypto-js");

const biboxws = 'wss://npush.bibox360.com/cbc'; // 1.请求路径

let ws;

let apikey = '900625568558820892a8c833c33ebc8fd2701efe'; // 你的apikey
let secret = 'c708ac3e70d115ec29efbee197330627d7edf842'; // apikey的密码

let subparam = JSON.stringify({ // 格式化参数对象,得到subparam
    apikey,
    sub: 'ALL_ALL_login'
});
let sign = CryptoJS.HmacMD5(subparam, String(secret)).toString(); // 用apikey的密码secret对得到subparam进行HmacMD5签名,得到签名结果sign
let form = { // 得到最终的订阅参数
    apikey,
    sign,
    sub: 'ALL_ALL_login',
};
console.log('form', form)

let reiniting = false;

let resend = function (user_id) {
    if (ws.readyState != WebSocket.OPEN) {
        return setTimeout(function () {
            resend(user_id);
        }, 1000 * 10);
    }

    ws.send(JSON.stringify(form));
};

setInterval(function () {
    if (ws && ws.readyState == WebSocket.OPEN) {
        ws.ping(new Date().getTime());
    }
}, 1000 * 10);

let reinit = function () {
    if (reiniting) {
        return;
    }
    reiniting = true;
    try {
        if (ws && ws.readyState == WebSocket.OPEN) {
            console.log('manu close ')
            ws.close();
        }
    } catch (err) {

    }
    setTimeout(function () {
        init();
    }, 1000 * 30);
};

let init = function (user_id) {

    console.log('init', user_id);
    reiniting = false;

    ws = new WebSocket(biboxws);

    setTimeout(function () {
        if (!ws || ws.readyState != WebSocket.OPEN) {
            reinit(user_id);
        }
    }, 1000 * 60);

    ws.on('open', function open() {

        resend(user_id);

    });

    ws.on('close', err => {
        console.log('close, ', err);
        reinit(user_id);
    });

    ws.on('error', err => {
        console.log('error', err);
        reinit(user_id);
    });

    ws.on('ping', err => {
        console.log('ping on', err.toString('utf8'));
    });

    ws.on('pong', err => {
        // console.log('pong ', err.toString('utf8'));
    });

    ws.on('message', function incoming(data) {
        if (data[0] == '1') {
            decodeMsg(data);
        } else {
            console.log(1, JSON.parse(data));
        }

    });
};

let login = function () {
    if (reiniting) {
        return;
    }
    reiniting = false;
    init();
};

let decodeMsg = function (data) {
    let data1 = data.slice(1, data.length);
    zlib.unzip(data1, (err, buffer) => {
        if (err) {
            console.log('2', err);
        } else {
            try {
                let res = JSON.parse(buffer.toString());
                console.log('3', buffer.toString());
            } catch (e) {
                console.log('4', e);
            }
        }
    });
};

module.exports = {};

login();

# /usr/bin/env python
# -*- coding: UTF-8 -*-

import websocket # websocket-client
import json
import zlib
import hmac
import hashlib

ws_url = 'wss://npush.bibox360.com/cbc'
apikey = '900625568558820892a8c833c33ebc8fd2701efe'  # your apikey
secret = 'c708ac3e70d115ec29efbee197330627d7edf842'  # your apikey secret


def stringify(obj):
    return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")


def get_sign(data, secret):
    return hmac.new(secret.encode("utf-8"), data.encode("utf-8"), hashlib.md5).hexdigest()


def get_sub_str():
    subdata = {
        'apikey': apikey,
        'sub': 'ALL_ALL_login',
    }
    # print(stringify(subdata))
    sign = get_sign(stringify(subdata), secret)
    subdata = {
        'apikey': apikey,
        'sign': sign,
        'sub': 'ALL_ALL_login',
    }
    # print(stringify(subdata))
    return stringify(subdata)


def get_unsub_str():
    subdata = {
        'unsub': 'ALL_ALL_login',
    }
    return stringify(subdata)


def decode_data(message):
    if message[0] == '\x01' or message[0] == 1:
        message = message[1:]
        data = zlib.decompress(message, zlib.MAX_WBITS | 32)
        jmsgs = json.loads(data)
        print(jmsgs)
        print(type(jmsgs))
    else:
        jmsgs = json.loads(message)
        print(jmsgs)
        print(type(jmsgs))


def on_message(ws, message):
    # print(message)
    decode_data(message)


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    ws.send(get_sub_str())


def connect():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(ws_url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever(ping_interval=30, ping_timeout=5)


if __name__ == "__main__":
    connect()

using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Example
{
    public class SortContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

            return properties.OrderBy(x=>x.PropertyName).ToList();
        }
    }

  public class Program
  {

    public static string Decompress(byte[] bytes)
    {
        MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
        MemoryStream msOut = new MemoryStream();

        GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
        cprs.CopyTo(msOut);
        cprs.Close();

        return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
    }

    static string HmacMD5(string source, string key)
           {
               HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
               byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
               StringBuilder sb = new StringBuilder();

               for (int i = 0; i < inArray.Length; i++)
               {
                   sb.Append(inArray[i].ToString("X2"));
               }

               hmacmd.Clear();

               return sb.ToString().ToLower();
           }

    public static void Main (string[] args)
    {
        string wsuri = "wss://npush.bibox360.com/cbc";
        string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
        string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

      using (var ws = new WebSocket (wsuri)) {
        ws.OnMessage += (sender, e) => {

            Console.WriteLine ("recv: " + e.Data);

            if (e.IsText) {
              Console.WriteLine ("data[0]: {");

            } else if (e.IsBinary) {
                if (e.RawData[0] == 1) {
                    Console.WriteLine ("RawData[0]: 1");
                    string strres = Decompress(e.RawData);
                    Console.WriteLine (strres);

                } else if (e.RawData[0] == 0) {
                    Console.WriteLine ("RawData[0]: 0");
                    string strres = Encoding.ASCII.GetString(e.RawData);
                    Console.WriteLine (strres);

                }
            }

        };

        ws.Connect ();

        var myparam = new {
            apikey = apikey,
            sub = "ALL_ALL_login",
        };
        string myparamstr = JsonConvert.SerializeObject(myparam, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
        string sign = HmacMD5(myparamstr, secret);


        var myobj = new {
            apikey = apikey,
            sign = sign,
            sub = "ALL_ALL_login",
        };

        string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });

        ws.Send (payload);

        ConsoleKey key;
        do
      {
            key=Console.ReadKey().Key;
      
      } while (key != ConsoleKey.Q);

      }
    }
  }
}

wss://push.bibox.com/cbc

参数名称 是否必须 类型 描述 默认值 取值范围
apikey true string 您在Bibox交易所申请的apikey
sign true string 使用您在Bibox交易所申请的apisecret对整个请求数据进行签名
sub true string 'ALL_ALL_login'

1.定义参数对象param,需要用到apikey

let apikey = 'this is your apikey';

let param = { "apikey": apikey, "sub": "ALL_ALL_login" };

2.格式化参数对象param,得到strParam

let strParam = JSON.stringify(param);

3.用apikey的密码secret对strParam进行HmacMD5签名,得到签名结果sign

let CryptoJS = require("crypto-js");

let secret = 'this is your apikey secret';

let sign = CryptoJS.HmacMD5(strParam, secret).toString();

4.生成订阅参数 wsparam

let wsparam = { "apikey": apikey, "sign": sign, "sub": "ALL_ALL_login" };

5.取消订阅

let wsparam = { "apikey": apikey, "sign": sign, "unsub": "ALL_ALL_login" };

Response

{
    "topic":"ALL_ALL_login",
    "uid":"1000000",
    "t":0,
    "d":{
        "result":"订阅成功"
    }
}

名称 描述
result "订阅成功" 代表订阅成功
其它字段 忽略

32.订阅用户数据解析资产

cbc_assets

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "cbc_assets":{
            "b":"2.1020558887",
            "c":"BTC",
            "u":100006,
            "f":"0",
            "m":"0.0000141934"
        }
    }
}

名称 描述
b 可用余额
c 币种符号
u 用户id
f 冻结资金
m 冻结保证金
其它字段 忽略

33.订阅用户数据解析仓位

cbc_order

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "cbc_order":{
            "pt":"0.0020756655",
            "f":"0.0000001168",
            "l":"10",
            "sd":2,
            "pa":"47096342.2962158",
            "ui":100006,
            "fb0":"0",
            "pf":"47096342.2962158",
            "md":1,
            "lc":"7",
            "pi":"5BTC_USD",
            "mg":"0.0000147457",
            "hc":"7",
            "fb":"0",
            "po":"47096.3422962158"
        }
    }
}

名称 描述
l 杠杆
sd 仓位方向: 1, 多仓 2 , 空仓
pa 告警价格
ui 用户id
pf 爆仓价格
md 仓位模式: 1全仓, 2逐仓
lc 可平仓位价值
pi 交易对
mg 保证金
hc 仓位价值 = 合约张数X合约面值
po 开仓价格
其它字段 忽略

34.订阅用户数据解析挂单

cbc_pending

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "cbc_pending":{
            "f":"0.0000000167",
            "dp":"36017.9",
            "eq":"1",
            "p":"35660",
            "tif":0,
            "q":"1",
            "sd":2,
            "r":0,
            "s":3,
            "t":1646466808030,
            "ui":100006,
            "fz":"0",
            "fb0":"0",
            "of":6,
            "pi":"5BTC_USD",
            "oi":"15393162788872",
            "coi":"0",
            "fb":"0",
            "po":false
        }
    }
}

名称 描述
f 手续费
dp 成交价格
eq 成交数量
p 下单价格
q 下单数量
sd 下单方向
r 失败原因
s 订单状态
t 下单时间
ui 用户id
fz 挂单冻结
fb0 优惠券抵扣
of 订单来源
pi 交易对
oi 订单id
coi 用户自定义订单id
fb bix抵扣
其它字段 忽略

35.订阅用户数据解析成交明细

cbc_detail

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "cbc_detail":{
            "oi":"15393162788872",
            "ui":"100006",
            "id":"1125899906851141149",
            "coi":"0",
            "pi":"5BTC_USD",
            "sd":2,
            "s":3,
            "ot":1,
            "of":6,
            "q":"1",
            "p":"35660",
            "dp":"36017.9",
            "ep":"1",
            "f":"0.0000000167",
            "fb":"0",
            "fb0":"0",
            "im":0,
            "t":1646466808030
        }
    }
}

名称 描述
oi 订单id
ui 用户id
id 明细id
coi 用户自定义订单id
pi 交易对
sd 下单方向
of 订单来源
p 下单价格
dp 成交价格
f 手续费
fb0 优惠券抵扣
fb bix抵扣
im 是否是maker
t 下单时间
其它字段 忽略

36.订阅用户数据解析持仓被动变化信息

cbc_deal_log

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "cbc_deal_log":{
            "id":"1125899906842654296",// 变化id
            "user_id":100006,//用户id
            "type":5,//变化类型,1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
            "mode":2,//仓位模式 1全仓,2逐仓
            "pair":"5BTC_USD",//交易对
            "price":"11247.6",//参考价格
            "hold_dx":"1",//持仓变化量
            "order_side":2,// 仓位方向,1多仓,2空仓
            "time":1602755131000, //变化时间
        }
    }
}

名称 描述
id 变化id
user_id 用户id
type 变化类型,1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
mode 仓位模式 1全仓,2逐仓
pair 交易对
price 参考价格
hold_dx 持仓变化量
order_side 仓位方向,1多仓,2空仓
time 变化时间
其它字段 忽略

Errors

错误码

Code 描述 Msg
2003 Cookie 失效 Cookie expired
2033 操作失败!订单已完成或已撤销 Operation failed! Order completed or canceled
2034 操作失败!请检查参数是否正确 Operation failed! Please check parameter
2040 操作失败!没有该订单 Operation failed! No record
2064 订单撤销中,不能再次撤销 Canceling. Unable to cancel again
2065 委托价格设置过高,请重新设置价格 Precatory price is exorbitant, please reset
2066 委托价格设置过低,请重新设置价格 Precatory price is low , please reset
2067 暂不支持市价单 Limit Order Only
2068 下单数量不能低于0.0001 Min Amount:0.0001
2069 市价单无法撤销 Market order can not be canceled
2078 下单价格非法 unvalid order price
2085 币种最小下单数量限制 the trade amount is low
2086 账户资产异常,限制下单 Abnormal account assets, trade is forbiden
2091 请求过于频繁,请稍后再试 request is too frequency, please try again later
2092 币种最小下单金额限制 Minimum amount not met
3000 请求参数错误 Requested parameter incorrect
3002 参数不能为空 Parameter cannot be null
3009 推送订阅channel不合法 Illegal subscription channel
3010 websocket连接异常 websocket connection error
3011 接口不支持apikey请求方式 Illegal subscribe event
3012 apikey无效 Interface does not support apikey request method
3016 交易对错误 Invalid apikey
3017 推送订阅event不合法 Trading pair error
3024 apikey权限不足 apikey authorization insufficient
3025 apikey签名验证失败 apikey signature verification failed
3026 apikey ip受限制 apikey ip is restricted
3027 账户没有apikey No apikey in your account
3028 账户apikey数量超过了限制数量 Account apikey has exceeded the limit amount
3029 apikey允许ip数量超过了限制数量 apikey ip has exceeded the limit amount
3033 查询类请求限制一个cmd query allow only one cmd
3034 最大cmd个数限制 maxinum cmds
3035 cmd请求个数限制 too many cmds
4000 当前网络连接不稳定,请稍候重试 the network is unstable now, please try again later
4003 服务器繁忙,请稍后再试 The server is busy, please try again later