Base-coin contract
List of alternate API domains
https://api.bibox.tel/v1/public/queryApiDomain
SDK and Demo
console.log('Base-coin contract javascript Demo');
# -*- coding:utf-8 -*-
if __name__ == '__main__':
print_hi('Base-coin contract python Demo')
Console.WriteLine("Base-coin 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:
- Data signature
- Data merge, for example: automatically merge depth
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":"BTC",
"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/assets/transfer/cbc";
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' #
def do_sign(body):
timestamp = int(time.time()) * 1000
# to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
to_sign = str(timestamp) + json.dumps(body)
sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
print(to_sign)
headers = {
'bibox-api-key': API_KEY,
'bibox-api-sign': sign,
'bibox-timestamp': str(timestamp)
}
return headers
def transfer(inout, amount):
path = '/v3/assets/transfer/cbc'
body = {
'symbol': 'BTC',
'type': inout,
'amount': amount,
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
transfer(0, 1) # transfer in contract
transfer(1, 1) # transfer out contract
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/assets/transfer/cbc";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
symbol = "BTC",
type = 0,
amount = "0.001",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
1.Get current timestamp
2.Understand the parameter param required by the interface request, and format the parameter to get strParam
3.Generate the string strToSign that needs to be signed
4.Use apikey's secret to sign the string strToSign that needs to be signed with HmacMD5
5.When requesting, set the following fields of http headers
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 |
6.When requesting, set http body as the formatted request parameter strParam
7.The return value contains the field state, 0 means success, and other error codes, means failure. Successful results will have a corresponding field result, and failed results will have a corresponding field msg.
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":"BTC",
"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/assets/transfer/cbc";
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' #
def do_sign(body):
timestamp = int(time.time()) * 1000
# to_sign = str(timestamp)+json.dumps(body,separators=(',',':'))
to_sign = str(timestamp) + json.dumps(body)
sign = hmac.new(SECRET_KEY.encode("utf-8"), to_sign.encode("utf-8"), hashlib.md5).hexdigest()
print(to_sign)
headers = {
'bibox-api-key': API_KEY,
'bibox-api-sign': sign,
'bibox-timestamp': str(timestamp)
}
return headers
def transfer(inout, amount):
path = '/v3/assets/transfer/cbc'
body = {
'symbol': 'BTC',
'type': inout,
'amount': amount,
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
transfer(0, 1) # transfer in contract
transfer(1, 1) # transfer out contract
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/assets/transfer/cbc";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
symbol = "BTC",
type = 0,
amount = "0.001",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/assets/transfer/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
amount | true | string | Number to string | ||
symbol | true | string | coin symbol | BTC,ETH, ... | |
type | true | integer | 0 transfer in, 1 transfer out | 0,1 |
Response
{
"state":0, // success
"result":"352559634189422592" // ignore
}
- 3.Response field description
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/cbc/order/open";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"pair":"5BTC_USD",
"order_side":1,
"order_type":2,
"price":"11500",
"amount":1,
"order_from":6,
"client_oid": "1234567890",
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/open'
body = {
"pair": "5BTC_USD",
"order_side": 1,
"order_type": 2,
"price": "11500",
"amount": 1,
"order_from": 6,
"client_oid": "1234567890",
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/open";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
order_side = 1,
order_type = 2,
price = "11500",
amount = 1,
order_from = 6,
client_oid = "1234567890",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/open
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
amount | true | string | Number to string | ||
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 |
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
}
- 3.Response field description
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/cbc/order/close";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"order_id":"425510999949316"
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/close'
body = {
"order_id": "425510999949316"
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/close";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
order_id = "425510999949316",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/close
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
order_id | true | string | order id |
Response
{
"state":0, // success
"result":"success",
"cmd":"close"
}
- 3.Response field description
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/cbc/order/closeBatch";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"order_ids":["2234567890","2234567891"]
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/closeBatch'
body = {
"order_ids": ["2234567890", "2234567891"]
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/closeBatch";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
order_ids = new [] {"2234567890", "2234567891"},
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/closeBatch
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
order_ids | true | Array | Order id array |
Response
{
"state":0,// success
"result":"success",
"cmd":"close"
}
- 3.Response field description
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/cbc/order/closeAll";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"pair":"5BTC_USD"
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/closeAll'
body = {
"pair": "5BTC_USD"
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/closeAll";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/closeAll
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | Contract symbol | 5BTC_USD,5ETH_USD, ... |
Response
{
"state":0,// success
"result":"success",
"cmd":"closeAll"
}
- 3.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
Other fields | ignore |
7.Adjust margin on a fixed position
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/changeMargin";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"pair":"5BTC_USD",
"margin":"0.01",
"side":1
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/changeMargin'
body = {
"pair": "5BTC_USD",
"margin": "0.01",
"side": 1
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/changeMargin";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
margin = "0.01",
side = 1
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/changeMargin
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
margin | true | string | margin | ||
side | true | integer | Position side, 1 long position, 2 short position | 1,2 |
Response
{
"state":3103, // failed
"msg":"没有持仓不支持该操作",
"cmd":"changeMargin"
}
- 3.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
Other fields | ignore |
8.Adjust position mode and leverage
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/changeMode";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"pair":"5BTC_USD",
"mode":2,
"leverage_long":10,
"leverage_short":20
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/changeMode'
body = {
"pair": "5BTC_USD",
"mode": 2,
"leverage_long": 10,
"leverage_short": 20
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/changeMode";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
mode = 2,
leverage_long = 10,
leverage_short = 20,
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/changeMode
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
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"
}
- 3.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
Other fields | ignore |
9.Query assets
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/assets";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
// "coin":"BTC",
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/assets'
body = {
"coin": "BTC",
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/assets";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
coin = "BTC",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/assets
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
coin | false | string | coin symbol | BTC,ETH,... |
Response
{
"state":0,
"result":[
{
"b":"1", // Available Balance
"c":"BTC", // coin symbol
"u":100006, // user id
"f":"0", // Frozen funds
"m":"0" // margin
},
{
"b":"1",
"c":"ETH",
"u":100006,
"f":"0",
"m":"0"
}
],
"cmd":"assets"
}
- 3.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
b | Available Balance |
c | coin symbol |
u | user id |
f | Frozen funds |
m | margin |
Other fields | ignore |
10.Query position
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/position";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
// "pair":"5BTC_USD",
// "side":1
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/position'
body = {
"pair": "5BTC_USD",
"side": 1
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/position";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
side = 1,
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/position
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | false | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
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":"5BTC_USD", // pair
"mg":"0", //margin
"hc":"0",// Position value = Contract number multiplied by contract value
"fb":"0",//ignore
"po":"0" //Open price
},
...
],
"cmd":"position"
}
- 3.Response field description
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 |
Other fields | ignore |
11.Query order list
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/order/list";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
// "pair":"5BTC_USD",
// "order_side":1
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/list'
body = {
"pair": "5BTC_USD",
"order_side": 1
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/list";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
order_side = 1,
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/list
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | false | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
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":"5BTC_USD", //pair
"oi":"426610511577093", // order id
"coi":"1602679943911", //clientoid
"fb":"0", //BIX deduction
"po":false //ignore
},
...
]
},
"cmd":"orderList"
}
- 3.Response field description
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 |
Other fields | ignore |
12.Query order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/order/detail";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"order_id":"426610511577093",
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/detail'
body = {
"order_id": "426610511577093",
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/detail";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
order_id = "426610511577093",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/detail
- 2.Request parameter
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":"5BTC_USD", //pair
"oi":"426610511577093", // order id
"coi":"1602679943911", //clientoid
"fb":"0", //BIX deduction
"po":false //ignore
},
"cmd":"orderDetail"
}
- 3.Response field description
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 |
Other fields | ignore |
13. Batch query order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/order/listBatch";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"order_ids":["426610511577093"],
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/listBatch'
body = {
"order_ids": ["426610511577093"],
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/listBatch";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
order_ids = new [] {"426610511577093"},
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/listBatch
- 2.Request parameter
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":"5BTC_USD", //pair
"oi":"426610511577093", // order id
"coi":"1602679943911", //clientoid
"fb":"0", //BIX deduction
"po":false //ignore
}
],
"cmd":"orderListBatch"
}
- 3.Response field description
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 |
Other fields | ignore |
14.Query order list based on clientoid
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3/cbc/order/listBatchByClientOid";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"order_ids":["1602679943911"],
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3/cbc/order/listBatchByClientOid'
body = {
"order_ids": ["1602679943911"],
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3/cbc/order/listBatchByClientOid";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
order_ids = new [] {"1602679943911"},
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3/cbc/order/listBatchByClientOid
- 2.Request parameter
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":"5BTC_USD", //pair
"oi":"426610511577093", // order id
"coi":"1602679943911", //clientoid
"fb":"0", //BIX deduction
"po":false //ignore
}
],
"cmd":"orderListBatchByCLientOid"
}
- 3.Response field description
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 |
Other fields | ignore |
15.Get server time
- 1.Request path
GET https://api.bibox.com/v3/cbc/timestamp
Response
{
"time":"1602680518605"
}
- 2.Response field description
Name | Description |
---|---|
time | server time |
16.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_coin/dealLog";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"pair": "5BTC_USD",
"page": 1,
"size": 10,
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3.1/cquery/base_coin/dealLog'
body = {
"pair": "5BTC_USD",
"page": 1,
"size": 10,
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3.1/cquery/base_coin/dealLog";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
pair = "5BTC_USD",
page = 1,
size = 10,
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3.1/cquery/base_coin/dealLog
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
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":"BTC",// coin symbol
"pair":"5BTC_USD",// 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
}
- 3.Response field description
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 |
17.Query order deals detail
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderDetail";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"orderId":"421112953438213",
"page":1,
"size":10
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3.1/cquery/base_coin/orderDetail'
body = {
"orderId": "421112953438213",
"page": 1,
"size": 10
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderDetail";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
orderId = "421112953438213",
page = 1,
size = 10,
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3.1/cquery/base_coin/orderDetail
- 2.Request parameter
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":"BTC",// coin symbol
"pair":"5BTC_USD",// 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
}
- 3.Response field description
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 |
18.Query historical orders
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderHistory";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"page": 1,
"size": 10,
"pair": "5BTC_USD",
"side": 1,
"status": [3, 4, 5, 100],
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3.1/cquery/base_coin/orderHistory'
body = {
"page": 1,
"size": 10,
"pair": "5BTC_USD",
"side": 1,
"status": [3, 4, 5, 100],
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderHistory";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
page = 1,
size = 10,
pair = "5BTC_USD",
side = 1,
status = new [] {3, 4, 5, 100},
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3.1/cquery/base_coin/orderHistory
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | false | string | Contract symbol | 5BTC_USD,5ETH_USD, ... | |
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":"BTC",// coin symbol
"pair":"5BTC_USD",// 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
}
- 3.Response field description
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 |
19.Query order
Request
let CryptoJS = require("crypto-js");
let request = require("request");
let url = "https://api.bibox.com/v3.1/cquery/base_coin/orderById";
let apikey = "900625568558820892a8c833c33ebc8fd2701efe"; //your apikey
let secret = "c708ac3e70d115ec29efbee197330627d7edf842"; //your apikey secret
let param = {
"orderIds": ["421112953438213", "421112953438214"],
"clientOids": ["1602644402806", "1602644402811"],
};
let cmd = JSON.stringify(param); //format param
let timestamp = '' + (Date.now());
let sign = CryptoJS.HmacMD5(timestamp + cmd, secret).toString();//sign cmds
request.post({
url: url,//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 do_request():
path = '/v3.1/cquery/base_coin/orderById'
body = {
"orderIds": ["421112953438213", "421112953438214"],
"clientOids": ["1602644402806", "1602644402811"],
}
headers = do_sign(body)
resp = requests.post(BASE_URL + path, json=body, headers=headers)
print(resp.text)
if __name__ == '__main__':
do_request()
using System;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleProgram
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Class1
{
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
string uri = "https://api.bibox.com/v3.1/cquery/base_coin/orderById";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
string timestamp = GetTimeStamp();
var myobj = new {
orderIds = new [] {"421112953438213", "421112953438214"},
clientOids = new [] {"1602644402806", "1602644402811"},
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string source = timestamp + payload;
string sign = HmacMD5(source, secret);
Console.WriteLine(source);
Console.WriteLine(sign);
client.DefaultRequestHeaders.Add("bibox-api-key", apikey);
client.DefaultRequestHeaders.Add("bibox-api-sign", sign);
client.DefaultRequestHeaders.Add("bibox-timestamp", timestamp);
HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
}
}
- 1.Request path
POST https://api.bibox.com/v3.1/cquery/base_coin/orderById
- 2.Request parameter
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":"BTC",// coin symbol
"pair":"5BTC_USD",// 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
}
- 3.Response field description
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 |
20.Qeury fund fee rate
- 1.Request path
GET https://api.bibox.com/v3.1/cquery/bcFundRate
Response
{
"result":{
"5BTC_USD":{
"pair":"5BTC_USD",
"close":"0.0000000000",
"fund_rate":"0.0001000000",
"createdAt":"2020-10-14T00:00:00.000Z"
},
"5ETH_USD":{
"pair":"5ETH_USD",
"close":"0.0000000000",
"fund_rate":"0.0001000000",
"createdAt":"2020-10-14T00:00:00.000Z"
}
},
"state":0
}
- 2.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
pair | pair |
fund_rate | fund fee rate |
Other fields | ignore |
21.Qeury tag price
- 1.Request path
GET https://api.bibox.com/v3.1/cquery/bcTagPrice
Response
{
"result":{
"5BTC_USD":{//pair
"close":"11453.7224909000",// Index price
"priceTag":"11454.2951770245",// Tag price
"createdAt":"2020-10-14T03:41:08.000Z" // time
},
"5ETH_USD":{
"close":"383.1999999600",
"priceTag":"383.2191599600",
"createdAt":"2020-10-14T03:41:08.000Z"
}
},
"state":0
}
- 2.Response field description
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 |
22.Query basic contract information
- 1.Request path
GET https://api.bibox.com/v3.1/cquery/bcValue
Response
{
"result":[
{
"id":465, // ignore
"pair":"5BTC_USD",//pair
"coin_symbol":"BTC", // ignore
"leverage_init":"10.0000000000", // ignore
"leverage_min":"0.0100000000",//Minimum leverage
"leverage_max":"100.0000000000",//Maximum leverage
"value":"1.0000000000",//contract value
"risk_level_base":"1000000.0000000000",//ignore
"risk_level_dx":"50000.0000000000",//ignore
"maker_fee":"0.0006000000",//default maker fee rate
"taker_fee":"0.0006000000",//default taker fee rate
"open_max_per":"10000000.0000000000",//Maximum number of single pending orders
"pending_max":100,//Maximum number of pending orders
"hold_max":"100000000.0000000000",//Maximum position value
"price_precision":1 // ignore
},
...
],
"state":0
}
- 2.Response field description
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 |
23.Query accuracy configuration
- 1.Request path
GET https://api.bibox.com/v3.1/cquery/bcUnit
Response
{
"result":[
{
"pair":"5BTC_USD",//pair
"price_unit":1,//Decimal points for order
"vol_unit":6, // ignore
"value_unit":0 // ignore
},
...
],
"state":0
}
- 2.Response field description
Name | Description |
---|---|
state | 0 means success, otherwise means failure |
pair | pair |
price_unit | Decimal points for order |
Other fields | ignore |
24.Query Kline
1.Request path
GET https://api.bibox.com/v2/mdata/kline?pair=5BTC_USD&period=1min&size=10
2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD, ... | |
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"
}
- 3.Response field description
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 |
25.Query market depth
- 1.Request path
GET https://api.bibox.com/v2/mdata/depth?pair=5BTC_USD&size=10
- 2.Request parameter
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":"5BTC_USD",
"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"
}
- 3.Response field description
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 |
26.Subscription to Kline
Example
'use strict'
const WebSocket = require('ws');
const zlib = require('zlib');
const biboxws = 'wss://npush.bibox360.com/cbc';
let wsClass = function () {
};
wsClass.prototype._decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log(err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log(new Date(), buffer.toString());
} catch (e) {
console.log(e);
}
}
});
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws)
let ws = new WebSocket(biboxws);
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open')
ws.send(JSON.stringify({
sub: '5BTC_USD_kline_1min',
// unsub: '5BTC_USD_kline_1min',
}));
});
ws.on('close', err => {
console.log('close, ', err);
});
ws.on('error', err => {
console.log('error', err);
});
ws.on('ping', err => {
console.log('ping ', err.toString('utf8'));
});
ws.on('pong', err => {
console.log('pong ', err.toString('utf8'));
});
ws.on('message', data => {
if (data[0] == '1') {
that._decodeMsg(data);
} else if (data[0] == '0') {
console.log(1, new Date(), JSON.parse(data.slice(1)));
} else {
console.log(2, new Date(), JSON.parse(data));
}
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
ws_url = 'wss://npush.bibox360.com/cbc'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
'sub': '5BTC_USD_kline_1min',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': '5BTC_USD_kline_1min',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
elif message[0] == '\x00' or message[0] == 0:
message = message[1:]
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myobj = new {
sub = "5BTC_USD_kline_1min",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Subscription path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD | |
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: '5BTC_USD_kline_1min',
t: 1,
d: [
[
'1646464740000',
'39113.6',
'39135.2',
'39111.8',
'39111.8',
'576699'
],
[
'1646464800000',
'39111.8',
'39129.6',
'39081.2',
'39129.6',
'1348253'
]
]
}
- 3.Response field description
[ k-line start time, Opening price, Highest price, Lowest price, Closing price, Volume(Contract value) ]
27.Subscription to Tag price
Example
'use strict'
const WebSocket = require('ws');
const zlib = require('zlib');
const biboxws = 'wss://npush.bibox360.com/cbc';
let wsClass = function () {
};
wsClass.prototype._decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log(err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log(new Date(), buffer.toString());
} catch (e) {
console.log(e);
}
}
});
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws)
let ws = new WebSocket(biboxws);
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open')
ws.send(JSON.stringify({
sub: '5BTC_USDTAGPRICE_kline_1min',
// unsub: '5BTC_USDTAGPRICE_kline_1min',
}));
});
ws.on('close', err => {
console.log('close, ', err);
});
ws.on('error', err => {
console.log('error', err);
});
ws.on('ping', err => {
console.log('ping ', err.toString('utf8'));
});
ws.on('pong', err => {
console.log('pong ', err.toString('utf8'));
});
ws.on('message', data => {
if (data[0] == '1') {
that._decodeMsg(data);
} else if (data[0] == '0') {
console.log(1, new Date(), JSON.parse(data.slice(1)));
} else {
console.log(2, new Date(), JSON.parse(data));
}
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
ws_url = 'wss://npush.bibox360.com/cbc'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
'sub': '5BTC_USDTAGPRICE_kline_1min',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': '5BTC_USDTAGPRICE_kline_1min',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
elif message[0] == '\x00' or message[0] == 0:
message = message[1:]
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myobj = new {
sub = "5BTC_USDTAGPRICE_kline_1min",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Subscription path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD | |
sub | true | string | ${pair} + 'TAGPRICE_kline_1min' |
Response
{
topic: '5BTC_USDTAGPRICE_kline_1min',
t: 1,
d: [
[
'1646464680000',
'39106.67632734',
'39143.47178728',
'39106.67632734',
'39133.04415693',
'30'
],
[
'1646464740000',
'39132.729153',
'39146.25432206',
'39132.57415106',
'39138.78672871',
'16'
]
]
}
- 3.Response field description
[ k-line start time, Opening price, Highest price, Lowest price, Latest price, Other fields (ignore) ]
28.Subscription to Market depth
Example
'use strict'
const WebSocket = require('ws');
const zlib = require('zlib');
const biboxws = 'wss://npush.bibox360.com/cbc';
let wsClass = function () {
};
wsClass.prototype._decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log(err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log(new Date(), buffer.toString());
} catch (e) {
console.log(e);
}
}
});
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws)
let ws = new WebSocket(biboxws);
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open')
ws.send(JSON.stringify({
sub: '5BTC_USD_depth',
// unsub: '5BTC_USD_depth',
}));
});
ws.on('close', err => {
console.log('close, ', err);
});
ws.on('error', err => {
console.log('error', err);
});
ws.on('ping', err => {
console.log('ping ', err.toString('utf8'));
});
ws.on('pong', err => {
console.log('pong ', err.toString('utf8'));
});
ws.on('message', data => {
if (data[0] == '1') {
that._decodeMsg(data);
} else if (data[0] == '0') {
console.log(1, new Date(), JSON.parse(data.slice(1)));
} else {
console.log(2, new Date(), JSON.parse(data));
}
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
ws_url = 'wss://npush.bibox360.com/cbc'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
'sub': '5BTC_USD_depth',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': '5BTC_USD_depth',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
elif message[0] == '\x00' or message[0] == 0:
message = message[1:]
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myobj = new {
sub = "5BTC_USD_depth",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Subscription path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD | |
sub | true | string | ${pair} + '_depth' |
Response
{
"topic":"5BTC_USD_depth",
"t":1,
"d":{
"pair":"5BTC_USD",
"ut":1646465078003,
"seq":2078286,
"add":{
"asks":[
[
"18438",
"39092.2"
]
],
"bids":[
[
"7314",
"39075.2"
]
]
},
"del":{
"asks":[
[
"25",
"44840"
]
],
"bids":[
[
"422685",
"39040.9"
]
]
}
}
}
- 3.Response field description
Name | Description |
---|---|
pair | pair |
ut | time |
seq | sequance id |
add | add data |
del | delete data |
mod | modify data |
asks | ask data [Order quantity, price] |
bids | bid data [Order quantity, price] |
Other fields | ignore |
29.Subscription to deals detail
Example
'use strict'
const WebSocket = require('ws');
const zlib = require('zlib');
const biboxws = 'wss://npush.bibox360.com/cbc';
let wsClass = function () {
};
wsClass.prototype._decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log(err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log(new Date(), buffer.toString());
} catch (e) {
console.log(e);
}
}
});
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws)
let ws = new WebSocket(biboxws);
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open')
ws.send(JSON.stringify({
sub: '5BTC_USD_deals',
// unsub: '5BTC_USD_deals',
}));
});
ws.on('close', err => {
console.log('close, ', err);
});
ws.on('error', err => {
console.log('error', err);
});
ws.on('ping', err => {
console.log('ping ', err.toString('utf8'));
});
ws.on('pong', err => {
console.log('pong ', err.toString('utf8'));
});
ws.on('message', data => {
if (data[0] == '1') {
that._decodeMsg(data);
} else if (data[0] == '0') {
console.log(1, new Date(), JSON.parse(data.slice(1)));
} else {
console.log(2, new Date(), JSON.parse(data));
}
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
ws_url = 'wss://npush.bibox360.com/cbc'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
'sub': '5BTC_USD_deals',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': '5BTC_USD_deals',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
elif message[0] == '\x00' or message[0] == 0:
message = message[1:]
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myobj = new {
sub = "5BTC_USD_deals",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Subscription path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD | |
sub | true | string | ${pair} + '_deals' |
Response
[{
"topic":"5BTC_USD_deals",
"t":0,
"d":{
"pair":"5BTC_USD",
"d":[
[
"39087.2",
"47001",
"2",
"1646465389633",
""
],
[
"39111.8",
"1281",
"2",
"1646464813823",
""
]
]
}
}
{
topic: '5BTC_USD_deals',
t: 1,
d: [ '5BTC_USD', '39086.6', '50', '1', '1646465418417', '' ]
}
- 3.Response field description
Name | Description |
---|---|
t | 0 represents full data,1 represents incremental data |
d | array definition:pair,Deal price,Deal amount,trade side(1-buy,2-sel),Timestamp |
30.Subscription to ticker
Example
'use strict'
const WebSocket = require('ws');
const zlib = require('zlib');
const biboxws = 'wss://npush.bibox360.com/cbc';
let wsClass = function () {
};
wsClass.prototype._decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log(err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log(new Date(), buffer.toString());
} catch (e) {
console.log(e);
}
}
});
};
wsClass.prototype._initWs = async function () {
let that = this;
console.log(biboxws)
let ws = new WebSocket(biboxws);
that.ws = ws;
ws.on('open', function open() {
console.log(new Date(), 'open')
ws.send(JSON.stringify({
sub: '5BTC_USD_ticker',
// unsub: '5BTC_USD_ticker',
}));
});
ws.on('close', err => {
console.log('close, ', err);
});
ws.on('error', err => {
console.log('error', err);
});
ws.on('ping', err => {
console.log('ping ', err.toString('utf8'));
});
ws.on('pong', err => {
console.log('pong ', err.toString('utf8'));
});
ws.on('message', data => {
if (data[0] == '1') {
that._decodeMsg(data);
} else if (data[0] == '0') {
console.log(1, new Date(), JSON.parse(data.slice(1)));
} else {
console.log(2, new Date(), JSON.parse(data));
}
});
};
let instance = new wsClass();
instance._initWs().catch(err => {
console.log(err);
});
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
ws_url = 'wss://npush.bibox360.com/cbc'
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sub_str():
subdata = {
'sub': '5BTC_USD_ticker',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': '5BTC_USD_ticker',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
elif message[0] == '\x00' or message[0] == 0:
message = message[1:]
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myobj = new {
sub = "5BTC_USD_ticker",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Subscription path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
pair | true | string | pair | 5BTC_USD, 5ETH_USD | |
sub | true | string | ${pair} + '_ticker' |
Response
{
"topic":"5BTC_USD_ticker",
"t":0,
"d":[
"5BTC_USD",
"39043.5",
"39043.50",
"248316.10",
"41890.7",
"38540",
"39043.4",
"7009",
"39043.5",
"1500",
"1750950839",
"-5.55%",
"1646465730385",
"248316.10000000"
]
}
- 3.Response field description
[ pair, last price, last usd price, last cny price, 24h Highest price, 24h Lowest price, Latest bid price, Latest bid amount, Latest ask price, Latest ask amount, 24h Deal amount, 24h Quote change, Timestamp, Latest cny price ]
31.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/cbc'; // 1.请求路径
let ws;
let apikey = '900625568558820892a8c833c33ebc8fd2701efe'; // 你的apikey
let secret = 'c708ac3e70d115ec29efbee197330627d7edf842'; // apikey的密码
let subparam = JSON.stringify({ // 格式化参数对象,得到subparam
apikey,
sub: 'ALL_ALL_login'
});
let sign = CryptoJS.HmacMD5(subparam, String(secret)).toString(); // 用apikey的密码secret对得到subparam进行HmacMD5签名,得到签名结果sign
let form = { // 得到最终的订阅参数
apikey,
sign,
sub: 'ALL_ALL_login',
};
console.log('form', form)
let reiniting = false;
let resend = function (user_id) {
if (ws.readyState != WebSocket.OPEN) {
return setTimeout(function () {
resend(user_id);
}, 1000 * 10);
}
ws.send(JSON.stringify(form));
};
setInterval(function () {
if (ws && ws.readyState == WebSocket.OPEN) {
ws.ping(new Date().getTime());
}
}, 1000 * 10);
let reinit = function () {
if (reiniting) {
return;
}
reiniting = true;
try {
if (ws && ws.readyState == WebSocket.OPEN) {
console.log('manu close ')
ws.close();
}
} catch (err) {
}
setTimeout(function () {
init();
}, 1000 * 30);
};
let init = function (user_id) {
console.log('init', user_id);
reiniting = false;
ws = new WebSocket(biboxws);
setTimeout(function () {
if (!ws || ws.readyState != WebSocket.OPEN) {
reinit(user_id);
}
}, 1000 * 60);
ws.on('open', function open() {
resend(user_id);
});
ws.on('close', err => {
console.log('close, ', err);
reinit(user_id);
});
ws.on('error', err => {
console.log('error', err);
reinit(user_id);
});
ws.on('ping', err => {
console.log('ping on', err.toString('utf8'));
});
ws.on('pong', err => {
// console.log('pong ', err.toString('utf8'));
});
ws.on('message', function incoming(data) {
if (data[0] == '1') {
decodeMsg(data);
} else {
console.log(1, JSON.parse(data));
}
});
};
let login = function () {
if (reiniting) {
return;
}
reiniting = false;
init();
};
let decodeMsg = function (data) {
let data1 = data.slice(1, data.length);
zlib.unzip(data1, (err, buffer) => {
if (err) {
console.log('2', err);
} else {
try {
let res = JSON.parse(buffer.toString());
console.log('3', buffer.toString());
} catch (e) {
console.log('4', e);
}
}
});
};
module.exports = {};
login();
# /usr/bin/env python
# -*- coding: UTF-8 -*-
import websocket # websocket-client
import json
import zlib
import hmac
import hashlib
ws_url = 'wss://npush.bibox360.com/cbc'
apikey = '900625568558820892a8c833c33ebc8fd2701efe' # your apikey
secret = 'c708ac3e70d115ec29efbee197330627d7edf842' # your apikey secret
def stringify(obj):
return json.dumps(obj, sort_keys=True).replace("\'", "\"").replace(" ", "")
def get_sign(data, secret):
return hmac.new(secret.encode("utf-8"), data.encode("utf-8"), hashlib.md5).hexdigest()
def get_sub_str():
subdata = {
'apikey': apikey,
'sub': 'ALL_ALL_login',
}
# print(stringify(subdata))
sign = get_sign(stringify(subdata), secret)
subdata = {
'apikey': apikey,
'sign': sign,
'sub': 'ALL_ALL_login',
}
# print(stringify(subdata))
return stringify(subdata)
def get_unsub_str():
subdata = {
'unsub': 'ALL_ALL_login',
}
return stringify(subdata)
def decode_data(message):
if message[0] == '\x01' or message[0] == 1:
message = message[1:]
data = zlib.decompress(message, zlib.MAX_WBITS | 32)
jmsgs = json.loads(data)
print(jmsgs)
print(type(jmsgs))
else:
jmsgs = json.loads(message)
print(jmsgs)
print(type(jmsgs))
def on_message(ws, message):
# print(message)
decode_data(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
ws.send(get_sub_str())
def connect():
websocket.enableTrace(True)
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=30, ping_timeout=5)
if __name__ == "__main__":
connect()
using System;
using WebSocketSharp;
using System.Net.Http;
using System.Text;
using System.IO.Compression;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Example
{
public class SortContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
return properties.OrderBy(x=>x.PropertyName).ToList();
}
}
public class Program
{
public static string Decompress(byte[] bytes)
{
MemoryStream msIn = new MemoryStream(bytes, 1, bytes.Length - 1);
MemoryStream msOut = new MemoryStream();
GZipStream cprs = new GZipStream(msIn, CompressionMode.Decompress);
cprs.CopyTo(msOut);
cprs.Close();
return Encoding.ASCII.GetString(msOut.ToArray());//转换为普通的字符串
}
static string HmacMD5(string source, string key)
{
HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));
byte[] inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inArray.Length; i++)
{
sb.Append(inArray[i].ToString("X2"));
}
hmacmd.Clear();
return sb.ToString().ToLower();
}
public static void Main (string[] args)
{
string wsuri = "wss://npush.bibox360.com/cbc";
string apikey = "900625568558820892a8c833c33ebc8fd2701efe";
string secret = "c708ac3e70d115ec29efbee197330627d7edf842";
using (var ws = new WebSocket (wsuri)) {
ws.OnMessage += (sender, e) => {
Console.WriteLine ("recv: " + e.Data);
if (e.IsText) {
Console.WriteLine ("data[0]: {");
} else if (e.IsBinary) {
if (e.RawData[0] == 1) {
Console.WriteLine ("RawData[0]: 1");
string strres = Decompress(e.RawData);
Console.WriteLine (strres);
} else if (e.RawData[0] == 0) {
Console.WriteLine ("RawData[0]: 0");
string strres = Encoding.ASCII.GetString(e.RawData);
Console.WriteLine (strres);
}
}
};
ws.Connect ();
var myparam = new {
apikey = apikey,
sub = "ALL_ALL_login",
};
string myparamstr = JsonConvert.SerializeObject(myparam, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
string sign = HmacMD5(myparamstr, secret);
var myobj = new {
apikey = apikey,
sign = sign,
sub = "ALL_ALL_login",
};
string payload = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings { ContractResolver = new SortContractResolver() });
ws.Send (payload);
ConsoleKey key;
do
{
key=Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
}
}
}
- 1.Request path
wss://push.bibox.com/cbc
- 2.Request parameter
Name | Necessary or not | Type | Description | Default | Value Range |
---|---|---|---|---|---|
apikey | true | string | your apikey | ||
sign | true | string | sign | ||
sub | true | string | 'ALL_ALL_login' |
- 3.Signature method
1.Define the parameter object param, need to use apikey
let apikey = 'thisisyourapikey';
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 = 'c708ac3e70d115ec29efbee197330627d7edf842';
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":"订阅成功"
}
}
- 4.Response field description
Name | Description |
---|---|
result | "订阅成功" means subscription success |
Other fields | ignore |
32.Get assets from subscribed user data
- 1.Key field
cbc_assets
Response
{
"topic":"ALL_ALL_login",
"uid":"100006",
"t":1,
"d":{
"cbc_assets":{
"b":"2.1020558887",
"c":"BTC",
"u":100006,
"f":"0",
"m":"0.0000141934"
}
}
}
- 2.Response field description
Name | Description |
---|---|
b | Available Balance |
c | coin symbol |
u | user id |
f | Frozen funds |
m | margin |
Other fields | ignore |
33.Get position from subscribed user data
- 1.Key field
cbc_order
Response
{
"topic":"ALL_ALL_login",
"uid":"100006",
"t":1,
"d":{
"cbc_order":{
"pt":"0.0020756655",
"f":"0.0000001168",
"l":"10",
"sd":2,
"pa":"47096342.2962158",
"ui":100006,
"fb0":"0",
"pf":"47096342.2962158",
"md":1,
"lc":"7",
"pi":"5BTC_USD",
"mg":"0.0000147457",
"hc":"7",
"fb":"0",
"po":"47096.3422962158"
}
}
}
- 2.Response field description
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 |
Other fields | ignore |
34.Get order from subscribed user data
- 1.Key field
cbc_pending
Response
{
"topic":"ALL_ALL_login",
"uid":"100006",
"t":1,
"d":{
"cbc_pending":{
"f":"0.0000000167",
"dp":"36017.9",
"eq":"1",
"p":"35660",
"tif":0,
"q":"1",
"sd":2,
"r":0,
"s":3,
"t":1646466808030,
"ui":100006,
"fz":"0",
"fb0":"0",
"of":6,
"pi":"5BTC_USD",
"oi":"15393162788872",
"coi":"0",
"fb":"0",
"po":false
}
}
}
- 2.Response field description
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 |
35.Get deals detail from subscribed user data
- 1.Key field
cbc_detail
Response
{
"topic":"ALL_ALL_login",
"uid":"100006",
"t":1,
"d":{
"cbc_detail":{
"oi":"15393162788872",
"ui":"100006",
"id":"1125899906851141149",
"coi":"0",
"pi":"5BTC_USD",
"sd":2,
"s":3,
"ot":1,
"of":6,
"q":"1",
"p":"35660",
"dp":"36017.9",
"ep":"1",
"f":"0.0000000167",
"fb":"0",
"fb0":"0",
"im":0,
"t":1646466808030
}
}
}
- 2.Response field description
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 |
36.Get passive changes in positions from subscribed user data
- 1.Key field
cbc_deal_log
Response
{
"topic":"ALL_ALL_login",
"uid":"100006",
"t":1,
"d":{
"cbc_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":"5BTC_USD",// pair
"price":"11247.6",// proposed price
"hold_dx":"1",// Change in position
"order_side":2,// Position side, 1 Long, 2 Short
"time":1602755131000, // time
}
}
}
- 2.Response field description
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 |
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 |