English
javascript python csharp

U本位合约

SDK与代码示例

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

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


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

Console.WriteLine("U本位合约 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":"USDT",
    "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/cbuassets/transfer";

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
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/cbuassets/transfer'
    body = {
        'symbol': 'USDT',
        '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/cbuassets/transfer";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                symbol = "USDT",
                type = 0,
                amount = 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);
          }
        }

    }
}

字段名 类型 描述 取值
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":"USDT",
    "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/cbuassets/transfer";

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
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/cbuassets/transfer'
    body = {
        'symbol': 'USDT',
        '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/cbuassets/transfer";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                symbol = "USDT",
                type = 0,
                amount = 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/cbuassets/transfer

参数名称 是否必须 类型 描述 默认值 取值范围
amount true string 数量转字符串
symbol true string 币种 USDT
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/cbu/order/open";

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

let param = {
    "pair":"4BTC_USDT",
    "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
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 order_open():
    path = '/v3/cbu/order/open'
    body = {
        "pair": "4BTC_USDT",
        "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__':
    order_open()

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/cbu/order/open";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                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);
          }
        }

    }
}

在合约账户中转入资金之后,才能下单成功。 下单的数量参数amount必须是合约面值的整数倍,本意是以一张合约为基本单位。例如:一张4XRP_USDT合约的面值为10XRP,那么amount参数必须是10的整数倍,如果传的不是10的整数倍,则会提示“amount参数错误”。 下市价单的时候,price参数传1即可,系统会根据最优价格下单。最优价格跟杠杆倍数有关,如果是高杠杆,就限制了最优价格偏离当前指数价不能太远,所以可能会导致单子不能完全成交甚至没有成交的情况。 下限价单的时候,price参数同样受到最优价格的限制,如果是高杠杆,下单价格不能偏离当前指数价太远,不允许出现单子一成交就爆仓的情况。

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

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 4BTC_USDT,4ETH_USDT, ...
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

如果是开仓单,并且希望成交后设置止盈止损,可以增加以下参数。

参数名称 是否必须 类型 描述 默认值 取值范围
plan_type true integer 止盈止损触发后委托类型 1市价,2限价
profit_price true string 止盈触发价(限价开多时,止盈触发价必须大于委托价。限价开空时,止盈触发价应该小于委托价。市价开多时,止盈触发价必须大于最新价。市价开空时,止盈触发价应该小于最新价。)
loss_price true string 止损触发价(限价开多时,止损触发价必须小于委托价。限价开空时,止损触发价应该大于委托价。市价开多时,止损触发价必须小于最新价。市价开空时,止损触发价应该大于最新价。)
exec_profit_price false string 止盈委托价(如果plan_type=2,则必须设置)
exec_loss_price false string 止盈委托价(如果plan_type=2,则必须设置)

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/cbu/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 order_close():
    path = '/v3/cbu/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__':
    order_close()

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/cbu/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/cbu/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/cbu/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 order_close_batch():
    path = '/v3/cbu/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__':
    order_close_batch()

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/cbu/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/cbu/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/cbu/order/closeAll";

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

let param = {
    "pair":"4BTC_USDT"
};

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 order_close_all():
    path = '/v3/cbu/order/closeAll'
    body = {
        "pair": "4BTC_USDT"
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_close_all()

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/cbu/order/closeAll";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
             };

             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/cbu/order/closeAll

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

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/cbu/order/planOpen";

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

let param = {
    pair:"4BTC_USDT", 
    price: 58000, 
    trigger_price: 58000, 
    amount: 0.001, 
    side: 1, 
    plan_type: 1, 
    book_type: 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 order_plan_open():
    path = '/v3/cbu/order/planOpen'
    body = {
        'pair': "4BTC_USDT",
        'price': 58000,
        'trigger_price': 58000,
        'amount': 0.001,
        'side': 1,
        'plan_type': 1,
        'book_type': 1,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_plan_open()

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/cbu/order/planOpen";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                price = "58000",
                trigger_price = "58000",
                amount = "0.001",
                side = 1,
                plan_type = 1,
                book_type = 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);
          }
        }

    }
}

止盈委托数量amount不能超过持仓量。已委托的止盈委托数量可以在仓位信息接口中获取,关键字pp。多仓止盈触发价trigger_price应该比当前价高,空仓止盈触发价应该比当前价低,否则会提示“触发价错误”。 止损委托数量amount不能超过持仓量。已委托的止损委托数量可以在仓位信息接口中获取,关键字ps。多仓止损触发价trigger_price应该比当前价低,空仓止损触发价应该比当前价高,否则会提示“触发价错误”。

POST https://api.bibox.com/v3/cbu/order/planOpen

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 4BTC_USDT,4ETH_USDT, ...
price true string 委托价
trigger_price true string 触发价
amount true string 委托数量
side true int 多仓或空仓 1多仓、2空仓
plan_type true int 止盈或止损 1止盈、2止损
book_type true int 市价或限价 1市价止盈止损,2限价止盈止损

Response

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

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

8.止盈止损委托列表

Request

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

let url = "https://api.bibox.com/v3/cbu/order/planOrderList";

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

let param = {
    pair:"4BTC_USDT", 
};

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 order_plan_order_list():
    path = '/v3/cbu/order/planOrderList'
    body = {
        'pair': "4BTC_USDT",
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_plan_order_list()

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/cbu/order/planOrderList";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
             };

             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/cbu/order/planOrderList

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 4BTC_USDT,4ETH_USDT, ...

Response

{
    "state":0,
    "result":[
        {
            "tt":1,
            "pr":"49900",
            "pt":1,
            "pid":"0",
            "q":"0.001",
            "sd":2,
            "r":0,
            "bt":1,
            "s":1,
            "t":1638155219319,
            "ui":100006,
            "si":"0",
            "pi":"4BTC_USDT",
            "oi":"5198029",
            "bid":"0",
            "tp":"49900",
            "otd":"0"
        },
        ...
    ],
    "cmd":"planOrderList"
}

名称 描述
state 0代表成功,否则代表失败
oi 委托ID号
pi 合约符号
pr 委托价
tp 触发价
q 委托数量
sd 多仓或空仓:1多仓、2空仓
pt 止盈或止损:1止盈、2止损
bt 市价或限价:1市价止盈止损,2限价止盈止损
s 委托状态:1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消
其它字段 忽略

9.撤销止盈止损委托

Request

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

let url = "https://api.bibox.com/v3/cbu/order/planClose";

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 order_plan_close():
    path = '/v3/cbu/order/planClose'
    body = {
        "order_id": "425510999949316"
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_plan_close()

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/cbu/order/planClose";
             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);
          }
        }

    }
}

需要从止盈止损委托列表中获取订单id号。

POST https://api.bibox.com/v3/cbu/order/planClose

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

Response

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

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

10.全部撤销止盈止损委托

Request

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

let url = "https://api.bibox.com/v3/cbu/order/planCloseAll";

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

let param = {
    "pair":"4BTC_USDT"
};

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 order_plan_close_all():
    path = '/v3/cbu/order/planCloseAll'
    body = {
        "pair":"4BTC_USDT"
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_plan_close_all()

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/cbu/order/planCloseAll";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
             };

             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/cbu/order/planCloseAll

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 4BTC_USDT,4ETH_USDT, ...

Response

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

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

11.逐仓调整保证金

Request

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

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

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

let param = {
    "pair":"4BTC_USDT",
    "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 change_margin():
    path = '/v3/cbu/changeMargin'
    body = {
        "pair": "4BTC_USDT",
        "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__':
    change_margin()

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/cbu/changeMargin";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                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/cbu/changeMargin

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

Response

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

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

12.调整持仓模式及杠杆

Request

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

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

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

let param = {
    "pair":"4BTC_USDT",
    "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 change_mode():
    path = '/v3/cbu/changeMode'
    body = {
        "pair": "4BTC_USDT",
        "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__':
    change_mode()

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/cbu/changeMode";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                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/cbu/changeMode

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 4BTC_USDT,4ETH_USDT, ...
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代表成功,否则代表失败
其它字段 忽略

13.查询资产

Request

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

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

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

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

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 assets():
    path = '/v3/cbu/assets'
    body = {
        "coin": "USDT",
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    assets()

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/cbu/assets";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

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

             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/cbu/assets

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

Response

{
    "state":0,
    "result":[
        { ff: '0',
           b: '219311.9556',
           c: 'USDT',
           u: 100006,
           mc: '93265.8573',
           mf: '60.8824',
           fc: '0' }
    ],
    "cmd":"assets"
}

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

14.查询仓位

Request

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

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

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

let param = {
    // "pair":"4BTC_USDT",
    // "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 position():
    path = '/v3/cbu/position'
    body = {
        "pair": "4BTC_USDT",
        "side": 1
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    position()

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/cbu/position";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                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);
          }
        }

    }
}

pp是指已经委托的止盈仓位数量,剩余可以作为止盈委托的仓位数量为hc - pp。例如:持仓数量hc为1BTC,已委托止盈数量pp为0.4BTC,那么剩余0.6BTC可以下止盈委托。 ps是指已经委托的止损仓位数量,剩余可以作为止损委托的仓位数量为hc - ps。例如:持仓数量hc为1BTC,已委托止损数量ps为0BTC,那么剩余1BTC可以下止损委托。

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

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 4BTC_USDT,4ETH_USDT, ...
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":"4BTC_USDT", // 交易对
            "mg":"0", //保证金
            "hc":"0",// 仓位价值 = 合约张数X合约面值
            "fb":"0",//忽略
            "po":"0" //开仓价格
            "pp":"0.004",
            "ps":"0.001",
        },
        ...
    ],
    "cmd":"position"
}

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

15.查询订单列表

Request

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

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

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

let param = {
    // "pair":"4BTC_USDT",
    // "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 order_list():
    path = '/v3/cbu/order/list'
    body = {
        "pair": "4BTC_USDT",
        "order_side": 1
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    order_list()

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/cbu/order/list";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                pair = "4BTC_USDT",
                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/cbu/order/list

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

Response

{
    "state":0,
    "result":{
        "p":1,
        "t":1,
        "o":[
            {
                "tt":1,
                "tw":"47000",
                "pw":"47000",
                "dp":"0",
                "tif":0,
                "sd":2,
                "bt":2,
                "ui":100006,
                "fz":"48.6048",
                "of":4,
                "oi":"17592186044698",
                "ot":2,
                "f":"0",
                "eq":"0",
                "p":"48000",
                "q":"0.01",
                "tpl":"49000",
                "r":0,
                "s":1,
                "t":1639462436971,
                "pd":"0",
                "fb0":"0",
                "tl":"49000",
                "pi":"4BTC_USDT",
                "tpw":"0",
                "coi":"1639462436446",
                "fb":"0",
                "pl":"49000",
                "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抵扣
bt 止盈止损委托类型:1市价,2限价,否则代表未设置止盈止损。
tw 止盈触发价
tl 止损触发价
pw 止盈委托价(如果bt=1,则忽略)
pl 止损委托价(如果bt=1,则忽略)
其它字段 忽略

16.查询在线订单

Request

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

let url = "https://api.bibox.com/v3/cbu/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 order_detail():
    path = '/v3/cbu/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__':
    order_detail()

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/cbu/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/cbu/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":"4BTC_USDT", //交易对
        "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抵扣
bt 止盈止损委托类型:1市价,2限价,否则代表未设置止盈止损。
tw 止盈触发价
tl 止损触发价
pw 止盈委托价(如果bt=1,则忽略)
pl 止损委托价(如果bt=1,则忽略)
其它字段 忽略

17.批量查询订单列表

Request

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

let url = "https://api.bibox.com/v3/cbu/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 order_list_batch():
    path = '/v3/cbu/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__':
    order_list_batch()

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/cbu/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/cbu/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":"4BTC_USDT", //交易对
            "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抵扣
bt 止盈止损委托类型:1市价,2限价,否则代表未设置止盈止损。
tw 止盈触发价
tl 止损触发价
pw 止盈委托价(如果bt=1,则忽略)
pl 止损委托价(如果bt=1,则忽略)
其它字段 忽略

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

Request

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

let url = "https://api.bibox.com/v3/cbu/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 order_list_batch_by_client_oid():
    path = '/v3/cbu/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__':
    order_list_batch_by_client_oid()

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/cbu/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/cbu/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":"4BTC_USDT", //交易对
            "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抵扣
bt 止盈止损委托类型:1市价,2限价,否则代表未设置止盈止损。
tw 止盈触发价
tl 止损触发价
pw 止盈委托价(如果bt=1,则忽略)
pl 止损委托价(如果bt=1,则忽略)
其它字段 忽略

19.获取服务器时间

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

Response

{
    "time":"1602680518605"
}

名称 描述
time 服务器时间

20.查询持仓变化记录

Request

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

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

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

let param = {
    "pair": "4BTC_USDT",
    "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 get_baseu_deal_log():
    path = '/v3.1/cquery/base_u/dealLog'
    body = {
        "pair": "4BTC_USDT",
        "page": 1,
        "size": 10,
    }
    headers = do_sign(body)
    resp = requests.post(BASE_URL + path, json=body, headers=headers)
    print(resp.text)


if __name__ == '__main__':
    get_baseu_deal_log()

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_u/dealLog";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 pair = "4BTC_USDT",
                 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_u/dealLog

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 合约符号 4BTC_USDT,4ETH_USDT, ...
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":"USDT",// 币种
                "pair":"4BTC_USDT",// 交易对
                "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 变化时间
其它字段 忽略

21.查询订单成交明细

Request

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

let url = "https://api.bibox.com/v3.1/cquery/base_u/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 get_baseu_order_detail():
    path = '/v3.1/cquery/base_u/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__':
    get_baseu_order_detail()

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_u/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_u/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":"USDT",// 币种
                "pair":"4BTC_USDT",// 交易对
                "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
其它字段 忽略

22.查询历史委托

Request

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

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

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

let param = {
    "page": 1,
    "size": 10,
    "pair": "4BTC_USDT",
    "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 get_baseu_order_history():
    path = '/v3.1/cquery/base_u/orderHistory'
    body = {
        "page": 1,
        "size": 10,
        "pair": "4BTC_USDT",
        "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__':
    get_baseu_order_history()

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_u/orderHistory";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 page = 1,
                 size = 10,
                 pair = "4BTC_USDT",
                 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_u/orderHistory

参数名称 是否必须 类型 描述 默认值 取值范围
pair false string 合约符号 4BTC_USDT,4ETH_USDT, ...
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":"USDT",// 币种
                "pair":"4BTC_USDT",// 交易对
                "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 挂单时间
其它字段 忽略

23.查询订单(历史订单也可以查到)

Request

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

let url = "https://api.bibox.com/v3.1/cquery/base_u/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 get_baseu_order_by_id():
    path = '/v3.1/cquery/base_u/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__':
    get_baseu_order_by_id()

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_u/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_u/orderById

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

Response

{
    "result":[
        {
            "id":421112953438214,// 订单id
            "user_id":100006,// 用户id
            "coin_symbol":"USDT",// 币种
            "pair":"4BTC_USDT",// 交易对
            "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 挂单时间
其它字段 忽略

24.查询账单

Request

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

let url = "https://api.bibox.com/v3.1/cquery/base_u/bills";

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

let param = {
    // pair: '4BTC_USDT',
    coin_symbol: 'USDT', 
    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 get_baseu_bills():
    path = '/v3.1/cquery/base_u/bills'
    timestamp = int(time.time()) * 1000
    body = {
        'coin_symbol': 'USDT',
        '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__':
    get_baseu_bills()

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_u/bills";
             string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
             string secret = "c708ac3e70d115ec29efbee197330627d7edf842";

             string timestamp = GetTimeStamp();
             var myobj = new {
                 coin_symbol = "USDT",
                 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_u/bills

参数名称 是否必须 类型 描述 默认值 取值范围
coin_symbol false string 币种符号 USDT
page true integer 第几页 1,2, ...
size true integer 条数 10,20, ...
from false integer 起始时间
to false integer 结束时间
pair false string 交易对 4BTC_USDT,4ETH_USDT,...
bill_type false integer 账单类型 1划转,2交易,3交易手续费,4资金费用,5资金费用调整,6降低风险等级减仓,7强平,8ADL系统减仓

Response

{
    "result":{
        "count":5,
        "page":1,
        "items":[
            {
                "id":"1125899906862835742",
                "user_id":100006,
                "coin_symbol":"USDT",
                "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 交易对
bill_type 账单类型:1划转,2交易,3交易手续费,4资金费用,5资金费用调整,6降低风险等级减仓,7强平,8ADL系统减仓
change_amount 划转数量
createdAt 时间
其它字段 忽略

25.查询资产估值

Request

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

let url = "https://api.bibox.com/v3.1/cquery/base_u/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 get_baseu_bassets():
    path = '/v3.1/cquery/base_u/bassets'
    body = {

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


if __name__ == '__main__':
    get_baseu_bassets()

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_u/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_u/bassets

Response

{
    "result":{
        "coin_symbol":"USDT",
        "balance":"219311.9556002830",
        "freeze":"93326.7398201745",
        "profit":"-60.6199055207",
        "unprofit":"192892.4452599042",
        "unprofit_cross":"191985.4645940268",
        "can_transfer":"219311.9556002830",
        "total_balance":"505531.1406803617",
        "total_balance_usd":"505529.2297726499",
        "total_balance_cny":"3269853.9470297875",
        "total_balance_btc":"15.1760448432",
        "order_freeze":"0.0000000000",
        "margin":"93326.7398201745",
        "freeze_fixed":"0.0000000000",
        "freeze_cross":"0.0000000000",
        "margin_fixed":"60.8824269189",
        "margin_cross":"93265.8573932556"
    },
    "state":0
}

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

26.查询资金费率

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

Response

{
    "result":{
        "4BTC_USDT":{
            "pair":"4BTC_USDT",
            "close":"0.0000000000",
            "fund_rate":"0.0001000000",
            "createdAt":"2020-10-14T00:00:00.000Z"
        },
        "4ETH_USDT":{
            "pair":"4ETH_USDT",
            "close":"0.0000000000",
            "fund_rate":"0.0001000000",
            "createdAt":"2020-10-14T00:00:00.000Z"
        }
    },
    "state":0
}

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

27.查询标记价格

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

Response

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

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

28.查询合约基本信息

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

Response

{
    "result":[
        {
            "id":304,
            "pair":"4BTC_USDT",
            "coin_symbol":"USDT",
            "leverage_init":"10.0000000000",
            "leverage_min":"0.0100000000",
            "leverage_max":"150.0000000000",
            "value":"0.0001000000",
            "risk_level_base":"1.0000000000",
            "risk_level_dx":"1.0000000000",
            "maker_fee":"0.0002000000",
            "taker_fee":"0.0005500000",
            "open_max_per":"100.0000000000",
            "pending_max":100,
            "hold_max":"100.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 最大持仓价值
其它字段 忽略

29.查询精度配置

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

Response

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

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

30.查询k线

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 4BTC_USDT,4ETH_USDT, ...
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 成交量
其它字段 忽略

31.查询合约市场深度

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

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

Response

{
    "result":{
        "pair":"4BTC_USDT",
        "update_time":1602669350668,
        "asks":[//卖方深度

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

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

32.订阅 Kline 增量数据

完整例子


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

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

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(3, 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')
        {// kline
            ws.send(JSON.stringify({
                event: 'addChannel',
                sub: '4BTC_USDT_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(), 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/cbu'


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


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


def get_unsub_str():
    subdata = {
        'unsub': '4BTC_USDT_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/cbu";
      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 = "4BTC_USDT_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);

      }
    }
  }
}

kline只提供最近两根数据。全量数据请通过api get 调用。

wss://npush.bibox360.com/cbu

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

Response

{
  topic: '4BTC_USDT_kline_1min',
  t: 1,
  d: [
    [
      '1639122420000',
      '47868.1',
      '47892.3',
      '47825.4',
      '47825.4',
      '10.86'
    ],
    [
      '1639122480000',
      '47825.4',
      '47830.9',
      '47728.7',
      '47775.6',
      '10.88'
    ]
  ]
}

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

33.订阅标记价格

完整例子


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

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

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(3, 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')
        {// kline
            ws.send(JSON.stringify({
                event: 'addChannel',
                sub: '4BTC_USDTTAGPRICE_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(), 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/cbu'


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


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


def get_unsub_str():
    subdata = {
        'unsub': '4BTC_USDTTAGPRICE_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/cbu";
      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 = "4BTC_USDTTAGPRICE_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://npush.bibox360.com/cbu

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

Response

{
  topic: '4BTC_USDTTAGPRICE_kline_1min',
  t: 1,
  d: [
    [
      '1639123440000',
      '47744.46219748',
      '47744.46219748',
      '47678.11820096',
      '47685.89214597',
      '30'
    ],
    [
      '1639123500000',
      '47683.92095634',
      '47707.9817466',
      '47683.25428563',
      '47705.7285557',
      '28'
    ]
  ]
}

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

34.订阅深度

完整例子


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

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

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(3, 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')
        {// kline
            ws.send(JSON.stringify({
                event: 'addChannel',
                sub: '4BTC_USDT_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(), 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/cbu'


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


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


def get_unsub_str():
    subdata = {
        'unsub': '4BTC_USDT_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/cbu";
      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 = "4BTC_USDT_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);

      }
    }
  }
}

第一次会返回全量数据,接下来会返回增量数据。注意接收到的seq应该是不断递增加1的,如果发现有跳跃的情况,需要重新订阅。

wss://npush.bibox360.com/cbu

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

Response


{
    "topic":"4BTC_USDT_depth",
    "t":0,
    "d":{
        "pair":"4BTC_USDT",
        "ut":1639124171584,
        "seq":188236,
        "asks":[
            [
                "7.904",
                "47741.6"
            ],
            [
                "0.604",
                "47741.8"
            ]
        ],
        "bids":[
            [
                "1.667",
                "47741.3"
            ],
            [
                "0.534",
                "47726.8"
            ]
        ]
    }
}

{
    "topic":"4BTC_USDT_depth",
    "t":1,
    "d":{
        "pair":"4BTC_USDT",
        "ut":1639124172771,
        "seq":188240,
        "add":{
            "asks":[
                [
                    "0.11",
                    "47744.9"
                ]
            ],
            "bids":[
                [
                    "0.809",
                    "47741.5"
                ]
            ]
        },
        "del":{
            "asks":null,
            "bids":[
                [
                    "0.522",
                    "47741.3"
                ]
            ]
        }
    }
}

名称 描述
pair 交易对
ut 时间
t 0代表全量数据,1代表增量数据
seq 序列号
add 新增的深度
del 删除的深度
mod 修改的深度
asks 卖单,第一字段是挂单数量,第二字段是深度价格
bids 买单
其它字段 忽略

35.订阅成交记录

完整例子


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

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

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(3, 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')
        {// kline
            ws.send(JSON.stringify({
                event: 'addChannel',
                sub: '4BTC_USDT_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(), 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/cbu'


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


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


def get_unsub_str():
    subdata = {
        'unsub': '4BTC_USDT_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/cbu";
      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 = "4BTC_USDT_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);

      }
    }
  }
}

第一次会返回全量数据,接下来会返回增量数据。注意t=0和t=1时数据结构的区别。

wss://npush.bibox360.com/cbu

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 4BTC_USDT, 4ETH_USDT
sub true string ${pair} + '_deals'

Response

{
    "topic":"4BTC_USDT_deals",
    "t":0,
    "d":{
        "pair":"4BTC_USDT",
        "d":[
            [
                "48008.1",
                "0.009",
                "1",
                "1639124930499",
                ""
            ],
            [
                "48006.5",
                "0.021",
                "1",
                "1639124930328",
                ""
            ]
        ]
    }
}

{
  topic: '4BTC_USDT_deals',
  t: 1,
  d: [
         "48008.1",
         "0.009",
         "1",
         "1639124930499",
         ""
     ]
}

名称 描述
pair 交易对
t 0代表全量数据,1代表增量数据
d 数组定义:成交价格,成交价值,成交方向(1-开多,2-开空),成交时间戳

36.订阅最新成交价

完整例子


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

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

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(3, 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')
        {// kline
            ws.send(JSON.stringify({
                event: 'addChannel',
                sub: '4BTC_USDT_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(), 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/cbu'


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


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


def get_unsub_str():
    subdata = {
        'unsub': '4BTC_USDT_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/cbu";
      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 = "4BTC_USDT_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://npush.bibox360.com/cbu

参数名称 是否必须 类型 描述 默认值 取值范围
pair true string 交易对 4BTC_USDT, 4ETH_USDT
sub true string ${pair} + '_ticker'

Response

{
    "topic":"4BTC_USDT_ticker",
    "t":1,
    "d":[
        "4BTC_USDT",
        "48099.9",
        "48099.90",
        "299951.30",
        "49631.3",
        "47319.1",
        "48095.1",
        "0.041",
        "48098.1",
        "2.292",
        "16781.668",
        "-2.83%",
        "1639125637999",
        "299951.30000000"
    ]
}

[ 交易对, 最新成交价, 最新成交价(cny计价), 最新成交价(usd计价), 24h最高价, 24h最低价, 最新买一价, 买一价值, 最新卖一价, 卖一价值, 24h成交价值, 24h涨跌幅, 时间戳, 最新成交价(cny计价) ]

37.订阅用户数据方法

实际例子



'use strict'

const WebSocket = require('ws');
const zlib = require('zlib');
let CryptoJS = require("crypto-js");

const biboxws = 'wss://npush.bibox360.com/cbu'; // 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/cbu'
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/cbu";
        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://npush.bibox360.com/cbu

参数名称 是否必须 类型 描述 默认值 取值范围
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 "订阅成功" 代表订阅成功
其它字段 忽略

38.订阅用户数据解析资产

第一次订阅会返回全量数据assets_all,之后会返回增量数据contract_assets。

Response

{
    "topic":"ALL_ALL_login",
    "uid":"10000",
    "t":0,
    "d":{
        "assets_all":[
            {
                "ff":"0",
                "b":"2050.8565",
                "c":"USDT",
                "t":1639123200000,
                "u":11008936,
                "v":62938352964,
                "mc":"261.3161",
                "mf":"0",
                "fc":"0"
            }
        ]
    }
}

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "contract_assets":{
            "ff":"0",
            "b":"1862.4156",
            "c":"USDT",
            "t":1639128405433,
            "u":100006,
            "v":108774606,
            "mc":"130.6414",
            "mf":"0",
            "fc":"6.0756"
        }
    }
}

名称 描述
b 可用余额
c 币种符号
u 用户id
ff 逐仓冻结资金
fc 全仓冻结资金
mf 逐仓冻结保证金
mc 全仓冻结保证金
其它字段 忽略

39.订阅用户数据解析仓位

第一次订阅会返回全量数据position_all,之后会返回增量数据contract_order。

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":0,
    "d":{
        "position_all":[
            {
                "pp":"0",
                "ps":"0",
                "pt":"-0.0886026273",
                "sd":1,
                "ui":100006,
                "md":1,
                "mg":"72.825",
                "id":"1125899906842624043",
                "sp":0,
                "ut":1639123200000,
                "cc":"0",
                "st":0,
                "f":"0.4344",
                "l":"10",
                "pa":"0",
                "pc":"0",
                "t":1638177636516,
                "fb0":"0",
                "v":108181199,
                "pf":"0",
                "lc":"0.013",
                "pi":"4BTC_USDT",
                "hc":"0.013",
                "fb":"0",
                "po":"55700.1923076923"
            }
        ]
    }
}

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "contract_order":{
            "pp":"0",
            "ps":"0",
            "pt":"-0.0886026273",
            "sd":1,
            "ui":100006,
            "md":1,
            "mg":"72.825",
            "id":"1125899906842624043",
            "sp":0,
            "ut":1639128405433,
            "cc":"0",
            "st":0,
            "f":"0.4344",
            "l":"10",
            "pa":"0",
            "pc":"0",
            "t":1638177636516,
            "fb0":"0",
            "v":108774604,
            "pf":"0",
            "lc":"0.013",
            "pi":"4BTC_USDT",
            "hc":"0.013",
            "fb":"0",
            "po":"55700.1923076923"
        }
    }
}

名称 描述
l 杠杆
sd 仓位方向: 1, 多仓 2 , 空仓
pa 告警价格
ui 用户id
pf 爆仓价格
md 仓位模式: 1全仓, 2逐仓
lc 可平仓位价值
pi 交易对
mg 保证金
hc 仓位价值 = 合约张数X合约面值
po 开仓价格
pp 止盈委托数量
ps 止损委托数量
其它字段 忽略

40.订阅用户数据解析挂单

第一次订阅会返回全量数据order_all,之后会返回增量数据contract_pending。

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":0,
    "d":{
        "order_all":[
            {
                "tt":0,
                "tw":"0",
                "pw":"0",
                "dp":"0",
                "tif":0,
                "sd":2,
                "bt":0,
                "ui":100006,
                "fz":"6.0756",
                "of":6,
                "oi":"17592186044417",
                "ot":2,
                "f":"0",
                "eq":"0",
                "p":"60000",
                "q":"0.001",
                "tpl":"0",
                "r":0,
                "s":1,
                "t":1639128405433,
                "pd":"0",
                "fb0":"0",
                "tl":"0",
                "pi":"4BTC_USDT",
                "tpw":"0",
                "coi":"1639128409489",
                "fb":"0",
                "pl":"0",
                "po":false
            }
        ]
    }
}

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "contract_pending":{
            "tt":0,
            "tw":"0",
            "pw":"0",
            "dp":"0",
            "tif":0,
            "sd":2,
            "bt":0,
            "ui":100006,
            "fz":"6.0756",
            "of":6,
            "oi":"17592186044417",
            "ot":2,
            "f":"0",
            "eq":"0",
            "p":"60000",
            "q":"0.001",
            "tpl":"0",
            "r":0,
            "s":1,
            "t":1639128405433,
            "pd":"0",
            "fb0":"0",
            "tl":"0",
            "pi":"4BTC_USDT",
            "tpw":"0",
            "coi":"1639128409489",
            "fb":"0",
            "pl":"0",
            "po":false
        }
    }
}

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

41.订阅用户数据解析成交明细

contract_detail

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
        "contract_detail":{
            "oi":"17592186044418",
            "ui":"100006",
            "id":"1125899906846520658",
            "coi":"1639128805027",
            "pi":"4BTC_USDT",
            "sd":1,
            "s":3,
            "ot":1,
            "of":6,
            "q":"0.001",
            "p":"48173.6",
            "dp":"48082.7",
            "ep":"0.001",
            "f":"0.02884962",
            "fb":"0",
            "fb0":"0",
            "im":0,
            "t":1639128800022
        }
    }
}

名称 描述
oi 订单id
ui 用户id
id 明细id
coi 用户自定义订单id
pi 交易对
sd 下单方向
of 订单来源
p 下单价格
dp 成交价格
ep 成交数量
f 手续费
fb0 优惠券抵扣
fb bix抵扣
im 是否是maker
t 下单时间
其它字段 忽略

42.订阅用户数据解析持仓被动变化信息

contract_deal_log

Response

[
    {
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
            "contract_deal_log":{
                "id":"1125899906842654296",// 变化id
                "user_id":100006,//用户id
                "type":5,//变化类型,1开仓,2平仓,3减仓降低风险等级, 4爆仓清空仓位, 5ADL
                "mode":2,//仓位模式 1全仓,2逐仓
                "pair":"4BTC_USDT",//交易对
                "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 变化时间
其它字段 忽略

43.订阅用户数据解析止盈止损委托信息

base_u_plan_order_v3

Response

[
    {
        "topic":"ALL_ALL_login",
        "uid":"100006",
        "t":1,
        "d":{
            "base_u_plan_order_v3":{
                "tt":1,
                "pr":"49900",
                "pt":1,
                "pid":"0",
                "q":"0.001",
                "sd":2,
                "r":0,
                "bt":1,
                "s":1,
                "t":1638157434782,
                "ui":100006,
                "si":"0",
                "pi":"4BTC_USDT",
                "oi":"5226915",
                "bid":"0",
                "tp":"49900",
                "otd":"0"
            }
        }
    }
]

名称 描述
oi 委托ID号
pi 合约符号
pr 委托价
tp 触发价
q 委托数量
sd 多仓或空仓:1多仓、2空仓
pt 止盈或止损:1止盈、2止损
bt 市价或限价:1市价止盈止损,2限价止盈止损
s 委托状态:1未触发、2触发结束、3取消结束、4触发挂单失败、5对应的止盈(或止损)委托已经触发,当前委托自动取消
其它字段 忽略

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