English
javascript python csharp

Base-USDT contract

List of alternate API domains

https://api.bibox.tel/v1/public/queryApiDomain

SDK and Demo

console.log('Base-USDT contract javascript Demo');

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


if __name__ == '__main__':
    print('Base-USDT contract python Demo')

Console.WriteLine("Base-USDT contract c# Demo");

Bibox provides contract SDKs for developers in multiple languages.

These SDKs are developed based on the Bibox contract API and automatically complete the following functions:

It's more convenient to use SDK to develop programs to access Bibox than to use API.

If you need to download or read more information, please click the following link:

1.Signature interface request method

Example

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

let timestamp = Date.now(); // 1.Current timestamp

let param = { // 2.Requested parameters
    "amount":"0.01",
    "symbol":"USDT",
    "type":0
};

let strParam = JSON.stringify(param); // 2.Formatting parameters

let strToSign = '' + timestamp + strParam; // 3.This is the string that needs to be signed

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let sign = CryptoJS.HmacMD5(strToSign, secret).toString();//4.Signed result

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

request.post({
        url: url,//Request path
        method: "POST",//Request method
        headers: {//5.Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: strParam // 6.Formatting parameters
    },

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

    });

# -*- 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);
          }
        }

    }
}

Field name Field type Field description Field value
content-type string 'application/json'
bibox-api-key string your apikey
bibox-timestamp long Current timestamp,expressed in milliseconds timestamp
bibox-api-sign string Signature result sign

2.Fund transfer

Request

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

let timestamp = Date.now(); // 1.Current timestamp

let param = { // 2.Requested parameters
    "amount":"0.01",
    "symbol":"USDT",
    "type":0
};

let strParam = JSON.stringify(param); // 2.Formatting parameters

let strToSign = '' + timestamp + strParam; // 3.This is the string that needs to be signed

let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //你的 apikey 密码
let sign = CryptoJS.HmacMD5(strToSign, secret).toString();//4.Signed result

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

request.post({
        url: url,//Request path
        method: "POST",//Request method
        headers: {//5.Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: strParam // 6.Formatting parameters
    },

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

    });

# -*- 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

Name Necessary or not Type Description Default Value Range
amount true string Number to string
symbol true string coin symbol USDT
type true integer 0 transfer in, 1 transfer out 0,1

Response

{
    "state":0, // success
    "result":"352559634189422592"  // ignore
}

Name Description
state 0 means success, otherwise means failure
Other fields ignore

3.Place order

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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);
          }
        }

    }
}

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

Name Necessary or not Type Description Default Value Range
pair true string Contract symbol 4BTC_USDT,4ETH_USDT, ...
amount true string Number to string (Must be a multiple of the contract unit)
order_side true integer Order side, 1 open long, 2 open short, 3 close long, 4 close short 1,2,3,4
order_type true integer Order type, 1 market order, 2 limit order 1,2
price true string Order price
order_from true integer Order source 6
client_oid false string client order id

If you are opening postions order and want to set a stop profit stop loss after the transaction, you can add the following parameters.

Name Necessary or not Type Description Default Value Range
plan_type true integer market order or limit order 1 market order,2 limit order
profit_price true string Stop-profit trigger price (The stop-profit trigger price must be greater than the order price if the limit price is extended. When the limit is short, the stop-profit trigger price should be less than the order price. The stop-profit trigger price must be higher than the latest price when the market is open. The stop-profit trigger price should be lower than the latest price when the market is open short.)
loss_price true string Stop-loss trigger price (when the limit is wide, the stop-loss trigger price must be less than the order price. When limit open short, stop loss trigger price should be greater than the order price. The stop-loss trigger price must be lower than the latest price when the market is open. The stop-loss trigger price should be higher than the latest price when the market is short.)
exec_profit_price false string Stop-profit mandate price (must be set if plan_type=2)
exec_loss_price false string Stop-profit mandate price (must be set if plan_type=2)

Response

{
    "state":0,
    "order_id":"425510999949316", // order id
    "client_oid":"1234567890", // client order id
    "status":1, // Order status 1 waiting to be traded, 2 partly traded, 3 fully traded, 4 partly cancelled, 5 fully cancelled, 100 order failed
    "cmd":"open" // ignore
}

Name Description
state 0 means success, otherwise means failure
order_id order id
client_oid client order id
status Order status 1 waiting to be traded, 2 partly traded, 3 fully traded, 4 partly cancelled, 5 fully cancelled, 100 order failed
Other fields ignore

4.Cancel order

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
order_id true string order id

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

5.Batch cancellation

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
order_ids true Array Order id array

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

6.Cancel all orders

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair true string Contract symbol 4BTC_USDT,4ETH_USDT, ...

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

7.Place Stop-profit Stop-loss Order

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,//Request path
        method: "POST",//
        headers: {//
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//
    },

    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);
          }
        }

    }
}

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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 4BTC_USDT,4ETH_USDT, ...
price true string book price
trigger_price true string trigger price
amount true string amount
side true int position side 1Long、2Short
plan_type true int Stop-profit or Stop-loss 1Stop-profit、2Stop-loss
book_type true int market order or limit order 1market order,2limit order

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

8.list Stop-profit Stop-loss Order

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,//Request path
        method: "POST",//
        headers: {//
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//
    },

    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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 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"
}

Name Description
state 0 means success, otherwise means failure
oi order id
pi Contract symbol
pr book price
tp trigger price
q book quantity
sd Position side:1Long、2Short
pt Stop-profit or Stop-loss:1Stop-profit、2Stop-loss
bt market order or limit order:1market order,2limit order
s order status:1wait trigger、2triggered、3canceled、4triggered failed、5canceled
Other fields ignore

9.Cancel Stop-profit Stop-loss Order

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,//Request path
        method: "POST",//
        headers: {//
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//
    },

    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);
          }
        }

    }
}

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

Name Necessary or not Type Description Default Value Range
order_id true string order id

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

10.Cancel all Stop-profit Stop-loss Order

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,//Request path
        method: "POST",//
        headers: {//
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//
    },

    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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 4BTC_USDT,4ETH_USDT, ...

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

11.Adjust margin on a fixed position

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair true string Contract symbol 4BTC_USDT,4ETH_USDT, ...
margin true string margin
side true integer Position side, 1 long position, 2 short position 1,2

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

12.Adjust position mode and leverage

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair true string Contract symbol 4BTC_USDT,4ETH_USDT, ...
mode true integer Position mode, 1 cross, 2 fixed 1,2
leverage_long true integer Long leverage 1~100
leverage_short true integer Short leverage 1~100

Response

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

Name Description
state 0 means success, otherwise means failure
Other fields ignore

13.Query assets

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
coin false string coin symbol 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"
}

Name Description
state 0 means success, otherwise means failure
b Available Balance
c coin symbol
u user id
ff Fixed Position Frozen funds
fc Cross Position Frozen funds
mf Fixed Position margin
mc Cross Position margin
Other fields ignore

14.Query position

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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);
          }
        }

    }
}

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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 4BTC_USDT,4ETH_USDT, ...
side false integer Position side, 1 long position, 2 short position 1,2

Response

{
    "state":0,
    "result":[
        {
            "pt":"0",//ignore
            "f":"0",//ignore
            "l":"10", // leverage
            "sd":1, // Position side, 1 Long, 2 Short
            "pa":"0", //Alert price
            "ui":100006,//user id
            "fb0":"0",//ignore
            "pf":"0",//Liquidation price
            "md":2,//Position mode, 1 Cross, 2 Fixed
            "lc":"0",// Can liquidate position value
            "pi":"4BTC_USDT", // pair
            "mg":"0", //margin
            "hc":"0",// Position value = Contract number multiplied by contract value
            "fb":"0",//ignore
            "po":"0", //Open price
            "pp":"0",
            "ps":"0",
        },
        ...
    ],
    "cmd":"position"
}

Name Description
state 0 means success, otherwise means failure
l leverage
sd Position side, 1 Long, 2 Short
pa Alert price
ui user id
pf Liquidation price
md Position mode, 1 Cross, 2 Fixed
lc Can liquidate position value
pi pair
mg margin
hc Position value = Contract number multiplied by contract value
po Open price
pp Stop-profit quantity
ps Stop-loss quantity
Other fields ignore

15.Query order list

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 4BTC_USDT,4ETH_USDT, ...
order_side true integer Order side, 1 open long, 2 open short, 3 close long, 4 close short 1,2,3,4

Response

{
    "state":0,
    "result":{
        "p":1,
        "t":1,
        "o":[
            {
                "f":"0", //fee
                "dp":"0", //Deal price
                "eq":"0", //Deal amount
                "p":"11092", //Order price
                "tif":0, // ignore
                "q":"1", //Order quantity
                "sd":1, //Order side
                "r":0, //reason
                "s":1, // status
                "t":1602679944815, //time
                "ui":100006, //user id
                "fz":"0.0000091417", //Frozen funds
                "fb0":"0", //Coupon deduction
                "of":4, //order from
                "pi":"4BTC_USDT", //pair
                "oi":"426610511577093", // order id
                "coi":"1602679943911", //clientoid
                "fb":"0", //BIX deduction
                "po":false //ignore
            },
            ...
        ]
    },
    "cmd":"orderList"
}

Name Description
state 0 means success, otherwise means failure
f fee
dp Deal price
eq Deal amount
p Order price
q Order quantity
sd Order side
r Reason for failure
s Order status
t time
ui user id
fz Frozen funds
fb0 Coupon deduction
of Order source
pi pair
oi order id
coi Client order id
fb BIX deduction
bt Stop-profit and stop-loss orders: 1 market price, 2 limit price, Otherwise no stop-profit and stop-loss is set.
tw Stop earnings trigger price
tl Stop loss trigger price
pw Stop-profit order price (ignored if bt =1)
pl Stop loss order price (ignored if bt =1)
Other fields ignore

16.Query order

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
order_id true string order id

Response

{
    "state":0,
    "result":{
        "f":"0", //fee
        "dp":"0", //Deal price
        "eq":"0", //Deal amount
        "p":"11092", //Order price
        "tif":0, // ignore
        "q":"1", //Order quantity
        "sd":1, //Order side
        "r":0, //reason
        "s":1, // status
        "t":1602679944815, //time
        "ui":100006, //user id
        "fz":"0.0000091417", //Frozen funds
        "fb0":"0", //Coupon deduction
        "of":4, //order from
        "pi":"4BTC_USDT", //pair
        "oi":"426610511577093", // order id
        "coi":"1602679943911", //clientoid
        "fb":"0", //BIX deduction
        "po":false //ignore
    },
    "cmd":"orderDetail"
}

Name Description
state 0 means success, otherwise means failure
f fee
dp Deal price
eq Deal amount
p Order price
q Order quantity
sd Order side
r Reason for failure
s Order status
t time
ui user id
fz Frozen funds
fb0 Coupon deduction
of Order source
pi pair
oi order id
coi Client order id
fb BIX deduction
bt Stop-profit and stop-loss orders: 1 market price, 2 limit price, Otherwise no stop-profit and stop-loss is set.
tw Stop earnings trigger price
tl Stop loss trigger price
pw Stop-profit order price (ignored if bt =1)
pl Stop loss order price (ignored if bt =1)
Other fields ignore

17. Batch query order

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
order_ids true Array Order id array

Response

{
    "state":0,
    "result":[
        {
             "f":"0", //fee
            "dp":"0", //Deal price
            "eq":"0", //Deal amount
            "p":"11092", //Order price
            "tif":0, // ignore
            "q":"1", //Order quantity
            "sd":1, //Order side
            "r":0, //reason
            "s":1, // status
            "t":1602679944815, //time
            "ui":100006, //user id
            "fz":"0.0000091417", //Frozen funds
            "fb0":"0", //Coupon deduction
            "of":4, //order from
            "pi":"4BTC_USDT", //pair
            "oi":"426610511577093", // order id
            "coi":"1602679943911", //clientoid
            "fb":"0", //BIX deduction
            "po":false //ignore
        }
    ],
    "cmd":"orderListBatch"
}

Name Description
state 0 means success, otherwise means failure
f fee
dp Deal price
eq Deal amount
p Order price
q Order quantity
sd Order side
r Reason for failure
s Order status
t time
ui user id
fz Frozen funds
fb0 Coupon deduction
of Order source
pi pair
oi order id
coi Client order id
fb BIX deduction
bt Stop-profit and stop-loss orders: 1 market price, 2 limit price, Otherwise no stop-profit and stop-loss is set.
tw Stop earnings trigger price
tl Stop loss trigger price
pw Stop-profit order price (ignored if bt =1)
pl Stop loss order price (ignored if bt =1)
Other fields ignore

18.Query order list based on 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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
order_ids true Array Array of client order id

Response

{
    "state":0,
    "result":[
        {
             "f":"0", //fee
            "dp":"0", //Deal price
            "eq":"0", //Deal amount
            "p":"11092", //Order price
            "tif":0, // ignore
            "q":"1", //Order quantity
            "sd":1, //Order side
            "r":0, //reason
            "s":1, // status
            "t":1602679944815, //time
            "ui":100006, //user id
            "fz":"0.0000091417", //Frozen funds
            "fb0":"0", //Coupon deduction
            "of":4, //order from
            "pi":"4BTC_USDT", //pair
            "oi":"426610511577093", // order id
            "coi":"1602679943911", //clientoid
            "fb":"0", //BIX deduction
            "po":false //ignore
        }
    ],
    "cmd":"orderListBatchByCLientOid"
}

Name Description
state 0 means success, otherwise means failure
f fee
dp Deal price
eq Deal amount
p Order price
q Order quantity
sd Order side
r Reason for failure
s Order status
t time
ui user id
fz Frozen funds
fb0 Coupon deduction
of Order source
pi pair
oi order id
coi Client order id
fb BIX deduction
bt Stop-profit and stop-loss orders: 1 market price, 2 limit price, Otherwise no stop-profit and stop-loss is set.
tw Stop earnings trigger price
tl Stop loss trigger price
pw Stop-profit order price (ignored if bt =1)
pl Stop loss order price (ignored if bt =1)
Other fields ignore

19.Get server time

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

Response

{
    "time":"1602680518605"
}

Name Description
time server time

20.Qeury position holding changed records

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair true string Contract symbol 4BTC_USDT,4ETH_USDT, ...
page true integer page number 1,2, ...
size true integer return size 10,20, ...

Response

{
    "result":{
        "count":3,
        "page":1,
        "items":[
            {
                "id":"1125899906842635654", // record id
                "user_id":100006, // user id
                "coin_symbol":"USDT",// coin symbol
                "pair":"4BTC_USDT",// pair
                "side":1,// Position side, 1 Long, 2 Short
                "model":1,// Position model, 1Cross, 2Fixed
                "log_type":1,// Record type, 1 open position, 2 close position, 3 lighten position to reduce risk level, 4 liquidate position, 5ADL
                "hold_coin_dx":"1.0000000000",// Change in position
                "hold_coin":"1.0000000000",// Position holding
                "price_log":"11692.0000000000",// proposed price
                "price_open":"11692.0000000000",// Average open price
                "profit":"0.0000000000",// profit
                "fee":"0.0000000599",// fee
                "fee_bix":"0.0000000000",// BIX deduction
                "fee_bix0":"0.0000000000", // Coupon deduction
                "createdAt":"2020-10-14T03:00:08.000Z",// time
                "updatedAt":"2020-10-14T03:00:08.000Z"
            },
            ...
        ]
    },
    "state":0
}

Name Description
state 0 means success, otherwise means failure
id record id
user_id user id
coin_symbol coin symbol
pair pair
side Position side, 1 Long, 2 Short
model Position model, 1Cross, 2Fixed
log_type Record type, 1 open position, 2 close position, 3 lighten position to reduce risk level, 4 liquidate position, 5ADL
hold_coin_dx Change in position
hold_coin Position holding
price_log proposed price
price_open Average open price
profit profit
fee fee
fee_bix BIX deduction
fee_bix0 Coupon deduction
createdAt time
Other fields ignore

21.Query order deals detail

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
orderId true long order id
page true integer page number 1,2, ...
size true integer return size 10,20, ...

Response

{
    "result":{
        "count":1,
        "page":1,
        "items":[
            {
                "id":"1125899906842635651",// record id
                "coin_symbol":"USDT",// coin symbol
                "pair":"4BTC_USDT",// pair
                "side":2,// Pending order side, 1 open long, 2 open short, 3 close long, 4 close short
                "order_from":4,// Order source
                "price":"10692.0000000000",// Pending order price
                "deal_price":"11510.0000000000",// Deal price
                "deal_coin":"1.0000000000",// Deal amount
                "fee":"0.0000000608",// fee
                "fee_bix":"0.0000000000",// BIX deduction
                "fee_bix0":"0.0000000000",// Coupon deduction
                "is_maker":0,// is maker
                "createdAt":"2020-10-14T02:58:59.000Z"// time
            }
        ]
    }
    "state":0
}

Name Description
state 0 means success, otherwise means failure
id record id
coin_symbol coin symbol
pair pair
side Pending order side, 1 open long, 2 open short, 3 close long, 4 close short
order_from Order source
price Pending order price
deal_price Deal price
deal_coin Deal amount
fee fee
fee_bix BIX deduction
fee_bix0 Coupon deduction
createdAt time
is_maker is maker
Other fields ignore

22.Query historical orders

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
pair false string Contract symbol 4BTC_USDT,4ETH_USDT, ...
page true integer page number 1,2, ...
size true integer return size 10,20, ...
side false integer Order side, 1 open long 2 open short 3 close long 4 close short
status false Array Order status, 1 uncompleted, 2 partially completed, 3 completely completed, 4 partially cancelled, 5 completely cancelled, 100 failed to place an order

Response

{
    "result":{
        "count":1,
        "page":1,
        "items":[
            {
                "id":421112953438215,// order id
                "user_id":100006,// user id
                "coin_symbol":"USDT",// coin symbol
                "pair":"4BTC_USDT",// pair
                "side":1,// Order side, 1 open long 2 open short 3 close long 4 close short
                "order_type":2,// Order type, 1 market price, 2 limit price
                "price":"11692.0000000000",// Pending order price
                "amount_coin":"1.0000000000",// Order quantity
                "freeze":"0.0000000000",// Frozen funds
                "price_deal":"11692.0000000000",// Average deal price
                "deal_coin":"1.0000000000",// Deal amount
                "deal_num":1,// Deal number
                "fee":"0.0000000599",// fee
                "fee_bix":"0.0000000000",// BIX deduction
                "fee_bix0":"0.0000000000",// Coupon deduction
                "status":3,// Order status, 1 uncompleted, 2 partially completed, 3 completely completed, 4 partially cancelled, 5 completely cancelled, 100 failed to place an order
                "reason":0,// Reason for failure
                "fee_rate_maker":"0.0007000000",// maker fee rate
                "fee_rate_taker":"0.0007000000",// taker fee rate
                "client_oid":1602644402806,// client order id
                "order_from":4, // ignore
                "createdAt":"2020-10-14T03:00:08.000Z",// created time
                "updatedAt":"2020-10-14T03:00:08.000Z"// updated time
            }
        ]
    },
    "state":0
}

Name Description
state 0 means success, otherwise means failure
id order id
user_id user id
coin_symbol coin symbol
pair pair
side Pending order side, 1 open long, 2 open short, 3 close long, 4 close short
order_type Order type, 1 market price, 2 limit price
price Pending order price
amount_coin Order quantity
freeze Frozen funds
price_deal Average deal price
deal_coin Deal amount
deal_num Deal number
fee fee
fee_bix BIX deduction
fee_bix0 Coupon deduction
status Order status, 1 uncompleted, 2 partially completed, 3 completely completed, 4 partially cancelled, 5 completely cancelled, 100 failed to place an order
reason Reason for failure
fee_rate_maker maker fee rate
fee_rate_taker taker fee rate
client_oid client order id
order_from Order source
createdAt created time
Other fields ignore

23.Query order

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,//Request path
        method: "POST",//Request method
        headers: {//Set request headers
            'content-type': 'application/json',
            'bibox-api-key': apikey,
            'bibox-api-sign': sign,
            'bibox-timestamp': timestamp
        },
        body: cmd//parameter string
    },

    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

Name Necessary or not Type Description Default Value Range
orderIds true Array Order id array
clientOids true Array Array of client order id

Response

{
    "result":[
        {
            "id":421112953438214,// order id
            "user_id":100006,// user id
            "coin_symbol":"USDT",// coin symbol
            "pair":"4BTC_USDT",// pair
            "side":1,// Order side, 1 open long 2 open short 3 close long 4 close short
            "order_type":2,// Order type, 1 market price, 2 limit price
            "price":"11692.0000000000",// Pending order price
            "amount_coin":"1.0000000000",// Order quantity
            "freeze":"0.0000000000",// Frozen funds
            "price_deal":"11692.0000000000",// Average deal price
            "deal_coin":"1.0000000000",// Deal amount
            "deal_num":1,// Deal number
            "fee":"0.0000000599",// fee
            "fee_bix":"0.0000000000",// BIX deduction
            "fee_bix0":"0.0000000000",// Coupon deduction
            "status":3,// Order status, 1 uncompleted, 2 partially completed, 3 completely completed, 4 partially cancelled, 5 completely cancelled, 100 failed to place an order
            "reason":0,// Reason for failure
            "fee_rate_maker":"0.0007000000",// maker fee rate
            "fee_rate_taker":"0.0007000000",// taker fee rate
            "client_oid":1602644402806,// client order id
            "order_from":4, // ignore
            "createdAt":"2020-10-14T03:00:08.000Z",// created time
            "updatedAt":"2020-10-14T03:00:08.000Z"// updated time
        },
        ...
    ],
    "state":0
}

Name Description
state 0 means success, otherwise means failure
id order id
user_id user id
coin_symbol coin symbol
pair pair
side Pending order side, 1 open long, 2 open short, 3 close long, 4 close short
order_type Order type, 1 market price, 2 limit price
price Pending order price
amount_coin Order quantity
freeze Frozen funds
price_deal Average deal price
deal_coin Deal amount
deal_num Deal number
fee fee
fee_bix BIX deduction
fee_bix0 Coupon deduction
status Order status, 1 uncompleted, 2 partially completed, 3 completely completed, 4 partially cancelled, 5 completely cancelled, 100 failed to place an order
reason Reason for failure
fee_rate_maker maker fee rate
fee_rate_taker taker fee rate
client_oid client order id
order_from Order source
createdAt created time
Other fields ignore

24.Qeury fund fee rate

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
}

Name Description
state 0 means success, otherwise means failure
pair pair
fund_rate fund fee rate
Other fields ignore

25.Qeury tag price

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

Response

{
    "result":{
        "4BTC_USDT":{//pair
            "close":"11453.7224909000",// Index price
            "priceTag":"11454.2951770245",// Tag price
            "createdAt":"2020-10-14T03:41:08.000Z" // time
        },
        "4ETH_USDT":{
            "close":"383.1999999600",
            "priceTag":"383.2191599600",
            "createdAt":"2020-10-14T03:41:08.000Z"
        }
    },
    "state":0
}

Name Description
state 0 means success, otherwise means failure
result The keyword is pair
close Index price
priceTag Tag price
createdAt time
Other fields ignore

26.Query basic contract information

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
}

Name Description
state 0 means success, otherwise means failure
pair pair
leverage_min Minimum leverage
leverage_max Maximum leverage
value contract value
maker_fee default maker fee rate
taker_fee default taker fee rate
open_max_per Maximum number of single pending orders
pending_max Maximum number of pending orders
hold_max Maximum position value
Other fields ignore

27.Query accuracy configuration

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

Response

{
    "result":[
        {
            "pair":"4BTC_USDT",//pair
            "price_unit":1,//Decimal points for order
            "vol_unit":6, // ignore
            "value_unit":0 // ignore
        },
        ...
    ],
    "state":0
}

Name Description
state 0 means success, otherwise means failure
pair pair
price_unit Decimal points for order
Other fields ignore

28.Query Kline

Name Necessary or not Type Description Default Value Range
pair true string pair 4BTC_USDT, 4ETH_USDT, ...
period true string k-line period '1min', '3min', '5min', '15min', '30min', '1hour', '2hour', '4hour', '6hour', '12hour', 'day', 'week'
size false integer size 1000 1-1000

Response

{
    "result":[
        {
            "time":1602680580000,// Timestamp
            "open":"10666.00000000",// Opening price
            "high":"10666.00000000",// Highest price
            "low":"10666.00000000", // Lowest price
            "close":"10666.00000000",// Closing price
            "vol":"0.00000000"// Volume
        },
        ...
    ],
    "cmd":"kline",
    "ver":"2.0"
}

Name Description
result Value means success, otherwise means failure
time Timestamp
open Opening price
high Highest price
low Lowest price
close Closing price
vol Volume
Other fields ignore

29.Query market depth

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

Name Necessary or not Type Description Default Value Range
pair true string pair 4BTC_USDT, 4ETH_USDT, ...
size false integer size 200 1-200

Response

{
    "result":{
        "pair":"4BTC_USDT",
        "update_time":1602669350668,
        "asks":[//Seller Depth of Market

        ],
        "bids":[//Buyer market depth
            {
                "volume":"54054",//Order quantity
                "price":"10666"//Pending order price
            },
            ...
        ]
    },
    "cmd":"depth",
    "ver":"2.0"
}

Name Description
result Value means success, otherwise means failure
pair pair
update_time time
asks Seller Depth of Market
bids Buyer market depth
volume Order quantity
price Pending order price
Other fields ignore

30.Subscription to Kline

Example


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);

      }
    }
  }
}

wss://npush.bibox360.com/cbu

Name Necessary or not Type Description Default Value Range
pair true string pair 4BTC_USDT, 4ETH_USDT
period true string k-line period 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-line start time, Deal number, Opening price, Highest price, Lowest price, Closing price, Volume(Contract value) ]

31.Subscription to Tag price

Example


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

Name Necessary or not Type Description Default Value Range
pair true string pair 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-line start time, Deal number, Opening price, Highest price, Lowest price, Latest price, Volume(ignore) ]

32.Subscription to Market depth

Example


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);

      }
    }
  }
}

wss://npush.bibox360.com/cbu

Name Necessary or not Type Description Default Value Range
pair true string pair 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"
                ]
            ]
        }
    }
}

Name Description
pair pair
update_time time
seq pair
add add data
del delete data
mod modify data
asks ask data
bids bid data
volume Order quantity
price price
Other fields ignore

33.Subscription to deals detail

Example


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);

      }
    }
  }
}

wss://npush.bibox360.com/cbu

Name Necessary or not Type Description Default Value Range
pair true string pair 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",
         ""
     ]
}

[ Deal price, Deal amount, trade side(1 buy, 2 sell), Timestamp ]

34.Subscription to ticker

Example


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

Name Necessary or not Type Description Default Value Range
pair true string pair 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"
    ]
}

[ pair, last price, last cny price, last usd price, 24hHighest price, 24hLowest price, Latest bid price, Latest bid amount, Latest ask price, Latest ask amount, 24hDeal amount, 24h Quote change, Timestamp, Latest cny price ]

35.Subscription to user data

Example


'use strict'

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

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

let ws;

let apikey = '900625568558820892a8c833c33ebc8fd2701efe'; // your apikey
let secret = 'c708ac3e70d115ec29efbee197330627d7edf842'; // apikey的密码

let subparam = JSON.stringify({ // .Format the parameter object, get subparam
    apikey,
    sub: 'ALL_ALL_login'
});
let sign = CryptoJS.HmacMD5(subparam, String(secret)).toString(); // Use apikey's secret to sign subparam with HmacMD5, and get the signature result sign
let form = { // 2.Request parameter
    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

Name Necessary or not Type Description Default Value Range
apikey true string your apikey
sign true string sign
sub true string 'ALL_ALL_login'

1.Define the parameter object param, need to use apikey

let apikey = 'this is your apikey';

let param = { "apikey": apikey, "sub": "ALL_ALL_login" };

2.Format the parameter object param, get strParam

let strParam = JSON.stringify(param);

3.Use apikey's secret to sign strParam with HmacMD5, and get the signature result sign

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

let secret = 'this is your apikey secret';

let sign = CryptoJS.HmacMD5(strParam, secret).toString();

4.Generate subscription parameters wsparam

let wsparam = { "apikey": apikey, "sign": sign, "sub": "ALL_ALL_login", };

Response

{
    "topic":"ALL_ALL_login",
    "uid":"1000000",
    "t":0,
    "d":{
        "result":"订阅成功"
    }
}

Name Description
result "订阅成功" means subscription success
Other fields ignore

36.Get assets from subscribed user data

contract_assets or assets_all

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"
        }
    }
}

Name Description
b Available Balance
c coin symbol
u user id
ff Fixed Position Frozen funds
fc Cross Position Frozen funds
mf Fixed Position margin
mc Cross Position margin
Other fields ignore

37.Get position from subscribed user data

contract_order or position_all

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"
        }
    }
}


Name Description
l leverage
sd Position side, 1 Long, 2 Short
pa Alert price
ui user id
pf Liquidation price
md Position mode, 1 Cross, 2 Fixed
lc Can liquidate position value
pi pair
mg margin
hc Position value = Contract number multiplied by contract value
po Open price
pp Stop-profit quantity
ps Stop-loss quantity
Other fields ignore

38.Get order from subscribed user data

contract_pending or order_all

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
        }
    }
}

Name Description
f fee
dp Deal price
eq Deal amount
p Order price
q Order quantity
sd Order side
r Reason for failure
s Order status
t time
ui user id
fz Frozen funds
fb0 Coupon deduction
of Order source
pi pair
oi order id
coi Client order id
fb BIX deduction
Other fields ignore

39.Get deals detail from subscribed user data

contract_detail

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
            "contract_detail":{
                "oi":"432108069715999",//Order id
                "ui":"100006",//user id
                "id":"1125899906842648855",//deals detail id
                "coi":"1602750117684",//client order id
                "pi":"4BTC_USDT",//pair
                "sd":1,//
                "s":3,//
                "ot":2,
                "of":4,// Order source
                "q":"1",
                "p":"11692",//Pending order price
                "dp":"10655",//Deal price
                "ep":"1",
                "f":"0.0000000657",//fee
                "fb":"0",//BIX deduction
                "fb0":"0",//Coupon deduction
                "im":0,//is maker
                "t":1602750121093, //time
            }
        }
}


Name Description
oi order id
ui user id
id record id
coi Client order id
pi pair
sd Order side
of Order source
p Order price
dp Deal price
f fee
fb0 Coupon deduction
fb BIX deduction
im is maker
t time
Other fields ignore

40.Get passive changes in positions from subscribed user data

contract_deal_log

Response

{
    "topic":"ALL_ALL_login",
    "uid":"100006",
    "t":1,
    "d":{
            "contract_deal_log":{
                "id":"1125899906842654296",// record id
                "user_id":100006,//user id
                "type":5,//Change type, 1 open position, 2 close position, 3 lighten position to reduce risk level, 4 liquidate position, 5ADL
                "mode":2,//Position model, 1Cross, 2Fixed
                "pair":"4BTC_USDT",//pair
                "price":"11247.6",//proposed price
                "hold_dx":"1",//Change in position
                "order_side":2,// Position side, 1Long, 2Short
                "time":1602755131000, //time
            }
        }
    }


Name Description
id record id
user_id user id
type Change type, 1 open position, 2 close position, 3 lighten position to reduce risk level, 4 liquidate position, 5ADL
mode Position model, 1Cross, 2Fixed
pair pair
price proposed price
hold_dx Change in position
order_side Position side, 1Long, 2Short
time time
Other fields ignore

41.Get Stop-profit Stop-loss Order from subscribed user data

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"
            }
        }
    }


Name Description
oi order id
pi Contract symbol
pr book price
tp trigger price
q book quantity
sd Position side:1Long、2Short
pt Stop-profit or Stop-loss:1Stop-profit、2Stop-loss
bt market order or limit order:1market order,2limit order
s order status:1wait trigger、2triggered、3canceled、4triggered failed、5canceled
Other fields ignore

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